diff --git a/generated-src/classes.h b/generated-src/classes.h index e0ded33..6ba84a7 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -375,6 +375,8 @@ struct KAGE_ReferenceCount_ImageBase; struct KColor; struct KerningPair; struct KeyConfigs; +struct KnifeShot; +struct KnifeThrow; struct LRoomAreaDesc; struct LRoomTileDesc; struct LaserShot; @@ -523,6 +525,7 @@ struct QueueItemData; struct RNG; struct RadiusDamage; struct RailManager; +struct RailPoint; struct RainSpawner; struct RebirthSaveData; struct RedirectedPath; @@ -607,6 +610,7 @@ struct SubtitleCue; struct TargetSearch; struct TearParams; struct TechLaserShot; +struct TechXShot; struct TemporaryEffect; struct TemporaryEffects; struct TextMeasure; @@ -4109,30 +4113,6 @@ struct Weapon_Fetus { }; LAYOUT32(sizeof(Weapon_Fetus) == 0x44); -struct Weapon_Knife { - virtual ~Weapon_Knife(); // 009f99b0 slot 0 - virtual void Init(uint32_t param_2, uint32_t param_3); // 009f34d0 slot 1 Weapon::Init - virtual void Update(char param_2); // 009f34f0 slot 2 Weapon::Update - virtual void Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated); // 00a03f90 slot 3 - virtual void Reset(); // 009f3480 slot 4 Weapon::Reset - virtual void ClearReferences(); // 00a04f90 slot 5 - virtual float GetMaxCharge(); // 00a05010 slot 6 - virtual long double GetChargeBarAmount(); // 009f4150 slot 7 Weapon::GetChargeBarAmount - virtual void vfunc_8(); // 009f3130 slot 8 Weapon::GetMaxCharge - virtual Entity * GetFocusEntity(); // 009fa190 slot 9 Weapon_Bombs::GetFocusEntity - virtual Entity * GetMainEntity(); // 009f3150 slot 10 Weapon::GetMainEntity - virtual void TriggerNewRoom(); // 009fef20 slot 11 Weapon_Bone::TriggerNewRoom - virtual int GetMarkedTargetVariant(); // 009fa1b0 slot 12 Weapon_Bombs::GetMarkedTargetVariant - virtual uint8_t SupportsTractorBeam(); // 00a05060 slot 13 - virtual uint8_t CanShutDoors(); // 005ccc00 slot 14 Entity::CanShutDoors - virtual void vfunc_15(); // 005ccc00 slot 15 Entity::CanShutDoors - virtual void vfunc_16(); // 005ccc00 slot 16 Entity::CanShutDoors - void init_knife(Entity_Knife *knife); // 00a05070 - - uint8_t _pad_0x4[0x50]; -}; -LAYOUT32(sizeof(Weapon_Knife) == 0x54); - struct Weapon_Ludovico { virtual ~Weapon_Ludovico(); // 009f9880 slot 0 Weapon_Bombs::Free virtual void Init(uint32_t param_2, uint32_t param_3); // 009f34d0 slot 1 Weapon::Init @@ -6127,10 +6107,6 @@ void FUN_004cf0f0(uint8_t param_1); // 004cf0f0 void FUN_004cf380(int *param_1); // 004cf380 void FUN_004d3050(); // 004d3050 void FUN_004d3230(uint32_t *param_1); // 004d3230 -void FUN_004d4210(int param_1, char param_2); // 004d4210 -void FUN_004d42f0(int param_1, char param_2); // 004d42f0 -void FUN_004d43b0(int param_1, char param_2); // 004d43b0 -void FUN_004d4480(int param_1, char param_2); // 004d4480 void invoke_pending_callbacks(void *owner); // 004d6ee0 void FUN_004d7100(void *param_1); // 004d7100 void FUN_004d7130(); // 004d7130 @@ -6162,8 +6138,6 @@ void pow_wrapper(); // 00505b40 void set_byte_0x101(void *self, uint8_t value); // 00505b50 int FUN_00505ca0(); // 00505ca0 uint32_t * FUN_00505ce0(); // 00505ce0 -uint32_t FUN_00515010(); // 00515010 -Vector * room_grid_line_direction(Vector *outDirection, Vector *from, Vector *to); // 005150b0 long double FUN_00515290(Vector *param_1, uint32_t param_2, int param_3); // 00515290 void npc_distribute_orbit_angles(Entity_NPC *npc); // 00547040 int FUN_0054d1b0(int param_1); // 0054d1b0 @@ -6712,9 +6686,7 @@ void FUN_006f4170(); // 006f4170 void FUN_006f5850(int *param_1, int *param_2, int param_3, uint32_t param_4, int param_5); // 006f5850 void daily_challenge_params_assign(void *self, void *other); // 006f6260 uint8_t FUN_006f9730(); // 006f9730 -int get_stage_ending_id(uint8_t isIgnorePhotos); // 006f9d20 void FUN_006f9f20(int param_1); // 006f9f20 -void apply_tear_effects_in_rect(float *param_1, float *param_2, Entity *param_3); // 006fefd0 void FUN_007008b0(int *param_1); // 007008b0 void FUN_00703140(); // 00703140 void FUN_00704b50(); // 00704b50 @@ -9285,9 +9257,7 @@ uint8_t is_any_player_restart_held(); // 009563b0 uint32_t FUN_00956750(); // 00956750 uint8_t * FUN_009587e0(StringTable *param_1, uint8_t *param_2, uint8_t *param_3); // 009587e0 uint8_t * FUN_00958840(StringTable *param_1, uint8_t *param_2, int param_3, uint8_t *param_4); // 00958840 -void save_rerun_to_steam_cloud(); // 00959180 void FUN_00959500(); // 00959500 -void unlock_completion_mark_for_player_type(int markIndex, int playerType, int difficulty); // 0095aa30 void render_online_icon(int frame, Vector position, float scaleX, float scaleY); // 0095ae60 void FUN_0095be60(int param_1, int param_2); // 0095be60 void FUN_0095be90(void *param_1, int param_2); // 0095be90 @@ -9514,7 +9484,6 @@ uint32_t * FUN_009f92d0(); // 009f92d0 uint32_t * FUN_009f9350(); // 009f9350 uint32_t * FUN_009f93d0(); // 009f93d0 uint32_t * FUN_009f9440(); // 009f9440 -uint32_t * FUN_009f9540(); // 009f9540 uint32_t * FUN_009f95d0(); // 009f95d0 uint32_t * FUN_009f96c0(); // 009f96c0 uint32_t * FUN_009f9740(); // 009f9740 @@ -13249,7 +13218,6 @@ int FUN_00a695e0(char *param_1); // 00a695e0 uint32_t FUN_00a69620(); // 00a69620 void FUN_00a69640(); // 00a69640 uint32_t FUN_00a69650(uint32_t param_1, uint32_t param_2, uint8_t param_3); // 00a69650 -KColor * FUN_00a69700(KColor *param_1, uint32_t param_2, uint32_t param_3); // 00a69700 void FUN_00a69760(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4, uint32_t param_5); // 00a69760 void FUN_00a69950(); // 00a69950 int FUN_00a69b10(); // 00a69b10 @@ -21277,12 +21245,8 @@ void ENTITY_DEATH(Entity_NPC *npc); // 00459d20 void ENTITY_FALLEN(Entity_NPC *npc); // 0045b830 void ENTITY_HEADLESS_HORSEMAN(Entity_NPC *npc); // 0045cd60 void ENTITY_DARK_ONE(Entity_NPC *npc); // 0045d7d0 -void ENTITY_ADVERSARY(Entity_NPC *npc); // 0045e050 -void ENTITY_MEGA_FATTY(Entity_NPC *npc); // 00460780 -void ENTITY_MASK_OF_INFAMY(Entity_NPC *npc); // 00461fc0 float ENTITY_ISAAC(Entity_NPC *npc); // 00463100 void ENTITY_DADDYLONGLEGS(Entity_NPC *npc); // 00468180 -void ENTITY_BLASTOCYST_BIG(Entity_NPC *npc); // 00472c40 void ENTITY_SLOTH(Entity_NPC *npc); // 004741f0 void ENTITY_LUST(Entity_NPC *npc); // 00474e00 void ENTITY_WRATH(Entity_NPC *npc); // 00475110 @@ -21290,12 +21254,8 @@ void ENTITY_GREED(Entity_NPC *npc); // 00475a30 void ENTITY_ENVY(Entity_NPC *npc); // 004760a0 void ENTITY_PIN(Entity_NPC *npc); // 00476860 void ENTITY_PRIDE(Entity_NPC *npc); // 00479d80 -void ENTITY_CHUB(Entity_NPC *npc); // 0047a360 Entity_NPC * ENTITY_SATAN(Entity_NPC *npc); // 0047f640 void ENTITY_THE_LAMB(Entity_NPC *npc); // 00483710 -void ENTITY_MR_FRED(Entity_NPC *npc); // 00486db0 -void ENTITY_CAGE(Entity_NPC *npc); // 004878a0 -void ENTITY_MAMA_GURDY(Entity_NPC *npc); // 0048ae30 void ENTITY_BROWNIE(Entity_NPC *npc); // 0048c3b0 void ENTITY_CORN_MINE(Entity_NPC *npc); // 0048ee30 void ENTITY_FORSAKEN(Entity_NPC *npc); // 0048f110 @@ -21325,9 +21285,7 @@ void ENTITY_HUSH(Entity_NPC *npc); // 004bfd30 void ENTITY_MATRIARCH(Entity_NPC *npc); // 004c59d0 void ENTITY_MEGA_SATAN(Entity_NPC *npc); // 004c8090 void ENTITY_MEGA_SATAN_hand(Entity_NPC *npc); // 004cca10 -void ENTITY_MINECART(Entity_NPC *npc); // 004ce8a0 void ENTITY_MIN_MIN(Entity_NPC *npc); // 004cf690 -void ENTITY_MOMS_HEART(Entity_NPC *npc); // 004d48b0 void ENTITY_MOMS_HEART_mausoleum_death(Entity_NPC *npc); // 004d64f0 void ENTITY_SMALL_MAGGOT(Entity_NPC *npc); // 004d77b0 void ENTITY_ADULT_LEECH(Entity_NPC *npc); // 004d9000 @@ -21376,43 +21334,33 @@ void ENTITY_DUSTY_DEATHS_HEAD(Entity_NPC *npc); // 00504a40 void ENTITY_NECRO(Entity_NPC *npc); // 005052a0 void ENTITY_STONE_EYE(Entity_NPC *npc); // 00505d00 void ENTITY_KNIGHT(Entity_NPC *npc); // 005135d0 -uint32_t * ENTITY_GUTS(Entity_NPC *npc); // 005153b0 void ENTITY_MRMAW(Entity_NPC *npc); // 00517de0 void ENTITY_SWARMER(Entity_NPC *npc); // 00518e20 -void ENTITY_MEMBRAIN(Entity_NPC *npc); // 0051c040 void ENTITY_HANGER(Entity_NPC *npc); // 0051cb30 void ENTITY_URIEL(Entity_NPC *npc); // 0051e0f0 void ENTITY_HEART(Entity_NPC *npc); // 0051f2f0 void ENTITY_POKY(Entity_NPC *npc); // 00521ab0 -void ENTITY_LUMP(Entity_NPC *npc); // 00522430 void ENTITY_EYE(Entity_NPC *npc); // 00522ef0 -uint32_t ENTITY_PARA_BITE(Entity_NPC *npc); // 005240a0 void ENTITY_FRED(Entity_NPC *npc); // 00524a10 void ENTITY_DOPLE(Entity_NPC *npc); // 00525650 void ENTITY_BABY(Entity_NPC *npc); // 0052ae30 void ENTITY_VIS_chubber_projectile(Entity_NPC *npc); // 0052c2f0 void ENTITY_VIS(Entity_NPC *npc); // 0052c720 -void ENTITY_FAT_SACK(Entity_NPC *npc); // 00530a80 void ENTITY_COD_WORM(Entity_NPC *npc); // 00531350 void ENTITY_MOBILE_HOST(Entity_NPC *npc); // 005321d0 -void ENTITY_DEATHS_HEAD(Entity_NPC *npc); // 00532cf0 void ENTITY_MOMS_HAND(Entity_NPC *npc); // 00533b80 -void ENTITY_SWINGER(Entity_NPC *npc); // 00536d00 void ENTITY_WIZOOB(Entity_NPC *npc); // 005374a0 -void ENTITY_NERVE_ENDING(Entity_NPC *npc); // 00537e20 void ENTITY_HOMUNCULUS(Entity_NPC *npc); // 00539b90 void ENTITY_OOB(Entity_NPC *npc); // 0053ab40 void ENTITY_BLACK_MAW(Entity_NPC *npc); // 0053b2f0 void ENTITY_WALL_CREEP(Entity_NPC *npc); // 0053c0d0 Entity_Effect * ENTITY_MEATBALL(Entity_NPC *npc); // 00541ce0 -float ENTITY_BLISTER(Entity_NPC *npc); // 005430d0 float ENTITY_TARBOY(Entity_NPC *npc); // 005442a0 void ENTITY_FISTULOID(Entity_NPC *npc); // 00545f70 void ENTITY_GUSH(Entity_NPC *npc); // 00547330 void ENTITY_LEPER(Entity_NPC *npc); // 00547b60 void ENTITY_MR_MINE(Entity_NPC *npc); // 005492c0 void ENTITY_BUTT_SLICKER(Entity_NPC *npc); // 0054d250 -void ENTITY_NEEDLE(Entity_NPC *npc); // 0054eb80 ColorMod * ENTITY_WRINKLY_BABY(Entity_NPC *npc); // 0054fa80 void ENTITY_SWARM_SPIDER(Entity_NPC *npc); // 005505c0 void ENTITY_COHORT(Entity_NPC *npc); // 005513a0 @@ -21424,12 +21372,10 @@ void ENTITY_PEEPER_FATTY(Entity_NPC *npc); // 005562b0 void ENTITY_WILLO(Entity_NPC *npc); // 005586b0 int ENTITY_WILLO_L2_find_target(Entity_NPC *npc); // 005591c0 void ENTITY_WILLO_L2(Entity_NPC *npc); // 005593c0 -void ENTITY_BLURB(Entity_NPC *npc); // 0055a010 Entity_Projectile * ENTITY_BUBBLES(Entity_NPC *npc); // 0055ad20 void ENTITY_SMALL_LEECH(Entity_NPC *npc); // 0055b740 void ENTITY_STRIDER(Entity_NPC *npc); // 0055c810 uint32_t ENTITY_POLTY(Entity_NPC *npc); // 0055d230 -void ENTITY_DEEP_GAPER(Entity_NPC *npc); // 00560570 void ENTITY_FLY_TRAP(Entity_NPC *npc); // 00560ca0 void ENTITY_FLY_orbit_parent(Entity_NPC *npc); // 00561580 void ENTITY_FARTIGAN(Entity_NPC *npc); // 00561a20 diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index 54e3443..110c3a6 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -5459,57 +5459,6 @@ Entity * NpcHelper::query_nearest_other(void *queryList, Entity *exclude, Vector return pEVar1; } -// 004cee90 -void NpcHelper::minecart_break(Entity_NPC *minecart) -{ - uint32_t rngResult; - uint32_t *local_44; - ColorMod particleColor; - float local_14; - Manager *manager; - - local_14 = (float)(__security_cookie ^ GHIDRA_UINT(((&particleColor)[1]._tint + 1))); - (**(code **)(*GHIDRA_CAST(minecart) + 0x28))(); - manager = g_manager; - local_44 = GHIDRA_CAST(0x1e1); - seed_fart_sound_override(GHIDRA_CAST(&local_44)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_44),1.0,10,0,1.0,0.0); - particleColor._tint[0] = 1.0; - particleColor._tint[1] = 1.0; - particleColor._tint[2] = 1.0; - particleColor._tint[3] = 1.0; - particleColor._colorize[0] = 0.0; - particleColor._colorize[1] = 0.0; - particleColor._colorize[2] = 0.0; - particleColor._colorize[3] = 0.0; - if (*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x1d18)) == 0x2e) { - particleColor._tint[0] = 0.9; - particleColor._tint[1] = 0.9; - particleColor._tint[2] = 0.9; - particleColor._colorize[0] = 1.0; - particleColor._colorize[1] = 1.0; - particleColor._colorize[2] = 1.0; - particleColor._colorize[3] = 0.7; - } - particleColor._offset[0] = 0.0; - particleColor._offset[1] = 0.0; - particleColor._offset[2] = 0.0; - rngResult = Random(); - local_44 = (uint32_t *) - ((float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 4.0 + 3.0); - rngResult = Random(); - Game::SpawnParticles - (g_game,&minecart->_pos,0x1b,rngResult % 3 + 6,(float)local_44,&particleColor,100000.0,0 - ); - if (minecart->_child != 0) { - local_44 = &minecart->_child; - msvc::multiset::erase(&local_44); - } - minecart->_child = 0; - return; -} - // 004cf5b0 void NpcHelper::min_min_willo_count(Entity_NPC *minMin, int *outWilloCount, int *outOwnedCount) { @@ -5557,593 +5506,6 @@ void NpcHelper::min_min_willo_count(Entity_NPC *minMin, int *outWilloCount, int return; } -// 004d33d0 -void NpcHelper::moms_heart_attack_pattern(Entity_NPC *npc, int pattern, int stateFrame) -{ - uint8_t isHeartbeat; - Entity *target; - int iVar1; - uint32_t frameMod4; - int framesLeft; - uint32_t uVar2; - Entity_Laser *laser; - int updateTime; - uint32_t baseBulletFlags; - bool isOnBeat; - float fVar3; - double dVar4; - float fVar5; - uint8_t auStack_f8 [4]; - float local_f4; - float local_f0; - Vector local_ec; - float local_e4; - float local_e0; - Vector firePos; - float local_d4; - Vector local_d0; - float rotationSpeed; - Vector laserOffset; - uint32_t isPositiveRotation; - ProjectileParams projParams; - code *projectileCallback; - uint32_t stackCookie; - - stackCookie = __security_cookie ^ GHIDRA_UINT(auStack_f8); - ProjectileParams::ProjectileParams(&projParams); - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams)) + 0x4))) = 0x40a00000; - projParams.Scale = 1.5; - projParams.FallingAccelModifier = -0.06; - projParams.FallingSpeedModifier = -2.0; - target = Entity_NPC::GetPlayerTarget(npc); - local_f4 = (target->_pos).x - (npc->_pos).x; - local_e4 = (target->_pos).y - (npc->_pos).y; - fVar3 = sqrtf(local_e4 * local_e4 + local_f4 * local_f4); - if (fVar3 <= 0.0) { - fVar5 = local_e4; - fVar3 = local_f4; - } - else { - fVar5 = local_e4 * (1.0 / fVar3); - fVar3 = local_f4 * (1.0 / fVar3); - } - projParams.CircleAngle = atan2f(fVar5,fVar3); - uVar2 = GHIDRA_UINT(projParams.BulletFlags); - iVar1 = GHIDRA_INT(npc->_prevUpdateTime); - baseBulletFlags = GHIDRA_UINT(projParams.BulletFlags) | 0x80; - updateTime = GHIDRA_INT(npc->_updateTime); - firePos.x = (npc->_pos).x; - firePos.y = (npc->_pos).y; - switch(pattern) { - case 0: - fVar3 = (float)stateFrame; - local_f0 = (fVar3 * fVar3 - fVar3) * 0.01 + fVar3; - fVar3 = (fVar3 - 0.0) / 180.0; - if (fVar3 <= 0.0) { - fVar3 = 0.0; - } - if (1.0 <= fVar3) { - fVar3 = 1.0; - } - if (updateTime == iVar1) { - return; - } - local_f4 = 3.0; - fVar3 = (6.0 - fVar3 * 3.0) + 0.5; - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - FUN_008370b0(); - if (stateFrame % GHIDRA_INT(fVar3) != 0) { - return; - } - fVar5 = local_f0; - goto LAB_004d358e; - case 1: - if (updateTime == iVar1) { - return; - } - if (stateFrame != (stateFrame / 0x12) * 0x12) { - return; - } - dVar4 = (double)((((float)stateFrame / 30.0) / 6.0) * 6.2831855); - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - libm_sse2_cos_precise(); - fVar3 = 1.12104e-44; - local_ec.x = 3.0; - projParams.CircleAngle = ((((float)dVar4 * 10.0) / 6.0) / 30.0) * 6.2831855; - break; - case 2: - case 3: - if ((npc->_sprite)._animState._animData == (void *)0x0) { - return; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - isHeartbeat = AnimationState::IsEventTriggered(&(npc->_sprite)._animState,GHIDRA_CAST("Heartbeat")); - if (isHeartbeat == 0) { - return; - } - if (npc->_aiCounter == 3) { - fVar3 = 5.60519e-45; - } - else { - fVar3 = 1.4013e-44; - } - local_ec.x = 5.0; - projParams.CircleAngle = (((float)stateFrame / 6.0) / 30.0) * 6.2831855; - if (pattern == 3) { - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = GHIDRA_UINT(projParams.BulletFlags) | 0x200000; - } - break; - case 4: - if (updateTime == iVar1) { - return; - } - if (stateFrame % 6 != 0) { - return; - } - fVar3 = 4.2039e-45; - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = GHIDRA_UINT(projParams.BulletFlags) | 0x200080; - local_ec.x = 3.0; - projParams.CircleAngle = (((float)stateFrame / 6.0) / 30.0) * 6.2831855; - break; - case 5: - if (updateTime == iVar1) { - return; - } - frameMod4 = stateFrame & 0x80000003; - isOnBeat = frameMod4 == 0; - if (GHIDRA_INT(frameMod4) < 0) { - isOnBeat = (frameMod4 - 1 | 0xfffffffc) == 0xffffffff; - } - if (!isOnBeat) { - return; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - fVar5 = cos(((float)stateFrame * 0.9424779) / 30.0); - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = uVar2 | 0x200080; - fVar3 = 4.2039e-45; - local_ec.x = 3.5; - projParams.CircleAngle = (fVar5 * 6.2831855) / 3.0; - break; - case 6: - if (updateTime == iVar1) { - return; - } - uVar2 = stateFrame & 0x80000003; - isOnBeat = uVar2 == 0; - if (GHIDRA_INT(uVar2) < 0) { - isOnBeat = (uVar2 - 1 | 0xfffffffc) == 0xffffffff; - } - if (!isOnBeat) { - return; - } - fVar3 = 1.4013e-45; - fVar5 = ((float)npc->_stateFrame - 0.0) / 60.0; - if (fVar5 <= 0.0) { - fVar5 = 0.0; - } - if (1.0 <= fVar5) { - fVar5 = 1.0; - } - local_ec.x = fVar5 * 7.0 + 8.0; - goto LAB_004d417d; - case 7: - if (updateTime == iVar1) { - return; - } - uVar2 = stateFrame & 0x80000003; - isOnBeat = uVar2 == 0; - if (GHIDRA_INT(uVar2) < 0) { - isOnBeat = (uVar2 - 1 | 0xfffffffc) == 0xffffffff; - } - if (!isOnBeat) { - return; - } - local_ec.x = 6.0; - fVar3 = 7.00649e-45; - projParams.CircleAngle = projParams.CircleAngle * -1.0; - goto LAB_004d417d; - case 8: - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - isHeartbeat = (GHIDRA_CAST((GHIDRA_CAST(&npc->_sprite))))->Sprite::IsEventTriggered("Heartbeat"); - if (isHeartbeat == 0) { - return; - } - projParams.FireDirectionLimit.x = 0.0; - projParams.FireDirectionLimit.y = 1.0; - projParams.DotProductLimit = 0.0; - firePos.x = (npc->_pos).x; - fVar3 = (float)((npc->_aiCounter != 3) + 7); - if (npc->_aiCounter == 3) { - fVar3 = 5.60519e-45; - } - local_ec.x = 5.0; - projParams.CircleAngle = (((float)stateFrame / 6.0) / 30.0) * 6.2831855; - firePos.y = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x18)) + 20.0; - break; - case 9: - if (updateTime == iVar1) { - return; - } - if (stateFrame != 2) { - return; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - uVar2 = Random(); - local_f4 = (float)(uVar2 % 0x1e + 0xf); - isPositiveRotation = Random(); - isPositiveRotation = isPositiveRotation & 1; - uVar2 = Random(); - local_d4 = 30.0; - local_e0 = 90.0; - local_f0 = 0.0; - local_e4 = ((float)((uVar2 & 3) + 1) + 0.0) * 180.0; - do { - local_ec.x = (npc->_pos).x + 0.0; - local_ec.y = (npc->_pos).y - local_d4; - laserOffset.x = 0.0; - laserOffset.y = 0.0; - laser = Entity_Laser::ShootAngle - (1,&local_ec,(float)GHIDRA_INT(local_f0) * local_e0 - 135.0,0x5a,&laserOffset, - GHIDRA_CAST(npc),0); - laser->_isActiveRotating = 1; - laser->_rotationDelay = GHIDRA_INT(local_f4); - if (isPositiveRotation == 0) { - local_d0.x = -local_e4; - rotationSpeed = -2.0; - } - else { - rotationSpeed = 2.0; - local_d0.x = local_e4; - } - iVar1 = __ftoui3(); - laser->_rotationDegrees = local_d0.x; - laser->_rotationSpd = rotationSpeed; - laser->_timeout = iVar1 + GHIDRA_INT(local_f4) + 1; - (**(code **)(*GHIDRA_CAST(laser) + 0xc))(); - local_f0 = (float)(GHIDRA_INT(local_f0) + 1); - } while (GHIDRA_INT(local_f0) < 4); - return; - case 10: - framesLeft = 0xb4 - stateFrame; - local_e0 = ((float)(framesLeft * framesLeft) - (float)framesLeft) * 0.01 + (float)framesLeft; - fVar3 = ((float)stateFrame - 0.0) / 180.0; - if (fVar3 <= 0.0) { - fVar3 = 0.0; - } - if (1.0 <= fVar3) { - fVar3 = 1.0; - } - if (updateTime == iVar1) { - return; - } - local_f4 = 3.0; - fVar3 = fVar3 * 0.0 + 3.0 + 0.5; - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - FUN_008370b0(); - if (stateFrame % GHIDRA_INT(fVar3) != 0) { - return; - } - fVar5 = local_e0; -LAB_004d358e: - fVar3 = 2.8026e-45; - projParams.CircleAngle = ((fVar5 / 6.0) / 30.0) * 6.2831855; - local_ec.x = local_f4; - break; - case 0xb: - if (updateTime == iVar1) { - return; - } - uVar2 = stateFrame & 0x8000000f; - isOnBeat = uVar2 == 0; - if (GHIDRA_INT(uVar2) < 0) { - isOnBeat = (uVar2 - 1 | 0xfffffff0) == 0xffffffff; - } - if (!isOnBeat) { - return; - } - fVar3 = 1.12104e-44; - projParams.CircleAngle = (float)stateFrame * 0.62831855 * 0.0625; - uVar2 = stateFrame & 0x8000001f; - isOnBeat = uVar2 == 0; - if (GHIDRA_INT(uVar2) < 0) { - isOnBeat = (uVar2 - 1 | 0xffffffe0) == 0xffffffff; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = 0x40000; - if (!isOnBeat) { - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = 0x80000; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags | GHIDRA_UINT(projParams.BulletFlags); - local_ec.x = 5.0; - break; - case 0xc: - case 0xd: - if ((npc->_sprite)._animState._animData == (void *)0x0) { - return; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - isHeartbeat = AnimationState::IsEventTriggered(&(npc->_sprite)._animState,GHIDRA_CAST("Heartbeat")); - if (isHeartbeat == 0) { - return; - } - local_f4 = 6.0; - projParams.FallingAccelModifier = -0.08; - projParams.CircleAngle = (((float)stateFrame / 6.0) / 30.0) * 6.2831855; - if ((pattern == 0xd) && (npc->_aiCounter != 3)) { - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = GHIDRA_UINT(projParams.BulletFlags) | 0x200000; - } - local_f0 = 4.2039e-45; - if (npc->_aiCounter == 3) { - local_ec.x = 0.8; - } - else { - local_f0 = 1.12104e-44; - local_ec.x = 0.5; - } - local_ec.x = local_ec.x * 6.0; - local_ec.y = (float)GHIDRA_INT(local_f0); - Entity_NPC::FireProjectiles(npc,&firePos,&local_ec,9,&projParams); - projParams.Scale = 1.0; - fVar3 = local_f0; - local_ec.x = local_f4; - if (npc->_aiCounter == 3) { - projParams.CircleAngle = (((float)-stateFrame / local_f4) / 30.0) * 6.2831855; - } - else { - projParams.CircleAngle = 3.1415927 / (float)GHIDRA_INT(local_f0) + projParams.CircleAngle; - } - break; - case 0xe: - if (updateTime == iVar1) { - return; - } - uVar2 = stateFrame & 0x80000003; - isOnBeat = uVar2 == 0; - if (GHIDRA_INT(uVar2) < 0) { - isOnBeat = (uVar2 - 1 | 0xfffffffc) == 0xffffffff; - } - if (!isOnBeat) { - return; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = GHIDRA_UINT(projParams.BulletFlags) | 0x280080; - projectileCallback = FUN_004d4210; - fVar3 = (float)stateFrame / 180.0 + (float)stateFrame / 180.0; - projParams.CircleAngle = ((fVar3 + fVar3) * 3.1415927) / 3.0; - fVar3 = 7.00649e-45; - local_ec.x = 3.0; - break; - case 0xf: - if (updateTime == iVar1) { - return; - } - uVar2 = stateFrame & 0x80000007; - isOnBeat = uVar2 == 0; - if (GHIDRA_INT(uVar2) < 0) { - isOnBeat = (uVar2 - 1 | 0xfffffff8) == 0xffffffff; - } - if (!isOnBeat) { - return; - } - projParams.Scale = 1.0; - projParams.CircleAngle = 0.06981317; - projectileCallback = FUN_004d43b0; - local_ec.x = 6.0; - local_ec.y = 8.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - Entity_NPC::FireProjectiles(npc,&firePos,&local_ec,9,&projParams); - projParams.CircleAngle = projParams.CircleAngle - 0.13962634; - projParams.WiggleFrameOffset = 0x14; - fVar3 = 1.12104e-44; - local_ec.x = 6.0; - break; - case 0x10: - if (updateTime == iVar1) { - return; - } - if (stateFrame != (stateFrame / 0x1e) * 0x1e) { - return; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = GHIDRA_UINT(projParams.BulletFlags) | 0x2080; - projParams.Scale = 1.0; - projParams.FallingAccelModifier = -0.085; - projectileCallback = FUN_004d4480; - projParams.CurvingStrength = 2.0; - local_ec.x = 3.0; - local_ec.y = 4.0; - projParams.CircleAngle = (((float)stateFrame + (float)stateFrame) * 3.1415927) / 600.0; - projParams.TargetPosition.x = (npc->_pos).x; - projParams.TargetPosition.y = (npc->_pos).y; - Entity_NPC::FireProjectiles(npc,&firePos,&local_ec,9,&projParams); - projParams.CurvingStrength = -2.0; - local_ec.x = 3.0; - local_ec.y = 4.0; - Entity_NPC::FireProjectiles(npc,&firePos,&local_ec,9,&projParams); - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = GHIDRA_UINT(projParams.BulletFlags) & 0xffffdfff; - projParams.CircleAngle = 0.0; - projParams.Scale = 1.5; - projectileCallback = (code *)0x0; - fVar3 = 1.68156e-44; - local_ec.x = 3.0; - break; - case 0x11: - if (updateTime == iVar1) { - return; - } - uVar2 = stateFrame & 0x80000007; - isOnBeat = uVar2 == 0; - if (GHIDRA_INT(uVar2) < 0) { - isOnBeat = (uVar2 - 1 | 0xfffffff8) == 0xffffffff; - } - if (!isOnBeat) { - return; - } - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = GHIDRA_UINT(projParams.BulletFlags) | 0x2080; - projParams.CircleAngle = 0.0; - projectileCallback = FUN_004d42f0; - fVar3 = 1.12104e-44; - local_ec.x = 8.0; - break; - case 0x12: - if (updateTime == iVar1) { - return; - } - if (stateFrame == 2) { - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - uVar2 = Random(); - local_f0 = (float)(uVar2 % 0x1e + 0xf); - uVar2 = Random(); - local_e0 = (float)(uVar2 & 1); - iVar1 = 0; - local_d4 = (float)(GHIDRA_INT(local_f0) + -0x39515eff); - do { - local_d0.x = (npc->_pos).x + 0.0; - local_d0.y = (npc->_pos).y - 30.0; - laserOffset.x = 0.0; - laserOffset.y = 0.0; - laser = Entity_Laser::ShootAngle - (1,&local_d0,(float)iVar1 * 180.0 + 90.0,0x78,&laserOffset,GHIDRA_CAST(npc),0 - ); - laser->_isActiveRotating = 1; - laser->_rotationDelay = GHIDRA_INT(local_f0); - if (local_e0 == 0.0) { - fVar3 = -0.3; - fVar5 = -1e+09; - } - else { - fVar3 = 0.3; - fVar5 = 1e+09; - } - laser->_rotationDegrees = fVar5; - laser->_rotationSpd = fVar3; - laser->_timeout = GHIDRA_INT(local_d4); - (**(code **)(*GHIDRA_CAST(laser) + 0xc))(); - iVar1 = iVar1 + 1; - } while (iVar1 < 2); - return; - } - if (stateFrame != (stateFrame / 9) * 9) { - return; - } - local_ec.x = 8.0; - fVar3 = 2.8026e-45; -LAB_004d417d: - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = baseBulletFlags; - break; - default: - goto switchD_004d34fb_default; - } - local_ec.y = (float)GHIDRA_INT(fVar3); - Entity_NPC::FireProjectiles(npc,&firePos,&local_ec,9,&projParams); -switchD_004d34fb_default: - return; -} - -// 004d4610 -void NpcHelper::moms_heart_pick_attack(Entity_NPC *npc) -{ - uint32_t attackRoll; - int maxAttack; - uint32_t attackRange; - int iVar1; - float fVar2; - Vector local_48; - Vector local_40; - float local_38; - ColorMod splatColor; - float local_8; - - local_8 = (float)(__security_cookie ^ GHIDRA_UINT(((&splatColor)[1]._tint + 1))); - iVar1 = 0; - maxAttack = 7; - local_38 = (float)npc->_subtype; - if (local_38 == 1.4013e-45) { - iVar1 = 10; - maxAttack = 0x11; - } - if (npc->_i1 == 5) { - iVar1 = 8; - attackRange = 1; - } - else { - npc->_state = 8; - if (npc->_aiCounter == 1) { - maxAttack = 3; - if (local_38 == 1.4013e-45) { - maxAttack = 0xd; - } - } - else if ((npc->_aiCounter == 2) && (iVar1 = 2, local_38 == 1.4013e-45)) { - iVar1 = 0xe; - } - attackRange = (maxAttack - iVar1) + 1; - if (attackRange == 0) { - attackRoll = 0; - goto LAB_004d4664; - } - } - attackRoll = Random(); - attackRoll = attackRoll % attackRange; -LAB_004d4664: - (npc->_v1).y = (float)((double)GHIDRA_INT(attackRoll) + - __uint_to_double_fixup[-(GHIDRA_INT(attackRoll) >> 0x1f)]) + (float)iVar1; - npc->_stateFrame = 0; - if (npc->_health / npc->_maxHitPoints <= 0.2) { - iVar1 = 9; - if (local_38 == 1.4013e-45) { - iVar1 = 0x12; - } - fVar2 = (float)iVar1; - (npc->_v1).y = fVar2; - if (fVar2 == 9.0) { - iVar1 = 0; - local_48.y = -20.0; - local_48.x = 0.0; - do { - splatColor._offset[0] = 0.0; - splatColor._colorize[0] = 0.0; - splatColor._colorize[1] = 0.0; - splatColor._colorize[2] = 0.0; - splatColor._colorize[3] = 0.0; - splatColor._offset[1] = 0.0; - splatColor._tint[0] = 0.6; - splatColor._tint[1] = 0.05; - splatColor._tint[2] = 0.0; - splatColor._tint[3] = 0.8; - splatColor._offset[2] = 0.0; - local_38 = ((float)iVar1 * 90.0 - 135.0) * 0.017453292; - local_40.x = cos(local_38); - local_40.y = sin(local_38); - Entity::SpawnFollowingEffect198(GHIDRA_CAST(npc),&local_48,&local_40,0xc,&splatColor,4.0); - iVar1 = iVar1 + 1; - } while (iVar1 < 4); - return; - } - if (fVar2 == 18.0) { - iVar1 = 0; - local_40.y = -20.0; - local_40.x = 0.0; - do { - splatColor._offset[0] = 0.0; - splatColor._colorize[0] = 0.0; - splatColor._colorize[1] = 0.0; - splatColor._colorize[2] = 0.0; - splatColor._colorize[3] = 0.0; - splatColor._offset[1] = 0.0; - splatColor._tint[0] = 0.6; - splatColor._tint[1] = 0.05; - splatColor._tint[2] = 0.0; - splatColor._tint[3] = 0.8; - splatColor._offset[2] = 0.0; - local_38 = ((float)iVar1 * 180.0 + 90.0) * 0.017453292; - local_48.x = cos(local_38); - local_48.y = sin(local_38); - Entity::SpawnFollowingEffect198(GHIDRA_CAST(npc),&local_40,&local_48,0xc,&splatColor,4.0); - iVar1 = iVar1 + 1; - } while (iVar1 < 2); - } - } - return; -} - // 004d8d10 Entity_NPC * NpcHelper::gaper_l2_spawn_maggot(Vector *origin, float yOffset, Vector *velocity, float fallingSpeed) { @@ -12068,644 +11430,6 @@ uint8_t NpcHelper::is_target_valid(Entity *target) return 0; } -// 006bf120 -void NpcHelper::ChampionDrop(Entity_NPC *npc) -{ - code *pcVar1; - uint8_t bVar2; - float fVar3; - int iVar4; - uint32_t uVar5; - uint32_t uVar6; - Vector *dropDir; - Entity_Pickup *pickup; - Entity *spawned; - Entity_Player *nearestPlayer; - ProjectileParams *params; - uint8_t isDropAllowed; - float fVar7; - int gridY; - char isDropping; - uint32_t extraout_EDX; - RNG *dropRng; - bool isIceFrozen; - float local_138; - uint32_t dropVariant; - Vector *local_130; - PlayerManager *local_12c; - char local_125; - int dropCount; - Entity_NPC *local_120; - Vector local_11c; - Vector local_114; - Entity_Player *glyphOwner; - Vector randomDir; - Vector zeroDir; - Vector dropVelocity; - EntityRef sourceRef; - RNG local_c8; - ProjectileParams projParams; - uint32_t stackCookie; - uint32_t flagsHigh; - Game *game; - Room *room; - - stackCookie = __security_cookie ^ GHIDRA_UINT(&local_138); - dropVariant = 0; - local_130 = GHIDRA_CAST(0x0); - dropCount = 1; - local_125 = (npc->_killDamageFlags & 0x200000000) != 0; - fVar3 = 1.4013e-43; - local_138 = 1.4013e-43; - if (g_game->_difficulty == 1) { - if (!(bool)local_125) { - fVar3 = 4.62428e-44; - } - local_138 = fVar3; - } - fVar3 = local_138; - local_120 = npc; - bVar2 = PlayerManager::AnyoneHasTrinket(&g_game->_playerManager,5); - if (bVar2 != 0) { - iVar4 = PlayerManager::GetTrinketMultiplier(&g_game->_playerManager,5); - if (iVar4 < 3) { - fVar7 = 9.24857e-44; - if (iVar4 != 2) { - fVar7 = 7.00649e-44; - } - } - else { - fVar7 = 1.05097e-43; - } - local_138 = fVar3; - if (GHIDRA_UINT(fVar3) < GHIDRA_UINT(fVar7)) { - local_138 = fVar7; - } - } - uVar5 = (npc->_dropRNG)._seed; - dropRng = &npc->_dropRNG; - local_11c.x = (float)dropRng; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = dropRng->_seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift3 & 0x1f) ^ uVar5; - (npc->_dropRNG)._seed = uVar5; - if ((g_game->_difficulty == 2) || (g_game->_difficulty == 3)) { - bVar2 = 0; - } - else { - bVar2 = 1; - } - isDropAllowed = 0; - if (npc->_spawnerType != 0x132) { - isDropAllowed = bVar2; - } - local_138 = (float)GHIDRA_UINT((isDropAllowed & - (g_game->_challenge != 0x22 && - (uVar5 % 100 < GHIDRA_UINT(local_138) && g_game->_victoryLap < 1)) & - *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 1)))); - bVar2 = PlayerManager::AnyoneHasTrinket(&g_game->_playerManager,5); - if ((bVar2 == 0) && (g_game->_stage == 0xc)) { - uVar5 = 0x14; - if (local_125 != '\0') { - uVar5 = 7; - } - uVar5 = (GHIDRA_CAST((&npc->_dropRNG)))->RNG::RandomInt(uVar5); - if (uVar5 != 0) { - local_138 = (float)(extraout_EDX & 0xffffff00); - } - } - isIceFrozen = (npc->_flags & 0x2000000000000) != 0; - local_12c = GHIDRA_CAST(CONCAT31((*GHIDRA_CAST((GHIDRA_CAST(&(local_12c)) + 0x1))),isIceFrozen)); - isDropping = SUB41(local_138,0); - switch(npc->_championColorIdx) { - case 0: - case 0x14: - dropVariant = 10; - case 0x10: - local_130 = GHIDRA_CAST(0x1); - break; - case 1: - dropVariant = 0x5a; - break; - case 2: - dropVariant = 0x46; - break; - case 3: - uVar5 = Random(); - dropVariant = 0x14; - dropCount = uVar5 % 3 + 1; - break; - case 4: - if (isDropping == '\0') { - return; - } - nearestPlayer = Game::GetNearestPlayer(g_game,&npc->_pos); - Entity_Player::AddBlueFlies(nearestPlayer,3,&npc->_pos,GHIDRA_CAST(0x0)); - return; - case 5: - dropVariant = 0x28; - if (((!isIceFrozen) && (bVar2 = Entity::HasEntityFlags(GHIDRA_CAST(npc),0x1000000), bVar2 == 0)) && - ((dropDir = &npc->_pos, 0x1e < g_game->_frameCount - npc->_spawnFrame || - (nearestPlayer = Game::GetNearestPlayer(g_game,dropDir), - fVar3 = (npc->_pos).y - (nearestPlayer->_pos).y, - fVar7 = dropDir->x - (nearestPlayer->_pos).x, 6400.0 < fVar3 * fVar3 + fVar7 * fVar7)))) { - Game::BombDamage(g_game,dropDir,40.0,60.0,1,GHIDRA_CAST(npc),g_tearFlagsNone,4,0); - Game::spawn_bomb_crater(g_game,dropDir,GHIDRA_CAST(0x0),1.0); - uVar5 = Random(); - Game::SpawnEx(g_game,1000,1,dropDir,&g_vectorZero,GHIDRA_CAST(0x0),0,uVar5,0); - } - break; - case 6: - dropVariant = 10; - local_130 = GHIDRA_CAST(0x4); - break; - case 7: - dropVariant = 0x1e; - break; - case 8: - dropVariant = 0x3c; - break; - case 9: - dropVariant = 0x168; - break; - default: - goto switchD_006bf331_caseD_a; - case 0xb: - dropVariant = 0x15e; - break; - case 0xc: - dropVariant = 10; - local_130 = GHIDRA_CAST(0x5); - break; - case 0xd: - dropVariant = 10; - local_130 = GHIDRA_CAST(0x2); - if (((!isIceFrozen) && (bVar2 = Entity::HasEntityFlags(GHIDRA_CAST(npc),0x1000000), bVar2 == 0)) && - ((dropDir = &npc->_pos, 0x1e < g_game->_frameCount - npc->_spawnFrame || - (nearestPlayer = Game::GetNearestPlayer(g_game,dropDir), - fVar3 = (npc->_pos).y - (nearestPlayer->_pos).y, - fVar7 = dropDir->x - (nearestPlayer->_pos).x, 6400.0 < fVar3 * fVar3 + fVar7 * fVar7)))) { - params = ProjectileParams::ProjectileParams(&projParams); - local_11c.x = 7.0; - local_11c.y = 0.0; - Entity_NPC::FireProjectiles(npc,dropDir,&local_11c,8,params); - } - break; - case 0xe: - dropVariant = 300; - fVar3 = (float)(GHIDRA_CAST((&npc->_dropRNG)))->RNG::Next(); - iVar4 = ItemPool::GetCardEx(GHIDRA_INT(fVar3),0,1,0,1); - local_c8._shift3 = 7; - local_c8._shift1 = 5; - local_c8._shift2 = 9; - local_c8._seed = GHIDRA_INT(fVar3); - local_130 = GHIDRA_CAST(lua_callback_run_get_card(&local_c8,iVar4,0,1,1)); - break; - case 0xf: - if (!isIceFrozen) { - local_120 = GHIDRA_CAST(0x2); - do { - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift3 & 0x1f) ^ uVar5; - (npc->_dropRNG)._seed = uVar5; - uVar6 = Random(); - fVar3 = (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_12c = GHIDRA_CAST((fVar3 + fVar3)); - fVar3 = cos((float)local_12c); - local_11c.x = fVar3 * 14.0 + (npc->_pos).x; - fVar3 = sin((float)local_12c); - local_11c.y = fVar3 * 14.0 + (npc->_pos).y; - Game::SpawnEx(g_game,npc->_type,npc->_variant,&local_11c,&g_vectorZero,GHIDRA_CAST(npc),0,uVar5 - ,0); - local_120 = GHIDRA_CAST((GHIDRA_INT(local_120) + -1)); - } while (local_120 != GHIDRA_CAST(0x0)); - } - break; - case 0x11: - if (!isIceFrozen) { - uVar5 = Random(); - spawned = Game::SpawnEx(g_game,0x12,0,&npc->_pos,&g_vectorZero,GHIDRA_CAST(npc),0,uVar5,0); - bVar2 = Entity::HasEntityFlags(GHIDRA_CAST(npc),0x1000000); - if (bVar2 != 0) { - *GHIDRA_CAST(&spawned->_flags) = GHIDRA_UINT(spawned->_flags) & 0xfeffffff; - *GHIDRA_CAST((GHIDRA_INT(&spawned->_flags) + 4)) = *GHIDRA_CAST((GHIDRA_INT(&spawned->_flags) + 4)); - sourceRef._type = npc->_type; - sourceRef._position.x = (npc->_pos).x; - sourceRef._position.y = (npc->_pos).y; - sourceRef._variant = npc->_variant; - sourceRef._spawnerType = npc->_spawnerType; - sourceRef._spawnerVariant = npc->_spawnerVariant; - sourceRef._velocity.x = (npc->_velocity).x; - sourceRef._velocity.y = (npc->_velocity).y; - local_120 = GHIDRA_CAST(GHIDRA_UINT(((npc->_flags & 0x100) != 0))); - if ((npc->_flags & 0x20000000) == 0) { - uVar5 = 0; - } - else { - uVar5 = 2; - } - if ((npc->_flags & 0x40000000000000) == 0) { - uVar6 = 0; - } - else { - uVar6 = 4; - } - sourceRef._flags = uVar6 | uVar5 | GHIDRA_UINT(local_120); - sourceRef._entity = npc; - Entity::AddShrink(spawned,&sourceRef,0x96,0,0); - if (0 < spawned->_shrinkCountdown) { - flagsHigh = *GHIDRA_CAST((GHIDRA_INT(&spawned->_flags) + 4)); - *GHIDRA_CAST(&spawned->_flags) = GHIDRA_UINT(spawned->_flags) | 0x1000000; - *GHIDRA_CAST((GHIDRA_INT(&spawned->_flags) + 4)) = flagsHigh; - spawned->_shrinkStatus1 = spawned->_shrinkStatus2; - } - } - } - break; - case 0x12: - dropRng = &npc->_dropRNG; - uVar5 = (GHIDRA_CAST((dropRng)))->RNG::RandomInt(5); - if (uVar5 != 0) { - return; - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(local_138)) + 0x0))) == '\0') { - return; - } - bVar2 = PlayerManager::AnyoneHasTrinket(&g_game->_playerManager,5); - local_138 = 0.0; - dropCount = 1; - if (bVar2 != 0) { - dropCount = 2; - } - local_130 = &npc->_pos; - do { - uVar5 = dropRng->_seed; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - game = g_game; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(local_120->_dropRNG)._shift3 & 0x1f) ^ uVar5; - dropRng->_seed = uVar5; - uVar6 = ItemPool::ForceAddPillEffect(&game->_itemPool,0x21); - dropDir = Room::FindFreePickupSpawnPosition - (g_game->_room,GHIDRA_CAST(&local_c8),local_130,0.0,0,0,0); - npc = local_120; - local_11c.y = (float)((double)GHIDRA_INT(local_138) + - __uint_to_double_fixup[-(GHIDRA_INT(local_138) >> 0x1f)]) + dropDir->y; - local_11c.x = (float)((double)GHIDRA_INT(local_138) + - __uint_to_double_fixup[-(GHIDRA_INT(local_138) >> 0x1f)]) + dropDir->x; - Game::SpawnEx(g_game,5,0x46,&local_11c,&g_vectorZero,GHIDRA_CAST(local_120),uVar6,uVar5,0); - dropRng = &npc->_dropRNG; - local_138 = (float)(GHIDRA_INT(local_138) + 1); - } while (GHIDRA_UINT(local_138) < GHIDRA_UINT(dropCount)); - return; - case 0x13: - dropRng = &npc->_dropRNG; - uVar5 = (GHIDRA_CAST((dropRng)))->RNG::RandomInt(5); - if (uVar5 != 0) { - return; - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(local_138)) + 0x0))) == '\0') { - return; - } - bVar2 = PlayerManager::AnyoneHasTrinket(&g_game->_playerManager,5); - local_138 = 0.0; - dropCount = 1; - if (bVar2 != 0) { - dropCount = 2; - } - local_130 = &npc->_pos; - do { - uVar5 = dropRng->_seed; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - game = g_game; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(local_120->_dropRNG)._shift3 & 0x1f) ^ uVar5; - dropRng->_seed = uVar5; - uVar6 = ItemPool::ForceAddPillEffect(&game->_itemPool,0x20); - dropDir = Room::FindFreePickupSpawnPosition - (g_game->_room,GHIDRA_CAST(&local_c8),local_130,0.0,0,0,0); - npc = local_120; - local_11c.y = (float)((double)GHIDRA_INT(local_138) + - __uint_to_double_fixup[-(GHIDRA_INT(local_138) >> 0x1f)]) + dropDir->y; - local_11c.x = (float)((double)GHIDRA_INT(local_138) + - __uint_to_double_fixup[-(GHIDRA_INT(local_138) >> 0x1f)]) + dropDir->x; - Game::SpawnEx(g_game,5,0x46,&local_11c,&g_vectorZero,GHIDRA_CAST(local_120),uVar6,uVar5,0); - dropRng = &npc->_dropRNG; - local_138 = (float)(GHIDRA_INT(local_138) + 1); - } while (GHIDRA_UINT(local_138) < GHIDRA_UINT(dropCount)); - return; - case 0x15: - if (isDropping == '\0') { - return; - } - nearestPlayer = Game::GetNearestPlayer(g_game,&npc->_pos); - uVar5 = (GHIDRA_CAST((GHIDRA_CAST(local_11c.x))))->RNG::RandomInt(3); - Entity_Player::AddBlueFlies(nearestPlayer,uVar5 + 4,&npc->_pos,GHIDRA_CAST(0x0)); - return; - case 0x16: - if (isDropping == '\0') { - return; - } - uVar5 = (GHIDRA_CAST((&npc->_dropRNG)))->RNG::RandomInt(2); - local_138 = (float)(uVar5 + 2); - bVar2 = PlayerManager::AnyoneHasTrinket(&g_game->_playerManager,5); - if (bVar2 != 0) { - local_138 = (float)(GHIDRA_INT(local_138) * 2); - } - if (GHIDRA_INT(local_138) < 1) { - return; - } - do { - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - game = g_game; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift3 & 0x1f) ^ uVar5; - (npc->_dropRNG)._seed = uVar5; - dropDir = Room::FindFreePickupSpawnPosition - (game->_room,GHIDRA_CAST(&local_c8),&npc->_pos,0.0,0,0,0); - Game::SpawnEx(g_game,5,0,dropDir,&g_vectorZero,GHIDRA_CAST(npc),4,uVar5,0); - local_138 = (float)(GHIDRA_INT(local_138) + -1); - } while (local_138 != 0.0); - return; - case 0x17: - nearestPlayer = Game::GetNearestPlayerEx(&npc->_pos,1,0,1); - if (nearestPlayer == GHIDRA_CAST(0x0)) { - nearestPlayer = Game::GetPlayer(g_game,0); - } - Entity_Player::UseActiveItem(nearestPlayer,GHIDRA_CAST(&local_12c),0x23,1,-1,0); - ItemOverlay::Show(&g_game->_itemOverlay,0xc,3,GHIDRA_CAST(0x0)); - return; - case 0x19: - local_130 = GHIDRA_CAST(0x0); - dropRng = &npc->_dropRNG; - do { - if (SUB41(local_138,0) == '\0') { - uVar5 = dropRng->_seed; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift3 & 0x1f) ^ uVar5; - dropRng->_seed = uVar5; - if ((uVar5 & 1) == 0) goto LAB_006c0128; - } - else { -LAB_006c0128: - Room::FindFreePickupSpawnPosition(g_game->_room,&local_11c,&npc->_pos,40.0,0,0,0); - uVar5 = dropRng->_seed; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - game = g_game; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift3 & 0x1f) ^ uVar5; - dropRng->_seed = uVar5; - spawned = Game::SpawnEx(game,5,*GHIDRA_CAST((&DAT_00b67400 + GHIDRA_INT(local_130) * 4)),&local_11c, - &g_vectorZero,GHIDRA_CAST(npc),0,uVar5,0); - spawned[1]._sprite._championColor._offset[2] = (float)local_130; - bVar2 = PlayerManager::AnyoneHasTrinket(&g_game->_playerManager,5); - if (bVar2 != 0) { - dropDir = Room::FindFreePickupSpawnPosition - (g_game->_room,GHIDRA_CAST(&local_c8),&npc->_pos,40.0,0,0,0); - uVar5 = dropRng->_seed; - local_11c.x = dropDir->x; - local_11c.y = dropDir->y; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - game = g_game; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift3 & 0x1f) ^ uVar5; - dropRng->_seed = uVar5; - spawned = Game::SpawnEx(game,5,*GHIDRA_CAST((&DAT_00b67400 + GHIDRA_INT(local_130) * 4)),&local_11c, - &g_vectorZero,GHIDRA_CAST(npc),0,uVar5,0); - spawned[1]._sprite._championColor._offset[2] = (float)local_130; - } - } - local_130 = GHIDRA_CAST((GHIDRA_INT(&local_130->x) + 1)); - } while (local_130 < GHIDRA_CAST(0x7)); - if ((char)local_12c == '\0') { - bVar2 = Entity::HasEntityFlags(GHIDRA_CAST(npc),0x1000000); - if ((bVar2 == 0) && - ((dropDir = &npc->_pos, 0x1e < g_game->_frameCount - npc->_spawnFrame || - (nearestPlayer = Game::GetNearestPlayer(g_game,dropDir), - fVar3 = (npc->_pos).y - (nearestPlayer->_pos).y, - fVar7 = dropDir->x - (nearestPlayer->_pos).x, 6400.0 < fVar3 * fVar3 + fVar7 * fVar7)))) { - Game::BombDamage(g_game,dropDir,40.0,60.0,1,GHIDRA_CAST(npc),g_tearFlagsNone,4,0); - Game::spawn_bomb_crater(g_game,dropDir,GHIDRA_CAST(0x0),1.0); - uVar5 = Random(); - Game::SpawnEx(g_game,1000,1,dropDir,&g_vectorZero,GHIDRA_CAST(0x0),0,uVar5,0); - } - bVar2 = Entity::HasEntityFlags(GHIDRA_CAST(npc),0x1000000); - if ((bVar2 == 0) && - ((dropDir = &npc->_pos, 0x1e < g_game->_frameCount - npc->_spawnFrame || - (nearestPlayer = Game::GetNearestPlayer(g_game,dropDir), - fVar3 = (npc->_pos).y - (nearestPlayer->_pos).y, - fVar7 = dropDir->x - (nearestPlayer->_pos).x, 6400.0 < fVar3 * fVar3 + fVar7 * fVar7)))) { - params = ProjectileParams::ProjectileParams(&projParams); - local_c8._seed = 0x40e00000; - (*GHIDRA_CAST((GHIDRA_CAST(&(local_c8)) + 0x4))) = (uint64_t)GHIDRA_UINT(local_c8._shift2) << 0x20; - Entity_NPC::FireProjectiles(npc,dropDir,GHIDRA_CAST(&local_c8),8,params); - } - } - goto switchD_006bf331_caseD_a; - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(local_138)) + 0x0))) != '\0') { - local_120 = GHIDRA_CAST((npc->_pos).x); - local_138 = (npc->_pos).y; - room = g_game->_room; - iVar4 = GHIDRA_INT((((npc->_pos).x - 40.0) / 40.0 + 0.5)); - gridY = GHIDRA_INT(((local_138 - 120.0) / 40.0 + 0.5)); - if ((((iVar4 < 0) || (room->_gridWidth <= iVar4)) || (gridY < 0)) || - (room->_gridHeight <= gridY)) { - iVar4 = -1; - } - else { - iVar4 = room->_gridWidth * gridY + iVar4; - } - local_114.x = (float)local_120; - local_114.y = local_138; - uVar5 = Room::GetGridCollision(room,iVar4); - if (0 < GHIDRA_INT(uVar5)) { - dropDir = Room::FindFreeTilePosition(room,GHIDRA_CAST(&local_c8),&local_114,40.0); - local_120 = GHIDRA_CAST(dropDir->x); - local_138 = dropDir->y; - } - dropRng = &npc->_dropRNG; - uVar5 = dropRng->_seed; - local_12c = &g_game->_playerManager; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = dropRng->_seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift3 & 0x1f) ^ uVar5; - dropRng->_seed = uVar5; - glyphOwner = PlayerManager::RandomCollectibleOwner(local_12c,0x1d0,uVar5,GHIDRA_CAST(0x0)); - if ((dropCount != 0) && (local_125 != '\0')) { - uVar5 = dropRng->_seed; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = dropRng->_seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift3 & 0x1f) ^ uVar5; - dropRng->_seed = uVar5; - if ((uVar5 & 1) == 0) { - dropCount = dropCount + 1; - } - } - bVar2 = PlayerManager::AnyoneHasTrinket(&g_game->_playerManager,5); - if ((bVar2 != 0) && (npc->_isChampion != 0)) { - dropCount = dropCount * 2; - } - if (dropCount != 0) { - uVar5 = dropVariant; - local_12c = GHIDRA_CAST(dropCount); - do { - if (glyphOwner != GHIDRA_CAST(0x0)) { - Entity_Player::GetGlyphOfBalanceDrop(glyphOwner,GHIDRA_CAST(&dropVariant),GHIDRA_CAST(&local_130)); - uVar5 = dropVariant; - } - if (uVar5 != 0) { - if (GHIDRA_UINT(dropCount) < 2) { - zeroDir.x = g_vectorZero.x; - dropDir = &zeroDir; - zeroDir.y = g_vectorZero.y; - } - else { - uVar5 = Random(); - local_114.x = (float)((double)GHIDRA_INT(uVar5) + __uint_to_double_fixup[-(GHIDRA_INT(uVar5) >> 0x1f)] - ) * 2.3283064e-10 * 3.14; - local_114.x = local_114.x + local_114.x; - randomDir.x = cos(local_114.x); - randomDir.y = sin(local_114.x); - dropDir = &randomDir; - } - local_114.x = dropDir->x; - local_11c.x = dropDir->y; - uVar5 = dropRng->_seed; - dropVelocity.x = local_114.x; - dropVelocity.y = local_11c.x; - if (uVar5 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - uVar5 = (npc->_dropRNG)._seed; - if (uVar5 == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - game = g_game; - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift1 & 0x1f) ^ uVar5; - uVar5 = uVar5 << ((uint8_t)(npc->_dropRNG)._shift2 & 0x1f) ^ uVar5; - local_c8._seed = GHIDRA_INT((local_114.x * 3.0 + (float)local_120)); - uVar5 = uVar5 >> ((uint8_t)(npc->_dropRNG)._shift3 & 0x1f) ^ uVar5; - dropRng->_seed = uVar5; - local_c8._shift1 = GHIDRA_INT((local_11c.x * 3.0 + local_138)); - pickup = (Entity_Pickup *) - Game::SpawnEx(game,5,dropVariant,GHIDRA_CAST(&local_c8),&dropVelocity,GHIDRA_CAST(npc), - GHIDRA_UINT(local_130),uVar5,0); - if ((pickup->_variant == 0x15e) && - ((((g_manager->_persistentGameData)._achievements[0x269] != 0 || - (((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((g_manager)) + 0x8)))) == 2 && (g_game != GHIDRA_CAST(0x0))) && - (((g_game->_dailyChallenge)._id != 0 || (g_game->_isDebug != 0)))))) && - (((npc->_flags & 0x400) != 0 && ((pickup->_subtype & 0x8000U) == 0)))))) { - Entity_Pickup::Morph(pickup,pickup->_type,0x15e,pickup->_subtype | 0x8000,1,1,1); - } - uVar5 = dropVariant; - } - local_12c = GHIDRA_CAST((GHIDRA_INT(&local_12c[-1]._extraPlayers._capacity) + 3)); - } while (local_12c != GHIDRA_CAST(0x0)); - return; - } - } -switchD_006bf331_caseD_a: - return; -} - // 006d0ec0 void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) { diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index 739c795..26df7d0 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -9261,10 +9261,7 @@ Entity * NpcHelper::horny_boys_pull_entity(Entity_NPC *npc, int slot, Vector *ta Entity * NpcHelper::horny_boys_spawn_bomb(Entity_NPC *npc, int slot) { generated_stub("NpcHelper::horny_boys_spawn_bomb 004bcc70"); } void NpcHelper::horny_boys_render(Entity_NPC *npc, Vector *offset) { generated_stub("NpcHelper::horny_boys_render 004bcfd0"); } Entity * NpcHelper::query_nearest_other(void *queryList, Entity *exclude, Vector position) { generated_stub("NpcHelper::query_nearest_other 004be670"); } -void NpcHelper::minecart_break(Entity_NPC *minecart) { generated_stub("NpcHelper::minecart_break 004cee90"); } void NpcHelper::min_min_willo_count(Entity_NPC *minMin, int *outWilloCount, int *outOwnedCount) { generated_stub("NpcHelper::min_min_willo_count 004cf5b0"); } -void NpcHelper::moms_heart_attack_pattern(Entity_NPC *npc, int pattern, int stateFrame) { generated_stub("NpcHelper::moms_heart_attack_pattern 004d33d0"); } -void NpcHelper::moms_heart_pick_attack(Entity_NPC *npc) { generated_stub("NpcHelper::moms_heart_pick_attack 004d4610"); } Entity_NPC * NpcHelper::gaper_l2_spawn_maggot(Vector *origin, float yOffset, Vector *velocity, float fallingSpeed) { generated_stub("NpcHelper::gaper_l2_spawn_maggot 004d8d10"); } Vector * NpcHelper::adult_leech_heading(Vector *outHeading, Entity *target, Vector npcPos) { generated_stub("NpcHelper::adult_leech_heading 004d8f20"); } void NpcHelper::twitchy_jump_target(Vector *outTarget, Entity_NPC *npc) { generated_stub("NpcHelper::twitchy_jump_target 004db3c0"); } @@ -9322,7 +9319,6 @@ void NpcHelper::visage_chain_solve(Entity_NPC *npc, uint8_t isInterpolate) { gen 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::ChampionDrop(Entity_NPC *npc) { generated_stub("NpcHelper::ChampionDrop 006bf120"); } void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) { generated_stub("NpcHelper::fireplace_moveable_update 006d0ec0"); } float * NpcHelper::hush_fly_shape_build(float *outPath, int shape, float radius) { generated_stub("NpcHelper::hush_fly_shape_build 009bfd40"); } void NpcHelper::path_point_at(void *path, Vector *outPoint, float share) { generated_stub("NpcHelper::path_point_at 009bffb0"); } @@ -9488,24 +9484,6 @@ uint8_t Weapon_Fetus::CanShutDoors() { generated_stub("Weapon_Fetus::CanShutDoor void Weapon_Fetus::vfunc_14() { generated_stub("Weapon_Fetus::vfunc_14 005ccc00"); } uint8_t Weapon_Fetus::CanTakeDamageFromTearEffects() { generated_stub("Weapon_Fetus::CanTakeDamageFromTearEffects 00709c30"); } void Weapon_Fetus::vfunc_16() { generated_stub("Weapon_Fetus::vfunc_16 005ccc00"); } -Weapon_Knife::~Weapon_Knife() { generated_stub("Weapon_Knife::~Weapon_Knife 009f99b0"); } -void Weapon_Knife::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_Knife::Init 009f34d0"); } -void Weapon_Knife::Update(char param_2) { generated_stub("Weapon_Knife::Update 009f34f0"); } -void Weapon_Knife::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) { generated_stub("Weapon_Knife::Fire 00a03f90"); } -void Weapon_Knife::Reset() { generated_stub("Weapon_Knife::Reset 009f3480"); } -void Weapon_Knife::ClearReferences() { generated_stub("Weapon_Knife::ClearReferences 00a04f90"); } -float Weapon_Knife::GetMaxCharge() { generated_stub("Weapon_Knife::GetMaxCharge 00a05010"); } -long double Weapon_Knife::GetChargeBarAmount() { generated_stub("Weapon_Knife::GetChargeBarAmount 009f4150"); } -void Weapon_Knife::vfunc_8() { generated_stub("Weapon_Knife::vfunc_8 009f3130"); } -Entity * Weapon_Knife::GetFocusEntity() { generated_stub("Weapon_Knife::GetFocusEntity 009fa190"); } -Entity * Weapon_Knife::GetMainEntity() { generated_stub("Weapon_Knife::GetMainEntity 009f3150"); } -void Weapon_Knife::TriggerNewRoom() { generated_stub("Weapon_Knife::TriggerNewRoom 009fef20"); } -int Weapon_Knife::GetMarkedTargetVariant() { generated_stub("Weapon_Knife::GetMarkedTargetVariant 009fa1b0"); } -uint8_t Weapon_Knife::SupportsTractorBeam() { generated_stub("Weapon_Knife::SupportsTractorBeam 00a05060"); } -uint8_t Weapon_Knife::CanShutDoors() { generated_stub("Weapon_Knife::CanShutDoors 005ccc00"); } -void Weapon_Knife::vfunc_15() { generated_stub("Weapon_Knife::vfunc_15 005ccc00"); } -void Weapon_Knife::vfunc_16() { generated_stub("Weapon_Knife::vfunc_16 005ccc00"); } -void Weapon_Knife::init_knife(Entity_Knife *knife) { generated_stub("Weapon_Knife::init_knife 00a05070"); } Weapon_Ludovico::~Weapon_Ludovico() { generated_stub("Weapon_Ludovico::~Weapon_Ludovico 009f9880"); } void Weapon_Ludovico::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_Ludovico::Init 009f34d0"); } void Weapon_Ludovico::Update(char param_2) { generated_stub("Weapon_Ludovico::Update 009f34f0"); } @@ -10136,12 +10114,8 @@ void NpcAI::ENTITY_DEATH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DEATH void NpcAI::ENTITY_FALLEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FALLEN 0045b830"); } void NpcAI::ENTITY_HEADLESS_HORSEMAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HEADLESS_HORSEMAN 0045cd60"); } void NpcAI::ENTITY_DARK_ONE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DARK_ONE 0045d7d0"); } -void NpcAI::ENTITY_ADVERSARY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ADVERSARY 0045e050"); } -void NpcAI::ENTITY_MEGA_FATTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEGA_FATTY 00460780"); } -void NpcAI::ENTITY_MASK_OF_INFAMY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MASK_OF_INFAMY 00461fc0"); } float NpcAI::ENTITY_ISAAC(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ISAAC 00463100"); } void NpcAI::ENTITY_DADDYLONGLEGS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DADDYLONGLEGS 00468180"); } -void NpcAI::ENTITY_BLASTOCYST_BIG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLASTOCYST_BIG 00472c40"); } void NpcAI::ENTITY_SLOTH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SLOTH 004741f0"); } void NpcAI::ENTITY_LUST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LUST 00474e00"); } void NpcAI::ENTITY_WRATH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WRATH 00475110"); } @@ -10150,12 +10124,8 @@ void NpcAI::ENTITY_ENVY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ENVY 00 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 NpcAI::ENTITY_PRIDE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PRIDE 00479d80"); } -void NpcAI::ENTITY_CHUB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CHUB 0047a360"); } Entity_NPC * NpcAI::ENTITY_SATAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SATAN 0047f640"); } void NpcAI::ENTITY_THE_LAMB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_THE_LAMB 00483710"); } -void NpcAI::ENTITY_MR_FRED(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MR_FRED 00486db0"); } -void NpcAI::ENTITY_CAGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CAGE 004878a0"); } -void NpcAI::ENTITY_MAMA_GURDY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MAMA_GURDY 0048ae30"); } void NpcAI::ENTITY_BROWNIE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BROWNIE 0048c3b0"); } void NpcAI::ENTITY_CORN_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CORN_MINE 0048ee30"); } void NpcAI::ENTITY_FORSAKEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FORSAKEN 0048f110"); } @@ -10236,18 +10206,12 @@ void NpcAI::ENTITY_MEGA_SATAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_M void NpcAI::ENTITY_MEGA_SATAN_hand(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEGA_SATAN_hand 004cca10"); } void FUN_004cdce0() { generated_stub("FUN_004cdce0 004cdce0"); } uint32_t FUN_004ce0f0() { generated_stub("FUN_004ce0f0 004ce0f0"); } -void NpcAI::ENTITY_MINECART(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MINECART 004ce8a0"); } void FUN_004cf0f0(uint8_t param_1) { generated_stub("FUN_004cf0f0 004cf0f0"); } void msvc::set::clear() { generated_stub("msvc::set::clear 004cf350"); } void FUN_004cf380(int *param_1) { generated_stub("FUN_004cf380 004cf380"); } void NpcAI::ENTITY_MIN_MIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MIN_MIN 004cf690"); } void FUN_004d3050() { generated_stub("FUN_004d3050 004d3050"); } void FUN_004d3230(uint32_t *param_1) { generated_stub("FUN_004d3230 004d3230"); } -void FUN_004d4210(int param_1, char param_2) { generated_stub("FUN_004d4210 004d4210"); } -void FUN_004d42f0(int param_1, char param_2) { generated_stub("FUN_004d42f0 004d42f0"); } -void FUN_004d43b0(int param_1, char param_2) { generated_stub("FUN_004d43b0 004d43b0"); } -void FUN_004d4480(int param_1, char param_2) { generated_stub("FUN_004d4480 004d4480"); } -void NpcAI::ENTITY_MOMS_HEART(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOMS_HEART 004d48b0"); } void NpcAI::ENTITY_MOMS_HEART_mausoleum_death(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOMS_HEART_mausoleum_death 004d64f0"); } void invoke_pending_callbacks(void *owner) { generated_stub("invoke_pending_callbacks 004d6ee0"); } void FUN_004d7100(void *param_1) { generated_stub("FUN_004d7100 004d7100"); } @@ -10327,39 +10291,28 @@ int FUN_00505ca0() { generated_stub("FUN_00505ca0 00505ca0"); } uint32_t * FUN_00505ce0() { generated_stub("FUN_00505ce0 00505ce0"); } void NpcAI::ENTITY_STONE_EYE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_STONE_EYE 00505d00"); } void NpcAI::ENTITY_KNIGHT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_KNIGHT 005135d0"); } -uint32_t FUN_00515010() { generated_stub("FUN_00515010 00515010"); } -Vector * room_grid_line_direction(Vector *outDirection, Vector *from, Vector *to) { generated_stub("room_grid_line_direction 005150b0"); } long double FUN_00515290(Vector *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00515290 00515290"); } -uint32_t * NpcAI::ENTITY_GUTS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GUTS 005153b0"); } void NpcAI::ENTITY_MRMAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MRMAW 00517de0"); } void NpcAI::ENTITY_SWARMER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SWARMER 00518e20"); } -void NpcAI::ENTITY_MEMBRAIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEMBRAIN 0051c040"); } void NpcAI::ENTITY_HANGER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HANGER 0051cb30"); } void NpcAI::ENTITY_URIEL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_URIEL 0051e0f0"); } void NpcAI::ENTITY_HEART(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HEART 0051f2f0"); } void NpcAI::ENTITY_POKY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POKY 00521ab0"); } -void NpcAI::ENTITY_LUMP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LUMP 00522430"); } void NpcAI::ENTITY_EYE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EYE 00522ef0"); } -uint32_t NpcAI::ENTITY_PARA_BITE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PARA_BITE 005240a0"); } void NpcAI::ENTITY_FRED(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FRED 00524a10"); } void NpcAI::ENTITY_DOPLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOPLE 00525650"); } void NpcAI::ENTITY_BABY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BABY 0052ae30"); } void NpcAI::ENTITY_VIS_chubber_projectile(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VIS_chubber_projectile 0052c2f0"); } void NpcAI::ENTITY_VIS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VIS 0052c720"); } -void NpcAI::ENTITY_FAT_SACK(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FAT_SACK 00530a80"); } void NpcAI::ENTITY_COD_WORM(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_COD_WORM 00531350"); } void NpcAI::ENTITY_MOBILE_HOST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOBILE_HOST 005321d0"); } -void NpcAI::ENTITY_DEATHS_HEAD(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DEATHS_HEAD 00532cf0"); } void NpcAI::ENTITY_MOMS_HAND(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOMS_HAND 00533b80"); } -void NpcAI::ENTITY_SWINGER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SWINGER 00536d00"); } void NpcAI::ENTITY_WIZOOB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WIZOOB 005374a0"); } -void NpcAI::ENTITY_NERVE_ENDING(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_NERVE_ENDING 00537e20"); } void NpcAI::ENTITY_HOMUNCULUS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HOMUNCULUS 00539b90"); } void NpcAI::ENTITY_OOB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_OOB 0053ab40"); } void NpcAI::ENTITY_BLACK_MAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLACK_MAW 0053b2f0"); } void NpcAI::ENTITY_WALL_CREEP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WALL_CREEP 0053c0d0"); } Entity_Effect * NpcAI::ENTITY_MEATBALL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEATBALL 00541ce0"); } -float NpcAI::ENTITY_BLISTER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLISTER 005430d0"); } float NpcAI::ENTITY_TARBOY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TARBOY 005442a0"); } void NpcAI::ENTITY_FISTULOID(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FISTULOID 00545f70"); } void npc_distribute_orbit_angles(Entity_NPC *npc) { generated_stub("npc_distribute_orbit_angles 00547040"); } @@ -10368,7 +10321,6 @@ void NpcAI::ENTITY_LEPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LEPER void NpcAI::ENTITY_MR_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MR_MINE 005492c0"); } int FUN_0054d1b0(int param_1) { generated_stub("FUN_0054d1b0 0054d1b0"); } void NpcAI::ENTITY_BUTT_SLICKER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BUTT_SLICKER 0054d250"); } -void NpcAI::ENTITY_NEEDLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_NEEDLE 0054eb80"); } ColorMod * NpcAI::ENTITY_WRINKLY_BABY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WRINKLY_BABY 0054fa80"); } void NpcAI::ENTITY_SWARM_SPIDER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SWARM_SPIDER 005505c0"); } void NpcAI::ENTITY_COHORT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_COHORT 005513a0"); } @@ -10385,13 +10337,11 @@ void collect_npcs_with_same_parent(Entity_NPC *npc) { generated_stub("collect_np void NpcAI::ENTITY_WILLO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WILLO 005586b0"); } int NpcAI::ENTITY_WILLO_L2_find_target(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WILLO_L2_find_target 005591c0"); } void NpcAI::ENTITY_WILLO_L2(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WILLO_L2 005593c0"); } -void NpcAI::ENTITY_BLURB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLURB 0055a010"); } Entity_Projectile * NpcAI::ENTITY_BUBBLES(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BUBBLES 0055ad20"); } void NpcAI::ENTITY_SMALL_LEECH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SMALL_LEECH 0055b740"); } uint32_t FUN_0055c6a0(float *param_1) { generated_stub("FUN_0055c6a0 0055c6a0"); } void NpcAI::ENTITY_STRIDER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_STRIDER 0055c810"); } uint32_t NpcAI::ENTITY_POLTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POLTY 0055d230"); } -void NpcAI::ENTITY_DEEP_GAPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DEEP_GAPER 00560570"); } void NpcAI::ENTITY_FLY_TRAP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLY_TRAP 00560ca0"); } void NpcAI::ENTITY_FLY_orbit_parent(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLY_orbit_parent 00561580"); } void NpcAI::ENTITY_FARTIGAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FARTIGAN 00561a20"); } @@ -11021,9 +10971,7 @@ void FUN_006f4170() { generated_stub("FUN_006f4170 006f4170"); } void FUN_006f5850(int *param_1, int *param_2, int param_3, uint32_t param_4, int param_5) { generated_stub("FUN_006f5850 006f5850"); } void daily_challenge_params_assign(void *self, void *other) { generated_stub("daily_challenge_params_assign 006f6260"); } uint8_t FUN_006f9730() { generated_stub("FUN_006f9730 006f9730"); } -int get_stage_ending_id(uint8_t isIgnorePhotos) { generated_stub("get_stage_ending_id 006f9d20"); } void FUN_006f9f20(int param_1) { generated_stub("FUN_006f9f20 006f9f20"); } -void apply_tear_effects_in_rect(float *param_1, float *param_2, Entity *param_3) { generated_stub("apply_tear_effects_in_rect 006fefd0"); } 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"); } @@ -13608,9 +13556,7 @@ uint8_t is_any_player_restart_held() { generated_stub("is_any_player_restart_hel uint32_t FUN_00956750() { generated_stub("FUN_00956750 00956750"); } uint8_t * FUN_009587e0(StringTable *param_1, uint8_t *param_2, uint8_t *param_3) { generated_stub("FUN_009587e0 009587e0"); } uint8_t * FUN_00958840(StringTable *param_1, uint8_t *param_2, int param_3, uint8_t *param_4) { generated_stub("FUN_00958840 00958840"); } -void save_rerun_to_steam_cloud() { generated_stub("save_rerun_to_steam_cloud 00959180"); } void FUN_00959500() { generated_stub("FUN_00959500 00959500"); } -void unlock_completion_mark_for_player_type(int markIndex, int playerType, int difficulty) { generated_stub("unlock_completion_mark_for_player_type 0095aa30"); } void render_online_icon(int frame, Vector position, float scaleX, float scaleY) { generated_stub("render_online_icon 0095ae60"); } void FUN_0095be60(int param_1, int param_2) { generated_stub("FUN_0095be60 0095be60"); } void FUN_0095be90(void *param_1, int param_2) { generated_stub("FUN_0095be90 0095be90"); } @@ -13838,7 +13784,6 @@ uint32_t * FUN_009f92d0() { generated_stub("FUN_009f92d0 009f92d0"); } uint32_t * FUN_009f9350() { generated_stub("FUN_009f9350 009f9350"); } uint32_t * FUN_009f93d0() { generated_stub("FUN_009f93d0 009f93d0"); } uint32_t * FUN_009f9440() { generated_stub("FUN_009f9440 009f9440"); } -uint32_t * FUN_009f9540() { generated_stub("FUN_009f9540 009f9540"); } uint32_t * FUN_009f95d0() { generated_stub("FUN_009f95d0 009f95d0"); } uint32_t * FUN_009f96c0() { generated_stub("FUN_009f96c0 009f96c0"); } uint32_t * FUN_009f9740() { generated_stub("FUN_009f9740 009f9740"); } @@ -17578,7 +17523,6 @@ int FUN_00a695e0(char *param_1) { generated_stub("FUN_00a695e0 00a695e0"); } uint32_t FUN_00a69620() { generated_stub("FUN_00a69620 00a69620"); } void FUN_00a69640() { generated_stub("FUN_00a69640 00a69640"); } uint32_t FUN_00a69650(uint32_t param_1, uint32_t param_2, uint8_t param_3) { generated_stub("FUN_00a69650 00a69650"); } -KColor * FUN_00a69700(KColor *param_1, uint32_t param_2, uint32_t param_3) { generated_stub("FUN_00a69700 00a69700"); } void FUN_00a69760(uint32_t param_1, uint32_t param_2, uint32_t param_3, uint32_t param_4, uint32_t param_5) { generated_stub("FUN_00a69760 00a69760"); } void FUN_00a69950() { generated_stub("FUN_00a69950 00a69950"); } int FUN_00a69b10() { generated_stub("FUN_00a69b10 00a69b10"); } diff --git a/generated-src/weapon_bone.cpp b/generated-src/weapon_bone.cpp index 0a89639..58f3bf6 100644 --- a/generated-src/weapon_bone.cpp +++ b/generated-src/weapon_bone.cpp @@ -2502,118 +2502,6 @@ long double Weapon_Bone::GetMaxCharge() return (long double)fireDelay + (long double)fireDelay; } -// 009fef20 -void Weapon_Bone::TriggerNewRoom() -{ - uint8_t bVar1; - uint8_t *pbVar2; - uint32_t uVar3; - uint8_t *pbVar4; - uint8_t *idleName; - int *knifeSlot; - bool isLess; - int *eraseKey; - int slotsLeft; - int knife; - int *targetRef; - - knifeSlot = GHIDRA_CAST((GHIDRA_INT(this) + 0x44)); - slotsLeft = 4; - do { - knife = *knifeSlot; - if (knife != 0) { - targetRef = GHIDRA_CAST((knife + 0x3c4)); - *GHIDRA_CAST((knife + 0x334)) = g_vectorZero.x; - *GHIDRA_CAST((knife + 0x338)) = g_vectorZero.y; - if (*targetRef != 0) { - eraseKey = targetRef; - msvc::multiset::erase(&eraseKey); - } - *targetRef = 0; - *GHIDRA_CAST((knife + 0x444)) = 0; - *GHIDRA_CAST((knife + 0x464)) = 0; - *GHIDRA_CAST((knife + 0x448)) = 0; - *GHIDRA_CAST((knife + 0x4e5)) = 0; - switch(*GHIDRA_CAST((knife + 0x2c))) { - case 2: - case 3: - case 4: - case 8: - case 9: -code_r0x009fefcb: - if ((*GHIDRA_CAST((knife + 0x7c)) != 0) && (*GHIDRA_CAST((knife + 0x8c)) != '\0')) { - pbVar2 = *GHIDRA_CAST((knife + 0x7c)); - if (0xf < *GHIDRA_CAST((pbVar2 + 0x14))) { - pbVar2 = *GHIDRA_CAST(pbVar2); - } - pbVar4 = &DAT_00b602e8; - do { - bVar1 = *pbVar2; - isLess = bVar1 < *pbVar4; - if (bVar1 != *pbVar4) { -LAB_009ff012: - uVar3 = -GHIDRA_UINT(isLess) | 1; - goto LAB_009ff017; - } - if (bVar1 == 0) break; - bVar1 = pbVar2[1]; - isLess = bVar1 < pbVar4[1]; - if (bVar1 != pbVar4[1]) goto LAB_009ff012; - pbVar2 = pbVar2 + 2; - pbVar4 = pbVar4 + 2; - } while (bVar1 != 0); - uVar3 = 0; -LAB_009ff017: - if (uVar3 == 0) { - pbVar2 = *GHIDRA_CAST((knife + 0x7c)); - if (pbVar2 != GHIDRA_CAST(0x0)) { - pbVar4 = pbVar2; - if (0xf < *GHIDRA_CAST((pbVar2 + 0x14))) { - pbVar4 = *GHIDRA_CAST(pbVar2); - } - idleName = s_Idle; - do { - bVar1 = *pbVar4; - isLess = bVar1 < *idleName; - if (bVar1 != *idleName) { -LAB_009ff054: - uVar3 = -GHIDRA_UINT(isLess) | 1; - goto LAB_009ff059; - } - if (bVar1 == 0) break; - bVar1 = pbVar4[1]; - isLess = bVar1 < idleName[1]; - if (bVar1 != idleName[1]) goto LAB_009ff054; - pbVar4 = pbVar4 + 2; - idleName = idleName + 2; - } while (bVar1 != 0); - uVar3 = 0; -LAB_009ff059: - if ((uVar3 == 0) && ((pbVar2[0x34] == 0 || (*GHIDRA_CAST((knife + 0x8c)) != '\0')))) break; - } - bVar1 = ANM2::SetAnimation(GHIDRA_CAST((knife + 0x48)),s_Idle,1); - if (bVar1 != 0) { - AnimationState::Rewind(GHIDRA_CAST((knife + 0x78))); - *GHIDRA_CAST((knife + 0x8c)) = 1; - } - } - } - break; - case 5: - case 0xb: - break; - default: - if (*GHIDRA_CAST((knife + 0x2c)) == 1) goto code_r0x009fefcb; - } - } - knifeSlot = knifeSlot + 1; - slotsLeft = slotsLeft + -1; - if (slotsLeft == 0) { - return; - } - } while( true ); -} - // 009ff0c0 void Weapon_Bone::init_club(int *param_1) { diff --git a/generated-src/weapon_knife.cpp b/generated-src/weapon_knife.cpp deleted file mode 100644 index 7a7a130..0000000 --- a/generated-src/weapon_knife.cpp +++ /dev/null @@ -1,940 +0,0 @@ -#include "classes.h" - -// 00a03f90 -void Weapon_Knife::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) -{ - void *pvVar1; - int iVar2; - uint32_t uVar3; - Entity_Knife *pEVar4; - uint8_t bVar5; - Entity_Knife **ppEVar6; - float aimTargetX; - uint16_t uVar10; - undefined3 uVar9; - Vector *tmpVec; - BitSet128 *maskedTearFlags; - Entity_Knife **ppEVar7; - uint32_t rngValue; - int iVar8; - Entity *parent; - float aimTargetY; - Entity_Player *ownerPlayer; - int iVar11; - int iVar12; - char cVar13; - float fVar14; - uint32_t uVar15; - int *piVar16; - uint32_t *puVar17; - bool bVar18; - float fVar19; - undefined3 in_stack_00000009; - undefined3 in_stack_0000000d; - Entity_Knife aEStackY_7ffffdb4 [1636800]; - Entity_Knife *pEVar20; - Weapon_MultiShotParams *outParams; - Entity_Player *pEVar21; - uint8_t local_94 [12]; - float fStack_88; - Entity_Knife *knifeRange; - uint8_t multiShotParams [29]; - uint8_t bStack_63; - uint8_t bStack_62; - uint32_t uStack_60; - Entity_Knife *local_5c; - Vector local_58; - Entity_Knife *local_50; - float local_4c; - float shotSpeed; - uint32_t local_44; - uint8_t orbitTearFlags [4]; - Entity_Knife *knifeList; - Vector local_38; - float local_30; - Entity_Knife *local_2c; - char isMomsEye; - Weapon *local_24; - Entity_Player *local_20; - uint32_t *local_1c; - Entity_Player *local_18; - char isMarkedAim; - void *local_10; - uint8_t *puStack_c; - void *local_8; - Entity_Knife *knife; - - local_8 = (void *)0xffffffff; - puStack_c = &LAB_00b1081d; - local_10 = ExceptionList; - ExceptionList = &local_10; - pEVar20 = _isShooting; - knife = _isInterpolated; - local_24 = this; - Weapon::Fire(this,direction,isShooting,isInterpolated); - local_18 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - local_30 = 0.0; - local_20 = GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) >> 4 & 0xffffff01)); - local_44 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) >> 6 & 0xffffff01; - if (local_18 == GHIDRA_CAST(0x0)) { -LAB_00a04011: - pEVar21 = GHIDRA_CAST(0x0); - if ((local_18 == GHIDRA_CAST(0x0)) || (local_18->_type != 1)) { -LAB_00a04022: - local_18 = GHIDRA_CAST(0x0); - } - } - else { - if (local_18->_type != 1) { - if (local_18->_type != 3) goto LAB_00a04011; - pEVar21 = *GHIDRA_CAST(&(GHIDRA_CAST(&local_18->_isControlsEnabled))->_l); - goto LAB_00a04022; - } - pEVar21 = local_18; - } - if (pEVar21 == GHIDRA_CAST(0x0)) { -LAB_00a04043: - isMarkedAim = '\0'; - } - else { - knife = GHIDRA_CAST(0x0); - pEVar20 = GHIDRA_CAST(0x18a); - bVar5 = Entity_Player::HasCollectible(pEVar21,0x18a,0); - isMarkedAim = '\x01'; - if (bVar5 == 0) goto LAB_00a04043; - } - ppEVar7 = GHIDRA_CAST((GHIDRA_INT(this) + 0x10)); - local_5c = GHIDRA_CAST(0x3a83126f); - ppEVar6 = &local_5c; - if (0.001 < (float)*ppEVar7 || (float)*ppEVar7 == 0.001) { - ppEVar6 = ppEVar7; - } - local_2c = *ppEVar6; - if (local_18 == GHIDRA_CAST(0x0)) { - fVar14 = 0.0; - } - else { - knife = GHIDRA_CAST(0x6e); - pEVar20 = GHIDRA_CAST(0xa0407f); - bVar5 = TemporaryEffects::HasNullEffect(&local_18->_temporaryeffects,0x6e); - fVar14 = 0.0; - if (bVar5 != 0) { - fVar14 = 7.00649e-45; - } - local_30 = fVar14; - } - if (pEVar21 == GHIDRA_CAST(0x0)) { - fVar19 = 260.0; - } - else { - fVar19 = pEVar21->_tearrange; - } - knifeRange = GHIDRA_CAST((fVar19 * 0.6)); - parent = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (parent == GHIDRA_CAST(0x0)) { -LAB_00a04100: - shotSpeed = 1.0; - } - else if (parent->_type == 1) { - shotSpeed = parent[5]._pendingDamage; - } - else { - if ((parent->_type != 3) || (*GHIDRA_CAST((parent + 1)) == 0)) goto LAB_00a04100; - shotSpeed = *GHIDRA_CAST((*GHIDRA_CAST((parent + 1)) + 0x1464)); - } - local_50 = knifeRange; - if ((char)local_20 != '\0') { - if (isInterpolated != 0) goto LAB_00a04e59; - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) == 0) { - _isInterpolated = Weapon::fire_knife(this,parent,GHIDRA_UINT(fVar14),1,GHIDRA_INT(pEVar20),GHIDRA_INT(knife),0.0); - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) != _isInterpolated) { - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) != GHIDRA_CAST(0x0)) { - local_58.y = (float)(GHIDRA_INT(this) + 0x44); - msvc::multiset::erase(); - } - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) = _isInterpolated; - if (_isInterpolated != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(); - } - } - if (pEVar21 != GHIDRA_CAST(0x0)) { - init_knife(this,_isInterpolated); - } - (**(code **)&(*GHIDRA_CAST((GHIDRA_CAST(((*GHIDRA_CAST(_isInterpolated)))) + 0xc))))(); - } - knife = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)); - local_50 = knife; - init_knife(this,knife); - if ((local_18 != GHIDRA_CAST(0x0)) && - (iVar8 = Entity::GetIntervalTicks(GHIDRA_CAST(local_18),(float)local_2c,0.0), iVar8 != 0)) { - if (knife == GHIDRA_CAST(0x0)) { -LAB_00a04c17: - tmpVec = MusicManager::RandomVector(&local_38); - } - else { - local_58.y = (knife->_pos).y; - local_58.x = (knife->_pos).x; - local_38.x = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x33c)); - local_38.y = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x340)); - bVar5 = (GHIDRA_CAST((&local_58)))->Vector::operator_ne(&local_38); - if (bVar5 == 0) goto LAB_00a04c17; - local_38.x = (knife->_pos).x - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x33c)); - local_38.y = (knife->_pos).y - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x340)); - tmpVec = (GHIDRA_CAST((&local_38)))->Vector::Normalized(&local_58); - } - Weapon::TriggerTearEffects(this,tmpVec,1); - } - pEVar20 = g_game->_room; - if ((*GHIDRA_CAST(pEVar20) != '\0') && (g_game->_frameCount == pEVar20[3]._entityRef3._type)) { - tmpVec = Weapon::get_owner_position(this,&local_38); - pEVar20 = GHIDRA_CAST(tmpVec->x); - (knife->_pos).x = (float)pEVar20; - (knife->_pos).y = tmpVec->y; - } - pEVar21 = GHIDRA_CAST(multiShotParams); - Weapon::GetMultiShotParams(this,pEVar21,GHIDRA_INT(pEVar20)); - local_2c = GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&((short)multiShotParams)) + 0x0))) + -1)); - _isInterpolated = GHIDRA_CAST(0x0); - knifeList = GHIDRA_CAST(0x0); - if (GHIDRA_INT(local_2c) < 0) { - local_2c = GHIDRA_CAST(0x0); - } - ownerPlayer = GHIDRA_CAST(0x0); - local_20 = GHIDRA_CAST(0x0); - local_38.x = 0.0; - local_18 = GHIDRA_CAST(0x0); - local_38.y = 0.0; - local_8 = (void *)0x0; - local_44 = knife->_child; - if (local_44 != 0) { - do { - if (GHIDRA_CAST(local_38.x) == ownerPlayer) { - pEVar20 = GHIDRA_CAST(&local_44); - pEVar21 = GHIDRA_CAST(local_38.x); - msvc::vector::_Emplace_reallocate(); - ownerPlayer = GHIDRA_CAST(local_38.y); - } - else { - *GHIDRA_CAST(local_38.x) = local_44; - local_38.x = (float)(GHIDRA_INT(local_38.x) + 4); - } - local_44 = *GHIDRA_CAST((local_44 + 0x3c0)); - } while (local_44 != 0); - local_44 = 0; - local_20 = GHIDRA_CAST(local_38.x); - local_18 = ownerPlayer; - } - pEVar4 = knifeList; - local_58.y = (float)(GHIDRA_INT(local_20) - GHIDRA_INT(knifeList) >> 2); - local_38.x = (float)local_20; - _isInterpolated = knifeList; - if (GHIDRA_UINT(local_58.y) < local_2c) { - local_2c = GHIDRA_CAST((GHIDRA_INT(local_2c) - GHIDRA_INT(local_58.y))); - if (0 < GHIDRA_INT(local_2c)) { - do { - ownerPlayer = GHIDRA_CAST(local_38.x); - _isInterpolated = - Weapon::fire_knife(local_24,GHIDRA_CAST(knife),GHIDRA_UINT(local_30),0,GHIDRA_INT(pEVar21), - GHIDRA_INT(pEVar20),0.0); - pEVar21 = GHIDRA_CAST(0xa04d23); - pEVar20 = _isInterpolated; - init_knife(local_24,_isInterpolated); - if (ownerPlayer == local_18) { - pEVar20 = GHIDRA_CAST(&isInterpolated); - msvc::vector::_Emplace_reallocate(); - local_18 = GHIDRA_CAST(local_38.y); - } - else { - *GHIDRA_CAST(ownerPlayer) = _isInterpolated; - local_38.x = (float)(GHIDRA_INT(ownerPlayer) + 4); - ownerPlayer = pEVar21; - } - local_2c = GHIDRA_CAST((GHIDRA_INT(local_2c[-1]._sprite._color._offset) + 0x40f)); - pEVar21 = ownerPlayer; - } while (local_2c != GHIDRA_CAST(0x0)); - _isInterpolated = knifeList; - local_2c = GHIDRA_CAST(0x0); - } -LAB_00a04d8c: - fVar14 = (float)(GHIDRA_INT(local_38.x) - GHIDRA_INT(_isInterpolated) >> 2); - local_30 = 0.0; - pEVar20 = _isInterpolated; - if (fVar14 != 0.0) { - do { - local_50 = *(Entity_Knife **) - (GHIDRA_INT((&(pEVar20->_sprite)._filename + -3)) + GHIDRA_INT(local_30) * 4); - if (knife->_child != 0) { - local_58.y = (float)&knife->_child; - msvc::multiset::erase(); - pEVar20 = _isInterpolated; - } - knife->_child = local_50; - if (local_50 != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(); - pEVar20 = _isInterpolated; - } - knife = *GHIDRA_CAST((GHIDRA_INT((&(pEVar20->_sprite)._filename + -3)) + GHIDRA_INT(local_30) * 4)); - if (g_game->_frameCount == knife->_spawnFrame) { - (**(code **)(*GHIDRA_CAST(knife) + 0xc))(); - knife = *(Entity_Knife **) - (GHIDRA_INT((&(_isInterpolated->_sprite)._filename + -3)) + GHIDRA_INT(local_30) * 4); - pEVar20 = _isInterpolated; - } - local_30 = (float)(GHIDRA_INT(local_30) + 1); - } while (GHIDRA_UINT(local_30) < GHIDRA_UINT(fVar14)); - } - } - else { - pEVar20 = knifeList; - if (local_2c < GHIDRA_UINT(local_58.y)) { - knife = local_2c; - do { - (**(code **)(**GHIDRA_CAST((GHIDRA_INT((&(pEVar4->_sprite)._filename + -3)) + GHIDRA_INT(knife) * 4)) + 0x28) - )(); - knife = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((knife)) + 0x1)))); - } while (knife < GHIDRA_UINT(local_58.y)); - pEVar21 = GHIDRA_CAST((GHIDRA_INT((&(pEVar4->_sprite)._filename + -3)) + GHIDRA_INT(local_2c) * 4)); - local_38.x = (float)local_20; - if (pEVar21 != local_20) { - local_38.x = (float)pEVar21; - } - knife = local_50; - goto LAB_00a04d8c; - } - } - if (pEVar20 != GHIDRA_CAST(0x0)) { - uVar15 = GHIDRA_INT(local_18) - GHIDRA_INT(pEVar20) & 0xfffffffc; - knife = pEVar20; - if (0xfff < uVar15) { - knife = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(pEVar20[-1])) + 0x51c)))); - uVar15 = uVar15 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pEVar20) + (-4 - GHIDRA_INT(knife))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(knife,uVar15); - } - this = local_24; -LAB_00a04e59: - iVar8 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)); - if (iVar8 == 0) { - ExceptionList = local_10; - return; - } - if (isShooting == 0) { - ExceptionList = local_10; - return; - } - shotSpeed = shotSpeed * 5.0; - fVar14 = direction->x; - _isInterpolated = GHIDRA_CAST(direction->y); - fVar19 = fVar14 * fVar14 + (float)_isInterpolated * (float)_isInterpolated; - if ((1.0 < fVar19) && (fVar19 = sqrtf(fVar19), 0.0 < fVar19)) { - fVar14 = direction->x * (1.0 / fVar19); - _isInterpolated = GHIDRA_CAST((direction->y * (1.0 / fVar19))); - } - fVar19 = *GHIDRA_CAST((iVar8 + 0x36c)); - if (fVar19 == 0.0) { - ExceptionList = local_10; - return; - } - *GHIDRA_CAST((iVar8 + 0x364)) = - (*GHIDRA_CAST((iVar8 + 0x39c)) * shotSpeed * (float)_isInterpolated * 0.5) / fVar19 + - *GHIDRA_CAST((iVar8 + 0x364)); - *GHIDRA_CAST((iVar8 + 0x360)) = - (*GHIDRA_CAST((iVar8 + 0x39c)) * shotSpeed * fVar14 * 0.5) / fVar19 + *GHIDRA_CAST((iVar8 + 0x360)) - ; - ExceptionList = local_10; - return; - } - if ((parent == GHIDRA_CAST(0x0)) || - ((((parent->_type != 1 && - ((parent->_type != 3 || (parent = *GHIDRA_CAST((parent + 1)), parent == GHIDRA_CAST(0x0))))) || - (pvVar1 = parent[4]._entityPtrReferrers._head, pvVar1 == (void *)0x0)) || - (isMarkedAim == '\0')))) { - aimTargetX = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x28)); - aimTargetY = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x2c)); - } - else { - aimTargetX = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x33c)); - aimTargetY = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x340)); - } - uVar10 = (uint16_t)(GHIDRA_UINT(&local_38) >> 0x10); - uVar9 = CONCAT21(uVar10,(aimTargetX == g_vectorZero.x) << 6 | - (NAN(aimTargetX) || NAN(g_vectorZero.x)) << 2 | 2U | - aimTargetX < g_vectorZero.x); - if ((aimTargetX != g_vectorZero.x) || - (uVar9 = CONCAT21(uVar10,(aimTargetY == g_vectorZero.y) << 6 | - (NAN(aimTargetY) || NAN(g_vectorZero.y)) << 2 | 2U | - aimTargetY < g_vectorZero.y), aimTargetY != g_vectorZero.y)) { - isMarkedAim = '\x01'; - } - else { - isMarkedAim = '\0'; - } - local_24 = GHIDRA_CAST(CONCAT31(uVar9,isShooting)); - local_5c = GHIDRA_CAST(0x3dcccccd); - local_38.x = aimTargetX; - local_38.y = aimTargetY; - if (((isInterpolated == 0) && (isShooting != 0)) && (isMarkedAim != '\0')) { - pEVar20 = GHIDRA_CAST(0xa041bd); - tmpVec = Weapon::get_owner_position(this,&local_38); - fVar14 = aimTargetY - tmpVec->y; - fVar19 = aimTargetX - tmpVec->x; - knife = GHIDRA_CAST(0xa041d7); - fVar14 = sqrtf(fVar14 * fVar14 + fVar19 * fVar19); - fVar19 = (fVar14 - 50.0) / 250.0; - if (fVar19 <= 0.0) { - fVar19 = 0.0; - } - if (1.0 <= fVar19) { - fVar19 = 1.0; - } - fVar19 = (((float)local_2c * 4.0 - 5.0) * fVar19 + 5.0) - 1.0; - if ((0.0 < fVar19) && - (local_5c = GHIDRA_CAST((fVar14 / ((fVar19 / (float)local_2c) * 4.0))), - (float)local_5c <= 0.1)) { - local_5c = GHIDRA_CAST(0x3dcccccd); - } - local_24 = GHIDRA_CAST((GHIDRA_UINT(local_24) & 0xff)); - if (fVar19 < *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14))) { - local_24 = GHIDRA_CAST(0x0); - } - } - if (pEVar21 == GHIDRA_CAST(0x0)) { -LAB_00a0427f: - _isShooting = GHIDRA_CAST((GHIDRA_UINT(_isShooting) & 0xffffff)); - if (pEVar21 != GHIDRA_CAST(0x0)) goto LAB_00a04287; -LAB_00a0429a: - isMomsEye = '\0'; - } - else { - knife = GHIDRA_CAST(0x0); - pEVar20 = GHIDRA_CAST(0x57); - bVar5 = Entity_Player::HasCollectible(pEVar21,0x57,0); - if (bVar5 == 0) goto LAB_00a0427f; - _isShooting = GHIDRA_CAST(CONCAT13(1,_isShooting)); -LAB_00a04287: - knife = GHIDRA_CAST(0x0); - pEVar20 = GHIDRA_CAST(0x37); - bVar5 = Entity_Player::HasCollectible(pEVar21,0x37,0); - if (bVar5 == 0) goto LAB_00a0429a; - isMomsEye = '\x01'; - } - uVar15 = 0; - do { - if (((uVar15 == 0) || ((uVar15 == 1 && (isMomsEye != '\0')))) || - ((*GHIDRA_CAST((GHIDRA_CAST(&(in_stack_00000009)) + 0x2))) != '\0')) { - if (*GHIDRA_CAST((GHIDRA_CAST(this) + uVar15 * 4 + 0x44)) == 0) { - local_20 = (Entity_Player *) - Weapon::fire_knife(this,*GHIDRA_CAST((GHIDRA_CAST(this) + 4)),GHIDRA_UINT(local_30),1,GHIDRA_INT(pEVar20) - ,GHIDRA_INT(knife),0.0); - pEVar21 = *GHIDRA_CAST((GHIDRA_CAST(this) + uVar15 * 4 + 0x44)); - puVar17 = GHIDRA_CAST((GHIDRA_INT(this) + uVar15 * 4 + 0x44)); - if (pEVar21 != local_20) { - if (pEVar21 != GHIDRA_CAST(0x0)) { - pEVar20 = GHIDRA_CAST(0xa04339); - local_1c = puVar17; - msvc::multiset::erase(); - puVar17 = GHIDRA_CAST((GHIDRA_INT(this) + uVar15 * 4 + 0x44)); - } - *puVar17 = local_20; - if (local_20 != GHIDRA_CAST(0x0)) { - pEVar20 = GHIDRA_CAST(0xa0434e); - msvc::multiset::insert(); - } - } - *GHIDRA_CAST(((local_20->_bodySprite)._animDefaultName._buf + 4)) = (&DAT_00b81710)[uVar15] - ; - knife = GHIDRA_CAST(0xa04363); - (**(code **)(*GHIDRA_CAST(local_20) + 0xc))(); - } - } - else { - piVar16 = *GHIDRA_CAST((GHIDRA_CAST(this) + uVar15 * 4 + 0x44)); - if (piVar16 != GHIDRA_CAST(0x0)) { - knife = GHIDRA_CAST(0xa042c8); - (**(code **)(*piVar16 + 0x28))(); - if (*GHIDRA_CAST((GHIDRA_CAST(this) + uVar15 * 4 + 0x44)) != 0) { - knife = GHIDRA_CAST(&local_20); - pEVar20 = GHIDRA_CAST(0xa042eb); - local_20 = GHIDRA_CAST((GHIDRA_INT(this) + uVar15 * 4 + 0x44)); - msvc::multiset::erase(); - *GHIDRA_CAST((GHIDRA_CAST(this) + uVar15 * 4 + 0x44)) = 0; - } - } - } - uVar15 = uVar15 + 1; - } while (uVar15 < 4); - local_20 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)); - if (local_20 == GHIDRA_CAST(0x0)) { - ExceptionList = local_10; - return; - } - puVar17 = GHIDRA_CAST((GHIDRA_INT(this) + 0x44)); - _isShooting = GHIDRA_CAST(0x4); - do { - if (GHIDRA_CAST(*puVar17) != GHIDRA_CAST(0x0)) { - init_knife(this,GHIDRA_CAST(*puVar17)); - } - puVar17 = puVar17 + 1; - _isShooting = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(_isShooting[-1])) + 0x51f)))); - } while (_isShooting != GHIDRA_CAST(0x0)); - Weapon::IsAxisAligned(this); - cVar13 = *GHIDRA_CAST((GHIDRA_CAST(local_20) + 0x464)); - if (((cVar13 == '\0') || ((char)local_44 != '\0')) || (isMarkedAim != '\0')) { - _isShooting = GHIDRA_CAST(direction->x); - local_1c = GHIDRA_CAST(direction->y); - if ((((char)local_24 == '\0') && (cVar13 == '\0')) && - ((0.0 < *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) && (isMarkedAim == '\0')))) { - _isShooting = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)); - local_1c = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)); - } - if (((float)local_1c == 0.0) && ((float)_isShooting == 0.0)) { - if (local_18 == GHIDRA_CAST(0x0)) { - if (*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x28)) == 3) { - switch(*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0xd58))) { - case 0: - goto LAB_00a0445a; - case 1: - goto LAB_00a04464; - case 2: - goto LAB_00a044dd; - case 3: - local_1c = GHIDRA_CAST(0x3f800000); - } - } - } - else { - switch(local_18->_headDirection) { - case 0: -LAB_00a0445a: - _isShooting = GHIDRA_CAST(&DAT_bf800000); - break; - case 1: -LAB_00a04464: - local_1c = GHIDRA_CAST(&DAT_bf800000); - break; - case 2: -LAB_00a044dd: - _isShooting = GHIDRA_CAST(0x3f800000); - break; - case 3: - local_1c = GHIDRA_CAST(0x3f800000); - } - } - } - if (((char)local_44 != '\0') && (isMarkedAim == '\0')) { - if (ABS((float)_isShooting) <= ABS((float)local_1c)) { - _isShooting = GHIDRA_CAST(0x0); - if (0.0 <= (float)local_1c) { - local_1c = GHIDRA_CAST(0x3f800000); - } - else { - local_1c = GHIDRA_CAST(&DAT_bf800000); - } - } - else { - local_1c = GHIDRA_CAST(0x0); - if (0.0 <= (float)_isShooting) { - _isShooting = GHIDRA_CAST(0x3f800000); - } - else { - _isShooting = GHIDRA_CAST(&DAT_bf800000); - } - } - } - piVar16 = GHIDRA_CAST((GHIDRA_INT(this) + 0x44)); - local_18 = GHIDRA_CAST(0x0); - do { - if (*piVar16 != 0) { - fVar14 = atan2f((float)local_1c,(float)_isShooting); - fVar14 = fVar14 * 57.295776 + *GHIDRA_CAST((GHIDRA_INT(&DAT_00b81710) + GHIDRA_INT(local_18))); - if (360.0 < ABS(fVar14)) { - fVar14 = fmodf(fVar14,360.0); - } - if (fVar14 <= 180.0) { - if (fVar14 < -180.0) { - fVar14 = fVar14 + 360.0; - } - } - else { - fVar14 = fVar14 - 360.0; - } - *GHIDRA_CAST((*piVar16 + 0x438)) = fVar14; - local_4c = (float)*piVar16; - *GHIDRA_CAST((GHIDRA_CAST(local_4c) + 0x43c)) = 0; - } - local_18 = GHIDRA_CAST((GHIDRA_INT(local_18) + 4)); - piVar16 = piVar16 + 1; - } while (local_18 < 0x10); - cVar13 = *GHIDRA_CAST((GHIDRA_CAST(local_20) + 0x464)); - } - pEVar21 = local_20; - local_2c = GHIDRA_CAST(((float)local_2c * 4.0)); - if ((char)local_24 == '\0') { - if ((cVar13 == '\0') && (fVar14 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)), 0.0 < fVar14)) { - local_4c = (float)local_2c; - if (fVar14 <= (float)local_2c) { - local_4c = fVar14; - } - Weapon::TriggerTearEffects(this,direction,1); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_94)) + 0x0))) = *GHIDRA_CAST((GHIDRA_CAST(pEVar21) + 0x410)); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_94)) + 0x4))) = *GHIDRA_CAST((GHIDRA_CAST(pEVar21) + 0x414)); - (*GHIDRA_CAST((GHIDRA_CAST(&(local_94)) + 0x8))) = *GHIDRA_CAST((GHIDRA_CAST(pEVar21) + 0x418)); - fStack_88 = *GHIDRA_CAST((GHIDRA_CAST(pEVar21) + 0x41c)); - local_18 = GHIDRA_CAST(0x43960000); - _isShooting = GHIDRA_CAST(0x43960000); - outParams = GHIDRA_CAST(0xa046fd); - maskedTearFlags = - BitSet128::operator_and - (GHIDRA_CAST(orbitTearFlags),GHIDRA_CAST(local_94),&g_tearFlagOrbit); - if ((GHIDRA_INT(maskedTearFlags->_l) != 0 || *GHIDRA_CAST((GHIDRA_INT(&maskedTearFlags->_l) + 4)) != 0) || - (GHIDRA_INT(maskedTearFlags->_h) != 0 || *GHIDRA_CAST((GHIDRA_INT(&maskedTearFlags->_h) + 4)) != 0)) { - local_18 = GHIDRA_CAST(0x47c35000); - _isShooting = GHIDRA_CAST(0x47c35000); - } - ownerPlayer = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if ((ownerPlayer == GHIDRA_CAST(0x0)) || - ((ownerPlayer->_type != 1 && - ((ownerPlayer->_type != 3 || - (ownerPlayer = *GHIDRA_CAST(&ownerPlayer->_isControlsEnabled), - ownerPlayer == GHIDRA_CAST(0x0))))))) { - _isInterpolated = GHIDRA_CAST(0x0); - (*GHIDRA_CAST((GHIDRA_CAST(&(multiShotParams)) + 0x14))) = 1.4013e-45; - (*GHIDRA_CAST((GHIDRA_CAST(&(multiShotParams)) + 0x0))) = 0; - uVar15 = 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(multiShotParams)) + 0x18))) = 0.0; - stack0xffffff9c = GHIDRA_CAST((GHIDRA_UINT(stack0xffffff9c) & 0xff000000)); - (*GHIDRA_CAST((GHIDRA_CAST(&(multiShotParams)) + 0x4))) = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(multiShotParams)) + 0x8))) = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(multiShotParams)) + 0xc))) = 0.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(multiShotParams)) + 0x10))) = 0.0; - local_24 = GHIDRA_CAST(0x0); - uStack_60 = uStack_60 & 0xffff0000; - } - else { - outParams = GHIDRA_CAST(multiShotParams); - Entity_Player::GetMultiShotParams(ownerPlayer,outParams,*GHIDRA_CAST((GHIDRA_CAST(this) + 0x30))); - register0x0000001e = (uint16_t)(GHIDRA_UINT(pEVar21) >> 0x10); - _isInterpolated = (*GHIDRA_CAST((GHIDRA_CAST(&(multiShotParams)) + 0x0))); - uVar15 = GHIDRA_UINT(CONCAT11(bStack_63,bStack_62)); - local_24 = GHIDRA_CAST((uStack_60 & 0xffff)); - } - direction = GHIDRA_CAST(0x0); - do { - uVar3 = _isInterpolated; - knife = *GHIDRA_CAST((GHIDRA_CAST(this) + GHIDRA_INT(direction) * 4 + 0x44)); - if (knife != GHIDRA_CAST(0x0)) { - if (direction != GHIDRA_CAST(0x0)) { - if (direction == GHIDRA_CAST(0x1)) { - cVar13 = (char)(uVar15 >> 8); - } - else { - if (direction < GHIDRA_CAST(0x2)) goto LAB_00a04912; - cVar13 = (char)uVar15; - } - if (cVar13 == '\0') goto LAB_00a04912; - } - ppEVar7 = &knifeRange; - if ((float)local_18 <= (float)local_50) { - ppEVar7 = GHIDRA_CAST(&isShooting); - } - pEVar20 = *ppEVar7; - if ((float)pEVar20 <= (float)local_5c) { - pEVar20 = local_5c; - } - outParams = GHIDRA_CAST((local_4c / (float)local_2c)); - Entity_Knife::Shoot(knife,(float)outParams,(float)pEVar20); - puVar17 = GHIDRA_CAST(0x0); - if (0 < (short)uVar3) { - local_38.x = 1.0; - local_1c = GHIDRA_CAST((GHIDRA_INT((short)uVar3) / 2)); - local_38.y = 0.0; - do { - outParams = stack0xffffff9c; - FUN_009f4230(local_94,puVar17,4,local_38.x,local_38.y,shotSpeed); - iVar8 = 0xa04873; - fVar14 = atan2f(fStack_88,(*GHIDRA_CAST((GHIDRA_CAST(&((float)local_94)) + 0x8)))); - fVar14 = fVar14 * 57.295776; - local_58.y = *GHIDRA_CAST((GHIDRA_CAST(this) + GHIDRA_INT(direction) * 4 + 0x44)); - if (puVar17 == local_1c) { - if (360.0 < ABS(fVar14)) { - fVar14 = fmodf(fVar14,360.0); - } - if (fVar14 <= 180.0) { - if (fVar14 < -180.0) { - fVar14 = fVar14 + 360.0; - } - *GHIDRA_CAST((GHIDRA_CAST(local_58.y) + 0x43c)) = fVar14; - } - else { - *GHIDRA_CAST((GHIDRA_CAST(local_58.y) + 0x43c)) = fVar14 - 360.0; - } - } - else { - knife = Weapon::fire_knife(this,GHIDRA_CAST(local_58.y),GHIDRA_UINT(local_30),0,GHIDRA_INT(outParams) - ,iVar8,fVar14); - (**(code **)(*GHIDRA_CAST(knife) + 0xc))(); - } - puVar17 = GHIDRA_CAST((GHIDRA_INT(puVar17) + 1)); - } while (GHIDRA_INT(puVar17) < GHIDRA_INT((short)_isInterpolated)); - } - } -LAB_00a04912: - direction = GHIDRA_CAST((GHIDRA_INT(&direction->x) + 1)); - uVar15 = GHIDRA_UINT(CONCAT11(bStack_63,bStack_62)); - } while (GHIDRA_INT(direction) < 4); - for (uVar15 = GHIDRA_UINT(local_24) & 0xffff; uVar15 != 0; uVar15 = uVar15 - 1) { - iVar8 = 0xa04937; - rngValue = Random(); - knife = Weapon::fire_knife(this,*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)),GHIDRA_UINT(local_30),0, - GHIDRA_INT(outParams),iVar8, - (float)((double)GHIDRA_INT(rngValue) + - __uint_to_double_fixup[-(GHIDRA_INT(rngValue) >> 0x1f)]) * - 2.3283064e-10 * 360.0); - (**(code **)(*GHIDRA_CAST(knife) + 0xc))(); - } - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)) = g_vectorZero.x; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)) = g_vectorZero.y; - } - } - else if (cVar13 == '\0') { - if (isInterpolated == 0) { - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) == 0) { - fVar14 = 1.0; - } - else { - fVar14 = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x39c)); - } - fVar14 = fVar14 + *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)); - fVar19 = (float)local_2c; - if (fVar14 <= (float)local_2c) { - fVar19 = fVar14; - } - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) = fVar19; - } - tmpVec = Weapon::get_aim_direction(this,&local_38,direction); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)) = tmpVec->x; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)) = tmpVec->y; - } - if (((*GHIDRA_CAST((GHIDRA_CAST(local_20) + 0x464)) == '\0') || - (25.0 < *GHIDRA_CAST((GHIDRA_CAST(local_20) + 0x444)) || *GHIDRA_CAST((GHIDRA_CAST(local_20) + 0x444)) == 25.0)) || - (*GHIDRA_CAST((GHIDRA_CAST(local_20) + 0x448)) <= 0.0)) { - iVar8 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (((iVar8 != 0) && (iVar11 = iVar8, *GHIDRA_CAST((iVar8 + 0x28)) == 1)) || - ((iVar11 = 0, iVar8 == 0 || (*GHIDRA_CAST((iVar8 + 0x28)) != 3)))) { - if (iVar11 != 0) { - iVar8 = *GHIDRA_CAST((iVar11 + 0x1338)); - if (iVar8 < 7) { - iVar8 = 7; - } - *GHIDRA_CAST((iVar11 + 0x1338)) = iVar8; - } - goto LAB_00a04a62; - } - iVar11 = *GHIDRA_CAST((iVar8 + 0xd50)); - iVar12 = 7; - bVar18 = SBORROW4(iVar11,7); - iVar2 = iVar11 + -7; - } - else { - iVar8 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (((iVar8 != 0) && (iVar11 = iVar8, *GHIDRA_CAST((iVar8 + 0x28)) == 1)) || - ((iVar11 = 0, iVar8 == 0 || (*GHIDRA_CAST((iVar8 + 0x28)) != 3)))) { - if (iVar11 != 0) { - iVar8 = *GHIDRA_CAST((iVar11 + 0x1338)); - if (iVar8 < 0xf) { - iVar8 = 0xf; - } - *GHIDRA_CAST((iVar11 + 0x1338)) = iVar8; - } - goto LAB_00a04a62; - } - iVar11 = *GHIDRA_CAST((iVar8 + 0xd50)); - iVar12 = 0xf; - bVar18 = SBORROW4(iVar11,0xf); - iVar2 = iVar11 + -0xf; - } - if (bVar18 != iVar2 < 0) { - iVar11 = iVar12; - } - *GHIDRA_CAST((iVar8 + 0xd50)) = iVar11; -LAB_00a04a62: - if (((*GHIDRA_CAST((GHIDRA_CAST(local_20) + 0x464)) != '\0') && (isMarkedAim == '\0')) && - ((char)local_44 == '\0')) { - iVar8 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (((iVar8 == 0) || (iVar11 = iVar8, *GHIDRA_CAST((iVar8 + 0x28)) != 1)) && - ((iVar11 = 0, iVar8 != 0 && (*GHIDRA_CAST((iVar8 + 0x28)) == 3)))) { - iVar11 = *GHIDRA_CAST((iVar8 + 0xda8)); - if (iVar11 < 2) { - iVar11 = 2; - } - *GHIDRA_CAST((iVar8 + 0xda8)) = iVar11; - ExceptionList = local_10; - return; - } - if (iVar11 != 0) { - iVar8 = *GHIDRA_CAST((iVar11 + 0x133c)); - if (iVar8 < 2) { - iVar8 = 2; - } - *GHIDRA_CAST((iVar11 + 0x133c)) = iVar8; - ExceptionList = local_10; - return; - } - } - ExceptionList = local_10; - return; -} - -// 00a04f90 -void Weapon_Knife::ClearReferences() -{ - int *entityRef; - int remaining; - int *local_8; - - entityRef = GHIDRA_CAST((GHIDRA_INT(this) + 8)); - local_8 = this; - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 8)) != GHIDRA_CAST(0x0)) { - (**(code **)(**GHIDRA_CAST((GHIDRA_CAST(this) + 8)) + 0x28))(); - if (*entityRef != 0) { - local_8 = entityRef; - msvc::multiset::erase(&local_8); - *entityRef = 0; - } - } - entityRef = GHIDRA_CAST((GHIDRA_INT(this) + 0x44)); - remaining = 4; - do { - if (GHIDRA_CAST(*entityRef) != GHIDRA_CAST(0x0)) { - (**(code **)(*GHIDRA_CAST(*entityRef) + 0x28))(); - if (*entityRef != 0) { - local_8 = entityRef; - msvc::multiset::erase(&local_8); - *entityRef = 0; - } - } - entityRef = entityRef + 1; - remaining = remaining + -1; - } while (remaining != 0); - return; -} - -// 00a05010 -float Weapon_Knife::GetMaxCharge() -{ - float baseCharge; - - if ((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) >> 4 & 1) != 0) { - return 0.0; - } - baseCharge = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)); - if (baseCharge < 0.001) { - baseCharge = 0.001; - } - return baseCharge * 4.0; -} - -// 00a05060 -uint8_t Weapon_Knife::SupportsTractorBeam() -{ - return ~(uint8_t)(*GHIDRA_CAST((GHIDRA_CAST(this) + 0x34)) >> 4) & 1; -} - -// 00a05070 -void Weapon_Knife::init_knife(Entity_Knife *knife) -{ - float *extraout_EAX; - ColorMod *tearColor; - BitSet128 *ownerTearFlags; - uint32_t ludoFlagsWord1; - Entity_Player *this_00; - uint32_t ludoFlagsWord3; - uint32_t ludoFlagsWord2; - Weapon *unaff_EDI; - float fVar1; - float fStack_6c; - int tearFlagsWord1; - uint8_t auStack_58 [4]; - float knifeOffsetY; - float knifeOffsetX; - Weapon *local_4c; - Vector flyingOffset [2]; - ColorMod tearColorOut; - uint32_t local_c; - uint64_t tearFlagsHigh; - uint32_t tearFlagsWord1; - uint32_t tearFlagsWord3; - code *virtualFn; - - local_c = __security_cookie ^ GHIDRA_UINT(auStack_58); - this_00 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - local_4c = this; - if (this_00 == GHIDRA_CAST(0x0)) { -LAB_00a05166: - knifeOffsetX = 0.0; - knifeOffsetY = -10.0; - } - else { - knifeOffsetX = 0.0; - if (this_00->_type != 1) { - if (this_00->_type != 3) goto LAB_00a05166; - this_00 = *GHIDRA_CAST(&this_00->_isControlsEnabled); - knifeOffsetY = -10.0; - if (this_00 == GHIDRA_CAST(0x0)) goto LAB_00a0517d; - } - knifeOffsetX = (this_00->_posOffset).x + 0.0; - knifeOffsetY = (this_00->_posOffset).y - 10.0; - if ((this_00->_flags & 0x200000000000000) != 0) { - knifeOffsetY = knifeOffsetY - 15.0; - } - tearFlagsWord1 = this_00->_entityGridCollisionClass; - if ((((tearFlagsWord1 == 0) || (tearFlagsWord1 == 3)) || (tearFlagsWord1 == 1)) || (tearFlagsWord1 == 2)) { - Entity_Player::GetFlyingOffset(this_00,flyingOffset); - knifeOffsetX = *extraout_EAX / 0.65 + knifeOffsetX; - knifeOffsetY = extraout_EAX[1] / 0.65 + knifeOffsetY; - } - } -LAB_00a0517d: - virtualFn = *(code **)(*GHIDRA_CAST(knife) + 0x3c); - tearColor = Weapon::get_tear_color(local_4c,&tearColorOut); - tearFlagsWord1 = 1; - fStack_6c = 3.57331e-43; - (*virtualFn)(tearColor,0xffffffff); - if ((GHIDRA_UINT(unaff_EDI->_modifiers) >> 4 & 1) == 0) { - ownerTearFlags = Weapon::get_owner_tear_flags(unaff_EDI,GHIDRA_CAST((auStack_58 + -4))); - tearFlagsWord1 = *GHIDRA_CAST((GHIDRA_INT(&ownerTearFlags->_l) + 4)); - tearFlagsHigh = ownerTearFlags->_h; - tearFlagsWord3 = *GHIDRA_CAST((GHIDRA_INT(&ownerTearFlags->_h) + 4)); - *GHIDRA_CAST(&(knife->_tearFlags)._l) = GHIDRA_INT(ownerTearFlags->_l); - *GHIDRA_CAST((GHIDRA_INT(&(knife->_tearFlags)._l) + 4)) = tearFlagsWord1; - *GHIDRA_CAST(&(knife->_tearFlags)._h) = GHIDRA_INT(tearFlagsHigh); - *GHIDRA_CAST((GHIDRA_INT(&(knife->_tearFlags)._h) + 4)) = tearFlagsWord3; - } - else { - ownerTearFlags = Weapon::get_owner_tear_flags(unaff_EDI,GHIDRA_CAST((auStack_58 + -4))); - ludoFlagsWord2 = GHIDRA_UINT(ownerTearFlags->_h) | GHIDRA_UINT(g_tearFlagLudovico._h); - ludoFlagsWord3 = *GHIDRA_CAST((GHIDRA_INT(&ownerTearFlags->_h) + 4)) | (*GHIDRA_CAST((GHIDRA_CAST(&(g_tearFlagLudovico._h)) + 0x4))); - ludoFlagsWord1 = *GHIDRA_CAST((GHIDRA_INT(&ownerTearFlags->_l) + 4)) | (*GHIDRA_CAST((GHIDRA_CAST(&(g_tearFlagLudovico._l)) + 0x4))); - *GHIDRA_CAST(&(knife->_tearFlags)._l) = GHIDRA_UINT(ownerTearFlags->_l) | GHIDRA_UINT(g_tearFlagLudovico._l); - *GHIDRA_CAST((GHIDRA_INT(&(knife->_tearFlags)._l) + 4)) = ludoFlagsWord1; - *GHIDRA_CAST(&(knife->_tearFlags)._h) = ludoFlagsWord2; - *GHIDRA_CAST((GHIDRA_INT(&(knife->_tearFlags)._h) + 4)) = ludoFlagsWord3; - } - virtualFn = *(code **)(*GHIDRA_CAST(knife) + 0x40); - fVar1 = Weapon::get_damage(unaff_EDI); - (*virtualFn)(fVar1); - if ((*GHIDRA_CAST((tearFlagsWord1 + 4)) != 0) && (*GHIDRA_CAST((*GHIDRA_CAST((tearFlagsWord1 + 4)) + 0x28)) == 3)) { - fVar1 = g_vectorOne.x * 0.75; - (knife->_sprite)._scale.y = g_vectorOne.y * 0.75; - fStack_6c = -20.0; - (knife->_sprite)._scale.x = fVar1; - } - (knife->_posOffset).x = 0.0; - (knife->_posOffset).y = fStack_6c; - return; -} diff --git a/src/boss_adversary.cpp b/src/boss_adversary.cpp new file mode 100644 index 0000000..8e390a1 --- /dev/null +++ b/src/boss_adversary.cpp @@ -0,0 +1,328 @@ +#include "boss_ai.h" +#include "camera.h" +#include "entity_bomb.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "grid_entity_trap_door.h" +#include "npc_caves.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include + +// The Adversary's states: wandering, the brimstone, the spiders, the flight and the scream that darkens the room. +constexpr int ADVERSARY_BRIMSTONE = NPC_STATE_ATTACK; +constexpr int ADVERSARY_SPIDERS = NPC_STATE_SUMMON; +constexpr int ADVERSARY_FLIGHT = NPC_STATE_JUMP; +constexpr int ADVERSARY_SCREAM = NPC_STATE_SPECIAL; + +constexpr float ADVERSARY_FRICTION = 0.85f; + +// It acts on a beat of 30 frames (15 below 30 percent health): on the double beat it screams three times in 4 (or +// whenever feared) while the room is lit, on a beat in view one time in 3 it fires brimstone (90 frames apart among +// Adversaries), with few enemies about one time in 3 it throws spiders, else one time in 3 it flies. +constexpr int ADVERSARY_BEAT = 30; +constexpr int ADVERSARY_HURT_BEAT = 15; +constexpr float ADVERSARY_HURT_HEALTH = 0.3f; +constexpr uint32_t ADVERSARY_SCREAM_ODDS = 3; +constexpr uint32_t ADVERSARY_ATTACK_ODDS = 3; +constexpr int ADVERSARY_SPIDER_ENEMY_LIMIT = 3; +constexpr int ADVERSARY_BRIMSTONE_COOLDOWN = 90; + +// The brimstone, left, up, right or down: a tracer for 28 frames, then a 10-frame homing beam from the mouth. +constexpr std::array ADVERSARY_BRIMSTONE_ANIMS = {"Attack2Left", "Attack2Up", "Attack2Right", + "Attack2Down"}; +constexpr ColorMod ADVERSARY_TRACER_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float ADVERSARY_TRACER_SCALE = 4; +constexpr int ADVERSARY_TRACER_TIMEOUT = 28; +constexpr float ADVERSARY_MOUTH_SIDE = 30; +constexpr float ADVERSARY_MOUTH_HEIGHT = -25; +constexpr float ADVERSARY_MOUTH_LOW = -5; +constexpr int ADVERSARY_LASER_VARIANT = 1; +constexpr int ADVERSARY_LASER_TIMEOUT = 10; +constexpr uint32_t ADVERSARY_LASER_HOMING = 2; +constexpr float ADVERSARY_LASER_DEPTH_DOWN = 10; + +// The spiders: four less the enemies about (or its Delirium spiders), each thrown to a free spot within 100. +constexpr int ADVERSARY_SPIDER_LIMIT = 4; +constexpr float ADVERSARY_SPIDER_SEARCH = 100; +constexpr float ADVERSARY_SPIDER_VOLUME = 0.7f; +constexpr int ADVERSARY_SPIDER_PATH = 900; +constexpr int ADVERSARY_SPIDER_PATH_LIMIT = 950; +constexpr float ADVERSARY_SPIDER_RISE = -8; +constexpr float ADVERSARY_SPIDER_STEP = 0.04f; +constexpr float ADVERSARY_SPIDER_LIFT = 10; + +// The flight: it soars at its target, comes down after 75 frames, and lands with a crushing shockwave. +constexpr float ADVERSARY_FLIGHT_PUSH = 1.3f; +constexpr int ADVERSARY_FLIGHT_FRAMES = 75; +constexpr float ADVERSARY_FLIGHT_VOLUME = 0.8f; +constexpr int ADVERSARY_FLIGHT_CRY_DELAY = 60; +constexpr int ADVERSARY_SHOCKWAVE_TIMEOUT = 20; +constexpr float ADVERSARY_SHOCKWAVE_REACH = 75; +constexpr int ADVERSARY_LAND_SHAKE = 15; +constexpr float ADVERSARY_LAND_DAMAGE = 50; +constexpr float ADVERSARY_RIPPLE_AMPLITUDE = 0.04f; +constexpr float ADVERSARY_RIPPLE_SPEED = 0.025f; +constexpr int ADVERSARY_RIPPLE_FRAMES = 13; + +// The scream darkens the room for 180 frames. In Mega Satan's room it keeps below his platform. +constexpr float ADVERSARY_DARKNESS = 1; +constexpr int ADVERSARY_DARKNESS_FRAMES = 180; +constexpr float ADVERSARY_MEGA_SATAN_FLOOR = 320; + +// The brimstone's start: facing its target on the nearer axis, a tracer, and every Adversary waits 90 frames. +static void adversary_brimstone_start(Entity_NPC& npc, Vector toTarget) +{ + npc.state = ADVERSARY_BRIMSTONE; + npc.stateFrame = 0; + npc.PlaySound(SOUND_MONSTER_ROAR_3, 1, 2, false, 1); + + float angle = 0; + Vector offset = vector_make(ADVERSARY_MOUTH_SIDE, ADVERSARY_MOUTH_HEIGHT); + if (std::abs(toTarget.y) <= std::abs(toTarget.x)) + { + npc.i1 = toTarget.x >= 0 ? DIRECTION_RIGHT : DIRECTION_LEFT; + if (toTarget.x < 0) + { + angle = 180; + offset.x = -ADVERSARY_MOUTH_SIDE; + } + } + else + { + npc.i1 = toTarget.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP; + angle = toTarget.y >= 0 ? 90 : 270; + offset = vector_make(0, toTarget.y >= 0 ? ADVERSARY_MOUTH_LOW : ADVERSARY_MOUTH_HEIGHT); + } + following_effect_spawn(npc, {.offset = offset, + .targetPosition = vector_from_angle(angle), + .color = ADVERSARY_TRACER_COLOR, + .scale = ADVERSARY_TRACER_SCALE, + .timeout = ADVERSARY_TRACER_TIMEOUT}); + if (npc.IsFriendly()) return; + + bool isVersus = g_game->deathmatchManager.is_active(); + for (Entity* entity : entity_query(npc.type, npc.variant)) + { + bool isEnemy = (isVersus && entity->type == ENTITY_PLAYER) || + (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENTITY_LAST_ENEMY); + if (isEnemy && !entity->isDead && !entity->HasEntityFlags(FLAG_FRIENDLY)) + static_cast(entity)->i2 = ADVERSARY_BRIMSTONE_COOLDOWN; + } +} + +// The wander: on its beats it screams, fires brimstone, throws spiders or flies. +static void adversary_wander(Entity_NPC& npc, int ticks, Vector toTarget) +{ + npc.stateFrame += ticks; + npc.sprite.Play("Walk"); + npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + + bool isSeen = g_game->room->camera->IsPosVisible(npc.pos); + int beat = npc.health / npc.maxHitPoints < ADVERSARY_HURT_HEALTH ? ADVERSARY_HURT_BEAT : ADVERSARY_BEAT; + bool isFrameUpdate = !npc.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused(); + uint32_t frame = g_game->frameCount + npc.index; + bool isScreaming = isFrameUpdate && frame % (uint32_t)(beat * 2) == 0 && (Random() & 3) < ADVERSARY_SCREAM_ODDS; + if ((npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || isScreaming) && g_game->darknessModifier <= 0) + { + npc.state = ADVERSARY_SCREAM; + npc.stateFrame = 0; + return; + } + + if (isSeen && npc.IsFrame(beat, (int)npc.index) && Random() % ADVERSARY_ATTACK_ODDS == 0 && npc.i2 <= 0) + return adversary_brimstone_start(npc, toTarget); + if (g_game->room->GetAliveEnemiesCount() < ADVERSARY_SPIDER_ENEMY_LIMIT && npc.IsFrame(beat, (int)npc.index) && + Random() % ADVERSARY_ATTACK_ODDS == 0) + { + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + npc.state = ADVERSARY_SPIDERS; + return; + } + if (!isFrameUpdate || frame % (uint32_t)beat != 0 || Random() % ADVERSARY_ATTACK_ODDS != 0) return; + npc.state = ADVERSARY_FLIGHT; + npc.sprite.Play("FlyUp"); + npc.stateFrame = 0; + npc.PlaySound(SOUND_MONSTER_GRUNT_4, 1, 2, false, 1); +} + +// The brimstone: on Shoot a short homing beam from its mouth. Whether it is done. +static bool adversary_brimstone(Entity_NPC& npc, int ticks) +{ + npc.stateFrame += ticks; + if (npc.i1 >= DIRECTION_LEFT && npc.i1 <= DIRECTION_DOWN) npc.sprite.Play(ADVERSARY_BRIMSTONE_ANIMS[npc.i1]); + if (!npc.sprite.animState.animData) return true; + if (!npc.sprite.IsEventTriggered("Shoot")) return npc_anim_is_done(npc); + + float angle = 0; + Vector offset{}; + switch (npc.i1) + { + case DIRECTION_LEFT: + angle = 180; + offset = vector_make(-ADVERSARY_MOUTH_SIDE, ADVERSARY_MOUTH_HEIGHT); + break; + case DIRECTION_UP: + angle = 270; + offset = vector_make(0, ADVERSARY_MOUTH_HEIGHT); + break; + case DIRECTION_RIGHT: + offset = vector_make(ADVERSARY_MOUTH_SIDE, ADVERSARY_MOUTH_HEIGHT); + break; + case DIRECTION_DOWN: + angle = 90; + offset = vector_make(0, ADVERSARY_MOUTH_LOW); + break; + } + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = vector_add(offset, npc.pos), + .posOffset = vector_make(0, ADVERSARY_MOUTH_HEIGHT), + .source = &npc, + .angleDegrees = angle, + .timeout = ADVERSARY_LASER_TIMEOUT, + .variant = ADVERSARY_LASER_VARIANT}); + laser->homingType = ADVERSARY_LASER_HOMING; + if (npc.i1 == DIRECTION_DOWN) laser->renderDepthOffset = ADVERSARY_LASER_DEPTH_DOWN; + laser->Update(); + return npc_anim_is_done(npc); +} + +// The spiders: on Shoot it throws spiders out to free spots around it. Whether it is done. +static bool adversary_spiders(Entity_NPC& npc) +{ + npc.sprite.Play("Attack1"); + if (!npc.sprite.animState.animData) return true; + if (npc.sprite.IsEventTriggered("Skin Pull")) npc.PlaySound(SOUND_SKIN_PULL, 1, 2, false, 1); + if (!npc.sprite.animState.animData || !npc.sprite.IsEventTriggered("Shoot")) return npc_anim_is_done(npc); + + npc.PlaySound(SOUND_SUMMONSOUND, ADVERSARY_SPIDER_VOLUME, 2, false, 1); + int about = g_game->room->GetAliveEnemiesCount(); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) about = npc.CountRelatedEntities(ENTITY_SPIDER, 0, nullptr); + for (int i = 0; i < ADVERSARY_SPIDER_LIMIT - about; i++) + { + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = ADVERSARY_SPIDER_SEARCH}); + auto* spider = static_cast( + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_SPIDER, .seed = Random()})); + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(spot); + if (gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS && room.gridPaths[gridIndex] <= ADVERSARY_SPIDER_PATH_LIMIT) + room.gridPaths[gridIndex] = ADVERSARY_SPIDER_PATH; + + spider->targetPosition = spider->pos; + spider->pos = npc.pos; + spider->posOffset.y -= ADVERSARY_SPIDER_LIFT; + spider->state = NPC_STATE_JUMP; + spider->v2.y = ADVERSARY_SPIDER_RISE; + spider->velocity = vector_scale(vector_sub(spider->targetPosition, npc.pos), ADVERSARY_SPIDER_STEP); + spider->v1 = spider->velocity; + } + return npc_anim_is_done(npc); +} + +// The landing: a shockwave ring, a shake, a crushing blast and a ripple. +static void adversary_land(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + auto* wave = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_SHOCKWAVE, .seed = Random()})); + wave->lifespan = ADVERSARY_SHOCKWAVE_TIMEOUT; + wave->timeout = ADVERSARY_SHOCKWAVE_TIMEOUT; + wave->minRadius = npc.size; + wave->maxRadius = npc.size + ADVERSARY_SHOCKWAVE_REACH; + wave->parent = &npc; + game_shake_screen(ADVERSARY_LAND_SHAKE); + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + explosion_damage({.position = npc.pos, + .source = &npc, + .damageFlags = DAMAGE_CRUSH, + .damage = ADVERSARY_LAND_DAMAGE, + .radius = npc.size, + .isLineCheck = false}); + shockwave_make(npc.pos, ADVERSARY_RIPPLE_AMPLITUDE, ADVERSARY_RIPPLE_SPEED, ADVERSARY_RIPPLE_FRAMES); +} + +// The flight: it soars at its target out of reach, comes down once it has flown long enough, and lands. Whether it +// is done. +static bool adversary_flight(Entity_NPC& npc, int ticks, Vector toAim) +{ + npc.stateFrame += ticks; + const AnimationData* data = npc.sprite.animState.animData; + if (!data || data->name != "FlyUp") + { + if (npc.sprite.IsEventTriggered("Land")) adversary_land(npc); + return npc_anim_is_done(npc); + } + + if (npc.sprite.WasEventTriggered("Fly")) + { + Vector push = vector_normalized(toAim); + npc.velocity.x = push.x * ADVERSARY_FLIGHT_PUSH * npc.speedMultiplier + npc.velocity.x; + npc.velocity.y = push.y * ADVERSARY_FLIGHT_PUSH * npc.speedMultiplier + npc.velocity.y; + } + npc.entityCollisionClass = ENTCOLL_NONE; + if (!npc_anim_is_done(npc)) return false; + npc.PlaySound(SOUND_MONSTER_ROAR_1, ADVERSARY_FLIGHT_VOLUME, ADVERSARY_FLIGHT_CRY_DELAY, false, 1); + if (npc.stateFrame > ADVERSARY_FLIGHT_FRAMES) npc.sprite.Play("FlyDown"); + return false; +} + +// The scream: once it ends the room goes dark. +static void adversary_scream(Entity_NPC& npc, int ticks) +{ + npc.sprite.Play("Scream"); + npc.stateFrame += ticks; + if (npc.sprite.IsEventTriggered("Scream")) npc.PlaySound(SOUND_MONSTER_YELL_B, 1, 2, false, 1); + if (!npc_anim_is_done(npc)) return; + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + g_game->darknessStrength = ADVERSARY_DARKNESS; + g_game->darknessTimeout = ADVERSARY_DARKNESS_FRAMES; +} + +// 0045e050 NpcAI::ENTITY_ADVERSARY: the Adversary wanders, fires homing brimstone along an axis, throws spiders, +// flies at its target and lands with a shockwave, and screams the room dark. Adversaries' explosions spare it. +void boss_adversary_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + Vector toTarget = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + Vector toAim = vector_sub(npc.CalcTargetPosition(0), npc.pos); + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + return; + } + + npc.friction = ADVERSARY_FRICTION; + if (npc.pendingDamage > 0 && npc.pendingDamageFlags & DAMAGE_EXPLOSION) + for (DamageEvent& event : npc.damageEvents) + if (event.source.type == npc.type) event.damage = 0; + if (npc.i2 > 0) npc.i2 -= ticks; + + bool isDone = false; + switch (npc.state) + { + case NPC_STATE_MOVE: + adversary_wander(npc, ticks, toTarget); + break; + case ADVERSARY_BRIMSTONE: + isDone = adversary_brimstone(npc, ticks); + break; + case ADVERSARY_SPIDERS: + isDone = adversary_spiders(npc); + break; + case ADVERSARY_FLIGHT: + isDone = adversary_flight(npc, ticks, toAim); + break; + case ADVERSARY_SCREAM: + adversary_scream(npc, ticks); + break; + } + if (isDone) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + } + if (g_game->room->bossId == BOSS_ID_MEGA_SATAN && npc.pos.y < ADVERSARY_MEGA_SATAN_FLOOR) + npc.pos.y = ADVERSARY_MEGA_SATAN_FLOOR; +} diff --git a/src/boss_ai.h b/src/boss_ai.h index 3a1a74f..5ccf2a9 100644 --- a/src/boss_ai.h +++ b/src/boss_ai.h @@ -127,7 +127,20 @@ struct RadiusDamage void damage_radius(const RadiusDamage& hit); +// Whether QueryNPCsSpawnerType keeps every entity or only the active enemies. +enum SpawnerQueryMode +{ + SPAWNER_QUERY_ALL, + SPAWNER_QUERY_ENEMIES +}; + +std::vector npc_query_spawner_type(int spawnerType, int entityType, SpawnerQueryMode mode); + +void boss_adversary_update(Entity_NPC& npc); void boss_baby_plum_update(Entity_NPC& npc); +void boss_blastocyst_update(Entity_NPC& npc); +void boss_cage_update(Entity_NPC& npc); +void boss_chub_update(Entity_NPC& npc); void boss_dingle_update(Entity_NPC& npc); void boss_duke_update(Entity_NPC& npc); void boss_famine_update(Entity_NPC& npc); @@ -140,8 +153,14 @@ void boss_haunt_update(Entity_NPC& npc); void boss_larry_jr_update(Entity_NPC& npc); void boss_little_horn_update(Entity_NPC& npc); void boss_loki_update(Entity_NPC& npc); +void boss_mama_gurdy_update(Entity_NPC& npc); +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_mr_fred_update(Entity_NPC& npc); +void boss_moms_heart_update(Entity_NPC& npc); +void boss_moms_heart_death_shots(Entity_NPC& npc); void boss_monstro_update(Entity_NPC& npc); void boss_peep_update(Entity_NPC& npc); void boss_pestilence_update(Entity_NPC& npc); diff --git a/src/boss_blastocyst.cpp b/src/boss_blastocyst.cpp new file mode 100644 index 0000000..8492c3c --- /dev/null +++ b/src/boss_blastocyst.cpp @@ -0,0 +1,408 @@ +#include "boss_ai.h" +#include "grid_entity_trap_door.h" +#include "npc_caves.h" +#include "room_render.h" +#include "sfx_manager.h" + +// Blastocyst's states: its drop into the boss room (the big jump's landing too), the hop, the big jump and the stomp, +// and the split. +constexpr int BLASTOCYST_DROP = NPC_STATE_APPEAR_CUSTOM; +constexpr int BLASTOCYST_HOP = NPC_STATE_MOVE; +constexpr int BLASTOCYST_JUMP = NPC_STATE_JUMP; +constexpr int BLASTOCYST_LAND = NPC_STATE_STOMP; +constexpr int BLASTOCYST_STOMP = NPC_STATE_ATTACK; +constexpr int BLASTOCYST_SPLIT = NPC_STATE_SPECIAL; + +constexpr int BOSS_ID_BLASTOCYST = 16; + +constexpr int BLASTOCYST_LAYER_BODY = 0; +constexpr int BLASTOCYST_LAYER_EYES = 4; +constexpr float BLASTOCYST_FRICTION = 0.8f; +constexpr float BLASTOCYST_SIZED_FRICTION = 0.9f; +constexpr float BLASTOCYST_GROUND_FRICTION = 0.6f; + +// The big one stomps within 180 of its target (within 250 four times in 5) or hops, else jumps at it. +constexpr float BLASTOCYST_NEAR_SQUARED = 32400; +constexpr float BLASTOCYST_FAR_SQUARED = 62500; +constexpr float BLASTOCYST_FAR = 250; +constexpr uint32_t BLASTOCYST_STAY_ODDS = 5; +constexpr float BLASTOCYST_HOP_SPEED = 1.5f; +constexpr float BLASTOCYST_STOMP_SPEED = 0.4f; +constexpr float BLASTOCYST_JUMP_SPEED = 3; + +// The landings' ripple, thuds and shots: eight from the big jump, ten lobbed from the stomp, a ring from the +// medium one's and four from the small one's, with a poof. +constexpr float BLASTOCYST_RIPPLE_AMPLITUDE = 0.04f; +constexpr float BLASTOCYST_RIPPLE_SPEED = 0.025f; +constexpr int BLASTOCYST_RIPPLE_FRAMES = 13; +constexpr float BLASTOCYST_LAND_VOLUME = 1.2f; +constexpr float BLASTOCYST_HOP_VOLUME = 0.8f; +constexpr float BLASTOCYST_SMALL_HOP_VOLUME = 0.6f; +constexpr float BLASTOCYST_JUMP_SHOT_SPEED = 12; +constexpr int BLASTOCYST_STOMP_SHOTS = 10; +constexpr float BLASTOCYST_STOMP_TRAJECTORY = 2; +constexpr float BLASTOCYST_STOMP_SPEEDUP = 1.2f; +constexpr float BLASTOCYST_STOMP_RISE = -2; +constexpr float BLASTOCYST_SHOT_SPEED = 10; +constexpr float BLASTOCYST_RING_SHOTS = 6; +constexpr float BLASTOCYST_RING_TURN = 0.5235988f; +constexpr float BLASTOCYST_SHOT_SCALE = 1.5f; +constexpr float BLASTOCYST_SHOT_FALL = -0.04f; +constexpr float BLASTOCYST_POOF_SCALE = 0.75f; +constexpr int BLASTOCYST_POOF_SUBTYPE = 3; + +// The splits: two of the next size thrown apart (Delirium's own have fixed health), the small one's Embryo, and the +// blood each leaves. +constexpr float BLASTOCYST_SPLIT_THROW = 12; +constexpr float BLASTOCYST_BIG_SPLIT_SPREAD = 20; +constexpr float BLASTOCYST_MEDIUM_SPLIT_SPREAD = 12; +constexpr float BLASTOCYST_DELIRIUM_MEDIUM_HEALTH = 30; +constexpr float BLASTOCYST_DELIRIUM_SMALL_HEALTH = 20; +constexpr float BLASTOCYST_DELIRIUM_EMBRYO_HEALTH = 5; +constexpr float BLASTOCYST_BIG_POOF = 1; +constexpr float BLASTOCYST_MEDIUM_POOF = 0.75f; +constexpr int BLASTOCYST_BLOOD_SUBTYPE = 3; +constexpr float BLASTOCYST_BLOOD_RISE = -10; +constexpr float BLASTOCYST_BLOOD_FRAME = 5; + +// What a split leaves: the size it splits into, how far apart they land, and their health as a Delirium form's. +struct BlastocystSplit +{ + float health = 0; + float spread = 0; + int type = 0; +}; + +// Pushes it along its hop while in the air. +static void blastocyst_airborne_push(Entity_NPC& npc) +{ + if (npc.sprite.WasEventTriggered("Jump") && !npc.sprite.WasEventTriggered("Land")) npc_push(npc, npc.v1); +} + +// Spawns one half of a split, thrown along throwDirection. +static void blastocyst_half_spawn(Entity_NPC& npc, const BlastocystSplit& split, Vector spot, Vector velocity) +{ + Entity* half = g_game->Spawn( + {.position = spot, .velocity = velocity, .spawner = &npc, .type = split.type, .seed = npc.dropRNG.Next()}); + half->ClearEntityFlags(FLAG_APPEAR); + if (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) return; + half->health = split.health; + half->maxHitPoints = split.health; +} + +// Splits in two once its split animation ends, unless a Delirium form that may not, and bursts. +static void blastocyst_split(Entity_NPC& npc, const BlastocystSplit& split, float poofScale) +{ + if (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM) || !npc.HasEntityFlags(FLAG_NO_SPLIT)) + { + Vector direction = RandomVector(npc.dropRNG.Next()); + Vector reach = vector_scale(direction, split.spread); + blastocyst_half_spawn(npc, split, vector_sub(npc.pos, reach), vector_scale(direction, -BLASTOCYST_SPLIT_THROW)); + blastocyst_half_spawn(npc, split, vector_add(reach, npc.pos), vector_scale(direction, BLASTOCYST_SPLIT_THROW)); + } + npc.isDead = true; + npc.MakeBloodPoof(npc.pos, COLOR_DEFAULT, poofScale); + npc.BloodExplode(); +} + +// A killed one lives on, untouchable, to play its split. +static void blastocyst_split_start(Entity_NPC& npc) +{ + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.isDead = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.state = BLASTOCYST_SPLIT; + npc.stateFrame = 1; + npc.isInvincible = true; +} + +// The big one's rest: it stomps near its target, hops or jumps at it. +static void blastocyst_big_idle(Entity_NPC& npc, Vector toTarget) +{ + npc.sprite.Play("Idle"); + npc.stateFrame = 0; + float speed = BLASTOCYST_HOP_SPEED; + npc.state = BLASTOCYST_HOP; + if (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM) || !room_is_clear()) + { + float distanceSquared = vector_length_squared(toTarget); + bool isNear = distanceSquared < BLASTOCYST_NEAR_SQUARED || + (distanceSquared < BLASTOCYST_FAR_SQUARED && Random() % BLASTOCYST_STAY_ODDS != 0); + if (!isNear) + { + speed = BLASTOCYST_JUMP_SPEED; + npc.state = BLASTOCYST_JUMP; + } + else if ((Random() & 1) == 0) + { + speed = BLASTOCYST_STOMP_SPEED; + npc.state = BLASTOCYST_STOMP; + } + } + npc.v1 = vector_scale(vector_normalized(toTarget), speed); +} + +// The drop: it falls onto its spot (from the big jump with eight shots), rippling the floor. +static void blastocyst_drop(Entity_NPC& npc) +{ + if (npc.stateFrame == 1) npc_anim_restart(npc.sprite, "JumpDown"); + bool isLanded = npc.sprite.WasEventTriggered("Land"); + if (!isLanded) npc_push(npc, npc.v1); + npc.entityCollisionClass = isLanded ? ENTCOLL_ALL : ENTCOLL_NONE; + if (!npc.sprite.IsEventTriggered("Land")) return; + + shockwave_make(npc.pos, BLASTOCYST_RIPPLE_AMPLITUDE, BLASTOCYST_RIPPLE_SPEED, BLASTOCYST_RIPPLE_FRAMES); + npc.MakeBloodPoof(npc.pos, COLOR_DEFAULT, 1); + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, BLASTOCYST_LAND_VOLUME, 2, false, 1); + if (npc.state != BLASTOCYST_LAND) return; + ProjectileParams params; + params = ProjectileParams(); + npc.FireProjectiles(npc.pos, vector_make(BLASTOCYST_JUMP_SHOT_SPEED, 0), PROJECTILES_EIGHT, params); +} + +// A hop or stomp's first frame: its animation from the start, with a cry. +static void blastocyst_leap_start(Entity_NPC& npc, std::string_view anim, int sound) +{ + if (npc.stateFrame != 1) return; + npc_anim_restart(npc.sprite, anim); + npc.PlaySound(sound, 1, 2, false, 1); +} + +// The big one: it hops, stomps out lobbed shots and jumps across the room, then splits into two medium ones. +static void blastocyst_big_update(Entity_NPC& npc, Vector toTarget) +{ + npc.friction *= BLASTOCYST_SIZED_FRICTION; + if (npc_anim_is_done(npc)) + { + if (npc.state == BLASTOCYST_JUMP) + { + npc.state = BLASTOCYST_LAND; + npc.stateFrame = 1; + } + else if (npc.state == BLASTOCYST_SPLIT) + blastocyst_split(npc, + {BLASTOCYST_DELIRIUM_MEDIUM_HEALTH, BLASTOCYST_BIG_SPLIT_SPREAD, ENTITY_BLASTOCYST_MEDIUM}, + BLASTOCYST_BIG_POOF); + else npc.state = NPC_STATE_IDLE; + } + if (npc.isDead && npc.state != BLASTOCYST_SPLIT) blastocyst_split_start(npc); + + switch (npc.state) + { + case BLASTOCYST_DROP: + case BLASTOCYST_LAND: + return blastocyst_drop(npc); + case NPC_STATE_IDLE: + return blastocyst_big_idle(npc, toTarget); + case BLASTOCYST_HOP: + blastocyst_leap_start(npc, "Walk", SOUND_BLASTOCYST_JUMP); + if (npc.sprite.IsEventTriggered("Land")) + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, BLASTOCYST_HOP_VOLUME, 2, false, 1); + return blastocyst_airborne_push(npc); + case BLASTOCYST_JUMP: + blastocyst_leap_start(npc, "JumpUp", SOUND_BLASTOCYST_JUMP_BIG); + if (!npc.sprite.WasEventTriggered("Jump")) npc.friction *= BLASTOCYST_GROUND_FRICTION; + else npc_push(npc, npc.v1); + if (npc_anim_is_done(npc)) npc.entityCollisionClass = ENTCOLL_NONE; + return; + case BLASTOCYST_STOMP: + blastocyst_leap_start(npc, "Attack", SOUND_BLASTOCYST_JUMP); + if (npc.sprite.IsEventTriggered("Land")) + { + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + npc.MakeBloodPoof(npc.pos, COLOR_DEFAULT, 1); + ProjectileParams params; + params.velocityMulti = BLASTOCYST_STOMP_SPEEDUP; + params.fallingSpeedModifier = BLASTOCYST_STOMP_RISE; + npc.FireBossProjectiles(BLASTOCYST_STOMP_SHOTS, {}, BLASTOCYST_STOMP_TRAJECTORY, params); + } + return blastocyst_airborne_push(npc); + case BLASTOCYST_SPLIT: + if (npc.stateFrame == 1) npc_anim_restart(npc.sprite, "Split"); + return; + } +} + +// The medium one: it hops (at random when its target is far) or stomps out a ring, then splits into two small ones. +static void blastocyst_medium_update(Entity_NPC& npc, Vector toTarget) +{ + npc.friction *= BLASTOCYST_SIZED_FRICTION; + if (npc_anim_is_done(npc)) + { + if (npc.state == BLASTOCYST_SPLIT) + blastocyst_split( + npc, {BLASTOCYST_DELIRIUM_SMALL_HEALTH, BLASTOCYST_MEDIUM_SPLIT_SPREAD, ENTITY_BLASTOCYST_SMALL}, + BLASTOCYST_MEDIUM_POOF); + else npc.state = NPC_STATE_IDLE; + } + if (npc.isDead && npc.state != BLASTOCYST_SPLIT) blastocyst_split_start(npc); + + switch (npc.state) + { + case NPC_STATE_IDLE: + npc.stateFrame = 0; + npc.sprite.Play("Idle"); + if (vector_length(toTarget) >= BLASTOCYST_FAR) + { + npc.v1 = vector_scale(random_direction(), BLASTOCYST_HOP_SPEED); + npc.state = BLASTOCYST_HOP; + return; + } + npc.state = BLASTOCYST_HOP; + if ((!npc.HasEntityFlags(FLAG_DELIRIUM_FORM) || !room_is_clear()) && (Random() & 1) == 0) + { + npc.state = BLASTOCYST_STOMP; + npc.v1 = vector_scale(vector_normalized(toTarget), BLASTOCYST_STOMP_SPEED); + return; + } + npc.v1 = vector_scale(vector_normalized(toTarget), BLASTOCYST_HOP_SPEED); + return; + case BLASTOCYST_HOP: + blastocyst_leap_start(npc, "Walk", SOUND_BLASTOCYST_JUMP_SMALL); + if (npc.sprite.IsEventTriggered("Land")) + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, BLASTOCYST_HOP_VOLUME, 2, false, 1); + return blastocyst_airborne_push(npc); + case BLASTOCYST_STOMP: + blastocyst_leap_start(npc, "Attack", SOUND_BLASTOCYST_JUMP_SMALL); + if (npc.sprite.IsEventTriggered("Land")) + { + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, BLASTOCYST_HOP_VOLUME, 2, false, 1); + npc.MakeBloodPoof(npc.pos, COLOR_DEFAULT, BLASTOCYST_MEDIUM_POOF); + ProjectileParams params; + params.circleAngle = (Random() & 1) ? BLASTOCYST_RING_TURN : 0; + params.scale = BLASTOCYST_SHOT_SCALE; + params.fallingAccelModifier = BLASTOCYST_SHOT_FALL; + npc.FireProjectiles(npc.pos, vector_make(BLASTOCYST_SHOT_SPEED, BLASTOCYST_RING_SHOTS), + PROJECTILES_RING, params); + } + return blastocyst_airborne_push(npc); + case BLASTOCYST_SPLIT: + if (npc.stateFrame == 1) npc_anim_restart(npc.sprite, "Split"); + return; + } +} + +// The small one: it wanders hopping or stomps out four shots with a poof, then dies into an Embryo. +static void blastocyst_small_update(Entity_NPC& npc) +{ + npc.friction *= BLASTOCYST_SIZED_FRICTION; + if (npc_anim_is_done(npc)) + { + if (npc.state == BLASTOCYST_SPLIT) + { + npc.isDead = true; + npc.isVisible = false; + if (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM) || !npc.HasEntityFlags(FLAG_NO_SPLIT)) + { + Entity* embryo = + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EMBRYO, .seed = Random()}); + embryo->ClearEntityFlags(FLAG_APPEAR); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + { + embryo->health = BLASTOCYST_DELIRIUM_EMBRYO_HEALTH; + embryo->maxHitPoints = BLASTOCYST_DELIRIUM_EMBRYO_HEALTH; + } + } + npc.BloodExplode(); + } + else npc.state = NPC_STATE_IDLE; + } + if (npc.isDead && npc.state != BLASTOCYST_SPLIT) + { + Entity* blood = blood_explosion_spawn(BLASTOCYST_BLOOD_SUBTYPE, npc.pos, vector_make(0, BLASTOCYST_BLOOD_RISE), + COLOR_DEFAULT, {}); + blood->Update(); + if (blood->sprite.animState.animData) blood->sprite.animState.SetFrameFloat(BLASTOCYST_BLOOD_FRAME); + blastocyst_split_start(npc); + } + + switch (npc.state) + { + case NPC_STATE_IDLE: + npc.stateFrame = 0; + npc.sprite.Play("Idle"); + if ((Random() & 1) == 0 || (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear())) + { + npc.state = BLASTOCYST_HOP; + npc.pathfinder.movementTarget = {}; + npc.pathfinder.moveDirection = {}; + } + else npc.state = BLASTOCYST_STOMP; + break; + case BLASTOCYST_HOP: + if (npc.stateFrame == 1) + { + npc.sprite.Play("Walk"); + npc.PlaySound(SOUND_BLASTOCYST_JUMP_SMALL, 1, 2, false, 1); + } + if (npc.sprite.IsEventTriggered("Land")) + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, BLASTOCYST_SMALL_HOP_VOLUME, 2, false, 1); + if (npc.sprite.WasEventTriggered("Land")) npc.friction *= BLASTOCYST_GROUND_FRICTION; + break; + case BLASTOCYST_STOMP: + if (npc.stateFrame == 1) + { + npc.PlaySound(SOUND_BLASTOCYST_JUMP_SMALL, 1, 2, false, 1); + npc_anim_restart(npc.sprite, "Attack"); + } + if (npc.sprite.IsEventTriggered("Land")) + { + npc.PlaySound(SOUND_HEARTOUT, 1, 2, false, 1); + Entity* poof = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = BLASTOCYST_POOF_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, + .seed = Random()}); + poof->sprite.scale = vector_make(BLASTOCYST_POOF_SCALE, BLASTOCYST_POOF_SCALE); + poof->sprite.isFlipX = (Random() & 1) == 0; + poof->Update(); + ProjectileParams params; + params.scale = BLASTOCYST_SHOT_SCALE; + params.fallingAccelModifier = BLASTOCYST_SHOT_FALL; + npc.FireProjectiles(npc.pos, vector_make(BLASTOCYST_SHOT_SPEED, 0), PROJECTILES_PLUS, params); + } + npc.velocity = {}; + break; + case BLASTOCYST_SPLIT: + if (npc.stateFrame == 1) npc_anim_restart(npc.sprite, "Death"); + break; + } + if (npc.state != BLASTOCYST_STOMP) npc.pathfinder.MoveRandomly(STATUS_OBEYED); +} + +// 00472c40 NpcAI::ENTITY_BLASTOCYST_BIG: Blastocyst, big, medium and small, hops after its target and stomps out +// shots. Each size splits into two of the next when killed, and the small one dies into an Embryo. In its boss room +// the big one drops in from above. +void boss_blastocyst_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + Room& room = *g_game->room; + if (npc.type != ENTITY_BLASTOCYST_BIG || room.roomType != ROOM_BOSS || room.bossId != BOSS_ID_BLASTOCYST) + return; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.sprite.Play("JumpUp"); + if (npc.sprite.animState.animData) + npc.sprite.animState.AdvancePosition(npc.sprite.animState.animData->length - 1); + npc.stateFrame = 1; + npc.state = BLASTOCYST_DROP; + npc.entityCollisionClass = ENTCOLL_NONE; + return; + } + + npc.friction *= BLASTOCYST_FRICTION; + Vector toTarget = vector_sub(npc.CalcTargetPosition(0), npc.pos); + if (std::abs(npc.velocity.y) < std::abs(npc.velocity.x)) + { + npc.sprite.isFlipX = npc.velocity.x < 0; + npc.sprite.GetLayer(BLASTOCYST_LAYER_BODY)->isFlipX = npc.sprite.isFlipX; + npc.sprite.GetLayer(BLASTOCYST_LAYER_EYES)->isFlipX = npc.sprite.isFlipX; + } + + if (npc.type == ENTITY_BLASTOCYST_BIG) blastocyst_big_update(npc, toTarget); + else if (npc.type == ENTITY_BLASTOCYST_MEDIUM) blastocyst_medium_update(npc, toTarget); + else if (npc.type == ENTITY_BLASTOCYST_SMALL) blastocyst_small_update(npc); + npc.stateFrame++; +} diff --git a/src/boss_cage.cpp b/src/boss_cage.cpp new file mode 100644 index 0000000..9b1e023 --- /dev/null +++ b/src/boss_cage.cpp @@ -0,0 +1,463 @@ +#include "boss_ai.h" +#include "entity_config.h" +#include "entity_familiar.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "grid_entity_trap_door.h" +#include "npc_caves.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include + +// The Cage's subtypes: the green one that leaves creep, and the twins that only roll. +constexpr int CAGE_GREEN = 1; +constexpr int CAGE_TWINS = 2; + +// Its states: the roll, the puke ring, the Vis it vomits, the jump and landing, and the laser. +constexpr int CAGE_ROLL = NPC_STATE_ATTACK; +constexpr int CAGE_PUKE = NPC_STATE_ATTACK2; +constexpr int CAGE_LASER = NPC_STATE_ATTACK3; +constexpr int CAGE_VOMIT = NPC_STATE_SUMMON; +constexpr int CAGE_JUMP = NPC_STATE_JUMP; +constexpr int CAGE_LAND = NPC_STATE_STOMP; + +// The roll's phases (i1): winding up, rolling and taunting. The jump's (i1): rising and in the air. +enum CageRoll +{ + CAGE_ROLL_START, + CAGE_ROLL_LOOP, + CAGE_ROLL_TAUNT +}; + +enum CageLaser +{ + CAGE_LASER_START, + CAGE_LASER_FIRE, + CAGE_LASER_HOLD, + CAGE_LASER_END +}; + +constexpr ColorMod CAGE_SPLAT_COLOR = { + {10 / 255.0f, 80 / 255.0f, 10 / 255.0f, 1}, {0, 0, 0, 0}, {100 / 255.0f, 100 / 255.0f, 80 / 255.0f}}; +constexpr float CAGE_WIDTH = 1.2f; +constexpr float CAGE_HEIGHT = 0.5f; +constexpr float CAGE_TWIN_SPREAD = 24; +constexpr float CAGE_TWIN_SIZE = 0.67f; +constexpr float CAGE_FRICTION = 0.5f; + +// How it picks an attack after 30 frames at rest, one time in 20: one time in 3 a puke ring, or the Vis vomit while +// few enemies besides bosses are about, else a roll (always for the twins) or a jump onto where its target is headed. +constexpr int CAGE_REST = 30; +constexpr uint32_t CAGE_ATTACK_ODDS = 20; +constexpr uint32_t CAGE_PUKE_ODDS = 3; +constexpr int CAGE_VOMIT_ENEMY_LIMIT = 3; +constexpr float CAGE_HALF_TURN = 180; +constexpr float CAGE_FULL_TURN = 360; +constexpr float CAGE_JUMP_LEAD = 10; + +// The jump drifts it 2 percent more of the way each frame, and lands once within reach of its spot. +constexpr float CAGE_JUMP_DRIFT = 0.02f; +constexpr float CAGE_ARRIVED_SQUARED = 2; +constexpr float CAGE_LAND_SEARCH = 80; + +// The landing: tinted red creep around it, a shake, crackwaves out and a ripple. +constexpr int CAGE_CREEPS = 5; +constexpr float CAGE_CREEP_REACH = 75; +constexpr float CAGE_CREEP_SCALE = 2; +constexpr ColorMod CAGE_CREEP_COLOR = {{1, 1, 1, 1}, {3.2f, 3.2f, 2.3f, 1}, {0, 0, 0}}; +constexpr float CAGE_STOMP_VOLUME = 0.8f; +constexpr int CAGE_SHAKE = 10; +constexpr int CAGE_CRACKWAVES_MIN = 4; +constexpr float CAGE_RIPPLE_AMPLITUDE = 0.04f; +constexpr float CAGE_RIPPLE_SPEED = 0.025f; +constexpr int CAGE_RIPPLE_FRAMES = 13; + +// The puke ring: every 3 frames between its events, six lobbed blobs 60 degrees apart (each one time in 4 missing), +// the ring turning 9 degrees a volley. +constexpr int CAGE_PUKE_FRAMES = 3; +constexpr float CAGE_PUKE_STEP = 60; +constexpr float CAGE_PUKE_TURN = 9; +constexpr float CAGE_PUKE_SPEED = 8; +constexpr float CAGE_PUKE_HEIGHT = -30; +constexpr float CAGE_PUKE_RISE = 3; +constexpr float CAGE_PUKE_FALL = -0.05f; +constexpr float CAGE_PUKE_SCALE_MIN = 0.5f; +constexpr ColorMod CAGE_PUKE_COLOR = {{1, 1, 1, 1}, {0.8f, 1, 0.85f, 1}, {0, 0, 0}}; + +// The vomit: a Vis thrown out below it (none while a Delirium form's is about), and two to four splats. +constexpr float CAGE_VIS_DROP = 20; +constexpr float CAGE_VIS_SPEED = 5; +constexpr int CAGE_SPLATS_MIN = 2; +constexpr uint32_t CAGE_SPLATS_RANGE = 3; +constexpr float CAGE_SPLAT_MIN = 0.5f; +constexpr float CAGE_SPLAT_RANGE = 0.5f; +constexpr ColorMod CAGE_VOMIT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.42f, 0.43f, 0.35f}}; + +// The roll: at 25 a frame, bouncing off walls, for 150 frames. Sisters Vis stop one time in 3 when lined up within 20. +constexpr float CAGE_ROLL_SPEED = 25; +constexpr int CAGE_ROLL_FRAMES = 150; +constexpr float CAGE_ROLL_BAND = 20; +constexpr uint32_t CAGE_ROLL_STOP_ODDS = 3; +constexpr float CAGE_ROLL_STOP_FRICTION = 0.6f; + +// The laser, out of its side, top or bottom: a brimstone beam for 30 frames. +constexpr std::array CAGE_LASER_STARTS = {"LaserStartSide", "LaserStartUp", "LaserStartSide", + "LaserStartDown"}; +constexpr std::array CAGE_LASER_LOOPS = {"LaserLoopSide", "LaserLoopUp", "LaserLoopSide", + "LaserLoopDown"}; +constexpr std::array CAGE_LASER_ENDS = {"LaserEndSide", "LaserEndUp", "LaserEndSide", + "LaserEndDown"}; +constexpr int CAGE_LASER_VARIANT = 6; +constexpr int CAGE_LASER_TIMEOUT = 30; +constexpr float CAGE_LASER_SIDE = 35; +constexpr float CAGE_LASER_RISE = -30; +constexpr float CAGE_LASER_QUARTER = 90; +constexpr float CAGE_LASER_DEPTH_UP = -10; +constexpr float CAGE_LASER_DEPTH = 3000; + +constexpr int CAGE_CREEP_FRAMES = 30; + +// Starts an animation with its cry, unless it already shows. +static void cage_anim_start(Entity_NPC& npc, std::string_view anim, int sound) +{ + const AnimationData* data = npc.sprite.animState.animData; + if (data && data->name == anim) return; + npc.sprite.Play(anim); + npc_sound_play(sound, 1, 2, 1); +} + +// The first frame: rests, sized wide, with green blood. The twins spawn their twin beside them. +static void cage_init(Entity_NPC& npc) +{ + npc.stateFrame = 0; + npc.state = NPC_STATE_IDLE; + npc.sizeMulti = vector_make(CAGE_WIDTH, CAGE_HEIGHT); + npc.splatColor = CAGE_SPLAT_COLOR; + if (npc.subtype != CAGE_TWINS) return; + + if (npc.spawnerType != npc.type) + { + g_game->Spawn({.position = vector_make(npc.pos.x + CAGE_TWIN_SPREAD, npc.pos.y + 0), + .velocity = npc.velocity, + .spawner = &npc, + .subType = npc.subtype, + .type = npc.type, + .variant = npc.variant, + .seed = Random()}); + npc.pos.x -= CAGE_TWIN_SPREAD; + npc.pos.y -= 0; + } + npc.size = npc.config->collisionRadius * CAGE_TWIN_SIZE; +} + +// The rest: after a while it pukes, vomits a Vis, rolls or jumps. +static void cage_idle(Entity_NPC& npc) +{ + npc.sprite.Play("Idle"); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + if (npc.stateFrame++ <= CAGE_REST || Random() % CAGE_ATTACK_ODDS != 0) return; + + Room& room = *g_game->room; + if (Random() % CAGE_PUKE_ODDS == 0) + { + int others = room.GetAliveEnemiesCount() - room.GetAliveBossesCount(); + if (others < CAGE_VOMIT_ENEMY_LIMIT && random_below(2) != 0 && npc.subtype != CAGE_GREEN) + { + npc.state = CAGE_VOMIT; + return; + } + npc.state = CAGE_PUKE; + npc.v1.x = random_unit() * CAGE_FULL_TURN - CAGE_HALF_TURN; + float turn = (float)(Random() & 1) + 0; + npc.v1.y = (turn + turn) - 1; + return; + } + + bool isRolling = (Random() & 1) == 0 || npc.subtype == CAGE_TWINS; + if (isRolling && !npc.HasEntityFlags(FLAG_DISTRACTED)) + { + npc.state = CAGE_ROLL; + npc.i1 = CAGE_ROLL_START; + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + } + else if (!npc.HasEntityFlags(FLAG_CONFUSION) && npc.subtype != CAGE_TWINS) + { + npc.state = CAGE_JUMP; + Vector aim = npc.CalcTargetPosition(0); + Vector lead = npc.GetPlayerTarget()->velocity; + npc.targetPosition = vector_make(lead.x * CAGE_JUMP_LEAD + aim.x, lead.y * CAGE_JUMP_LEAD + aim.y); + npc.targetPosition = room.GetClampedPosition(npc.targetPosition, npc.size); + npc.v1.x = 0; + npc.i1 = 0; + } +} + +// The jump: it rises, then hangs in the air drifting onto its spot until it lands there. +static void cage_jump(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + if (npc.i1 == 0) + { + cage_anim_start(npc, "Jumping", SOUND_CAGE_JUMP); + if (npc_anim_is_done(npc)) npc.i1 = 1; + } + else + { + npc.sprite.Play("JumpLoop"); + if (vector_length_squared(vector_sub(npc.targetPosition, npc.pos)) < CAGE_ARRIVED_SQUARED) + npc.state = CAGE_LAND; + } + + if (anim.animData && anim.IsEventTriggered("Jump")) npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + if (npc.i1 == 0 && !(anim.animData && anim.WasEventTriggered("Jump"))) return; + + float share = std::min(npc.v1.x + CAGE_JUMP_DRIFT, 1.0f); + npc.v1.x = share; + npc.pos.y = share * npc.targetPosition.y + (1 - share) * npc.pos.y; + npc.pos.x = (1 - share) * npc.pos.x + share * npc.targetPosition.x; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; +} + +// The landing's burst: tinted creep, thuds and a shake, crackwaves all around and a ripple. +static void cage_land_burst(Entity_NPC& npc) +{ + for (int i = 0; i < CAGE_CREEPS; i++) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float reach = random_unit() * CAGE_CREEP_REACH; + Vector spot = vector_make(std::cos(angle) * reach + npc.pos.x, std::sin(angle) * reach + npc.pos.y); + Entity* creep = g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = seed}); + creep->SetColor(CAGE_CREEP_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + creep->sprite.scale = vector_make(CAGE_CREEP_SCALE, CAGE_CREEP_SCALE); + } + float pitch = champion_pitch_get(npc); + npc_sound_play(SOUND_FAT_WIGGLE, 1, 2, pitch); + npc_sound_play(SOUND_FORESTBOSS_STOMPS, CAGE_STOMP_VOLUME, 2, pitch); + game_shake_screen(CAGE_SHAKE); + + float step = CAGE_FULL_TURN / ((float)((Random() & 1) + CAGE_CRACKWAVES_MIN) + 0); + for (float angle = 0; angle < CAGE_FULL_TURN; angle += step) + { + auto* wave = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACKWAVE, + .seed = Random()})); + wave->parent = &npc; + wave->rotation = angle; + } + npc_sound_play(SOUND_FORESTBOSS_STOMPS, 1, 2, pitch); + shockwave_make(npc.pos, CAGE_RIPPLE_AMPLITUDE, CAGE_RIPPLE_SPEED, CAGE_RIPPLE_FRAMES); +} + +// The landing: out of a wall it moves to a free cell and collides again, and on Landed it bursts. +static void cage_land(Entity_NPC& npc) +{ + npc.sprite.Play("Landing"); + if (npc.entityGridCollisionClass != GRIDCOLL_GROUND) + { + if (room_grid_collision_at(npc.pos) != 0) npc.pos = room_free_tile_position_find(npc.pos, CAGE_LAND_SEARCH); + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + } + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Landed")) cage_land_burst(npc); +} + +// The puke ring: volleys of blobs between its events, turning each time. +static void cage_puke(Entity_NPC& npc) +{ + cage_anim_start(npc, "Puking", SOUND_CAGE_PREP_SHOOT); + if (!npc.sprite.animState.animData) return; + if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_MEGA_PUKE, 1, 2, false, 1); + if (!npc.sprite.WasEventTriggered("Shoot") || npc.sprite.WasEventTriggered("StopShooting") || + !npc.IsFrame(CAGE_PUKE_FRAMES, 0)) + return; + + float start = npc.v1.x; + for (float angle = start; angle < start + CAGE_FULL_TURN; angle += CAGE_PUKE_STEP) + { + if ((Random() & 3) == 0) continue; + float radians = angle * DEGREES_TO_RADIANS; + ProjectileParams params; + params.heightModifier = CAGE_PUKE_HEIGHT; + params.fallingSpeedModifier = CAGE_PUKE_RISE; + params.fallingAccelModifier = CAGE_PUKE_FALL; + float scale = random_unit(); + params.bulletFlags |= PROJECTILE_ANY_HEIGHT_ENTITY_HIT; + params.variant = PROJECTILE_PUKE; + params.color = CAGE_PUKE_COLOR; + params.scale = scale + CAGE_PUKE_SCALE_MIN; + Vector velocity = vector_make(std::cos(radians) * CAGE_PUKE_SPEED, std::sin(radians) * CAGE_PUKE_SPEED); + npc.FireProjectiles(npc.pos, velocity, PROJECTILES_SINGLE, params); + } + npc.v1.x = npc.v1.y * CAGE_PUKE_TURN + start; +} + +// The vomit: a Vis thrown out below it on Shoot, among splats. +static void cage_vomit(Entity_NPC& npc) +{ + cage_anim_start(npc, "Attack1", SOUND_CAGE_RIBS); + if (!npc.sprite.animState.animData || !npc.sprite.IsEventTriggered("Shoot")) return; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && npc.CountRelatedEntities(ENTITY_VIS, 0, nullptr) != 0) return; + + Vector mouth = vector_make(npc.pos.x + 0, npc.pos.y + CAGE_VIS_DROP); + g_game + ->Spawn({.position = mouth, + .velocity = vector_make(0, CAGE_VIS_SPEED), + .spawner = &npc, + .type = ENTITY_VIS, + .seed = Random()}) + ->Update(); + npc.PlaySound(SOUND_SKIN_PULL, 1, 2, false, 1); + + int splats = (int)(Random() % CAGE_SPLATS_RANGE) + CAGE_SPLATS_MIN; + for (int i = 0; i < splats; i++) + { + Entity_Effect* splat = npc.MakeSplat(random_unit() * CAGE_SPLAT_RANGE + CAGE_SPLAT_MIN); + if (i == 0) splat->pos = mouth; + else + { + float share = random_unit(); + splat->pos = vector_make(share * 0 + npc.pos.x, share * CAGE_VIS_DROP + npc.pos.y); + } + splat->SetColor(CAGE_VOMIT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + } +} + +// The roll: it winds up and launches at its target, rolls bouncing off walls, then taunts. Whether it rests now. +static bool cage_roll(Entity_NPC& npc) +{ + if (npc.i1 == CAGE_ROLL_START) + { + cage_anim_start(npc, "RollStart", SOUND_CAGE_ROLL_START); + if (!npc_anim_is_done(npc)) return false; + npc.i1++; + Vector toward = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.velocity = vector_add(vector_scale(toward, CAGE_ROLL_SPEED), npc.velocity); + return true; + } + if (npc.i1 == CAGE_ROLL_LOOP) + { + npc.sprite.Play("RollLoop"); + if (!vector_is_zero(npc.velocity)) + { + npc.velocity = vector_scale(vector_normalized(npc.velocity), CAGE_ROLL_SPEED); + if (npc.isCollidesWithGrid) npc_sound_play(SOUND_CAGE_ROLL_BOUNCE, 1, 2, 1); + } + if (npc.stateFrame++ > CAGE_ROLL_FRAMES || npc.HasEntityFlags(FLAG_DISTRACTED)) npc.i1++; + Entity* target = npc.GetPlayerTarget(); + bool isLinedUp = std::abs(target->pos.x - npc.pos.x) < CAGE_ROLL_BAND || + std::abs(target->pos.y - npc.pos.y) < CAGE_ROLL_BAND; + if (npc.type == ENTITY_SISTERS_VIS && isLinedUp && Random() % CAGE_ROLL_STOP_ODDS == 0) + { + npc.friction *= CAGE_ROLL_STOP_FRICTION; + npc.i1++; + } + return false; + } + + cage_anim_start(npc, "Taunt", SOUND_CAGE_ROLL_STOP); + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_IDLE; + return true; +} + +// The laser out of the side facing its target: it opens up, fires once, holds until the beam ends and closes. +// Whether it rests now. +static bool cage_laser(Entity_NPC& npc) +{ + Direction direction = vector_to_direction(npc.targetPosition); + npc.sprite.isFlipX = direction == DIRECTION_LEFT; + switch (npc.i1) + { + case CAGE_LASER_START: + npc.sprite.Play(CAGE_LASER_STARTS[direction]); + if (npc_anim_is_done(npc)) npc.i1++; + return false; + case CAGE_LASER_FIRE: + { + npc.sprite.Play(CAGE_LASER_LOOPS[direction]); + Vector offset = vector_make(0, CAGE_LASER_RISE); + if (direction == DIRECTION_LEFT) offset.x = -CAGE_LASER_SIDE; + else if (direction == DIRECTION_RIGHT) offset.x = CAGE_LASER_SIDE; + Entity_Laser* laser = Entity_Laser::ShootAngle( + {.position = npc.pos, + .posOffset = offset, + .source = &npc, + .angleDegrees = angle_wrap((float)direction * CAGE_LASER_QUARTER + CAGE_HALF_TURN), + .timeout = CAGE_LASER_TIMEOUT, + .variant = CAGE_LASER_VARIANT}); + laser->renderDepthOffset = direction == DIRECTION_UP ? CAGE_LASER_DEPTH_UP : CAGE_LASER_DEPTH; + laser->Update(); + npc.entityRef = laser; + npc.i1++; + return false; + } + case CAGE_LASER_HOLD: + if (!npc.entityRef) npc.i1 = CAGE_LASER_END; + return false; + case CAGE_LASER_END: + npc.sprite.Play(CAGE_LASER_ENDS[direction]); + if (!npc_anim_is_done(npc)) return false; + npc.state = NPC_STATE_IDLE; + npc.i1 = 0; + return true; + } + return false; +} + +// 004878a0 NpcAI::ENTITY_CAGE: the Cage rests, then rolls at its target, jumps onto it with crackwaves, pukes rings +// of blobs or vomits a Vis. It shrugs off its own lasers and explosions. The green one leaves creep where it rests. +void boss_cage_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return cage_init(npc); + + if (npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + if ((event.damageFlags & DAMAGE_LASER && event.source.spawnerType == ENTITY_CAGE) || + (event.damageFlags & DAMAGE_EXPLOSION && event.source.type == ENTITY_CAGE)) + event.damage = 0; + + bool isRested = false; + switch (npc.state) + { + case NPC_STATE_IDLE: + cage_idle(npc); + break; + case CAGE_JUMP: + cage_jump(npc); + break; + case CAGE_ROLL: + isRested = cage_roll(npc); + break; + case CAGE_LASER: + isRested = cage_laser(npc); + break; + case CAGE_LAND: + case CAGE_PUKE: + case CAGE_VOMIT: + if (npc.state == CAGE_LAND) cage_land(npc); + else if (npc.state == CAGE_PUKE) cage_puke(npc); + else cage_vomit(npc); + isRested = npc_anim_is_done(npc); + if (isRested) npc.state = NPC_STATE_IDLE; + break; + } + if (isRested) npc.stateFrame = 0; + + bool isCreepFrame = (g_game->frameCount + npc.index) % CAGE_CREEP_FRAMES == 0; + if (npc.subtype == CAGE_GREEN && !npc.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused() && + isCreepFrame) + g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_GREEN, + .seed = Random()}); + if (npc.isDead) npc_sound_play(SOUND_CAGE_DEATH, 1, 2, 1); + npc.friction *= CAGE_FRICTION; +} diff --git a/src/boss_chub.cpp b/src/boss_chub.cpp new file mode 100644 index 0000000..20df22e --- /dev/null +++ b/src/boss_chub.cpp @@ -0,0 +1,642 @@ +#include "boss_ai.h" +#include "entity_bomb.h" +#include "grid_entity.h" +#include "npc_caves.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include + +// Chub's kinds, by variant: Chub, C.H.A.D. and the Carrion Queen, and its subtypes' summons. +constexpr int CHUB_CHAD = 1; +constexpr int CHUB_QUEEN = 2; +constexpr int CHUB_SUMMONS_BOILS = 1; +constexpr int CHUB_SUMMONS_SPITTIES = 2; + +// The links of a Chub (i1): the head, the middle body and the tail. +enum ChubLink +{ + CHUB_HEAD, + CHUB_BODY, + CHUB_TAIL +}; + +// A Chub is three links, each a step of 40 diagonally from the last, filled up by a Delirium form. Each body walks +// 15 (the tail 13) points back along its parent's trail, whose points lie 2 apart, 30 at most before trimming to 20. +constexpr int CHUB_LINKS = 3; +constexpr float CHUB_LINK_REACH = 40; +constexpr int CHUB_BODY_TRAIL_POINT = 15; +constexpr int CHUB_TAIL_TRAIL_POINT = 13; +constexpr float CHUB_TRAIL_STEP = 2; +constexpr size_t CHUB_TRAIL_LIMIT = 30; +constexpr size_t CHUB_TRAIL_KEPT = 20; +constexpr float CHUB_TRAIL_PULL = 4; + +// How each link appears: its animation, shadow (the head keeps its own), depth and flags. +struct ChubAppear +{ + std::string_view anim; + float shadowSize = 0; + int renderZOffset = 0; + uint64_t addedFlags = 0; + uint64_t clearedFlags = 0; +}; + +constexpr float CHUB_SHADOW_KEPT = -1; +constexpr std::array CHUB_APPEARS = {{ + {"AppearHead", CHUB_SHADOW_KEPT, 1500, 0, FLAG_NO_DEATH_TRIGGER}, + {"AppearBody01", 0.34f, 500, FLAG_DONT_COUNT_BOSS_HP, 0}, + {"AppearBody02", 0.26f, -500, FLAG_DONT_COUNT_BOSS_HP, 0}, +}}; + +// C.H.A.D. grows with its health and drags slower as it shrinks. +constexpr float CHAD_SCALE_BASE = 0.7f; +constexpr float CHAD_SCALE_HEALTH = 0.35f; +constexpr float CHAD_DRAG_BASE = 1.1f; +constexpr float CHAD_DRAG_HEALTH = 0.14f; + +// How the head wanders and charges: after 50 frames it charges a target lined up within 20 on an axis (leading it +// by up to 16 frames), until it is about to hit a wall. +constexpr float CHUB_WANDER_SPEED = 1.5f; +constexpr int CHUB_CHARGE_WAIT = 50; +constexpr float CHUB_CHARGE_LEAD = 16; +constexpr float CHUB_CHARGE_BAND = 20; +constexpr float CHUB_CHARGE_FRICTION = 0.9f; +constexpr float CHUB_CHARGE_PUSH = 3.7f; +constexpr float CHUB_LOOKAHEAD = 40; +constexpr int CHUB_WALL_PATH = 999; + +// The summon: one time in 100, while fewer than 5 of its spawns are about (the Carrion Queen while at most 4 red +// poops are), the tail poops a summon 5 frames after the head's swallow. The head's swallow lasts 30 frames. +constexpr uint32_t CHUB_SUMMON_ODDS = 100; +constexpr size_t CHUB_SUMMON_LIMIT = 5; +constexpr int CARRION_POOP_LIMIT = 4; +constexpr int CHUB_TAIL_CUE_FRAME = 5; +constexpr int CHUB_SWALLOW_FRAME = 10; +constexpr int CHUB_SWALLOW_END = 30; +constexpr int CHUB_POOP_FRAME = 5; +constexpr size_t CHUB_POOP_TRAIL_POINT = 5; +constexpr int CHUB_DELIRIUM_SUMMON_LIMIT = 3; +constexpr uint32_t CHUB_EXTRA_SUMMON_ODDS = 3; +constexpr float CHUB_SUMMON_VOLUME_SOFT = 0.7f; +constexpr float CHUB_SUMMON_RECOIL = 0.1f; +constexpr int CARRION_RED_POOP = 1; +constexpr int CARRION_HEART_ENEMY_LIMIT = 5; +constexpr float CARRION_HEART_HEALTH = 0.7f; +constexpr float CARRION_HEART_SCALE = 0.5f; + +// The Carrion Queen's rage below 30 percent health: bouncing diagonally, fleeing within 120 while feared. +constexpr float CARRION_RAGE_HEALTH = 0.3f; +constexpr float CARRION_RAGE_PUSH = 2; +constexpr float CARRION_RAGE_RISE = 0.1f; +constexpr float CARRION_FLEE_RANGE = 120; +constexpr float CARRION_FLEE_SCALE = 0.04f; +constexpr float CARRION_FLEE_MAX = 1.8f; +constexpr uint32_t CARRION_VOX_ODDS = 100; +constexpr int CARRION_VOX_DELAY = 100; + +// A swallowed bomb: it explodes inside after 37 frames, or is spat back at the target after 10 (the Matriarch's +// Chub), led by its speed and pulsing 18 frames before it blows. +constexpr int CHUB_BOMB_BURST_FRAME = 37; +constexpr int CHUB_BOMB_SPIT_FRAME = 9; +constexpr float CHUB_SWALLOW_FRICTION = 0.6f; +constexpr float CHUB_BURST_VOLUME = 0.8f; +constexpr int CHUB_BOMB_HELD_FUSE = 24; +constexpr int CHUB_BOMB_SPAT_FUSE = 18; +constexpr float CHUB_SPIT_LEAD = 0.1f; +constexpr float CHUB_SPIT_SPEED = 20; +constexpr float CHUB_SPIT_VOLUME = 1.2f; +constexpr float CHUB_ROCKET_SPEED = 0.1f; + +// The friction each frame: Chub's boil summoner 0.75, its spitty summoner 0.86, others 0.8. +constexpr float CHUB_FRICTION = 0.8f; +constexpr float CHUB_BOILS_FRICTION = 0.75f; +constexpr float CHUB_SPITTIES_FRICTION = 0.86f; +constexpr float CHUB_DEATH_VOLUME = 0.5f; +constexpr int CHUB_SHARED_DAMAGE_COUNTDOWN = 30; + +// The head's walk animations for a state: sideways, down and up. +struct ChubAnims +{ + std::string_view hori; + std::string_view down; + std::string_view up; +}; + +constexpr ChubAnims CHUB_WALK = {"WalkNormalHori", "WalkNormalDown", "WalkNormalUp"}; +constexpr ChubAnims CHUB_CHARGE = {"WalkAttack01Hori", "WalkAttack01Down", "WalkAttackUp"}; +constexpr ChubAnims CHUB_CHUBBY = {"WalkChubbyHori", "WalkChubbyDown", "WalkNormalUp"}; +constexpr ChubAnims CHUB_SWALLOW = {"WalkAttack02Hori", "WalkAttack02Down", "WalkAttackUp"}; +constexpr ChubAnims CHUB_SAD = {"WalkSadHori", "WalkSadDown", "WalkNormalUp"}; +constexpr ChubAnims CHUB_SPIT = {"SpitHori", "SpitDown", "SpitUp"}; + +// 006d0ca0 Entity_NPC::QueryNPCsSpawnerType: the updated entities a type spawned (of one type, unless 0), only the +// active enemies among them when asked. +std::vector npc_query_spawner_type(int spawnerType, int entityType, SpawnerQueryMode mode) +{ + std::vector found; + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity->spawnerType != spawnerType || (entityType != 0 && entity->type != entityType)) continue; + if (mode == SPAWNER_QUERY_ENEMIES && !entity->IsActiveEnemy(DEAD_EXCLUDED)) continue; + found.push_back(entity); + } + return found; +} + +static float chub_health_ratio(Entity_NPC& npc) +{ + return npc.health / npc.maxHitPoints; +} + +// Back to wandering. A healthy Carrion Queen cries out. +static void chub_move_resume(Entity_NPC& npc) +{ + npc.state = NPC_STATE_MOVE; + if (npc.variant == CHUB_QUEEN && chub_health_ratio(npc) >= CARRION_RAGE_HEALTH) + npc.PlaySound(SOUND_CARRION_QUEEN_DIAGONAL_START, 1, 2, false, 1); +} + +// The first frame of a free Chub: it chains the two nearest free Chubs of its kind within reach behind it (a +// Delirium form spawns the missing ones), and each link appears in its part. A linked one just starts walking. +static void chub_init(Entity_NPC& npc) +{ + if (npc.parent || npc.child) + { + npc.state = NPC_STATE_MOVE; + return; + } + + std::vector free; + for (Entity* entity : entity_query(npc.type, npc.variant)) + { + auto* other = static_cast(entity); + if (!other->parent && !other->child && !other->isDead) free.push_back(other); + } + if (free.empty()) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Chub cannot find Chub?! - Should at least find myself."); + std::stable_sort(free.begin(), free.end(), [&](Entity_NPC* a, Entity_NPC* b) { + return vector_length(vector_sub(npc.pos, a->pos)) < vector_length(vector_sub(npc.pos, b->pos)); + }); + + Entity_NPC* last = &npc; + int links = 1; + for (Entity_NPC* other : free) + { + if (other == &npc) continue; + if (vector_length(vector_sub(other->pos, last->pos)) > std::sqrt(2.0f) * CHUB_LINK_REACH + 1) break; + other->parent = last; + last->child = other; + last = other; + if (++links == CHUB_LINKS) break; + } + if (npc.unknownF54 || npc.deliriumBossType == (uint32_t)npc.type) + for (; links < CHUB_LINKS; links++) + { + auto* other = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = npc.subtype, + .type = npc.type, + .variant = npc.variant, + .seed = Random()})); + other->parent = last; + last->child = other; + last = other; + } + + Entity_NPC* link = &npc; + for (int i = 0; i < CHUB_LINKS && link; i++, link = link->ChildNPC()) + { + const ChubAppear& appear = CHUB_APPEARS[i]; + link->i1 = i; + link->sprite.Play(appear.anim); + link->renderZOffset = appear.renderZOffset; + if (appear.shadowSize != CHUB_SHADOW_KEPT) link->shadowSize = appear.shadowSize; + link->flags = (link->flags | appear.addedFlags) & ~appear.clearedFlags; + } +} + +// A dying link cries and takes its neighbours with it. +static void chub_death(Entity_NPC& npc) +{ + npc_sound_play(SOUND_MONSTER_ROAR_2, CHUB_DEATH_VOLUME, 2, champion_pitch_get(npc)); + if (npc.child) npc.child->Kill(EntityRef()); + if (npc.parent) npc.parent->Kill(EntityRef()); +} + +// Only the Carrion Queen's tail is hurt from outside: its other links drop all damage but each other's. +static void carrion_damage_filter(Entity_NPC& npc) +{ + for (DamageEvent& event : npc.damageEvents) + if (event.source.type != npc.type || event.source.variant != npc.variant) + { + npc.pendingDamage -= event.damage; + event.damage = 0; + } +} + +// The links share their health: each is hurt down to the lowest of them. +static void chub_health_share(Entity_NPC& npc) +{ + float lowest = npc.health - npc.pendingDamage; + for (Entity_NPC* link = npc.ChildNPC(); link; link = link->ChildNPC()) + lowest = std::min(lowest, link->health - link->pendingDamage); + for (Entity_NPC* link = &npc; link; link = link->ChildNPC()) + if (lowest < link->health - link->pendingDamage) + link->TakeDamage(link->health - lowest, 0, EntityRef(&npc), CHUB_SHARED_DAMAGE_COUNTDOWN); +} + +// The tail's summon: a poop animation away from its parent, then on frame 5 a summon on the cell of an older trail +// point: Chub's Chargers, Boils or Spitties, C.H.A.D.'s Suckers, the Carrion Queen's red poop or (pink) Hearts. +static void chub_tail_summon(Entity_NPC& npc) +{ + if (++npc.stateFrame == 1) + { + npc.PlaySound(npc.variant == CHUB_QUEEN ? SOUND_CARRION_QUEEN_ROAR : SOUND_MONSTER_ROAR_1, 1, 2, false, + 1); + Vector toParent = npc.parent ? vector_sub(npc.parent->pos, npc.pos) : Vector{}; + std::string_view anim = toParent.y >= 0 ? "PoopUp" : "PoopDown"; + if (std::abs(toParent.x) > std::abs(toParent.y)) + { + anim = "PoopSide"; + npc.sprite.isFlipX = toParent.x > 0; + } + npc_anim_restart(npc.sprite, anim); + return; + } + if (npc.stateFrame != CHUB_POOP_FRAME) return; + + std::deque& trail = npc.vectorDeque1; + Room& room = *g_game->room; + int gridIndex = + room.GetGridIndex(trail.size() <= CHUB_POOP_TRAIL_POINT ? trail.back() : trail[CHUB_POOP_TRAIL_POINT]); + Vector spot = room.GetGridPosition(gridIndex); + if (npc.variant == CHUB_QUEEN) + { + if (npc.subtype == 0) + { + GridEntity* standing = (uint32_t)gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + bool isFree = !standing || standing->type == GRID_DECORATION || standing->type == GRID_SPIDERWEB; + if (isFree && room.roomType != ROOM_DUNGEON) + { + room.SpawnGridEntity(gridIndex, GRID_POOP, CARRION_RED_POOP, npc.dropRNG.Next(), 0); + npc.PlaySound(SOUND_POOP_DROP, 1, 2, false, 1); + } + } + else if (room.GetAliveEnemiesCount() < CARRION_HEART_ENEMY_LIMIT && + (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM) || + npc.CountRelatedEntities(ENTITY_HEART, 0, nullptr) < CHUB_DELIRIUM_SUMMON_LIMIT)) + { + auto* heart = static_cast( + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_HEART, .seed = Random()})); + heart->health *= CARRION_HEART_HEALTH; + heart->SetScale(heart->scale * CARRION_HEART_SCALE); + heart->parent = &npc; + } + return chub_move_resume(npc); + } + + int summon = ENTITY_SUCKER; + if (npc.variant == 0) + summon = npc.subtype == CHUB_SUMMONS_BOILS ? ENTITY_BOIL + : npc.subtype == CHUB_SUMMONS_SPITTIES ? ENTITY_SPITTY + : ENTITY_CHARGER; + npc.state = NPC_STATE_MOVE; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && + npc.CountRelatedEntities(summon, 0, nullptr) >= CHUB_DELIRIUM_SUMMON_LIMIT) + return; + + if (summon == ENTITY_BOIL || Random() % CHUB_EXTRA_SUMMON_ODDS != 0) + npc.PlaySound(SOUND_SUMMONSOUND, CHUB_SUMMON_VOLUME_SOFT, 2, false, 1); + else + { + npc.PlaySound(SOUND_SUMMONSOUND, 1, 2, false, 1); + g_game->Spawn({.position = spot, .spawner = &npc, .type = summon, .seed = Random()}); + } + auto* spawned = + static_cast(g_game->Spawn({.position = spot, .spawner = &npc, .type = summon, .seed = Random()})); + if (summon == ENTITY_BOIL) spawned->SetBossColorIdx(0, 0); + else npc.AddVelocity_divided(vector_scale(vector_sub(spot, npc.pos), -CHUB_SUMMON_RECOIL), false); +} + +// A body follows its parent's trail a fixed number of points back, pulled along it when it fell behind. The +// orphaned one dies. +static void chub_body_update(Entity_NPC& npc) +{ + if (npc.i1 == CHUB_BODY || npc_anim_is_done(npc)) + npc.sprite.Play(npc.i1 == CHUB_TAIL ? "WalkBody02" : "WalkBody01"); + if (!npc.parent) npc.Kill(EntityRef()); + if (npc.parent) + { + std::deque& trail = npc.ParentNPC()->vectorDeque1; + size_t point = npc.i1 == CHUB_TAIL ? CHUB_TAIL_TRAIL_POINT : CHUB_BODY_TRAIL_POINT; + if (!trail.empty() && point < trail.size()) + { + npc.pos = trail[point]; + npc.velocity = {}; + bool isBehind = !npc.vectorDeque1.empty() && + vector_length(vector_sub(npc.pos, npc.vectorDeque1.front())) > CHUB_TRAIL_STEP; + if (isBehind) npc_push(npc, vector_scale(vector_sub(trail[point - 1], trail[point]), CHUB_TRAIL_PULL)); + } + } + if (npc.i1 == CHUB_TAIL && npc.state == NPC_STATE_SUMMON) chub_tail_summon(npc); +} + +// Charges a target lined up on an axis in plain sight, unless distracted. +static void chub_charge_try(Entity_NPC& npc) +{ + Vector aim = npc.CalcTargetPosition(0); + Vector lead = npc.GetPlayerTarget()->velocity; + float share = random_unit(); + Vector toward = vector_make((share * lead.x * CHUB_CHARGE_LEAD + aim.x) - npc.pos.x, + (share * lead.y * CHUB_CHARGE_LEAD + aim.y) - npc.pos.y); + if (std::abs(toward.y) >= CHUB_CHARGE_BAND && std::abs(toward.x) >= CHUB_CHARGE_BAND) return; + if (!room_check_line(npc.pos, vector_add(npc.pos, toward), LINE_MODE_GROUND, 0) || + npc.HasEntityFlags(FLAG_DISTRACTED)) + return; + + npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + npc.v1 = vector_cardinal(toward); + npc.stateFrame = 0; + npc.state = NPC_STATE_ATTACK; + npc.pathfinder.ResetMovementTarget(); +} + +// The red poops in the room, which cap the Carrion Queen's. +static int carrion_poop_count() +{ + Room& room = *g_game->room; + int count = 0; + for (int i = 0; i < room.gridWidth * room.gridHeight && i < ROOM_GRID_CELLS; i++) + { + GridEntity* entity = room.gridEntities[i]; + if (entity && entity->type == GRID_POOP && entity->variant == CARRION_RED_POOP) count++; + } + return count; +} + +// The Carrion Queen's rage: bouncing diagonally, fleeing a near target while feared, thudding off walls. +static void carrion_rage(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_CONFUSION)) + { + for (int i = 0; i < 3; i++) npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return; + } + + Vector diagonal = vector_make(npc.velocity.x > 0 ? 1 : -1, npc.velocity.y < CARRION_RAGE_RISE ? -1 : 1); + npc.AddVelocity_divided(vector_scale(diagonal, CARRION_RAGE_PUSH), false); + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + { + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float push = + std::clamp((CARRION_FLEE_RANGE - vector_length(away)) * CARRION_FLEE_SCALE, 0.0f, CARRION_FLEE_MAX); + npc.AddVelocity_divided(vector_resized(away, push), false); + } + if (npc.isCollidesWithGrid) npc.PlaySound(SOUND_CARRION_QUEEN_BOUNCE, 1, 2, false, 1); + if (npc.v2.y / npc.maxHitPoints >= CARRION_RAGE_HEALTH) + npc.PlaySound(SOUND_CARRION_QUEEN_DIAGONAL_START, 1, 2, false, 1); + if (Random() % CARRION_VOX_ODDS == 0) + npc.PlaySound(SOUND_CARRION_QUEEN_DIAGONAL_VOX, 1, CARRION_VOX_DELAY, false, 1); +} + +// Wandering: after a while it charges a lined up target, and now and then it swallows to have its tail summon. +static const ChubAnims* chub_move(Entity_NPC& npc) +{ + bool isActive = !npc.HasEntityFlags(FLAG_DELIRIUM_FORM) || !room_is_clear(); + if (npc.variant == CHUB_QUEEN && chub_health_ratio(npc) < CARRION_RAGE_HEALTH && npc.subtype == 0) + { + carrion_rage(npc); + return &CHUB_WALK; + } + + npc.pathfinder.MoveRandomlyAxisAligned(CHUB_WANDER_SPEED, STATUS_OBEYED); + npc.stateFrame++; + if (!isActive) return &CHUB_WALK; + if (npc.stateFrame > CHUB_CHARGE_WAIT) chub_charge_try(npc); + if (npc.state != NPC_STATE_MOVE || Random() % CHUB_SUMMON_ODDS != 0) return &CHUB_WALK; + + if (npc.variant != CHUB_QUEEN && + npc_query_spawner_type(npc.type, 0, SPAWNER_QUERY_ENEMIES).size() >= CHUB_SUMMON_LIMIT) + return &CHUB_WALK; + if (npc.variant == CHUB_QUEEN && carrion_poop_count() > CARRION_POOP_LIMIT) return &CHUB_WALK; + npc.stateFrame = 0; + npc.state = NPC_STATE_SUMMON; + npc.pathfinder.ResetMovementTarget(); + return &CHUB_WALK; +} + +// The charge along its axis, until the cell ahead is a wall or it hits one. +static const ChubAnims* chub_charge(Entity_NPC& npc, const Vector& ahead) +{ + npc.stateFrame++; + if (!npc.isCollidesWithGrid) + { + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(ahead); + bool isWall = (uint32_t)gridIndex < ROOM_GRID_CELLS && room.gridPaths[gridIndex] == CHUB_WALL_PATH; + if (!isWall && !npc.HasEntityFlags(FLAG_DISTRACTED)) + { + npc.friction *= CHUB_CHARGE_FRICTION; + npc.AddVelocity_divided(vector_scale(npc.v1, CHUB_CHARGE_PUSH), false); + return &CHUB_CHARGE; + } + } + chub_move_resume(npc); + npc.v1 = {}; + return &CHUB_CHARGE; +} + +// Holds a swallowed bomb in its mouth, or lets it go nowhere. +static void chub_bomb_hold(Entity_NPC& npc) +{ + if (!npc.entityRef) return; + npc.entityRef->velocity = {}; + npc.entityRef->pos = npc.pos; +} + +// The spit: the swallowed bomb flies at where the target will be, pulsing (a rocket turned that way). +static void chub_spit(Entity_NPC& npc) +{ + chub_bomb_hold(npc); + if (npc.entityRef && npc.entityRef->type == ENTITY_BOMB) + static_cast(npc.entityRef.get())->SetExplosionCountdown(CHUB_BOMB_HELD_FUSE); + + if (npc.sprite.IsEventTriggered("Shoot")) + { + Entity* target = npc.GetPlayerTarget(); + Vector lead = vector_scale(target->velocity, CHUB_SPIT_LEAD); + float distance = vector_length(vector_sub(npc.pos, target->pos)); + Vector aim = vector_make(target->pos.x + distance * lead.x, target->pos.y + distance * lead.y); + Vector shot = vector_scale(vector_normalized(vector_sub(aim, npc.pos)), CHUB_SPIT_SPEED); + npc.PlaySound(SOUND_LITTLE_SPIT, CHUB_SPIT_VOLUME, 2, false, 1); + if (npc.entityRef) + { + npc.entityRef->velocity = shot; + npc.entityRef->pos = vector_add(npc.pos, shot); + if (npc.entityRef->type == ENTITY_BOMB) + { + auto* bomb = static_cast(npc.entityRef.get()); + bomb->sprite.Play("Pulse", PLAY_FORCED); + bomb->SetExplosionCountdown(CHUB_BOMB_SPAT_FUSE); + if (bomb->IsRocket()) + { + bomb->velocity = vector_scale(shot, CHUB_ROCKET_SPEED); + bomb->rocketAngle = std::atan2(shot.y, shot.x) * RADIANS_TO_DEGREES; + } + bomb->entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + bomb->isVisible = true; + bomb->parent = &npc; + } + npc.SetRef_bec(nullptr); + } + } + if (!npc_anim_is_done(npc)) return; + chub_move_resume(npc); + npc.v1 = {}; + npc.v2.x = 0; + npc.i2 = 0; +} + +// The swallow: the head gorges while its tail is told to summon, then swallows the summon down. +static const ChubAnims* chub_swallow(Entity_NPC& npc) +{ + if (++npc.stateFrame == CHUB_TAIL_CUE_FRAME && npc.child && npc.ChildNPC()->child) + { + Entity_NPC* tail = npc.ChildNPC()->ChildNPC(); + tail->state = NPC_STATE_SUMMON; + tail->stateFrame = 0; + } + if (npc.stateFrame <= CHUB_SWALLOW_FRAME) return &CHUB_CHUBBY; + if (npc.stateFrame > CHUB_SWALLOW_END) chub_move_resume(npc); + return &CHUB_SWALLOW; +} + +// A swallowed bomb: Chub sulks frozen, then the bomb blows inside it, or the Matriarch's Chub spits it out. +static const ChubAnims* chub_sulk(Entity_NPC& npc, bool isSpitter) +{ + if (npc.stateFrame == 1) npc.PlaySound(SOUND_SMB_LARGE_CHEWS_4, 1, 2, false, 1); + npc.stateFrame++; + npc.friction *= CHUB_SWALLOW_FRICTION; + if (npc.entityRef) + { + chub_bomb_hold(npc); + if (npc.stateFrame < CHUB_BOMB_BURST_FRAME) + { + if (!isSpitter || npc.stateFrame <= CHUB_BOMB_SPIT_FRAME) return &CHUB_SAD; + npc.state = NPC_STATE_ATTACK5; + return &CHUB_SPIT; + } + if (npc.entityRef->type == ENTITY_BOMB) + { + static_cast(npc.entityRef.get())->SetExplosionCountdown(0); + npc.entityRef->Update(); + npc.entityRef->isVisible = true; + } + } + npc.PlaySound(SOUND_MONSTER_ROAR_2, CHUB_BURST_VOLUME, 2, false, 1); + npc.state = NPC_STATE_MOVE; + npc.v1 = {}; + if (npc.variant == CHUB_QUEEN && chub_health_ratio(npc) >= CARRION_RAGE_HEALTH) + npc.PlaySound(SOUND_CARRION_QUEEN_DIAGONAL_START, 1, 2, false, 1); + return &CHUB_SAD; +} + +// Plays the head's walk the way it moves (frozen on its first frame while sulking, with its body). +static void chub_anims_play(Entity_NPC& npc, const ChubAnims& anims) +{ + std::string_view anim = anims.up; + if (std::abs(npc.velocity.x) > std::abs(npc.velocity.y)) + { + npc.sprite.isFlipX = npc.velocity.x < 0; + anim = anims.hori; + } + else if (npc.velocity.y > 0) anim = anims.down; + + if (npc.state != NPC_STATE_SPECIAL) return npc.sprite.Play(anim); + npc.sprite.SetFrame(anim, 0); + if (!npc.child) return; + npc.ChildNPC()->state = NPC_STATE_SPECIAL; + if (npc.ChildNPC()->child) npc.ChildNPC()->ChildNPC()->state = NPC_STATE_SPECIAL; +} + +// The head: it shares the links' health, hurts what it walks into, and wanders, charges, summons and swallows +// bombs. It dies once it has no body. +static void chub_head_update(Entity_NPC& npc, bool isSpitter) +{ + chub_health_share(npc); + Vector ahead = vector_add(npc.pos, vector_scale(vector_normalized(npc.velocity), CHUB_LOOKAHEAD)); + Room& room = *g_game->room; + EntityRef self(&npc); + int aheadIndex = room.GetGridIndex(ahead); + if ((uint32_t)aheadIndex < ROOM_GRID_CELLS && room.gridEntities[aheadIndex]) + room.gridEntities[aheadIndex]->Hurt(1, self); + + const ChubAnims* anims = &CHUB_WALK; + switch (npc.state) + { + case NPC_STATE_MOVE: + anims = chub_move(npc); + break; + case NPC_STATE_ATTACK: + anims = chub_charge(npc, ahead); + break; + case NPC_STATE_ATTACK5: + chub_spit(npc); + anims = nullptr; + break; + case NPC_STATE_SUMMON: + anims = chub_swallow(npc); + break; + case NPC_STATE_SPECIAL: + anims = chub_sulk(npc, isSpitter); + break; + } + if (anims) chub_anims_play(npc, *anims); + if (!npc.child) npc.Kill(EntityRef()); +} + +// Each link lays its trail: points 2 apart from its last one up to where it stands, the newest first. +static void chub_trail_update(Entity_NPC& npc) +{ + std::deque& trail = npc.vectorDeque1; + if (trail.empty()) trail.push_back(npc.pos); + + Vector delta = vector_sub(npc.pos, trail.front()); + float distance = vector_length(delta); + Vector step = vector_scale(vector_normalized(delta), CHUB_TRAIL_STEP); + for (; distance > CHUB_TRAIL_STEP; distance -= CHUB_TRAIL_STEP) trail.push_front(vector_add(trail.front(), step)); + if (trail.size() > CHUB_TRAIL_LIMIT) trail.resize(CHUB_TRAIL_KEPT); + + float friction = CHUB_FRICTION; + if (npc.variant == 0 && npc.subtype == CHUB_SUMMONS_BOILS) friction = CHUB_BOILS_FRICTION; + else if (npc.variant == 0 && npc.subtype == CHUB_SUMMONS_SPITTIES) friction = CHUB_SPITTIES_FRICTION; + npc.friction *= friction; +} + +// 0047a360 NpcAI::ENTITY_CHUB: Chub, C.H.A.D. and the Carrion Queen, a head dragging two bodies along its trail. The +// head wanders, charges lined up targets and swallows bombs, and its tail poops out summons. C.H.A.D. shrinks as it +// is hurt and the Carrion Queen rages when low. +void boss_chub_update(Entity_NPC& npc) +{ + bool isSpitter = npc.type == ENTITY_CHUB && npc.variant == 0 && npc.spawnerType == ENTITY_MATRIARCH; + if (npc.variant == CHUB_CHAD) + { + float health = std::max(chub_health_ratio(npc), 0.0f); + 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); + } + if (npc.isDead) chub_death(npc); + + if (npc.state == NPC_STATE_INIT) chub_init(npc); + else + { + if (npc.variant == CHUB_QUEEN && npc.i1 != CHUB_TAIL && npc.pendingDamage > 0) + carrion_damage_filter(npc); + if (npc.i1 != CHUB_HEAD) chub_body_update(npc); + else chub_head_update(npc, isSpitter); + chub_trail_update(npc); + } + npc.v2.y = npc.health; +} diff --git a/src/boss_death.cpp b/src/boss_death.cpp index d0ad4d8..db45bdf 100644 --- a/src/boss_death.cpp +++ b/src/boss_death.cpp @@ -748,7 +748,7 @@ void npc_blood_guide_update(Entity_NPC& npc, const NullFrame& bloodGuide) large->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); } } - if (npc.type == ENTITY_MOMS_HEART) reconstruction_missing("Entity_NPC::Update 006c4b30: Mom's Heart's death shots"); + if (npc.type == ENTITY_MOMS_HEART) boss_moms_heart_death_shots(npc); if (npc.type == ENTITY_POLYCEPHALUS && npc.variant == VARIANT_THE_PILE) reconstruction_missing("Entity_NPC::Update 006c4b30: The Pile's chunks"); npc.shadowSize = 0; diff --git a/src/boss_gemini.cpp b/src/boss_gemini.cpp index eb7b6de..1ffdc5c 100644 --- a/src/boss_gemini.cpp +++ b/src/boss_gemini.cpp @@ -98,7 +98,6 @@ constexpr float STEVEN_DEATH_FALL = -0.08f; constexpr float WALLACE_DEATH_FALL = -0.06f; constexpr float STEVEN_DEATH_SCALE = 2; -constexpr int SOUND_MONSTER_YELL_B = 122; constexpr int SOUND_STEVEN_DEATH_BIG = 961; constexpr int SOUND_STEVEN_DEATH_SMALL = 962; constexpr int SOUND_STEVEN_RAGE = 963; diff --git a/src/boss_mama_gurdy.cpp b/src/boss_mama_gurdy.cpp new file mode 100644 index 0000000..c79bab1 --- /dev/null +++ b/src/boss_mama_gurdy.cpp @@ -0,0 +1,426 @@ +#include "boss_ai.h" +#include "entity_projectile.h" +#include "hud.h" +#include "npc_caves.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include + +// Mama Gurdy's parts, by variant: the body in the top wall and its two hands. +constexpr int MAMA_GURDY_LEFT_HAND = 1; +constexpr int MAMA_GURDY_RIGHT_HAND = 2; + +// Its states: the shots, the spikes, the puke (or the rise when it only roars) and the brains it summons. +constexpr int MAMA_GURDY_SHOOT = NPC_STATE_ATTACK; +constexpr int MAMA_GURDY_SPIKES = NPC_STATE_ATTACK2; +constexpr int MAMA_GURDY_PUKE = NPC_STATE_ATTACK3; +constexpr int MAMA_GURDY_SUMMON = NPC_STATE_SUMMON; + +// The puke's phases (i1): the plain puke, the rise with spikes, the wait up high, and the puke coming back down. +enum MamaGurdyPuke +{ + MAMA_GURDY_PUKE_PLAIN, + MAMA_GURDY_PUKE_RISE, + MAMA_GURDY_PUKE_WAIT, + MAMA_GURDY_PUKE_FALL +}; + +// How the body sits: shifted up into the wall, wide and drawn far behind, its hands out at the sides. +constexpr float MAMA_GURDY_SPRITE_DROP = 26; +constexpr float MAMA_GURDY_WIDTH = 2.2f; +constexpr float MAMA_GURDY_LIFT = 40; +constexpr int MAMA_GURDY_DEPTH = -8000; +constexpr float MAMA_GURDY_HAND_Y = 175; +constexpr float MAMA_GURDY_LEFT_HAND_SHARE = 0.5f; +constexpr float MAMA_GURDY_RIGHT_HAND_SHARE = 1.5f; +constexpr float MAMA_GURDY_BODY_Y = 155; +constexpr float MAMA_GURDY_HAND_DROP = 8; + +// It rests 30 to 54 frames, but only at full health: the original truncates its health share. +constexpr float MAMA_GURDY_REST_SHARE = 0.5f; +constexpr int MAMA_GURDY_REST_MIN = 30; +constexpr uint32_t MAMA_GURDY_REST_RANGE = 25; +constexpr uint32_t MAMA_GURDY_ATTACKS = 3; + +// The shots: one to seven volleys of five aimed shots (three times in ten a big lob instead) from frame 31. +constexpr uint32_t MAMA_GURDY_SINGLE_ODDS = 30; +constexpr int MAMA_GURDY_AIM_FRAME = 31; +constexpr int MAMA_GURDY_BARF_DELAY = 20; +constexpr float MAMA_GURDY_MOUTH_DROP = 40; +constexpr float MAMA_GURDY_LOB_SPEEDUP = 1.8f; +constexpr float MAMA_GURDY_LOB_REACH = 0.7f; +constexpr int MAMA_GURDY_LOB_SHOTS = 12; +constexpr float MAMA_GURDY_LOB_TRAJECTORY = 10; +constexpr float MAMA_GURDY_SPREAD_SPEED = 8.5f; + +// The spikes: twenty spikes on free spots across the room below its wall. +constexpr int MAMA_GURDY_SPIKES_FRAME = 20; +constexpr int MAMA_GURDY_SPIKE_COUNT = 20; +constexpr float MAMA_GURDY_SPIKES_TOP = 40; +constexpr int MAMA_GURDY_GROWL_DELAY = 60; + +// The puke: two times in ten it rises 280 over 45 frames with spikes on frame 35, waits up to a second, then falls +// back with a shake on frame 34, retching debris every other frame from 42 to 65. +constexpr uint32_t MAMA_GURDY_RISE_ODDS = 20; +constexpr float MAMA_GURDY_RISE = 280; +constexpr float MAMA_GURDY_RISE_FRAMES = 45; +constexpr int MAMA_GURDY_RISE_SPIKES_FRAME = 35; +constexpr int MAMA_GURDY_RISE_END = 44; +constexpr uint32_t MAMA_GURDY_WAIT_RANGE = 60; +constexpr int MAMA_GURDY_FALL_FRAME = 34; +constexpr float MAMA_GURDY_FALL_FRAMES = 10; +constexpr int MAMA_GURDY_SHAKE = 8; +constexpr int MAMA_GURDY_RETCH_FIRST = 42; +constexpr int MAMA_GURDY_RETCH_END = 66; +constexpr int MAMA_GURDY_DEBRIS = 3; +constexpr float MAMA_GURDY_DEBRIS_SCATTER = 6.5f; +constexpr float MAMA_GURDY_DEBRIS_THROW = 9; +constexpr float MAMA_GURDY_DEBRIS_REACH = 30; +constexpr float MAMA_GURDY_DEBRIS_RISE = 10; +constexpr float MAMA_GURDY_DEBRIS_SCALE = 2; +constexpr float MAMA_GURDY_DEBRIS_HEIGHT = 20; +constexpr float MAMA_GURDY_DEBRIS_FALL = 7; +constexpr ColorMod MAMA_GURDY_DEBRIS_COLOR = { + {0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0.6509804f, 0.40784317f, 0.16078432f}}; + +// The brains it summons, and the hands' smash. +constexpr int MAMA_GURDY_SUMMON_FRAME = 25; +constexpr float MAMA_GURDY_BRAIN_Y = 240; +constexpr float MAMA_GURDY_LEFT_BRAIN_X = 220; +constexpr float MAMA_GURDY_RIGHT_BRAIN_X = 420; +constexpr float MAMA_GURDY_SMASH_VOLUME = 0.7f; +constexpr float MAMA_GURDY_SMASH_THRESHOLD = 50; +constexpr float MAMA_GURDY_SMASH_DAMAGE = 45; +constexpr float MAMA_GURDY_SMASH_RADIUS = 150; + +// The body slides along its wall after its target, at most 2 a frame and 60 from the sides. +constexpr float MAMA_GURDY_FRICTION = 0.8f; +constexpr float MAMA_GURDY_WALL_MARGIN = 60; +constexpr float MAMA_GURDY_FOLLOW = 0.05f; +constexpr float MAMA_GURDY_FOLLOW_MAX = 2; + +// The frames each shot volley pattern (i1) fires on. +static bool is_mama_gurdy_volley_frame(int pattern, int frame) +{ + switch (pattern) + { + case 0: + case 1: + return frame == 31; + case 3: + return frame == 31 || frame == 36 || frame == 41; + case 5: + return frame == 31 || frame == 34 || frame == 37 || frame == 40 || frame == 43; + case 7: + return frame >= 31 && frame <= 43 && frame % 2 == 1; + } + return false; +} + +// Twenty spikes across the room below its wall. +static void mama_gurdy_spikes_spawn(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_GRROOWL, 1, MAMA_GURDY_GROWL_DELAY, false, 1); + for (int i = 0; i < MAMA_GURDY_SPIKE_COUNT; i++) + { + Room& room = *g_game->room; + float left = room.topLeftPos.x; + float top = room.topLeftPos.y + MAMA_GURDY_SPIKES_TOP; + float right = room.bottomRightPos.x; + float bottom = room.bottomRightPos.y; + float down = random_unit(); + float across = random_unit(); + Vector spot = vector_make(across * (right - left) + left, (bottom - top) * down + top); + spot = room_free_pickup_position_find({.position = spot}); + g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_SPIKE, .seed = Random()}); + } +} + +// The body's rest: it picks one of its three attacks, never the same twice in a row unless rerolled into it. +static void mama_gurdy_idle(Entity_NPC& npc) +{ + if (!npc.sprite.IsOverlayPlaying("Organs")) npc.sprite.PlayOverlay("Organs"); + if (npc_anim_is_done(npc)) npc.sprite.Play("Idle"); + if (npc.stateFrame-- >= 0) return; + + int attack = (int)(Random() % MAMA_GURDY_ATTACKS); + if (attack == npc.i2) attack = (int)(Random() % MAMA_GURDY_ATTACKS); + npc.i2 = attack; + if (attack == 0) + { + npc.state = MAMA_GURDY_SHOOT; + npc_anim_restart(npc.sprite, "Shoot"); + npc.i1 = (int)(Random() & 3) * 2 + 1; + if (Random() % 100 < MAMA_GURDY_SINGLE_ODDS) npc.i1 = 0; + } + else if (attack == 1) + { + npc.state = MAMA_GURDY_SPIKES; + npc_anim_restart(npc.sprite, "Attack1"); + } + else + { + npc.state = MAMA_GURDY_PUKE; + bool isRising = Random() % 100 < MAMA_GURDY_RISE_ODDS; + npc.i1 = isRising ? MAMA_GURDY_PUKE_RISE : MAMA_GURDY_PUKE_PLAIN; + npc_anim_restart(npc.sprite, isRising ? "Attack1" : "Puke"); + npc.stateFrame = 0; + } +} + +// The shots: aimed at where its target stood on frame 31, on its pattern's frames. +static void mama_gurdy_shoot(Entity_NPC& npc, int rest) +{ + if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = rest; + } + int frame = npc.sprite.GetFrame(); + if (frame == MAMA_GURDY_AIM_FRAME) npc.v2 = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (!is_mama_gurdy_volley_frame(npc.i1, frame)) return; + + npc.PlaySound(SOUND_BOSS_SPIT_BLOB_BARF, 1, MAMA_GURDY_BARF_DELAY, false, 1); + if (npc.i1 != 0) + { + ProjectileParams params; + Vector velocity = vector_scale(vector_normalized(npc.v2), MAMA_GURDY_SPREAD_SPEED); + Vector mouth = vector_make(npc.pos.x - 0, npc.pos.y + MAMA_GURDY_MOUTH_DROP); + npc.FireProjectiles(mouth, velocity, PROJECTILES_FIVE, params); + return; + } + + Vector position = npc.pos; + npc.pos = vector_make(position.x - 0, npc.pos.y + MAMA_GURDY_MOUTH_DROP); + ProjectileParams params; + params.velocityMulti = MAMA_GURDY_LOB_SPEEDUP; + Vector target = npc.GetPlayerTarget()->pos; + Vector aim = vector_make((target.x - npc.pos.x) * MAMA_GURDY_LOB_REACH + npc.pos.x, + (target.y - npc.pos.y) * MAMA_GURDY_LOB_REACH + npc.pos.y); + npc.FireBossProjectiles(MAMA_GURDY_LOB_SHOTS, aim, MAMA_GURDY_LOB_TRAJECTORY, params); + npc.pos = position; +} + +// Three chunks of debris retched from its mouth, thrown down and out. +static void mama_gurdy_debris_spawn(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_GURG_BARF, 1, MAMA_GURDY_GROWL_DELAY, false, 1); + Vector down = vector_normalized(vector_make(0, std::sqrt(2500.0f))); + for (int i = 0; i < MAMA_GURDY_DEBRIS; i++) + { + Vector scatter = random_direction(); + float share = random_unit(); + Vector velocity = vector_make(scatter.x * share * MAMA_GURDY_DEBRIS_SCATTER + down.x * MAMA_GURDY_DEBRIS_THROW, + scatter.y * share * MAMA_GURDY_DEBRIS_SCATTER + down.y * MAMA_GURDY_DEBRIS_THROW); + Vector out = random_direction(); + out.x *= random_unit() + 1; + out = vector_normalized(out); + float reach = random_unit() * MAMA_GURDY_DEBRIS_REACH + 1; + Vector spot = vector_make(((npc.pos.x + 0) - 0) + reach * out.x, + ((npc.pos.y - MAMA_GURDY_DEBRIS_RISE) + MAMA_GURDY_MOUTH_DROP) + out.y * reach); + auto* debris = static_cast(g_game->Spawn( + {.position = spot, .velocity = velocity, .spawner = &npc, .type = ENTITY_PROJECTILE, .seed = Random()})); + debris->SetColor(MAMA_GURDY_DEBRIS_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + debris->scale = MAMA_GURDY_DEBRIS_SCALE; + debris->height -= MAMA_GURDY_DEBRIS_HEIGHT; + debris->projectileFlags |= PROJECTILE_CREEP_BROWN; + debris->fallingSpeed += random_unit() * MAMA_GURDY_DEBRIS_FALL; + } +} + +// The puke: the plain one retches debris. The rising one first lifts it off-screen with spikes, waits, and falls back. +static void mama_gurdy_puke(Entity_NPC& npc, int rest) +{ + float top = npc.v1.y - MAMA_GURDY_RISE; + if (npc.i1 == MAMA_GURDY_PUKE_RISE) + { + if (npc.stateFrame == 0) npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + float share = std::clamp(((float)npc.stateFrame - 0) / MAMA_GURDY_RISE_FRAMES, 0.0f, 1.0f); + npc.targetPosition.y = (top - npc.v1.y) * share + npc.v1.y; + if (npc.stateFrame == MAMA_GURDY_RISE_SPIKES_FRAME) mama_gurdy_spikes_spawn(npc); + if (++npc.stateFrame > MAMA_GURDY_RISE_END) + { + npc.i1 = MAMA_GURDY_PUKE_WAIT; + npc.stateFrame = (int)(Random() % MAMA_GURDY_WAIT_RANGE); + } + } + if (npc.i1 == MAMA_GURDY_PUKE_WAIT && --npc.stateFrame < 1) + { + npc.i1 = MAMA_GURDY_PUKE_FALL; + npc.sprite.Play("Puke"); + } + + AnimationState& anim = npc.sprite.animState; + if (!anim.animData || anim.animData->name != "Puke") return; + if (npc.i1 == MAMA_GURDY_PUKE_FALL) + { + if (npc.sprite.GetFrame() == MAMA_GURDY_FALL_FRAME) + { + game_shake_screen(MAMA_GURDY_SHAKE); + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + } + float share = + std::clamp(((float)npc.sprite.GetFrame() - MAMA_GURDY_FALL_FRAME) / MAMA_GURDY_FALL_FRAMES, 0.0f, 1.0f); + npc.targetPosition.y = (npc.v1.y - top) * share + top; + } + if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = rest; + } + int frame = npc.sprite.GetFrame(); + if (frame >= MAMA_GURDY_RETCH_FIRST && frame < MAMA_GURDY_RETCH_END && (frame & 1) != 0) + mama_gurdy_debris_spawn(npc); +} + +// The summon: two brains on free spots left and right on frame 25. +static void mama_gurdy_summon(Entity_NPC& npc, int rest) +{ + if (npc_anim_is_done(npc)) + { + npc.stateFrame = rest; + npc.state = NPC_STATE_IDLE; + return; + } + if (npc.sprite.GetFrame() != MAMA_GURDY_SUMMON_FRAME) return; + + npc.PlaySound(SOUND_GRROOWL, 1, MAMA_GURDY_GROWL_DELAY, false, 1); + for (float x : {MAMA_GURDY_LEFT_BRAIN_X, MAMA_GURDY_RIGHT_BRAIN_X}) + { + Vector spot = room_free_pickup_position_find( + {.position = vector_make(x, MAMA_GURDY_BRAIN_Y), .isAvoidActiveEntities = true}); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_BRAIN, .seed = Random()}); + } +} + +// The body's first frame: it sinks into the wall with its organs showing and spawns its hidden hands. +static void mama_gurdy_body_init(Entity_NPC& npc) +{ + npc.sprite.offset = vector_make(0, MAMA_GURDY_SPRITE_DROP); + npc.sizeMulti.x = MAMA_GURDY_WIDTH; + npc.pos = vector_make(npc.pos.x + 0, npc.pos.y - MAMA_GURDY_LIFT); + npc.renderZOffset = MAMA_GURDY_DEPTH; + npc.sprite.PlayOverlay("Organs"); + + for (auto [variant, share] : {std::pair{MAMA_GURDY_LEFT_HAND, MAMA_GURDY_LEFT_HAND_SHARE}, + std::pair{MAMA_GURDY_RIGHT_HAND, MAMA_GURDY_RIGHT_HAND_SHARE}}) + { + uint32_t seed = Random(); + Vector spot = vector_make(Room::GetCenterPos().x * share, MAMA_GURDY_HAND_Y); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_MAMA_GURDY, .variant = variant, .seed = seed}) + ->isVisible = false; + } + npc.targetPosition = vector_make(Room::GetCenterPos().x + 0, MAMA_GURDY_BODY_Y); + npc.v1 = npc.targetPosition; +} + +// A hand's first frame: hidden on the top wall, held at its offset from the body. +static void mama_gurdy_hand_init(Entity_NPC& npc, Entity* body) +{ + npc.pos.y = g_game->room->topLeftPos.y + MAMA_GURDY_HAND_DROP; + npc.v1 = npc.pos; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.isVisible = false; + if (body) npc.targetPosition = vector_sub(npc.pos, body->pos); + npc.isCanShutDoors = false; + if (npc.variant == MAMA_GURDY_RIGHT_HAND) npc.sprite.isFlipX = true; +} + +// A hand's smash, hurting all around it. +static void mama_gurdy_smash(Entity_NPC& npc) +{ + if (!npc.sprite.IsEventTriggered("Smash")) + { + if (!npc_anim_is_done(npc)) return; + npc.sprite.Play("Idle"); + npc.state = NPC_STATE_IDLE; + return; + } + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, MAMA_GURDY_SMASH_VOLUME, MAMA_GURDY_BARF_DELAY, false, 1); + damage_radius({.position = npc.pos, + .source = &npc, + .damage = MAMA_GURDY_SMASH_DAMAGE, + .playerDamageThreshold = MAMA_GURDY_SMASH_THRESHOLD, + .radius = MAMA_GURDY_SMASH_RADIUS}); +} + +// The body slides along its wall after its target, and its death lets the room's death triggers run. +static void mama_gurdy_body_move(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.pos.y = npc.targetPosition.y; + npc.friction *= MAMA_GURDY_FRICTION; + npc.velocity.y = 0; + npc.pos.x = std::min(std::max(npc.pos.x, room.topLeftPos.x + MAMA_GURDY_WALL_MARGIN), + room.bottomRightPos.x - MAMA_GURDY_WALL_MARGIN); + float follow = (npc.GetPlayerTarget()->pos.x - npc.pos.x) * MAMA_GURDY_FOLLOW; + npc.velocity.x = std::clamp(follow, -MAMA_GURDY_FOLLOW_MAX, MAMA_GURDY_FOLLOW_MAX); + if (npc.isDead) npc.ClearEntityFlags(FLAG_NO_DEATH_TRIGGER); +} + +// A hand passes its hurt to the body and stays whole, riding along with it. Without a body it goes away. +static void mama_gurdy_hand_follow(Entity_NPC& npc, Entity* body) +{ + if (!body) return npc.Remove(); + for (DamageEvent& event : npc.damageEvents) body->TakeDamage(event.damage, event.damageFlags, event.source, 0); + npc.damageEvents.clear(); + npc.pendingDamage = 0; + npc.pendingDamageFlags = 0; + npc.isDead = false; + npc.health = npc.maxHitPoints; + npc.pos = vector_add(body->pos, npc.targetPosition); + npc.velocity = {}; +} + +// 0048ae30 NpcAI::ENTITY_MAMA_GURDY: Mama Gurdy sits in the top wall sliding after its target, shooting volleys, +// raising spikes across the room, puking debris (rising off-screen first now and then) and summoning brains. Its +// hands pass their damage to it and smash the floor. +void boss_mama_gurdy_update(Entity_NPC& npc) +{ + std::vector bodies = entity_query(ENTITY_MAMA_GURDY, 0); + Entity* body = bodies.empty() ? nullptr : bodies.front(); + float health = npc.health / npc.maxHitPoints; + int rest = (int)(health * MAMA_GURDY_REST_SHARE + MAMA_GURDY_REST_SHARE) * + (int)(Random() % MAMA_GURDY_REST_RANGE + MAMA_GURDY_REST_MIN); + g_game->hud.isBossBarBottom = true; + + bool isBody = npc.variant == 0; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + npc.state = NPC_STATE_IDLE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + npc.stateFrame = rest; + if (isBody) mama_gurdy_body_init(npc); + else mama_gurdy_hand_init(npc, body); + break; + case NPC_STATE_IDLE: + if (isBody) mama_gurdy_idle(npc); + else npc.isVisible = false; + break; + case MAMA_GURDY_SHOOT: + if (isBody) mama_gurdy_shoot(npc, rest); + else mama_gurdy_smash(npc); + break; + case MAMA_GURDY_SPIKES: + if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = rest; + } + if (npc.sprite.GetFrame() == MAMA_GURDY_SPIKES_FRAME) mama_gurdy_spikes_spawn(npc); + break; + case MAMA_GURDY_PUKE: + mama_gurdy_puke(npc, rest); + break; + case MAMA_GURDY_SUMMON: + mama_gurdy_summon(npc, rest); + break; + } + + if (isBody) mama_gurdy_body_move(npc); + else mama_gurdy_hand_follow(npc, body); +} diff --git a/src/boss_mask_of_infamy.cpp b/src/boss_mask_of_infamy.cpp new file mode 100644 index 0000000..09263cc --- /dev/null +++ b/src/boss_mask_of_infamy.cpp @@ -0,0 +1,276 @@ +#include "boss_ai.h" +#include "entity_player.h" +#include "npc_caves.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include + +// The Mask of Infamy's states: drifting about sad, and angry once its heart is gone. Its dash (i1): none, its own +// charge, and the lunge its hurt heart provokes. +constexpr int MASK_ANGRY = NPC_STATE_ATTACK2; +constexpr int MASK_VARIANT_LINKED = 1; + +enum MaskDash +{ + MASK_DASH_NONE, + MASK_DASH_CHARGE, + MASK_DASH_LUNGE +}; + +constexpr std::array MASK_SAD_ANIMS = {"SadMaskLeft", "SadMaskUp", "SadMaskRight", "SadMaskDown"}; +constexpr std::array MASK_ANGRY_ANIMS = {"AngryMaskLeft", "AngryMaskUp", "AngryMaskRight", + "AngryMaskDown"}; +constexpr std::array MASK_PLAIN_ANIMS = {"Left", "Up", "Right", "Down"}; + +// Its heart spawns on a free spot within 40, with 50 health for a Delirium form. +constexpr float MASK_HEART_SEARCH = 40; +constexpr int MASK_HEART_PATH = 900; +constexpr int MASK_HEART_PATH_LIMIT = 950; +constexpr float MASK_DELIRIUM_HEART_HEALTH = 50; + +// It faces where it has been going lately, the last 35 percent of its recent motion. +constexpr float MASK_FACING_DECAY = 0.35f; + +// The charge: every 4 frames, at a target lined up within 20 on an axis and within 200 (leading it by up to 16 +// frames), along a line its corners clear of walls (each step over something slowing it costs 0.3). +constexpr int MASK_CHARGE_FRAMES = 4; +constexpr float MASK_TARGET_LEAD = 16; +constexpr float MASK_CHARGE_BAND = 20; +constexpr float MASK_CHARGE_REACH = 200; +constexpr float MASK_TRACE_STEP = 10; +constexpr float MASK_TRACE_CORNER = 5; +constexpr int MASK_TRACE_IGNORED_PATH = 990; +constexpr int MASK_TRACE_WALL_PATH = 1000; +constexpr float MASK_TRACE_ROUGH = 0.3f; +constexpr float MASK_CHARGE_PUSH = 2; +constexpr float MASK_LUNGE_PUSH = 1.6f; + +// The dash: pushed along its axis, kept to its row or column, until it hits a wall. +constexpr float MASK_DASH_FRICTION = 0.82f; +constexpr float MASK_FACING_PUSH = 3; +constexpr float MASK_LANE_PULL = 0.1f; +constexpr float MASK_LANE_KEEP = 0.9f; + +// Wandering along the axes, faster once angry, with its own drag on each axis. +constexpr float MASK_WANDER_SPEED = 0.85f; +constexpr float MASK_ANGRY_WANDER_SPEED = 1.5f; +constexpr float MASK_DRAG_X = 0.85f; +constexpr float MASK_DRAG_Y = 0.78f; + +// The middle of the room cell a position lies in, clamped to the grid. +static Vector mask_cell_center(Vector position) +{ + Room& room = *g_game->room; + int column = std::min(std::max((int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f), 0), room.gridWidth - 1); + int row = std::min(std::max((int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f), 0), room.gridHeight - 1); + return room.GetGridPosition(row * room.gridWidth + column); +} + +// A unit step along the axis it lies nearer, pointing back against delta. +static Vector mask_axis_away(Vector delta) +{ + if (std::abs(delta.x) <= std::abs(delta.y)) return vector_make(0, delta.y >= 0 ? -1.0f : 1.0f); + return vector_make(delta.x >= 0 ? -1.0f : 1.0f, 0); +} + +// From the cell's middle to where the target will be, led by a random share of 16 frames of its motion. +static Vector mask_target_delta(Entity_NPC& npc, Vector cell) +{ + Vector target = npc.GetPlayerTarget()->pos; + Vector lead = npc.GetPlayerTarget()->velocity; + float share = random_unit() * MASK_TARGET_LEAD; + return vector_make(cell.x - (share * lead.x + target.x), cell.y - (share * lead.y + target.y)); +} + +// The first frame: it takes a free Heart of Infamy as its own or spawns one, and drifts untouchable. +static void mask_init(Entity_NPC& npc) +{ + Entity* heart = nullptr; + if (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + for (Entity* other : entity_query(ENTITY_HEART_OF_INFAMY, -1)) + if (!other->child) + { + heart = other; + break; + } + if (heart) + { + heart->child = &npc; + npc.parent = heart; + } + else + { + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = MASK_HEART_SEARCH}); + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(spot); + if (gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS && room.gridPaths[gridIndex] <= MASK_HEART_PATH_LIMIT) + room.gridPaths[gridIndex] = MASK_HEART_PATH; + heart = g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_HEART_OF_INFAMY, .seed = Random()}); + heart->child = &npc; + npc.parent = heart; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + { + heart->health = MASK_DELIRIUM_HEART_HEALTH; + heart->maxHitPoints = MASK_DELIRIUM_HEART_HEALTH; + } + } + npc.v2.x = heart->health; + npc.i1 = MASK_DASH_NONE; + npc.pathfinder.movementTarget = {}; + npc.pathfinder.moveDirection = {}; + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.state = NPC_STATE_MOVE; + npc.isInvincible = true; + npc.v1 = npc.velocity; +} + +// Without its heart the Mask of Infamy turns angry and vulnerable, and a plain Mask dies. A linked Mask first takes +// its partner as its heart. +static void mask_heart_check(Entity_NPC& npc) +{ + if (npc.variant == MASK_VARIANT_LINKED) + { + if (npc.entityRef && npc.parent) return; + if (npc.entityRef) + { + npc.parent = npc.entityRef.get(); + npc.entityRef->child = &npc; + npc.entityRef = nullptr; + } + npc.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.state = MASK_ANGRY; + } + if (npc.parent) return; + if (npc.type != ENTITY_MASK_OF_INFAMY) return npc.Kill(EntityRef()); + if (npc.isInvincible) + { + npc.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.isInvincible = false; + npc_sound_play(SOUND_MASKINFAMY_MAD, 1, 2, 1); + } + npc.state = MASK_ANGRY; +} + +// Each time its heart is hurt it may lunge away from the target, one time in 2. +static void mask_lunge_check(Entity_NPC& npc) +{ + if (npc.type != ENTITY_MASK_OF_INFAMY || npc.state == MASK_ANGRY || !npc.parent) return; + if (npc.v2.x == npc.parent->health) return; + + npc.v2.x = npc.parent->health; + if ((Random() & 1) != 0) return; + Vector delta = mask_target_delta(npc, mask_cell_center(npc.pos)); + npc.targetPosition = vector_scale(mask_axis_away(delta), MASK_LUNGE_PUSH); + npc.i1 = MASK_DASH_LUNGE; +} + +// Shows its face toward where it is heading, frozen on the first frame. +static void mask_face(Entity_NPC& npc) +{ + const std::array* anims = &MASK_PLAIN_ANIMS; + if (npc.type == ENTITY_MASK_OF_INFAMY) anims = npc.state == MASK_ANGRY ? &MASK_ANGRY_ANIMS : &MASK_SAD_ANIMS; + else if (npc.variant == MASK_VARIANT_LINKED && npc.state == MASK_ANGRY) anims = &MASK_ANGRY_ANIMS; + + int direction = npc.v1.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + if (std::abs(npc.v1.x) <= std::abs(npc.v1.y)) direction = npc.v1.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP; + if (npc.sprite.SetAnimation((*anims)[direction], SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + if (npc.sprite.animState.animData) npc.sprite.animState.isPlaying = false; + } + npc.v1.x = (npc.v1.x + npc.velocity.x) * MASK_FACING_DECAY; + npc.v1.y = (npc.velocity.y + npc.v1.y) * MASK_FACING_DECAY; +} + +// Whether the line from the cell's middle back along delta is clear: each step checks the four corners around it, +// walls ruling it out and slowing cells wearing it down. +static bool is_mask_line_clear(Vector cell, Vector delta, float distance) +{ + Room& room = *g_game->room; + constexpr std::array, 4> CORNERS = {{{-MASK_TRACE_CORNER, -MASK_TRACE_CORNER}, + {-MASK_TRACE_CORNER, MASK_TRACE_CORNER}, + {MASK_TRACE_CORNER, MASK_TRACE_CORNER}, + {MASK_TRACE_CORNER, -MASK_TRACE_CORNER}}}; + Vector step = vector_make(delta.x / distance * MASK_TRACE_STEP, delta.y / distance * MASK_TRACE_STEP); + Vector point = cell; + float score = 1; + for (float traced = 0; traced < distance; traced += MASK_TRACE_STEP) + { + point = vector_sub(point, step); + for (auto [x, y] : CORNERS) + { + Vector probe = mask_cell_center(vector_make(point.x + x, point.y + y)); + int gridIndex = room.GetGridIndex(probe); + if ((uint32_t)gridIndex >= ROOM_GRID_CELLS) continue; + int path = room.gridPaths[gridIndex]; + if (path == MASK_TRACE_IGNORED_PATH) continue; + if (path >= MASK_TRACE_WALL_PATH) score = -1; + else if (path > 0) score -= MASK_TRACE_ROUGH; + } + } + return score > 0; +} + +// Every 4 frames it charges a target lined up with it along a clear line. +static void mask_charge_try(Entity_NPC& npc, Vector cell) +{ + if (!npc.IsFrame(MASK_CHARGE_FRAMES, (int)npc.index)) return; + Vector delta = mask_target_delta(npc, cell); + if (std::abs(delta.x) >= MASK_CHARGE_BAND && std::abs(delta.y) >= MASK_CHARGE_BAND) return; + float distance = vector_length(delta); + if (distance >= MASK_CHARGE_REACH) return; + if (distance > 0 && !is_mask_line_clear(cell, delta, distance)) return; + if (npc.HasEntityFlags(FLAG_DISTRACTED)) return; + + npc.targetPosition = vector_scale(mask_axis_away(delta), MASK_CHARGE_PUSH); + npc.i1 = MASK_DASH_CHARGE; + npc_sound_play(SOUND_MASKINFAMY_DASH, 1, 2, 1); +} + +// The dash along its axis, drawn into its lane, until it hits a wall or is distracted. +static void mask_dash(Entity_NPC& npc, Vector cell) +{ + if (npc.isCollidesWithGrid || npc.HasEntityFlags(FLAG_DISTRACTED)) + { + npc.i1 = MASK_DASH_NONE; + npc.pathfinder.movementTarget = {}; + npc.pathfinder.moveDirection = {}; + npc.targetPosition = {}; + return; + } + npc.friction *= MASK_DASH_FRICTION; + npc_push(npc, npc.targetPosition); + npc.v1.y = npc.targetPosition.y * MASK_FACING_PUSH + npc.v1.y; + npc.v1.x = npc.targetPosition.x * MASK_FACING_PUSH + npc.v1.x; + if (std::abs(cell.x) <= std::abs(cell.y)) npc.pos.x = cell.x * MASK_LANE_PULL + npc.pos.x * MASK_LANE_KEEP; + else npc.pos.y = cell.y * MASK_LANE_PULL + npc.pos.y * MASK_LANE_KEEP; +} + +// 00461fc0 NpcAI::ENTITY_MASK_OF_INFAMY: the Mask of Infamy (and the plain Mask) drifts along the axes untouchable +// while its heart lives, charging targets lined up with it and lunging when the heart is hurt. Without the heart it +// turns angry and can be hurt. The original compares the lane cell's coordinates, not the dash's axis, to pick +// which way it is drawn into its lane. +void boss_mask_of_infamy_update(Entity_NPC& npc) +{ + bool isControlled = npc.controllerID != -1; + for (Entity* link : {npc.parent.get(), npc.entityRef.get()}) + isControlled |= link && link->IsEnemy() && static_cast(link)->controllerID != -1; + if (isControlled) reconstruction_missing("NpcAI::ENTITY_MASK_OF_INFAMY 00461fc0: a Mask under a player's control"); + + if (npc.state == NPC_STATE_INIT) return mask_init(npc); + mask_heart_check(npc); + mask_lunge_check(npc); + mask_face(npc); + + Vector cell = mask_cell_center(npc.pos); + bool isActive = !npc.HasEntityFlags(FLAG_DELIRIUM_FORM) || !room_is_clear(); + if ((npc.i1 == MASK_DASH_NONE || npc.i1 == MASK_DASH_LUNGE) && !npc.HasEntityFlags(FLAG_DISTRACTED) && isActive) + mask_charge_try(npc, cell); + if (npc.i1 != MASK_DASH_NONE) return mask_dash(npc, cell); + + 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); +} diff --git a/src/boss_mega_fatty.cpp b/src/boss_mega_fatty.cpp new file mode 100644 index 0000000..6e8d888 --- /dev/null +++ b/src/boss_mega_fatty.cpp @@ -0,0 +1,442 @@ +#include "boss_ai.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "grid_entity.h" +#include "grid_entity_trap_door.h" +#include "npc_caves.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include + +// Mega Fatty's subtypes: the red one (its belly layers hidden) that pukes rings and drops poop, and the brown one that +// sends out crackwaves and farts out Dips. +constexpr int MEGA_FATTY_RED = 1; +constexpr int MEGA_FATTY_BROWN = 2; + +// Its states: the suck, the puke that follows it, the jump and landing, and the fart. +constexpr int MEGA_FATTY_SUCK = NPC_STATE_SPECIAL; +constexpr int MEGA_FATTY_PUKE = NPC_STATE_ATTACK; +constexpr int MEGA_FATTY_JUMP = NPC_STATE_JUMP; +constexpr int MEGA_FATTY_LAND = NPC_STATE_STOMP; +constexpr int MEGA_FATTY_FART = NPC_STATE_ATTACK3; + +// The jump's phases (i1): a full jump, one cut short by its early transition, done rising, and cut short. +enum MegaFattyJump +{ + MEGA_FATTY_JUMP_FULL, + MEGA_FATTY_JUMP_EARLY, + MEGA_FATTY_JUMP_RISEN, + MEGA_FATTY_JUMP_CUT +}; + +constexpr float MEGA_FATTY_SHADOW_DROP = 5; +constexpr int MEGA_FATTY_FIRST_BELLY_LAYER = 2; +constexpr int MEGA_FATTY_BELLY_LAYER_END = 8; +constexpr float MEGA_FATTY_FRICTION = 0.5f; + +// How it picks an attack after 30 frames at rest, one time in 15 (in 5 while hurt): weights for the suck (none for the +// brown one), the fart (more when the target is near the room's corner) and the jump (more when it is far). The +// original measures the target's distance from the room's origin, not from Mega Fatty. +constexpr int MEGA_FATTY_REST = 30; +constexpr uint32_t MEGA_FATTY_ATTACK_ODDS = 15; +constexpr uint32_t MEGA_FATTY_HURT_ATTACK_ODDS = 5; +constexpr int MEGA_FATTY_SUCK_WEIGHT = 30; +constexpr int MEGA_FATTY_FART_WEIGHT = 30; +constexpr int MEGA_FATTY_NEAR_FART_WEIGHT = 50; +constexpr int MEGA_FATTY_JUMP_WEIGHT = 20; +constexpr int MEGA_FATTY_FAR_JUMP_WEIGHT = 40; +constexpr float MEGA_FATTY_NEAR = 120; +constexpr float MEGA_FATTY_FAR = 240; +constexpr float MEGA_FATTY_JUMP_LEAD = 10; + +// The suck pulls players, enemies, tears, projectiles and pickups within 600 toward it, up to 0.9 a frame. A player +// near its twin is pulled from between them. +constexpr float MEGA_FATTY_SUCK_REACH = 600; +constexpr float MEGA_FATTY_SUCK_PULL = 0.9f; +constexpr float MEGA_FATTY_TWIN_NEAR_SQUARED = 2704; + +// The puke: a spray of vomit lobbed at the target, wider as the animation goes, or the red one's fire rings. +constexpr int MEGA_FATTY_SPRAY_FRAME = 10; +constexpr float MEGA_FATTY_SPRAY_FRAMES = 15; +constexpr float MEGA_FATTY_SPRAY_HEIGHT = -300; +constexpr float MEGA_FATTY_SPRAY_RISE = -40; +constexpr float MEGA_FATTY_SPRAY_FALL = 2; +constexpr float MEGA_FATTY_SPRAY_AIM = 0.025f; +constexpr float MEGA_FATTY_SPRAY_LEAD = 0.6f; +constexpr float MEGA_FATTY_SHOT_SCALE_MIN = 0.5f; +constexpr int MEGA_FATTY_RING_FRAMES = 3; +constexpr float MEGA_FATTY_RING_HEIGHT = -40; +constexpr float MEGA_FATTY_RING_SCALE = 1.5f; +constexpr float MEGA_FATTY_RING_FALL = 1.5f; +constexpr float MEGA_FATTY_RING_SPIN = 0.05f; +constexpr float MEGA_FATTY_RING_RISE = 8; +constexpr float MEGA_FATTY_RING_SPEED = 5; +constexpr float MEGA_FATTY_RING_SHOTS = 4; + +// The jump drifts it 2 percent more of the way each frame. Landing in a wall moves it to a free cell within 80. +constexpr float MEGA_FATTY_JUMP_DRIFT = 0.02f; +constexpr float MEGA_FATTY_ARRIVED_SQUARED = 2; +constexpr float MEGA_FATTY_LAND_SEARCH = 80; + +// The landing: the red one's ring of shots and splat, the brown one's crackwaves, or red creep about it, with a +// shake and a ripple. +constexpr float MEGA_FATTY_LAND_RING_SPEED = 10; +constexpr float MEGA_FATTY_LAND_RING_SHOTS = 6; +constexpr float MEGA_FATTY_SPLAT = 3; +constexpr int MEGA_FATTY_CRACKWAVES_MIN = 3; +constexpr float MEGA_FATTY_FULL_TURN = 360; +constexpr int MEGA_FATTY_CREEPS = 5; +constexpr float MEGA_FATTY_CREEP_REACH = 75; +constexpr float MEGA_FATTY_CREEP_SCALE = 2; +constexpr int MEGA_FATTY_SHAKE = 10; +constexpr float MEGA_FATTY_RIPPLE_AMPLITUDE = 0.04f; +constexpr float MEGA_FATTY_RIPPLE_SPEED = 0.025f; +constexpr int MEGA_FATTY_RIPPLE_FRAMES = 13; + +// The fart: Dips beside it while the room has few enemies (4, 8 for the brown one), else the red one's poop (8 at +// most, 3 for a Delirium form) or a lob of 30 shots, and always a poison cloud. +constexpr int MEGA_FATTY_DIP_LIMIT = 4; +constexpr int MEGA_FATTY_BROWN_DIP_LIMIT = 8; +constexpr int MEGA_FATTY_BROWN_DIPS = 3; +constexpr float MEGA_FATTY_DIP_SEARCH = 60; +constexpr float MEGA_FATTY_DIP_SPREAD = 10; +constexpr int MEGA_FATTY_POOP_LIMIT = 8; +constexpr int MEGA_FATTY_DELIRIUM_POOP_LIMIT = 3; +constexpr int MEGA_FATTY_POOP_VARIANT = 1; +constexpr float MEGA_FATTY_LOB_RISE = 80; +constexpr int MEGA_FATTY_LOB_SHOTS = 30; +constexpr float MEGA_FATTY_LOB_TRAJECTORY = 15; +constexpr float MEGA_FATTY_CLOUD_THRESHOLD = 50; +constexpr float MEGA_FATTY_CLOUD_DAMAGE = 15; +constexpr float MEGA_FATTY_CLOUD_RADIUS = 100; + +// The rest: it starts an attack after a while, unless it is a calm Delirium form. +static void mega_fatty_idle(Entity_NPC& npc) +{ + npc.sprite.Play("Idle"); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + if (npc.stateFrame++ <= MEGA_FATTY_REST) return; + if (Random() % MEGA_FATTY_ATTACK_ODDS != 0 && + !(npc.pendingDamage > 0 && Random() % MEGA_FATTY_HURT_ATTACK_ODDS == 0)) + return; + + float distance = vector_length(npc.GetPlayerTarget()->pos); + int suck = npc.subtype == MEGA_FATTY_BROWN ? 0 : MEGA_FATTY_SUCK_WEIGHT; + int fart = (distance < MEGA_FATTY_NEAR ? MEGA_FATTY_NEAR_FART_WEIGHT : MEGA_FATTY_FART_WEIGHT) + suck; + int jump = (distance > MEGA_FATTY_FAR ? MEGA_FATTY_FAR_JUMP_WEIGHT : MEGA_FATTY_JUMP_WEIGHT) + fart; + int roll = random_below(jump + fart + suck); + if (roll < suck) npc.state = MEGA_FATTY_SUCK; + else if (roll < fart) + { + npc.state = MEGA_FATTY_FART; + npc.PlaySound(SOUND_FAT_GRUNT, 1, 2, false, 1); + } + else if (roll < jump) + { + npc.state = MEGA_FATTY_JUMP; + Vector aim = npc.CalcTargetPosition(0); + Vector lead = npc.GetPlayerTarget()->velocity; + npc.targetPosition = vector_make(lead.x * MEGA_FATTY_JUMP_LEAD + aim.x, lead.y * MEGA_FATTY_JUMP_LEAD + aim.y); + npc.v1.x = 0; + npc.i1 = (int)(Random() & 1); + } +} + +// Whether the suck pulls an entity: a living player, enemy (but a fireplace), tear, projectile or pickup. +static bool is_suckable(Entity& entity) +{ + if (entity.isDead) return false; + if (entity.type == ENTITY_PLAYER || entity.type == ENTITY_TEAR || entity.type == ENTITY_PROJECTILE || + entity.type == ENTITY_PICKUP) + return true; + return entity.type >= ENTITY_FIRST_ENEMY && entity.type <= ENTITY_LAST_ENEMY && entity.type != ENTITY_FIREPLACE; +} + +// The suck: between its events it pulls everything in, then it pukes. +static void mega_fatty_suck(Entity_NPC& npc) +{ + npc.sprite.Play("Sucking"); + if (!npc.sprite.animState.animData) + { + npc.state = MEGA_FATTY_PUKE; + return; + } + + if (npc.sprite.WasEventTriggered("StartSucking") && !npc.sprite.WasEventTriggered("EndSucking")) + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (!is_suckable(*entity)) continue; + Vector from = entity->pos; + Entity* twin = + entity->type == ENTITY_PLAYER ? static_cast(entity)->twinPlayer.get() : nullptr; + if (twin && vector_length_squared(vector_sub(from, twin->pos)) < MEGA_FATTY_TWIN_NEAR_SQUARED) + from = vector_scale(vector_add(twin->pos, from), 0.5f); + + Vector toward = vector_normalized(vector_sub(npc.pos, from)); + float distance = vector_length(vector_sub(npc.pos, entity->pos)); + float pull = std::clamp((MEGA_FATTY_SUCK_REACH - distance) * MEGA_FATTY_SUCK_PULL / MEGA_FATTY_SUCK_REACH, + 0.0f, MEGA_FATTY_SUCK_PULL); + npc_push(*entity, vector_scale(toward, pull)); + } + if (npc_anim_is_done(npc)) npc.state = MEGA_FATTY_PUKE; +} + +// One frame of the puke: the red one's spinning rings every 3 frames, else a lobbed blob at the target. +static void mega_fatty_puke_fire(Entity_NPC& npc) +{ + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.subtype == MEGA_FATTY_RED) + { + if (!npc.IsFrame(MEGA_FATTY_RING_FRAMES, (int)npc.index)) return; + ProjectileParams params; + params.variant = PROJECTILE_PUKE; + params.bulletFlags |= PROJECTILE_SINE_VELOCITY; + params.heightModifier = MEGA_FATTY_RING_HEIGHT; + params.scale = MEGA_FATTY_RING_SCALE; + params.fallingSpeedModifier = MEGA_FATTY_RING_FALL; + params.circleAngle = (float)(g_game->frameCount - npc.spawnFrame) * MEGA_FATTY_RING_SPIN; + Vector mouth = vector_make(npc.pos.x - 0, npc.pos.y - MEGA_FATTY_RING_RISE); + return npc.FireProjectiles(mouth, vector_make(MEGA_FATTY_RING_SPEED, MEGA_FATTY_RING_SHOTS), PROJECTILES_RING, + params); + } + + ProjectileParams params; + params.variant = PROJECTILE_PUKE; + float spread = + std::clamp(((float)npc.sprite.GetFrame() - MEGA_FATTY_SPRAY_FRAME) / MEGA_FATTY_SPRAY_FRAMES, 0.0f, 1.0f); + spread = spread + spread + 1; + params.heightModifier = MEGA_FATTY_SPRAY_HEIGHT; + params.fallingSpeedModifier = MEGA_FATTY_SPRAY_RISE; + params.fallingAccelModifier = MEGA_FATTY_SPRAY_FALL; + params.scale = random_unit() + MEGA_FATTY_SHOT_SCALE_MIN; + Vector scatter = random_direction(); + float share = random_unit(); + Vector lead = npc.GetPlayerTarget()->velocity; + Vector velocity = + vector_make(scatter.x * share * spread + toward.x * MEGA_FATTY_SPRAY_AIM + lead.x * MEGA_FATTY_SPRAY_LEAD, + scatter.y * share * spread + toward.y * MEGA_FATTY_SPRAY_AIM + lead.y * MEGA_FATTY_SPRAY_LEAD); + npc.FireProjectiles(npc.pos, velocity, PROJECTILES_SINGLE, params); +} + +// The puke: vomit from its Shoot event until it stops shooting. Without an animation it rests at once. +static void mega_fatty_puke(Entity_NPC& npc) +{ + npc.sprite.Play("Puking"); + if (!npc.sprite.animState.animData) return; + + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_MEGA_PUKE, 1, 2, false, 1); + npc_sound_play(SOUND_MEGAFATTY_VOMIT, 1, 2, 1); + } + if (npc.sprite.WasEventTriggered("Shoot") && !npc.sprite.WasEventTriggered("StopShooting")) + mega_fatty_puke_fire(npc); +} + +// The jump: it rises (cut short at its early transition when told), drifting toward its spot, and lands once there. +static void mega_fatty_jump(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + if (npc.i1 < MEGA_FATTY_JUMP_RISEN) + { + npc.sprite.Play("Jumping"); + if (!anim.animData) npc.i1 = MEGA_FATTY_JUMP_RISEN; + else if (anim.IsEventTriggered("EarlyTransition") && npc.i1 == MEGA_FATTY_JUMP_EARLY) + npc.i1 = MEGA_FATTY_JUMP_CUT; + else if (!anim.isPlaying) npc.i1 = MEGA_FATTY_JUMP_RISEN; + } + bool isArrived = vector_length_squared(vector_sub(npc.targetPosition, npc.pos)) < MEGA_FATTY_ARRIVED_SQUARED; + if (npc.i1 != MEGA_FATTY_JUMP_FULL && (isArrived || npc.i1 == MEGA_FATTY_JUMP_CUT)) npc.state = MEGA_FATTY_LAND; + + if (anim.animData && anim.IsEventTriggered("Jump")) npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + if (npc.i1 == MEGA_FATTY_JUMP_FULL && !(anim.animData && anim.WasEventTriggered("Jump"))) return; + + float share = std::min(npc.v1.x + MEGA_FATTY_JUMP_DRIFT, 1.0f); + npc.v1.x = share; + npc.velocity.x = (npc.pos.x * (1 - share) + share * npc.targetPosition.x) - npc.pos.x; + npc.velocity.y = (share * npc.targetPosition.y + npc.pos.y * (1 - share)) - npc.pos.y; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; +} + +// What its landing leaves: the red one's ring and splat, the brown one's crackwaves (none after a cut jump), else red +// creep about it. +static void mega_fatty_land_burst(Entity_NPC& npc) +{ + if (npc.subtype == MEGA_FATTY_RED) + { + npc.FireProjectiles(npc.pos, vector_make(MEGA_FATTY_LAND_RING_SPEED, MEGA_FATTY_LAND_RING_SHOTS), + PROJECTILES_RING, ProjectileParams()); + npc.MakeSplat(MEGA_FATTY_SPLAT); + return; + } + if (npc.subtype == MEGA_FATTY_BROWN && npc.i1 != MEGA_FATTY_JUMP_CUT) + { + float step = MEGA_FATTY_FULL_TURN / ((float)((Random() & 1) + MEGA_FATTY_CRACKWAVES_MIN) + 0); + for (float angle = 0; angle < MEGA_FATTY_FULL_TURN; angle += step) + { + auto* wave = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACKWAVE, + .seed = Random()})); + wave->parent = &npc; + wave->rotation = angle; + } + return; + } + for (int i = 0; i < MEGA_FATTY_CREEPS; i++) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float reach = random_unit() * MEGA_FATTY_CREEP_REACH; + Vector spot = vector_make(std::cos(angle) * reach + npc.pos.x, std::sin(angle) * reach + npc.pos.y); + Entity* creep = g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = seed}); + creep->sprite.scale = vector_make(MEGA_FATTY_CREEP_SCALE, MEGA_FATTY_CREEP_SCALE); + } +} + +// The landing: out of a wall it moves to a free cell, and on Landed it collides again and bursts with a shake. +static void mega_fatty_land(Entity_NPC& npc) +{ + npc.sprite.Play("Landing"); + if (npc.entityGridCollisionClass == GRIDCOLL_NONE) + { + if (room_grid_collision_at(npc.pos) != 0) + npc.pos = room_free_tile_position_find(npc.pos, MEGA_FATTY_LAND_SEARCH); + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + } + if (!npc.sprite.animState.animData || !npc.sprite.IsEventTriggered("Landed")) return; + + npc.entityCollisionClass = ENTCOLL_ALL; + mega_fatty_land_burst(npc); + game_shake_screen(MEGA_FATTY_SHAKE); + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + shockwave_make(npc.pos, MEGA_FATTY_RIPPLE_AMPLITUDE, MEGA_FATTY_RIPPLE_SPEED, MEGA_FATTY_RIPPLE_FRAMES); +} + +// Dips around a free spot near it: one or two, three for the brown one. +static void mega_fatty_dips_spawn(Entity_NPC& npc) +{ + int count = (int)(Random() & 1) + 1; + if (npc.subtype == MEGA_FATTY_BROWN) count = MEGA_FATTY_BROWN_DIPS; + for (int i = 0; i < count; i++) + { + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = MEGA_FATTY_DIP_SEARCH}); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float reach = random_unit(); + Vector position = vector_make(std::cos(angle) * reach * MEGA_FATTY_DIP_SPREAD + spot.x, + std::sin(angle) * reach * MEGA_FATTY_DIP_SPREAD + spot.y); + g_game->Spawn({.position = position, .spawner = &npc, .type = ENTITY_DIP, .seed = seed}); + } +} + +// The red one's poop on a free spot near it, now and then, up to its limit. +static bool mega_fatty_poop(Entity_NPC& npc, int limit) +{ + if (npc.subtype != MEGA_FATTY_RED || npc.i2 >= limit || (Random() & 1) != 0) return false; + + Room& room = *g_game->room; + int gridIndex = + room.GetGridIndex(room_free_pickup_position_find({.position = npc.pos, .step = MEGA_FATTY_DIP_SEARCH})); + GridEntity* standing = (uint32_t)gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + bool isFree = !standing || standing->type == GRID_DECORATION || standing->type == GRID_SPIDERWEB; + if (isFree && room.roomType != ROOM_DUNGEON) + { + room.SpawnGridEntity(gridIndex, GRID_POOP, MEGA_FATTY_POOP_VARIANT, npc.dropRNG.Next(), 0); + npc.i2++; + } + return true; +} + +// The fart: on its event a fart cloud, Dips, the red one's poop or a lob of shots, and a poison cloud around it. +static void mega_fatty_fart(Entity_NPC& npc) +{ + npc.sprite.Play("Fart"); + bool isDelirium = npc.HasEntityFlags(FLAG_DELIRIUM_FORM); + if (!npc.sprite.IsEventTriggered("Fart")) return; + + g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_FART, .seed = Random()}); + npc.PlaySound(SOUND_MEGA_FATTY_MEGA_FART, 1, 2, false, 1); + int dipLimit = npc.subtype == MEGA_FATTY_BROWN ? MEGA_FATTY_BROWN_DIP_LIMIT : MEGA_FATTY_DIP_LIMIT; + if (isDelirium) dipLimit -= npc.CountRelatedEntities(ENTITY_DIP, 0, nullptr); + + bool isDips = + npc.subtype != MEGA_FATTY_RED && dipLimit > g_game->room->GetAliveEnemiesCount() && (Random() & 1) == 0; + if (isDips) mega_fatty_dips_spawn(npc); + else if (!mega_fatty_poop(npc, isDelirium ? MEGA_FATTY_DELIRIUM_POOP_LIMIT : MEGA_FATTY_POOP_LIMIT)) + { + Vector target = npc.GetPlayerTarget()->pos; + target.y = std::min(target.y, npc.pos.y - MEGA_FATTY_LOB_RISE); + ProjectileParams params; + params.variant = PROJECTILE_PUKE; + params.scale = random_unit() + MEGA_FATTY_SHOT_SCALE_MIN; + npc.FireBossProjectiles(MEGA_FATTY_LOB_SHOTS, target, MEGA_FATTY_LOB_TRAJECTORY, params); + } + + TearFlags poison; + poison.set(TEAR_POISON); + damage_radius({.tearFlags = poison, + .position = npc.pos, + .source = &npc, + .damage = MEGA_FATTY_CLOUD_DAMAGE, + .playerDamageThreshold = MEGA_FATTY_CLOUD_THRESHOLD, + .radius = MEGA_FATTY_CLOUD_RADIUS}); +} + +// 00460780 NpcAI::ENTITY_MEGA_FATTY: Mega Fatty rests, then sucks everything in and pukes, jumps onto its target +// with a shockwave, or farts out Dips and a poison cloud. The red one shrugs off poop damage. +void boss_mega_fatty_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.shadowOffset.y = MEGA_FATTY_SHADOW_DROP; + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + npc.i2 = 0; + if (npc.subtype == MEGA_FATTY_RED) + for (int layer = MEGA_FATTY_FIRST_BELLY_LAYER; layer < MEGA_FATTY_BELLY_LAYER_END; layer++) + npc.sprite.GetLayer(layer)->isVisible = false; + return; + } + + if (npc.subtype == MEGA_FATTY_RED) + for (DamageEvent& event : npc.damageEvents) + if (event.damageFlags & DAMAGE_POOP) event.damage = 0; + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("EndSucking")) npc_sound_play(SOUND_MEGAFATTY_GULP, 1, 2, 1); + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("StartSucking")) + npc_sound_play(SOUND_MEGAFATTY_SUCKIN, 1, 2, 1); + } + + switch (npc.state) + { + case NPC_STATE_IDLE: + mega_fatty_idle(npc); + break; + case MEGA_FATTY_SUCK: + mega_fatty_suck(npc); + break; + case MEGA_FATTY_JUMP: + mega_fatty_jump(npc); + break; + case MEGA_FATTY_PUKE: + case MEGA_FATTY_LAND: + case MEGA_FATTY_FART: + if (npc.state == MEGA_FATTY_PUKE) mega_fatty_puke(npc); + else if (npc.state == MEGA_FATTY_LAND) mega_fatty_land(npc); + else mega_fatty_fart(npc); + if (!npc_anim_is_done(npc)) break; + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + break; + } + npc.friction *= MEGA_FATTY_FRICTION; +} diff --git a/src/boss_moms_heart.cpp b/src/boss_moms_heart.cpp new file mode 100644 index 0000000..a85a58f --- /dev/null +++ b/src/boss_moms_heart.cpp @@ -0,0 +1,906 @@ +#include "boss_ai.h" +#include "entity_config.h" +#include "entity_familiar.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "grid_entity_trap_door.h" +#include "level.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include +#include +#include + +// Mom's Heart's forms: It Lives (its variant), the beating sprite drawn in front of either (variant 10), and the +// Mausoleum's heart (its subtype), which has a third more health, its own attacks and summons, and opens the way to +// the Corpse. +constexpr int HEART_IT_LIVES = 1; +constexpr int HEART_BEAT = 10; +constexpr int HEART_MAUSOLEUM = 1; +constexpr float MAUSOLEUM_HEALTH_SCALE = 1.4f; + +// The heart's phase (its i1): beating at its pace, coming down out of the flesh, or hidden in it. Its pace (aiCounter) +// is 1 to 3, faster as it loses health. +enum HeartPhase +{ + HEART_BEAT_SLOW = 1, + HEART_BEAT_MEDIUM, + HEART_BEAT_FAST, + HEART_COMEDOWN, + HEART_HIDDEN +}; + +// The players start in front of the bottom door, the others 20 around the first. The beating sprite sits at y 255. +constexpr float HEART_PLAYER_ROW = 370; +constexpr float HEART_PLAYER_SCATTER = 20; +constexpr float HEART_BEAT_ROW = 255; +constexpr float HEART_BEAT_DEPTH = 1; + +// Hiding: the heart counts 100 down a frame of beating (3 a frame it is hurt), then hides unless at its fastest. It +// comes back down once its summon cooldown is under 40 (at once at its fastest after the medium pace). +constexpr float HIDE_COUNTDOWN = 100; +constexpr float HIDE_HURT_STEP = 3; +constexpr int COMEOUT_COOLDOWN = 40; +constexpr int COMEDOWN_FRAMES = 31; +constexpr int COMEDOWN_SOLID_FRAME = 6; +constexpr int COMEOUT_VOICE_DELAY = 45; +constexpr int COMEOUT_SHAKE = 15; + +// Its attacks: one every 75 frames while fewer than 3 enemies are left, an attack lasting 180 frames (longer while its +// sweeping lasers last). The Mausoleum's heart waits 15 more frames while 18 or more of its shots fly in the room. +constexpr int ATTACK_COOLDOWN = 75; +constexpr int ATTACK_CROWD = 3; +constexpr int HEART_ATTACK_FRAMES = 180; +constexpr int MAUSOLEUM_SHOT_LIMIT = 17; +constexpr int MAUSOLEUM_SHOT_WAIT = 15; +constexpr float SHOT_ROOM_MARGIN = 20; +constexpr float LOW_HEALTH = 0.2f; + +// The heart is hurt aloud by more than 10 to 29 damage at once, 25 to 54 frames later. +constexpr int HEART_HURT_VOICE_MIN = 10; +constexpr uint32_t HEART_HURT_VOICE_SPREAD = 20; +constexpr int HEART_HURT_VOICE_DELAY = 25; +constexpr uint32_t HEART_HURT_VOICE_DELAY_SPREAD = 30; + +// At its fastest it bleeds a splat a frame, sized 0.2 to 0.7. +constexpr float BLEED_SCALE_MIN = 0.2f; +constexpr float BLEED_SCALE_SPREAD = 0.5f; + +// Each beat ripples the room and plays a wet beat (pitched lower the slower the pace) with the heartbeat of its pace. +struct Heartbeat +{ + float amplitude; + float speed; + float wetPitch; + int duration; + int sound; + int shake; +}; + +constexpr float WET_BEAT_VOLUME = 0.5f; + +constexpr Heartbeat BEAT_HIDDEN = {0.01f, 0.1f, 0.1f, 5, SOUND_HEARTBEAT, 0}; +constexpr Heartbeat BEAT_SLOW = {0.008f, 0.02f, 0.1f, 48, SOUND_HEARTBEAT, 3}; +constexpr Heartbeat BEAT_MEDIUM = {0.008f, 0.025f, 0.15f, 30, SOUND_HEARTBEAT_FASTER, 3}; +constexpr Heartbeat BEAT_FAST = {0.008f, 0.03f, 0.2f, 12, SOUND_HEARTBEAT_FASTEST, 4}; +constexpr float WET_PITCH_TINY_RAISE = 0.5f; +constexpr float WET_PITCH_GIANT_SCALE = 0.5f; + +// The ripple of the heart coming down. +constexpr float COMEOUT_AMPLITUDE = 0.01f; +constexpr float COMEOUT_SPEED = 0.015f; +constexpr int COMEOUT_RIPPLE = 100; + +// An enemy the heart calls (an entry of its summon table): its type and variant, how many at once, the enemies left +// below which it calls them while hidden (plus 2), and how many it calls in one hiding. +struct HeartSummon +{ + int type; + int variant; + int count; + int crowdLimit; + int hiddenLimit; +}; + +// The summons of each pace, which the heart steps through in order. A heart past full health (pace 0) has its own. +constexpr std::array SUMMONS_OVERHEALED = {{{25, 0, 3, 3, 6}}}; +constexpr std::array HEART_SUMMONS_SLOW = {{{60, 0, 2, 1, 4}, {247, 0, 3, 2, 6}, {24, 0, 3, 3, 6}}}; +constexpr std::array HEART_SUMMONS_MEDIUM = {{{56, 0, 3, 2, 6}, {216, 0, 2, 3, 4}, {24, 0, 3, 3, 6}}}; +constexpr std::array HEART_SUMMONS_FAST = { + {{88, 0, 4, 3, 7}, {}, {229, 0, 4, 3, 7}, {}, {92, 0, 4, 4, 6}, {}}}; +constexpr std::array IT_LIVES_SUMMONS_SLOW = { + {{60, 0, 2, 1, 4}, {247, 0, 3, 2, 6}, {269, 0, 1, 1, 1}, {71, 0, 1, 1, 1}}}; +constexpr std::array IT_LIVES_SUMMONS_MEDIUM = { + {{41, 0, 2, 2, 4}, {88, 0, 4, 3, 7}, {71, 1, 1, 1, 1}, {28, 0, 1, 1, 1}}}; +constexpr std::array IT_LIVES_SUMMONS_FAST = { + {{56, 0, 3, 2, 6}, {}, {24, 0, 3, 3, 6}, {}, {229, 0, 4, 3, 7}, {}, {92, 0, 4, 4, 6}, {}}}; +constexpr std::array MAUSOLEUM_SUMMONS_SLOW = {{{60, 0, 2, 1, 2}, {}}}; +constexpr std::array MAUSOLEUM_SUMMONS_LATER = {{{}}}; + +// Summons come down 30 inside the room's top, away from the heart (20 tries), or spread on an arc below it: 40 out, +// 180 for the eyes (type 60) in a room's first 100 frames and for type 231, and twice that for the three at once of +// type 28. +constexpr float SUMMON_WALL_MARGIN = 30; +constexpr uint32_t SUMMON_SPOT_TRIES = 20; +constexpr float SUMMON_ARC = 40; +constexpr float SUMMON_ARC_WIDE = 180; +constexpr float SUMMON_ARC_SQUASH = 0.8f; +constexpr int SUMMON_EYE = 60; +constexpr int SUMMON_WIDE = 231; +constexpr int SUMMON_TRIPLE = 28; +constexpr int SUMMON_TRIPLE_COUNT = 3; +constexpr int ROOM_SETTLED_FRAMES = 99; +constexpr float SUMMON_VOLUME_STEP = 0.1f; + +// The attack patterns: Mom's Heart and It Lives pick from 0 to 7 (0 to 3 slow, 2 to 7 medium), the Mausoleum's heart +// from 10 to 17 (10 to 13, 14 to 17). Hidden, every heart rains shots (8). At a fifth of its health a heart sweeps +// lasers instead (9, the Mausoleum's 18), with red tracers marking where they will turn. +constexpr int ATTACK_LAST = 7; +constexpr int ATTACK_SLOW_LAST = 3; +constexpr int ATTACK_MEDIUM_FIRST = 2; +constexpr int MAUSOLEUM_ATTACK_FIRST = 10; +constexpr int MAUSOLEUM_ATTACK_LAST = 17; +constexpr int MAUSOLEUM_ATTACK_SLOW_LAST = 13; +constexpr int MAUSOLEUM_ATTACK_MEDIUM_FIRST = 14; +constexpr int ATTACK_HIDDEN = 8; +constexpr int ATTACK_LASERS = 9; +constexpr int MAUSOLEUM_ATTACK_LASERS = 18; +constexpr ColorMod TRACER_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +static const Vector TRACER_OFFSET = vector_make(0, -20); +constexpr int TRACER_TIMEOUT = 12; +constexpr float TRACER_SCALE = 4; + +// The shots: big (1.5), floating 5 high and falling slowly, at the nearest player unless a pattern turns them. +constexpr float HEART_SHOT_HEIGHT = 5; +constexpr float HEART_SHOT_SCALE = 1.5f; +constexpr float HEART_SHOT_FALL_ACCEL = -0.06f; +constexpr float HEART_SHOT_FALL_SPEED = -2; +constexpr float TURN = 2 * PI_F; + +// The death: every enemy left dies with the heart, its shots burst in a ring of 14 at 5, and blood runs from the walls. +constexpr int DEATH_RING = 14; +constexpr float DEATH_RING_SPEED = 5; +constexpr int HEART_DEATH_BLOOD_FRAMES = 30; +constexpr int HEART_DEATH_BLOOD_DROPS = 7; +constexpr int ENTITY_MOTHER_BALL = 866; +constexpr int DEATH_TARGET_FIRST = 10; +constexpr int DEATH_TARGET_LAST = 1000; + +// The sweeping lasers: 4 (the Mausoleum's 2) from 30 above the heart, after a 15 to 44 frame wait turning 2 a frame +// for 1 to 4 half turns either way. The Mausoleum's turn 0.3 a frame without end, a timeout so far below zero that it +// never runs out. +constexpr int SWEEP_LASER_VARIANT = 1; +constexpr int SWEEP_LASERS = 4; +constexpr int MAUSOLEUM_SWEEP_LASERS = 2; +constexpr float SWEEP_LASER_RISE = 30; +constexpr int SWEEP_START_FRAME = 2; +constexpr int SWEEP_DELAY_MIN = 15; +constexpr uint32_t SWEEP_DELAY_SPREAD = 30; +constexpr float SWEEP_SPEED = 2; +constexpr float SWEEP_HALF_TURN = 180; +constexpr int SWEEP_TIMEOUT = 90; +constexpr int MAUSOLEUM_SWEEP_TIMEOUT = 120; +constexpr float MAUSOLEUM_SWEEP_SPEED = 0.3f; +constexpr float MAUSOLEUM_SWEEP_DEGREES = 1e9f; +constexpr int MAUSOLEUM_SWEEP_LIFE = -961634047; + +// A ring of shots fired by FireProjectiles: its speed and count. +struct ShotRing +{ + float speed; + int count; +}; + +// A vector turned by an angle in radians. +static Vector vector_turned(Vector v, float radians) +{ + float c = std::cos(radians); + float s = std::sin(radians); + return vector_make(v.x * c - v.y * s, v.x * s + v.y * c); +} + +// (004d4210) A shot of attack 14: it swerves on a 30 frame swing that calms over its first 120 frames, and speeds up. +static void swerve_hook(Entity_Projectile& shot, ProjectileStep step) +{ + if (step != PROJECTILE_STEP_UPDATE) return; + float swing = std::cos(shot.updateTime * TURN / 30); + float calm = std::clamp(shot.updateTime / 120, 0.0f, 1.0f); + float rate = shot.speedMultiplier; + float accel = rate != 1 ? 1.022f / ((rate + 1.022f) - rate * 1.022f) : 1.022f; + shot.curvingStrength = (0.06f - calm * 0.048f) * swing; + shot.velocity = vector_scale(shot.velocity, accel); +} + +// (004d42f0) A shot of attack 17: it weaves on a 90 frame swing, up to 10 degrees a frame. +static void weave_hook(Entity_Projectile& shot, ProjectileStep step) +{ + if (step != PROJECTILE_STEP_UPDATE) return; + float turn = std::cos(shot.updateTime * TURN / 90) * 10 * shot.speedMultiplier * DEGREES_TO_RADIANS; + shot.velocity = vector_turned(shot.velocity, turn); +} + +// (004d43b0) A shot of attack 15: it wiggles on a 40 frame swing offset by its wiggle frame, up to 7 degrees a frame. +static void wiggle_hook(Entity_Projectile& shot, ProjectileStep step) +{ + if (step != PROJECTILE_STEP_UPDATE) return; + float phase = ((float)shot.wiggleFrameOffset + shot.updateTime) * TURN / 40 + 0.3f; + float turn = std::cos(phase) * 7 * shot.speedMultiplier * DEGREES_TO_RADIANS; + shot.velocity = vector_turned(shot.velocity, turn); +} + +// (004d4480) A shot of attack 16: it orbits its target position by its curving strength in degrees a frame (half on +// an interpolation), its velocity kept along the orbit at its speed. +static void orbit_hook(Entity_Projectile& shot, ProjectileStep step) +{ + float rate = step == PROJECTILE_STEP_UPDATE ? 1 : 0.5f; + float turn = shot.curvingStrength * shot.speedMultiplier * rate * DEGREES_TO_RADIANS; + shot.pos = vector_add(vector_turned(vector_sub(shot.pos, shot.targetPosition), turn), shot.targetPosition); + if (step != PROJECTILE_STEP_UPDATE) return; + shot.velocity = vector_resized(vector_sub(shot.pos, shot.targetPosition), vector_length(shot.velocity)); +} + +// A pitch by the heart's size: a normal one, a tiny champion's and a giant's. +static float heart_pitch_get(const Entity_NPC& npc, float pitch, float tiny, float giant) +{ + if (npc.championColorIdx == CHAMPION_TINY) return tiny; + return npc.championColorIdx == CHAMPION_GIANT ? giant : pitch; +} + +// The summons of the heart's form at its pace. The heart reads the one at its summon index, kept inside the table +// here where the original could read past it. +static std::span summons_get(const Entity_NPC& npc) +{ + if (npc.aiCounter < HEART_BEAT_SLOW || npc.aiCounter > HEART_BEAT_FAST) return SUMMONS_OVERHEALED; + if (npc.subtype == HEART_MAUSOLEUM) + return npc.aiCounter == HEART_BEAT_SLOW ? std::span(MAUSOLEUM_SUMMONS_SLOW) + : MAUSOLEUM_SUMMONS_LATER; + if (npc.variant != HEART_IT_LIVES) + { + if (npc.aiCounter == HEART_BEAT_SLOW) return HEART_SUMMONS_SLOW; + return npc.aiCounter == HEART_BEAT_MEDIUM ? std::span(HEART_SUMMONS_MEDIUM) + : HEART_SUMMONS_FAST; + } + if (npc.aiCounter == HEART_BEAT_SLOW) return IT_LIVES_SUMMONS_SLOW; + return npc.aiCounter == HEART_BEAT_MEDIUM ? std::span(IT_LIVES_SUMMONS_MEDIUM) + : IT_LIVES_SUMMONS_FAST; +} + +// Steps to the next summon, back to the first after the last (the Mausoleum's heart stays on its last). +static void summon_advance(Entity_NPC& npc, std::span summons) +{ + if (++npc.projectileDelay < (int)summons.size()) return; + npc.projectileDelay = npc.subtype == HEART_MAUSOLEUM ? (int)summons.size() - 1 : 0; +} + +// 004d4610 NpcHelper::moms_heart_pick_attack: picks the next attack pattern for the pace (attacking), or the hidden +// rain, and starts it. At a fifth of its health the heart sweeps lasers instead, the tracers marking them. +static void heart_attack_pick(Entity_NPC& npc) +{ + bool isMausoleum = npc.subtype == HEART_MAUSOLEUM; + int first = isMausoleum ? MAUSOLEUM_ATTACK_FIRST : 0; + int last = isMausoleum ? MAUSOLEUM_ATTACK_LAST : ATTACK_LAST; + if (npc.i1 == HEART_HIDDEN) + { + first = ATTACK_HIDDEN; + last = ATTACK_HIDDEN; + } + else + { + npc.state = NPC_STATE_ATTACK; + if (npc.aiCounter == HEART_BEAT_SLOW) last = isMausoleum ? MAUSOLEUM_ATTACK_SLOW_LAST : ATTACK_SLOW_LAST; + else if (npc.aiCounter == HEART_BEAT_MEDIUM) + first = isMausoleum ? MAUSOLEUM_ATTACK_MEDIUM_FIRST : ATTACK_MEDIUM_FIRST; + } + npc.v1.y = (float)(Random() % (uint32_t)(last - first + 1)) + (float)first; + npc.stateFrame = 0; + if (npc.health / npc.maxHitPoints > LOW_HEALTH) return; + + npc.v1.y = (float)(isMausoleum ? MAUSOLEUM_ATTACK_LASERS : ATTACK_LASERS); + int tracers = isMausoleum ? MAUSOLEUM_SWEEP_LASERS : SWEEP_LASERS; + for (int i = 0; i < tracers; i++) + { + float angle = isMausoleum ? (float)i * SWEEP_HALF_TURN + 90 : (float)i * 90 - 135; + following_effect_spawn(npc, {.offset = TRACER_OFFSET, + .targetPosition = vector_from_angle(angle), + .color = TRACER_COLOR, + .scale = TRACER_SCALE, + .timeout = TRACER_TIMEOUT}); + } +} + +// Attack 9: four lasers from above the heart that wait, then sweep together 1 to 4 half turns either way. +static void lasers_sweep(Entity_NPC& npc) +{ + Vector from = vector_make(npc.pos.x, npc.pos.y - SWEEP_LASER_RISE); + int delay = (int)(Random() % SWEEP_DELAY_SPREAD) + SWEEP_DELAY_MIN; + float side = (Random() & 1) ? 1 : -1; + float turns = (float)((Random() & 3) + 1) * SWEEP_HALF_TURN; + for (int i = 0; i < SWEEP_LASERS; i++) + { + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = from, + .source = &npc, + .angleDegrees = (float)i * 90 - 135, + .timeout = SWEEP_TIMEOUT, + .variant = SWEEP_LASER_VARIANT}); + laser->isActiveRotating = true; + laser->rotationDelay = delay; + laser->rotationDegrees = side * turns; + laser->rotationSpd = side * SWEEP_SPEED; + laser->timeout = (int)(uint32_t)(turns / SWEEP_SPEED) + delay + 1; + laser->Update(); + } +} + +// Attack 18: the Mausoleum's two lasers from above the heart, turning slowly either way without end. +static void lasers_sweep_endless(Entity_NPC& npc) +{ + Vector from = vector_make(npc.pos.x, npc.pos.y - SWEEP_LASER_RISE); + int delay = (int)(Random() % SWEEP_DELAY_SPREAD) + SWEEP_DELAY_MIN; + float side = (Random() & 1) ? 1 : -1; + for (int i = 0; i < MAUSOLEUM_SWEEP_LASERS; i++) + { + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = from, + .source = &npc, + .angleDegrees = (float)i * SWEEP_HALF_TURN + 90, + .timeout = MAUSOLEUM_SWEEP_TIMEOUT, + .variant = SWEEP_LASER_VARIANT}); + laser->isActiveRotating = true; + laser->rotationDelay = delay; + laser->rotationDegrees = side * MAUSOLEUM_SWEEP_DEGREES; + laser->rotationSpd = side * MAUSOLEUM_SWEEP_SPEED; + laser->timeout = delay + MAUSOLEUM_SWEEP_LIFE; + laser->Update(); + } +} + +// The angle of a ring turning a full turn every 180 of a count (6 seconds of frames). +static float ring_angle(float count) +{ + return count / 6 / 30 * TURN; +} + +// 004d33d0 NpcHelper::moms_heart_attack_pattern: one frame of an attack pattern, mostly rings of shots on a beat or a +// frame interval. The shots hurt enemies too. +static void heart_attack_fire(Entity_NPC& npc, int pattern, int frame) +{ + ProjectileParams params; + params.heightModifier = HEART_SHOT_HEIGHT; + params.scale = HEART_SHOT_SCALE; + params.fallingAccelModifier = HEART_SHOT_FALL_ACCEL; + params.fallingSpeedModifier = HEART_SHOT_FALL_SPEED; + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + params.circleAngle = std::atan2(aim.y, aim.x); + params.bulletFlags |= PROJECTILE_HIT_ENEMIES; + Vector from = npc.pos; + bool isTick = npc_ticks_get(npc) != 0; + bool isBeat = npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Heartbeat"); + bool isFast = npc.aiCounter == HEART_BEAT_FAST; + float time = (float)frame; + ShotRing ring{}; + + switch (pattern) + { + case 0: + { + int every = (int)std::floor(6 - std::clamp(time / 180, 0.0f, 1.0f) * 3 + 0.5f); + if (!isTick || frame % every != 0) return; + params.circleAngle = ring_angle((time * time - time) * 0.01f + time); + ring = {3, 2}; + break; + } + case 1: + if (!isTick || frame % 18 != 0) return; + params.circleAngle = ring_angle((float)std::cos((double)(time / 30 / 6 * TURN)) * 10); + ring = {3, 8}; + break; + case 2: + case 3: + if (!isBeat) return; + params.circleAngle = ring_angle(time); + if (pattern == 3) params.bulletFlags |= PROJECTILE_SINE_VELOCITY; + ring = {5, isFast ? 4 : 10}; + break; + case 4: + if (!isTick || frame % 6 != 0) return; + params.bulletFlags |= PROJECTILE_SINE_VELOCITY; + params.circleAngle = ring_angle(time); + ring = {3, 3}; + break; + case 5: + if (!isTick || frame % 4 != 0) return; + params.bulletFlags |= PROJECTILE_SINE_VELOCITY; + params.circleAngle = std::cos(time * 0.9424779f / 30) * TURN / 3; + ring = {3.5f, 3}; + break; + case 6: + if (!isTick || frame % 4 != 0) return; + ring = {std::clamp((float)npc.stateFrame / 60, 0.0f, 1.0f) * 7 + 8, 1}; + break; + case 7: + if (!isTick || frame % 4 != 0) return; + params.circleAngle = -params.circleAngle; + ring = {6, 5}; + break; + case 8: + if (!npc.sprite.IsEventTriggered("Heartbeat")) return; + params.fireDirectionLimit = vector_make(0, 1); + params.dotProductLimit = 0; + params.circleAngle = ring_angle(time); + from = vector_make(npc.pos.x, g_game->room->topLeftPos.y + 20); + ring = {5, isFast ? 4 : 8}; + break; + case 9: + if (isTick && frame == SWEEP_START_FRAME) lasers_sweep(npc); + return; + case 10: + { + float left = (float)(180 - frame); + if (!isTick || frame % 3 != 0) return; + params.circleAngle = ring_angle((left * left - left) * 0.01f + left); + ring = {3, 2}; + break; + } + case 11: + if (!isTick || frame % 16 != 0) return; + params.circleAngle = time * 0.62831855f * 0.0625f; + params.bulletFlags |= frame % 32 == 0 ? PROJECTILE_CURVE_LEFT : PROJECTILE_CURVE_RIGHT; + ring = {5, 8}; + break; + case 12: + case 13: + { + if (!isBeat) return; + int count = isFast ? 3 : 8; + params.fallingAccelModifier = -0.08f; + params.circleAngle = ring_angle(time); + if (pattern == 13 && !isFast) params.bulletFlags |= PROJECTILE_SINE_VELOCITY; + npc.FireProjectiles(from, vector_make((isFast ? 0.8f : 0.5f) * 6, (float)count), PROJECTILES_RING, params); + params.scale = 1; + params.circleAngle = isFast ? ring_angle(-time) : PI_F / (float)count + params.circleAngle; + ring = {6, count}; + break; + } + case 14: + if (!isTick || frame % 4 != 0) return; + params.bulletFlags |= PROJECTILE_SINE_VELOCITY | PROJECTILE_CURVE_RIGHT; + params.motionHook = swerve_hook; + params.circleAngle = (time / 180 + time / 180) * 2 * PI_F / 3; + ring = {3, 5}; + break; + case 15: + if (!isTick || frame % 8 != 0) return; + params.scale = 1; + params.circleAngle = 0.06981317f; + params.motionHook = wiggle_hook; + npc.FireProjectiles(from, vector_make(6, 8), PROJECTILES_RING, params); + params.circleAngle -= 0.13962634f; + params.wiggleFrameOffset = 20; + ring = {6, 8}; + break; + case 16: + if (!isTick || frame % 30 != 0) return; + params.bulletFlags |= PROJECTILE_NO_WALL_COLLIDE; + params.scale = 1; + params.fallingAccelModifier = -0.085f; + params.motionHook = orbit_hook; + params.curvingStrength = 2; + params.circleAngle = (time + time) * PI_F / 600; + params.targetPosition = npc.pos; + npc.FireProjectiles(from, vector_make(3, 4), PROJECTILES_RING, params); + params.curvingStrength = -2; + npc.FireProjectiles(from, vector_make(3, 4), PROJECTILES_RING, params); + params.bulletFlags &= ~(uint64_t)PROJECTILE_NO_WALL_COLLIDE; + params.circleAngle = 0; + params.scale = HEART_SHOT_SCALE; + params.motionHook = nullptr; + ring = {3, 12}; + break; + case 17: + if (!isTick || frame % 8 != 0) return; + params.bulletFlags |= PROJECTILE_NO_WALL_COLLIDE; + params.circleAngle = 0; + params.motionHook = weave_hook; + ring = {8, 8}; + break; + case 18: + if (!isTick) return; + if (frame == SWEEP_START_FRAME) return lasers_sweep_endless(npc); + if (frame % 9 != 0) return; + ring = {8, 2}; + break; + default: + return; + } + npc.FireProjectiles(from, vector_make(ring.speed, (float)ring.count), PROJECTILES_RING, params); +} + +// The beating sprite in front of the heart: it shows the heart's phase at y 255 and dies with it. +static void heart_beat_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_DEATH_TRIGGER); + npc.state = NPC_STATE_IDLE; + return; + } + if (!npc.parent) return npc.Kill(EntityRef()); + + npc.pos.y = HEART_BEAT_ROW; + constexpr std::array PHASE_ANIMATIONS = {"", "Heartbeat1", "Heartbeat2", + "Heartbeat3", "HeartSummon", "HeartRetracted"}; + int phase = static_cast(*npc.parent).i1; + if (phase >= HEART_BEAT_SLOW && phase <= HEART_HIDDEN) npc.sprite.Play(PHASE_ANIMATIONS[phase]); +} + +// The heart's start: the players placed before it (its familiars with them) when it is part of the room's layout, +// its timers set, the Mausoleum's health raised, and its beating sprite spawned in front. +static void heart_start(Entity_NPC& npc) +{ + Game& game = *g_game; + if (npc.spawnGridIndex >= 0) + { + Vector start = vector_make(npc.pos.x, HEART_PLAYER_ROW); + for (size_t i = 0; i < game.playerManager.playerList.size(); i++) + { + Vector spot = i == 0 ? start : vector_add(start, vector_scale(random_direction(), HEART_PLAYER_SCATTER)); + game.GetPlayer((int)i)->Teleport(spot, false, false); + } + for (Entity* entity : game.room->entityList.updateEL) + if (entity && entity->type == ENTITY_FAMILIAR) + entity->pos = static_cast(entity)->GetFollowTargetPosition(FOLLOW_EXACT); + } + + npc.targetPosition = npc.pos; + npc.i2 = -1; + npc.aiCounter = 4; + npc.i1 = HEART_BEAT_SLOW; + npc.projectileDelay = 0; + npc.v1.x = HIDE_COUNTDOWN; + npc.projectileCooldown = 0; + npc.stateFrame = 0; + npc.state = NPC_STATE_IDLE; + if (npc.subtype == HEART_MAUSOLEUM) + { + npc.maxHitPoints *= MAUSOLEUM_HEALTH_SCALE; + npc.health = npc.maxHitPoints; + } + + uint32_t seed = Random(); + Entity* beat = game.Spawn({.position = vector_make(npc.pos.x, npc.pos.y + HEART_BEAT_DEPTH), + .spawner = &npc, + .type = npc.type, + .variant = HEART_BEAT, + .seed = seed}); + beat->parent = &npc; + npc.child = beat; + beat->Update(); +} + +// On the "Heartbeat" event: the screen shakes, the wet beat and the heartbeat of the pace play, and the room ripples. +static void heartbeat_play(Entity_NPC& npc) +{ + const Heartbeat* beat = nullptr; + if (npc.i1 == HEART_HIDDEN) beat = &BEAT_HIDDEN; + else if (npc.i1 == HEART_COMEDOWN || npc.aiCounter == HEART_BEAT_SLOW) beat = &BEAT_SLOW; + else if (npc.aiCounter == HEART_BEAT_MEDIUM) beat = &BEAT_MEDIUM; + else if (npc.aiCounter == HEART_BEAT_FAST) beat = &BEAT_FAST; + + if (beat) + { + if (beat->shake) game_shake_screen(beat->shake); + float tinyPitch = beat->wetPitch + WET_PITCH_TINY_RAISE; + float giantPitch = beat->wetPitch * WET_PITCH_GIANT_SCALE; + float wetPitch = heart_pitch_get(npc, beat->wetPitch, tinyPitch, giantPitch); + npc_sound_play(SOUND_MEAT_JUMPS, WET_BEAT_VOLUME, 2, wetPitch); + npc_sound_play(beat->sound, 1, 2, champion_pitch_get(npc)); + } + const Heartbeat& ripple = beat ? *beat : BEAT_HIDDEN; + shockwave_make(npc.pos, ripple.amplitude, ripple.speed, ripple.duration); +} + +// The heart comes down out of the flesh: its voice, a big shake and ripple, and the next summon. +static void heart_comeout(Entity_NPC& npc, std::span summons) +{ + npc_sound_play(SOUND_HEARTOUT, 1, 2, champion_pitch_get(npc)); + npc_sound_play(SOUND_MOM_VOX_FILTERED_ISAAC, 1, COMEOUT_VOICE_DELAY, champion_pitch_get(npc)); + npc.v1.x = HIDE_COUNTDOWN; + npc.i1 = HEART_COMEDOWN; + npc.stateFrame = 0; + game_shake_screen(COMEOUT_SHAKE); + shockwave_make(npc.pos, COMEOUT_AMPLITUDE, COMEOUT_SPEED, COMEOUT_RIPPLE); + summon_advance(npc, summons); +} + +// The phase while idle: hidden it comes out once its cooldown nears its end, coming down it attacks once down, and +// beating it counts down to hiding (the Mausoleum's heart steps through its summons instead, but at its first). +static void heart_phase_update(Entity_NPC& npc, std::span summons) +{ + int phase = npc.i1; + bool isComeout = phase == HEART_HIDDEN || (phase == HEART_COMEDOWN && npc.stateFrame < COMEDOWN_FRAMES && + npc.aiCounter == HEART_BEAT_FAST); + if (isComeout) + { + bool isRush = npc.aiCounter == HEART_BEAT_FAST && npc.i2 == HEART_BEAT_MEDIUM && phase == HEART_HIDDEN; + if (npc.projectileCooldown < COMEOUT_COOLDOWN || isRush) heart_comeout(npc, summons); + return; + } + if (phase == HEART_COMEDOWN) + { + if (npc.stateFrame >= COMEDOWN_FRAMES) heart_attack_pick(npc); + return; + } + + npc.i1 = npc.aiCounter; + npc.stateFrame = 0; + npc.v1.x -= 1; + if (npc.v1.x >= 0 || npc.aiCounter == HEART_BEAT_FAST) return; + if (npc.subtype == HEART_MAUSOLEUM && (npc.aiCounter != HEART_BEAT_SLOW || npc.projectileDelay != 0)) + { + if (++npc.projectileDelay >= (int)summons.size()) npc.projectileDelay = (int)summons.size() - 1; + return; + } + npc.PlaySound(SOUND_HEARTIN, 1, 2, false, 1); + npc.i1 = HEART_HIDDEN; + npc.stateFrame = 0; + heart_attack_pick(npc); +} + +// Hidden, the heart rains shots and calls its summon one at a time down from the room's top, away from it, while +// few enemies are left and until it called its share for this hiding. +static void hidden_summon(Entity_NPC& npc, const HeartSummon& summon) +{ + Room& room = *g_game->room; + if (summon.type != 0) + { + int enemies = room.GetAliveEnemiesCount(); + if (summon.crowdLimit <= enemies - 2 || (float)summon.hiddenLimit <= npc.v2.x) return; + + float left = room.topLeftPos.x + SUMMON_WALL_MARGIN; + float span = room.bottomRightPos.x - SUMMON_WALL_MARGIN - left; + float x = span * random_unit() + left; + for (uint32_t tries = 0; tries < SUMMON_SPOT_TRIES; tries++) + { + if (x < npc.pos.x - npc.size || npc.pos.x + npc.size < x) break; + x = span * random_unit() + left; + } + Vector top = vector_make(x, room.topLeftPos.y + SUMMON_WALL_MARGIN); + Vector spot = room_free_pickup_position_find({.position = top}); + uint32_t seed = Random(); + g_game->Spawn( + {.position = spot, .spawner = &npc, .type = summon.type, .variant = summon.variant, .seed = seed}); + } + npc.v2.x += 1; +} + +// Whether the Mausoleum's heart has too many of its shots flying in the room (past its walls they do not count). +static bool is_shot_crowd(const Entity_NPC& npc) +{ + Room& room = *g_game->room; + int shots = 0; + float margin = SHOT_ROOM_MARGIN; + for (Entity* entity : room.entityList.updateEL) + { + if (entity->type != ENTITY_PROJECTILE) continue; + Vector at = entity->pos; + bool isInside = at.x >= room.topLeftPos.x + margin && at.x <= room.bottomRightPos.x - margin && + at.y >= room.topLeftPos.y + margin && at.y <= room.bottomRightPos.y - margin; + if (room.IsLShapedRoom()) + { + Vector clamped = room.GetClampedPositionImpl(at, margin, margin, margin, margin); + isInside = clamped.x == at.x && clamped.y == at.y; + } + if (isInside && entity->spawnerType == npc.type) shots++; + } + return shots > MAUSOLEUM_SHOT_LIMIT; +} + +// Calls the summon in an arc below the heart (three at once for type 28), louder as the pace quickens. +static void arc_summon(Entity_NPC& npc, const HeartSummon& summon) +{ + float radius = SUMMON_ARC; + bool isEarlyEye = summon.type == SUMMON_EYE && g_game->room->GetFrameCount() <= ROOM_SETTLED_FRAMES; + if (isEarlyEye || summon.type == SUMMON_WIDE) radius = SUMMON_ARC_WIDE; + npc_sound_play(SOUND_SUMMONSOUND, (float)npc.aiCounter * SUMMON_VOLUME_STEP + 1, 2, champion_pitch_get(npc)); + + if (summon.type == SUMMON_TRIPLE) + { + for (int i = 0; i < SUMMON_TRIPLE_COUNT; i++) + { + uint32_t seed = Random(); + g_game->Spawn({.position = vector_make(npc.pos.x, npc.pos.y + radius * 2), + .spawner = &npc, + .type = summon.type, + .variant = summon.variant, + .seed = seed}); + } + return; + } + npc.v2.x = 0; + for (int i = 0; i < summon.count; i++) + { + Vector direction = vector_make(0, 1); + if (summon.count != 1) + { + float angle = (float)i / (float)(summon.count - 1) * PI_F; + direction = vector_make(std::cos(angle), std::sin(angle) * SUMMON_ARC_SQUASH); + } + uint32_t seed = Random(); + g_game->Spawn({.position = vector_add(vector_scale(direction, radius), npc.pos), + .spawner = &npc, + .type = summon.type, + .variant = summon.variant, + .seed = seed}); + npc.v2.x += 1; + } +} + +// Idle with its cooldown out: a summon in an arc, or an attack once out of summons or low on health (the Mausoleum's +// heart holding off while its shots crowd the room). +static void heart_cooldown_update(Entity_NPC& npc, std::span summons, const HeartSummon& summon) +{ + if (summon.type != 0 && npc.health / npc.maxHitPoints > LOW_HEALTH) + { + arc_summon(npc, summon); + npc.projectileCooldown = ATTACK_COOLDOWN; + if (npc.aiCounter == HEART_BEAT_FAST) summon_advance(npc, summons); + npc.i2 = npc.aiCounter; + return; + } + if (npc.subtype == HEART_MAUSOLEUM && is_shot_crowd(npc)) + { + npc.projectileCooldown = MAUSOLEUM_SHOT_WAIT; + return; + } + heart_attack_pick(npc); + npc.projectileCooldown = ATTACK_COOLDOWN; + summon_advance(npc, summons); + npc.i2 = npc.aiCounter; +} + +// Whether the heart's sweeping lasers still turn. +static bool is_sweeping() +{ + for (Entity* laser : entity_query(ENTITY_LASER, SWEEP_LASER_VARIANT)) + if (laser->spawnerType == ENTITY_MOMS_HEART) return true; + return false; +} + +// The animation of the phase: the beat of the pace, the comedown, or hiding (retracting, then beating hidden). +static void heart_animation_update(Entity_NPC& npc) +{ + ANM2& sprite = npc.sprite; + switch (npc.i1) + { + case HEART_BEAT_SLOW: + return sprite.Play("Heartbeat1"); + case HEART_BEAT_MEDIUM: + return sprite.Play("Heartbeat2"); + case HEART_BEAT_FAST: + return sprite.Play("Heartbeat3"); + case HEART_COMEDOWN: + return sprite.Play("HeartComedown"); + case HEART_HIDDEN: + { + bool isHiding = sprite.IsFinished("HeartRetracted") || sprite.IsPlaying("HeartHidingHeartbeat"); + return sprite.Play(isHiding ? "HeartHidingHeartbeat" : "HeartRetracted"); + } + default: + return; + } +} + +// Whether the heart's death takes an entity with it: an enemy (or a versus player) that holds the doors, not Mother's +// ball or a friendly one. +static bool is_death_target(Entity& entity) +{ + bool isFoe = (entity.type >= DEATH_TARGET_FIRST && entity.type <= DEATH_TARGET_LAST) || + (g_game->deathmatchManager.is_active() && entity.type == ENTITY_PLAYER); + return isFoe && entity.CanShutDoors() && entity.type != ENTITY_MOTHER_BALL && !entity.HasEntityFlags(FLAG_FRIENDLY); +} + +// The heart's death: its cry, every enemy left killed by it, its beating sprite killed, blood from the walls, and in +// the Mausoleum's secret exit the way to the Corpse. +static void heart_death(Entity_NPC& npc) +{ + Game& game = *g_game; + Room& room = *game.room; + npc_sound_play(SOUND_MOM_VOX_FILTERED_DEATH_1, 1, 2, champion_pitch_get(npc)); + EntityList_EL& entities = room.entityList.updateEL; + for (size_t i = 0; i < entities.size(); i++) + if (is_death_target(*entities[i])) entities[i]->Kill(EntityRef(&npc)); + if (npc.child) npc.child->Kill(EntityRef()); + room.bloodFromWallsDuration = HEART_DEATH_BLOOD_FRAMES; + room.bloodFromWallsCount = HEART_DEATH_BLOOD_DROPS; + + bool isMausoleum = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; + if (isMausoleum && !npc.HasEntityFlags(FLAG_FRIENDLY) && game.currentRoomIdx == ROOM_SECRET_EXIT_IDX) + reconstruction_missing("NpcAI::ENTITY_MOMS_HEART_mausoleum_death 004d64f0 (the Mausoleum's escape)"); +} + +// 004d48b0 NpcAI::ENTITY_MOMS_HEART: Mom's Heart and It Lives, set in the room's flesh. Beating at a pace its health +// sets, it calls enemies in arcs and fires attack patterns. It hides after a while (not at its fastest), raining shots +// and calling enemies from the top, and comes back down. Its beating sprite in front follows its phase. +void boss_moms_heart_update(Entity_NPC& npc) +{ + if (npc.variant == HEART_BEAT) return heart_beat_update(npc); + + int ticks = npc_ticks_get(npc); + if ((float)(Random() % HEART_HURT_VOICE_SPREAD + HEART_HURT_VOICE_MIN) < npc.pendingDamage) + { + int delay = (int)(Random() % HEART_HURT_VOICE_DELAY_SPREAD) + HEART_HURT_VOICE_DELAY; + npc.PlaySound(SOUND_MOM_VOX_FILTERED_HURT, 1, delay, false, 1); + } + if (npc.state == NPC_STATE_INIT) heart_start(npc); + + npc.friction *= 0.8f; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.pendingDamage > 0) npc.v1.x -= HIDE_HURT_STEP; + if (npc.aiCounter == HEART_BEAT_FAST) + { + float scale = random_unit() * BLEED_SCALE_SPREAD + BLEED_SCALE_MIN; + uint32_t seed = Random(); + Entity* splat = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = seed}); + splat->sprite.scale = vector_make(scale, scale); + splat->Update(); + } + npc.aiCounter = std::min((int)HEART_BEAT_FAST, 4 - (int)(npc.health / npc.maxHitPoints * 3 + 0.95f)); + if (npc.i2 != npc.aiCounter) npc.projectileDelay = 0; + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Heartbeat")) heartbeat_play(npc); + + std::span summons = summons_get(npc); + const HeartSummon& summon = summons[std::min((size_t)std::max(npc.projectileDelay, 0), summons.size() - 1)]; + if (npc.state == NPC_STATE_IDLE) heart_phase_update(npc, summons); + if (npc.i1 == HEART_HIDDEN) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.shadowSize = 0; + heart_attack_fire(npc, (int)npc.v1.y, npc.stateFrame); + hidden_summon(npc, summon); + } + else if (npc.i1 == HEART_COMEDOWN && npc.stateFrame < COMEDOWN_SOLID_FRAME) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.shadowSize = 0; + } + else + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.shadowSize = npc.config->shadowSize; + } + + bool isQuiet = g_game->room->GetAliveEnemiesCount() < ATTACK_CROWD && npc.state != NPC_STATE_ATTACK; + if (isQuiet || (npc.aiCounter == HEART_BEAT_FAST && summon.type == 0)) npc.projectileCooldown -= ticks; + if (npc.state == NPC_STATE_IDLE && npc.projectileCooldown < 0) heart_cooldown_update(npc, summons, summon); + else if (npc.state == NPC_STATE_ATTACK) + { + heart_attack_fire(npc, (int)npc.v1.y, npc.stateFrame); + npc.i1 = npc.aiCounter; + bool isLasering = (npc.v1.y == ATTACK_LASERS || npc.v1.y == MAUSOLEUM_ATTACK_LASERS) && is_sweeping(); + if (npc.stateFrame > HEART_ATTACK_FRAMES && !isLasering) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + } + } + + heart_animation_update(npc); + if (npc.isDead) heart_death(npc); + npc.stateFrame += ticks; +} + +// The Mom's Heart part of 006c4b30 (Entity_NPC::Update): its last shots burst in a ring of 14. +void boss_moms_heart_death_shots(Entity_NPC& npc) +{ + ProjectileParams params; + params.heightModifier = HEART_SHOT_HEIGHT; + params.scale = HEART_SHOT_SCALE; + params.fallingAccelModifier = HEART_SHOT_FALL_ACCEL; + params.fallingSpeedModifier = HEART_SHOT_FALL_SPEED; + npc.FireProjectiles(npc.pos, vector_make(DEATH_RING_SPEED, DEATH_RING), PROJECTILES_RING, params); +} diff --git a/src/boss_mr_fred.cpp b/src/boss_mr_fred.cpp new file mode 100644 index 0000000..a2ac4ef --- /dev/null +++ b/src/boss_mr_fred.cpp @@ -0,0 +1,250 @@ +#include "boss_ai.h" +#include "npc_caves.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include + +// Mr. Fred's states: the dig, the squirt, the barf of a Fred and the cord pulling a Homunculus. +constexpr int MR_FRED_DIG = NPC_STATE_ATTACK; +constexpr int MR_FRED_SQUIRT = NPC_STATE_ATTACK2; +constexpr int MR_FRED_BARF = NPC_STATE_SUMMON; +constexpr int MR_FRED_CORD = NPC_STATE_SPECIAL; + +// It rests 30 to 59 frames, then digs below 40 percent of rolls, squirts below 66 percent, else pulls a Homunculus's +// cord (7 times in 10), barfs a Fred while fewer than 4 are about, or digs. A dig keeps it under for 15 to 44 frames. +constexpr int MR_FRED_REST_MIN = 30; +constexpr uint32_t MR_FRED_REST_RANGE = 30; +constexpr float MR_FRED_DIG_ROLL = 0.4f; +constexpr float MR_FRED_SQUIRT_ROLL = 0.666f; +constexpr uint32_t MR_FRED_CORD_PERCENT = 30; +constexpr size_t MR_FRED_FRED_LIMIT = 4; +constexpr int MR_FRED_UNDER_MIN = 15; +constexpr uint32_t MR_FRED_UNDER_RANGE = 30; + +// The dig's and the squirt's shots, the Fred it barfs (3 at most for a Delirium form) and how long a cord holds. +constexpr int MR_FRED_CRY_FRAME = 1; +constexpr int MR_FRED_RISE_SHOT_FRAME = 5; +constexpr float MR_FRED_RISE_SHOT_SPEED = 8; +constexpr int MR_FRED_SQUIRT_FRAME = 15; +constexpr float MR_FRED_SQUIRT_SPEED = 10; +constexpr float MR_FRED_SQUIRT_SCALE = 2; +constexpr int MR_FRED_BARF_FRAME = 8; +constexpr int MR_FRED_DELIRIUM_FRED_LIMIT = 3; +constexpr float MR_FRED_MOUTH_X = -15; +constexpr float MR_FRED_MOUTH_Y = 1; +constexpr float MR_FRED_FRED_LANDING = -100; +constexpr int MR_FRED_CORD_HOLD = 150; + +// The room's Homunculi. +static std::vector homunculi_get() +{ + std::vector found; + for (Entity* entity : entity_query(ENTITY_HOMUNCULUS, -1)) found.push_back(static_cast(entity)); + return found; +} + +// Back to rest for 30 to 59 frames. +static void mr_fred_rest(Entity_NPC& npc) +{ + npc.state = NPC_STATE_IDLE; + npc.stateFrame = (int)(Random() % MR_FRED_REST_RANGE) + MR_FRED_REST_MIN; +} + +// Digs under for 15 to 44 frames. +static void mr_fred_dig_start(Entity_NPC& npc) +{ + npc.state = MR_FRED_DIG; + npc.sprite.Play("Dissapear"); + npc.stateFrame = (int)(Random() % MR_FRED_UNDER_RANGE) + MR_FRED_UNDER_MIN; +} + +// The rest: once its count runs out it picks an attack, unless it is a calm Delirium form. +static void mr_fred_idle(Entity_NPC& npc) +{ + if (npc_anim_is_done(npc)) npc.sprite.Play("Idle"); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + if (npc.stateFrame-- >= 0) return; + + float roll = random_unit(); + if (roll < MR_FRED_DIG_ROLL) return mr_fred_dig_start(npc); + if (roll < MR_FRED_SQUIRT_ROLL) + { + npc.state = MR_FRED_SQUIRT; + npc.sprite.Play("Squirt"); + return; + } + + bool isCrawling = false; + for (Entity_NPC* homunculus : homunculi_get()) isCrawling |= homunculus->state == NPC_STATE_MOVE; + if (isCrawling && Random() % 100 > MR_FRED_CORD_PERCENT) + { + npc.state = MR_FRED_CORD; + npc.sprite.Play("Cord"); + return; + } + if (entity_query(ENTITY_FRED, -1).size() >= MR_FRED_FRED_LIMIT) return mr_fred_dig_start(npc); + npc.state = MR_FRED_BARF; + npc.sprite.Play("Barf"); +} + +// The dig: it sinks, untouchable once its overlay hides, waits under, then rises with eight shots. +static void mr_fred_dig(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + bool isSinking = anim.animData && anim.animData->name == "Dissapear"; + int frame = npc.sprite.GetFrame(); + if (frame == MR_FRED_CRY_FRAME) npc.PlaySound(SOUND_MEATHEADSHOOT, 1, 2, false, 1); + const NullFrame* overlay = anim.animData ? anim.GetNullFrame("OverlayEffect") : nullptr; + bool isOverlayShown = overlay && overlay->isVisible; + + if (isSinking) + { + if (npc.entityCollisionClass != ENTCOLL_NONE && !isOverlayShown) + { + npc.isInvincible = true; + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (!npc_anim_is_done(npc)) return; + npc.isVisible = false; + if (npc.stateFrame-- >= 0) return; + npc.isVisible = true; + npc.sprite.Play("Appear"); + return; + } + + if (npc.entityCollisionClass == ENTCOLL_NONE && isOverlayShown) + { + npc.isInvincible = false; + npc.entityCollisionClass = ENTCOLL_ALL; + } + if (npc.sprite.GetFrame() == MR_FRED_RISE_SHOT_FRAME) + return npc.FireProjectiles(npc.pos, vector_make(MR_FRED_RISE_SHOT_SPEED, 0), PROJECTILES_EIGHT, + ProjectileParams()); + if (!npc_anim_is_done(npc)) return; + npc.state = NPC_STATE_IDLE; + npc.sprite.Play("Idle"); + npc.stateFrame = (int)(Random() % MR_FRED_REST_RANGE) + MR_FRED_REST_MIN; +} + +// The frame its animation shows, rounded down. +static int mr_fred_frame(Entity_NPC& npc) +{ + return (int)std::floor(npc.sprite.animState.animFrame); +} + +// The squirt: a grunt, then four big red creeping shots. +static void mr_fred_squirt(Entity_NPC& npc) +{ + if (npc.sprite.animState.animData) + { + if (mr_fred_frame(npc) == MR_FRED_CRY_FRAME) npc.PlaySound(SOUND_MONSTER_GRUNT_2, 1, 2, false, 1); + if (mr_fred_frame(npc) == MR_FRED_SQUIRT_FRAME) + { + npc.PlaySound(SOUND_BOSS_LITE_ROAR, 1, 2, false, 1); + ProjectileParams params; + params.bulletFlags |= PROJECTILE_ACID_RED | PROJECTILE_RED_CREEP; + params.scale = MR_FRED_SQUIRT_SCALE; + npc.FireProjectiles(npc.pos, vector_make(MR_FRED_SQUIRT_SPEED, 0), PROJECTILES_PLUS, params); + return; + } + if (npc.sprite.animState.isPlaying) return; + } + mr_fred_rest(npc); +} + +// The barf: a Fred thrown out to land beside it. +static void mr_fred_barf(Entity_NPC& npc) +{ + if (npc.sprite.animState.animData) + { + if (mr_fred_frame(npc) == MR_FRED_BARF_FRAME) + { + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && + npc.CountRelatedEntities(ENTITY_FRED, 0, nullptr) >= MR_FRED_DELIRIUM_FRED_LIMIT) + return; + npc.PlaySound(SOUND_BOSS_SPIT_BLOB_BARF, 1, 2, false, 1); + auto* fred = static_cast( + g_game->Spawn({.position = vector_make(npc.pos.x + MR_FRED_MOUTH_X, npc.pos.y + MR_FRED_MOUTH_Y), + .spawner = &npc, + .type = ENTITY_FRED, + .seed = Random()})); + Vector landing = vector_make(npc.pos.x + MR_FRED_FRED_LANDING, npc.pos.y + 0); + fred->targetPosition = room_free_pickup_position_find({.position = landing}); + fred->sprite.Play("JumpDownHead"); + fred->state = NPC_STATE_JUMP; + fred->Update(); + return; + } + if (npc.sprite.animState.isPlaying) return; + } + mr_fred_rest(npc); +} + +// The cord: once pulled, the first crawling Homunculus is reeled in. +static void mr_fred_cord(Entity_NPC& npc) +{ + if (npc.sprite.animState.animData) + { + if (mr_fred_frame(npc) == MR_FRED_CRY_FRAME) npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + } + for (Entity_NPC* homunculus : homunculi_get()) + if (homunculus->state == NPC_STATE_MOVE) + { + homunculus->i2 = 1; + break; + } + mr_fred_rest(npc); + npc.sprite.Play("Idle"); +} + +// 00486db0 NpcAI::ENTITY_MR_FRED: Mr. Fred stays rooted where it appeared and only the players' explosions hurt it. It +// digs under and rises with a burst of shots, squirts red creeping shots, barfs out Freds and pulls Homunculi in. +void boss_mr_fred_update(Entity_NPC& npc) +{ + npc.velocity = {}; + if (npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + { + bool isPlayers = event.source.type == ENTITY_PLAYER || event.source.spawnerType == ENTITY_PLAYER || + event.source.spawnerType == ENTITY_FAMILIAR; + if (event.damageFlags & DAMAGE_EXPLOSION && !isPlayers && !(event.damageFlags & DAMAGE_TNT)) + event.damage = 0; + } + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_IDLE; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.stateFrame = (int)(Random() % MR_FRED_REST_RANGE) + MR_FRED_REST_MIN; + npc.v1 = npc.pos; + npc.UpdateDirtColor(true); + break; + case NPC_STATE_IDLE: + mr_fred_idle(npc); + break; + case MR_FRED_DIG: + mr_fred_dig(npc); + break; + case MR_FRED_SQUIRT: + mr_fred_squirt(npc); + break; + case MR_FRED_BARF: + mr_fred_barf(npc); + break; + case MR_FRED_CORD: + mr_fred_cord(npc); + break; + } + npc.pos = npc.v1; + + if (npc.i1 <= 0) return; + npc.i1 = 0; + for (Entity_NPC* homunculus : homunculi_get()) + if (homunculus->stateFrame < MR_FRED_CORD_HOLD) + { + homunculus->stateFrame = 0; + npc.i1++; + } +} diff --git a/src/console.cpp b/src/console.cpp index 2aa8ddc..153132a 100644 --- a/src/console.cpp +++ b/src/console.cpp @@ -1,16 +1,20 @@ #include "console.h" +#include "entity_config.h" #include "entity_pickup.h" #include "entity_player.h" #include "font.h" #include "game.h" +#include "item_config.h" #include "kage_graphics.h" #include "kage_input.h" +#include "level.h" #include "lua_engine.h" #include "manager.h" #include "menu_manager.h" #include "platform.h" #include "render_passes.h" #include "room.h" +#include "room_config.h" #include #include #include @@ -18,6 +22,7 @@ #include #include #include +#include // The GLFW keys the console reads. enum ConsoleKey : int @@ -76,6 +81,44 @@ constexpr uint32_t SUGGESTION_COLOR = 0xff8a2be2; constexpr uint32_t INPUT_COLOR = 0xffadff2f; constexpr uint32_t CURSOR_EDGE_COLOR = 0xff000000; +// The suggestions: the commands offered for the first word (0x00c5cab8 and the six FillOmnicomplete adds), and the +// lists offered after gridspawn, debug, curse and combo. The original lost a comma after the fireplace. +constexpr std::string_view SUGGESTED_COMMANDS[] = { + "spawn", "goto", "stage", "gridspawn", "debug", "giveitem", "remove", "costumetest", "time", "restart", + "listcollectibles", "repeat", "clearseeds", "seed", "challenge", "combo", "cutscene", "clearcache", "macro", + "playsfx", "prof", "profstop", "curse", "reseed", "eggs", "copy", "clear", "metro", "delirious", "luarun", + "luamem", "luamod", "reloadshaders", "reloadfx", "lua"}; +constexpr std::string_view GRID_SUGGESTIONS[] = { + "1000:Rock", "1001:Rock Bomb", "1002:Alt Rock", "1003:Tainted Rock", "1004:Super Tainted Rock", "1300:TNT", + "1400:Fireplace1498:White Poop", "1497:Black Poop", "1496:Golden Poop", "1495:Chunky Poop", "1494:Rainbow Poop", + "1490:Red Poop", "1500:Brown Poop", "1900:Block", "1930:Spikes", "1931:On/Off Spikes", "1940:Spider Web", + "3000:Pit", "4000:Lock", "4500:Pressure Plate", "4500.1:Reward Plate", "5000:Devil Statue", "5001:Angel Statue", + "9000:Trap Door", "9100:Staircase", "10000:Gravity"}; +constexpr std::string_view DEBUG_FLAG_SUGGESTIONS[] = { + "1:Entity Positions", "2:Grid", "3:Infinite HP", "4:High Damage", "5:Show Room Info", "6:Show Hitspheres", + "7:Show Damage Values", "8:Infinite Item Charges", "9:High Luck", "10:Quick Kill", "11:Grid Info", + "12:Player Item Info", "13:Show Grid Collision Points", "14:Show Lua Memory Usage"}; +constexpr std::string_view CURSE_SUGGESTIONS[] = {"0:None", "1:Darkness", "2:Labyrinth", "4:Lost", "8:Unknown", + "16:Cursed", "32:Maze", "64:Blind", "128:Giant"}; +constexpr std::string_view COMBO_POOL_SUGGESTIONS[] = { + "0:Treasure", "1:Shop", "2:Boss", "3:Devil", "4:Angel", "5:Secret", "6:Library", "7:Challenge", "8:Golden_Chest", + "9:Red_Chest", "10:Beggar", "11:Demon_Beggar", "12:Curse", "13:Key_Master", "14:Boss_Rush", "15:Dungeon"}; +constexpr std::string_view ITEM_COMMANDS[] = {"giveitem", "g", "remove", "r", "giveitem2", "g2", "remove2", "r2"}; +constexpr std::string_view COMMAND_KILL = "kill"; +constexpr int CUTSCENE_SUGGESTION_LAST = 26; +constexpr int ROOM_TYPE_SUGGESTION_END = 31; +constexpr int ROOM_DIFFICULTY_MIN = 1; +constexpr int ROOM_DIFFICULTY_MAX = 10; +// Past this many rooms, the goto suggestions leave out a room named as the one before. +constexpr size_t ROOM_SUGGESTIONS_UNMERGED = 7; + +// Whether the item suggestions list every kind of item or only collectibles (the metro command). +enum ItemSuggestions +{ + SUGGEST_ITEMS, + SUGGEST_COLLECTIBLES +}; + constexpr float DEFAULT_LINE_HEIGHT = 15; constexpr float SMALL_LINE_HEIGHT = 12; constexpr float TINY_LINE_HEIGHT = 8; @@ -657,10 +700,248 @@ void Console::input_submit() scroll = scroll_min_get(); } -// 00686da0 Fills the suggestions for what the input is being typed into: commands, then their arguments. +// What the input asks suggestions for: its words, the words after the command lowercased and joined, and the +// suggestions found, each ended by '#'. +struct SuggestionQuery +{ + std::vector words; + std::string found{}; + std::string typed{}; +}; + +// The text in lowercase. +static std::string text_lower(std::string text) +{ + std::ranges::transform(text, text.begin(), [](unsigned char c) { return (char)std::tolower(c); }); + return text; +} + +// Whether text starts with words[index], or there is no such word. +static bool is_word_prefix(const std::vector& words, size_t index, std::string_view text) +{ + return words.size() <= index || text.starts_with(words[index]); +} + +// Adds a suggestion. +static void suggestion_add(SuggestionQuery& query, std::string_view text) +{ + query.found += text; + query.found += '#'; +} + +// Adds the entries of a list that start with the second word. +static void list_suggestions_add(SuggestionQuery& query, std::span list) +{ + for (std::string_view entry : list) + if (is_word_prefix(query.words, 1, entry)) suggestion_add(query, entry); +} + +// Adds "id:name" when the id starts with the second word or the lowercased name holds the words after the command. +static void named_suggestion_add(SuggestionQuery& query, std::string_view id, std::string_view name) +{ + if (is_word_prefix(query.words, 1, id) || text_lower(std::string(name)).find(query.typed) != std::string::npos) + suggestion_add(query, std::string(id) + ":" + std::string(name)); +} + +// spawn: every entity as type.variant (and subtype when it has one) and name, skipping the cards past the first. With +// a dot typed, a boss lists one subtype per champion color. +static void entity_suggestions_add(SuggestionQuery& query) +{ + bool isSubtyped = query.words.size() == 2 && text_split(query.words[1], '.').size() > 1; + + for (auto& [key, entity] : g_manager->entityConfig.entities) + { + if (entity.id == ENTITY_PICKUP && entity.variant == PICKUP_TAROTCARD && entity.subtype != 0) continue; + + int subtypes = isSubtyped ? (int)entity.bossColors.size() + 1 : 1; + for (int subtype = 0; subtype < subtypes; subtype++) + { + bool isFull = subtypes > 1 || entity.subtype != 0; + std::string id = std::to_string(entity.id) + "." + std::to_string(entity.variant); + if (isFull) id += "." + std::to_string(subtypes > 1 ? subtype : entity.subtype); + named_suggestion_add(query, id, entity.GetName(NAME_LANGUAGE_ENGLISH)); + } + } +} + +// delirious: the bosses Delirious becomes, then kill. +static void delirious_suggestions_add(SuggestionQuery& query) +{ + for (const DeliriousBoss& boss : DELIRIOUS_BOSSES) + { + EntityConfig_Entity* entity = g_manager->entityConfig.GetEntity(boss.type, boss.variant, 0); + named_suggestion_add(query, std::to_string(boss.type) + "." + std::to_string(boss.variant), + entity ? entity->GetName(NAME_LANGUAGE_ENGLISH) : "unknown"); + } + if (query.words.size() < 2 || COMMAND_KILL.find(query.words[1]) != std::string_view::npos) + suggestion_add(query, COMMAND_KILL); +} + +// giveitem and remove: collectibles, trinkets, pill effects and cards. metro: only the collectibles. +static void item_suggestions_add(SuggestionQuery& query, ItemSuggestions kinds) +{ + ItemConfig& config = g_manager->itemConfig; + + for (int id = 0; id < (int)config.collectibles.size(); id++) + if (ItemConfig_Item* item = config.GetCollectible(id)) + named_suggestion_add(query, "c" + std::to_string(id), item->GetLocalizedName(NAME_LANGUAGE_ENGLISH)); + if (kinds == SUGGEST_COLLECTIBLES) return; + + for (uint32_t id = 0; id < config.trinkets.size(); id++) + if (ItemConfig_Item* item = config.GetTrinket(id)) + named_suggestion_add(query, "t" + std::to_string(id), item->GetLocalizedName(NAME_LANGUAGE_ENGLISH)); + auto pocket_add = [&](const std::string& id, PocketItemConfig* pocket) { + if (pocket && is_word_prefix(query.words, 1, id)) + suggestion_add(query, id + ":" + pocket->GetName(NAME_LANGUAGE_ENGLISH)); + }; + for (int id = 0; id < (int)config.pillEffects.size(); id++) + pocket_add("p" + std::to_string(id), config.GetPillEffect(id)); + for (int id = 0; id < (int)config.cards.size(); id++) pocket_add("k" + std::to_string(id), config.GetCard(id)); +} + +// stage: each floor with its alternate letters and display names. As in the original, typing a filter hides some +// letters that show without one. +static void stage_suggestions_add(SuggestionQuery& query) +{ + bool isGreed = g_game->IsGreedMode(); + bool isFiltered = query.words.size() >= 2; + + for (int stage = STAGE_BASEMENT_I; stage <= (isGreed ? STAGE_ULTRA_GREED : STAGE_HOME); stage++) + { + auto add = [&](StageType type, std::string_view letter, bool isShown) { + std::string id = std::to_string(stage) + std::string(letter); + if (!isShown || !is_word_prefix(query.words, 1, id)) return; + int stageId = RoomConfig::GetStageID(stage, type, ROOM_MODE_CURRENT); + suggestion_add(query, id + ":" + g_game->roomConfig.GetStageDisplayName(stageId, NAME_LANGUAGE_ENGLISH)); + }; + bool isGreedAltShown = !isFiltered || stage < STAGE_GREED_SHOP; + + add(STAGETYPE_ORIGINAL, "", true); + if (isGreed) + { + add(STAGETYPE_WOTL, "a", isGreedAltShown); + add(STAGETYPE_AFTERBIRTH, "b", isGreedAltShown); + continue; + } + add(STAGETYPE_WOTL, "a", !isFiltered || (stage != STAGE_BLUE_WOMB && stage != STAGE_VOID)); + add(STAGETYPE_AFTERBIRTH, "b", stage < STAGE_BLUE_WOMB); + add(STAGETYPE_REPENTANCE, "c", stage < STAGE_BLUE_WOMB); + add(STAGETYPE_REPENTANCE_B, "d", stage < STAGE_WOMB_I); + } +} + +// goto and forceroom: s, d or x, then for d the variant range of the floor's normal rooms, for s and x the room types, +// then the rooms of that type in the special set (s) or the floor's (x). Past 7 rooms, rooms named as the one before +// are left out. +static void room_suggestions_add(SuggestionQuery& query) +{ + if (query.words.size() < 2) + { + query.found = "s#d#x"; + return; + } + + std::vector parts = text_split(query.words[1], '.'); + size_t depth = parts.size() + (query.words[1].ends_with('.') ? 1 : 0); + bool isSet = !parts.empty() && (parts[0] == "s" || parts[0] == "x"); + RoomQuery roomQuery{.maxDifficulty = ROOM_DIFFICULTY_MAX, .minDifficulty = ROOM_DIFFICULTY_MIN}; + + if (depth == 2 && parts[0] == "d") + { + roomQuery.stageId = g_game->GetStageID(); + uint32_t maxVariant = 0; + uint32_t minVariant = UINT32_MAX; + for (RoomConfig_Room* room : g_game->roomConfig.GetRooms(roomQuery)) + { + minVariant = std::min(minVariant, (uint32_t)room->variant); + maxVariant = std::max(maxVariant, (uint32_t)room->variant); + } + query.found = std::to_string(minVariant) + ".." + std::to_string(maxVariant); + } + else if (depth == 2 && isSet) + { + for (int type = ROOM_DEFAULT; type < ROOM_TYPE_SUGGESTION_END; type++) + if (std::string_view name = room_type_name(type); !name.empty() && is_word_prefix(parts, 1, name)) + suggestion_add(query, name); + } + else if (depth == 3 && isSet) + { + roomQuery.type = RoomConfig::room_type_find(parts[1]); + roomQuery.stageId = parts[0] == "x" ? g_game->GetStageID() : STAGE_ID_SPECIAL_ROOMS; + std::vector rooms = g_game->roomConfig.GetRooms(roomQuery); + std::erase_if(rooms, [&](RoomConfig_Room* room) { + if (is_word_prefix(parts, 2, std::to_string(room->variant))) return false; + return text_lower(room->name).find(text_lower(parts[2])) == std::string::npos; + }); + + std::string lastName; + for (RoomConfig_Room* room : rooms) + { + if (rooms.size() > ROOM_SUGGESTIONS_UNMERGED && !room->name.empty() && room->name == lastName) continue; + lastName = room->name; + suggestion_add(query, std::to_string(room->variant) + (room->name.empty() ? "" : ":" + room->name)); + } + } +} + +// The suggestions for the words after a command. A few commands only suggest for their second word. +static void argument_suggestions_add(SuggestionQuery& query, bool isSecondWord) +{ + std::string_view command = query.words[0]; + bool isItemCommand = std::ranges::find(ITEM_COMMANDS, command) != std::end(ITEM_COMMANDS); + + if (command == "spawn") entity_suggestions_add(query); + else if (command == "delirious") delirious_suggestions_add(query); + else if (isSecondWord && (command == "goto" || command == "forceroom")) room_suggestions_add(query); + else if (isSecondWord && command == "stage") stage_suggestions_add(query); + else if (isSecondWord && command == "gridspawn") list_suggestions_add(query, GRID_SUGGESTIONS); + else if (isSecondWord && command == "debug") list_suggestions_add(query, DEBUG_FLAG_SUGGESTIONS); + else if (isSecondWord && command == "curse") list_suggestions_add(query, CURSE_SUGGESTIONS); + else if (isItemCommand) item_suggestions_add(query, SUGGEST_ITEMS); + else if (isSecondWord && command == "combo") + { + if (query.words.size() < 2) return list_suggestions_add(query, COMBO_POOL_SUGGESTIONS); + std::vector parts = text_split(query.words[1], '.'); + if (parts.size() != 1 || parts[0].empty()) return; + int pool = std::atoi(parts[0].c_str()); + if (pool >= 0 && pool < (int)std::size(COMBO_POOL_SUGGESTIONS)) + suggestion_add(query, COMBO_POOL_SUGGESTIONS[pool]); + } + else if (isSecondWord && command == "cutscene") + { + for (int id = 1; id <= CUTSCENE_SUGGESTION_LAST; id++) + if (is_word_prefix(query.words, 1, std::to_string(id))) + suggestion_add(query, std::to_string(id) + ":" + g_manager->cutsceneManager.entries[id - 1].name); + } + else if (command == "metro") item_suggestions_add(query, SUGGEST_COLLECTIBLES); +} + +// 00686da0 Fills the suggestions for what the input is being typed into: the commands for the first word, then what +// each command takes, laid out on the six rows as many as fit the screen's width. void Console::FillOmnicomplete() { - reconstruction_missing("Console::FillOmnicomplete 00686da0"); + SuggestionQuery query{.words = text_split(input, ' ')}; + size_t wordCount = query.words.size() + (input.empty() || input.back() == ' ' ? 1 : 0); + + for (size_t i = 1; i < query.words.size(); i++) query.typed += (i > 1 ? " " : "") + query.words[i]; + query.typed = text_lower(query.typed); + if (wordCount == 1) + { + for (std::string_view command : SUGGESTED_COMMANDS) + if (is_word_prefix(query.words, 0, command)) suggestion_add(query, command); + } + else if (wordCount >= 2) argument_suggestions_add(query, wordCount == 2); + + std::vector entries = text_split(query.found, '#'); + Font& font = *console_text_get().font; + size_t next = 0; + for (std::string& row : suggestions) + { + row.clear(); + while (next < entries.size() && font.GetStringWidth(row + entries[next]) <= g_screenWidth - WRAP_MARGIN) + row += entries[next++] + "#"; + std::ranges::replace(row, '#', ' '); + } } // 00686950 Starts closing the console when it shows, gives the hotkeys back and saves the command history, removing diff --git a/src/console.h b/src/console.h index 34c9415..0914a75 100644 --- a/src/console.h +++ b/src/console.h @@ -18,6 +18,8 @@ constexpr uint32_t CONSOLE_ECHO = 0xff808080; constexpr int CONSOLE_FADE_FRAMES = 150; constexpr int CONSOLE_SUGGESTION_COUNT = 6; constexpr int DELIRIOUS_BOSS_COUNT = 59; +// The language the console names things in. +constexpr int NAME_LANGUAGE_ENGLISH = 0; // Where the console is in sliding open and closed. Nothing known sets CONSOLE_REOPEN, which snaps back to open. enum ConsoleState : int diff --git a/src/console_commands.cpp b/src/console_commands.cpp index 7cc9ac3..5dc1d0e 100644 --- a/src/console_commands.cpp +++ b/src/console_commands.cpp @@ -50,7 +50,6 @@ constexpr int DEBUG_FLAG_LUCK = 8; constexpr int TIME_FRAME_RATE = 30; constexpr int GRID_PATH_SPAWN = 900; constexpr int GRID_INDEX_COUNT = 448; -constexpr int NAME_LANGUAGE_ENGLISH = 0; constexpr int REPEAT_MAX = 10000; constexpr int TIME_MINUTE_SECONDS = 60; constexpr int TEST_BOSS_POOL_DRAWS = 10000; @@ -414,7 +413,7 @@ static void gridspawn_run(ConsoleCommand& command) if (command.words.size() > 2) { gridIndex = word_int(command, 2); - reconstruction_missing("Room::RemoveGridEntity 0081e930"); + room.RemoveGridEntity(gridIndex, 0, DECORATION_REMOVED); } room_entry_spawn(room, entry, {.gridIndex = gridIndex, .seed = Random()}); if (GridEntity* grid = room.GetGridEntity(gridIndex)) grid->PostInit(); diff --git a/src/entity.cpp b/src/entity.cpp index 798e845..550e7d2 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -1243,12 +1243,6 @@ int Entity::get_water_splash_variant() reconstruction_missing("Entity::get_water_splash_variant 006b6ed0"); } -// 006b7be0 -Entity_NPC* Entity::GiveMinecart(const Vector&, const Vector&) -{ - reconstruction_missing("Entity::GiveMinecart 006b7be0"); -} - // 007079c0 void Entity::RemoveWithPoof(Entity*) { diff --git a/src/entity.h b/src/entity.h index 2a10d08..5e18568 100644 --- a/src/entity.h +++ b/src/entity.h @@ -35,6 +35,7 @@ enum EntityType : int ENTITY_CHARGER = 23, ENTITY_GLOBIN = 24, ENTITY_BOOMFLY = 25, + ENTITY_MAW = 26, ENTITY_CHUB = 28, ENTITY_HOPPER = 29, ENTITY_BOIL = 30, @@ -54,13 +55,20 @@ enum EntityType : int ENTITY_GREED = 50, ENTITY_FLAMING_HOPPER = 54, ENTITY_LEECH = 55, + ENTITY_LUMP = 56, + ENTITY_MEMBRAIN = 57, ENTITY_PARA_BITE = 58, + ENTITY_FRED = 59, ENTITY_SUCKER = 61, ENTITY_PIN = 62, ENTITY_FAMINE = 63, ENTITY_FISTULA_BIG = 71, ENTITY_FISTULA_MEDIUM = 72, ENTITY_FISTULA_SMALL = 73, + ENTITY_BLASTOCYST_BIG = 74, + ENTITY_BLASTOCYST_MEDIUM = 75, + ENTITY_BLASTOCYST_SMALL = 76, + ENTITY_EMBRYO = 77, ENTITY_MOMS_HEART = 78, ENTITY_GEMINI = 79, ENTITY_MOTER = 80, @@ -88,8 +96,11 @@ enum EntityType : int ENTITY_WALL_HUGGER = 218, ENTITY_SQUIRT = 220, ENTITY_RING_OF_FLIES = 222, + ENTITY_DINGA = 223, ENTITY_SKINNY = 226, ENTITY_BONY = 227, + ENTITY_HOMUNCULUS = 228, + ENTITY_NERVE_ENDING = 231, ENTITY_GAPING_MAW = 235, ENTITY_BROKEN_GAPING_MAW = 236, ENTITY_GURGLING = 237, @@ -102,6 +113,8 @@ enum EntityType : int ENTITY_DART_FLY = 256, ENTITY_GATE = 263, ENTITY_MEGA_FATTY = 264, + ENTITY_CAGE = 265, + ENTITY_MAMA_GURDY = 266, ENTITY_POLYCEPHALUS = 269, ENTITY_URIEL = 271, ENTITY_GABRIEL = 272, @@ -111,6 +124,7 @@ enum EntityType : int ENTITY_BLACK_GLOBIN = 278, ENTITY_BLACK_GLOBIN_HEAD = 279, ENTITY_BLACK_GLOBIN_BODY = 280, + ENTITY_FLESH_DEATHS_HEAD = 286, ENTITY_ULCER = 289, ENTITY_PITFALL = 291, ENTITY_MOVABLE_TNT = 292, @@ -119,21 +133,28 @@ enum EntityType : int ENTITY_HUSH_GAPER = 297, ENTITY_POISON_MIND = 301, ENTITY_STONEY = 302, + ENTITY_BLISTER = 303, + ENTITY_PORTAL = 306, ENTITY_STAIN = 401, ENTITY_LITTLE_HORN = 404, ENTITY_ULTRA_GREED = 406, ENTITY_HUSH = 407, + ENTITY_SISTERS_VIS = 410, ENTITY_BIG_HORN = 411, ENTITY_DELIRIUM = 412, + ENTITY_MATRIARCH = 413, ENTITY_BLOOD_PUPPY = 802, ENTITY_BISHOP = 805, ENTITY_WILLO = 808, ENTITY_SMALL_LEECH = 810, + ENTITY_DEEP_GAPER = 811, + ENTITY_BLURB = 813, ENTITY_STRIDER = 814, ENTITY_ROCK_SPIDER = 818, ENTITY_FLY_BOMB = 819, ENTITY_SMALL_MAGGOT = 853, ENTITY_PUSTULE = 861, + ENTITY_CYST = 862, ENTITY_DARK_ESAU = 866, ENTITY_DRIP = 870, ENTITY_SPLURT = 871, @@ -161,6 +182,7 @@ enum EntityType : int ENTITY_BEAST = 951, ENTITY_GENERIC_PROP = 960, ENTITY_FROZEN_ENEMY = 963, + ENTITY_DUMMY = 964, ENTITY_MINECART = 965, ENTITY_EFFECT = 1000, ENTITY_TEXT = 9001 @@ -170,6 +192,17 @@ enum EntityType : int constexpr int ENTITY_FIRST_ENEMY = 10; constexpr int ENTITY_LAST_ENEMY = 999; +// An entity's fall into a pit (pitfallState): falling, at the bottom, climbing back out, or gone through to another +// room. +enum PitfallState : int +{ + PITFALL_NONE, + PITFALL_FALLING, + PITFALL_DOWN, + PITFALL_CLIMBING, + PITFALL_GONE +}; + // Lua's EntityFlag: the state and status effects an entity carries. enum EntityFlag : uint64_t { @@ -256,16 +289,19 @@ enum DamageFlag : uint64_t DAMAGE_SPAWN_FLY = 1ull << 14, DAMAGE_POISON_BURN = 1ull << 15, DAMAGE_CURSED_DOOR = 1ull << 16, + DAMAGE_PITFALL = 1ull << 19, DAMAGE_CHEST = 1ull << 20, DAMAGE_BOOGER = 1ull << 22, DAMAGE_SPAWN_BLACK_HEART = 1ull << 23, DAMAGE_CRUSH = 1ull << 24, + DAMAGE_NO_MODIFIERS = 1ull << 25, DAMAGE_SPAWN_RED_HEART = 1ull << 26, DAMAGE_SPAWN_COIN = 1ull << 27, DAMAGE_NO_PENALTIES = 1ull << 28, DAMAGE_IGNORE_ARMOR = 1ull << 30, DAMAGE_SPAWN_CARD = 1ull << 31, DAMAGE_SPAWN_RUNE = 1ull << 32, + DAMAGE_CHAMPION_REWARD = 1ull << 33, DAMAGE_THROUGH_COOLDOWN = 1ull << 35 }; diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index ee4ff21..3315dac 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -2,6 +2,7 @@ #include "entity_effect_combat.h" #include "entity_list.h" #include "entity_player.h" +#include "entity_player_forgotten.h" #include "game.h" #include "kage_graphics.h" #include "log.h" @@ -9,6 +10,7 @@ #include "manager.h" #include "room.h" #include "sfx_manager.h" +#include "mines.h" #include #include #include @@ -51,13 +53,52 @@ static bool is_listed(const std::array& list, int value) return std::find(list.begin(), list.end(), value) != list.end(); } +// A timer's callback, how many frames apart it runs and how many more times. None runs once, then it goes. +struct TimerData : Entity_Effect::ExtraData +{ + void (*callback)(Entity_Effect* timer) = nullptr; + uint32_t delay = 1; + int times = 1; +}; + +// The timer part of 005cdb20 (Init): a timer is invisible, never overwritten, and has nothing to run yet. +static void timer_init(Entity_Effect& timer) +{ + timer.isVisible = false; + timer.extraData = std::make_shared(); + timer.AddEntityFlags(FLAG_DONT_OVERWRITE); +} + +// The timer part of 005d4380 (Update): runs the callback every delay frames of its life until its times run out, then +// removes itself. Without a callback it goes at once. +// A delay of 0 divided by zero in the original. Here it runs every frame. +static EffectUpdateEnd timer_update(Entity_Effect& timer) +{ + auto& data = static_cast(*timer.extraData); + if (!data.callback) + { + timer.Remove(); + return EFFECT_UPDATE_RETURN; + } + if (data.delay && (uint32_t)timer.FrameCount() % data.delay != 0) return EFFECT_UPDATE_FINISH; + + data.callback(&timer); + if (data.times > 0) data.times--; + if (data.times != 0) return EFFECT_UPDATE_FINISH; + timer.Remove(); + return EFFECT_UPDATE_RETURN; +} + +constexpr EffectBehaviour TIMER_BEHAVIOURS[] = {{EFFECT_TIMER, timer_init, timer_update}}; + // The behaviour of a variant one of the groups hands out, indexed once by variant, or none. static const EffectBehaviour* behaviour_find(int variant) { static const std::array TABLE = [] { std::array table{}; for (auto group : {ambient_effect_behaviours(), hazard_effect_behaviours(), floor_effect_behaviours(), - beam_effect_behaviours()}) + beam_effect_behaviours(), player_effect_behaviours(), mines_effect_behaviours(), + std::span(TIMER_BEHAVIOURS)}) for (const EffectBehaviour& behaviour : group) table[behaviour.variant] = behaviour; return table; }(); @@ -185,7 +226,7 @@ void Entity_Effect::Init(int entityType, int entityVariant, int entitySubType, u if (behaviour->init) behaviour->init(*this); } else if (is_combat_effect(variant)) combat_effect_init(*this); - else reconstruction_missing("Entity_Effect::Init 005cdb20: this effect variant"); + else if (variant < EFFECT_VARIANT_LIMIT) reconstruction_missing("Entity_Effect::Init 005cdb20: this effect variant"); if (!isExists) return; sprite.LoadGraphics(); @@ -241,7 +282,7 @@ void Entity_Effect::Update() if (behaviour->update) end = behaviour->update(*this); } else if (is_combat_effect(variant)) end = combat_effect_update(*this); - else reconstruction_missing("Entity_Effect::Update 005d4380: this effect variant"); + else if (variant < EFFECT_VARIANT_LIMIT) reconstruction_missing("Entity_Effect::Update 005d4380: this effect variant"); if (end == EFFECT_UPDATE_RETURN) return; if (timeout > 0 && --timeout < 1) isDead = true; @@ -347,10 +388,18 @@ void Entity_Effect::moonlight_timer_callback(int) reconstruction_missing("Entity_Effect::moonlight_timer_callback 006073f0"); } -// 0060af00 -Entity_Effect* Entity_Effect::CreateTimer(void*, uint32_t, uint32_t, bool) +// 0060af00 Spawns a timer running a callback (taking the timer) every delay frames, times more times after the first +// (0 for once), kept across rooms when persistent. +Entity_Effect* Entity_Effect::CreateTimer(void* fn, uint32_t delay, uint32_t times, bool isPersistent) { - reconstruction_missing("Entity_Effect::CreateTimer 0060af00"); + auto* timer = static_cast( + g_game->Spawn({.type = ENTITY_EFFECT, .variant = EFFECT_TIMER, .seed = Random()})); + auto& data = static_cast(*timer->extraData); + data.callback = reinterpret_cast(fn); + data.delay = delay; + data.times = (int)times; + if (isPersistent) timer->AddEntityFlags(FLAG_PERSISTENT); + return timer; } // 0060b0d0 diff --git a/src/entity_effect.h b/src/entity_effect.h index 7fc0f4d..47cc9a3 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -71,6 +71,7 @@ enum EffectVariant : int EFFECT_LASER_IMPACT = 50, EFFECT_HOT_BOMB_FIRE = 51, EFFECT_PLAYER_CREEP_GREEN = 53, + EFFECT_SPIKE = 55, EFFECT_CREEP_BROWN = 56, EFFECT_PULLING_EFFECT = 57, EFFECT_POOP_PARTICLE = 58, @@ -108,12 +109,14 @@ enum EffectVariant : int EFFECT_SPAWNER = 120, EFFECT_LIGHT = 121, EFFECT_BIG_HORN_HOLE_HELPER = 122, + EFFECT_HALO = 123, EFFECT_TAR_BUBBLE = 124, EFFECT_BIG_HORN_HAND = 125, EFFECT_TECH_DOT = 126, EFFECT_BIG_SPLASH = 132, EFFECT_PEDESTAL_RIPPLE = 134, EFFECT_GRID_ENTITY_PROJECTILE_HELPER = 136, + EFFECT_MINES_TRAPDOOR_COVER = 139, EFFECT_BACKDROP_DECORATION = 140, EFFECT_SMOKE_CLOUD = 141, EFFECT_ENEMY_GHOST = 144, diff --git a/src/entity_factory.cpp b/src/entity_factory.cpp index 86f9ae3..b4c0bd7 100644 --- a/src/entity_factory.cpp +++ b/src/entity_factory.cpp @@ -29,13 +29,10 @@ constexpr int SPAWN_STATUS_FRAMES = 90; // The entity types, variants and boss ids spawning and layouts single out. constexpr int ENTITY_HORF = 12; -constexpr int ENTITY_MAW = 26; constexpr int ENTITY_HOST = 27; constexpr int ENTITY_FLAMINGHOPPER = 54; -constexpr int ENTITY_MEMBRAIN = 57; constexpr int ENTITY_EYE = 60; constexpr int ENTITY_WALKINGBOIL = 88; -constexpr int ENTITY_NERVE_ENDING = 231; constexpr int ENTITY_GREED_GAPER = 299; constexpr int ENTITY_MUSHROOM = 300; constexpr int ENTITY_SUB_HORF = 812; diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index 5c95eba..311c458 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -3,6 +3,7 @@ #include "entity_effect.h" #include "entity_list.h" #include "entity_player.h" +#include "entity_player_forgotten.h" #include "game_state_player.h" #include "log.h" #include "lua_engine.h" @@ -33,7 +34,7 @@ constexpr std::pair ORBIT_LAYERS[] = { // The familiars whose setup, drawing and links wait for their takeovers. constexpr int UNWRITTEN_INIT_VARIANTS[] = {48, 62, 121, 122, 128, 131, 206, 228, 231, - 233, 234, 236, 237, 238, 239, 240, 900}; + 233, 234, 236, 237, 238, 239, 240}; constexpr int UNWRITTEN_RENDER_VARIANTS[] = {48, 68, 75, 78, 79, 231, 237, 240, 243}; // The familiars that walk, Init's grid collision for them, and the ones whose hit list survives the reset. @@ -359,6 +360,7 @@ void Entity_Familiar::variant_init(int initSubtype) switch (variant) { + case FORGOTTEN_BODY: forgotten_body_init(*this); break; case BLUE_FLY: collisionDamage = player->meleeDamage + player->meleeDamage; if (initSubtype >= 1 && initSubtype <= 5) sprite.Play(LOCUST_ANIMS[initSubtype]); @@ -515,6 +517,7 @@ void Entity_Familiar::variant_update() FollowParent(); return update_weapon(false); case BLUE_FLY: return ai_blue_fly(); + case FORGOTTEN_BODY: return forgotten_body_update(*this); default: reconstruction_missing("Entity_Familiar::Update 0061da10 (this familiar's behaviour)"); } } @@ -711,7 +714,8 @@ void Entity_Familiar::Remove() // 006121d0 Drops its links and its weapon. The Forgotten's body, the wisps and Gello's cord stop the game. void Entity_Familiar::ClearReferences() { - if (variant == FORGOTTEN_BODY || variant == WISP || variant == ITEM_WISP || variant == UMBILICAL_BABY) + if (variant == FORGOTTEN_BODY) forgotten_body_clear(*this); + if (variant == WISP || variant == ITEM_WISP || variant == UMBILICAL_BABY) reconstruction_missing("Entity_Familiar::ClearReferences 006121d0 (this familiar's links)"); linkedEntity = nullptr; Entity::ClearReferences(); diff --git a/src/entity_knife.cpp b/src/entity_knife.cpp index 9f4608b..31450d8 100644 --- a/src/entity_knife.cpp +++ b/src/entity_knife.cpp @@ -1,5 +1,208 @@ #include "entity_knife.h" +#include "anm2.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "entity_tear.h" #include "log.h" +#include "lua_engine.h" +#include "npc_ai.h" +#include "weapon_knives.h" +#include + +constexpr float KNIFE_DAMAGE_DEFAULT = 22; +constexpr float KNIFE_MAX_DISTANCE_DEFAULT = 100; +constexpr float KNIFE_PATH_PROGRESS_NONE = -100; +constexpr float KNIFE_PATH_FOLLOW_SPEED = 0.1f; +constexpr float KNIFE_PATH_OFFSET_RANGE = 50; +constexpr float KNIFE_GRAVITY = -2; +constexpr float KNIFE_ORBIT_GRAVITY = -1; +constexpr float KNIFE_SWING_GRAVITY_SCALE = 0.75f; +constexpr float KNIFE_HYDROBOUNCE_LIFT = -10; +constexpr int KNIFE_SUBTYPE_HELD_ITEM = 4; +constexpr const char* DEAD_EYE_EFFECT_PATH = "gfx/DeadEyeTearEffect.anm2"; + +// The sprite of Dead Eye's mark over a knife, loaded once for every knife. +static ANM2 deadEyeSprite; + +// Whether a knife is a swung weapon: the clubs, bones, the bag and the axe. +static bool is_swung_variant(int variant) +{ + return variant == KNIFE_BONE_CLUB || variant == KNIFE_BONE_SCYTHE || variant == KNIFE_DONKEY_JAWBONE || + variant == KNIFE_BAG_OF_CRAFTING || variant == 8 || variant == KNIFE_NOTCHED_AXE; +} + +// 00960c10 Sets a knife up: Dead Eye's shared mark sprite first, then its own sprite, its default damage, distance and +// path offset, unmoved by knockback. A swung weapon (or sword) held as an item shows its other layers instead. +void Entity_Knife::Init(int knifeType, int knifeVariant, int knifeSubType, uint32_t knifeSeed) +{ + if (!deadEyeSprite.isLoaded) + { + deadEyeSprite.Load(DEAD_EYE_EFFECT_PATH, GRAPHICS_LOAD); + layer_additive_set(*deadEyeSprite.GetLayer(0)); + deadEyeSprite.Play("Idle"); + } + + Entity::Init(knifeType, knifeVariant, knifeSubType, knifeSeed); + if (config) + { + sprite.Load(config->anm2Path, GRAPHICS_LOAD); + sprite.Play(sprite.GetDefaultAnimationName()); + } + + collisionDamage = KNIFE_DAMAGE_DEFAULT; + scale = 1; + rotation = 0; + displayRotation = 0; + knifeDepthOffset = 0; + tearFlags.reset(); + rotationOffset = 0; + entityGridCollisionClass = GRIDCOLL_NONE; + knifeDistance = 0; + knifeVelocity = 0; + maxDistance = KNIFE_MAX_DISTANCE_DEFAULT; + charge = 0; + isFlying = false; + anchorPosition = {}; + initPosition = pos; + isPrismApplied = false; + isMultidimensionalApplied = false; + isUsingParentHitList = false; + pathSegment = 0; + pathProgress = KNIFE_PATH_PROGRESS_NONE; + pathFollowSpeed = KNIFE_PATH_FOLLOW_SPEED; + height = 0; + fallingSpeed = 0; + isDeadEyeHit = false; + isSwinging = false; + isSpinAttack = false; + removeDistance = KNIFE_DISTANCE_NONE; + spinsLeft = 0; + pathOffset = random_unit() * KNIFE_PATH_OFFSET_RANGE - KNIFE_PATH_OFFSET_RANGE / 2; + AddEntityFlags(FLAG_NO_KNOCKBACK); + isPrimaryClub = false; + showDistance = KNIFE_DISTANCE_NONE; + hitList.clear(); + + bool isHeldItem = subtype == KNIFE_SUBTYPE_HELD_ITEM; + if (is_swung_variant(variant) || variant == KNIFE_SPIRIT_SWORD || variant == KNIFE_TECH_SWORD) + { + sprite.GetLayer(0)->isVisible = !isHeldItem; + sprite.GetLayer(1)->isVisible = isHeldItem; + if (variant == KNIFE_SPIRIT_SWORD || variant == KNIFE_TECH_SWORD) sprite.GetLayer(2)->isVisible = isHeldItem; + } + lua_engine_get().PostKnifeInit(this); +} + +// 00960a20 The variant a knife behaves as: the swung weapons as the club, the tech sword as the sword, Bloody +// Babylon's as Mom's Knife. +int Entity_Knife::GetBaseVariant() +{ + if (is_swung_variant(variant)) return KNIFE_BONE_CLUB; + if (variant == KNIFE_SUMPTORIUM) return KNIFE_MOMS_KNIFE; + return variant == KNIFE_TECH_SWORD ? KNIFE_SPIRIT_SWORD : variant; +} + +// 009611d0 Lets go of its links: the tear it rides on forgets it, its Brimstone and Technology lasers go, and it +// forgets the knife it is linked to and its spin effect. +void Entity_Knife::ClearReferences() +{ + if (parent && parent->type == ENTITY_TEAR) + { + Entity_Tear& tear = *parent->ToTear(); + if (tear.attachedEffect == this) tear.attachedEffect = nullptr; + } + Entity::ClearReferences(); + if (brimstoneLaser) brimstoneLaser->Remove(); + if (techLaser) techLaser->Remove(); + brimstoneLaser = nullptr; + techLaser = nullptr; + linkedKnife = nullptr; + spinEffect = nullptr; +} + +// 009612e0 The hit list a knife shares: its own, or that of the first knife up its chain that keeps its own. +std::vector& Entity_Knife::GetHitEntities() +{ + Entity_Knife* knife = this; + while (knife->isUsingParentHitList && knife->parent && knife->parent->type == ENTITY_KNIFE) + knife = static_cast(knife->parent.get()); + return knife->hitList; +} + +// 00966650 The player a knife fights for: its parent (or its parent knife's), a familiar's player, the player of an +// effect, or the player that fired the tear it rides on. +Entity_Player* Entity_Knife::GetPlayer() +{ + Entity* owner = parent; + if (owner && owner->type == ENTITY_KNIFE) owner = owner->parent; + if (!owner) return nullptr; + + switch (owner->type) + { + case ENTITY_PLAYER: + return owner->ToPlayer(); + case ENTITY_FAMILIAR: + return static_cast(owner)->player; + case ENTITY_EFFECT: + owner = owner->parent; + break; + case ENTITY_TEAR: + owner = owner->spawnerEntity; + break; + default: + return nullptr; + } + return owner && owner->type == ENTITY_PLAYER ? owner->ToPlayer() : nullptr; +} + +// 00966ef0 Throws the knife with a charge over a range (Lua's Shoot): it flies out as fast as the distance needs +// against its pull back (weaker for an orbiting knife, a swung weapon or Hydrobounce, which also lifts it). A swung +// weapon starts its spin at a random frame. The homing path is laid out last. +void Entity_Knife::Shoot(float throwCharge, float range) +{ + float gravity = tearFlags[TEAR_ORBIT] ? KNIFE_ORBIT_GRAVITY : KNIFE_GRAVITY; + bool isSwung = is_swung_variant(variant); + maxDistance = throwCharge * range; + if (isSwung) gravity *= KNIFE_SWING_GRAVITY_SCALE; + if (tearFlags[TEAR_HYDROBOUNCE]) + { + gravity *= KNIFE_SWING_GRAVITY_SCALE; + height = 0; + fallingSpeed = KNIFE_HYDROBOUNCE_LIFT; + } + + knifeDistance = 0; + isFlying = true; + knifeVelocity = std::sqrt(std::abs(throwCharge * range / (gravity * -0.5f))) * -gravity; + charge = throwCharge; + if (isSwung) + { + sprite.rotation = 0; + knifeDepthOffset = 0; + hitList.clear(); + sprite.Play("Spin"); + const AnimationData* animation = sprite.animState.animData; + int startFrame = animation && animation->length ? (int)(Random() % (uint32_t)animation->length) : 0; + if (animation) sprite.animState.SetFrameFloat((float)startFrame); + } + UpdateHomingPath(); +} + +// 00967fc0 Brings a thrown knife back to rest: no target, distance or speed, Angelic Prism and Multidimensional Baby +// may apply again, and a swung weapon still spinning goes idle. +void Entity_Knife::Reset() +{ + targetPosition = {}; + target = nullptr; + knifeDistance = 0; + isFlying = false; + knifeVelocity = 0; + isPrismApplied = false; + isMultidimensionalApplied = false; + if (is_swung_variant(variant) && sprite.IsPlaying("Spin")) sprite.Play("Idle"); +} // 009665e0 Sorts by its own depth, ignoring the sorting layer. int Entity_Knife::GetRenderZ() @@ -17,12 +220,6 @@ Entity* Entity_Knife::GetRootParent() // The rest of Entity_Knife is not reconstructed yet. -// 00960c10 -void Entity_Knife::Init(int, int, int, uint32_t) -{ - reconstruction_missing("Entity_Knife::Init 00960c10"); -} - // 00961b00 void Entity_Knife::Update() { @@ -41,30 +238,12 @@ void Entity_Knife::Render(const Vector&) reconstruction_missing("Entity_Knife::Render 00965d30"); } -// 009611d0 -void Entity_Knife::ClearReferences() -{ - reconstruction_missing("Entity_Knife::ClearReferences 009611d0"); -} - // 009666f0 bool Entity_Knife::HandleCollision(Entity*, bool) { reconstruction_missing("Entity_Knife::HandleCollision 009666f0"); } -// 00960a20 -int Entity_Knife::GetBaseVariant() -{ - reconstruction_missing("Entity_Knife::GetBaseVariant 00960a20"); -} - -// 009612e0 -void* Entity_Knife::GetHitEntities() -{ - reconstruction_missing("Entity_Knife::GetHitEntities 009612e0"); -} - // 00961320 void Entity_Knife::InitHomingPath(Vector, Entity*, float) { @@ -83,18 +262,6 @@ uint32_t Entity_Knife::spawn_child_knife() reconstruction_missing("Entity_Knife::spawn_child_knife 00961870"); } -// 00966650 -Entity_Player* Entity_Knife::GetPlayer() -{ - reconstruction_missing("Entity_Knife::GetPlayer 00966650"); -} - -// 00966ef0 -void Entity_Knife::Shoot(float, float) -{ - reconstruction_missing("Entity_Knife::Shoot 00966ef0"); -} - // 00967180 void Entity_Knife::UpdateHomingPath() { @@ -119,12 +286,6 @@ void Entity_Knife::screen_wrap() reconstruction_missing("Entity_Knife::screen_wrap 00967d20"); } -// 00967fc0 -void Entity_Knife::Reset() -{ - reconstruction_missing("Entity_Knife::Reset 00967fc0"); -} - // 009680d0 void Entity_Knife::SetAttackAnimation() { diff --git a/src/entity_knife.h b/src/entity_knife.h index ff9ba99..c660140 100644 --- a/src/entity_knife.h +++ b/src/entity_knife.h @@ -4,6 +4,9 @@ #include "homing_laser.h" #include +// The distances a knife has no use for yet: removed or shown once it flies past them. +constexpr float KNIFE_DISTANCE_NONE = -1; + // Construction and destruction (00960b50, 00960a70) are the defaults. // Field accessors (004d7790, 004d77a0, 0060cf10, 0060cfb0, 0085de90, 0085deb0, 0085dec0) are the public fields. // A knife (Lua's EntityKnife): Mom's Knife and the swung weapons (bones, clubs, swords), with the tear effects they @@ -14,6 +17,10 @@ struct Entity_Knife : Entity std::vector hitList; TearFlags tearFlags; TearFlags usedTearFlags; + EntityPtr brimstoneLaser; + EntityPtr linkedKnife; + EntityPtr spinEffect; + EntityPtr techLaser; Vector anchorPosition{}; Vector initPosition{}; float basePosOffsetY = 0; @@ -29,9 +36,12 @@ struct Entity_Knife : Entity float pathOffset = 0; float pathProgress = 0; float rotation = 0; + float removeDistance = KNIFE_DISTANCE_NONE; float rotationOffset = 0; float scale = 0; + float showDistance = KNIFE_DISTANCE_NONE; int pathSegment = 0; + short spinsLeft = 0; bool isDeadEyeHit = false; bool isFlying = false; bool isMultidimensionalApplied = false; @@ -50,7 +60,7 @@ struct Entity_Knife : Entity bool HandleCollision(Entity* collider, bool isLow) override; int GetBaseVariant(); - void* GetHitEntities(); + std::vector& GetHitEntities(); void InitHomingPath(Vector direction, Entity* source, float pathOffset); void copy_parent_state(Entity_Knife* source); uint32_t spawn_child_knife(); diff --git a/src/entity_laser_hits.cpp b/src/entity_laser_hits.cpp index 923f1fa..b7ee753 100644 --- a/src/entity_laser_hits.cpp +++ b/src/entity_laser_hits.cpp @@ -49,6 +49,24 @@ constexpr int LASER_HIT_COUNTDOWN = 30; constexpr int GRID_HURT_CHANCE_MASK = 3; constexpr int SHIELD_RING_CHANCE = 50; constexpr int SHIELD_CHANCE = 5; +constexpr float RING_FAMILIAR_SCALE = 0.75f; +constexpr float RING_PULSE_RATE = 0.1f; +constexpr float RING_PULSE_SIZE = 20; +constexpr float RING_GROW_RANGE = 500; +constexpr float RING_GROW_SIZE = 50; +constexpr float RING_OPEN_MIN = 5; +constexpr float RING_WALL_FACING = 0.75f; +constexpr float RING_FADE_GROWTH = 0.2f; +constexpr float RING_HIT_INTERVAL = 2; +constexpr float RING_LUDOVICO_FRICTION = 0.8f; +constexpr float RING_SAMPLE_BLEND = 0.3f; +constexpr float RING_COLLINEAR_TOLERANCE = 0.001f; +constexpr float RING_WIGGLE_RATE = 1.6f; +constexpr float RING_GRID_OFFSET_SCALE = 0.8f; +constexpr float LIGHT_RING_INTERVAL = 30; +constexpr int RING_OPEN_FRAMES = 10; +constexpr int RING_FADE_FRAMES = 5; +constexpr int RING_BRIMSTONE_FADE = 20; constexpr int CHALLENGE_PONG_HITS = 30; constexpr int MARKED_SPRAY_SUBTYPE = 2; constexpr RNG BLACK_HEART_RNG = {0, 1, 5, 19}; @@ -112,7 +130,7 @@ void Entity_Laser::DoDamage(Entity* entity, float damage) Entity_Tear::ApplyTearFlagEffects(entity, pos, tearFlags, this, damage); if (entity->HasEntityFlags(FLAG_BRIMSTONE_MARKED) && is_thick_variant()) { - int sound = SOUND_MEAT_IMPACTS; + int sound = SOUND_MEATY_DEATHS; seed_fart_sound_override(&sound); g_manager->sfxManager.Play(sound, {.volume = MARKED_SOUND_VOLUME, .frameDelay = MARKED_SOUND_DELAY}); entity->AddEntityFlags(FLAG_EXTRA_GORE); @@ -464,8 +482,157 @@ void Entity_Laser::impact_tear_flag_effects(const Vector&, const Vector&) reconstruction_missing("Entity_Laser::impact_tear_flag_effects 0096d3f0"); } -// 0097baa0 The rings' frame (Tech X, the ring bosses' and Ludovico's lasers) is not reconstructed yet. +// How a ring's radius changes with its tear flags and age, before it is drawn: pulsing, growing or shrinking with the +// distance from its player, and a flying ring springing open over its first frames (wider than its radius at first). +static float ring_radius_get(Entity_Laser& laser, Entity_Player* player, float& widthScale) +{ + float radius = laser.radius; + if (laser.parent && laser.parent->type == ENTITY_FAMILIAR) radius *= RING_FAMILIAR_SCALE; + if (laser.tearFlags[TEAR_PULSE]) radius += std::sin(laser.updateTime * RING_PULSE_RATE) * RING_PULSE_SIZE; + if (laser.subtype == LASER_SUBTYPE_RING_FOLLOW_PARENT && laser.parent == player) return radius; + + float distance = player ? std::min(vector_length(vector_sub(laser.pos, player->pos)), RING_GROW_RANGE) : 0; + if (laser.tearFlags[TEAR_GROW]) radius += distance * RING_GROW_SIZE / RING_GROW_RANGE; + if (laser.tearFlags[TEAR_SHRINK]) radius += (1 - distance / RING_GROW_RANGE) * RING_GROW_SIZE; + if (laser.subtype != LASER_SUBTYPE_RING_PROJECTILE) return radius; + + int age = g_game->frameCount - laser.spawnFrame; + if (age >= RING_OPEN_FRAMES) return radius; + + float t = 1 - (float)age / RING_OPEN_FRAMES; + float opened = std::max((1 - (t * t * t - std::sin(t * PI_F) * t)) * radius, RING_OPEN_MIN); + if (opened > radius) widthScale = opened / radius; + return std::min(opened, radius); +} + +// A flying ring at the walls: it bounces off them once with Rubber Cement, and otherwise starts fading when it flies +// into one. +static void ring_walls_update(Entity_Laser& laser, float radius) +{ + Vector clamped = g_game->room->GetClampedPosition(laser.pos, radius); + if (!laser.tearFlags[TEAR_BOUNCE]) + { + if (laser.tearFlags[TEAR_CONTINUUM]) return; + float facing = vector_dot(vector_normalized(vector_sub(clamped, laser.pos)), vector_normalized(laser.velocity)); + if (facing < -RING_WALL_FACING && laser.timeout == 0) laser.timeout = RING_FADE_FRAMES; + return; + } + + for (int axis = 0; axis < 2; axis++) + { + float& position = axis == 0 ? laser.pos.x : laser.pos.y; + float& speed = axis == 0 ? laser.velocity.x : laser.velocity.y; + float wall = axis == 0 ? clamped.x : clamped.y; + if (!((wall < position && speed > 0) || (position < wall && speed < 0))) continue; + + position = wall; + speed = -speed; + laser.tearFlags.reset(TEAR_BOUNCE); + laser.heldTearFlags.set(TEAR_BOUNCE); + } +} + +// A ring that ended: Tech X's thin ring plays its fade and grows while it does, every other ring goes. +static void ring_fade_update(Entity_Laser& laser, float& widthScale) +{ + if (laser.variant == LASER_THIN_RED) + { + const AnimationData* animation = laser.sprite.animState.animData; + if (!animation || !animation->isLooping) + widthScale = (animation ? laser.sprite.animState.animFrame : -1) * RING_FADE_GROWTH + 1; + else laser.sprite.Play(laser.sprite.GetAnimation() + "Fade"); + if (laser.sprite.IsPlaying()) return; + } + laser.Remove(); +} + +// 0097baa0 A ring's frame (Tech X's, Ludovico's, the ring bosses'): it follows its parent, flies and fades or bounces +// off the walls, finds its radius, lays its circle of samples (cut by the grid) and hits what it covers every other +// frame. The light ring hurts enemies inside it every second instead. void Entity_Laser::UpdateHits() { - reconstruction_missing("Entity_Laser::UpdateHits 0097baa0"); + refresh_tear_params(); + if (isFirstUpdate || !isOneHit) activeTearFlags = tearFlags; + bool isHitFrame = !isDead && !isInterpolating && variant != LASER_LIGHT_RING && + (isFirstUpdate || GetIntervalTicks(RING_HIT_INTERVAL, 0)); + if (isHitFrame && !parentLaser) hitList.clear(); + if (!isInterpolating && subtype == LASER_SUBTYPE_RING_LUDOVICO) friction *= RING_LUDOVICO_FRICTION; + + homingLaser.bezier.clear(); + homingLaser.origin = pos; + homingLaser.endPoint = {}; + Entity_Player* player = spawnerEntity && spawnerEntity->type == ENTITY_PLAYER ? spawnerEntity->ToPlayer() : nullptr; + float widthScale = 1; + float radiusNow = ring_radius_get(*this, player, widthScale); + + bool isTimed = subtype == LASER_SUBTYPE_RING_PROJECTILE || subtype == LASER_SUBTYPE_RING_FOLLOW_PARENT; + if (subtype == LASER_SUBTYPE_RING_PROJECTILE) ring_walls_update(*this, radiusNow); + else if (subtype == LASER_SUBTYPE_RING_FOLLOW_PARENT && (!parent || parent->isDead) && !isDead) + { + isDead = true; + timeout = 0; + } + if (isTimed && isDead) ring_fade_update(*this, widthScale); + if (isTimed && timeout > 0 && !isInterpolating) + { + if (variant != LASER_THIN_RED && subtype == LASER_SUBTYPE_RING_PROJECTILE) + { + widthScale = (float)(RING_FADE_FRAMES - timeout) * RING_FADE_GROWTH + 1; + sprite.color = color; + sprite.color._tint[3] = (float)std::min(timeout, RING_FADE_FRAMES) * sprite.color._tint[3] / RING_FADE_FRAMES; + } + if (--timeout < 1) isDead = true; + } + + float blend = RING_SAMPLE_BLEND; + if (subtype == LASER_SUBTYPE_RING_FOLLOW_PARENT) + { + if (parent && !isDisableFollowParent) + { + pos = vector_add(parent->pos, parentOffset); + velocity = parent->velocity; + } + if (variant == LASER_THICK_RED || variant == LASER_BRIM_TECH || variant == LASER_THICKER_RED || + variant == LASER_THICKER_BRIM_TECH) + { + sprite.color = COLOR_DEFAULT; + sprite.color._tint[3] = (float)std::min(timeout, RING_BRIMSTONE_FADE) / RING_BRIMSTONE_FADE; + } + } + else if (!tearFlags[TEAR_CONTINUUM]) pos = g_game->room->GetClampedPosition(pos, radiusNow); + else if (!isInterpolating) reconstruction_missing("Entity_Laser::UpdateHits 0097baa0: Continuum's ring wrapping"); + + if ((variant == LASER_THIN_RED || variant == LASER_ELECTRIC) && child) + { + Vector childPosition = pos; + if (!isInterpolating && !tearFlags[TEAR_CONTINUUM] && subtype != LASER_SUBTYPE_RING_FOLLOW_PARENT) + childPosition = g_game->room->GetClampedPosition(vector_add(pos, vector_scale(velocity, friction)), radiusNow); + if (subtype == LASER_SUBTYPE_RING_PROJECTILE) childPosition = vector_sub(childPosition, velocity); + child->pos = childPosition; + child->SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + child->posOffset = posOffset; + } + + homingLaser.build_ring_bezier(pos, tearFlags[TEAR_HOMING], parent, radiusNow * widthScale); + homingLaser.CalculateSamples(blend); + homingLaser.remove_collinear_samples(RING_COLLINEAR_TOLERANCE); + if (tearFlags[TEAR_WIGGLE]) + { + bool isKnife = parent && parent->type == ENTITY_KNIFE; + float amplitude = player ? worm_multiplier_get(player, TEAR_WIGGLE) : 1; + homingLaser.apply_sine_offset(amplitude, isKnife ? (float)g_game->frameCount * RING_WIGGLE_RATE : 0); + } + isGridHit = false; + if (entityGridCollisionClass != GRIDCOLL_NONE) + isGridHit = homingLaser.clip_samples_to_grid(vector_scale(posOffset, RING_GRID_OFFSET_SCALE), + entityGridCollisionClass); + + if (isHitFrame) update_endpoint_and_hits(); + else if (!isDead && !isInterpolating && variant == LASER_LIGHT_RING && GetIntervalTicks(LIGHT_RING_INTERVAL, 0)) + for (Entity* entity : entity_query_radius(pos, radius, QUERY_ENEMIES)) + if (entity->IsVulnerableEnemy(nullptr) && !IsDescendantOf(entity)) + entity->TakeDamage(collisionDamage, 0, EntityRef(this), LASER_HIT_COUNTDOWN); + + if (isHitFrame && (std::isfinite(impactDistance) || isGridHit)) + impact_tear_flag_effects(impactPosition, impactDirection); } diff --git a/src/entity_laser_render.cpp b/src/entity_laser_render.cpp index b8d9e71..43ced35 100644 --- a/src/entity_laser_render.cpp +++ b/src/entity_laser_render.cpp @@ -97,8 +97,8 @@ static ColorMod beam_color(Entity_Laser& laser, const AnimationFrame& frame, boo } // The beam along the path: one quad per segment, joined at their middles, scrolling the beam's texture along its -// length (and with time for a ring). Lump of Coal widens it with distance, Proptosis narrows it. A line laser then -// draws its start sprite from its position to the beam. +// length (and with time for a ring, whose last quad closes onto its first). Lump of Coal widens it with distance, +// Proptosis narrows it. A line laser then draws its start sprite from its position to the beam. void Entity_Laser::render_path(const Vector& offset, bool isShadow) { const std::vector& samples = homingLaser.samples; @@ -127,7 +127,11 @@ void Entity_Laser::render_path(const Vector& offset, bool isShadow) Vector to = screen_point(samples[i + 1]); quads.push_back({vector_sub(from, side), vector_add(from, side), vector_sub(to, side), vector_add(to, side)}); } - if (IsCircleLaser()) reconstruction_missing("Entity_Laser::Render 009785d0: a ring's closing segment"); + if (IsCircleLaser()) + { + quads.back()._bottomLeft = quads.front()._topLeft; + quads.back()._bottomRight = quads.front()._topRight; + } bool isScaled = !IsCircleLaser(); float along = IsCircleLaser() ? (float)(g_game->frameCount - spawnFrame) * RING_SCROLL_SPEED : 0; diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index 9fea327..93852db 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -21,6 +21,7 @@ #include "room_descriptor.h" #include "room_grid.h" #include "sfx_manager.h" +#include "mines.h" #include #include #include @@ -256,6 +257,52 @@ static Entity* spawn_at(int type, int variant, int subType, const Vector& positi .seed = Random()}); } +// Whether an entity may be the nearest enemy (Game::GetNearestEnemy): a living, targetable, collidable enemy past its +// first frame that is not friendly, nor a fireplace, shopkeeper, TNT, poop, prop, minecart or the blood cultist's +// spawn. In a versus match the other players count too. +static bool is_nearest_enemy_candidate(Entity& entity, bool isVersusPlayer) +{ + constexpr int CULTIST_BLOOD_SPAWN = 10; + int type = entity.type; + + if (g_game->frameCount - entity.spawnFrame <= 1) return false; + if (!isVersusPlayer && (type < ENTITY_FIRST_ENEMY || type > ENTITY_LAST_ENEMY)) return false; + if (entity.entityCollisionClass == ENTCOLL_NONE || entity.entityCollisionClass == ENTCOLL_PLAYERONLY) return false; + if (entity.isInvincible || entity.isDead || entity.HasEntityFlags(FLAG_NO_TARGET | FLAG_FRIENDLY)) return false; + if (isVersusPlayer) return true; + if (type == ENTITY_CULTIST) return entity.variant != CULTIST_BLOOD_SPAWN; + return type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER && type != ENTITY_MOVABLE_TNT && type != ENTITY_POOP && + type != ENTITY_GENERIC_PROP && type != ENTITY_MINECART; +} + +// 00707370 Game::GetNearestEnemy: the enemy nearest a position within a radius that a source may target, a charmed +// one counted 400 farther. A friendly source passes over the players it may not hurt, and in a versus match over its +// own ancestors. The original's optional distance function is left out, as no caller here passes one. +Entity* game_nearest_enemy(const Vector& position, Entity* source, float radius) +{ + constexpr float CHARMED_DISTANCE_SQUARED = 160000; + bool isVersus = g_game->deathmatchManager.is_active(); + Entity* nearest = nullptr; + float best = radius * radius; + + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isPlayer = entity->type == ENTITY_PLAYER; + if (isPlayer && source && source->HasEntityFlags(FLAG_FRIENDLY) && + source->IsDamageSourceFriendly(EntityRef(entity))) + continue; + if (source && ((isVersus && source->IsDescendantOf(entity)) || !source->IsValidTarget(entity))) continue; + if (!is_nearest_enemy_candidate(*entity, isVersus && isPlayer)) continue; + + float distance = vector_length_squared(vector_sub(position, entity->pos)); + if (entity->HasEntityFlags(FLAG_CHARM)) distance += CHARMED_DISTANCE_SQUARED; + if (distance >= best) continue; + best = distance; + nearest = entity; + } + return nearest; +} + // 00703950 The player nearest a position, the first on ties. Entity_Player* game_nearest_player(const Vector& position) { @@ -2128,7 +2175,7 @@ int Entity_NPC::death_burst_get() } } -// 006be840 What it goes after: a charmed enemy picks the nearest enemy, Mom's Heart's (type 53) its own player, +// 006be840 What it goes after: a charmed enemy picks the nearest enemy, a Dople (type 53) its own player, // the rest the nearest target player (Game::GetNearestTargetPlayer), else the first player. Entity* Entity_NPC::GetPlayerTarget() { @@ -2137,7 +2184,7 @@ Entity* Entity_NPC::GetPlayerTarget() bool isRetargeting = IsFrame(TARGET_REFRESH_FRAMES, (int)index) || !target; if (HasEntityFlags(FLAG_CHARM) && !g_game->room->isPacifist && isRetargeting) - reconstruction_missing("Entity_NPC::GetPlayerTarget 006be840: a charmed enemy's prey (Game::GetNearestEnemy)"); + target = game_nearest_enemy(pos, this, TARGET_RANGE); if (target) return target; bool isTargetDecoys = type != ENTITY_NO_DECOY_TYPE && decoyTargetTimer >= 0; @@ -2414,9 +2461,8 @@ constexpr std::array RENDER_SPECIAL_TYPES = {273, 411, 807, 810, 815, 8 void Entity_NPC::Interpolate() { if (pauseTimer != 0) return; - if (type == ENTITY_MINECART) reconstruction_missing("Entity_NPC::Interpolate 006d2b50: a minecart's half step"); - - Entity::Interpolate(); + if (type == ENTITY_MINECART) minecart_interpolate(*this); + else Entity::Interpolate(); if (aiCallFlags & AI_CALL_INTERPOLATE) ai_call(AI_PHASE_INTERPOLATE); UpdateChildEffectPosition(true); @@ -2558,7 +2604,7 @@ void Entity_NPC::update_damage_history() void Entity_NPC::trigger_kill_item_effects() { if (isBoss) g_game->room->TriggerBossDeath(*this); - else if (isChampion) reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: NpcHelper::ChampionDrop"); + else if (isChampion) champion_drop(); if (type == ENTITY_ROTGUT && variant == 1) reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: Rotgut's death"); if (HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) @@ -2746,36 +2792,6 @@ void Entity_NPC::Hornfel_UpdateFrame() reconstruction_missing("Entity_NPC::Hornfel_UpdateFrame 004bb0e0"); } -// 004cde30 -void Entity_NPC::update_physics() -{ - reconstruction_missing("Entity_NPC::update_physics 004cde30"); -} - -// 004ce120 -void Entity_NPC::apply_velocity(char) -{ - reconstruction_missing("Entity_NPC::apply_velocity 004ce120"); -} - -// 004ce6d0 -void Entity_NPC::update_move_direction_anim() -{ - reconstruction_missing("Entity_NPC::update_move_direction_anim 004ce6d0"); -} - -// 004cf030 -void Entity_NPC::SetMinecartPosVel(const Vector&, const Vector&) -{ - reconstruction_missing("Entity_NPC::SetMinecartPosVel 004cf030"); -} - -// 004cf120 -void Entity_NPC::MinecartUpdateChild(Entity*) -{ - reconstruction_missing("Entity_NPC::MinecartUpdateChild 004cf120"); -} - // 004e8fa0 void Entity_NPC::UpdateCordChain(bool) { @@ -2830,10 +2846,44 @@ void Entity_NPC::KillUnique() reconstruction_missing("Entity_NPC::KillUnique 006be760"); } -// 006c2750 -Entity_NPC* Entity_NPC::ThrowSpider(const Vector&, Entity*, Vector, bool, float) +// A thrown spider: a free landing spot within 100 when none is given, a Strider instead over Downpour's and Dross's +// water, the path cost its landing cell is kept clear with, its first hop's rise and its step toward the spot. +constexpr float SPIDER_LANDING_SEARCH = 100; +constexpr float SPIDER_STRIDER_WATER = 0.1f; +constexpr int SPIDER_LANDING_PATH = 900; +constexpr int SPIDER_LANDING_PATH_LIMIT = 950; +constexpr float SPIDER_THROW_RISE = -8; +constexpr float SPIDER_THROW_STEP = 0.04f; + +// 006c2750 Throws a spider (or a big one) from position to land at targetPos, marking its landing cell in the room's +// paths so others steer clear. +Entity_NPC* Entity_NPC::ThrowSpider(const Vector& position, Entity* spawner, Vector targetPos, bool isBig, + float yOffset) { - reconstruction_missing("Entity_NPC::ThrowSpider 006c2750"); + if (vector_is_zero(targetPos)) + targetPos = room_free_pickup_position_find({.position = position, .step = SPIDER_LANDING_SEARCH}); + + int stageId = g_game->GetStageID(); + Room& room = *g_game->room; + if ((stageId == STAGE_ID_DOWNPOUR || stageId == STAGE_ID_DROSS) && room.waterAmount > SPIDER_STRIDER_WATER) + return ThrowStrider(position, spawner, targetPos); + + int gridIndex = room.GetGridIndex(targetPos); + if (gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS && room.gridPaths[gridIndex] <= SPIDER_LANDING_PATH_LIMIT) + room.gridPaths[gridIndex] = SPIDER_LANDING_PATH; + + auto* spider = static_cast(g_game->Spawn({.position = position, + .spawner = spawner, + .type = isBig ? ENTITY_BIG_SPIDER : ENTITY_SPIDER, + .seed = Random()})); + spider->state = NPC_STATE_JUMP; + spider->targetPosition = targetPos; + spider->v2.y = SPIDER_THROW_RISE; + spider->entityCollisionClass = ENTCOLL_NONE; + spider->velocity = vector_scale(vector_sub(targetPos, spider->pos), SPIDER_THROW_STEP); + spider->v1 = spider->velocity; + spider->posOffset.y = yOffset; + return spider; } // 006ca930 diff --git a/src/entity_npc.h b/src/entity_npc.h index befe81d..3684f11 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -274,6 +274,7 @@ struct Entity_NPC : Entity void white_champion_update(); void flicker_update(); void champion_shot_fire(); + void champion_drop(); void unreachable_update(); void dead_update(); void midas_coins_spawn(); @@ -376,6 +377,7 @@ 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* 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, diff --git a/src/entity_npc_drop.cpp b/src/entity_npc_drop.cpp new file mode 100644 index 0000000..d0f1813 --- /dev/null +++ b/src/entity_npc_drop.cpp @@ -0,0 +1,363 @@ +#include "active_items.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "item_overlay.h" +#include "item_pool.h" +#include "lua_engine.h" +#include "manager.h" +#include "npc_ai.h" +#include "persistent_game_data.h" +#include "room.h" +#include "room_grid.h" +#include + +// The percent chance a champion drops: always, a third on hard unless the kill makes sure, at least half with Purple +// Heart (two thirds doubled, three quarters tripled). The Void keeps one drop in 20 (in 7 for a sure kill). +constexpr uint32_t DROP_CHANCE = 100; +constexpr uint32_t DROP_CHANCE_HARD = 33; +constexpr uint32_t DROP_CHANCE_PURPLE_HEART = 50; +constexpr uint32_t DROP_CHANCE_PURPLE_HEART_DOUBLE = 66; +constexpr uint32_t DROP_CHANCE_PURPLE_HEART_TRIPLE = 75; +constexpr uint32_t PERCENT = 100; +constexpr uint32_t VOID_DROP_ODDS = 20; +constexpr uint32_t VOID_DROP_ODDS_SURE = 7; +constexpr int PURPLE_HEART_TRIPLE = 3; + +// The heart and null pickup subtypes the colours drop. +enum ChampionDropSubtype : int +{ + DROP_HEART_FULL = 1, + DROP_HEART_HALF = 2, + DROP_HEART_ETERNAL = 4, + DROP_HEART_DOUBLE = 5 +}; +constexpr int NULL_PICKUP_NO_ITEMS = 4; + +// A colour's drop: a pickup variant (none for 0), its subtype and how many. +struct ChampionReward +{ + int count = 1; + int subType = 0; + int variant = PICKUP_NULL; +}; + +// What each colour drops when it drops a pickup of its own. +constexpr std::array CHAMPION_REWARDS = {{{1, DROP_HEART_FULL, PICKUP_HEART}, + {1, 0, PICKUP_LIL_BATTERY}, + {1, 0, PICKUP_PILL}, + {1, 0, PICKUP_COIN}, + {}, + {1, 0, PICKUP_BOMB}, + {1, DROP_HEART_ETERNAL, PICKUP_HEART}, + {1, 0, PICKUP_KEY}, + {1, 0, PICKUP_LOCKEDCHEST}, + {1, 0, PICKUP_REDCHEST}, + {}, + {1, 0, PICKUP_TRINKET}, + {1, DROP_HEART_DOUBLE, PICKUP_HEART}, + {1, DROP_HEART_HALF, PICKUP_HEART}, + {1, 0, PICKUP_TAROTCARD}, + {}, + {1, DROP_HEART_FULL, PICKUP_NULL}, + {}, + {}, + {}, + {1, DROP_HEART_FULL, PICKUP_HEART}}}; + +// The orange champion's one to three coins, the rainbow champion's seven pickups, the king's two or three. +constexpr uint32_t ORANGE_COINS = 3; +constexpr std::array RAINBOW_VARIANTS = {PICKUP_TRINKET, PICKUP_PILL, PICKUP_COIN, PICKUP_HEART, + PICKUP_TAROTCARD, PICKUP_KEY, PICKUP_BOMB}; +constexpr uint32_t KING_EXTRA_PICKUPS = 2; +constexpr int KING_PICKUPS = 2; + +// The blue champion's flies, the size pulsing one's four to six, and the shrunk or grown one's pill one time in 5. +constexpr int BLUE_FLIES = 3; +constexpr int PULSE_FLIES = 4; +constexpr uint32_t PULSE_EXTRA_FLIES = 3; +constexpr uint32_t SIZE_PILL_ODDS = 5; + +// The bursts: a blast or ring of shots once it lived a second or died 80 away from the players. +constexpr int CHAMPION_BURST_AGE = 30; +constexpr float CHAMPION_BURST_DISTANCE_SQUARED = 6400; +constexpr float CHAMPION_BURST_DAMAGE = 40; +constexpr float CHAMPION_BURST_RADIUS = 60; +constexpr float CHAMPION_RING_SPEED = 7; + +// The green pulsing champion's two copies 14 out, and the fly protected one's fly, shrunk for 150 frames. +constexpr int SPLIT_COPIES = 2; +constexpr float SPLIT_DISTANCE = 14; +constexpr int SPLIT_FLY_SHRINK_FRAMES = 150; + +// How far drops search for a free spot, and how far apart spread drops start. +constexpr float DROP_SPOT_STEP = 40; +constexpr float DROP_SPREAD = 3; +constexpr int SIZE_PILLS_PURPLE_HEART = 2; + +// The camo champion's card may be a rune, and the death champion's Necronomicon shows its book 3 frames on. +constexpr int CAMO_RUNE_CHANCE = 1; +constexpr int NECRONOMICON_BOOK_DELAY = 3; + +// The player nearest a position among the main players (Game::GetNearestPlayerEx 00703ab0 with main players only and +// the uncollidable included), else the first player. +static Entity_Player* main_player_nearest_get(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()) continue; + nearest = player; + best = distance; + } + return nearest ? nearest : g_game->GetPlayer(0); +} + +// Whether the champion drops at all: its drop roll against the chance, never in Greed, from a portal, in Ultra Hard, on +// a victory lap or in a room seen before, and rarely in the Void without Purple Heart. +static bool is_champion_dropping(Entity_NPC& npc, bool isSure) +{ + PlayerManager& players = g_game->playerManager; + uint32_t chance = g_game->difficulty == DIFFICULTY_HARD && !isSure ? DROP_CHANCE_HARD : DROP_CHANCE; + bool isPurpleHeart = players.AnyoneHasTrinket(TRINKET_PURPLE_HEART); + + if (isPurpleHeart) + { + int multiplier = players.GetTrinketMultiplier(TRINKET_PURPLE_HEART); + uint32_t purple = multiplier >= PURPLE_HEART_TRIPLE ? DROP_CHANCE_PURPLE_HEART_TRIPLE + : multiplier == 2 ? DROP_CHANCE_PURPLE_HEART_DOUBLE + : DROP_CHANCE_PURPLE_HEART; + chance = std::max(chance, purple); + } + + uint32_t roll = npc.dropRNG.Next(); + bool isGreed = g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER; + bool isDropping = !isGreed && npc.spawnerType != ENTITY_PORTAL && g_game->challenge != CHALLENGE_ULTRA_HARD && + roll % PERCENT < chance && g_game->victoryLap < 1 && g_game->room->isFirstVisit; + if (!isPurpleHeart && g_game->stage == STAGE_VOID && + npc.dropRNG.RandomInt(isSure ? VOID_DROP_ODDS_SURE : VOID_DROP_ODDS) != 0) + isDropping = false; + return isDropping; +} + +// Whether a dying champion may burst: not shrunk, and either a second old or away from the nearest player. +static bool is_champion_burst_safe(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_SHRINK)) return false; + if (g_game->frameCount - npc.spawnFrame > CHAMPION_BURST_AGE) return true; + Vector away = vector_sub(npc.pos, game_nearest_player(npc.pos)->pos); + return vector_length_squared(away) > CHAMPION_BURST_DISTANCE_SQUARED; +} + +// The black champion's blast: a bomb's damage, crater and explosion where it died. +static void champion_explode(Entity_NPC& npc) +{ + if (!is_champion_burst_safe(npc)) return; + explosion_damage( + {.position = npc.pos, .source = &npc, .damage = CHAMPION_BURST_DAMAGE, .radius = CHAMPION_BURST_RADIUS}); + bomb_crater_spawn(npc.pos, nullptr, 1); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); +} + +// The light blue champion's ring of eight shots. +static void champion_shots_fire(Entity_NPC& npc) +{ + if (is_champion_burst_safe(npc)) + npc.FireProjectiles(npc.pos, vector_make(CHAMPION_RING_SPEED, 0), PROJECTILES_EIGHT, ProjectileParams{}); +} + +// The green pulsing champion splits into two plain copies around where it died. +static void champion_split(Entity_NPC& npc) +{ + for (int i = 0; i < SPLIT_COPIES; i++) + { + uint32_t seed = npc.dropRNG.Next(); + Vector offset = vector_scale(random_direction(), SPLIT_DISTANCE); + g_game->Spawn({.position = vector_add(npc.pos, offset), + .spawner = &npc, + .type = npc.type, + .variant = npc.variant, + .seed = seed}); + } +} + +// The fly protected champion leaves its fly, which a shrunk champion passes its shrinking on to. +static void champion_fly_release(Entity_NPC& npc) +{ + Entity* fly = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_ATTACKFLY, .seed = Random()}); + if (!npc.HasEntityFlags(FLAG_SHRINK)) return; + + fly->ClearEntityFlags(FLAG_SHRINK); + fly->AddShrink(EntityRef(&npc), SPLIT_FLY_SHRINK_FRAMES, false); + if (fly->shrinkCountdown <= 0) return; + fly->AddEntityFlags(FLAG_SHRINK); + fly->shrinkStatus1 = fly->shrinkStatus2; +} + +// The shrunk or grown champion's pill of the other size, one time in 5 (twice with Purple Heart). +static void champion_size_pills_drop(Entity_NPC& npc, bool isDropping, int pillEffect) +{ + if (npc.dropRNG.RandomInt(SIZE_PILL_ODDS) != 0 || !isDropping) return; + + int count = g_game->playerManager.AnyoneHasTrinket(TRINKET_PURPLE_HEART) ? SIZE_PILLS_PURPLE_HEART : 1; + for (int i = 0; i < count; i++) + { + uint32_t seed = npc.dropRNG.Next(); + int pillColor = g_game->itemPool.ForceAddPillEffect(pillEffect); + Vector spot = room_free_pickup_position_find({.position = npc.pos}); + g_game->Spawn({.position = vector_add(spot, vector_make((float)i, (float)i)), + .spawner = &npc, + .subType = pillColor, + .type = ENTITY_PICKUP, + .variant = PICKUP_PILL, + .seed = seed}); + } +} + +// The king champion's two or three random pickups (four or six with Purple Heart), none of them items or chests. +static void champion_king_drop(Entity_NPC& npc) +{ + int count = (int)npc.dropRNG.RandomInt(KING_EXTRA_PICKUPS) + KING_PICKUPS; + if (g_game->playerManager.AnyoneHasTrinket(TRINKET_PURPLE_HEART)) count *= 2; + for (int i = 0; i < count; i++) + { + uint32_t seed = npc.dropRNG.Next(); + g_game->Spawn({.position = room_free_pickup_position_find({.position = npc.pos}), + .spawner = &npc, + .subType = NULL_PICKUP_NO_ITEMS, + .type = ENTITY_PICKUP, + .variant = PICKUP_NULL, + .seed = seed}); + } +} + +// One of the rainbow champion's pickups, each a frame later than the last. +static void champion_rainbow_pickup_spawn(Entity_NPC& npc, int index) +{ + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = DROP_SPOT_STEP}); + uint32_t seed = npc.dropRNG.Next(); + auto* pickup = static_cast(g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_PICKUP, .variant = RAINBOW_VARIANTS[index], .seed = seed})); + pickup->dropDelay = index; +} + +// The rainbow champion's seven pickups, each half the time when it does not drop (doubled by Purple Heart), then the +// black and light blue champions' bursts. +static void champion_rainbow_drop(Entity_NPC& npc, bool isDropping, bool isIceFrozen) +{ + for (int i = 0; i < (int)RAINBOW_VARIANTS.size(); i++) + { + if (!isDropping && (npc.dropRNG.Next() & 1)) continue; + champion_rainbow_pickup_spawn(npc, i); + if (g_game->playerManager.AnyoneHasTrinket(TRINKET_PURPLE_HEART)) champion_rainbow_pickup_spawn(npc, i); + } + if (isIceFrozen) return; + champion_explode(npc); + champion_shots_fire(npc); +} + +// A colour's own pickups on a free cell where it died, each spread out when there are several: one more half the +// time for a sure kill, twice as many with Purple Heart, each turned by Glyph of Balance, and a trinket from a gold +// enemy golden once golden trinkets are unlocked. +static void champion_reward_spawn(Entity_NPC& npc, ChampionReward reward, bool isSure) +{ + PlayerManager& players = g_game->playerManager; + Room& room = *g_game->room; + Vector spot = npc.pos; + + if ((int)room.GetGridCollision(room.GetGridIndex(spot)) > 0) + spot = room_free_tile_position_find(spot, DROP_SPOT_STEP); + uint32_t glyphSeed = npc.dropRNG.Next(); + Entity_Player* glyphOwner = players.RandomCollectibleOwner(COLLECTIBLE_GLYPH_OF_BALANCE, glyphSeed, nullptr); + if (reward.count != 0 && isSure && (npc.dropRNG.Next() & 1) == 0) reward.count++; + if (players.AnyoneHasTrinket(TRINKET_PURPLE_HEART) && npc.isChampion) reward.count *= 2; + + for (int i = 0; i < reward.count; i++) + { + if (glyphOwner) glyphOwner->GetGlyphOfBalanceDrop(&reward.variant, &reward.subType); + if (reward.variant == PICKUP_NULL) continue; + + Vector direction = reward.count < 2 ? Vector{} : random_direction(); + uint32_t seed = npc.dropRNG.Next(); + auto* pickup = static_cast( + g_game->Spawn({.position = vector_add(spot, vector_scale(direction, DROP_SPREAD)), + .velocity = direction, + .spawner = &npc, + .subType = reward.subType, + .type = ENTITY_PICKUP, + .variant = reward.variant, + .seed = seed})); + bool isGolden = pickup->variant == PICKUP_TRINKET && + g_manager->persistentGameData.Unlocked(ACHIEVEMENT_GOLDEN_TRINKET) && + npc.HasEntityFlags(FLAG_MIDAS_FREEZE) && !(pickup->subtype & TRINKET_GOLDEN_FLAG); + if (isGolden) + pickup->Morph(pickup->type, PICKUP_TRINKET, (int)(pickup->subtype | TRINKET_GOLDEN_FLAG), true, true, true); + } +} + +// 006bf120 (NpcHelper::ChampionDrop) What a dead champion leaves by its colour: a pickup of its own, flies, a blast or +// shots, copies of itself, size pills, the Necronomicon's blast, or the rainbow's spread. Pink and brown leave nothing. +void Entity_NPC::champion_drop() +{ + bool isSure = killDamageFlags & DAMAGE_CHAMPION_REWARD; + bool isDropping = is_champion_dropping(*this, isSure); + bool isIceFrozen = HasEntityFlags(FLAG_ICE_FROZEN); + if (championColorIdx < 0 || championColorIdx >= CHAMPION_COUNT) return; + + ChampionReward reward = CHAMPION_REWARDS[championColorIdx]; + switch (championColorIdx) + { + case CHAMPION_ORANGE: reward.count = (int)(Random() % ORANGE_COINS) + 1; break; + case CHAMPION_DARK_BLUE: + if (isDropping) game_nearest_player(pos)->AddBlueFlies(BLUE_FLIES, pos, nullptr); + return; + case CHAMPION_DARK_GREEN: + if (!isIceFrozen) champion_explode(*this); + break; + case CHAMPION_LIGHT_BLUE: + if (!isIceFrozen) champion_shots_fire(*this); + break; + case CHAMPION_CAMO: + { + uint32_t seed = dropRNG.Next(); + RNG cardRng = {seed, 5, 9, 7}; + int card = ItemPool::GetCardEx((int)seed, 0, CAMO_RUNE_CHANCE, 0, true); + reward.subType = + lua_engine_get().GetCard({.rng = &cardRng, .card = card, .isOnlyRunes = true, .isRunes = true}); + break; + } + case CHAMPION_PULSE_GREEN: + if (!isIceFrozen) champion_split(*this); + break; + case CHAMPION_FLY_PROTECTED: + if (!isIceFrozen) champion_fly_release(*this); + break; + case CHAMPION_TINY: return champion_size_pills_drop(*this, isDropping, PILLEFFECT_SMALLER); + case CHAMPION_GIANT: return champion_size_pills_drop(*this, isDropping, PILLEFFECT_LARGER); + case CHAMPION_SIZE_PULSE: + { + if (!isDropping) return; + int flies = (int)dropRNG.RandomInt(PULSE_EXTRA_FLIES) + PULSE_FLIES; + game_nearest_player(pos)->AddBlueFlies(flies, pos, nullptr); + return; + } + case CHAMPION_KING: + if (isDropping) champion_king_drop(*this); + return; + case CHAMPION_DEATH: + main_player_nearest_get(pos)->UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM}); + g_game->itemOverlay.Show(GIANTBOOK_NECRONOMICON, NECRONOMICON_BOOK_DELAY, nullptr); + return; + case CHAMPION_RAINBOW: return champion_rainbow_drop(*this, isDropping, isIceFrozen); + case CHAMPION_PINK: + case CHAMPION_BROWN: return; + } + if (isDropping) champion_reward_spawn(*this, reward, isSure); +} diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index d386c3a..be44d82 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -9,6 +9,7 @@ #include "log.h" #include "lua_engine.h" #include "manager.h" +#include "menu_options.h" #include "platform.h" #include "room.h" #include "room_grid.h" @@ -130,7 +131,6 @@ constexpr int WISP_HEALED_BY_HEARTS = 296; // The sounds pickups play. constexpr int SOUND_CHEST_DROP = 21; -constexpr int SOUND_FETUS_JUMP = 38; constexpr int SOUND_KEYPICKUP_GAUNTLET = 58; constexpr int SOUND_KEY_DROP0 = 59; constexpr int SOUND_MEAT_FEET_SLOW0 = 68; @@ -903,7 +903,7 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u return; } if (choice.variant == PICKUP_SHOPITEM) shop_ware_choose(choice, seed); - if (is_listed({PICKUP_BROKEN_SHOVEL, PICKUP_BIGCHEST, PICKUP_TROPHY, PICKUP_BED, PICKUP_MOMSCHEST}, choice.variant)) + if (is_listed({PICKUP_BROKEN_SHOVEL, PICKUP_BED, PICKUP_MOMSCHEST}, choice.variant)) reconstruction_missing("Entity_Pickup::Init 006e02f0: the big pickups"); if (choice.variant == PICKUP_COLLECTIBLE) collectible_choose(choice.subType, seed); lua_engine_get().PostPickupSelection(this, choice.variant, choice.subType); @@ -928,6 +928,7 @@ void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, u sprite.Load(config->anm2Path, GRAPHICS_DEFER); UpdateSprite(false); } + if (variant == PICKUP_BIGCHEST || variant == PICKUP_TROPHY) ending_pickup_init(*this); if (variant == PICKUP_COLLECTIBLE) { AddEntityFlags(FLAG_NO_KNOCKBACK); @@ -1196,6 +1197,8 @@ void Entity_Pickup::Update() } bool isAppearing = sprite.IsPlaying("Appear") || sprite.IsPlaying("AppearFast"); if (collisionCooldown > 0 && !isAppearing) collisionCooldown--; + if (variant == PICKUP_BIGCHEST && big_chest_update(*this) == PICKUP_UPDATE_RETURN) return; + if (variant == PICKUP_TROPHY) trophy_update(*this); lua_engine_get().PostPickupUpdate(this); } @@ -1425,6 +1428,10 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) case PICKUP_BOMBCHEST: case PICKUP_HAUNTEDCHEST: break; + case PICKUP_BIGCHEST: + case PICKUP_TROPHY: + ending_pickup_touch(*this, *player); + break; default: reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: sacks and trinkets"); } @@ -1632,8 +1639,8 @@ void Entity_Pickup::coin_collect(Entity_Player& player) if (subtype != COIN_LUCKYPENNY) return; StringTable& strings = g_manager->stringTable; - std::string description(strings.translate("#LUCKY_PENNY_DESCRIPTION")); - std::string name(strings.translate("#LUCKY_PENNY_NAME")); + std::string description(string_table_translate(strings, "#LUCKY_PENNY_DESCRIPTION")); + std::string name(string_table_translate(strings, "#LUCKY_PENNY_NAME")); player.DonateLuck(1); g_game->hud.show_pill_name(&player, name.c_str(), description.c_str()); player.AnimateHappy(); diff --git a/src/entity_player.h b/src/entity_player.h index 451f106..800d4ac 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -26,6 +26,7 @@ constexpr int COLLECTIBLE_VANILLA_COUNT = 733; constexpr int COOP_BABY_BUFF_COUNT = 8; constexpr int COSTUME_LAYER_COUNT = 15; constexpr int FORGOTTEN_BODY_ROOM_NONE = -99999; +constexpr int DIMENSION_ROOM_COUNT = 169; constexpr int HUD_HEART_FLASH_FRAMES = 4; constexpr int INVENTORY_SIZE = 16; constexpr int POCKET_SLOT_COUNT = 4; @@ -183,6 +184,7 @@ enum RenderPass enum PlayerItemId : int { COLLECTIBLE_SAD_ONION = 1, + COLLECTIBLE_TRANSCENDENCE = 20, COLLECTIBLE_SPOON_BENDER = 3, COLLECTIBLE_NUMBER_ONE = 6, COLLECTIBLE_SKATOLE = 9, @@ -200,6 +202,7 @@ enum PlayerItemId : int COLLECTIBLE_SHOOP_DA_WHOOP = 49, COLLECTIBLE_DR_FETUS = 52, COLLECTIBLE_TREASURE_MAP = 54, + COLLECTIBLE_MOMS_EYE = 55, COLLECTIBLE_BOOK_OF_SHADOWS = 58, COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE = 59, COLLECTIBLE_BATTERY = 63, @@ -212,9 +215,11 @@ enum PlayerItemId : int COLLECTIBLE_BOOK_OF_REVELATIONS = 78, COLLECTIBLE_DEAD_CAT = 81, COLLECTIBLE_THE_NAIL = 83, + COLLECTIBLE_LOKIS_HORNS = 87, COLLECTIBLE_SPELUNKER_HAT = 91, COLLECTIBLE_RELIC = 98, COLLECTIBLE_D6 = 105, + COLLECTIBLE_PINKING_SHEARS = 107, COLLECTIBLE_WAFER = 108, COLLECTIBLE_MONEY_EQUALS_POWER = 109, COLLECTIBLE_GUARDIAN_ANGEL = 112, @@ -224,6 +229,7 @@ enum PlayerItemId : int COLLECTIBLE_BRIMSTONE = 118, COLLECTIBLE_WHORE_OF_BABYLON = 122, COLLECTIBLE_MONSTER_MANUAL = 123, + COLLECTIBLE_FORGET_ME_NOW = 127, COLLECTIBLE_RAZOR_BLADE = 126, COLLECTIBLE_PONY = 130, COLLECTIBLE_MOMS_PURSE = 139, @@ -301,6 +307,7 @@ enum PlayerItemId : int COLLECTIBLE_BURSTING_SACK = 377, COLLECTIBLE_PAY_TO_PLAY = 380, COLLECTIBLE_SERAPHIM = 390, + COLLECTIBLE_EMPTY_VESSEL = 409, COLLECTIBLE_ZODIAC = 392, COLLECTIBLE_SERPENTS_KISS = 393, COLLECTIBLE_MARKED = 394, @@ -315,6 +322,7 @@ enum PlayerItemId : int COLLECTIBLE_GLOWING_HOUR_GLASS = 422, COLLECTIBLE_NIGHT_LIGHT = 425, COLLECTIBLE_HEAD_OF_THE_KEEPER = 429, + COLLECTIBLE_TAROT_CLOTH = 451, COLLECTIBLE_MOMS_BOX = 439, COLLECTIBLE_KIDNEY_STONE = 440, COLLECTIBLE_DARK_PRINCES_CROWN = 442, @@ -322,17 +330,20 @@ enum PlayerItemId : int COLLECTIBLE_LEAD_PENCIL = 444, COLLECTIBLE_BELLY_BUTTON = 458, COLLECTIBLE_GLAUCOMA = 460, + COLLECTIBLE_GLYPH_OF_BALANCE = 464, COLLECTIBLE_BROKEN_GLASS_CANNON = 474, COLLECTIBLE_SMELTER = 479, COLLECTIBLE_DATAMINER = 481, COLLECTIBLE_WAIT_WHAT = 484, COLLECTIBLE_METRONOME = 488, + COLLECTIBLE_D_INFINITY = 489, COLLECTIBLE_DEEP_POCKETS = 416, COLLECTIBLE_PLAN_C = 475, COLLECTIBLE_DUALITY = 498, COLLECTIBLE_EUCHARIST = 499, COLLECTIBLE_GREEDS_GULLET = 501, COLLECTIBLE_LITTLE_HORN = 503, + COLLECTIBLE_DELIRIOUS = 510, COLLECTIBLE_BROKEN_MODEM = 514, COLLECTIBLE_JUMPER_CABLES = 520, COLLECTIBLE_COUPON = 521, @@ -342,6 +353,7 @@ enum PlayerItemId : int COLLECTIBLE_SCHOOLBAG = 534, COLLECTIBLE_BROKEN_SHOVEL = 550, COLLECTIBLE_BROKEN_SHOVEL_1 = 550, + COLLECTIBLE_BRITTLE_BONES = 549, COLLECTIBLE_GOLDEN_RAZOR = 555, COLLECTIBLE_ALMOND_MILK = 561, COLLECTIBLE_DREAM_CATCHER = 566, @@ -361,6 +373,8 @@ enum PlayerItemId : int COLLECTIBLE_ETERNAL_D6 = 609, COLLECTIBLE_LARYNX = 611, COLLECTIBLE_BIRTHRIGHT = 619, + COLLECTIBLE_GENESIS = 622, + COLLECTIBLE_DEATH_CERTIFICATE = 628, COLLECTIBLE_KNIFE_PIECE_1 = 626, COLLECTIBLE_KNIFE_PIECE_2 = 627, COLLECTIBLE_EVIL_CHARM = 632, @@ -419,6 +433,7 @@ enum PlayerItemId : int COLLECTIBLE_STYE = 731, TRINKET_POOL_SHIFT = 2, TRINKET_PETRIFIED_POOP = 2, + TRINKET_PURPLE_HEART = 5, TRINKET_ROSARY_BEAD = 7, TRINKET_CALLUS = 14, TRINKET_PAPER_CLIP = 19, @@ -442,6 +457,7 @@ enum PlayerItemId : int TRINKET_COUNTERFEIT_PENNY = 52, TRINKET_MAGGYS_FAITH = 55, TRINKET_JUDAS_TONGUE = 56, + TRINKET_TICK = 53, TRINKET_CAINS_EYE = 59, TRINKET_EVES_BIRD_FOOT = 60, TRINKET_LEFT_HAND = 61, @@ -496,6 +512,8 @@ enum PlayerItemId : int NULLITEM_BLINDFOLD = 14, NULLITEM_BLANKFACE = 15, NULLITEM_CHRISTMAS = 16, + NULLITEM_PURITY_GLOW = 17, + NULLITEM_EMPTY_VESSEL = 18, NULLITEM_LAZARUS_BOOST = 49, NULLITEM_SPIN_TO_WIN = 50, NULLITEM_INTRUDER = 55, @@ -519,7 +537,9 @@ enum PlayerItemId : int PILLEFFECT_FULL_HEALTH = 5, PILLEFFECT_HEALTH_UP = 7, - PILLEFFECT_TELEPILLS = 19 + PILLEFFECT_TELEPILLS = 19, + PILLEFFECT_LARGER = 32, + PILLEFFECT_SMALLER = 33 }; // The unlocks the player's code checks or grants (Lua's Achievement). @@ -540,7 +560,8 @@ enum PlayerAchievement : int ACHIEVEMENT_SAMSON_HOLDS_CHILDS_HEART = 334, ACHIEVEMENT_TEARS_UP_ITEMS = 378, ACHIEVEMENT_MYSTERY_EGG = 387, - ACHIEVEMENT_GOLDEN_RAZOR = 583 + ACHIEVEMENT_GOLDEN_RAZOR = 583, + ACHIEVEMENT_GOLDEN_TRINKET = 617 }; // The challenges the player's code tells apart (Lua's Challenge). @@ -1020,6 +1041,7 @@ public: int reverseSunBoneHearts = 0; int samsonBerserkCharge = 0; int strengthMaxHearts = 0; + int itemHeartsOverflow = 0; short bloodLustCounter = 0; short brittleBonesUpgrades = 0; short damageMultiplierStacks = 0; @@ -1127,6 +1149,8 @@ public: Vector GetLaserOffset(int laserOffsetId, const Vector& direction); Entity_Laser* FireTechLaser(const TechLaserShot& shot); Entity_Laser* FireBrimstone(const Vector& direction, Entity* source, float damageMultiplier); + Entity_Laser* FireTechXLaser(const TechXShot& shot); + Entity_Knife* FireKnife(const KnifeShot& shot); Vector delayed_shoot_direction(); void ClearReferences() override; @@ -1411,6 +1435,7 @@ public: void ClearDeadEyeCharge(); int GetZodiacEffect(); void update_purity_glow(); + void ReplaceCostumeSprite(ItemConfig_Item* item, std::string_view path); void trigger_immaculate_conception(bool isCambion); void AddImmaculateConceptionCounter(int amount); void dash_impact(); diff --git a/src/entity_player_actives.cpp b/src/entity_player_actives.cpp index eadc794..92b9d5f 100644 --- a/src/entity_player_actives.cpp +++ b/src/entity_player_actives.cpp @@ -1,5 +1,9 @@ #include "entity_player.h" #include "entity_player_characters.h" +#include "console.h" +#include "entity_familiar.h" +#include "npc_ai.h" +#include "room_grid.h" #include "active_items.h" #include "entity_bomb.h" #include "entity_pickup.h" @@ -151,6 +155,34 @@ constexpr float SPIDER_BUTT_SLOW = 0.9f; constexpr float TAMMY_TEAR_DAMAGE = 25; constexpr float TAMMY_TEAR_SCALE = 1.355f; constexpr float TAMMY_TEAR_SPEED = 10; +constexpr int METRONOME_TRIES = 15; +constexpr uint32_t METRONOME_RNG_SHIFT = 15; +constexpr int METRONOME_EXCLUDED[] = {488, 475, 422, 326, 482, 636, 640}; +constexpr float METRONOME_DEATH_CERTIFICATE_CHANCE = 0.15f; +constexpr float METRONOME_GENESIS_CHANCE = 0.25f; + +// Delirious's friends: the bosses that come in pairs, how far apart, its hallucination and its wisps (00b62c80). +constexpr int DELIRIOUS_LARRY_JR = 19; +constexpr int DELIRIOUS_LOKI = 69; +constexpr int DELIRIOUS_LOKII = 1; +constexpr int DELIRIOUS_HEADLESS_HORSEMAN = 82; +constexpr int DELIRIOUS_HORSEMAN_HEAD = 83; +constexpr float DELIRIOUS_HORSEMAN_HEAD_HEALTH = 50; +constexpr int DELIRIOUS_GURGLING = 237; +constexpr float DELIRIOUS_PAIR_SPACING = 40; +constexpr float DELIRIOUS_HALF_TURN = 3.14f; +constexpr int DELIRIOUS_HALLUCINATION_FRAMES = 25; +constexpr std::array DELIRIOUS_WISPS = {65550, 65551, 65552, 65553}; + +// Game::ShowHallucination's sound, the backdrops a random one picks from (00b67fb0) and the floor it frames. +constexpr int SOUND_FRAME_DELAY_DEFAULT = 2; +constexpr float HALLUCINATION_VOLUME = 3; +constexpr float HALLUCINATION_PITCH = 0.5f; +constexpr int HALLUCINATION_BACKDROP_RANDOM = 63; +constexpr int HALLUCINATION_BACKDROP_NONE = 18; +constexpr std::array HALLUCINATION_BACKDROPS = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17}; +constexpr float HALLUCINATION_FLOOR_MARGIN = 52; +constexpr float HALLUCINATION_TILE = 26; constexpr ColorMod SPIDER_BUTT_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.f, 40 / 255.f, 40 / 255.f}}; // The giant book a book or die from a slot shows over the screen. @@ -1014,6 +1046,227 @@ static void spider_butt_use(ItemUse& use) } } +// Metronome's pick: a random collectible from its own generator, never Metronome itself or an item that would undo the +// room (Plan C, Glowing Hour Glass, Breath of Life, Clicker, R Key, Urn of Souls), none Cantripped forbids, Forget Me +// Now not in a daily, Death Certificate and Genesis only on a lucky roll. Fifteen tries, else none. +static int metronome_item_roll(Entity_Player& player) +{ + ItemConfig& config = g_manager->itemConfig; + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_METRONOME); + RNG chances = rng_make(rng.Next(), METRONOME_RNG_SHIFT); + + for (int i = 0; i < METRONOME_TRIES; i++) + { + int id = (int)rng.RandomInt((uint32_t)config.collectibles.size() - 1) + 1; + if (std::ranges::find(METRONOME_EXCLUDED, id) != std::end(METRONOME_EXCLUDED)) continue; + if (g_game->challenge == CHALLENGE_CANTRIPPED && ItemConfig::is_collectible_tagged(id, TAG_NO_CANTRIP)) continue; + if (id == COLLECTIBLE_DEATH_CERTIFICATE && chances.RandomFloat() >= METRONOME_DEATH_CERTIFICATE_CHANCE) continue; + if (id == COLLECTIBLE_GENESIS && chances.RandomFloat() >= METRONOME_GENESIS_CHANCE) continue; + if (g_game->dailyChallenge._id != 0 && id == COLLECTIBLE_FORGET_ME_NOW) continue; + if (!ItemConfig::IsValidCollectible(id) || !config.GetCollectible(id)) continue; + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (Metronome's pick in a versus match)"); + return id; + } + return 0; +} + +// Metronome: the item it lent last time goes back (with Pinking Shears' flight and an active's held state), then a new +// one is rolled, or the one the console chose. An active is used at once, a passive lent with its costume and pickups, +// and Book of Virtues adds a wisp. Without an item it only warns. +static void metronome_use(ItemUse& use) +{ + Entity_Player& player = use.player; + TemporaryEffects& effects = player.temporaryEffects; + ItemConfig& config = g_manager->itemConfig; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + if (int lent = player.metronomeCollectibleId) + { + effects.RemoveCollectibleEffect(COLLECTIBLE_METRONOME, 1); + effects.RemoveCollectibleEffect(lent, 1); + if (lent == COLLECTIBLE_PINKING_SHEARS && !player.HasCollectible(COLLECTIBLE_TRANSCENDENCE)) + effects.RemoveCollectibleEffect(COLLECTIBLE_TRANSCENDENCE, 1); + ItemConfig_Item* item = config.GetCollectible(lent); + if (item->type == ITEM_ACTIVE) player.ResetItemState(); + player.metronomeCollectibleId = 0; + if (!player.HasCollectible(lent)) player.RemoveCostume(item); + } + player.metronomeCollectibleId = g_metronomeItem != 0 ? g_metronomeItem : metronome_item_roll(player); + if (player.metronomeCollectibleId == 0) + { + log_printf(LOG_INFO, "[warn] No Collectible found for Metronome!\n"); + use.isLuaAnimationAllowed = false; + return use_animate(use); + } + + int id = player.metronomeCollectibleId; + log_printf(LOG_INFO, "Metronome Collectible %d\n", id); + ItemConfig_Item* item = config.GetCollectible(id); + if (item->type == ITEM_ACTIVE) + { + player.UseActiveItem({.item = id}); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed) player.AddWisp(id, player.pos, false, false); + } + else + { + player.AddCostume(item, false); + player.AddBombs(item->addBombs); + player.AddKeys(item->addKeys); + player.AddCoins(item->addCoins); + player.AddMaxHearts(item->addMaxHearts, false); + player.AddHearts(item->addHearts, false, false); + player.AddSoulHearts(item->addSoulHearts, false); + player.AddBlackHearts(item->addBlackHearts); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed) + player.AddWisp(Entity_Familiar::GetRandomWisp(&player.GetCollectibleRNG(id)), player.pos, false, false); + } + if (use.isShowAnimation && player.metronomeCollectibleId != 0) + player.AnimateCollectible(player.metronomeCollectibleId, "UseItem", "PlayerPickupSparkle"); +} + +// Delirious: a random boss from its list comes as a friend, the item raised by hand. +static void delirious_use(ItemUse& use) +{ + Entity_Player& player = use.player; + if (player.variant == PLAYER_VARIANT_PLAYER) + { + uint32_t boss = player.GetCollectibleRNG(COLLECTIBLE_DELIRIOUS).RandomInt(DELIRIOUS_BOSS_COUNT); + player.console_spawn(DELIRIOUS_BOSSES[boss], use.isWispAllowed); + } + use.isLuaAnimationAllowed = false; + use_animate(use); +} + +// One boss Delirious makes: where it stands, what it is, its health and how many. +struct DeliriousSpawn +{ + Vector position{}; + float health = 0; + int count = 0; + int type = 0; + int variant = 0; +}; + +// Whether a boss comes with a partner Delirious places across the player: Larry Jr., Lokii, the Headless Horseman (with +// its head) and the Gurglings. +static bool is_delirious_pair(const DeliriousBoss& boss) +{ + return boss.type == DELIRIOUS_LARRY_JR || (boss.type == DELIRIOUS_LOKI && boss.variant == DELIRIOUS_LOKII) || + boss.type == DELIRIOUS_GURGLING || boss.type == DELIRIOUS_HEADLESS_HORSEMAN; +} + +// Gives Delirium's look to the other segments of a chained boss: from its first segment down the children, until the +// chain comes back round. +static void delirious_segments_load(Entity* friendly) +{ + Entity* root = friendly; + while (root->parent) root = root->parent; + + Entity* previous = nullptr; + for (auto* segment = dynamic_cast(root); segment;) + { + auto* next = dynamic_cast(segment->child.get()); + if (segment == friendly && next == previous) break; + if (segment != friendly) + { + ANM2::LoadDeliriumForm(segment->sprite, segment->type, segment->variant, true); + previous = segment; + } + segment = next; + } +} + +// 005caa70 Delirious's friend: the friends it made before die (marked so they do not split), then the boss (and its +// partner 40 away across the player for the pairs) is spawned near where it stands, never a champion, charmed for good, drawn in +// Delirium's look, set to its health and kept between rooms. The room hallucinates, and Book of Virtues adds one of +// Delirious's wisps. A boss of type 0 only kills the old friends. +void Entity_Player::console_spawn(const DeliriousBoss& boss, bool isAddWisp) +{ + Game& game = *g_game; + EntityList_EL& entities = game.room->GetEntities()->updateEL; + + for (size_t i = 0; i < entities.size(); i++) + { + Entity* entity = entities[i]; + if (!entity->HasEntityFlags(FLAG_DELIRIUM_FORM) || entity->charmSource.entity != this) continue; + entity->AddEntityFlags(FLAG_NO_SPLIT); + entity->Kill(EntityRef()); + } + if (boss.type == 0) return; + + RNG& rng = GetCollectibleRNG(COLLECTIBLE_DELIRIOUS); + std::vector spawns = { + {.position = pos, .health = boss.health, .count = boss.count, .type = boss.type, .variant = boss.variant}}; + if (is_delirious_pair(boss)) + { + float angle = random_unit() * DELIRIOUS_HALF_TURN; + angle += angle; + Vector offset = vector_make(std::cos(angle) * DELIRIOUS_PAIR_SPACING, std::sin(angle) * DELIRIOUS_PAIR_SPACING); + DeliriousSpawn partner = spawns[0]; + partner.position = vector_make(pos.x + offset.x, pos.y + offset.y); + if (boss.type == DELIRIOUS_HEADLESS_HORSEMAN) + { + partner.type = DELIRIOUS_HORSEMAN_HEAD; + partner.health = DELIRIOUS_HORSEMAN_HEAD_HEALTH; + } + spawns.push_back(partner); + spawns[0].position = vector_make(pos.x - offset.x, pos.y - offset.y); + } + + std::vector friends; + for (const DeliriousSpawn& spawn : spawns) + for (int i = 0; i < spawn.count; i++) + { + g_isChampionRollSkipped = true; + uint32_t seed = rng.Next(); + Vector at = room_free_pickup_position_find({.position = spawn.position, .step = DELIRIOUS_PAIR_SPACING}); + Entity* friendly = + game.Spawn({.position = at, .spawner = this, .type = spawn.type, .variant = spawn.variant, .seed = seed}); + friendly->AddEntityFlags(FLAG_DELIRIUM_FORM | FLAG_PERSISTENT); + friendly->AddCharmed(EntityRef(this), -1, false, false); + static_cast(friendly)->isCanShutDoors = false; + friendly->health = spawn.health; + friendly->maxHitPoints = spawn.health; + ANM2::LoadDeliriumForm(friendly->sprite, friendly->type, friendly->variant, true); + friends.push_back(friendly); + } + for (Entity* friendly : friends) + { + friendly->Update(); + friendly->AddEntityFlags(FLAG_DONT_COUNT_BOSS_HP); + game.room->entityList.AddPersistentEntity(friendly); + delirious_segments_load(friendly); + } + + if (game.hallucinationTimer < 1) game.ShowHallucination(DELIRIOUS_HALLUCINATION_FRAMES, HALLUCINATION_BACKDROP_RANDOM); + if (HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && isAddWisp) + AddWisp(DELIRIOUS_WISPS[rng.Next() & (DELIRIOUS_WISPS.size() - 1)], pos, false, false); +} + +// 007059f0 Shows a hallucination for some frames with the death card's sound: a backdrop (1 to 62, a random common +// one for 63) replaces the room's, its details redrawn. Not in a room of backdrop 18 or a crawlspace. +void Game::ShowHallucination(int frames, int backdrop) +{ + int shown = std::min(std::max(backdrop, 0), HALLUCINATION_BACKDROP_RANDOM); + hallucinationDuration = frames; + hallucinationTimer = frames; + npc_sound_play(ACTIVE_SOUND_DEATH_CARD, HALLUCINATION_VOLUME, SOUND_FRAME_DELAY_DEFAULT, HALLUCINATION_PITCH); + if (shown == 0 || room->backdropType == HALLUCINATION_BACKDROP_NONE || room->roomType == ROOM_DUNGEON) return; + + if (shown == HALLUCINATION_BACKDROP_RANDOM) + shown = HALLUCINATION_BACKDROPS[Random() & (HALLUCINATION_BACKDROPS.size() - 1)]; + for (Entity* entity : room->GetEntities()->updateEL) + if (entity->HasEntityFlags(FLAG_BACKDROP_DETAIL)) entity->Remove(); + if (shown < 0 || shown >= HALLUCINATION_BACKDROP_RANDOM) shown = 1; + room->backdropType = shown; + room->floorScreenTopLeft = vector_make(HALLUCINATION_FLOOR_MARGIN, HALLUCINATION_FLOOR_MARGIN); + room->floorScreenBottomRight = + vector_make((float)(room->gridWidth - 2) * HALLUCINATION_TILE + HALLUCINATION_FLOOR_MARGIN, + (float)(room->gridHeight - 2) * HALLUCINATION_TILE + HALLUCINATION_FLOOR_MARGIN); + room->backdrop.load_details(); +} + // Runs an item's own effect. The items without one of their own only add their room effect, and the ones not // written yet stop the game, named by the release that added them. static void item_effect_run(ItemUse& use) @@ -1049,6 +1302,10 @@ static void item_effect_run(ItemUse& use) return razor_blade_use(use); case COLLECTIBLE_SPIDER_BUTT: return spider_butt_use(use); + case COLLECTIBLE_METRONOME: + return metronome_use(use); + case COLLECTIBLE_DELIRIOUS: + return delirious_use(use); } if (std::ranges::find(CASED_ACTIVES, use.id) == std::end(CASED_ACTIVES)) return; @@ -1312,7 +1569,8 @@ void Entity_Player::ControlActiveItem(int slot) } // The temporary effects the plain frame, stats and tears are written for: the first floor's actives that leave one, -// Whore of Babylon and Tainted Eve's, Dead Bird, Bloody Lust and Bloody Gust, and Lazarus' boost. Book of Belial and +// Whore of Babylon and Tainted Eve's, Dead Bird, Bloody Lust and Bloody Gust, Lazarus' boost, and Metronome's and +// Delirious' marks (the item Metronome lends counts as owned, so its own checks still apply). Book of Belial and // Razor Blade change the damage and tears, which are not written for effects yet. bool is_temporary_effect_plain(const TemporaryEffect& effect) { @@ -1332,7 +1590,9 @@ bool is_temporary_effect_plain(const TemporaryEffect& effect) COLLECTIBLE_WHORE_OF_BABYLON, COLLECTIBLE_DEAD_BIRD, COLLECTIBLE_BLOODY_LUST, - COLLECTIBLE_BLOODY_GUST}; + COLLECTIBLE_BLOODY_GUST, + COLLECTIBLE_METRONOME, + COLLECTIBLE_DELIRIOUS}; if (effect.item->type == ITEM_NULL) return effect.item->id == NULLITEM_LAZARUS_BOOST || effect.item->id == NULLITEM_BLOODY_BABYLON; diff --git a/src/entity_player_characters.cpp b/src/entity_player_characters.cpp index c007f71..1c99ddb 100644 --- a/src/entity_player_characters.cpp +++ b/src/entity_player_characters.cpp @@ -40,7 +40,6 @@ constexpr int SAFE_SPAWN_TRIES = 150; constexpr int NPC_TYPE_FIRST = 10; constexpr int NPC_TYPE_LAST = 999; constexpr int ROOM_IDX_DEBUG = -16; -constexpr int DIMENSION_ROOM_COUNT = 169; constexpr float FORGOTTEN_CHAIN_SCALE = 120; constexpr int MAGDALENE_PILL_TRIES = 10; constexpr int REVIVE_DAMAGE_COOLDOWN = 90; diff --git a/src/entity_player_collectibles.cpp b/src/entity_player_collectibles.cpp index dc877e7..97a986c 100644 --- a/src/entity_player_collectibles.cpp +++ b/src/entity_player_collectibles.cpp @@ -7,6 +7,7 @@ #include "log.h" #include "manager.h" #include +#include // The collectibles and null items losing an item names (Lua's CollectibleType and NullItemID). enum RemovalItem : int @@ -241,3 +242,15 @@ void Entity_Player::AnimateCollectible(int collectibleId, std::string_view animN heldSprite.offset = vector_make(0, HELD_SPRITE_RISE); PlayExtraAnimation(animName); } + +// 0075eff0 How many collectibles the player has, counting copies. +int Entity_Player::GetCollectibleCount() +{ + return std::accumulate(collectibleCounts.begin(), collectibleCounts.end(), 0); +} + +// 00753ac0 Whether the player is a helper body (the Forgotten's soul, Esau...) rather than a player of its own. +uint32_t Entity_Player::IsSubPlayer() +{ + return playerIndex < 0; +} diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index 2d1479c..e0ede89 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -1,12 +1,15 @@ +#include "entity_effect_combat.h" #include "entity_familiar.h" #include "entity_npc.h" #include "entity_player.h" #include "entity_player_characters.h" +#include "entity_tear.h" #include "game.h" #include "level.h" #include "log.h" #include "lua_engine.h" #include "manager.h" +#include "npc_ai.h" #include "room.h" #include #include @@ -66,15 +69,12 @@ constexpr uint32_t CHALLENGE_PAY_TO_PLAY = 24; constexpr int SOUND_NAIL_HURT_1 = 104; constexpr int SOUND_NAIL_HURT_2 = 106; -constexpr int SOUND_MOM_VOX = 84; -constexpr int SOUND_HEARTBEAT = 86; constexpr int SOUND_BOSS_DELAY_RANDOM = 130; constexpr int SOUND_BOSS_DELAY_MIN = 50; constexpr int SOUND_FRAME_DELAY = 2; constexpr uint64_t DAMAGE_INVINCIBLE_IGNORED = 1ull << 13; constexpr uint64_t DAMAGE_FAKE = 1ull << 21; -constexpr uint64_t DAMAGE_NO_MODIFIERS = 1ull << 25; constexpr uint64_t DAMAGE_IGNORED = 1ull << 34; constexpr uint64_t DAMAGE_NO_HURT_EFFECTS = 0x100d0400; constexpr uint64_t DAMAGE_ISAACS_HEART_PIERCE = 0x2820; @@ -93,6 +93,20 @@ constexpr int COOLDOWN_SCALE_MIN = 16; constexpr int COOLDOWN_SCALE_SHIFT = 3; constexpr int CROW_HEART_KEEP_2 = 25; constexpr int CROW_HEART_KEEP_3 = 50; + +// A bone heart's break: its shards and snap, and Brittle Bones' ring of tears. +constexpr ColorMod BONE_SHARD_COLOR = {{0.7f, 0.7f, 0.65f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int BONE_SHARD_COUNT = 8; +constexpr float BONE_SHARD_SPEED_MIN = 2; +constexpr float BONE_SHARD_SPEED_RANDOM = 3; +constexpr float BONE_SNAP_VOLUME = 0.7f; +constexpr float BONE_SNAP_PITCH_RANDOM = 0.2f; +constexpr float BRITTLE_BONES_TURN = 360; +constexpr int BRITTLE_BONES_TEARS = 10; +constexpr float BRITTLE_BONES_SPEED = 10; +constexpr float BRITTLE_BONES_SCALE = 1.355f; +constexpr float BRITTLE_BONES_DAMAGE_SCALE = 2; +constexpr float BRITTLE_BONES_DAMAGE_BONUS = 22; constexpr float DAMAGE_ROUNDING = 0.5f; constexpr float HALVED_DAMAGE = 0.5f; constexpr float HALVED_DAMAGE_DEATHMATCH = 0.75f; @@ -207,12 +221,6 @@ template static bool is_listed(const int (&ids)[N], int id) return std::ranges::find(ids, id) != std::end(ids); } -// A random number below max, or 0 for none (Isaac::Random 0067f010). -static int random_below(int max) -{ - return max == 0 ? 0 : (int)(Random() % (uint32_t)max); -} - // 007db330 A damage cooldown in frames, scaled down in versus. static int damage_cooldown_scale(int frames) { @@ -264,22 +272,122 @@ static int damage_amount_get(Entity_Player& player, float damage, uint64_t damag return amount; } -// Takes a hit's half hearts from soul hearts first, then red ones, marking the floor as hurt for the red heart deals. -// Bone hearts, Crow Heart and red heart hits are not written yet. -static void hearts_remove(Entity_Player& player, int amount, uint64_t damageFlags, bool isPenalized) +// The soul half hearts above the last bone heart, which a hit takes before the bone heart. +static int souls_above_bones_count(Entity_Player& player) { - if (player.boneHearts > 0) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (bone hearts)"); - if ((damageFlags & DAMAGE_RED_HEARTS) || player.HasTrinket(TRINKET_CROW_HEART)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (hits that take red hearts first)"); + int count = 0; + for (int slot = player.boneHearts + (player.soulHearts + 1) / 2 - 1; slot >= 0 && !player.IsBoneHeart(slot); slot--) + count = count == 0 && (player.soulHearts & 1) ? 1 : count + 2; + return std::min(count, player.soulHearts); +} + +// A bone heart breaking: bone shards and a snap, The Forgotten's floor marked as hurt, and Brittle Bones' ring of bone +// tears with its tears up. +static void bone_heart_break(Entity_Player& player, bool isPenalized) +{ + player.boneHearts--; + player.UpdateHeartDependentEffects(); + if (player.playerType == PLAYER_THEFORGOTTEN && isPenalized && !player.parent) + { + g_game->SetRedHeartDamage(); + g_game->room->isRedHeartDamaged = true; + } + game_particles_spawn({.color = BONE_SHARD_COLOR, .position = player.pos, .height = player.posOffset.y, + .speed = random_unit() * BONE_SHARD_SPEED_RANDOM + BONE_SHARD_SPEED_MIN, + .count = BONE_SHARD_COUNT, .variant = EFFECT_TOOTH_PARTICLE}); + voice_play(SOUND_BONE_SNAP, BONE_SNAP_VOLUME, SOUND_FRAME_DELAY, random_unit() * BONE_SNAP_PITCH_RANDOM + 1); + if (!player.HasCollectible(COLLECTIBLE_BRITTLE_BONES)) return; + + float turn = random_unit() * BRITTLE_BONES_TURN; + for (int i = 0; i < BRITTLE_BONES_TEARS; i++) + { + uint32_t seed = Random(); + Vector direction = vector_from_angle(((float)i / BRITTLE_BONES_TEARS + turn) * BRITTLE_BONES_TURN); + auto* tear = static_cast(g_game->Spawn({.position = player.pos, + .velocity = vector_scale(direction, BRITTLE_BONES_SPEED), + .spawner = &player, .type = ENTITY_TEAR, + .variant = TEAR_BONE, .seed = seed})); + TearParams params = player.GetTearHitParams(WEAPON_TEARS, 1, random_below(2) * 2 - 1, nullptr); + params.tearFlags.set(TEAR_BONE_FLAG); + tear->SetTearFlags(params.tearFlags); + tear->SetScale(params.tearScale * BRITTLE_BONES_SCALE); + tear->SetCollisionDamage(params.tearDamage * BRITTLE_BONES_DAMAGE_SCALE + BRITTLE_BONES_DAMAGE_BONUS); + tear->SetHeight(params.tearHeight); + tear->parent = &player; + tear->Update(); + } + player.brittleBonesUpgrades++; + player.cacheFlags |= CACHE_FIREDELAY; + player.EvaluateItems(); +} + +// Takes a hit's half hearts from the red hearts: rotten hearts double what they lose, a bone heart filled with red only +// loses its own heart, an eternal heart soaks up the hit (when red hearts are not hit first or not enough), and a red +// heart lost marks the floor as hurt unless Crow Heart keeps it. Returns what was taken. +static int red_hearts_remove(Entity_Player& player, int amount, bool isRedFirst, bool isBoneFilled, uint64_t damageFlags, + bool isPenalized) +{ + if (player.rottenHearts > 0 && player.eternalHearts < 1) + { + int rotten = isRedFirst ? std::max(0, player.rottenHearts * 2 - player.redHearts + amount) : amount; + amount += std::min(player.rottenHearts, rotten); + } + if (player.boneHearts > 0 && isBoneFilled) amount = std::min(amount, (player.redHearts & 1) ? 1 : 2); + if (player.eternalHearts > 0) + { + int unshielded = player.redHearts - (player.soulHearts + player.boneHearts < 1 ? 1 : 0) - player.rottenHearts; + if (!(damageFlags & DAMAGE_RED_HEARTS) || amount > unshielded) + { + amount = std::max(amount - player.eternalHearts, 0); + player.eternalHearts = 0; + } + } + + bool isRedLost = amount > player.rottenHearts * 2; + int rottenLost = isRedFirst ? std::max(0, player.rottenHearts * 2 - player.redHearts + amount) : amount; + player.rottenHearts = std::max(player.rottenHearts - (rottenLost + 1) / 2, 0); + player.AddHearts(-amount, false, false); + + bool isKeeper = player.playerType == PLAYER_KEEPER || player.playerType == PLAYER_KEEPER_B; + if (player.playerType == PLAYER_MAGDALENE_B) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Tainted Magdalene's red heart damage)"); + if (isRedLost && !isKeeper && !player.parent && isPenalized && amount > 0 && player.redHearts < player.maxHearts) + { + int multiplier = player.GetTrinketMultiplier(TRINKET_CROW_HEART); + uint32_t keptChance = multiplier == 2 ? CROW_HEART_KEEP_2 : multiplier >= 3 ? CROW_HEART_KEEP_3 : 0; + if (player.GetTrinketRNG(TRINKET_CROW_HEART).RandomInt(100) >= keptChance) + { + g_game->SetRedHeartDamage(); + g_game->room->isRedHeartDamaged = true; + } + } + return amount; +} + +// Takes a hit's half hearts: the soul hearts above the last bone heart first (a black heart among them sets off the +// Necronomicon), then a bone heart, then the red hearts. Red Heart damage and Crow Heart hit the red hearts first when +// there are enough. An eternal heart soaks up a hit that would empty the last heart. Golden hearts break with the +// hearts emptied. Returns what was taken. +static int hearts_remove(Entity_Player& player, int amount, uint64_t damageFlags, bool isPenalized) +{ int soulBoneCount = (player.soulHearts + 1) / 2 + player.boneHearts; int filledCount = (std::min(player.redHearts, player.maxHearts) + 1) / 2; + bool isRedAsked = (damageFlags & DAMAGE_RED_HEARTS) || player.HasTrinket(TRINKET_CROW_HEART); + bool isRedFirst = isRedAsked && player.redHearts >= amount; + int soulsAbove = player.boneHearts > 0 ? souls_above_bones_count(player) : player.soulHearts; + bool isBoneFilled = player.boneHearts > 0 && player.redHearts >= player.maxHearts + player.boneHearts * 2 - 1; - if (player.soulHearts > 0) + if (soulsAbove > 0 && !isRedFirst) { - amount = std::min(amount, player.soulHearts); + amount = std::min(amount, soulsAbove); for (int heart = player.soulHearts; heart > player.soulHearts - amount; heart--) - if (player.IsBlackHeart(heart)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (black hearts)"); + { + if (!player.IsBlackHeart(heart)) continue; + player.RemoveBlackHeart(heart); + player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM | USE_ALLOWNONMAIN}); + voice_play(SOUND_BLACK_POOF, 1, SOUND_FRAME_DELAY, 1); + } if (player.eternalHearts > 0 && player.redHearts < 1 && player.boneHearts < 1 && player.soulHearts - amount < 1) { amount = std::max(amount - player.eternalHearts, 0); @@ -287,33 +395,16 @@ static void hearts_remove(Entity_Player& player, int amount, uint64_t damageFlag } if (amount > 0) player.soulHearts -= std::min(player.soulHearts, amount); } - else + else if (player.boneHearts > 0 && !isBoneFilled && !isRedFirst) { - if (player.rottenHearts > 0 && player.eternalHearts < 1) amount += std::min(player.rottenHearts, amount); - if (player.eternalHearts > 0) + if (player.eternalHearts > 0 && player.redHearts < 1 && player.soulHearts < 1 && player.boneHearts < 2) { amount = std::max(amount - player.eternalHearts, 0); player.eternalHearts = 0; } - - bool isRedLost = amount > player.rottenHearts * 2; - player.rottenHearts = std::max(player.rottenHearts - (amount + 1) / 2, 0); - player.AddHearts(-amount, false, false); - - bool isKeeper = player.playerType == PLAYER_KEEPER || player.playerType == PLAYER_KEEPER_B; - if (player.playerType == PLAYER_MAGDALENE_B) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Tainted Magdalene's red heart damage)"); - if (isRedLost && !isKeeper && !player.parent && isPenalized && amount > 0 && player.redHearts < player.maxHearts) - { - int multiplier = player.GetTrinketMultiplier(TRINKET_CROW_HEART); - uint32_t keptChance = multiplier == 2 ? CROW_HEART_KEEP_2 : multiplier >= 3 ? CROW_HEART_KEEP_3 : 0; - if (player.GetTrinketRNG(TRINKET_CROW_HEART).RandomInt(100) >= keptChance) - { - g_game->SetRedHeartDamage(); - g_game->room->isRedHeartDamaged = true; - } - } + if (amount > 0) bone_heart_break(player, isPenalized); } + else amount = red_hearts_remove(player, amount, isRedFirst, isBoneFilled, damageFlags, isPenalized); player.update_greeds_gullet(); int golden = player.goldenHearts; @@ -322,6 +413,7 @@ static void hearts_remove(Entity_Player& player, int amount, uint64_t damageFlag for (; soulBoneCount > newSoulBoneCount && player.goldenHearts > 0; soulBoneCount--) player.goldenHearts--; for (; filledCount > newFilledCount && player.goldenHearts > 0; filledCount--) player.goldenHearts--; if (player.goldenHearts < golden) player.BreakGoldenHearts(golden - player.goldenHearts); + return amount; } // The items a landed hit sets off, Eve's Dead Bird and Samson's Bloody Lust the only ones written yet, then Tainted @@ -446,7 +538,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR if (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_THE_NAIL)) grunt = random_below(2) ? SOUND_NAIL_HURT_1 : SOUND_NAIL_HURT_2; voice_play(grunt, volume, SOUND_FRAME_DELAY, pitch); if (source.type == ENTITY_MOM || source.type == ENTITY_MOMS_HEART) - voice_play(source.type == ENTITY_MOM ? SOUND_MOM_VOX : SOUND_HEARTBEAT, 1, + voice_play(source.type == ENTITY_MOM ? SOUND_MOM_VOX_EVILLAUGH : SOUND_MOM_VOX_FILTERED_EVILLAUGH, 1, random_below(SOUND_BOSS_DELAY_RANDOM) + SOUND_BOSS_DELAY_MIN, 1); hit_items_check(*this, damageFlags, isPenalized); @@ -467,7 +559,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR if (game.debugFlags & DEBUG_INFINITE_HP) amount = 0; else if (amount > 0 && game.deathmatchManager.is_active()) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (versus hearts)"); - else if (amount > 0) hearts_remove(*this, amount, damageFlags, isPenalized); + else if (amount > 0) amount = hearts_remove(*this, amount, damageFlags, isPenalized); bool isAstral = HasCollectible(COLLECTIBLE_ASTRAL_PROJECTION) && !game.room->IsClear() && !temporaryEffects.HasCollectibleEffect(COLLECTIBLE_ASTRAL_PROJECTION) && !astralProjectionBody; diff --git a/src/entity_player_evaluate.cpp b/src/entity_player_evaluate.cpp index 555c936..2207501 100644 --- a/src/entity_player_evaluate.cpp +++ b/src/entity_player_evaluate.cpp @@ -66,9 +66,6 @@ constexpr int COOP_BUFF_LUCK = 4; // Candy Heart, Soul Locket, Experimental Treatment, Libra, Rock Bottom, Adrenaline, the pill items, Mega Mush, // Berserk!, Jupiter, Dogma, Purity. constexpr std::array EVALUATION_UNHANDLED_ITEMS = {671, 686, 240, 304, 562, 493, 654, 407, 625, 704, 594, 633, 556}; -// The weapon items, which the frame does not handle yet: Ludovico, Tech X, Spirit Sword, C Section, Dr. Fetus, -// Mom's Knife, Brimstone, Epic Fetus, Monstro's Lung. -constexpr std::array WEAPON_ITEMS = {329, 395, 579, 678, 52, 114, 118, 168, 229}; // The constants of the other sections: the collectibles, trinkets, null items and characters they ask about. constexpr int PILL_TEARS_UP = 16; @@ -1031,12 +1028,12 @@ void Entity_Player::EvaluateItems() cacheFlags = 0; } -// The collectibles the frame (00782af0) looks at itself, which its plain path does not cover yet. +// The collectibles the frame (00782af0) looks at itself, which its plain path does not cover yet. The weapon items are +// not among them: the frame and its items' part (update_effects 00794e50) never ask for them, their weapons do. constexpr std::array FRAME_ITEMS = {375, 397, 465, 493, 497, 534, 575, 593, 619, 632, 641, 59, 202, 210, 399}; // Whether the player's frame runs its plain path: a plain character holding none of the items the frame handles. bool Entity_Player::is_frame_plain() { - return is_character_plain() && !is_owning_any(*this, FRAME_ITEMS) && !is_owning_any(*this, WEAPON_ITEMS) && - !is_owning_any(*this, EVALUATION_UNHANDLED_ITEMS); + return is_character_plain() && !is_owning_any(*this, FRAME_ITEMS) && !is_owning_any(*this, EVALUATION_UNHANDLED_ITEMS); } diff --git a/src/entity_player_footprints.cpp b/src/entity_player_footprints.cpp index f0d0ad3..59a4704 100644 --- a/src/entity_player_footprints.cpp +++ b/src/entity_player_footprints.cpp @@ -1,6 +1,12 @@ +#include "entity_effect.h" +#include "entity_npc.h" #include "entity_player.h" #include "game.h" #include "item_config.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_render.h" // Without a costume that steps, a player steps every 6 frames, with the left foot every 12. constexpr int FOOTSTEP_PERIOD = 6; @@ -10,6 +16,34 @@ constexpr int LEFT_FOOTSTEP_PERIOD = 12; constexpr int FOOT_ANY = -1; constexpr int FOOT_LEFT = 0; +// A footprint lands 2 to the side of the player's path, in a stain of 0.9 of the floor's color that a step moves half +// the way toward the floor under it, its strength 0.3 of the way toward 0.7. A step faster than 0.4 a frame leaves a +// splat a tenth the size, and one faster than 1 splashes in water. +constexpr float FOOT_SIDE = 2; +constexpr float FOOTPRINT_ALPHA = 0.7f; +constexpr float FOOTPRINT_ALPHA_STEP = 0.3f; +constexpr float FOOTPRINT_FLOOR_SHARE = 0.9f; +constexpr float FOOTPRINT_COLOR_STEP = 0.5f; +constexpr float FOOTPRINT_SPLAT_SCALE = 0.1f; +constexpr float FOOTPRINT_SPEED_SQUARED = 0.16f; +constexpr float SPLASH_SPEED_SQUARED = 1; +constexpr int FOOTPRINT_COLOR_PRIORITY = 255; + +// Mega Mush's stomps: a shake and a dust cloud thrown up to 20 away at 0.7 of the player's speed, turning up to 5 a +// frame either way for 15 to 29 frames. +constexpr int STOMP_SHAKE_FRAMES = 5; +constexpr float STOMP_VOLUME = 0.5f; +constexpr float STOMP_DUST_SPEED = 0.7f; +constexpr float STOMP_DUST_SPREAD = 20; +constexpr float STOMP_DUST_TURN = 5; +constexpr uint32_t STOMP_DUST_EXTRA_FRAMES = 15; +constexpr int STOMP_DUST_FRAMES = 15; + +// A splash in water throws 3 to 7 drops. +constexpr uint32_t SPLASH_EXTRA_DROPS = 5; +constexpr int SPLASH_DROPS = 3; +constexpr int SPLASH_DROP_SUBTYPE = 1; + // 007b9940 Whether the player stepped this frame, with any foot or the left one. Mega Mush's body costume steps on its // animation's events, any other player on a steady cadence while walking on the ground and the game runs. bool Entity_Player::is_footstep_triggered(int foot) @@ -46,3 +80,109 @@ void Entity_Player::SetFootprintColor(KColor footColor, bool isAnyFrame) footprint._offset[1] = footColor._green; footprint._offset[2] = footColor._blue; } + +// The floor's texel under a world position, read from the backdrop's floor buffer: white off it, or without one (where +// the original crashed). +static KColor floor_texel_get(Room& room, Vector world) +{ + if (!room.backdrop.floorBuffer) return kcolor_rgba(1, 1, 1, 1); + + Vector screen = vector_sub(render_position_get(world, RENDER_SNAPPED), room.renderSurfaceTopLeft); + return image_texel_get(*room.backdrop.floorBuffer, (uint32_t)(int)screen.x, (uint32_t)(int)screen.y); +} + +// A Mega Mush stomp: its sound and a shake, and a dust cloud thrown from the foot. +static void mega_mush_stomp(Entity_Player& player, Vector foot) +{ + int sound = SOUND_FORESTBOSS_STOMPS; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = STOMP_VOLUME, .frameDelay = 1}); + game_shake_screen(STOMP_SHAKE_FRAMES); + + uint32_t seed = Random(); + Vector velocity = vector_scale(player.velocity, STOMP_DUST_SPEED); + Vector direction = random_direction(); + Vector at = vector_add(foot, vector_scale(direction, random_unit() * STOMP_DUST_SPREAD)); + auto* dust = static_cast(g_game->Spawn( + {.position = at, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed})); + float turn = Random() & 1 ? -1.0f : 1.0f; + dust->rotation = random_unit() * STOMP_DUST_TURN * turn; + dust->timeout = (int)(Random() % STOMP_DUST_EXTRA_FRAMES) + STOMP_DUST_FRAMES; + dust->lifespan = dust->timeout; + dust->Update(); +} + +// A step in water: a splash at the player's speed ahead of the foot and 3 to 7 drops sprayed from it. +static void water_step_splash(Entity_Player& player, Vector foot) +{ + Vector at = vector_add(foot, player.velocity); + Entity* splash = g_game->Spawn( + {.position = at, .spawner = &player, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_SPLASH, .seed = Random()}); + splash->velocity = player.velocity; + splash->Update(); + + for (int drops = (int)(Random() % SPLASH_EXTRA_DROPS) + SPLASH_DROPS; drops > 0; drops--) + { + uint32_t seed = Random(); + Vector drift = vector_scale(player.velocity, random_unit()); + Vector spray = vector_add(random_direction(), drift); + g_game->Spawn({.position = at, + .velocity = spray, + .spawner = &player, + .subType = SPLASH_DROP_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_WATER_SPLASH, + .seed = seed}) + ->Update(); + } +} + +// 007b8cb0 A walking player's footprints: their stain starts as the floor's color, and each step stains the footprint +// of its foot toward the floor under it, leaves a splat of it when fast, stomps with Mega Mush, splashes in water and +// wipes ash. Co-op babies, ghosts and holograms leave none. +void Entity_Player::update_footprints() +{ + if (variant != PLAYER_VARIANT_PLAYER || isCoopGhost || IsHologram()) return; + + Room& room = *g_game->room; + if (footprintColor2._tint[3] == 0) + { + KColor floor = floor_texel_get(room, pos); + ColorMod stain = footprintColor2; + stain._tint[0] = 0; + stain._tint[1] = 0; + stain._tint[2] = 0; + stain._tint[3] = FOOTPRINT_ALPHA; + stain._offset[0] = floor._red * FOOTPRINT_FLOOR_SHARE; + stain._offset[1] = floor._green * FOOTPRINT_FLOOR_SHARE; + stain._offset[2] = floor._blue * FOOTPRINT_FLOOR_SHARE; + footprintColor1 = footprintColor2 = stain; + } + if (!is_footstep_triggered(FOOT_ANY)) return; + + bool isLeft = is_footstep_triggered(FOOT_LEFT); + ColorMod& footprint = isLeft ? footprintColor2 : footprintColor1; + Vector across = vector_normalized(vector_make(velocity.y, -velocity.x)); + Vector side = vector_scale(across, isLeft ? -FOOT_SIDE : FOOT_SIDE); + Vector foot = vector_add(pos, side); + if (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) mega_mush_stomp(*this, foot); + + float speedSquared = vector_length_squared(velocity); + if (speedSquared > FOOTPRINT_SPEED_SQUARED) + { + Entity* splat = + g_game->Spawn({.position = foot, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + splat->sprite.scale = vector_make(FOOTPRINT_SPLAT_SCALE, FOOTPRINT_SPLAT_SCALE); + splat->SetColor(footprint, -1, FOOTPRINT_COLOR_PRIORITY, false, true); + splat->Update(); + } + + KColor floor = floor_texel_get(room, foot); + std::array floorColor = {floor._red, floor._green, floor._blue}; + footprint._tint[3] += (FOOTPRINT_ALPHA - footprint._tint[3]) * FOOTPRINT_ALPHA_STEP; + for (int i = 0; i < 3; i++) + footprint._offset[i] += (floorColor[i] * FOOTPRINT_FLOOR_SHARE - footprint._offset[i]) * FOOTPRINT_COLOR_STEP; + + if (room.waterAmount > 0 && speedSquared > SPLASH_SPEED_SQUARED) water_step_splash(*this, foot); + if (room.backdrop.isTempSurfaceUsed && speedSquared > FOOTPRINT_SPEED_SQUARED) room_ash_step_clear(room, foot); +} diff --git a/src/entity_player_forgotten.cpp b/src/entity_player_forgotten.cpp new file mode 100644 index 0000000..fe69954 --- /dev/null +++ b/src/entity_player_forgotten.cpp @@ -0,0 +1,647 @@ +#include "entity_player_forgotten.h" +#include "entity_familiar.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_projectile.h" +#include "game.h" +#include "hud.h" +#include "manager.h" +#include "menu_manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_descriptor.h" +#include "room_grid.h" +#include "room_transition.h" +#include +#include + +constexpr int FORGOTTEN_SWAP_COOLDOWN = 15; +constexpr int FORGOTTEN_SWAP_HOLD_COOLDOWN = 10; +constexpr int D_INFINITY_FACES = 10; +constexpr int D_INFINITY_FACE_SHIFT = 16; +constexpr int D_INFINITY_FACE_MASK = 0xffff; +constexpr int TAINTED_ISAAC_SLOTS = 8; +constexpr int TAINTED_ISAAC_BIRTHRIGHT_SLOTS = 12; +constexpr uint32_t DROP_HOLD_FRAMES = 120; +constexpr uint32_t SPECIAL_DAILY_NO_DROP = 4; +constexpr int ACTION_TRIGGER_DROP = 0x20; +constexpr int DROP_TRINKET_TRIES = 2; +constexpr int DROP_POCKET_TRIES = 4; +constexpr int POCKET_SLOT_FIRST_FILLED = -1; +constexpr int DROPPED_POCKET_COOLDOWN = 4; +constexpr uint32_t CHALLENGE_PRIDE_DAY = 28; +constexpr float GFUEL_HORN_VOLUME = 1.2f; +constexpr int GFUEL_HORN_SHAKE = 8; +constexpr int DARK_PRINCES_CROWN_RED_HEARTS = 2; +constexpr float DARK_PRINCES_CROWN_DEATHMATCH_MIN = 0.1f; +constexpr float DARK_PRINCES_CROWN_DEATHMATCH_MAX = 0.3f; +constexpr float DARK_PRINCES_CROWN_OFFSET_Y = -7; + +// The swap's poofs: the white trail of puffs from The Soul to the body, its speed and size, and the projectiles the +// body clears as The Forgotten gets up. +constexpr ColorMod FORGOTTEN_SWAP_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 1, 1}}; +constexpr int FORGOTTEN_SWAP_FLASH_FRAMES = 8; +constexpr int SWAP_FLASH_PRIORITY = 255; +constexpr float SWAP_POOF_SPEED_SCALE = 0.1f; +constexpr float SWAP_POOF_SPEED_MAX = 4; +constexpr int SWAP_POOF_SUBTYPE = 10; +constexpr float SWAP_TRAIL_SPACING = 20; +constexpr int SWAP_TRAIL_MIN = 4; +constexpr int SWAP_TRAIL_MAX = 12; +constexpr float SWAP_TRAIL_TURN = 3.14f; +constexpr float SWAP_TRAIL_SPREAD = 15; +constexpr float SWAP_TRAIL_SPEED_MIN = 0.5f; +constexpr float SWAP_TRAIL_SIZE_MIN = 0.3f; +constexpr float SWAP_TRAIL_HEIGHT = -16; +constexpr int SWAP_BODY_SETTLE_FRAMES = 10; +constexpr float SWAP_BODY_CLEAR_RADIUS = 25; +constexpr float SWAP_PROJECTILE_HEIGHT_MIN = -50; + +// The body lying in a room: the grid path mark it leaves, the crawlspace's drag, and the shots it draws to itself. +constexpr int FORGOTTEN_BODY_GRID_PATH = 950; +constexpr int FORGOTTEN_BODY_LEFT_GRID_PATH = 900; +constexpr float FORGOTTEN_BODY_DUNGEON_FRICTION = 0.95f; +constexpr float FORGOTTEN_BODY_LURE_RADIUS = 30; +constexpr float FORGOTTEN_BODY_LURE_TURN_MAX = 0.99f; +constexpr float HALF_TURN_RADIANS = 3.1415927f; + +// The chain from The Soul to the body: its eight links spread along it, how far The Soul strays before it pulls, and +// its colour on a co-op ghost. +constexpr int CHAIN_LINK_FIRST = 2; +constexpr int CHAIN_LINK_END = 10; +constexpr float CHAIN_LINK_SPACING = 10; +constexpr float CHAIN_ANCHOR_SPAN = 0.1f; +constexpr float CHAIN_PULL = 0.01f; +constexpr float CHAIN_BODY_PULL = 0.5f; +constexpr float CHAIN_HEIGHT = 16; +constexpr int CHAIN_SUBTYPE_LINK = 1; +constexpr int BABY_GHOST_SOUL = 58; +constexpr ColorMod CHAIN_GHOST_COLOR = {{1, 0.05f, 0.12f, 0.2f}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The Purity glow's sheets by its state (00b6bb40). +constexpr std::string_view PURITY_GLOW_SHEETS[] = { + "gfx/characters/costumes/PurityGlow_red.png", "gfx/characters/costumes/PurityGlow_blue.png", + "gfx/characters/costumes/PurityGlow_yellow.png", "gfx/characters/costumes/PurityGlow_orange.png"}; + +// Puts a crown's float animation on, unless it already plays it (a looping one that stopped starts over). +static void crown_animation_set(ANM2& crown, std::string_view animation) +{ + const AnimationState& state = crown.animState; + bool isKept = state.animData && crown.GetAnimation() == animation && !(state.IsLoopingAnimation() && !state.isPlaying); + if (isKept || !crown.SetAnimation(animation)) return; + crown.animState.Rewind(); + crown.animState.isPlaying = true; +} + +// The flash a player gives when The Forgotten and The Soul swap: its own colour lit up for eight frames. +static void swap_flash(Entity_Player& player) +{ + ColorMod flash = player.sprite.color; + color_multiply(flash, FORGOTTEN_SWAP_FLASH); + player.SetColor(flash, FORGOTTEN_SWAP_FLASH_FRAMES, SWAP_FLASH_PRIORITY, true, false); +} + +// The trail of white puffs The Soul leaves on its way back into the body, thicker the further it flies. +static void swap_trail_spawn(Entity_Player& player, Vector toBody, Vector poofVelocity) +{ + Vector bodyPos = player.forgottenBody->pos; + int count = std::clamp((int)std::floor(vector_length(toBody) / SWAP_TRAIL_SPACING), SWAP_TRAIL_MIN, SWAP_TRAIL_MAX); + + for (int i = 1; i <= count; i++) + { + float t = (float)i / (float)(count + 1); + Vector along = vector_make(player.pos.x + (bodyPos.x - player.pos.x) * t, + player.pos.y + (bodyPos.y - player.pos.y) * t); + float angle = random_unit() * SWAP_TRAIL_TURN; + angle += angle; + float spread = random_unit(); + Vector spot = vector_make(std::cos(angle) * spread * SWAP_TRAIL_SPREAD + along.x, + along.y + spread * std::sin(angle) * SWAP_TRAIL_SPREAD); + uint32_t seed = Random(); + float speed = random_unit() * SWAP_TRAIL_SPEED_MIN + SWAP_TRAIL_SPEED_MIN; + Entity* puff = g_game->Spawn({.position = spot, .velocity = vector_scale(poofVelocity, speed), + .type = ENTITY_EFFECT, .variant = EFFECT_HAEMO_TRAIL, .seed = seed}); + puff->SetColor(FORGOTTEN_SWAP_FLASH, -1, SWAP_FLASH_PRIORITY, false, false); + float size = random_unit() * SWAP_TRAIL_SIZE_MIN + SWAP_TRAIL_SIZE_MIN; + puff->sprite.scale = vector_make(size * t, size * t); + puff->posOffset = vector_make(player.posOffset.x, player.sprite.scale.y * SWAP_TRAIL_HEIGHT + player.posOffset.y); + } +} + +// The Soul going back into the body: the puffs (unless quiet), the projectiles about a settled body cleared, then The +// Forgotten stands where the body lay and the body goes. +static void soul_return(Entity_Player& player, bool isNoEffects) +{ + Entity_Familiar* body = player.forgottenBody; + Vector toBody = body ? vector_sub(body->pos, player.pos) : Vector{}; + Vector poofVelocity = vector_scale(toBody, SWAP_POOF_SPEED_SCALE); + + if (!isNoEffects) + { + if (body) + { + if (vector_length(poofVelocity) > SWAP_POOF_SPEED_MAX) poofVelocity = vector_resized(poofVelocity, SWAP_POOF_SPEED_MAX); + swap_trail_spawn(player, toBody, poofVelocity); + } + Entity* poof = g_game->Spawn({.position = player.pos, .velocity = poofVelocity, .subType = SWAP_POOF_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_POOF02, .seed = Random()}); + poof->posOffset = player.posOffset; + poof->sprite.scale = player.sprite.scale; + if (body && g_game->frameCount - body->spawnFrame > SWAP_BODY_SETTLE_FRAMES) + for (Entity* entity : entity_query_radius(body->pos, body->size + SWAP_BODY_CLEAR_RADIUS, QUERY_PROJECTILES)) + { + auto* projectile = static_cast(entity); + if (projectile->isDead || projectile->height <= SWAP_PROJECTILE_HEIGHT_MIN) continue; + projectile->projectileFlags = 0; + projectile->isDead = true; + } + } + if (!body) return; + + player.Teleport(body->pos, false, false); + player.velocity = {}; + body->Remove(); +} + +// The swap's Whore of Babylon: its effects are taken off and put back, less one when the old form woke it, and the new +// form wakes it again at one red heart. +static void babylon_reapply(Entity_Player& player, bool wasAwake) +{ + TemporaryEffects& effects = player.temporaryEffects; + int count = effects.GetCollectibleEffectNum(COLLECTIBLE_WHORE_OF_BABYLON); + + for (int i = 0; i < count; i++) effects.RemoveCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON, 1); + int kept = wasAwake ? count - 1 : count; + if (player.HasCollectible(COLLECTIBLE_WHORE_OF_BABYLON) && !effects.HasCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON)) + { + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_WHORE_OF_BABYLON); + if (!item->isAddCostumeOnPickup) player.RemoveCostume(item); + if (player.redHearts < 2) effects.AddCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON, true, 1); + } + for (int i = 0; i < kept; i++) effects.AddCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON, true, 1); +} + +// The swap's heart effects for the new form: Empty Vessel's flight with no red hearts, Crown of Light's glow at full red +// health unhurt this room, and Dark Prince's Crown's at two red hearts (a share in versus), with the crowns' floats. +static void swap_crowns_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + ItemConfig& config = g_manager->itemConfig; + + effects.RemoveCollectibleEffect(COLLECTIBLE_EMPTY_VESSEL, 1); + if (player.HasCollectible(COLLECTIBLE_EMPTY_VESSEL) && !effects.HasCollectibleEffect(COLLECTIBLE_EMPTY_VESSEL)) + { + player.RemoveCostume(config.GetNullItem(NULLITEM_EMPTY_VESSEL)); + if (player.redHearts < 1) + { + effects.AddCollectibleEffect(COLLECTIBLE_EMPTY_VESSEL, true, 1); + player.AddCostume(config.GetNullItem(NULLITEM_EMPTY_VESSEL), false); + } + } + + if (player.HasCollectible(COLLECTIBLE_CROWN_OF_LIGHT)) + { + bool isLit = !player.isHurtThisRoom && player.redHearts >= player.GetEffectiveMaxHearts(); + if (isLit && !effects.HasCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT)) + { + effects.AddCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT, true, 1); + crown_animation_set(player.crownOfLightSprite, "FloatGlow"); + } + else if (!isLit && effects.HasCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT)) + { + effects.RemoveCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT, 1); + crown_animation_set(player.crownOfLightSprite, "FloatNoGlow"); + } + } + if (!player.HasCollectible(COLLECTIBLE_DARK_PRINCES_CROWN)) return; + + float share = (float)player.redHearts / (float)player.maxHearts; + bool isLit = g_game->deathmatchManager.is_active() + ? share >= DARK_PRINCES_CROWN_DEATHMATCH_MIN && share <= DARK_PRINCES_CROWN_DEATHMATCH_MAX + : player.redHearts == DARK_PRINCES_CROWN_RED_HEARTS; + if (isLit && !effects.HasCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN)) + { + effects.AddCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN, true, 1); + crown_animation_set(player.darkPrincesCrownSprite, "FloatGlow"); + } + else if (!isLit && effects.HasCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN)) + { + effects.RemoveCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN, 1); + crown_animation_set(player.darkPrincesCrownSprite, "FloatNoGlow"); + } + player.darkPrincesCrownSprite.offset = + player.HasCollectible(COLLECTIBLE_CROWN_OF_LIGHT) ? vector_make(0, DARK_PRINCES_CROWN_OFFSET_Y) : Vector{}; +} + +// 007cc200 Swaps The Forgotten and The Soul (or, when forced, Tainted Jacob and his ghost) with the sub player: their +// hearts, character, tear side and weapons trade places. The Soul leaves the body where The Forgotten stood and The +// Forgotten gets up from it (with Birthright the body may be in another room, which the swap travels to). The heart +// effects are settled again for the new form. False when the swap is refused: on cooldown, an empty Soul, or a +// transition. +bool Entity_Player::SwapForgottenForm(bool isForce, bool isNoEffects) +{ + Game& game = *g_game; + if (!subPlayer) return false; + + bool isForgotten = playerType == PLAYER_THEFORGOTTEN || playerType == PLAYER_THESOUL; + bool isJacob = playerType == PLAYER_JACOB_B || playerType == PLAYER_JACOB2_B; + if (isForgotten && !isForce) + { + if (forgottenSwapFormCooldown > 0) return false; + if (subPlayer->redHearts < 1 && subPlayer->soulHearts < 1 && subPlayer->boneHearts < 1) return false; + if (game.roomTransition.mode != TRANSITION_NONE || game.stageTransition.state != STAGE_TRANSITION_NONE || + game.deathCertificateExitTimer > 0) + return false; + } + else if (!isForgotten && (!isJacob || !isForce)) return false; + + if (isForgotten && !isNoEffects) forgottenSwapFormCooldown = FORGOTTEN_SWAP_COOLDOWN; + RemoveSkinCostume(); + bool wasBabylonAwake = HasCollectible(COLLECTIBLE_WHORE_OF_BABYLON) && redHearts <= 1; + for (int slot = 1; slot < WEAPON_SLOT_COUNT; slot++) + if (weapons[slot]) weapons[slot]->ClearReferences(); + + Entity_Player& other = *subPlayer; + std::swap(redHearts, other.redHearts); + std::swap(maxHearts, other.maxHearts); + std::swap(soulHearts, other.soulHearts); + std::swap(blackHearts, other.blackHearts); + std::swap(eternalHearts, other.eternalHearts); + std::swap(boneHearts, other.boneHearts); + std::swap(boneHeartsMask, other.boneHeartsMask); + std::swap(brokenHearts, other.brokenHearts); + std::swap(rottenHearts, other.rottenHearts); + std::swap(reverseEmpressMaxHearts, other.reverseEmpressMaxHearts); + std::swap(goldenHearts, other.goldenHearts); + std::swap(playerType, other.playerType); + std::swap(tearDisplacement, other.tearDisplacement); + std::swap(strengthMaxHearts, other.strengthMaxHearts); + std::swap(itemHeartsOverflow, other.itemHeartsOverflow); + std::swap(weaponTypes, other.weaponTypes); + std::swap_ranges(weapons.begin() + 1, weapons.end(), other.weapons.begin() + 1); + for (int slot = 1; slot < WEAPON_SLOT_COUNT; slot++) + if (weapons[slot]) weapons[slot]->owner = this; + + if (playerType == PLAYER_THESOUL) + { + if (!isNoEffects || !forgottenBody) spawn_forgotten_body(); + ResetColor(); + if (!isNoEffects) swap_flash(*this); + } + else if (playerType == PLAYER_THEFORGOTTEN) + { + int roomIdx = forgottenBodyRoomIdx >= 0 ? forgottenBodyRoomIdx % DIMENSION_ROOM_COUNT : forgottenBodyRoomIdx; + int dimension = forgottenBodyRoomIdx >= 0 ? forgottenBodyRoomIdx / DIMENSION_ROOM_COUNT : 0; + bool isBodyAway = !forgottenBody && forgottenBodyRoomIdx != FORGOTTEN_BODY_ROOM_NONE && + game.GetRoomByIdx(roomIdx, dimension) != game.room->descriptor; + if (isBodyAway && HasCollectible(COLLECTIBLE_BIRTHRIGHT)) + { + game.leaveDoor = -1; + game.StartRoomTransition({.player = this, .animation = TRANSITION_FORGOTTEN_TELEPORT, + .direction = DIRECTION_NONE, .dimension = dimension, .roomIndex = roomIdx}); + forgottenBodyRoomIdx = FORGOTTEN_BODY_ROOM_NONE; + } + else soul_return(*this, isNoEffects); + ResetColor(); + if (!isNoEffects) swap_flash(*this); + forgottenBodyRoomIdx = FORGOTTEN_BODY_ROOM_NONE; + } + + babylon_reapply(*this, wasBabylonAwake); + swap_crowns_update(*this); + cacheFlags |= CACHE_ALL; + itemHoldCooldown = FORGOTTEN_SWAP_HOLD_COOLDOWN; + EvaluateItems(); + stop_costume_item_anims(); + update_player_skin(); + update_purity_glow(); + return true; +} + +// 007c7a20 Gives every layer of the costume an item wears a new spritesheet. Co-op babies and ghosts wear none. +void Entity_Player::ReplaceCostumeSprite(ItemConfig_Item* item, std::string_view path) +{ + if (variant == PLAYER_VARIANT_COOP_BABY || isCoopGhost || !item) return; + + for (CostumeSpriteDesc& costume : costumeSpriteDescs) + { + if (costume.item != item) continue; + for (int layer = 0; layer < (int)costume.sprite.layerStates.size(); layer++) + costume.sprite.ReplaceSpritesheet(layer, path); + costume.sprite.LoadGraphics(); + } +} + +// 007c7c60 Colours Purity's glow by its state. A state past the four logs an error and, where the original read past +// its table, keeps the last colour. +void Entity_Player::update_purity_glow() +{ + int state = purityState; + if (state > (int)std::size(PURITY_GLOW_SHEETS) - 1) + { + KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"[err] Purity has a wrong state!"); + state = (int)std::size(PURITY_GLOW_SHEETS) - 1; + } + ReplaceCostumeSprite(g_manager->itemConfig.GetNullItem(NULLITEM_PURITY_GLOW), PURITY_GLOW_SHEETS[state]); +} + +// The pocket a slot names, -1 the first holding a card or pill, or the slot count when none does. +static int pocket_slot_resolve(Entity_Player& player, int slot) +{ + if (slot != POCKET_SLOT_FIRST_FILLED) return slot; + for (slot = 0; slot < POCKET_SLOT_COUNT; slot++) + if (player.pocketItems[slot].id != 0 && player.pocketItems[slot].type != POCKET_ACTIVE) return slot; + return POCKET_SLOT_COUNT; +} + +// Takes a card or pill out of its pocket, the pockets behind moving up and the last one emptied. The Red Key's door +// hints are redrawn. +static void pocket_slot_clear(Entity_Player& player, int slot) +{ + std::move(player.pocketItems.begin() + slot + 1, player.pocketItems.end(), player.pocketItems.begin() + slot); + player.pocketItems[POCKET_SLOT_COUNT - 1] = {.id = 0, .type = POCKET_CARD}; + g_game->room->UpdateRedKey(); +} + +// 00753900 The pocket in a slot, clamped to the four. +PocketItem& Entity_Player::GetPocketItem(int slot) +{ + return pocketItems[std::clamp(slot, 0, POCKET_SLOT_COUNT - 1)]; +} + +// 007a4850 Removes the card or pill in a slot (-1 for the first), never a pocket active. +void Entity_Player::RemovePocketItem(int slot) +{ + slot = pocket_slot_resolve(*this, slot); + if (slot >= POCKET_SLOT_COUNT || pocketItems[slot].id == 0 || pocketItems[slot].type == POCKET_ACTIVE) return; + pocket_slot_clear(*this, slot); +} + +// 007a48f0 Drops the card or pill in a slot (-1 for the first) at a position as its pickup, which the player cannot +// take back for four frames. +void Entity_Player::DropPocketItem(int slot, Vector position) +{ + slot = pocket_slot_resolve(*this, slot); + if (slot >= POCKET_SLOT_COUNT || pocketItems[slot].id == 0 || pocketItems[slot].type == POCKET_ACTIVE) return; + + PocketItem& held = pocketItems[slot]; + int variant = held.type == POCKET_CARD ? PICKUP_TAROTCARD : PICKUP_PILL; + Entity* pickup = g_game->Spawn({.position = position, .spawner = this, .subType = held.id, .type = ENTITY_PICKUP, + .variant = variant, .seed = Random()}); + if (pickup) static_cast(pickup)->collisionCooldown = DROPPED_POCKET_COOLDOWN; + pocket_slot_clear(*this, slot); +} + +// The drop button's turn of the pockets: each filled pocket moves one slot forward and the first goes last. +static void pocket_items_rotate(Entity_Player& player) +{ + for (int slot = 1; slot < POCKET_SLOT_COUNT && player.pocketItems[slot].id != 0; slot++) + { + std::swap(player.pocketItems[slot], player.pocketItems[slot - 1]); + g_game->hud.refresh_request(HUD_REFRESH_PLAYER); + } +} + +// The drop button's turn of the active slots: D Infinity shows its next face first and swaps only past its last. +static void active_items_rotate(Entity_Player& player) +{ + ActiveItemDesc& active = player.activeItems[ACTIVE_SLOT_PRIMARY]; + if (active.item == COLLECTIBLE_D_INFINITY) + { + uint32_t face = (uint32_t)((active.varData >> D_INFINITY_FACE_SHIFT) + 1) % D_INFINITY_FACES; + active.varData = (int)(face << D_INFINITY_FACE_SHIFT) | (active.varData & D_INFINITY_FACE_MASK); + g_game->hud.InvalidateActiveItem(&player, ACTIVE_SLOT_PRIMARY); + if (face != 0) return; + } + player.SwapActiveItems(); +} + +// The drop button's turn of the tainted inventories: Tainted Isaac's items and Tainted Cain's bag and item cards. +static void tainted_inventory_rotate(Entity_Player& player) +{ + HUD& hud = g_game->hud; + + if (player.playerType == PLAYER_ISAAC_B) + { + int limit = player.HasCollectible(COLLECTIBLE_BIRTHRIGHT) ? TAINTED_ISAAC_BIRTHRIGHT_SLOTS : TAINTED_ISAAC_SLOTS; + auto end = std::find_if(player.inventory.begin(), player.inventory.begin() + limit, [](int entry) { return entry < 0; }); + if (end - player.inventory.begin() > 1) + { + std::rotate(player.inventory.begin(), player.inventory.begin() + 1, end); + hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + } + } + if (player.playerType != PLAYER_CAIN_B) return; + + std::array& bag = player.bagOfCraftingContent; + char first = bag[0]; + if (first != 0 && bag[1] != 0) + { + int slot = 0; + for (; slot < BAG_OF_CRAFTING_SIZE - 1 && bag[slot + 1] != 0; slot++) bag[slot] = bag[slot + 1]; + bag[slot] = first; + } + if (player.itemCards.size() > 1) + { + std::rotate(player.itemCards.begin(), player.itemCards.begin() + 1, player.itemCards.end()); + hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + } +} + +// The drop button held two seconds: the trinkets (but Tick, and Rainbow Worm in Pride Day) and the cards and pills go +// to the floor. +static void drop_hold_update(Entity_Player& player) +{ + Game& game = *g_game; + bool isAnythingToDrop = false; + + player.actionHoldDrop = 0; + for (uint32_t trinket : player.trinkets) + { + if (trinket == 0) continue; + if (game.deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::pockets_rotate 007a42b0 (a versus mode's trinket drop)"); + if (trinket != TRINKET_TICK && !(trinket == TRINKET_RAINBOW_WORM && game.challenge == CHALLENGE_PRIDE_DAY)) + isAnythingToDrop = true; + } + for (uint32_t slot = 0; slot < player.GetMaxPocketItems(); slot++) + if (player.pocketItems[slot].id != 0 && player.pocketItems[slot].type != POCKET_ACTIVE) isAnythingToDrop = true; + if (!isAnythingToDrop) return; + + game.hud.refresh_request(HUD_REFRESH_PLAYER); + player.lastActionTriggers |= ACTION_TRIGGER_DROP; + for (int i = 0; i < DROP_TRINKET_TRIES; i++) + { + player.DropTrinket(room_free_pickup_position_find({.position = player.pos}), false); + if (player.variant == PLAYER_VARIANT_PLAYER && !player.isCoopGhost) player.InvalidateCoPlayerItems(); + } + for (int i = 0; i < DROP_POCKET_TRIES; i++) + player.DropPocketItem(POCKET_SLOT_FIRST_FILLED, room_free_pickup_position_find({.position = player.pos})); +} + +// 007a42b0 The drop button. A press swaps The Forgotten and The Soul, or else turns the pockets and, with no item state +// up, the active slots. Tainted Isaac's inventory and Tainted Cain's bag turn too, and the G FUEL! seed honks. Held two +// seconds (not in the daily that forbids it) it drops the trinkets and pocket items. The write the hold makes to a +// field nothing reads (+0x1880) is left out. +void Entity_Player::pockets_rotate() +{ + Game& game = *g_game; + if (variant != PLAYER_VARIANT_PLAYER || isCoopGhost || IsHologram()) return; + + if (forgottenSwapFormCooldown > 0) forgottenSwapFormCooldown--; + if (input_is_action_triggered(ACTION_DROP, controllerIndex, this)) + { + if (!SwapForgottenForm(false, false)) + { + pocket_items_rotate(*this); + if (itemState == 0) active_items_rotate(*this); + } + tainted_inventory_rotate(*this); + if (g_fuel_count() > 0) + { + npc_sound_play(SOUND_GFUEL_AIR_HORN, GFUEL_HORN_VOLUME, 1, 1); + game_shake_screen(GFUEL_HORN_SHAKE); + } + } + + if (!input_is_action_pressed(ACTION_DROP, controllerIndex, this)) + { + actionHoldDrop = 0; + return; + } + if ((uint32_t)++actionHoldDrop > DROP_HOLD_FRAMES && game.dailyChallenge._specialDailyId != SPECIAL_DAILY_NO_DROP) + drop_hold_update(*this); +} + +// 0060de70 (the body's case) Lies on the floor, or floats in the Beast's dungeon, unmoved by knockback. It appears +// with its animation unless the room has just started. +void forgotten_body_init(Entity_Familiar& body) +{ + Room& room = *g_game->room; + bool isFresh = room.GetFrameCount() < 2; + bool isFloating = room.IsBeastDungeon(); + + body.AddEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK | FLAG_DONT_OVERWRITE); + body.entityGridCollisionClass = isFloating ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; + if (isFloating) body.sprite.Play(isFresh ? "FlyingIdle" : "FlyingAppear"); + else body.sprite.Play(isFresh ? "Idle" : "Appear"); +} + +// 0061da10 (the body's case) Plays its idle on the floor or in the air and holds its place, marking its grid square +// (in a crawlspace it slides to a stop instead). Enemy shots that pass closer to the body than to the player are bent +// towards it, the more the more they head away. +void forgotten_body_update(Entity_Familiar& body) +{ + Room& room = *g_game->room; + + if (body.sprite.IsFinished()) body.sprite.Play(body.entityGridCollisionClass != GRIDCOLL_WALLS ? "Idle" : "FlyingIdle"); + if (room.roomType != ROOM_DUNGEON) + { + if (vector_is_zero(body.targetPosition)) + { + body.pathfinder.UpdateGridIndex(); + body.targetPosition = body.pos; + } + body.velocity = vector_sub(body.targetPosition, body.pos); + room.SetGridPath(body.pathfinder.gridIndex, FORGOTTEN_BODY_GRID_PATH); + } + else body.friction *= FORGOTTEN_BODY_DUNGEON_FRICTION; + + for (Entity* shot : entity_query_radius(body.pos, FORGOTTEN_BODY_LURE_RADIUS, QUERY_PROJECTILES)) + { + if (shot->HasEntityFlags(FLAG_FRIENDLY)) continue; + Vector toBody = vector_sub(body.pos, shot->pos); + if (vector_length_squared(toBody) >= vector_length_squared(vector_sub(shot->pos, body.player->pos))) continue; + + Vector heading = vector_normalized(shot->velocity); + Vector lure = vector_normalized(toBody); + Vector lured = vector_scale(lure, vector_length(shot->velocity)); + float kept = std::min(FORGOTTEN_BODY_LURE_TURN_MAX, std::acos(vector_dot(heading, lure)) / HALF_TURN_RADIANS); + shot->velocity = vector_add(vector_scale(shot->velocity, kept), vector_scale(lured, 1 - kept)); + } +} + +// 006121d0 (the body's case) The square the body lay on keeps a weaker mark than the one it held, unless something +// stronger marked it since. +void forgotten_body_clear(Entity_Familiar& body) +{ + int gridIndex = body.pathfinder.gridIndex; + std::array& paths = g_game->room->gridPaths; + if (gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS && paths[gridIndex] <= FORGOTTEN_BODY_GRID_PATH) + paths[gridIndex] = FORGOTTEN_BODY_LEFT_GRID_PATH; +} + +// Entity_Effect::Update 005d4380 (case 006040d8) The Forgotten's chain from the body (child) to The Soul (target): the +// first frame lays eight links along it. The chain end pulls a Soul that strays past its length back (and in a +// crawlspace drags the body along), every link sits its share of the way from the body to The Soul at their heights, +// and the chain shows The Soul's colour. Without both ends, or for The Soul's Birthright, it fades away. +static EffectUpdateEnd forgotten_chain_update(Entity_Effect& chain) +{ + Room& room = *g_game->room; + + if (chain.subtype == 0 && chain.state == 0) + { + chain.rotation = CHAIN_ANCHOR_SPAN; + for (int i = CHAIN_LINK_FIRST; i < CHAIN_LINK_END; i++) + { + auto* link = static_cast( + g_game->Spawn({.position = chain.pos, .spawner = &chain, .subType = CHAIN_SUBTYPE_LINK, + .type = ENTITY_EFFECT, .variant = EFFECT_FORGOTTEN_CHAIN, .seed = Random()})); + link->parent = &chain; + link->child = chain.child; + link->target = chain.target; + link->targetPosition = chain.targetPosition; + link->rotation = (float)i / CHAIN_LINK_SPACING; + link->Update(); + } + chain.state = 1; + } + + Entity* body = chain.child; + Entity* soul = chain.target; + auto* soulPlayer = soul ? soul->ToPlayer() : nullptr; + bool isBirthright = soulPlayer && soulPlayer->playerType == PLAYER_THESOUL && + soulPlayer->HasCollectible(COLLECTIBLE_BIRTHRIGHT); + if (!body || !soul || isBirthright) + { + chain.velocity = {}; + chain.sprite.Play("Disappear"); + if (chain.sprite.IsFinished()) chain.Remove(); + return EFFECT_UPDATE_FINISH; + } + + Vector anchor = vector_add(body->pos, chain.targetPosition); + if (chain.subtype == 0) + { + Vector stray = vector_sub(soul->pos, anchor); + float length = vector_length(stray); + if (chain.scale < length) + { + stray = vector_scale(stray, (chain.scale / length - 1) * CHAIN_PULL); + soul->velocity = vector_add(soul->velocity, stray); + if (room.roomType == ROOM_DUNGEON) body->velocity = vector_sub(body->velocity, vector_scale(stray, CHAIN_BODY_PULL)); + } + } + + float t = chain.rotation; + Vector spot = vector_make(anchor.x + (soul->pos.x - anchor.x) * t, anchor.y + (soul->pos.y - anchor.y) * t); + float soulHeight = soul->posOffset.y - soul->sprite.scale.y * CHAIN_HEIGHT; + float bodyHeight = body->posOffset.y - body->sprite.scale.y * CHAIN_HEIGHT; + chain.posOffset.y = bodyHeight + (soulHeight - bodyHeight) * t; + if (room.GetFrameCount() < 1) chain.pos = spot; + else chain.velocity = vector_sub(spot, chain.pos); + chain.isVisible = !soul->isDead; + chain.sprite.color = soul->IsType(ENTITY_PLAYER, PLAYER_VARIANT_COOP_BABY, BABY_GHOST_SOUL) ? CHAIN_GHOST_COLOR + : soul->sprite.color; + chain.sprite.scale = body->sprite.scale; + return EFFECT_UPDATE_FINISH; +} + +constexpr auto PLAYER_EFFECT_BEHAVIOURS = std::to_array({ + {EFFECT_FORGOTTEN_CHAIN, nullptr, forgotten_chain_update, nullptr}, +}); + +std::span player_effect_behaviours() +{ + return PLAYER_EFFECT_BEHAVIOURS; +} diff --git a/src/entity_player_forgotten.h b/src/entity_player_forgotten.h new file mode 100644 index 0000000..9231f59 --- /dev/null +++ b/src/entity_player_forgotten.h @@ -0,0 +1,16 @@ +#pragma once + +#include "entity_effect.h" +#include "entity_player.h" +#include + +struct Entity_Familiar; + +// The Forgotten's body lying in the room while The Soul is out (familiar 3.900, parts of Entity_Familiar::Init 0060de70, +// Update 0061da10 and ClearReferences 006121d0). +void forgotten_body_init(Entity_Familiar& body); +void forgotten_body_update(Entity_Familiar& body); +void forgotten_body_clear(Entity_Familiar& body); + +// The effects the players own: The Forgotten's chain. +std::span player_effect_behaviours(); diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index ac3c354..b2bdfe1 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -664,9 +664,8 @@ static void temporary_effects_update(Entity_Player& 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 and pocket buttons, shoots, its temporary effects count down and its body -// animates. Items, effects the plain frame does not know, the held entity and the drop button stop the game until -// reached. +// 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() { if (isPlayingExtraAnimation && sprite.IsFinished()) isPlayingExtraAnimation = false; @@ -676,6 +675,7 @@ void Entity_Player::Update() bodySprite.Reset(); heldSprite.Reset(); } + update_pitfall(); if (isHurtPending && !isPlayingExtraAnimation) { isHurtPending = false; @@ -685,8 +685,6 @@ void Entity_Player::Update() if (isDead) return death_update(); if (!is_frame_plain() || heldEntity) reconstruction_missing("Entity_Player::Update 00782af0 (items, effects and item animations)"); - if (isControlsEnabled && action_value(ACTION_DROP, controllerIndex) > 0) - reconstruction_missing("Entity_Player::Update 00782af0 (items, pockets and drop)"); Entity::Update(); if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) @@ -701,12 +699,14 @@ void Entity_Player::Update() ControlActiveItem(ACTIVE_SLOT_PRIMARY); pocket_use_input(); update_shooting(); + pockets_rotate(); temporary_effects_update(*this); walk_animation_update(); if (damageCooldown > 0) damageCooldown--; if (controlsCooldown > 0) controlsCooldown--; if (fireBlockCooldown > 0) fireBlockCooldown--; if (itemHoldCooldown > 0) itemHoldCooldown--; + update_footprints(); lua_engine_get().PostPlayerUpdate(this); } diff --git a/src/entity_player_health.cpp b/src/entity_player_health.cpp index 5300f0f..317fa6f 100644 --- a/src/entity_player_health.cpp +++ b/src/entity_player_health.cpp @@ -13,6 +13,9 @@ constexpr int CONSUMABLE_MAX = 99; constexpr int DEEP_POCKETS_COIN_MAX = 999; constexpr int BLUEBABY_B_POOP_CAP = 24; +// The poop Tainted ??? holds, more with his birthright. +constexpr int POOP_MANA_MAX = 9; +constexpr int POOP_MANA_BIRTHRIGHT_BONUS = 20; constexpr int COINS_UNLOCK_THRESHOLD = 55; constexpr int GREED_GULLET_COINS_PER_HEART = 25; constexpr int HEART_LIMIT_DEFAULT = 24; @@ -725,6 +728,27 @@ bool Entity_Player::TryUseKey() return true; } +// 007d65c0 The most poop Tainted ??? holds, more when any player has his birthright. +int Entity_Player::GetMaxPoopMana() +{ + bool isBirthright = g_game->playerManager.FirstBirthrightOwner(PLAYER_BLUEBABY_B); + return POOP_MANA_MAX + (isBirthright ? POOP_MANA_BIRTHRIGHT_BONUS : 0); +} + +// 007d65e0 Adds poop to Tainted ???'s store, kept between none and the most, and shows it on the HUD. +void Entity_Player::AddPoopMana(int amount) +{ + poopMana = std::max(std::min(poopMana + amount, GetMaxPoopMana()), 0); + ConsumableCountChanged(CONSUMABLE_POOP_MANA); + g_game->hud.refresh_request(HUD_REFRESH_PLAYER); +} + +// 00841cd0 The spell queued at a position, 0 past the queue. +int Entity_Player::GetPoopSpell(int position) +{ + return (uint32_t)position < POOP_SPELL_QUEUE_SIZE ? poopSpellQueue[position] : 0; +} + // 007597e0 Shares the changed consumables with every player, as the run keeps one purse. Coins unlock their // achievements. The deathmatch keeps each player's own. void Entity_Player::ConsumableCountChanged(int bitflags) diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index 3b2a5b2..4f2cb69 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -1346,7 +1346,6 @@ constexpr int NULLITEM_DOUBLED_COSTUME_A = 125; constexpr int NULLITEM_DOUBLED_COSTUME_B = 126; constexpr int NULLITEM_EDEN_HAIR = 12; constexpr int NULLITEM_EDEN_HAIR_B = 88; -constexpr int COLLECTIBLE_TRANSCENDENCE = 20; constexpr int NULLITEM_INTRUDER_TRANSCENDENCE = 132; constexpr int COLLECTIBLE_SACK_HEAD_COSTUME = 424; constexpr int COLLECTIBLE_HOLY_GRAIL = 184; diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index d5d03e4..036a630 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -25,7 +25,6 @@ Entity_Familiar* Entity_Player::AddItemWisp(int, Vector, bool) { reconstruction_missing("Entity_Player::AddItemWisp 005c96f0"); } -void Entity_Player::console_spawn(const DeliriousBoss&, bool) { reconstruction_missing("Entity_Player::console_spawn 005caa70"); } void Entity_Player::ResetDamageCooldown() { reconstruction_missing("Entity_Player::ResetDamageCooldown 0060d090"); } Vector Entity_Player::SpriteScale() { reconstruction_missing("Entity_Player::SpriteScale 0060d0a0"); } bool Entity_Player::IsP2Appearing() { reconstruction_missing("Entity_Player::IsP2Appearing 0065cf60"); } @@ -33,12 +32,10 @@ void Entity_Player::set_last_damage(uint64_t, const EntityRef&) { reconstruction_missing("Entity_Player::set_last_damage 006dad80"); } -PocketItem& Entity_Player::GetPocketItem(int) { reconstruction_missing("Entity_Player::GetPocketItem 00753900"); } void Entity_Player::QueueExtraAnimation(std::string_view) { reconstruction_missing("Entity_Player::QueueExtraAnimation 007539c0"); } -uint32_t Entity_Player::IsSubPlayer() { reconstruction_missing("Entity_Player::IsSubPlayer 00753ac0"); } void Entity_Player::release_weapons_and_effects(bool) { reconstruction_missing("Entity_Player::release_weapons_and_effects 00757ac0"); @@ -68,13 +65,11 @@ void Entity_Player::AddPlayerFormCostume(int) reconstruction_missing("Entity_Player::AddPlayerFormCostume 0075e9a0"); } void Entity_Player::SetItemState(int) { reconstruction_missing("Entity_Player::SetItemState 0075ea20"); } -int Entity_Player::GetCollectibleCount() { reconstruction_missing("Entity_Player::GetCollectibleCount 0075eff0"); } 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::HasGoldenTrinket(uint32_t) { reconstruction_missing("Entity_Player::HasGoldenTrinket 00771620"); } bool Entity_Player::TryHoldTrinket(int) { reconstruction_missing("Entity_Player::TryHoldTrinket 007716f0"); } -int Entity_Player::GetMaxTrinkets() { reconstruction_missing("Entity_Player::GetMaxTrinkets 007717c0"); } Entity_Pickup* Entity_Player::DropTrinket(Vector, bool) { reconstruction_missing("Entity_Player::DropTrinket 00771800"); @@ -99,24 +94,12 @@ Entity_Bomb* Entity_Player::FireBomb(Vector, Vector, Entity*) } void Entity_Player::ReviveFromTrinket(uint32_t) { reconstruction_missing("Entity_Player::ReviveFromTrinket 007a3430"); } void Entity_Player::remove_twin() { reconstruction_missing("Entity_Player::remove_twin 007a37c0"); } -void Entity_Player::AddCard(int) { reconstruction_missing("Entity_Player::AddCard 007a3c10"); } -void Entity_Player::AddPill(int) { reconstruction_missing("Entity_Player::AddPill 007a3c30"); } -int Entity_Player::GetCard(int) { reconstruction_missing("Entity_Player::GetCard 007a3c50"); } -int Entity_Player::GetPill(int) { reconstruction_missing("Entity_Player::GetPill 007a3c80"); } -void Entity_Player::SetCard(int, int) { reconstruction_missing("Entity_Player::SetCard 007a3cb0"); } -void Entity_Player::SetPill(int, int) { reconstruction_missing("Entity_Player::SetPill 007a3cf0"); } -void Entity_Player::pockets_rotate() { reconstruction_missing("Entity_Player::pockets_rotate 007a42b0"); } -void Entity_Player::RemovePocketItem(int) { reconstruction_missing("Entity_Player::RemovePocketItem 007a4850"); } -void Entity_Player::DropPocketItem(int, Vector) { reconstruction_missing("Entity_Player::DropPocketItem 007a48f0"); } -int Entity_Player::GetTrinket(uint32_t) { reconstruction_missing("Entity_Player::GetTrinket 007a6430"); } void Entity_Player::AnimateTrinket(int, std::string_view, std::string_view) { reconstruction_missing("Entity_Player::AnimateTrinket 007ab550"); } void Entity_Player::AnimateTrapdoor() { reconstruction_missing("Entity_Player::AnimateTrapdoor 007abc00"); } void Entity_Player::AnimateLightTravel() { reconstruction_missing("Entity_Player::AnimateLightTravel 007abc10"); } -void Entity_Player::AnimatePitfallIn(bool) { reconstruction_missing("Entity_Player::AnimatePitfallIn 007abc20"); } -void Entity_Player::AnimatePitfallOut() { reconstruction_missing("Entity_Player::AnimatePitfallOut 007abc90"); } void Entity_Player::AnimateAppear() { reconstruction_missing("Entity_Player::AnimateAppear 007abcb0"); } void Entity_Player::AnimateTeleport(bool) { reconstruction_missing("Entity_Player::AnimateTeleport 007abcc0"); } void Entity_Player::AddPrettyFly() { reconstruction_missing("Entity_Player::AddPrettyFly 007abdf0"); } @@ -145,8 +128,6 @@ void Entity_Player::TriggerTrinketRemoved(uint32_t) reconstruction_missing("Entity_Player::TriggerTrinketRemoved 007adb30"); } void Entity_Player::DonateLuck(int) { reconstruction_missing("Entity_Player::DonateLuck 007b2200"); } -void Entity_Player::update_footprints() { reconstruction_missing("Entity_Player::update_footprints 007b8cb0"); } -void Entity_Player::update_pitfall() { reconstruction_missing("Entity_Player::update_pitfall 007b9b50"); } void Entity_Player::TryDecreaseGlowingHourglassUses(int, bool) { reconstruction_missing("Entity_Player::TryDecreaseGlowingHourglassUses 007b9e10"); @@ -179,7 +160,6 @@ void Entity_Player::add_random_stat_up(RNG*) { reconstruction_missing("Entity_Pl bool Entity_Player::CanUsePill(int) { reconstruction_missing("Entity_Player::CanUsePill 007c40e0"); } void Entity_Player::AddDeadEyeCharge() { reconstruction_missing("Entity_Player::AddDeadEyeCharge 007c78b0"); } void Entity_Player::ClearDeadEyeCharge() { reconstruction_missing("Entity_Player::ClearDeadEyeCharge 007c78e0"); } -void Entity_Player::update_purity_glow() { reconstruction_missing("Entity_Player::update_purity_glow 007c7c60"); } void Entity_Player::trigger_immaculate_conception(bool) { reconstruction_missing("Entity_Player::trigger_immaculate_conception 007c7d70"); @@ -217,10 +197,6 @@ float Entity_Player::GetGreedDonationJamChance(PersistentGameData&) } void Entity_Player::hallowed_ground_add(int) { reconstruction_missing("Entity_Player::hallowed_ground_add 007cbc60"); } void Entity_Player::resolve_tainted_soul() { reconstruction_missing("Entity_Player::resolve_tainted_soul 007cbcb0"); } -bool Entity_Player::SwapForgottenForm(bool, bool) -{ - reconstruction_missing("Entity_Player::SwapForgottenForm 007cc200"); -} bool Entity_Player::CanRerollCollectible(int, bool) { reconstruction_missing("Entity_Player::CanRerollCollectible 007ce2a0"); @@ -249,8 +225,6 @@ uint32_t Entity_Player::bag_of_crafting_collect(Entity_Pickup*) { reconstruction_missing("Entity_Player::bag_of_crafting_collect 007d5170"); } -int Entity_Player::GetMaxPoopMana() { reconstruction_missing("Entity_Player::GetMaxPoopMana 007d65c0"); } -void Entity_Player::AddPoopMana(int) { reconstruction_missing("Entity_Player::AddPoopMana 007d65e0"); } void Entity_Player::poop_spell_roll() { reconstruction_missing("Entity_Player::poop_spell_roll 007d6670"); } void Entity_Player::UsePoopSpell(uint32_t) { reconstruction_missing("Entity_Player::UsePoopSpell 007d7290"); } void Entity_Player::RecomputeWispCollectibles(Entity_Familiar*) @@ -304,7 +278,6 @@ void Entity_Player::twins_duplicate_familiars(int) } const std::string& Entity_Player::GetName() { reconstruction_missing("Entity_Player::GetName 007e9280"); } void Entity_Player::TriggerRoomExit() { reconstruction_missing("Entity_Player::TriggerRoomExit 00832850"); } -int Entity_Player::GetPoopSpell(int) { reconstruction_missing("Entity_Player::GetPoopSpell 00841cd0"); } bool Entity_Player::HasFullHeartsAndSoulHearts() { reconstruction_missing("Entity_Player::HasFullHeartsAndSoulHearts 0085e200"); diff --git a/src/entity_player_pitfall.cpp b/src/entity_player_pitfall.cpp new file mode 100644 index 0000000..c0529cf --- /dev/null +++ b/src/entity_player_pitfall.cpp @@ -0,0 +1,103 @@ +#include "active_items.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "menu_manager.h" +#include "room.h" +#include "room_grid.h" + +// A fall costs half a heart, and the player climbs out after 40 frames once it moves, or on its own after 120, safe +// from harm for 120 frames. +constexpr float PITFALL_DAMAGE = 1; +constexpr int PITFALL_DAMAGE_COUNTDOWN = 30; +constexpr int PITFALL_CLIMB_FRAMES = 40; +constexpr int PITFALL_FORCED_CLIMB_FRAMES = 120; +constexpr int PITFALL_LANDING_COOLDOWN = 120; +constexpr std::array PITFALL_MOVE_ACTIONS = {ACTION_LEFT, ACTION_RIGHT, ACTION_UP, ACTION_DOWN}; + +// 007abc20 Drops the player into a pit: it plays "FallIn" without control or collisions, unless Mega Mush keeps it out. +// A fall ignoring that goes through to another room. +void Entity_Player::AnimatePitfallIn(bool isIgnoreEffect) +{ + if (!isIgnoreEffect && temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) return; + + PlayExtraAnimation("FallIn"); + isControlsEnabled = false; + entityCollisionClass = ENTCOLL_NONE; + pitfallTimer = 0; + pitfallState = isIgnoreEffect ? PITFALL_GONE : PITFALL_FALLING; +} + +// 007abc90 Plays the player's jump out of a pit. +void Entity_Player::AnimatePitfallOut() +{ + pitfallState = PITFALL_CLIMBING; + PlayExtraAnimation("JumpOut"); +} + +// The climb out of a pit: on the spot when it is free, else at a free spot near it, or near the door the room was +// entered by when that spot is no better. +// The original reads the slot before the doors when the room was entered by no door. Here no door is used. +static void pitfall_climb(Entity_Player& player) +{ + Room& room = *g_game->room; + if (room_grid_collision_at(player.pos) == 0) return player.AnimatePitfallOut(); + + Vector landing = room_free_pickup_position_find({.position = player.pos, .isAvoidActiveEntities = true}); + int door = g_game->enterDoor; + if (room_grid_collision_at(landing) > 0 && door >= 0 && door < DOOR_SLOT_COUNT && room.doors[door]) + { + Vector doorPos = room.doors[door]->Position(); + landing = room_free_pickup_position_find({.position = doorPos, .isAvoidActiveEntities = true}); + } + player.Teleport(landing, false, false); + player.AnimatePitfallOut(); + player.sprite.SetLastFrame(); +} + +// 007b9b50 A player's fall into a pit: the fall hurts it once "FallIn" ends, it climbs out once it moves after 40 +// frames or after 120, and gets its control and collisions back once "JumpOut" ends. Its extra animation holds +// meanwhile, and through a pixelated room transition. +void Entity_Player::update_pitfall() +{ + if (pitfallState == PITFALL_NONE) return; + + RoomTransition& transition = g_game->roomTransition; + if (transition.mode != TRANSITION_NONE) + { + if (pitfallState != PITFALL_CLIMBING && transition.animation == TRANSITION_PIXELATION) + isPlayingExtraAnimation = true; + return; + } + if (isDead) return; + + const AnimationState& animation = sprite.animState; + if (animation.animData && !animation.isPlaying && animation.animData->name == "FallIn" && + pitfallState == PITFALL_FALLING) + { + pitfallState = PITFALL_DOWN; + TakeDamage(PITFALL_DAMAGE, DAMAGE_PITFALL, EntityRef(), PITFALL_DAMAGE_COUNTDOWN); + } + if (pitfallState == PITFALL_DOWN && ++pitfallTimer >= PITFALL_CLIMB_FRAMES) + { + bool isMoving = false; + for (ButtonAction action : PITFALL_MOVE_ACTIONS) + isMoving = input_is_action_pressed(action, controllerIndex, this) || isMoving; + if (isMoving || pitfallTimer >= PITFALL_FORCED_CLIMB_FRAMES) + { + pitfall_climb(*this); + damageCooldown = PITFALL_LANDING_COOLDOWN; + } + } + if (pitfallState == PITFALL_CLIMBING && (!animation.animData || !animation.isPlaying)) + { + isPlayingExtraAnimation = false; + pitfallTimer = 0; + pitfallState = PITFALL_NONE; + isControlsEnabled = true; + entityCollisionClass = ENTCOLL_ALL; + return; + } + isPlayingExtraAnimation = true; +} diff --git a/src/entity_player_pockets.cpp b/src/entity_player_pockets.cpp index 13cf099..0378266 100644 --- a/src/entity_player_pockets.cpp +++ b/src/entity_player_pockets.cpp @@ -78,7 +78,6 @@ constexpr int ACHIEVEMENT_GULP = 386; constexpr int ANNOUNCER_FRAMES_RANDOM = 900; constexpr int ANNOUNCER_FRAMES = 2; constexpr int CHALLENGE_RANDOM_POCKETS = 32; -constexpr int COLLECTIBLE_TAROT_CLOTH = 451; constexpr int COLLECTIBLE_ECHO_CHAMBER = 700; constexpr int DELAYED_SFX_FRAMES = 2; constexpr int GULP_UNLOCK_USES = 4; @@ -213,6 +212,64 @@ void Entity_Player::AddPocketItem(int id, uint32_t pocketItemType) if (parent && pocketItemType != POCKET_ACTIVE) DropPocketItem(insert, pos); } +// 007a3c10 Pockets a card. +void Entity_Player::AddCard(int card) +{ + AddPocketItem(card, POCKET_CARD); +} + +// 007a3c30 Pockets a pill. +void Entity_Player::AddPill(int pillColor) +{ + AddPocketItem(pillColor, POCKET_PILL); +} + +// Whether a pocket slot exists. +static bool is_pocket_slot(int slot) +{ + return slot >= 0 && slot < POCKET_SLOT_COUNT; +} + +// 007a3c50 The card in a pocket slot, 0 for none. +int Entity_Player::GetCard(int slot) +{ + return is_pocket_slot(slot) && pocketItems[slot].type == POCKET_CARD ? pocketItems[slot].id : 0; +} + +// 007a3c80 The pill in a pocket slot, 0 for none. +int Entity_Player::GetPill(int slot) +{ + return is_pocket_slot(slot) && pocketItems[slot].type == POCKET_PILL ? pocketItems[slot].id : 0; +} + +// 007a3cb0 Puts a card in a pocket slot, then updates the Red Key's door outlines. +void Entity_Player::SetCard(int slot, int card) +{ + if (!is_pocket_slot(slot)) return; + pocketItems[slot] = {card, POCKET_CARD}; + g_game->room->UpdateRedKey(); +} + +// 007a3cf0 Puts a pill in a pocket slot, then updates the Red Key's door outlines. +void Entity_Player::SetPill(int slot, int pillColor) +{ + if (!is_pocket_slot(slot)) return; + pocketItems[slot] = {pillColor, POCKET_PILL}; + g_game->room->UpdateRedKey(); +} + +// 007717c0 How many trinkets the player holds: two with Mom's Purse or Belly Button. +int Entity_Player::GetMaxTrinkets() +{ + return HasCollectible(COLLECTIBLE_MOMS_PURSE) || HasCollectible(COLLECTIBLE_BELLY_BUTTON) ? 2 : 1; +} + +// 007a6430 The trinket held in a slot, 0 past the second. +int Entity_Player::GetTrinket(uint32_t slot) +{ + return slot < TRINKET_SLOT_COUNT ? (int)trinkets[slot] : 0; +} + // 007db740 Echo Chamber repeats the last three cards and pills used. Not written yet. void Entity_Player::TriggerEchoChamber(uint32_t, int) { diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp index cd34c18..87edb2f 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -9,7 +9,6 @@ #include "room.h" #include -constexpr int TRINKET_TICK = 53; constexpr int TRINKET_DOOR_STOP = 124; constexpr int TRINKET_LIL_CLOT = 176; constexpr int TRINKET_BETHS_ESSENCE = 182; diff --git a/src/entity_player_weapons.cpp b/src/entity_player_weapons.cpp index 3d51dab..aaf1c0b 100644 --- a/src/entity_player_weapons.cpp +++ b/src/entity_player_weapons.cpp @@ -1,4 +1,7 @@ #include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "weapon_knives.h" #include "entity_laser.h" #include "entity_player.h" #include "entity_tear.h" @@ -68,6 +71,8 @@ constexpr int PLAYERFORM_CONJOINED = 7; constexpr int PLAYERFORM_BOOKWORM = 10; constexpr int TRANSFORMATION_COUNT = 3; constexpr int TEAR_COLOR_PRIORITY = 255; +constexpr float TECH_X_THICKER_SCALE = 1.5f; +constexpr float TECH_X_RING_LIFT = -20; constexpr int COLLECTIBLE_BRIMSTONE_WEAPON = 118; constexpr int COLLECTIBLE_CURSED_EYE_WEAPON = 316; @@ -76,8 +81,6 @@ constexpr int COLLECTIBLE_EVIL_EYE = 410; constexpr int COLLECTIBLE_EYE_SORE = 558; constexpr int COLLECTIBLE_INNER_EYE = 2; constexpr int COLLECTIBLE_LARGE_ZIT = 502; -constexpr int COLLECTIBLE_LOKIS_HORNS = 87; -constexpr int COLLECTIBLE_MOMS_EYE = 55; constexpr int COLLECTIBLE_NEPTUNUS = 597; constexpr int COLLECTIBLE_THE_WIZ = 358; constexpr int COLLECTIBLE_TRACTOR_BEAM = 397; @@ -534,6 +537,77 @@ Entity_Laser* Entity_Player::FireTechLaser(const TechLaserShot& shot) return laser; } +// 007cb230 Fires a Tech X ring from the player (Lua's FireTechXLaser): thick red with Brimstone or as Azazel (half +// as thick for Tainted Azazel without Brimstone), doubled by a second Brimstone and thicker past one and a half, red +// and blue with Technology. It takes the player's laser color and hit params. +Entity_Laser* Entity_Player::FireTechXLaser(const TechXShot& shot) +{ + Entity* spawner = shot.source ? shot.source : this; + float scale = std::sqrt(shot.damageMultiplier); + if (spawner->type == ENTITY_FAMILIAR) scale *= 0.5f; + + int variant = LASER_THIN_RED; + bool isBrimstone = HasCollectible(COLLECTIBLE_BRIMSTONE); + if (isBrimstone || playerType == PLAYER_AZAZEL) variant = LASER_THICK_RED; + if (playerType == PLAYER_AZAZEL_B && !isBrimstone) + { + scale *= 0.5f; + variant = LASER_THICK_RED; + } + if (GetCollectibleNum(COLLECTIBLE_BRIMSTONE) > 1) scale += scale; + if (scale > TECH_X_THICKER_SCALE && variant == LASER_THICK_RED) + { + scale *= 0.5f; + variant = LASER_THICKER_RED; + } + if (HasCollectible(COLLECTIBLE_TECHNOLOGY)) + variant = variant == LASER_THICKER_RED ? LASER_THICKER_BRIM_TECH : LASER_BRIM_TECH; + + Entity_Laser* laser = static_cast(g_game->Spawn({.position = shot.position, + .velocity = shot.velocity, + .spawner = spawner, + .subType = LASER_SUBTYPE_RING_PROJECTILE, + .type = ENTITY_LASER, + .variant = variant, + .seed = Random()})); + int displacement = (int)(Random() & 1) * 2 - 1; + TearParams params = GetTearHitParams(WEAPON_LASER, 1, displacement, spawner); + laser->posOffset = vector_make(0, TECH_X_RING_LIFT); + laser->parent = spawner; + laser->renderDepthOffset = TECH_LASER_FRONT_DEPTH; + laser->SetColor(laserColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + laser->tearFlags = params.tearFlags; + laser->SetCollisionDamage(params.tearDamage); + laser->scale = scale; + laser->ResetSpriteScale(); + laser->radius = shot.radius; + laser->spawnerEntity = spawner; + laser->isPlayerParams = true; + laser->mass *= params.massMultiplier; + laser->damageMultiplier = shot.damageMultiplier; + return laser; +} + +// 007aded0 Fires a knife from the player (Lua's FireKnife): it hangs from its parent at its angle, with the player's +// tear color, tear flags and damage. +Entity_Knife* Entity_Player::FireKnife(const KnifeShot& shot) +{ + Entity* knife = g_game->Spawn({.position = pos, + .spawner = this, + .subType = shot.subType, + .type = ENTITY_KNIFE, + .variant = shot.variant, + .seed = Random()}); + knife->parent = shot.parent; + knife->posOffset = vector_make(0, KNIFE_LIFT); + knife->SetColor(tearColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + static_cast(knife)->tearFlags = tearFlags; + knife->SetCollisionDamage(damage); + static_cast(knife)->rotationOffset = angle_wrap(shot.rotationOffset); + if (shot.isCantOverwrite) knife->AddEntityFlags(FLAG_DONT_OVERWRITE); + return static_cast(knife); +} + // 007a0f50 Fires a Brimstone beam from the player in its laser color (Lua's FireBrimstone). Entity_Laser* Entity_Player::FireBrimstone(const Vector& direction, Entity*, float damageMultiplier) { diff --git a/src/familiar_evaluate.cpp b/src/familiar_evaluate.cpp index b7e156b..c4a955a 100644 --- a/src/familiar_evaluate.cpp +++ b/src/familiar_evaluate.cpp @@ -67,7 +67,6 @@ constexpr int HALO_FLY_CAP = 10; constexpr int COLLECTIBLE_BEST_BUD = 274; constexpr int ACHIEVEMENT_CUBE_OF_MEAT_FULL = 144; constexpr int ACHIEVEMENT_BALL_OF_BANDAGES_FULL = 19; -constexpr int COLLECTIBLE_PINKING_SHEARS = 107; constexpr int COLLECTIBLE_BROWN_NUGGET = 504; constexpr int COLLECTIBLE_SPRINKLER = 516; constexpr int COLLECTIBLE_KEY_BUM = 388; diff --git a/src/game.h b/src/game.h index 996264e..c56d289 100644 --- a/src/game.h +++ b/src/game.h @@ -317,6 +317,7 @@ public: void SetColorModifier(const ColorModState& color, bool isLerp, float rate); void save_rewind_state(int leaveDoor); void StartRoomTransition(RoomTransitionRequest request); + void ShowHallucination(int frames, int backdrop); void Fadeout(float speed, FadeOutTarget target, KColor color = kcolor_rgba(0, 0, 0, 1)); void store_game_state(GameState& state); void restore_game_state(GameState& state, GameRestore restore); diff --git a/src/game_end.cpp b/src/game_end.cpp new file mode 100644 index 0000000..b96b0d0 --- /dev/null +++ b/src/game_end.cpp @@ -0,0 +1,399 @@ +#include "game_end.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity.h" +#include "log.h" +#include "lua_engine.h" +#include "manager.h" +#include "menu_manager.h" +#include "persistent_game_data.h" +#include "room_config.h" +#include "sfx_manager.h" +#include "stage_transition.h" +#include +#include + +// The cutscene each ending plays, none for a death. Mom's Heart's first eleven kills each play the next of the Womb's +// endings (cutscenes 4 to 14), any later one the credits. +constexpr std::array ENDING_CUTSCENES = {0, 0, 3, 0, 15, 16, 18, 17, 19, 21, 20, 22, 23, 24, 26}; +constexpr int CUTSCENE_CREDITS = 2; +constexpr int WOMB_ENDINGS = 11; +constexpr int WOMB_ENDING_BEFORE_FIRST = 3; + +// The endings the floors give from Depths I (stage id 7) to Mortis (34): Mom, Mom's Heart, Hush, Satan, Isaac, the +// Lamb and Blue Baby (Mega Satan in his room), Ultra Greed, Delirium and Mother. The rest have none. +constexpr int ENDING_STAGE_FIRST = STAGE_ID_DEPTHS; +constexpr std::array STAGE_ENDINGS = { + ENDING_MOM, ENDING_MOM, ENDING_MOM, ENDING_MOMS_HEART, ENDING_MOMS_HEART, ENDING_MOMS_HEART, + ENDING_HUSH, ENDING_SATAN, ENDING_ISAAC, ENDING_LAMB, ENDING_BLUE_BABY, ENDING_UNKNOWN, + ENDING_UNKNOWN, ENDING_UNKNOWN, ENDING_UNKNOWN, ENDING_UNKNOWN, ENDING_UNKNOWN, ENDING_UNKNOWN, + ENDING_ULTRA_GREED, ENDING_DELIRIUM, ENDING_UNKNOWN, ENDING_UNKNOWN, ENDING_UNKNOWN, ENDING_UNKNOWN, + ENDING_UNKNOWN, ENDING_UNKNOWN, ENDING_MOTHER, ENDING_MOTHER}; + +constexpr int ACHIEVEMENT_HAT_TRICK = 322; +constexpr uint32_t HAT_TRICK_WINS = 2; + +// The bits of a completion counter, and the marks past the characters' own. +constexpr int MARK_COUNTER_NORMAL = 1; +constexpr int MARK_COUNTER_HARD = 2; +constexpr int EVENT_COUNTER_FINAL_MARKS = 21; +constexpr std::array LAZARUS_HARD_MARKS = {COMPLETION_MOMS_HEART, COMPLETION_ISAAC, COMPLETION_SATAN, + COMPLETION_BLUE_BABY, COMPLETION_LAMB, COMPLETION_MEGA_SATAN, + COMPLETION_HUSH, COMPLETION_MOTHER, COMPLETION_BEAST}; +constexpr int ACHIEVEMENT_LAZARUS_HARD_MARKS = 404; +constexpr int ACHIEVEMENT_MEGA_SATAN_MARK = 340; +constexpr int ACHIEVEMENT_MOTHER_MARK = 405; +constexpr int ACHIEVEMENT_MOTHER_MARK_SECOND = 635; +constexpr float CHALLENGE_FADE_SPEED = 0.04f; + +// The big chest opens on its own after the touch, the run's ending playing from frame 6 of its opening. A chest with no +// cutscene to play lets the player fall into it instead. +constexpr int BIG_CHEST_ENDING_FRAME = 6; +constexpr float BIG_CHEST_DROP = 20; +constexpr int ENDING_PICKUP_COOLDOWN = 10; +constexpr std::string_view G_FUEL_TROPHY_ANM2 = "gfx/promo/gfuel/trophy.anm2"; + +// Whether the run's progress counts: not in a custom run, one that cannot unlock achievements, or a rerun. +static bool is_progress_counted() +{ + Game& game = *g_game; + return !game.seedEffects.isCustomRun && !game.seedEffects.AchievementUnlocksDisallowed() && + !Manager::AchievementUnlocksDisallowed() && !game.isRerun; +} + +// The cutscene an ending plays: Mom's Heart's by how often she was beaten. +static int ending_cutscene_get(GameEnding ending) +{ + if (ending != ENDING_MOMS_HEART) return ENDING_CUTSCENES[ending]; + + int kills = g_manager->persistentGameData.eventCounters[EVENT_COUNTER_MOM_KILLS]; + return kills >= 1 && kills <= WOMB_ENDINGS ? kills + WOMB_ENDING_BEFORE_FIRST : CUTSCENE_CREDITS; +} + +// 00959130 Forgets the saved run, outside a daily: its file, its checksum in the save data, and saving on exit. +// Online the original keeps it too. Netplay is offline. +void game_save_delete() +{ + Manager& manager = *g_manager; + + if (g_game->dailyChallenge._id != 0) return; + manager.gamestate.Delete(); + manager.persistentGameData.gameStateChecksum = 0; + manager.persistentGameData.isChangesMade = true; + manager.isSaveOnExit = false; +} + +// 0095a680 Opens the save data to the run's progress once per run, unless the progress does not count: the run counts +// against the win streak (or the losing streak) and clears the run mask. +// Online, the original also reports the run to the netplay layer. Netplay is offline. +void persistent_game_data_set_writable() +{ + Manager& manager = *g_manager; + PersistentGameData& data = manager.persistentGameData; + + if (!is_progress_counted() || manager.isPersistentDataWritable) return; + + bool isReadOnlyBefore = data.isReadOnly; + data.SetReadOnly(false); + int streak = data.eventCounters[EVENT_COUNTER_STREAK]; + if (streak == 0) data.IncreaseEventCounter(EVENT_COUNTER_NEGATIVE_STREAK, 1); + else data.IncreaseEventCounter(EVENT_COUNTER_STREAK, -streak); + data.SetReadOnly(isReadOnlyBefore); + data.set_run_mask(0); + manager.isPersistentDataWritable = true; +} + +// 0095a4a0 (Game::end_save_progress) Saves a won run's progress unless it does not count: the win streak grows, +// clearing the losing streak and raising the best, more than two wins in a row unlock the Hat Trick, and the character +// joins the mask of characters won with in a row (which starts over once one repeats). +// Online the original first reports the run to the netplay layer. Netplay is offline. +void run_progress_save() +{ + PersistentGameData& data = g_manager->persistentGameData; + if (!is_progress_counted()) return; + + bool isReadOnlyBefore = data.isReadOnly; + data.SetReadOnly(false); + data.IncreaseEventCounter(EVENT_COUNTER_NEGATIVE_STREAK, -data.eventCounters[EVENT_COUNTER_NEGATIVE_STREAK]); + data.IncreaseEventCounter(EVENT_COUNTER_STREAK, 1); + uint32_t streak = data.eventCounters[EVENT_COUNTER_STREAK]; + uint32_t best = data.eventCounters[EVENT_COUNTER_BEST_STREAK]; + if (best < streak) data.IncreaseEventCounter(EVENT_COUNTER_BEST_STREAK, (int)(streak - best)); + data.SetReadOnly(isReadOnlyBefore); + if ((uint32_t)data.eventCounters[EVENT_COUNTER_STREAK] > HAT_TRICK_WINS) data.TryUnlock(ACHIEVEMENT_HAT_TRICK); + + int playerType = g_game->GetPlayer(0)->playerType; + if (playerType >= COMPLETION_PLAYER_TYPE_COUNT) return; + uint64_t character = 1ull << playerType; + uint64_t mask = (uint32_t)data.eventCounters[EVENT_COUNTER_RUN_MASK_LOW] | + (uint64_t)(uint32_t)data.eventCounters[EVENT_COUNTER_RUN_MASK_HIGH] << 32; + if (mask & character) mask = 0; + data.set_run_mask(mask | character); +} + +// 00959180 (save_rerun_to_steam_cloud) Saves the run to play again once RERUN is unlocked, unless the first player +// died with no lives left. +// The rerun file's writer (GameState::write_rerun 009d8190) is not reconstructed yet. Steam Cloud and netplay are +// offline. +void rerun_save() +{ + Manager& manager = *g_manager; + Game& game = *g_game; + Entity_Player& player = *game.GetPlayer(0); + + if (player.isDead && player.GetExtraLives() < 1) return; + if (!manager.persistentGameData.Unlocked(ACHIEVEMENT_RERUN)) return; + game.store_game_state(manager.gamestate); + reconstruction_missing("save_rerun_to_steam_cloud 00959180 (GameState::write_rerun 009d8190)"); +} + +// 0095aa30 (unlock_completion_mark_for_player_type) A character's completion mark: its unlock (Mom's Heart's only in a +// hard run), and the normal and hard bits of its counter. Lazarus's hard marks also unlock achievement 404, and the +// marks of Ultra Greed, Mom's Heart and the Beast count toward counter 21. Netplay is offline, so the online bits are +// left out. +static void completion_mark_unlock(int completion, int playerType, int difficulty) +{ + PersistentGameData& data = g_manager->persistentGameData; + bool isHard = difficulty == DIFFICULTY_HARD || difficulty == DIFFICULTY_GREEDIER; + + if (playerType < COMPLETION_PLAYER_TYPE_COUNT) + { + const CompletionMark& mark = COMPLETION_MARKS[playerType][completion]; + if ((completion != COMPLETION_MOMS_HEART || isHard) && mark.achievement) data.TryUnlock(mark.achievement); + int counter = mark.counter; + int& bits = data.eventCounters[counter]; + if (counter && !(bits & MARK_COUNTER_NORMAL)) data.IncreaseEventCounter(counter, MARK_COUNTER_NORMAL); + if (counter && isHard && !(bits & MARK_COUNTER_HARD)) data.IncreaseEventCounter(counter, MARK_COUNTER_HARD); + } + bool isLazarusMark = std::ranges::find(LAZARUS_HARD_MARKS, completion) != LAZARUS_HARD_MARKS.end(); + if (playerType == PLAYER_LAZARUS && isHard && isLazarusMark) data.TryUnlock(ACHIEVEMENT_LAZARUS_HARD_MARKS); + if (completion == COMPLETION_ULTRA_GREED || completion == COMPLETION_MOMS_HEART || completion == COMPLETION_BEAST) + data.IncreaseEventCounter(EVENT_COUNTER_FINAL_MARKS, 1); +} + +// 0095a7b0 Marks a completion for every main player (a twin once, the first of the pair), a risen Lazarus as Lazarus +// II, then Mega Satan's and Mother's own unlocks. +// Netplay is offline, so the online players' queued marks are left out. +void PlayerManager::unlock_completion_mark(int completionType) +{ + Game* game = g_game; + if (!game) return; + + for (Entity_Player* player : game->playerManager.playerList) + { + Entity_Player* twin = player->twin_get(); + bool isFirstTwin = + !twin || twin->playerIndex == -1 || player->playerIndex <= twin->playerIndex || twin == player; + if (player->variant != 0 || !isFirstTwin || player->parent) continue; + + int playerType = player->playerType; + if (playerType == PLAYER_LAZARUS && player->temporaryEffects.HasNullEffect(NULLITEM_LAZARUS_BOOST)) + playerType = PLAYER_LAZARUS2; + completion_mark_unlock(completionType, playerType, game->difficulty); + } + + PersistentGameData& data = g_manager->persistentGameData; + if (completionType == COMPLETION_MEGA_SATAN) data.TryUnlock(ACHIEVEMENT_MEGA_SATAN_MARK); + else if (completionType == COMPLETION_MOTHER) + { + data.TryUnlock(ACHIEVEMENT_MOTHER_MARK); + data.TryUnlock(ACHIEVEMENT_MOTHER_MARK_SECOND); + } +} + +// 006f9770 Ends the run (Rebirth's Game::End): a death forgets the saved run and opens the game over screen. Any other +// ending queues its cutscene, unloading the run and going back to the title after it, then saves the rerun (outside +// challenges) and the run's progress. Nothing ends during a versus match until it is over. Mods hear of the end. +// Netplay is offline: co-op's end vote and the online stats are left out. +void game_end(GameEnding ending) +{ + Game& game = *g_game; + Manager& manager = *g_manager; + + if ((unsigned)ending > ENDING_LAST) + { + log_printf(LOG_INFO, "Invalid ending specified to Game::End()\n"); + return; + } + if (game.deathmatchManager.is_active() && game.deathmatchManager.state != DEATHMATCH_OVER) return; + + if (ending == ENDING_DEATH) game_save_delete(); + if (game.dailyChallenge._id != 0) reconstruction_missing("Game::End 006f9770 (a daily run's end, 006f9f20)"); + + if (ending == ENDING_DEATH) + { + game.gameOver.Show(); + persistent_game_data_set_writable(); + } + else + { + if (ending != ENDING_NONE) manager.ShowCutscene(ending_cutscene_get(ending), CUTSCENE_UNLOAD_STATE, MENU_TITLE); + if (game.challenge == 0 && manager.persistentGameData.Unlocked(ACHIEVEMENT_RERUN)) rerun_save(); + run_progress_save(); + } + lua_engine_get().PostGameEnd(ending == ENDING_DEATH); +} + +// 006f9d20 (get_stage_ending_id) The ending the floor's last boss gives, by its stage id. On the Cathedral or Sheol +// (stage 10) the Polaroid or the Negative carries the run on, as does a challenge going past them by that path, unless +// the photos are ignored. +GameEnding stage_ending_get(EndingPhotos photos) +{ + Game& game = *g_game; + ChallengeParam& params = game.GetChallengeParams(); + bool isChallenge = game.challenge != 0 || game.dailyChallenge._id != 0; + bool isChallengePastStage = isChallenge && params.endStage > STAGE_SHEOL; + bool isChallengeCathedral = isChallenge && params.pathType == PATH_TYPE_CATHEDRAL; + int stageId = RoomConfig::GetStageID((int)game.stage, (int)game.stageType, ROOM_MODE_CURRENT); + + if (photos == ENDING_PHOTOS_CHECKED && game.stage == STAGE_SHEOL) + { + PlayerManager& players = game.playerManager; + if (stageId == STAGE_ID_CATHEDRAL && + (players.FirstCollectibleOwner(COLLECTIBLE_POLAROID, LAZARUS_SHARE_CHECK) || + (isChallengePastStage && isChallengeCathedral))) + return ENDING_NONE; + if (stageId == STAGE_ID_SHEOL && + (players.FirstCollectibleOwner(COLLECTIBLE_NEGATIVE, LAZARUS_SHARE_CHECK) || + (isChallengePastStage && !isChallengeCathedral))) + return ENDING_NONE; + } + + if ((uint32_t)(stageId - ENDING_STAGE_FIRST) >= STAGE_ENDINGS.size()) return ENDING_UNKNOWN; + GameEnding ending = STAGE_ENDINGS[stageId - ENDING_STAGE_FIRST]; + bool isMegaSatanRoom = game.currentRoomIdx == ROOM_MEGA_SATAN_IDX; + if ((ending == ENDING_LAMB || ending == ENDING_BLUE_BABY) && isMegaSatanRoom) return ENDING_MEGA_SATAN; + if (ending == ENDING_ULTRA_GREED && game.difficulty == DIFFICULTY_GREEDIER) return ENDING_ULTRA_GREEDIER; + return ending; +} + +// 00704f20 (Game::FinishChallenge) Ends a challenge won: marks it done outside runs that cannot unlock achievements, +// holds the unlock papers back, forgets the saved run and fades out to the title. Nothing happens while a fade out +// runs. Netplay is offline, so the online lobby is not left. +void challenge_finish() +{ + Game& game = *g_game; + Manager& manager = *g_manager; + PersistentGameData& data = manager.persistentGameData; + + if (game.fadeOutColor._alpha > 0) return; + if (game.challenge != 0 && !Manager::AchievementUnlocksDisallowed()) + { + data.SetReadOnly(false); + data.AddChallenge(game.challenge); + data.SetReadOnly(true); + } + manager.achievementOverlay.isPopupBlocked = true; + game_save_delete(); + game.Fadeout(CHALLENGE_FADE_SPEED, FADEOUT_MENU_TITLE); +} + +// Whether an ending plays a cutscene once the big chest opens, rather than the players dropping into the chest. +static bool is_cutscene_ending(GameEnding ending) +{ + return ending == ENDING_MOMS_HEART || ending == ENDING_SATAN || ending == ENDING_ISAAC || + ending == ENDING_ULTRA_GREED || ending == ENDING_ULTRA_GREEDIER; +} + +// The big chest and trophy part of 006e02f0: they hold their place, are never overwritten and take a touch only after +// 10 frames. G FUEL!'s seed dresses the trophy up, and Backasswards removes every trophy but the first room's. +void ending_pickup_init(Entity_Pickup& pickup) +{ + Game& game = *g_game; + pickup.AddEntityFlags(FLAG_NO_KNOCKBACK | FLAG_DONT_OVERWRITE); + pickup.collisionCooldown = ENDING_PICKUP_COOLDOWN; + if (pickup.variant != PICKUP_TROPHY) return; + + if (game.seedEffects.HasSeedEffect(SEED_G_FUEL)) pickup.sprite.Load(G_FUEL_TROPHY_ANM2, GRAPHICS_LOAD); + bool isFirstRoom = game.stage == STAGE_BASEMENT_I && game.currentRoomIdx == game.startingRoomIdx; + if (game.challenge == CHALLENGE_BACKASSWARDS && !isFirstRoom) pickup.Remove(); +} + +// The big chest part of 006e3940: once touched, the chest opens with the players held still and the ending's transition +// starting. Its cutscene ending plays from frame 6 of the opening. Otherwise the opening's end drops the player who +// touched it (or the first) into the chest, and the transition ends the run. +PickupUpdateEnd big_chest_update(Entity_Pickup& chest) +{ + Game& game = *g_game; + Entity* target = chest.target; + Entity_Player& player = target && target->type == ENTITY_PLAYER ? static_cast(*target) + : *game.GetPlayer(0); + if (chest.state == 1) + { + chest.sprite.Play("Open"); + for (Entity_Player* each : game.playerManager.playerList) + { + each->velocity = {}; + each->isControlsEnabled = false; + } + chest.AddEntityFlags(FLAG_TRANSITION_UPDATE); + chest.state++; + chest.entityCollisionClass = ENTCOLL_NONE; + player.moveToTarget = {}; + game.stageTransition.start({.player = &player, .type = STAGE_TRANSITION_ENDING}); + if (!is_cutscene_ending(stage_ending_get(ENDING_PHOTOS_CHECKED))) + grid_sound_play(SOUND_GIANT_CHEST_OPEN, {.volume = 1, .frameDelay = 2, .pitch = 1}); + return PICKUP_UPDATE_FINISH; + } + if (chest.state != 2) return PICKUP_UPDATE_FINISH; + + if (chest.sprite.GetFrame() == BIG_CHEST_ENDING_FRAME) + { + GameEnding ending = stage_ending_get(ENDING_PHOTOS_CHECKED); + if (is_cutscene_ending(ending)) + { + game_end(ending); + return PICKUP_UPDATE_RETURN; + } + } + if (!chest.sprite.IsFinished()) return PICKUP_UPDATE_FINISH; + + chest.state++; + grid_sound_play(SOUND_TRAP_DOOR_LEVEL); + player.PlayExtraAnimation("Trapdoor"); + player.moveToTarget = vector_make(chest.pos.x, chest.pos.y + BIG_CHEST_DROP); + return PICKUP_UPDATE_FINISH; +} + +// The trophy part of 006e3940: the player who touched it lifts it, then once the lift ends wins the challenge, or a +// daily ends with its floor's ending. +void trophy_update(Entity_Pickup& trophy) +{ + Entity* target = trophy.target; + if (!target || target->type != ENTITY_PLAYER) + { + trophy.state = 0; + return; + } + + auto& player = static_cast(*target); + if (trophy.state == 1) + { + player.entityCollisionClass = ENTCOLL_NONE; + player.isControlsEnabled = false; + player.AnimatePickup(&trophy.sprite, true, "Pickup"); + trophy.state++; + trophy.isVisible = false; + return; + } + if (trophy.state != 2) return; + const AnimationData* lift = player.bodySprite.animState.animData; + bool isLiftEnd = player.isPlayingItemAnimation && player.bodySprite.GetFrame() == (lift ? lift->length : 0) - 1; + if (!isLiftEnd && player.IsHoldingItem()) return; + + player.entityCollisionClass = ENTCOLL_ALL; + GameEnding ending = g_game->dailyChallenge._id != 0 ? stage_ending_get(ENDING_PHOTOS_IGNORED) : ENDING_NONE; + if (ending == ENDING_NONE || ending == ENDING_UNKNOWN) challenge_finish(); + else game_end(ending); +} + +// The big chest and trophy part of 006e8ae0: a player's touch marks it for its update, the player its target. Big +// chests do nothing in Backasswards. +void ending_pickup_touch(Entity_Pickup& pickup, Entity_Player& player) +{ + if (pickup.variant == PICKUP_BIGCHEST && g_game->challenge == CHALLENGE_BACKASSWARDS) return; + if (pickup.state != 0) return; + pickup.target = &player; + pickup.state = 1; +} diff --git a/src/game_end.h b/src/game_end.h new file mode 100644 index 0000000..d392c15 --- /dev/null +++ b/src/game_end.h @@ -0,0 +1,53 @@ +#pragma once + +#include "classes.h" + +// How a run ends (Game::End's ending id): a death, or the ending of the last boss beaten. NONE is no ending yet, as +// on a floor the run goes on from, and UNKNOWN a floor without one. +enum GameEnding : int +{ + ENDING_NONE, + ENDING_DEATH, + ENDING_MOM, + ENDING_MOMS_HEART, + ENDING_SATAN, + ENDING_ISAAC, + ENDING_LAMB, + ENDING_BLUE_BABY, + ENDING_MEGA_SATAN, + ENDING_ULTRA_GREED, + ENDING_HUSH, + ENDING_DELIRIUM, + ENDING_ULTRA_GREEDIER, + ENDING_MOTHER, + ENDING_BEAST, + ENDING_LAST = ENDING_BEAST, + ENDING_UNKNOWN = 0xff +}; + +// Whether stage_ending_get lets the Polaroid or the Negative (or a challenge going on) carry the run past the +// Cathedral or Sheol. +enum EndingPhotos +{ + ENDING_PHOTOS_CHECKED, + ENDING_PHOTOS_IGNORED +}; + +// Whether a pickup's update goes on after the ending part, or stops as the run ends. +enum PickupUpdateEnd +{ + PICKUP_UPDATE_FINISH, + PICKUP_UPDATE_RETURN +}; + +void game_end(GameEnding ending); +GameEnding stage_ending_get(EndingPhotos photos); +void game_save_delete(); +void persistent_game_data_set_writable(); +void run_progress_save(); +void rerun_save(); +void challenge_finish(); +void ending_pickup_init(Entity_Pickup& pickup); +PickupUpdateEnd big_chest_update(Entity_Pickup& chest); +void trophy_update(Entity_Pickup& trophy); +void ending_pickup_touch(Entity_Pickup& pickup, Entity_Player& player); diff --git a/src/game_over.cpp b/src/game_over.cpp index ec5d74c..279cc51 100644 --- a/src/game_over.cpp +++ b/src/game_over.cpp @@ -68,9 +68,6 @@ constexpr std::pair DAMAGE_PORTRAITS[] = { {DAMAGE_SPIKES, 66}, {DAMAGE_CURSED_DOOR, 117}, {DAMAGE_POOP, 67}, {DAMAGE_TNT, 113}, {DAMAGE_FIRE, 68}, {DAMAGE_DEVIL, 110}, {DAMAGE_EXPLOSION, 65}, {DAMAGE_TIMER, 112}, {DAMAGE_IV_BAG, 114}}; -constexpr int EVENT_COUNTER_DEATHS = 10; -constexpr int EVENT_COUNTER_STREAK = 22; -constexpr int EVENT_COUNTER_NEGATIVE_STREAK = 113; constexpr int MUSIC_GAME_OVER = 8; constexpr int MUSIC_JINGLE_GAME_OVER = 93; constexpr int GAME_OVER_LEFT_LABEL = 3; @@ -313,65 +310,6 @@ void GameOver::Render() diary_seed_render(sprite); } -// 00959130 Forgets the saved run, outside a daily: its file, its checksum in the save data, and saving on exit. -// Online the original keeps it too. Netplay is offline. -void game_save_delete() -{ - Manager& manager = *g_manager; - - if (g_game->dailyChallenge._id != 0) return; - manager.gamestate.Delete(); - manager.persistentGameData.gameStateChecksum = 0; - manager.persistentGameData.isChangesMade = true; - manager.isSaveOnExit = false; -} - -// 0095a680 Opens the save data to the run's progress once per run, unless the run is custom, cannot unlock -// achievements or is a rerun: the run counts against the win streak (or the losing streak) and clears the run mask. -// Online, the original also reports the run to the netplay layer. Netplay is offline. -void persistent_game_data_set_writable() -{ - Manager& manager = *g_manager; - Game& game = *g_game; - PersistentGameData& data = manager.persistentGameData; - - if (game.seedEffects.isCustomRun || game.seedEffects.AchievementUnlocksDisallowed() || - Manager::AchievementUnlocksDisallowed() || game.isRerun || manager.isPersistentDataWritable) - return; - - bool isReadOnlyBefore = data.isReadOnly; - data.SetReadOnly(false); - int streak = data.eventCounters[EVENT_COUNTER_STREAK]; - if (streak == 0) data.IncreaseEventCounter(EVENT_COUNTER_NEGATIVE_STREAK, 1); - else data.IncreaseEventCounter(EVENT_COUNTER_STREAK, -streak); - data.SetReadOnly(isReadOnlyBefore); - data.set_run_mask(0); - manager.isPersistentDataWritable = true; -} - -// 006f9770 Ends the run (Rebirth's Game::End): a death forgets the saved run and opens the game over screen. Nothing -// ends during a versus match until it is over. -// Netplay is offline: the online stats screen and co-op's end vote are left out. -void game_end(GameEnding ending) -{ - Game& game = *g_game; - - if ((unsigned)ending > ENDING_LAST) - { - log_printf(LOG_INFO, "Invalid ending specified to Game::End()\n"); - return; - } - if (game.deathmatchManager.is_active() && game.deathmatchManager.state != DEATHMATCH_OVER) return; - - if (ending == ENDING_DEATH) game_save_delete(); - if (game.dailyChallenge._id != 0) reconstruction_missing("Game::End 006f9770 (a daily run's end)"); - if (ending != ENDING_DEATH) reconstruction_missing("Game::End 006f9770 (the endings' cutscenes)"); - - game.gameOver.Show(); - persistent_game_data_set_writable(); - lua_engine_get().PostGameEnd(ending == ENDING_DEATH); -} - // 009bc120 A player's death that ends the run: the deaths counter, the game over jingle with its music queued, and the // run's end. A co-op baby leaves the run instead. void PlayerManager::trigger_coop_baby_death(Entity_Player* deadPlayerEntity) diff --git a/src/game_over.h b/src/game_over.h index c1fc383..d78b3d7 100644 --- a/src/game_over.h +++ b/src/game_over.h @@ -2,6 +2,7 @@ #include "anm2.h" #include "classes.h" +#include "game_end.h" // Whether the game over screen is up. Show is the only writer of a shown state. enum GameOverState : int @@ -10,14 +11,6 @@ enum GameOverState : int GAME_OVER_SHOWN = 2 }; -// How a run ends (Game::End's ending id). The others are the endings' cutscenes. -enum GameEnding : int -{ - ENDING_DEATH = 1, - ENDING_MOM = 2, - ENDING_LAST = 14 -}; - // Copies and destruction are the defaults. // Online only, left out: the lobby's item strip (008ebfb0) and the vote the screen starts online. // The game over screen (Rebirth's DeathScreen): the diary page of the run lost, with the player's portrait and name, @@ -34,7 +27,3 @@ struct GameOver void Update(); void Render(); }; - -void game_end(GameEnding ending); -void game_save_delete(); -void persistent_game_data_set_writable(); diff --git a/src/game_transition.cpp b/src/game_transition.cpp index ad55526..f2b493e 100644 --- a/src/game_transition.cpp +++ b/src/game_transition.cpp @@ -1,10 +1,13 @@ +#include "capsule.h" #include "entity_player.h" +#include "entity_projectile.h" #include "game.h" #include "grid_entity_door.h" #include "log.h" #include "manager.h" #include "platform.h" #include "room.h" +#include "room_grid.h" #include "seeds.h" #include #include @@ -52,6 +55,51 @@ static void room_indices_shuffle(std::vector& indices) for (int i = (int)indices.size() - 1; i > 0; i--) std::swap(indices[i], indices[Random() % (uint32_t)(i + 1)]); } +// A teleport in the Beast's dungeon: up to 50 random spots, kept 30 and 20 and the player's size above the floor's +// bottom, until one has no enemy or shot that may hurt the player within its size and 40 more. +constexpr int BEAST_TELEPORT_ATTEMPTS = 50; +constexpr float BEAST_FLOOR_EDGE = 30; +constexpr float BEAST_TELEPORT_MARGIN = 20; +constexpr float BEAST_TELEPORT_CLEARANCE = 40; +constexpr int BEAST_TELEPORT_COOLDOWN = 60; + +// Whether an entity near a teleport's landing spot may hurt the player: an unfriendly enemy (a player in a versus +// match) or a shot that can hit players. +static bool is_teleport_threat(Entity& entity, bool isVersus) +{ + bool isEnemy = (isVersus && entity.type == ENTITY_PLAYER) || + (entity.type >= ENTITY_FIRST_ENEMY && entity.type <= ENTITY_LAST_ENEMY); + if (isEnemy && !entity.HasEntityFlags(FLAG_FRIENDLY)) return true; + if (entity.type != ENTITY_PROJECTILE) return false; + return !(static_cast(entity).projectileFlags & PROJECTILE_CANT_HIT_PLAYER); +} + +// Part of 006fd7c0: a teleport in the Beast's dungeon only moves the player within it, to a safe random spot (where it +// stands when none is found), out of harm for a second at least. +// The original finds the threats by capsule over the partitions. Here the radius query feeds the same capsule test. +static void beast_dungeon_teleport(Entity_Player& player) +{ + Room& room = *g_game->room; + bool isVersus = g_game->deathmatchManager.is_active(); + Vector landing = player.pos; + + for (int attempt = 0; attempt < BEAST_TELEPORT_ATTEMPTS; attempt++) + { + Vector spot = room.GetRandomPosition(0); + if (spot.y >= room.bottomRightPos.y - BEAST_FLOOR_EDGE - player.size - BEAST_TELEPORT_MARGIN) continue; + + Capsule search(spot, vector_make(1, 1), 0, player.size + BEAST_TELEPORT_CLEARANCE); + auto isThreat = [&](Entity* entity) + { return Capsule::Collide(search, entity->GetCollisionCapsule({})) && is_teleport_threat(*entity, isVersus); }; + if (std::ranges::any_of(entity_query_radius(spot, search.radius, QUERY_PROJECTILES | QUERY_ENEMIES), isThreat)) + continue; + landing = spot; + break; + } + player.Teleport(landing, true, true); + player.damageCooldown = std::max(player.damageCooldown, BEAST_TELEPORT_COOLDOWN); +} + // 006fd7c0 Checks a room transition and starts it. A versus match's fight only buzzes. The Glowing Hourglass on the // first floor's untouched start room goes back to the menu's stage transition (in Greed, teleports to the error room). // A teleport in the Beast's dungeon only moves the player. Leaving saves the rewind state (a teleport out of an @@ -88,9 +136,7 @@ void Game::StartRoomTransition(RoomTransitionRequest request) if (player && (animation == TRANSITION_TELEPORT || animation == TRANSITION_GLOWING_HOURGLASS)) { - if (room->IsBeastDungeon()) - reconstruction_missing("Game::StartRoomTransition 006fd7c0: a teleport in the Beast's dungeon " - "(Room::GetRandomPosition, Entity_Player::Teleport 007cd950)"); + if (room->IsBeastDungeon()) return beast_dungeon_teleport(*player); if (animation == TRANSITION_TELEPORT) { int type = room->roomType; diff --git a/src/grid_entity.cpp b/src/grid_entity.cpp index ae87997..2ce136c 100644 --- a/src/grid_entity.cpp +++ b/src/grid_entity.cpp @@ -25,6 +25,7 @@ #include "grid_entity_web.h" #include "log.h" #include "manager.h" +#include "menu_options.h" #include "npc_ai.h" #include "room.h" #include "room_grid.h" @@ -360,7 +361,7 @@ static void sacrifice_pickups_spawn(RNG& reward, const Vector& near, int variant static void sacrifice_bless(float chance) { g_game->angelRoomChance += chance; - std::string text(g_manager->stringTable.translate("#YOU_FEEL_BLESSED")); + std::string text(string_table_translate(g_manager->stringTable, "#YOU_FEEL_BLESSED")); g_game->hud.show_fortune_text_impl(text.c_str()); } diff --git a/src/grid_entity_decoration.cpp b/src/grid_entity_decoration.cpp index a5b519c..1ba31b1 100644 --- a/src/grid_entity_decoration.cpp +++ b/src/grid_entity_decoration.cpp @@ -2,9 +2,12 @@ #include "entity_player.h" #include "game.h" #include "log.h" +#include "npc_ai.h" #include "room.h" +#include "room_render.h" #include "seeds.h" #include +#include #include #include @@ -15,6 +18,116 @@ constexpr uint32_t GFUEL_SEED_STEP = 5; // How many props Init draws before keeping one that suits the room. constexpr int DECORATION_ATTEMPTS = 20; +// A puddle stains a footprint with its texel under the player, any layer's that is not quite clear. +constexpr float PUDDLE_ALPHA_THRESHOLD = 0.01f; +constexpr int ANY_LAYER = -1; + +// What Sprite::GetTexel samples: a screen position, where the sprite draws, the alpha a texel must reach and the +// layer it looks in (any for -1). +struct TexelQuery +{ + Vector sample{}; + Vector renderPos{}; + float alphaThreshold = 0; + int layerId = ANY_LAYER; +}; + +// Turns a point about the origin, as KAGE's Quad::rotate turns a quad's corners. +static Vector point_turn(Vector point, float cosine, float sine) +{ + return vector_make(point.x * cosine - point.y * sine, point.y * cosine + point.x * sine); +} + +// 0040b600 (ANM2::GetTexel) The color an animation of a sprite shows at a screen position: the texel of the first +// visible layer keyframe over it that reaches the alpha, in the sprite's, layer's and keyframe's tints and offsets +// (colorize aside), else clear. A turned layer is turned back about the origin, sample and all. +static KColor animation_texel_get(const ANM2& sprite, const AnimationState& animation, const TexelQuery& query) +{ + if (!animation.animData) return {}; + + const std::vector& tracks = animation.animData->animLayers; + for (size_t track = 0; track < tracks.size(); track++) + { + const AnimationLayer& layer = tracks[track]; + int frameIndex = track < animation.layerFrames.size() ? animation.layerFrames[track] : -1; + bool isLayerKnown = layer.layerId >= 0 && layer.layerId < (int)sprite.layerStates.size(); + if (layer.frames.empty() || (query.layerId >= 0 && layer.layerId != query.layerId) || !isLayerKnown) continue; + if (frameIndex < 0 || frameIndex >= (int)layer.frames.size()) continue; + + const AnimationFrame& frame = layer.frames[frameIndex]; + const LayerState& state = sprite.layerStates[layer.layerId]; + if (!frame.isVisible || !state.isVisible || !state.spriteSheet) continue; + + SpriteDraw draw = {.position = query.renderPos}; + SourceQuad source = AnimationLayer::GetSourceQuad(frame, state, draw, sprite); + DestinationQuad screen = AnimationLayer::GetDestQuad(frame, state, draw, sprite); + Vector sample = query.sample; + float layerTurn = frame.rotation + state.rotation; + float spriteTurn = sprite.rotation; + if (spriteTurn != 0 || layerTurn != 0) + { + float layerScaleX = frame.scale.x * state.size.x; + float layerScaleY = state.isFlipY ? -(frame.scale.y * state.size.y) : frame.scale.y * state.size.y; + float spriteScaleY = sprite.isFlipY ? -sprite.scale.y : sprite.scale.y; + if ((sprite.scale.x < 0) != (layerScaleX < 0)) + { + if (sprite.scale.x < 0) + { + layerTurn = -layerTurn; + spriteTurn = -spriteTurn; + } + if (layerScaleX < 0) layerTurn = -layerTurn; + } + if ((spriteScaleY < 0) != (layerScaleY < 0)) + { + if (spriteScaleY < 0) + { + layerTurn = -layerTurn; + spriteTurn = -spriteTurn; + } + if (layerScaleY < 0) layerTurn = -layerTurn; + } + + float angle = -(layerTurn + spriteTurn) * DEGREES_TO_RADIANS; + float cosine = std::cos(angle); + float sine = std::sin(angle); + for (Vector* corner : {&screen._topLeft, &screen._topRight, &screen._bottomLeft, &screen._bottomRight}) + *corner = point_turn(*corner, cosine, sine); + sample = point_turn(sample, cosine, sine); + } + + Vector topLeft = screen._topLeft; + Vector bottomRight = screen._bottomRight; + bool isOverX = topLeft.x < sample.x && sample.x < bottomRight.x; + if (!isOverX || topLeft.y >= sample.y || sample.y >= bottomRight.y) continue; + + float across = std::clamp((sample.x - topLeft.x) / (bottomRight.x - topLeft.x), 0.0f, 1.0f); + float down = std::clamp((sample.y - topLeft.y) / (bottomRight.y - topLeft.y), 0.0f, 1.0f); + float texelX = (source._bottomRight.x - source._topLeft.x) * across + source._topLeft.x; + float texelY = (source._bottomRight.y - source._topLeft.y) * down + source._topLeft.y; + KColor texel = image_texel_get(*state.spriteSheet, (uint32_t)(int)texelX, (uint32_t)(int)texelY); + if (texel._alpha < query.alphaThreshold) continue; + + ColorMod color = sprite.color; + color_multiply(color, state.color); + color_multiply(color, frame.color); + float red = color._tint[0] * texel._red + color._offset[0]; + float green = color._tint[1] * texel._green + color._offset[1]; + float blue = color._tint[2] * texel._blue + color._offset[2]; + return kcolor_rgba(red, green, blue, color._tint[3] * texel._alpha); + } + return {}; +} + +// 0040b590 (Sprite::GetTexel) The color a sprite shows at a screen position: its overlay's, unless that falls short +// of the alpha, then its main animation's. +static KColor sprite_texel_get(const ANM2& sprite, const TexelQuery& query) +{ + KColor texel = animation_texel_get(sprite, sprite.overlayAnimState, query); + if (texel._alpha < query.alphaThreshold) texel = animation_texel_get(sprite, sprite.animState, query); + return texel; +} + // 0099acc0 Picks the prop: a crawlspace's ladder, Greed's props, or one of the backdrop's (G FUEL's on its seed) drawn // from the cell's decoration seed until it suits the backdrop and the room has no puddle yet. Counts the puddles. void GridEntity_Decoration::subclass_init() @@ -83,8 +196,8 @@ void GridEntity_Decoration::subclass_init() room.unknown721c++; } -// 0099a8e0 Animates the prop. A puddle stays on its frame and stains the next footprint of a player walking on it. -// Sampling the puddle's color waits for Sprite::GetTexel (0040b590). +// 0099a8e0 Animates the prop. A puddle stays on its frame and stains the next footprint of a player walking on it in +// its color under the player. void GridEntity_Decoration::Update() { if (variant == DECORATION_HIDDEN || !sprite.isLoaded) @@ -97,9 +210,17 @@ void GridEntity_Decoration::Update() if (sprite.animState.animData) sprite.animState.isPlaying = false; for (Entity_Player* player : g_game->playerManager.playerList) - if (player->entityGridCollisionClass == GRIDCOLL_GROUND) - reconstruction_missing("GridEntity_Decoration::Update 0099a8e0: a " - "puddle's color (Sprite::GetTexel 0040b590)"); + { + if (player->entityGridCollisionClass != GRIDCOLL_GROUND) + continue; + + TexelQuery query = {.sample = render_position_get(player->pos, RENDER_SNAPPED), + .renderPos = get_render_position(), + .alphaThreshold = PUDDLE_ALPHA_THRESHOLD}; + KColor texel = sprite_texel_get(sprite, query); + if (texel._alpha > 0) + player->SetFootprintColor(texel, true); + } } // 0099ac00 Draws the prop in the room's floor color. diff --git a/src/grid_entity_pit.cpp b/src/grid_entity_pit.cpp index 84207b5..de2b831 100644 --- a/src/grid_entity_pit.cpp +++ b/src/grid_entity_pit.cpp @@ -16,8 +16,6 @@ constexpr int GRID_PATH_SPIKED_BRIDGE = 999; // A layout pit's variant: its frame in the low byte, the event flag, and the rails above it. constexpr int PIT_VARIANT_FRAME = 0xff; constexpr int PIT_VARIANT_EVENT = 0x80; -constexpr int PIT_VARIANT_RAILS = 0xff00; -constexpr int PIT_RAILS_SHIFT = 8; // The neighbours a pit's frame counts, by bit. constexpr int PIT_EDGE_LEFT = 1 << 0; diff --git a/src/grid_entity_pit.h b/src/grid_entity_pit.h index 1b729ff..28a8888 100644 --- a/src/grid_entity_pit.h +++ b/src/grid_entity_pit.h @@ -4,6 +4,10 @@ struct GridEntity_Rock; +// The rail piece a pit's variant carries over it, in its second byte. +constexpr int PIT_VARIANT_RAILS = 0xff00; +constexpr int PIT_RAILS_SHIFT = 8; + // A pit empty, about to be bridged by a pressure plate, bridged, and bridged by a spiked rock. enum PitState : int { diff --git a/src/grid_entity_rock.cpp b/src/grid_entity_rock.cpp index fadfcc7..4ed301d 100644 --- a/src/grid_entity_rock.cpp +++ b/src/grid_entity_rock.cpp @@ -735,7 +735,7 @@ void GridEntity_Rock::PlayBreakSound(GridEntityType type, int backdropType) sound = ALT_ROCK_SOUNDS[alt_rock_type_get(backdropType)]; else if (std::find(std::begin(FLESHY_BACKDROPS), std::end(FLESHY_BACKDROPS), roomBackdrop) != std::end(FLESHY_BACKDROPS)) - sound = SOUND_MEAT_IMPACTS; + sound = SOUND_MEATY_DEATHS; grid_sound_play(sound); } diff --git a/src/grid_entity_trap_door.cpp b/src/grid_entity_trap_door.cpp index be4bd1c..8fb2e44 100644 --- a/src/grid_entity_trap_door.cpp +++ b/src/grid_entity_trap_door.cpp @@ -39,7 +39,6 @@ constexpr int GAME_STATE_BACKWARDS_PATH_INIT = 47; // Mother's boss room in the special rooms. constexpr int BOSS_MOTHER = 88; constexpr int MINES_LAYER_HIDDEN = 1; -constexpr int EFFECT_MINES_TRAPDOOR_COVER = 139; constexpr float PLAYER_FAR = 1e9f; constexpr float PLAYER_CLEARANCE = 50; @@ -47,7 +46,6 @@ 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 SOUND_TRAP_DOOR_LEVEL = 1052; constexpr int VOID_SHOCKWAVE_FRAMES = 15; constexpr float VOID_SHOCKWAVE_AMPLITUDE = 0.05f; diff --git a/src/homing_laser.cpp b/src/homing_laser.cpp index 8f7806b..fa583ee 100644 --- a/src/homing_laser.cpp +++ b/src/homing_laser.cpp @@ -9,6 +9,8 @@ #include constexpr float BEZIER_HALF = 0.5f; +constexpr float RING_HANDLE = 0.3466f; +constexpr int RING_SEGMENTS = 6; constexpr int BEZIER_LENGTH_STEPS = 10; constexpr float SMOOTHING_FULL_LENGTH = 200; constexpr float PLAYER_CUT_DISTANCE_SQUARED = 100; @@ -335,10 +337,20 @@ void HomingLaser::apply_sample_wiggle(float, float) reconstruction_missing("HomingLaser::apply_sample_wiggle 009a0fa0"); } -// 009a0850 -void HomingLaser::build_ring_bezier() +// 009a0850 Lays out a ring of radius around a center: seven points (the last closing the circle) with handles along +// its tangent. Spoon Bender's ring bending toward enemies is not reconstructed yet. +void HomingLaser::build_ring_bezier(const Vector& center, bool isHoming, Entity*, float radius) { - reconstruction_missing("HomingLaser::build_ring_bezier 009a0850"); + for (int i = 0; i <= RING_SEGMENTS; i++) + { + float angle = 0 - ((float)i / RING_SEGMENTS * PI_F + (float)i / RING_SEGMENTS * PI_F); + Vector point = vector_make(std::cos(angle) * radius + center.x, std::sin(angle) * radius + center.y); + float tangentAngle = angle - PI_F / 2; + Vector tangent = vector_make(std::cos(tangentAngle) * radius * RING_HANDLE, + std::sin(tangentAngle) * radius * RING_HANDLE); + bezier.push_back({point, vector_sub(point, tangent), vector_add(point, tangent)}); + } + if (isHoming) reconstruction_missing("HomingLaser::build_ring_bezier 009a0850 (a homing ring)"); } // 0099f2c0 diff --git a/src/homing_laser.h b/src/homing_laser.h index 669c3ab..29bcd33 100644 --- a/src/homing_laser.h +++ b/src/homing_laser.h @@ -69,7 +69,7 @@ struct HomingLaser void build_wiggle_bezier(); void truncate_samples_at_obstacle(const Vector& offset); void apply_sample_wiggle(float amplitude, float phase); - void build_ring_bezier(); + void build_ring_bezier(const Vector& center, bool isHoming, Entity* ignored, float radius); void trace_entities(uint32_t turnFlags); }; diff --git a/src/hud.cpp b/src/hud.cpp index 64a3dc6..53f15d1 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -638,7 +638,13 @@ void HUD::show_pill_name(Entity_Player* player, const char* title, const char* s if (hudIndex >= 0) messagePlayerHUD[hudIndex].Show(title, subtitle, true, false); return; } + ShowStackedItemTextCustom(title, subtitle); +} +// 009a34a0 (HUD::ShowStackedItemTextCustomUTF16) Shows a title and subtitle on the first free stacked banner, none +// when all six show. +void HUD::ShowStackedItemTextCustom(const char* title, const char* subtitle) +{ for (HUD_Message& message : messageStack) if (!message.isShowing) return message.Show(title, subtitle, true, false); } diff --git a/src/hud.h b/src/hud.h index 6caa1a3..b7f7b0b 100644 --- a/src/hud.h +++ b/src/hud.h @@ -172,6 +172,7 @@ public: bool IsVisible(); void ShowItemText(Entity_Player* player, ItemConfig_Item* item); + void ShowStackedItemTextCustom(const char* title, const char* subtitle); static int lua_show_item_text(void* luaState); void show_pill_name(Entity_Player* player, const char* title, const char* subtitle); void ShowFortuneText(const std::vector& lines); diff --git a/src/item_overlay.h b/src/item_overlay.h index cf3acd9..21a0804 100644 --- a/src/item_overlay.h +++ b/src/item_overlay.h @@ -23,6 +23,7 @@ enum GiantbookOverlay : int { GIANTBOOK_ETERNAL_SOUL_HEART = 6, GIANTBOOK_ETERNAL_HEART = 13, + GIANTBOOK_NECRONOMICON = 12, GIANTBOOK_CLICKER = 39, GIANTBOOK_SLEEP_NIGHTMARE = 44, GIANTBOOK_MEGA_MUSH = 45, diff --git a/src/item_pickup.cpp b/src/item_pickup.cpp index 5b6ff42..5758ad1 100644 --- a/src/item_pickup.cpp +++ b/src/item_pickup.cpp @@ -66,7 +66,6 @@ constexpr int SOUND_CHOIR_UNLOCK = 23; constexpr int SOUND_POWERUP2 = 129; constexpr int SOUND_POWERUP3 = 130; constexpr int SOUND_BAND_AID_PICK_UP = 169; -constexpr int SOUND_DEVILROOM_DEAL = 316; constexpr int ONE_UP_FRAME_DELAY = 30; constexpr float ITEM_SOUND_HALF_VOLUME = 0.5f; constexpr int COLLECTIBLE_MAGIC_MUSHROOM = 12; @@ -500,8 +499,7 @@ void item_text_show(HUD& hud, Entity_Player* player, ItemConfig_Item* item) reconstruction_missing("HUD::ShowItemText 009a2d20: the scrambled text"); if (item->id == COLLECTIBLE_TMTRAINER) reconstruction_missing("HUD::ShowItemText 009a2d20: TMTRAINER's pattern"); - for (HUD_Message& message : hud.messageStack) - if (!message.isShowing) return message.Show(name.c_str(), description.c_str(), true, false); + hud.ShowStackedItemTextCustom(name.c_str(), description.c_str()); } // 006edfa0 Turns a cycling pedestal to its next item every 30 frames (every 6 with four or more, every frame with diff --git a/src/level.cpp b/src/level.cpp index 3890e78..73c76c1 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -4,11 +4,13 @@ #include "entity_player.h" #include "game.h" #include "grid_entity_door.h" +#include "grid_entity_pit.h" #include "hud.h" #include "lua_engine.h" #include "menu_special_seeds.h" #include "music_manager.h" #include "manager.h" +#include "npc_ai.h" #include "platform.h" #include "room.h" #include "room_transition.h" @@ -133,6 +135,7 @@ constexpr int ULTRA_SECRET_GROUP = 99; constexpr int BOSS_MEGA_SATAN = 55; constexpr int BOSS_MOTHER = 88; constexpr int BOSS_MOTHER_HEART = 89; +constexpr int BOSS_MOMS_HEART_MAUSOLEUM = 90; constexpr int BOSS_ROOM_RETRIES = 50; constexpr int BOSS_ROOM_VARIANTS = 50; constexpr int BOSS_ROOM_REROLL_FIRST = 3700; @@ -166,6 +169,33 @@ constexpr uint32_t BEDROOM_ODDS = 50; constexpr uint32_t BEDROOM_DYING_ODDS = 5; constexpr int MIRROR_ROOM_SUBTYPE = 34; constexpr int MINESHAFT_ENTRANCE_SUBTYPE = 10; +constexpr int MINESHAFT_RAIL_PLATE_SUBTYPE = 1; +constexpr int GRID_SPAWN_PIT_RAIL = 3002; +constexpr int RAIL_RAISE_SHAKE = 20; +constexpr float RAIL_RAISE_VOLUME = 1.5f; + +// A room of the abandoned mineshaft: its top left cell, its shape and its layout subtype. +struct MineshaftRoom +{ + XY position; + RoomShape shape; + int subtype; +}; + +// The mineshaft's rooms, from the shaft under the entrance up to the knife piece's room. +constexpr int MINESHAFT_SHAFT_SUBTYPE = 11; +constexpr int MINESHAFT_TUNNEL_SUBTYPE = 30; +constexpr int MINESHAFT_KNIFE_SUBTYPE = 20; +constexpr std::array MINESHAFT_ROOMS = {{ + {{6, 12}, ROOMSHAPE_1x1, MINESHAFT_SHAFT_SUBTYPE}, + {{6, 10}, ROOMSHAPE_IIV, MINESHAFT_TUNNEL_SUBTYPE}, + {{5, 8}, ROOMSHAPE_2x2, MINESHAFT_TUNNEL_SUBTYPE}, + {{5, 7}, ROOMSHAPE_1x1, MINESHAFT_TUNNEL_SUBTYPE}, + {{5, 5}, ROOMSHAPE_2x2, MINESHAFT_TUNNEL_SUBTYPE}, + {{7, 5}, ROOMSHAPE_IIH, MINESHAFT_TUNNEL_SUBTYPE}, + {{9, 5}, ROOMSHAPE_1x1, MINESHAFT_TUNNEL_SUBTYPE}, + {{9, 4}, ROOMSHAPE_1x1, MINESHAFT_KNIFE_SUBTYPE}, +}}; constexpr int SPECIAL_DOOR_PUZZLE_SUBTYPE = 1; constexpr uint32_t DARK_ROOM_EXTRA_VARIANT_FIRST = 3; constexpr uint32_t DARK_ROOM_EXTRA_VARIANT_LAST = 9; @@ -2432,6 +2462,44 @@ static void corpse_door_splats_spawn(Level& level) } } +// The mineshaft entrance's sunken rail cells, by its layout's rail pits in order, and how many are raised already. +struct MineshaftRails +{ + std::vector cells; + int raisedCount = 0; +}; + +// Raises a sunken rail out of its pit: the pit bridged and a straight rail on it. +static void rail_pit_raise(Room& room, GridEntity_Pit& pit) +{ + if (pit.state == PIT_STATE_EMPTY) + { + pit.state = PIT_STATE_FILLED; + pit.UpdateCollision(); + } + pit.variant = (pit.variant & ~PIT_VARIANT_RAILS) | RAIL_VERTICAL << PIT_RAILS_SHIFT; + room.railManager.rails[pit.gridIndex] = RAIL_VERTICAL; +} + +// The rail cells of the mineshaft entrance's layout and how many of them its saved cells hold raised. +static MineshaftRails mineshaft_rails_get(RoomDescriptor& entrance) +{ + MineshaftRails rails; + RoomConfig_Room& data = *entrance.data; + + for (RoomSpawn& spawn : data.spawns) + { + if (spawn.entries.empty() || spawn.entries[0].type != GRID_SPAWN_PIT_RAIL) continue; + + int cell = spawn.x + 1 + (data.width + 2) * (spawn.y + 1); + GridEntityDesc& saved = entrance.savedGridEntities[cell]; + + rails.cells.push_back(cell); + if (saved._type == GRID_PIT && saved._state != PIT_STATE_EMPTY) rails.raisedCount++; + } + return rails; +} + // 0073e0a0 Builds the room the players are in from its descriptor: Devil's Crown's devil treasure rooms, the treasure // room rerolls, Greed's takeover config and a door into rooms off the map first, then the room itself, its doors and // the special doors a cleared room spawns, the mineshaft entrance's bridged pits, Genesis's reset, and the players' @@ -2464,7 +2532,12 @@ void Level::load_room() (desc.flags & ROOM_DESCRIPTOR_FLAG_SACRIFICE_DONE) && !desc.data->spawns.empty(); if (!isGreed && !IsAscent() && IsAltPath() && isMineshaftFloor && isMineshaftEntrance) - reconstruction_missing("Level::load_room 0073e0a0: the mineshaft entrance's bridged pits (Room+0x746d)"); + for (int cell : mineshaft_rails_get(desc).cells) + { + GridEntity* pit = cell < ROOM_GRID_CELLS ? room->gridEntities[cell] : nullptr; + if (pit && pit->type == GRID_PIT && pit->collisionClass == COLLISION_PIT) + rail_pit_raise(*room, static_cast(*pit)); + } doors_target(*this, desc); if (GetRoomByIdx(currentRoomIdx)->flags & ROOM_DESCRIPTOR_FLAG_CLEAR) { @@ -2636,16 +2709,78 @@ void Level::generate_random_layout() reconstruction_missing("Level::generate_random_layout 007508c0"); } -// 0074f0c0 Lays out the mirror world. +// 0074f0c0 Lays out the mirror world on dimension 1: a copy of every room of the floor with its decoration seed, but +// the first treasure room, which becomes the knife piece's treasure room of the same shape and doors. The mirrored +// rooms of the knife piece's own subtype keep their spawn seed. void Level::generate_mirror_world() { - reconstruction_missing("Level::generate_mirror_world 0074f0c0"); + int roomCount = nbRooms; + bool isTreasureReplaced = false; + + currentDimensionIdx = 1; + currentRoomMap = roomMap.data() + LEVEL_GRID_CELLS; + for (int i = 0; i < roomCount; i++) + { + RoomDescriptor& source = roomList[i]; + RoomConfig_Room* data = source.data; + if (data->type == ROOM_TREASURE && !isTreasureReplaced) + { + RoomQuery query = room_query(g_game->GetStageID(), ROOM_TREASURE, TREASURE_SUBTYPE_KNIFE_PIECE); + RNG rng = {source.spawnSeed, 2, 7, 7}; + + query.shape = data->shape; + query.requiredDoors = data->doors; + data = g_game->roomConfig.GetRandomRoomWithFallbackStage(rng.Next(), WEIGHT_KEEP, query, STAGE_ID_DOWNPOUR); + isTreasureReplaced = true; + } + + LevelGenerator_Room slot; + RoomDescriptor* mirrored = nullptr; + + slot.position = XY::NewFromGridIdx(source.gridIndex); + slot.shape = data->shape; + slot.doors = source.allowedDoors; + place_room(slot, data, source.decorationSeed, &mirrored); + mirrored->decorationSeed = source.decorationSeed; + if (data->type == ROOM_DEFAULT && data->subtype == TREASURE_SUBTYPE_KNIFE_PIECE) + mirrored->spawnSeed = source.spawnSeed; + } + currentDimensionIdx = 0; + currentRoomMap = roomMap.data(); } -// 0074f360 Lays out the abandoned mineshaft. +// 0074f360 Lays out the abandoned mineshaft on dimension 1: its eight rooms at their fixed cells, from the entrance's +// shaft at the bottom to the knife piece's room at the top, drawn from the floor's mineshaft rooms (the Mines' as a +// fallback) with the doors their neighbours give them. void Level::generate_mineshaft() { - reconstruction_missing("Level::generate_mineshaft 0074f360"); + LevelGenerator generator(generationRNG.Next()); + int stageId = RoomConfig::GetStageID((int)stage, (int)stageType, ROOM_MODE_CURRENT); + + currentDimensionIdx = 1; + currentRoomMap = roomMap.data() + LEVEL_GRID_CELLS; + for (const MineshaftRoom& room : MINESHAFT_ROOMS) + { + LevelGenerator_Room slot; + + slot.position = room.position; + slot.shape = room.shape; + generator.CreateRoom(slot); + } + for (size_t i = 0; i < MINESHAFT_ROOMS.size(); i++) + { + LevelGenerator_Room& slot = generator.rooms[i]; + RoomQuery query = room_query(stageId, ROOM_DEFAULT, MINESHAFT_ROOMS[i].subtype); + + query.minDifficulty = query.maxDifficulty = 0; + query.shape = slot.shape; + query.requiredDoors = slot.doors; + + RoomConfig_Room* data = fallback_room_get(generationRNG.Next(), query, STAGE_ID_MINES); + place_room(slot, data, generationRNG.Next(), nullptr); + } + currentDimensionIdx = 0; + currentRoomMap = roomMap.data(); } // 00751650 Lays out the Death Certificate area. @@ -2853,16 +2988,27 @@ Vector Level::GetEnterPosition() return g_vectorZero; } -// 0074c160 The cell a door leads to. -XY Level::get_door_neighbor_pos(XY, RoomShape, int) +// 0074c160 The cell a door slot of a shape at a cell leads into, or none when the shape lacks the slot. The layout +// generator's rule. +XY Level::get_door_neighbor_pos(XY gridPos, RoomShape shape, int doorSlot) { - reconstruction_missing("Level::get_door_neighbor_pos 0074c160"); + return LevelGenerator::get_door_target_position(gridPos, shape, doorSlot, THIN_SHAPES_RESTRICTED); } -// 0074c540 The room a door leads to. -int Level::GetNeighborRoomIdx(int, int) +// 0074c540 The map cell a room's door slot leads into: -1 when its layout has no door there, -2 when the cell is off +// the map. A room without a layout counts as a 1x1 room at its index. The room's size comes from its shape. +int Level::GetNeighborRoomIdx(int roomIdx, int doorSlot) { - reconstruction_missing("Level::GetNeighborRoomIdx 0074c540"); + RoomDescriptor& desc = *GetRoomByIdx(roomIdx); + RoomConfig_Room* data = desc.data; + if (data && !(data->doors & 1u << doorSlot)) return -1; + + XY cell = data ? LevelGenerator::get_door_target_position(XY::NewFromGridIdx(desc.gridIndex), data->shape, doorSlot, + THIN_SHAPES_IGNORED) + : get_door_neighbor_pos(XY::NewFromGridIdx(roomIdx), ROOMSHAPE_1x1, doorSlot); + int neighbor = cell.ToGridIdx(); + + return neighbor < 0 ? -2 : neighbor; } // 0074c9e0 The slots a red room would open toward. @@ -3074,10 +3220,76 @@ void Level::StartMamaMega(Vector&, Entity_Player*) reconstruction_missing("Level::StartMamaMega 0074ba00"); } -// 0074eaf0 Raises the mineshaft's rail. +// 0074eaf0 A rail plate pressed on the mineshaft floor raises the entrance's next rail: the plate rooms and the +// entrance count off in floor order, and the plate room's place picks the rail. In the entrance the pit becomes a +// bridged rail with a rumble; elsewhere its saved cell is rewritten and the rumble comes from the entrance's side. +// The secret room jingle plays once the last rail is up. void Level::raise_mineshaft_rail() { - reconstruction_missing("Level::raise_mineshaft_rail 0074eaf0"); + if (!HasAbandonedMineshaft()) return; + + RoomDescriptor* current = GetRoomByIdx(currentRoomIdx, currentDimensionIdx); + RoomDescriptor* entrance = nullptr; + int ordinal = 0; + int currentOrdinal = -1; + + for (int i = 0; i < nbRooms; i++) + { + RoomDescriptor& desc = roomList[i]; + if (desc.dimension != 0 || desc.data->type != ROOM_DEFAULT) continue; + + if (&desc == current) currentOrdinal = ordinal; + if (desc.data->subtype == MINESHAFT_ENTRANCE_SUBTYPE) + { + ordinal++; + if (!entrance) entrance = &desc; + } + else if (desc.data->subtype == MINESHAFT_RAIL_PLATE_SUBTYPE) ordinal++; + } + if (!entrance) return; + + MineshaftRails rails = mineshaft_rails_get(*entrance); + if (currentOrdinal < 0 || currentOrdinal >= (int)rails.cells.size()) return; + + int cell = rails.cells[currentOrdinal]; + int sound = SOUND_RAILROAD_TRACK_RAISE; + SoundPlay play = {.volume = RAIL_RAISE_VOLUME}; + + if (entrance == current) + { + GridEntity* pit = cell < ROOM_GRID_CELLS ? room->gridEntities[cell] : nullptr; + if (!pit || pit->type != GRID_PIT) return; + + rail_pit_raise(*room, static_cast(*pit)); + game_shake_screen(RAIL_RAISE_SHAKE); + seed_fart_sound_override(&sound); + } + else + { + if (cell < 0 || cell >= (int)entrance->savedGridEntities.size()) return; + + RNG spawnRng = {current->spawnSeed, 2, 15, 25}; + RNG variableRng = {current->spawnSeed, 2, 21, 9}; + + GridEntityDesc& saved = entrance->savedGridEntities[cell]; + + saved = GRID_SAVE_EMPTY; + saved._type = GRID_PIT; + saved._variant = RAIL_VERTICAL << PIT_RAILS_SHIFT; + saved._state = PIT_STATE_FILLED; + saved._spawnSeed = spawnRng.Next(); + saved._variableSeed = variableRng.Next(); + game_shake_screen(RAIL_RAISE_SHAKE); + sound = SOUND_RAILROAD_TRACK_RAISE_FAR; + if (currentRoomIdx >= 0) + { + XY from = XY::NewFromGridIdx(currentRoomIdx); + XY to = XY::NewFromGridIdx(entrance->gridIndex); + play.pan = vector_normalized(vector_make((float)(to.x - from.x), (float)(to.y - from.y))).x; + } + } + g_manager->sfxManager.Play(sound, play); + if (rails.raisedCount + 1 == (int)rails.cells.size()) g_manager->musicManager.PlayJingle(MUSIC_JINGLE_SECRET_ROOM_FIND); } // The music layer the Ascent turns on for a stage it climbs through: one per chapter, the alternate paths' past them. @@ -3188,10 +3400,20 @@ int Level::get_secret_exit_kind() } } -// 0074bba0 The secret exit's room. -RoomDescriptor* Level::get_secret_exit_room(int) +// 0074bba0 The secret exit's room, drawn from the special rooms the first time it is asked for: Mom's Heart's boss +// room, or the exit room of that kind. +RoomDescriptor* Level::get_secret_exit_room(int kind) { - reconstruction_missing("Level::get_secret_exit_room 0074bba0"); + RoomDescriptor& desc = *GetRoomByIdx(ROOM_SECRET_EXIT_IDX); + if (desc.data) return &desc; + + RoomQuery query = kind == SECRET_EXIT_MOMS_HEART + ? room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_BOSS, BOSS_MOMS_HEART_MAUSOLEUM) + : room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_SECRET_EXIT, kind); + + desc.InitSeeds(devilAngelRoomRNG); + desc.data = random_room_get(devilAngelRoomRNG.Next(), query, WEIGHT_KEEP); + return &desc; } // 00745ca0 A stage's display name in the current language: stages.xml's, then the endless basement's roman numeral and diff --git a/src/lua_api.h b/src/lua_api.h index 0c0d369..9e7605d 100644 --- a/src/lua_api.h +++ b/src/lua_api.h @@ -52,6 +52,7 @@ struct ItemConfig_Item; struct ItemConfig_Pill; struct KColor; struct ANM2; +struct PathFinder; struct ProjectileParams; struct QueueItemData; struct RoomConfig_Room; @@ -206,6 +207,8 @@ inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ROOM_DESCRIPT template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_ROOM_LIST; template <> +inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_PATH_FINDER; +template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_SEEDS; template <> inline constexpr LuaClass LUA_CLASS_OF = LUA_CLASS_SFX_MANAGER; diff --git a/src/lua_api_entities.cpp b/src/lua_api_entities.cpp index 0e404c7..44fa966 100644 --- a/src/lua_api_entities.cpp +++ b/src/lua_api_entities.cpp @@ -10,6 +10,8 @@ #include "entity_projectile.h" #include "entity_tear.h" #include "lua_api.h" +#include "weapon.h" +#include "path_finder.h" // Registers Lua's EntityTear and EntityProjectile, the shots of players and enemies. static void shots_register(lua_State* state) @@ -92,6 +94,7 @@ static void weapons_register(lua_State* state) lua_method(state, "GetKnifeDistance", [](Entity_Knife& knife) { return knife.knifeDistance; }); lua_method(state, "GetKnifeVelocity", [](Entity_Knife& knife) { return knife.knifeVelocity; }); lua_method(state, "SetPathFollowSpeed", [](Entity_Knife& knife, float speed) { knife.pathFollowSpeed = speed; }); + weapon_lua_knife_register(state); lua_class_end(state); lua_class_begin(state, "EntityLaser", LUA_CLASS_LASER, LUA_CLASS_ENTITY); @@ -126,6 +129,7 @@ static void weapons_register(lua_State* state) [](Entity_Laser& laser, float chance) { laser.blackHpDropChance = chance; }); lua_method(state, "IsCircleLaser", [](Entity_Laser& laser) { return laser.IsCircleLaser(); }); lua_method(state, "IsSampleLaser", [](Entity_Laser& laser) { return laser.isSampleLaser; }); + weapon_lua_laser_register(state); lua_class_end(state); } @@ -239,6 +243,7 @@ static void npc_pickup_register(lua_State* state) }); lua_method(state, "MakeSplat", [](Entity_NPC& npc, float size) { return npc.MakeSplat(size); }); lua_method(state, "KillUnique", [](Entity_NPC& npc) { npc.KillUnique(); }); + lua_property(state, "Pathfinder", [](Entity_NPC& npc) -> PathFinder& { return npc.pathfinder; }); lua_method(state, "ResetPathFinderTarget", [](Entity_NPC& npc) { npc.ResetPathFinderTarget(); }); lua_method(state, "GetAliveEnemyCount", [](Entity_NPC& npc) { return npc.GetAliveEnemyCount(); }); lua_method(state, "FireProjectiles", [](Entity_NPC& npc, Vector position, Vector velocity, ProjectilesMode mode, @@ -281,6 +286,43 @@ static void npc_pickup_register(lua_State* state) lua_class_end(state); } +// A movement argument from Lua: true moves a pathfinder despite fear, confusion or charm. +static StatusMode status_mode(bool isIgnored) +{ + return isIgnored ? STATUS_IGNORED : STATUS_OBEYED; +} + +// Registers Lua's PathFinder, an NPC's way around the room. +static void path_finder_register(lua_State* state) +{ + lua_class_begin(state, "PathFinder", LUA_CLASS_PATH_FINDER); + lua_method(state, "Reset", [](PathFinder& path) { path.Reset(); }); + lua_method(state, "ResetMovementTarget", [](PathFinder& path) { path.ResetMovementTarget(); }); + lua_method(state, "UpdateGridIndex", [](PathFinder& path) { path.UpdateGridIndex(); }); + lua_method(state, "GetGridIndex", [](PathFinder& path) { return path.gridIndex; }); + lua_method(state, "HasDirectPath", [](PathFinder& path) { return path.hasDirectPath; }); + lua_method(state, "GetEvadeMovementCountdown", [](PathFinder& path) { return path.evadeMovementCountdown; }); + lua_method(state, "SetCanCrushRocks", [](PathFinder& path, bool isCrushing) { path.canCrushRocks = isCrushing; }); + lua_method(state, "HasPathToPos", [](PathFinder& path, Vector position, bool isIgnorePoop) { + return path.HasPathToPos(position, isIgnorePoop); + }); + lua_method(state, "FindGridPath", + [](PathFinder& path, Vector position, float speed, int pathMarker, bool isDirect) { + path.FindGridPath(position, speed, pathMarker, isDirect ? DIRECT_PATH_FAR : DIRECT_PATH_NEAR); + }); + lua_method(state, "EvadeTarget", [](PathFinder& path, Vector target, bool isIgnored) { + path.EvadeTarget(target, status_mode(isIgnored)); + }); + lua_method(state, "MoveRandomly", + [](PathFinder& path, bool isIgnored) { return path.MoveRandomly(status_mode(isIgnored)); }); + lua_method(state, "MoveRandomlyBoss", + [](PathFinder& path, bool isIgnored) { path.MoveRandomlyBoss(status_mode(isIgnored)); }); + lua_method(state, "MoveRandomlyAxisAligned", [](PathFinder& path, float speed, bool isIgnored) { + path.MoveRandomlyAxisAligned(speed, status_mode(isIgnored)); + }); + lua_class_end(state); +} + // Registers Lua's ProjectileParams, how FireProjectiles shoots, which scripts construct. static void projectile_params_register(lua_State* state) { @@ -314,6 +356,7 @@ static void projectile_params_register(lua_State* state) void lua_api_entities_register(lua_State* state) { + path_finder_register(state); projectile_params_register(state); shots_register(state); weapons_register(state); diff --git a/src/lua_api_entity_player.cpp b/src/lua_api_entity_player.cpp index 935c47d..00c9df5 100644 --- a/src/lua_api_entity_player.cpp +++ b/src/lua_api_entity_player.cpp @@ -378,6 +378,7 @@ void lua_api_entity_player_register(lua_State* state) player_items_register(state); player_misc_register(state); player_stats_register(state); + weapon_lua_player_register(state); lua_class_end(state); lua_class_begin(state, "QueueItemData", LUA_CLASS_QUEUE_ITEM_DATA); diff --git a/src/lua_api_room.cpp b/src/lua_api_room.cpp index a03837d..c228472 100644 --- a/src/lua_api_room.cpp +++ b/src/lua_api_room.cpp @@ -298,6 +298,9 @@ static void room_register(lua_State* state) [](Room& room, int index, GridEntityType type, int variant, uint32_t seed, int varData) { return room.SpawnGridEntity(index, type, variant, seed, varData); }); + lua_method(state, "RemoveGridEntity", [](Room& room, int index, int pathTrail, bool isKeepDecoration) { + room.RemoveGridEntity(index, pathTrail, isKeepDecoration ? DECORATION_KEPT : DECORATION_REMOVED); + }); lua_method(state, "GetDoor", [](Room& room, int slot) { return room.GetDoor(slot); }); lua_method(state, "IsDoorSlotAllowed", [](Room& room, int slot) { return room.IsDoorSlotAllowed(slot); }); lua_method(state, "RemoveDoor", [](Room& room, int slot) { room.RemoveDoor(slot); }); diff --git a/src/lua_engine.h b/src/lua_engine.h index 67909bc..8b3680a 100644 --- a/src/lua_engine.h +++ b/src/lua_engine.h @@ -76,6 +76,7 @@ enum LuaClass LUA_CLASS_KCOLOR, LUA_CLASS_LEVEL, LUA_CLASS_MUSIC_MANAGER, + LUA_CLASS_PATH_FINDER, LUA_CLASS_PROJECTILE_PARAMS, LUA_CLASS_QUEUE_ITEM_DATA, LUA_CLASS_RNG, diff --git a/src/manager.cpp b/src/manager.cpp index 1fe559a..7a15763 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -191,8 +191,6 @@ constexpr int SCREENSHOT_KEY = 298; constexpr const char* SCREENSHOTS_FOLDER = "screenshots"; // The stage bar's icon for a stage not reached. constexpr int STAGE_ICON_EMPTY = 17; -// The rerun unlock, which keeps a slot's last run to play again. -constexpr int ACHIEVEMENT_RERUN = 337; // The loading screen's image pairs, one per seed numbered from 1, with a set of its own for the greed modes. constexpr uint32_t LOAD_IMAGE_COUNT = 56; constexpr uint32_t LOAD_IMAGE_GREED_COUNT = 20; @@ -1685,5 +1683,4 @@ void seed_fart_sound_override(int* soundId) // Not reconstructed yet: each stops the game where it is reached. Manager::~Manager() { reconstruction_missing("Manager::destructor 00951160"); } void Manager::render_button_sprite(int, Vector) { reconstruction_missing("Manager::render_button_sprite 0095ad30"); } -void Manager::RestartGame() { reconstruction_missing("Manager::RestartGame 00958cb0"); } void Manager::apply_device_key_config(int) { reconstruction_missing("Manager::apply_device_key_config 0095b180"); } diff --git a/src/manager_restart.cpp b/src/manager_restart.cpp new file mode 100644 index 0000000..efc78f1 --- /dev/null +++ b/src/manager_restart.cpp @@ -0,0 +1,25 @@ +#include "game.h" +#include "manager.h" + +// Where the back and confirm prompts slide out to while the new run loads. +constexpr float BUTTONS_HIDDEN_SLIDE = 96; + +// 00958cb0 Queues the run again on its own seeds, keeping the start seed only for a custom run outside a challenge, +// with no save of the run it leaves. +// Every caller passes the game's seeds and leaves the special seeds and the Mr. Resetter! reset count alone, so those +// arguments are gone. Netplay is offline, so no joins are pending and the restart always starts at once. +void Manager::RestartGame() +{ + Manager& manager = *g_manager; + + if (!g_game) log_printf(LOG_ASSERT, "Game must not be NULL"); + manager.startSeeds = g_game->seedEffects; + bool isSeedKept = manager.startSeeds.isCustomRun && g_game->challenge == 0; + manager.startSeeds.set_start_seed(isSeedKept ? manager.startSeeds.gameStartSeed : 0); + + manager.isStarting = true; + manager.isSaveOnExit = false; + manager.consecutiveResetCount = 0; + for (PopupButton& button : manager.popupButtons.buttons) button.targetSlideOffset = BUTTONS_HIDDEN_SLIDE; + manager.persistentGameData.set_run_mask(0); +} diff --git a/src/menu_bestiary.cpp b/src/menu_bestiary.cpp index 9996324..86c55de 100644 --- a/src/menu_bestiary.cpp +++ b/src/menu_bestiary.cpp @@ -2,6 +2,7 @@ #include "log.h" #include "manager.h" #include "menu_manager.h" +#include "menu_options.h" #include #include @@ -347,8 +348,8 @@ void Menu_Bestiary::details_render(Vector origin, EntityConfig_Entity& entity) { deathScreenSprite.SetLayerFrame(DIARY_ENEMY_LAYER, UNKNOWN_FRAME); deathScreenSprite.RenderLayer(DIARY_ENEMY_LAYER, {offset_get(origin, PORTRAIT)}); - font.DrawString(g_manager->stringTable.translate("#BESTIARY_UNKNOWN"), offset_get(origin, UNKNOWN_TEXT), - vector_make(1, 1), gray, settings); + std::string_view text = string_table_translate(g_manager->stringTable, "#BESTIARY_UNKNOWN"); + font.DrawString(text, offset_get(origin, UNKNOWN_TEXT), vector_make(1, 1), gray, settings); return; } diff --git a/src/menu_stats.cpp b/src/menu_stats.cpp index e7143be..d9befae 100644 --- a/src/menu_stats.cpp +++ b/src/menu_stats.cpp @@ -27,10 +27,6 @@ constexpr int DIGIT_LAYER = 7; constexpr int SECRETS_LOCK_LAYER = 8; constexpr int SECRETS_LOCK_FRAME = 1; constexpr int DIGIT_BASE = 10; -constexpr int EVENT_COUNTER_MOM_KILLS = 1; -constexpr int EVENT_COUNTER_DEATHS = 10; -constexpr int EVENT_COUNTER_BEST_STREAK = 23; -constexpr int EVENT_COUNTER_ONLINE_BEST_STREAK = 498; constexpr int FAST_HOLD = 60; constexpr int FASTER_HOLD = 180; constexpr float SPEED_RAMP_FRAMES = 30; diff --git a/src/mines.cpp b/src/mines.cpp new file mode 100644 index 0000000..9b5da87 --- /dev/null +++ b/src/mines.cpp @@ -0,0 +1,451 @@ +#include "mines.h" +#include "entity_effect_combat.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "manager.h" +#include "npc_ai.h" +#include "rail_manager.h" +#include "room.h" +#include +#include +#include +#include + +constexpr float TRAPDOOR_COVER_DEPTH = -26; + +constexpr int MINECART_STATE_RIDING = 4; +constexpr int MINECART_STATE_GONE = 3; +constexpr int MINECART_STATE_WAITING = 16; +constexpr int MINECART_EMPTY_FRAMES = 2; +constexpr int MINECART_SETTLE_FRAMES = 15; +constexpr float MINECART_PUSH = 1.3f; +constexpr float MINECART_FRICTION = 0.9f; +constexpr float MINECART_RIDDEN_FRICTION = 0.8f; +constexpr float MINECART_EMPTY_MASS = 50; +constexpr float MINECART_RIDDEN_MASS = 10000; +constexpr float MINECART_VARIANT_ENTRANCE_MASS = 100; +constexpr float MINECART_ACCELERATION = 1.02f; +constexpr float MINECART_ACCELERATION_STEP = 0.01f; +constexpr float MINECART_FADE_DISTANCE = 48; +constexpr float MINECART_LEAVE_MARGIN = -300; +constexpr float MINECART_DUST_SPEED = 0.8f; +constexpr float MINECART_DUST_INTERVAL = 2; +constexpr float MINECART_DUST_DRAG = 0.2f; +constexpr float MINECART_DUST_SPIN_RANGE = 10; +constexpr float MINECART_DUST_SPIN_MIN = 2; +constexpr int MINECART_DUST_FRAMES_MIN = 15; +constexpr float MINECART_DUST_SCALE_MIN = 0.3f; +constexpr float MINECART_DUST_SCALE_RANGE = 0.3f; +constexpr ColorMod MINECART_DUST_COLOR = tint_color_make(0.45f, 0.45f, 0.45f, 0.5f); +constexpr float MINECART_SPEED_MAX = 40; +constexpr float MINECART_LAUNCH_BONUS = 0.5f; +constexpr float MINECART_HALF_STEP = 0.5f; +constexpr float MINECART_STEP = 3; +constexpr float MINECART_DOOR_LOOKAHEAD = 10; +constexpr int MINECART_DIRECTIONS = 8; +constexpr int MINECART_SECTORS = 16; +constexpr int MINECART_HALF_TURN = 4; +constexpr int GRID_PATH_RAIL_CART = 900; +constexpr int GRID_PATH_BLOCK = 1000; + +constexpr int MINECART_BREAK_DELAY = 10; +constexpr int MINECART_PARTICLES_MIN = 6; +constexpr uint32_t MINECART_PARTICLES_SPREAD = 3; +constexpr float MINECART_PARTICLE_SPEED_MIN = 3; +constexpr float MINECART_PARTICLE_SPEED_RANGE = 4; +constexpr ColorMod ASHPIT_PARTICLE_COLOR = {{0.9f, 0.9f, 0.9f, 1}, {1, 1, 1, 0.7f}, {0, 0, 0}}; + +constexpr std::array MINECART_MOVE_ANIMS = { + "Move1", "Move2", "Move3", "Move4", "Move5", "Move6", "Move7", "Move8"}; + +// 005d4380 (case 139) The planks over the Mines' exit hole: they stay on their trapdoor's cell, underneath what +// stands there, and go once the trapdoor is gone. +static EffectUpdateEnd trapdoor_cover_update(Entity_Effect& cover) +{ + Room& room = *g_game->room; + + cover.renderDepthOffset = TRAPDOOR_COVER_DEPTH; + if (cover.state < 0) cover.Remove(); + else + { + cover.pos = room.GetGridPosition(cover.state); + cover.velocity = {}; + GridEntity* grid = room.GetGridEntity(cover.state); + if (!grid || grid->type != GRID_TRAPDOOR) cover.Remove(); + } + return EFFECT_UPDATE_FINISH; +} + +constexpr std::array MINES_BEHAVIOURS = {{ + {.variant = EFFECT_MINES_TRAPDOOR_COVER, .update = trapdoor_cover_update}, +}}; + +std::span mines_effect_behaviours() +{ + return MINES_BEHAVIOURS; +} + +// The players riding the entrance's minecart move with it, each at its own place in the cart. +static void minecart_riders_carry(Entity_NPC& minecart) +{ + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->minecart.get() != &minecart) continue; + + player->pos = vector_add(player->minecartOffset, minecart.pos); + player->velocity = minecart.velocity; + player->friction = minecart.friction; + } +} + +// 004cf030 Puts the minecart on a point of its rail, rolling with a velocity, and remembers the cell (none off the grid). +void Entity_NPC::SetMinecartPosVel(const Vector& position, const Vector& cartVelocity) +{ + pos = position; + i2 = g_game->room->GetGridIndex(position); + velocity = cartVelocity; + v1 = cartVelocity; + spawnGridIndex = i2; +} + +// 004cf120 Seats another rider in the minecart, the old one stepping out. +void Entity_NPC::MinecartUpdateChild(Entity* rider) +{ + if (child) child->minecart = nullptr; + child = rider; + if (rider) rider->minecart = this; +} + +// 006b7be0 Puts the entity in a new minecart at a point of a rail, rolling one way at full push. +Entity_NPC* Entity::GiveMinecart(const Vector& position, const Vector& cartVelocity) +{ + auto* cart = static_cast(g_game->Spawn({.position = position, + .type = ENTITY_MINECART, + .variant = MINECART_VARIANT_RIDDEN, + .seed = Random()})); + cart->v2.x = 1; + cart->SetMinecartPosVel(position, cartVelocity); + cart->Update(); + cart->targetPosition = cartVelocity; + minecart = cart; + cart->child = this; + return cart; +} + +// 004cee90 (NpcHelper::minecart_break) The minecart breaks apart with a crack and wood flying, gray in the Ashpit, +// and drops its rider. +void minecart_break(Entity_NPC& minecart) +{ + minecart.Remove(); + npc_sound_play(SOUND_WOOD_PLANK_BREAK, 1, MINECART_BREAK_DELAY, 1); + + float speed = random_unit() * MINECART_PARTICLE_SPEED_RANGE + MINECART_PARTICLE_SPEED_MIN; + int count = (int)(Random() % MINECART_PARTICLES_SPREAD) + MINECART_PARTICLES_MIN; + game_particles_spawn({.color = g_game->room->backdropType == BACKDROP_ASHPIT ? ASHPIT_PARTICLE_COLOR : COLOR_DEFAULT, + .position = minecart.pos, + .speed = speed, + .count = count, + .variant = EFFECT_WOOD_PARTICLE}); + minecart.child = nullptr; +} + +// 004ce6d0 Faces the minecart along its travel, one of eight ways, turning a step at a time once it has settled, and +// plays that way's animation: held on its first frame while it waits, else running. +void Entity_NPC::update_move_direction_anim() +{ + bool isMoving = velocity.x != 0 || velocity.y != 0; + if (isMoving && state != MINECART_STATE_WAITING) + { + float degrees = std::fmod(std::atan2(velocity.y, velocity.x) * -RADIANS_TO_DEGREES, 360.0f); + if (degrees < 0) degrees += 360; + + int facing = (int)(degrees * MINECART_SECTORS / 360 + 0.5f) % MINECART_DIRECTIONS; + if (facing != i1 && g_game->frameCount - spawnFrame < 2) i1 = facing; + else if (facing != i1) + { + int turn = (facing - i1 + MINECART_DIRECTIONS + MINECART_HALF_TURN) % MINECART_DIRECTIONS - MINECART_HALF_TURN; + i1 = (i1 + (turn >= 0 ? 1 : MINECART_DIRECTIONS - 1)) % MINECART_DIRECTIONS; + } + } + + std::string_view anim = MINECART_MOVE_ANIMS[i1]; + if (state == MINECART_STATE_WAITING) + { + if (!sprite.SetAnimation(anim) || !sprite.animState.animData) return; + sprite.animState.SetFrameFloat(0); + sprite.animState.isPlaying = false; + return; + } + + const AnimationData* current = sprite.animState.animData; + if (current && current->name == anim && (!current->isLooping || sprite.animState.isPlaying)) return; + if (!sprite.SetAnimation(anim)) return; + sprite.animState.Rewind(); + sprite.animState.isPlaying = true; +} + +// Whether a rail piece runs through the cell under a point, and which: none off the grid. +static int rail_type_at(Vector position, int& gridIndex) +{ + Room& room = *g_game->room; + + gridIndex = room.GetGridIndex(position); + if (gridIndex < 0 || gridIndex >= ROOM_GRID_CELLS) return -1; + uint8_t rail = room.railManager.rails[gridIndex]; + return rail == RAIL_NONE ? -1 : rail & RAIL_PIECE_MASK; +} + +// The entrance's launched minecart bursts open the door it is about to roll through. +static void minecart_door_ram(Entity_NPC& minecart, Vector heading) +{ + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(vector_add(minecart.pos, vector_scale(heading, MINECART_DOOR_LOOKAHEAD))); + GridEntity* grid = gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + if (!grid || grid->type != GRID_DOOR) return; + + auto* door = static_cast(grid); + door->Open(); + door->TryBlowOpen(true, nullptr); + door->TryBlowOpen(true, nullptr); +} + +// 004ce120 Rolls the minecart along its rail for a frame, or half of one between updates: friction slows it, its speed +// is capped, then it follows the track cell by cell in short steps, leaving the rail where it ends. Off the rails it +// rolls straight. A full step keeps the cell it is on and turns its velocity along the track. +void Entity_NPC::apply_velocity(char isInterpolated) +{ + Vector heading = vector_scale(velocity, friction); + if (!isInterpolated) + { + velocity = heading; + friction = baseFriction; + } + + bool isLaunched = variant == MINECART_VARIANT_ENTRANCE && state == MINECART_STATE_RIDING; + float speed = std::min(MINECART_SPEED_MAX, vector_length(heading) + (isLaunched ? MINECART_LAUNCH_BONUS : 0)); + if (isInterpolated) speed *= MINECART_HALF_STEP; + heading = vector_normalized(heading); + + int gridIndex = -1; + int railType = rail_type_at(pos, gridIndex); + if (railType < 0) + { + pos = vector_add(pos, vector_scale(heading, speed)); + return; + } + + RailManager& rails = g_game->room->railManager; + RailPoint rail = rails.get_closest_rail_point(pos, heading, gridIndex, railType); + pos = rail.point; + + float trackSpeed = vector_dot(rail.direction, heading) * speed; + for (float remaining = trackSpeed; remaining > 0;) + { + float step = std::min(remaining, MINECART_STEP); + remaining -= step; + pos = vector_add(pos, vector_scale(heading, step)); + + railType = rail_type_at(pos, gridIndex); + if (gridIndex < 1 || railType < 0) + { + if (!isInterpolated) i2 = -1; + pos = vector_add(pos, vector_scale(heading, remaining)); + return; + } + if (!isInterpolated) i2 = gridIndex; + + rail = rails.get_closest_rail_point(pos, heading, gridIndex, railType); + if (rail.isPastEnd) rail.direction = vector_scale(rail.direction, -1); + if (rail.direction.x == 0 && rail.direction.y == 0) + { + if (!isInterpolated) i2 = -1; + pos = vector_add(pos, vector_scale(heading, remaining)); + return; + } + + pos = rail.point; + heading = rail.direction; + if (isLaunched) minecart_door_ram(*this, heading); + } + if (isInterpolated) return; + + velocity = vector_scale(heading, trackSpeed); + v1 = velocity; +} + +// 004cde30 Moves the minecart for a frame: held in place while its rider is, else rolled along its rail and turned to +// face its travel. Its rider and, for the entrance's cart, its players ride along, and the entrance's cart marks its +// cell for the path finder. The entity update in between keeps its own motion. +void Entity_NPC::update_physics() +{ + holdCountdown = child ? child->holdCountdown : 0; + if (child) holdPosition = child->holdPosition; + if (holdCountdown <= 0) + { + apply_velocity(false); + update_move_direction_anim(); + } + + if (child) + { + child->pos = pos; + child->velocity = velocity; + child->friction = friction; + } + if (variant == MINECART_VARIANT_ENTRANCE) + { + minecart_riders_carry(*this); + + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(pos); + if (gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS) + { + int& path = room.gridPaths[gridIndex]; + if (path % GRID_PATH_BLOCK < GRID_PATH_RAIL_CART) path = path - path % GRID_PATH_BLOCK + GRID_PATH_RAIL_CART; + } + } + + Vector keptPos = pos; + Vector keptVelocity = velocity; + float keptFriction = friction; + Entity::Update(); + pos = keptPos; + velocity = keptVelocity; + friction = keptFriction; +} + +// 006d2b50 (the minecart's part) The minecart's half step between updates along its rail, its rider and players +// carried along. A minecart that skips interpolation does so once. +void minecart_interpolate(Entity_NPC& minecart) +{ + if (minecart.HasEntityFlags(FLAG_NO_INTERPOLATE)) + { + minecart.ClearEntityFlags(FLAG_NO_INTERPOLATE); + return; + } + + minecart.preInterpolatePos = minecart.pos; + if (minecart.holdCountdown < 1) + { + minecart.apply_velocity(true); + minecart.update_move_direction_anim(); + } + minecart.isInterpolating = true; + minecart.CollideWithGrid(GRID_COLLISION_SIMULATE); + if (minecart.child && minecart.child->index < minecart.index) minecart.child->pos = minecart.pos; + if (minecart.variant == MINECART_VARIANT_ENTRANCE) minecart_riders_carry(minecart); +} + +// Throws dust from under the entrance's minecart once it rolls fast. +static void minecart_dust_spawn(Entity_NPC& minecart) +{ + uint32_t seed = Random(); + Vector drift = vector_add(vector_scale(minecart.velocity, MINECART_DUST_DRAG), random_direction()); + auto* dust = static_cast(g_game->Spawn({.position = minecart.pos, + .velocity = drift, + .spawner = &minecart, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = seed})); + dust->rotation = random_unit() * MINECART_DUST_SPIN_RANGE + MINECART_DUST_SPIN_MIN; + dust->SetTimeout((int)(Random() % MINECART_DUST_FRAMES_MIN) + MINECART_DUST_FRAMES_MIN); + dust->SetColor(MINECART_DUST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + + float scale = random_unit() * MINECART_DUST_SCALE_RANGE + MINECART_DUST_SCALE_MIN; + dust->sprite.scale = vector_make(scale, scale); + if (g_game->roomTransition.mode != TRANSITION_NONE) dust->AddEntityFlags(FLAG_TRANSITION_UPDATE); + dust->Update(); +} + +// How far the minecart shows: whole in the room, fading out over the last stretch past its walls. +static float minecart_alpha_get(Entity_NPC& minecart) +{ + Room& room = *g_game->room; + if (room.IsPositionInRoom(minecart.pos, 0)) return 1; + + float outside = std::max({room.topLeftPos.x - minecart.pos.x, minecart.pos.x - room.bottomRightPos.x, + room.topLeftPos.y - minecart.pos.y, minecart.pos.y - room.bottomRightPos.y}); + return 1 - std::clamp(outside / MINECART_FADE_DISTANCE, 0.0f, 1.0f); +} + +// The minecart: the entrance's waits on its spot until the players set it off, then +// speeds up along its rail throwing dust. An enemy's rolls on, heavy and passable while it is ridden by a passable +// rider, and breaks once empty for a few frames. It fades out past the walls, and once it has settled a cart off the +// grid (the entrance's far off the room) is gone, its rider with it, which it tells. +static bool minecart_update(Entity_NPC& npc) +{ + if (npc.state == 0) + { + npc.state = npc.variant == MINECART_VARIANT_ENTRANCE ? MINECART_STATE_WAITING : MINECART_STATE_RIDING; + if (npc.variant == MINECART_VARIANT_ENTRANCE) npc.targetPosition = npc.pos; + npc.isInvincible = true; + npc.stateFrame = 0; + npc.AddEntityFlags(FLAG_NO_DAMAGE_BLINK | FLAG_NO_STATUS_EFFECTS); + npc.ClearEntityFlags(FLAG_APPEAR); + return false; + } + if (npc.state == MINECART_STATE_WAITING) + { + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + return false; + } + if (npc.state != MINECART_STATE_RIDING) + { + if (npc.state == MINECART_STATE_GONE) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + } + return false; + } + + Vector push = vector_scale(vector_normalized(npc.v1), MINECART_PUSH * npc.v2.x); + if (npc.variant == MINECART_VARIANT_ENTRANCE) + { + npc.mass = MINECART_VARIANT_ENTRANCE_MASS; + npc.entityCollisionClass = ENTCOLL_ALL; + if (npc.v2.x > MINECART_DUST_SPEED && npc.GetIntervalTicks(MINECART_DUST_INTERVAL, 0)) + minecart_dust_spawn(npc); + npc.isVisible = true; + npc.friction = MINECART_FRICTION; + npc.velocity = vector_add(npc.velocity, push); + npc.v2.x = npc.v2.x * MINECART_ACCELERATION + MINECART_ACCELERATION_STEP; + } + else + { + bool isPassable = npc.child && npc.child->entityCollisionClass != ENTCOLL_NONE; + npc.mass = npc.child ? MINECART_RIDDEN_MASS : MINECART_EMPTY_MASS; + npc.entityCollisionClass = isPassable ? ENTCOLL_NONE : ENTCOLL_ALL; + npc.isVisible = true; + if (npc.child) npc.velocity = vector_add(npc.velocity, push); + npc.friction = npc.child ? MINECART_RIDDEN_FRICTION : MINECART_FRICTION; + } + + npc.entityGridCollisionClass = GRIDCOLL_NONE; + bool isEmpty = !npc.child && npc.variant != MINECART_VARIANT_ENTRANCE; + npc.stateFrame = isEmpty ? npc.stateFrame + 1 : 0; + if (isEmpty && npc.stateFrame > MINECART_EMPTY_FRAMES) minecart_break(npc); + npc.sprite.color._tint[3] = minecart_alpha_get(npc); + + Game& game = *g_game; + bool isSettled = game.frameCount - npc.spawnFrame > MINECART_SETTLE_FRAMES || + (game.roomTransition.mode != TRANSITION_NONE && game.roomTransition.animation == TRANSITION_MINECART); + bool isHornfel = npc.child && npc.child->type == ENTITY_HORNFEL && npc.child->variant == 0; + if (!isSettled || isHornfel) return false; + + bool isGone = npc.variant == MINECART_VARIANT_ENTRANCE ? !game.room->IsPositionInRoom(npc.pos, MINECART_LEAVE_MARGIN) + : game.room->GetGridIndex(npc.pos) < 0; + if (!isGone) return false; + + npc.state = MINECART_STATE_GONE; + if (npc.child) npc.child->Remove(); + npc.Remove(); + return true; +} + +// 004ce8a0 (NpcAI::ENTITY_MINECART) The minecart never dies while it stays. +void npc_minecart_update(Entity_NPC& npc) +{ + if (!minecart_update(npc)) npc.isDead = false; +} diff --git a/src/mines.h b/src/mines.h new file mode 100644 index 0000000..b6c7ff7 --- /dev/null +++ b/src/mines.h @@ -0,0 +1,17 @@ +#pragma once + +#include "entity_effect.h" +#include "entity_npc.h" +#include + +// The minecart's variants: the one an enemy rides, and the entrance's that carries the players out of the room. +enum MinecartVariant : int +{ + MINECART_VARIANT_RIDDEN = 0, + MINECART_VARIANT_ENTRANCE = 10 +}; + +std::span mines_effect_behaviours(); +void npc_minecart_update(Entity_NPC& npc); +void minecart_break(Entity_NPC& minecart); +void minecart_interpolate(Entity_NPC& minecart); diff --git a/src/music_manager.h b/src/music_manager.h index fd39dfe..3a2b00a 100644 --- a/src/music_manager.h +++ b/src/music_manager.h @@ -72,7 +72,9 @@ enum MusicId : int MUSIC_TITLE_REPENTANCE = 63, MUSIC_REVERSE_GENESIS_START = 64, MUSIC_HUSH_TRANSITION = 65, + MUSIC_JINGLE_STRANGE_DOOR = 68, MUSIC_ECHOES_REVERSE = 69, + MUSIC_JINGLE_SECRET_ROOM_FIND = 85, MUSIC_TREASURE_JINGLE_FIRST = 87, MUSIC_GAME_START_JINGLE = 95, MUSIC_VOID_BOSS = 103, diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index 583cbb3..bc88f23 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -1,11 +1,12 @@ #include "npc_ai.h" #include "boss_ai.h" -#include "npc_caves.h" +#include "npc_depths.h" #include "game.h" #include "manager.h" #include "npc_fireplace.h" #include "room_special.h" #include "sfx_manager.h" +#include "mines.h" // The Beast's forms, by variant: its stalactites, rocks and soul, the four ultra horsemen and their summons, and // the background beasts. @@ -138,7 +139,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 859: return npc_host_update(npc); case 28: - return (void)NpcAI::ENTITY_CHUB(&npc); + return boss_chub_update(npc); case 29: case 34: case 54: @@ -169,7 +170,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 40: case 218: case 862: - return (void)NpcAI::ENTITY_GUTS(&npc); + return npc_guts_update(npc); case 41: case 254: case 283: @@ -198,12 +199,12 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 53: return (void)NpcAI::ENTITY_DOPLE(&npc); case 56: - return (void)NpcAI::ENTITY_LUMP(&npc); + return npc_lump_update(npc); case 57: case 223: - return (void)NpcAI::ENTITY_MEMBRAIN(&npc); + return npc_membrain_update(npc); case 58: - return (void)NpcAI::ENTITY_PARA_BITE(&npc); + return npc_para_bite_update(npc); case 59: return (void)NpcAI::ENTITY_FRED(&npc); case 60: @@ -231,11 +232,11 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 74: case 75: case 76: - return (void)NpcAI::ENTITY_BLASTOCYST_BIG(&npc); + return boss_blastocyst_update(npc); case 77: return npc_embryo_update(npc); case 78: - return (void)NpcAI::ENTITY_MOMS_HEART(&npc); + return boss_moms_heart_update(npc); case 79: return boss_gemini_update(npc); case 81: @@ -269,7 +270,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 96: return npc_eternal_fly_update(npc); case 97: - return (void)NpcAI::ENTITY_MASK_OF_INFAMY(&npc); + return boss_mask_of_infamy_update(npc); case 98: if (npc.state == NPC_STATE_INIT) npc.state = NPC_STATE_MOVE; return; @@ -292,15 +293,15 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 207: return npc_baby_long_legs_update(npc); case 209: - return (void)NpcAI::ENTITY_FAT_SACK(&npc); + return npc_fat_sack_update(npc); case 212: case 286: - return (void)NpcAI::ENTITY_DEATHS_HEAD(&npc); + return npc_deaths_head_update(npc); case 213: case 287: return (void)NpcAI::ENTITY_MOMS_HAND(&npc); case 216: - return (void)NpcAI::ENTITY_SWINGER(&npc); + return npc_swinger_update(npc); case 217: case 870: return npc_dip_update(npc); @@ -327,7 +328,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) return (void)NpcAI::ENTITY_HOMUNCULUS(&npc); case 231: case 964: - return (void)NpcAI::ENTITY_NERVE_ENDING(&npc); + return npc_nerve_ending_update(npc); case 232: case 234: return npc_one_tooth_update(npc); @@ -356,20 +357,20 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 263: return boss_gate_update(npc); case 264: - return (void)NpcAI::ENTITY_MEGA_FATTY(&npc); + return boss_mega_fatty_update(npc); case 265: - return (void)NpcAI::ENTITY_CAGE(&npc); + return boss_cage_update(npc); case 266: - return (void)NpcAI::ENTITY_MAMA_GURDY(&npc); + return boss_mama_gurdy_update(npc); case 267: return (void)NpcAI::ENTITY_DARK_ONE(&npc); case 268: - return (void)NpcAI::ENTITY_ADVERSARY(&npc); + return boss_adversary_update(npc); case 269: case 401: return boss_polycephalus_update(npc); case 270: - return (void)NpcAI::ENTITY_MR_FRED(&npc); + return boss_mr_fred_update(npc); case 271: case 272: return (void)NpcAI::ENTITY_URIEL(&npc); @@ -408,7 +409,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 300: return npc_mushroom_update(npc); case 303: - return (void)NpcAI::ENTITY_BLISTER(&npc); + return npc_blister_update(npc); case 306: return npc_portal_update(npc); case 307: @@ -458,11 +459,11 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 810: return (void)NpcAI::ENTITY_SMALL_LEECH(&npc); case 811: - return (void)NpcAI::ENTITY_DEEP_GAPER(&npc); + return npc_deep_gaper_update(npc); case 812: return npc_sub_horf_update(npc); case 813: - return (void)NpcAI::ENTITY_BLURB(&npc); + return npc_blurb_update(npc); case 814: return (void)NpcAI::ENTITY_STRIDER(&npc); case 815: @@ -560,7 +561,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 880: return (void)NpcAI::ENTITY_FLESH_MAIDEN(&npc); case 881: - return (void)NpcAI::ENTITY_NEEDLE(&npc); + return npc_needle_update(npc); case 882: return (void)NpcAI::ENTITY_DUST(&npc); case 883: @@ -647,7 +648,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 960: return (void)NpcAI::ENTITY_GENERIC_PROP(&npc); case 965: - return (void)NpcAI::ENTITY_MINECART(&npc); + return npc_minecart_update(npc); case 966: return (void)NpcAI::ENTITY_SIREN_HELPER(&npc); case 967: diff --git a/src/npc_ai.h b/src/npc_ai.h index 732ea20..dbca27f 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -4,6 +4,7 @@ #include "log.h" #include "lua_engine.h" #include "seeds.h" +#include "sfx_manager.h" #include #include @@ -13,16 +14,6 @@ constexpr float RANDOM_HALF_TURN = 3.14f; constexpr float DEGREES_TO_RADIANS = 0.017453292f; constexpr float RADIANS_TO_DEGREES = 57.295776f; -// The sound ids the common enemies play (Lua's SoundEffect). -enum NpcSound : int -{ - SOUND_BOSS1_EXPLOSIONS = 28, - SOUND_MEAT_IMPACTS = 77, - SOUND_ZOMBIE_WALKER_KID = 165, - SOUND_SUMMON_POOF = 286, - SOUND_SUMMON_WAVE = 872 -}; - inline Vector vector_add(Vector a, Vector b) { return vector_make(a.x + b.x, a.y + b.y); diff --git a/src/npc_blister.cpp b/src/npc_blister.cpp new file mode 100644 index 0000000..4ce9f98 --- /dev/null +++ b/src/npc_blister.cpp @@ -0,0 +1,133 @@ +#include "npc_depths.h" +#include "game.h" +#include "sfx_manager.h" + +// The Blister hops toward its prey (or the ball it spat) along the axis it is farther along, up to 40 a hop, every 0 +// to 29 frames. One time in ten, with no ball out, it spits a rolling ball at 4 instead (Little Horn's dark ball). +// Dying on open ground (not to a champion's regrowth), it leaves a Sack at half health. +constexpr uint32_t BLISTER_WAIT_RANGE = 30; +constexpr float BLISTER_HOP_REACH = 40; +constexpr float BLISTER_HOP_SHARE = 0.2f; +constexpr uint32_t BLISTER_SPIT_ODDS = 10; +constexpr float BLISTER_RANGE = 1000; +constexpr int BLISTER_RANGE_FRAMES = 7; +constexpr float BLISTER_FRICTION = 0.6f; +constexpr float BLISTER_HOP_FRICTION = 0.9f; +constexpr float BLISTER_SPIT_FRICTION = 0.7f; +constexpr int BLISTER_BALL_VARIANT = 1; +constexpr float BLISTER_BALL_SPEED = 4; +constexpr float BLISTER_BALL_DROP = 1; +constexpr float BLISTER_SPIT_PITCH = 0.9f; +constexpr float BLISTER_SPIT_PITCH_RANGE = 0.2f; +constexpr int BLISTER_SACK_VARIANT = 2; +constexpr float BLISTER_SACK_HEALTH = 0.5f; + +// Back to waiting a random while. +static void blister_rest(Entity_NPC& npc) +{ + npc.state = NPC_STATE_MOVE; + npc.stateFrame = (int)(Random() % BLISTER_WAIT_RANGE); +} + +// Starting the spit at its prey, or where its controller aims. +static void blister_spit_start(Entity_NPC& npc) +{ + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Attack"); + if (!vector_is_zero(npc.GetControllerMovementInput(0))) npc.targetPosition = npc.GetControllerMovementInput(0); +} + +// Waiting, then hopping (its target position holds the hop's push) or spitting. +static void blister_wait(Entity_NPC& npc) +{ + npc.sprite.Play("Idle"); + npc.stateFrame -= npc_ticks_get(npc); + if (npc.stateFrame < 0 || npc.controllerID != -1) + { + Entity* goal = npc.child ? npc.child.get() : npc.GetPlayerTarget(); + Vector away = vector_sub(npc.pos, goal->pos); + Vector hop{}; + bool isSpitting = false; + if (npc.controllerID == -1) + { + if (std::abs(away.x) <= std::abs(away.y)) + hop.y = std::min(std::max(away.y, -BLISTER_HOP_REACH), BLISTER_HOP_REACH); + else hop.x = std::min(std::max(away.x, -BLISTER_HOP_REACH), BLISTER_HOP_REACH); + isSpitting = Random() % BLISTER_SPIT_ODDS == 0 && !npc.child; + } + else + { + Vector input = npc.GetControllerInput(0); + hop = vector_make(-input.x * BLISTER_HOP_REACH, -input.y * BLISTER_HOP_REACH); + isSpitting = (npc.IsTargetInAttackRange(BLISTER_RANGE, BLISTER_RANGE_FRAMES, false) || + npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT)) && + !npc.child; + } + npc.targetPosition = vector_make(-hop.x * BLISTER_HOP_SHARE, -hop.y * BLISTER_HOP_SHARE); + + if (isSpitting) blister_spit_start(npc); + else if (!vector_is_zero(hop)) + { + npc.state = NPC_STATE_JUMP; + npc.sprite.Play("Hop"); + } + } + npc.friction *= BLISTER_FRICTION; +} + +// Hopping: the push fading over the hop, a thud on landing. +static void blister_hop(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + int length = anim.animData ? anim.animData->length : 0; + float fade = 1 - (float)npc.sprite.GetFrame() / (float)length; + npc.velocity = vector_make(fade * npc.targetPosition.x, fade * npc.targetPosition.y); + if (anim.animData && anim.IsEventTriggered("Land")) npc.PlaySound(SOUND_MEAT_IMPACTS, 1, 2, false, 1); + if (!anim.animData || !anim.isPlaying) blister_rest(npc); + npc.friction *= BLISTER_HOP_FRICTION; +} + +// Spitting its ball on the "Shoot" event, which it then hops after. +static void blister_spit(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + if (anim.animData && anim.IsEventTriggered("Shoot")) + { + uint32_t seed = Random(); + Entity* ball = g_game->Spawn({.position = vector_make(npc.pos.x + 0, npc.pos.y + BLISTER_BALL_DROP), + .velocity = vector_resized(npc.targetPosition, BLISTER_BALL_SPEED), + .spawner = &npc, + .type = ENTITY_LITTLE_HORN, + .variant = BLISTER_BALL_VARIANT, + .seed = seed}); + ball->ClearEntityFlags(FLAG_APPEAR); + ball->spawnerEntity = &npc; + npc.child = ball; + npc.PlaySound(SOUND_LITTLE_HORN_COUGH, 1, 2, false, + random_unit() * BLISTER_SPIT_PITCH_RANGE + BLISTER_SPIT_PITCH); + } + if (!anim.animData || !anim.isPlaying) blister_rest(npc); + npc.friction *= BLISTER_SPIT_FRICTION; +} + +// 005430d0 The Blister's AI: it hops toward its prey and spits a rolling ball now and then, and leaves a Sack as it +// dies. +void npc_blister_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return blister_rest(npc); + + if (npc.state == NPC_STATE_MOVE) blister_wait(npc); + else if (npc.state == NPC_STATE_JUMP) blister_hop(npc); + else if (npc.state == NPC_STATE_ATTACK) blister_spit(npc); + + if (!npc.isDead || room_grid_collision_at(npc.pos) != 0 || npc.championRegenCount != 0) return; + Entity* spawned = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_BOIL, + .variant = BLISTER_SACK_VARIANT, + .seed = npc.dropRNG.Next()}); + auto* sack = static_cast(spawned); + sack->ClearEntityFlags(FLAG_APPEAR); + sack->health = sack->maxHitPoints * BLISTER_SACK_HEALTH; + if (npc.controllerID != -1) npc.TransferControl(sack); +} diff --git a/src/npc_blurb.cpp b/src/npc_blurb.cpp new file mode 100644 index 0000000..c100d7f --- /dev/null +++ b/src/npc_blurb.cpp @@ -0,0 +1,150 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "level.h" +#include "sfx_manager.h" + +// The Blurb walks its grid path at 0.3 with its head full, groaning one time in 3 while it sees its prey. Within 100 +// of it (or hurt to half health) it bursts after 4 frames: 7 to 9 lobbed shots onto its prey (no farther than 100), +// water ones in the Downpour and Dross. Emptied, it walks on at 0.72. +constexpr float BLURB_FULL_SPEED = 0.3f; +constexpr float BLURB_ATTACK_SPEED = 0.1f; +constexpr float BLURB_EMPTY_SPEED = 0.72f; +constexpr int BLURB_PATH_MARKER = 900; +constexpr float BLURB_WALK_THRESHOLD = 0.1f; +constexpr float BLURB_FEAR_FRICTION = 0.8f; +constexpr float BLURB_HURT_SHARE = 0.5f; +constexpr float BLURB_REACH = 100; +constexpr float BLURB_RANGE = 1000; +constexpr int BLURB_RANGE_FRAMES = 7; +constexpr float BLURB_DEADZONE = 0.1f; +constexpr int BLURB_BURST_DELAY = 4; +constexpr uint32_t BLURB_GROAN_ODDS = 3; +constexpr float BLURB_FULL_GROAN_VOLUME = 0.8f; +constexpr int BLURB_FULL_GROAN_DELAY = 120; +constexpr int BLURB_EMPTY_GROAN_DELAY = 40; +constexpr float BLURB_CONTROLLED_REACH = 120; +constexpr uint32_t BLURB_SHOT_RANGE = 3; +constexpr int BLURB_SHOTS = 7; +constexpr float BLURB_SHOT_SPEED = 3; +constexpr int BLURB_DOWNPOUR_SHOT = 4; +constexpr int BLURB_DROSS_SHOT = 3; +constexpr float BLURB_POOF_DROP = 1; +constexpr float BLURB_POOF_HEIGHT = -20; + +// Dying (unless blown apart past 25 overkill), it rises again as a Gusher one time in 2, a Pacer one time in 3 of +// those. +constexpr float BLURB_GIBBED_HEALTH = -25; +constexpr uint32_t BLURB_PACER_ODDS = 3; + +// The burst: a spread of lobbed shots onto its prey (or where its controller aims), and a poof at its mouth. +static void blurb_burst(Entity_NPC& npc) +{ + npc_sound_play(SOUND_MEATHEADSHOOT, 1, 2, champion_pitch_get(npc)); + ProjectileParams params; + int poof = EFFECT_BULLET_POOF; + uint32_t stage = Level::GetStageID(); + if (stage == STAGE_ID_DOWNPOUR || stage == STAGE_ID_DROSS) + { + params.variant = stage == STAGE_ID_DOWNPOUR ? BLURB_DOWNPOUR_SHOT : BLURB_DROSS_SHOT; + poof = EFFECT_TEAR_POOF_A; + } + + Vector target = npc.GetPlayerTarget()->pos; + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) + target = vector_make(npc.controllerMovement.x * BLURB_CONTROLLED_REACH + npc.pos.x, + npc.controllerMovement.y * BLURB_CONTROLLED_REACH + npc.pos.y); + if (vector_length(vector_sub(npc.pos, target)) > BLURB_REACH) + target = vector_add(vector_scale(vector_normalized(vector_sub(target, npc.pos)), BLURB_REACH), npc.pos); + npc.FireBossProjectiles((int)(Random() % BLURB_SHOT_RANGE) + BLURB_SHOTS, target, BLURB_SHOT_SPEED, params); + + Entity* mouth = g_game->Spawn({.position = vector_make(npc.pos.x + 0, npc.pos.y + BLURB_POOF_DROP), + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = poof, + .seed = Random()}); + mouth->posOffset = vector_make(0, BLURB_POOF_HEIGHT); + mouth->Update(); +} + +// Full: closing in, and bursting once near (or hurt). +static void blurb_full(Entity_NPC& npc, bool isHostile) +{ + npc.sprite.PlayOverlay("HeadFull"); + npc.aiFloat = BLURB_FULL_SPEED; + bool isAttacking = true; + if (npc.controllerID != -1) isAttacking = npc.IsTargetInAttackRange(BLURB_RANGE, BLURB_RANGE_FRAMES, false); + else if (npc.health / npc.maxHitPoints > BLURB_HURT_SHARE) + { + bool isNear = vector_length(vector_sub(npc.pos, npc.CalcTargetPosition(0))) < BLURB_REACH; + if (isNear && !isHostile) return; + isAttacking = isNear; + } + + if (isAttacking) + { + npc.stateFrame = BLURB_BURST_DELAY; + npc.state = NPC_STATE_ATTACK; + npc.controllerMovement = npc.controllerID == -1 ? Vector{} : npc.GetControllerMovementInput(BLURB_DEADZONE); + } + if (isHostile && npc.pathfinder.hasDirectPath && Random() % BLURB_GROAN_ODDS == 0) + npc.PlaySound(SOUND_ANGRY_GURGLE, BLURB_FULL_GROAN_VOLUME, BLURB_FULL_GROAN_DELAY, false, 1); +} + +// 0055a010 The Blurb's AI: it walks after its prey and bursts into a spread of shots once near, then walks on +// emptied. It may rise again as a Gusher. +void npc_blurb_update(Entity_NPC& npc) +{ + bool isBursting = false; + bool isHostile = npc.IsHostileTo(npc.GetPlayerTarget()); + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.sprite.PlayOverlay("HeadAppear"); + if (npc.sprite.SetAnimation("WalkVert", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } + } + else if (npc.state == NPC_STATE_MOVE || npc.state == NPC_STATE_ATTACK || npc.state == NPC_STATE_SPECIAL) + { + npc.AnimWalkFrame("WalkHori", "WalkVert", BLURB_WALK_THRESHOLD); + if (npc.state == NPC_STATE_MOVE) blurb_full(npc, isHostile); + else if (npc.state == NPC_STATE_ATTACK) + { + npc.sprite.PlayOverlay("HeadAttack"); + npc.aiFloat = BLURB_ATTACK_SPEED; + if (npc.stateFrame > 0) isBursting = --npc.stateFrame < 1; + AnimationState& overlay = npc.sprite.overlayAnimState; + if (!overlay.animData || !overlay.isPlaying) npc.state = NPC_STATE_SPECIAL; + } + else + { + npc.sprite.PlayOverlay("Head"); + npc.aiFloat = BLURB_EMPTY_SPEED; + if (isHostile && npc.pathfinder.hasDirectPath && Random() % BLURB_GROAN_ODDS == 0) + npc.PlaySound(SOUND_ZOMBIE_WALKER_KID, 1, BLURB_EMPTY_GROAN_DELAY, false, 1); + } + + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), npc.aiFloat, BLURB_PATH_MARKER, DIRECT_PATH_FAR); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= BLURB_FEAR_FRICTION; + } + } + + if (npc.isDead) + { + if (npc.state == NPC_STATE_MOVE || (npc.state == NPC_STATE_ATTACK && npc.stateFrame > 0)) isBursting = true; + if (npc.health > BLURB_GIBBED_HEALTH && (Random() & 1) == 0) + { + npc.Morph(ENTITY_GUSHER, Random() % BLURB_PACER_ODDS == 0 ? 1 : 0, 0, -1); + npc.health = npc.maxHitPoints; + npc.isDead = false; + } + } + if (isBursting) blurb_burst(npc); +} diff --git a/src/npc_collision.cpp b/src/npc_collision.cpp index e34550e..95aa02f 100644 --- a/src/npc_collision.cpp +++ b/src/npc_collision.cpp @@ -21,13 +21,10 @@ constexpr int ENTITY_BEGOTTEN = 251; constexpr int ENTITY_THE_HAUNT = 260; constexpr int ENTITY_DINGLE = 261; constexpr int ENTITY_MEGA_MAW = 262; -constexpr int ENTITY_CAGE = 265; constexpr int ENTITY_SWARM = 281; constexpr int ENTITY_ULTRA_COIN = 293; constexpr int ENTITY_FISTULOID = 308; constexpr int ENTITY_BROWNIE = 402; -constexpr int ENTITY_SISTERS_VIS = 410; -constexpr int ENTITY_MATRIARCH = 413; constexpr int ENTITY_BOMB_GRIMACE = 809; constexpr int ENTITY_FISSURE = 815; constexpr int ENTITY_BLASTER = 821; diff --git a/src/npc_deaths_head.cpp b/src/npc_deaths_head.cpp new file mode 100644 index 0000000..2fa2482 --- /dev/null +++ b/src/npc_deaths_head.cpp @@ -0,0 +1,315 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "camera.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "sfx_manager.h" +#include + +// The Death's Heads: the plain one, the Dank one (which can be hurt and outlives the room), the Cursed one with its +// fear aura, the Brimstone one and the Red Skull (which can be hurt too). +constexpr int DANK_DEATHS_HEAD = 1; +constexpr int CURSED_DEATHS_HEAD = 2; +constexpr int BRIMSTONE_DEATHS_HEAD = 3; +constexpr int RED_SKULL = 4; +constexpr ColorMod DEATHS_HEAD_SPLAT = {{0.15f, 0, 0, 1}, {0, 0, 0, 0}, {0.1f, 0.1f, 0.1f}}; + +// They bounce about the room's walls, pushed 0.45 a frame along their diagonal (the Red Skull 0.36), a controller +// steering them up to half as much again. +constexpr float DEATHS_HEAD_FRICTION = 0.9f; +constexpr float DEATHS_HEAD_ATTACK_FRICTION = 0.6f; +constexpr float DEATHS_HEAD_PUSH = 0.45f; +constexpr float RED_SKULL_PUSH = 0.35999998f; +constexpr float DEATHS_HEAD_STEER = 0.5f; +constexpr float DEATHS_HEAD_DEADZONE = 0.1f; + +// The Cursed one's halo, 15 up, frightens the players within 70 for as long as they stay. +constexpr int CURSED_HALO_SUBTYPE = 3; +constexpr float CURSED_HALO_HEIGHT = -15; +constexpr float CURSED_FEAR_RANGE_SQUARED = 4900; +constexpr int CURSED_FEAR_DURATION = -45; + +// The Brimstone one fires a beam at a player whose next 5 frames come within 24 of its row or column, warning with a +// red line for 23 frames, then rests 60 frames. +constexpr float BRIMSTONE_LEAD_FRAMES = 5; +constexpr float BRIMSTONE_LANE = 24; +constexpr float BRIMSTONE_SKULL_WARNING_HEIGHT = -20; +constexpr float BRIMSTONE_SKULL_WARNING_SCALE = 4; +constexpr int BRIMSTONE_SKULL_WARNING_FRAMES = 23; +constexpr ColorMod BRIMSTONE_SKULL_WARNING_COLOR = tint_color_make(0.6f, 0.05f, 0, 0.6f); +constexpr int BRIMSTONE_SKULL_LASER_VARIANT = 1; +constexpr int BRIMSTONE_LASER_FRAMES = 16; +constexpr float BRIMSTONE_LASER_BASE_ANGLE = 180; +constexpr float BRIMSTONE_LASER_ANGLE_STEP = 90; +constexpr float BRIMSTONE_LASER_UP_DEPTH = -10; +constexpr float BRIMSTONE_LASER_DEPTH = 3000; +constexpr int BRIMSTONE_REST_FRAMES = 60; +constexpr std::array BRIMSTONE_ATTACKS = {"AttackLeft", "AttackUp", "AttackRight", "AttackDown"}; + +// The Red Skull checks every 6 frames whether its prey's lead (a tenth of its distance in frames) comes within 100, +// then bursts into a ring of 5 fire jets 40 out, and 5 frames later 10 more 80 out, resting 30 frames. +constexpr int RED_SKULL_CHECK_FRAMES = 6; +constexpr float RED_SKULL_LEAD_SHARE = 0.1f; +constexpr float RED_SKULL_RANGE_SQUARED = 10000; +constexpr float RED_SKULL_CONTROLLED_RANGE = 1000; +constexpr int RED_SKULL_RANGE_FRAMES = 7; +constexpr int RED_SKULL_FIRST_RING = -1; +constexpr int RED_SKULL_SECOND_RING = -6; +constexpr int RED_SKULL_FIRST_JETS = 5; +constexpr int RED_SKULL_SECOND_JETS = 10; +constexpr float RED_SKULL_FIRST_RADIUS = 40; +constexpr float RED_SKULL_SECOND_RADIUS = 80; +constexpr float RED_SKULL_JET_MARGIN = 10; +constexpr int RED_SKULL_REST_FRAMES = 30; + +// They all crumble with the room's last enemy (its plates done), but the Dank one. The Flesh Death's Head bursts into +// a ring of 6 shots at 7 as it dies, and a controlled one bursts at will. +constexpr int DEATHS_HEAD_PLATE_DELAY = 9; +constexpr int DEATHS_HEAD_DEATH_SOUND_DELAY = 60; +constexpr float FLESH_DEATHS_HEAD_RING_SPEED = 7; +constexpr float FLESH_DEATHS_HEAD_RING_SHOTS = 6; +constexpr float FLESH_DEATHS_HEAD_RING_SPREAD = 360; +constexpr float FLESH_DEATHS_HEAD_RING_OFFSET = -180; + +// Setting out in a random direction, invulnerable and unaffected (but for the Dank one and the Red Skull). The Cursed +// one lights its halo. +static void deaths_head_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_MOVE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + bool isDeathsHead = npc.type == ENTITY_DEATHS_HEAD; + if (isDeathsHead && npc.variant != DANK_DEATHS_HEAD && npc.variant != RED_SKULL) + { + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_HIDE_HP_BAR); + npc.isInvincible = true; + } + npc.velocity = random_direction(); + if (npc.type != ENTITY_FLESH_DEATHS_HEAD) npc.splatColor = DEATHS_HEAD_SPLAT; + if (!isDeathsHead || npc.variant != CURSED_DEATHS_HEAD) return; + + auto* halo = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = CURSED_HALO_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_HALO, + .seed = Random()})); + halo->sprite.offset = vector_make(0, CURSED_HALO_HEIGHT); + halo->FollowParent(&npc); + npc.child = halo; +} + +// The bounce: pushed along its diagonal, or wandering while confused. +static void deaths_head_drift(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_CONFUSION) && npc.controllerID == -1) + { + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return; + } + + float push = npc.type == ENTITY_DEATHS_HEAD && npc.variant == RED_SKULL ? RED_SKULL_PUSH : DEATHS_HEAD_PUSH; + Vector along = vector_make(npc.velocity.x < 0 ? -push : push, npc.velocity.y < 0 ? -push : push); + if (npc.controllerID != -1) + { + Vector input = npc.GetControllerInput(0); + float steer = vector_length(along) * DEATHS_HEAD_STEER; + along = vector_make(steer * input.x + along.x, along.y + steer * input.y); + } + npc_push(npc, along); +} + +// The Cursed one frightens every player near it. +static void cursed_deaths_head_scare(Entity_NPC& npc) +{ + for (int i = 0; i < (int)g_game->playerManager.playerList.size(); i++) + { + Entity_Player* player = g_game->GetPlayer(i); + bool isNear = player->entityCollisionClass != ENTCOLL_NONE && + vector_length_squared(vector_sub(npc.pos, player->pos)) < CURSED_FEAR_RANGE_SQUARED; + if (isNear) player->AddFear(EntityRef(&npc), CURSED_FEAR_DURATION, false); + } +} + +// Starting an attack: its animation from the start. +static void deaths_head_attack_start(Entity_NPC& npc, std::string_view animation) +{ + npc.state = NPC_STATE_ATTACK; + npc_anim_restart(npc.sprite, animation); +} + +// The Brimstone one turns toward a player coming onto its row or column, with a warning line that way. +static void brimstone_deaths_head_aim(Entity_NPC& npc) +{ + if (npc.controllerID != -1) + { + if (npc.projectileCooldown >= 1) return; + Vector input = npc.GetControllerMovementInput(DEATHS_HEAD_DEADZONE); + if (vector_is_zero(input)) return; + npc.state = NPC_STATE_ATTACK; + npc.i1 = vector_to_direction(input); + npc.v1 = npc.velocity; + return npc_anim_restart(npc.sprite, BRIMSTONE_ATTACKS[npc.i1]); + } + if (!g_game->room->camera->IsPosVisible(npc.pos)) return; + + for (int i = 0; i < (int)g_game->playerManager.playerList.size(); i++) + { + Entity_Player* player = g_game->GetPlayer(i); + if (player->entityCollisionClass == ENTCOLL_NONE) continue; + Vector lead = vector_add(vector_scale(player->velocity, BRIMSTONE_LEAD_FRAMES), player->pos); + lead = vector_sub(lead, npc.pos); + if (std::abs(lead.x) > BRIMSTONE_LANE && std::abs(lead.y) > BRIMSTONE_LANE) continue; + + int direction = vector_to_direction(lead); + if (direction == DIRECTION_NONE) return; + npc.i1 = direction; + npc.v1 = npc.velocity; + deaths_head_attack_start(npc, BRIMSTONE_ATTACKS[direction]); + + Vector at = vector_make(npc.pos.x + 0, npc.pos.y + BRIMSTONE_SKULL_WARNING_HEIGHT); + auto* warning = static_cast( + g_game->Spawn({.position = at, .type = ENTITY_EFFECT, .variant = EFFECT_GENERIC_TRACER, .seed = Random()})); + warning->FollowParent(&npc); + warning->sprite.color = BRIMSTONE_SKULL_WARNING_COLOR; + warning->sprite.scale = vector_make(BRIMSTONE_SKULL_WARNING_SCALE, BRIMSTONE_SKULL_WARNING_SCALE); + warning->targetPosition = vector_from_direction(direction); + warning->timeout = BRIMSTONE_SKULL_WARNING_FRAMES; + warning->lifespan = BRIMSTONE_SKULL_WARNING_FRAMES; + warning->Update(); + return; + } +} + +// The Red Skull bursts when its prey's lead comes near (or its controller says). +static void red_skull_aim(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_SHRINK) || npc.projectileCooldown >= 1) return; + if (npc.controllerID == -1) + { + if (!npc.IsFrame(RED_SKULL_CHECK_FRAMES, 0)) return; + Entity* target = npc.GetPlayerTarget(); + float lead = vector_length(vector_sub(npc.pos, target->pos)) * RED_SKULL_LEAD_SHARE; + Vector gap = vector_sub(npc.pos, vector_add(vector_scale(target->velocity, lead), target->pos)); + if (vector_length_squared(gap) >= RED_SKULL_RANGE_SQUARED) return; + } + else if (!npc.IsTargetInAttackRange(RED_SKULL_CONTROLLED_RANGE, RED_SKULL_RANGE_FRAMES, false) && + !npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT)) + return; + + deaths_head_attack_start(npc, "Attack"); + npc.projectileCooldown = 0; +} + +// The Brimstone one's beam on its "Shoot" event, the way it faces (behind it when it faces up). +static bool brimstone_deaths_head_fire(Entity_NPC& npc) +{ + if (!npc.sprite.animState.animData) return true; + if (npc.sprite.animState.IsEventTriggered("Shoot")) + { + Vector offset = npc.GetNullOffset("LaserPos"); + Entity_Laser* laser = Entity_Laser::ShootAngle( + {.position = vector_make(npc.pos.x + offset.x, npc.pos.y), + .posOffset = vector_make(0, offset.y), + .source = &npc, + .angleDegrees = (float)npc.i1 * BRIMSTONE_LASER_ANGLE_STEP + BRIMSTONE_LASER_BASE_ANGLE, + .timeout = BRIMSTONE_LASER_FRAMES, + .variant = BRIMSTONE_SKULL_LASER_VARIANT}); + laser->renderDepthOffset = npc.i1 == DIRECTION_UP ? BRIMSTONE_LASER_UP_DEPTH : BRIMSTONE_LASER_DEPTH; + } + return !npc.sprite.animState.animData || !npc.sprite.animState.isPlaying; +} + +// A ring of fire jets around the Red Skull, those inside the room. +static void red_skull_ring(Entity_NPC& npc, int count, float radius) +{ + for (int i = 0; i < count; i++) + { + float angle = (float)i * DEGREES_PER_TURN / (float)count * DEGREES_TO_RADIANS; + Vector at = vector_make(std::cos(angle) * radius + npc.pos.x, std::sin(angle) * radius + npc.pos.y); + if (!g_game->room->IsPositionInRoom(at, RED_SKULL_JET_MARGIN)) continue; + Entity* jet = g_game->Spawn( + {.position = at, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_FIRE_JET, .seed = Random()}); + jet->Update(); + } +} + +// The Red Skull's burst on its "Shoot" event, its rings counted down tick by tick. +static bool red_skull_fire(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_MONSTER_GRUNT_1, 1, 2, false, 1); + npc.projectileCooldown = RED_SKULL_FIRST_RING; + } + bool isBursting = npc.projectileCooldown >= RED_SKULL_SECOND_RING && npc.projectileCooldown <= RED_SKULL_FIRST_RING; + for (int tick = npc_ticks_get(npc); isBursting && tick > 0; tick--) + { + if (npc.projectileCooldown == RED_SKULL_FIRST_RING) + red_skull_ring(npc, RED_SKULL_FIRST_JETS, RED_SKULL_FIRST_RADIUS); + else if (npc.projectileCooldown == RED_SKULL_SECOND_RING) + red_skull_ring(npc, RED_SKULL_SECOND_JETS, RED_SKULL_SECOND_RADIUS); + npc.projectileCooldown--; + } + return !npc.sprite.animState.animData || !npc.sprite.animState.isPlaying; +} + +// The room's last enemy gone (its plates done), it crumbles. A Flesh Death's Head bursts as it dies. +static void deaths_head_end_check(Entity_NPC& npc) +{ + Room& room = *g_game->room; + bool isRoomDone = npc.GetAliveEnemyCount() < 1 && + (!room.isTriggerPressurePlates || room.roomClearDelay < DEATHS_HEAD_PLATE_DELAY); + bool isOutliving = npc.type == ENTITY_DEATHS_HEAD && npc.variant == DANK_DEATHS_HEAD; + if (isRoomDone && npc.state != NPC_STATE_DEATH && !isOutliving) + { + npc.state = NPC_STATE_DEATH; + npc.stateFrame = 0; + npc.PlaySound(SOUND_DEVILROOM_DEAL, 1, DEATHS_HEAD_DEATH_SOUND_DELAY, false, 1); + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (npc.type != ENTITY_FLESH_DEATHS_HEAD) return; + + if (npc.controllerID != -1 && npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT)) npc.Kill(EntityRef()); + if ((!npc.isDead && npc.state != NPC_STATE_DEATH) || npc.HasEntityFlags(FLAG_SHRINK)) return; + ProjectileParams params; + params.circleAngle = random_unit() * FLESH_DEATHS_HEAD_RING_SPREAD + FLESH_DEATHS_HEAD_RING_OFFSET; + Vector ring = vector_make(FLESH_DEATHS_HEAD_RING_SPEED, FLESH_DEATHS_HEAD_RING_SHOTS); + npc.FireProjectiles(npc.pos, ring, PROJECTILES_RING, params); +} + +// 00532cf0 The Death's Head's AI, for every Death's Head and the Flesh Death's Head: they bounce about the room until +// its last enemy dies. The Cursed one frightens, the Brimstone one fires beams down its row and column, and the +// Red Skull bursts into rings of fire. +void npc_deaths_head_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + if (npc.state == NPC_STATE_INIT) return deaths_head_init(npc); + + npc.friction *= DEATHS_HEAD_FRICTION; + bool isDeathsHead = npc.type == ENTITY_DEATHS_HEAD; + if (npc.state == NPC_STATE_MOVE) + { + npc.sprite.Play("Idle"); + deaths_head_drift(npc); + if (isDeathsHead && npc.variant == CURSED_DEATHS_HEAD) cursed_deaths_head_scare(npc); + else if (isDeathsHead && npc.variant == BRIMSTONE_DEATHS_HEAD) brimstone_deaths_head_aim(npc); + else if (isDeathsHead && npc.variant == RED_SKULL) red_skull_aim(npc); + } + else if (npc.state == NPC_STATE_ATTACK) + { + npc.friction *= DEATHS_HEAD_ATTACK_FRICTION; + if (isDeathsHead && npc.variant == BRIMSTONE_DEATHS_HEAD && brimstone_deaths_head_fire(npc)) + { + npc.projectileCooldown = BRIMSTONE_REST_FRAMES; + npc.state = NPC_STATE_MOVE; + } + else if (isDeathsHead && npc.variant == RED_SKULL && red_skull_fire(npc)) + { + npc.projectileCooldown = RED_SKULL_REST_FRAMES; + npc.state = NPC_STATE_MOVE; + } + } + + if (npc.projectileCooldown > 0) npc.projectileCooldown -= ticks; + deaths_head_end_check(npc); +} diff --git a/src/npc_deep_gaper.cpp b/src/npc_deep_gaper.cpp new file mode 100644 index 0000000..64c302d --- /dev/null +++ b/src/npc_deep_gaper.cpp @@ -0,0 +1,155 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "sfx_manager.h" +#include + +// One Deep Gaper in 3 without a subtype rolls one of 6 heads, the sixth carrying a leech it throws as it dies. +constexpr int DEEP_GAPER_HEAD_ODDS = 3; +constexpr int DEEP_GAPER_HEADS = 6; +constexpr int DEEP_GAPER_LEECH_HEAD = 6; + +// 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 +// no player within 60, it rises out. +constexpr int DEEP_GAPER_PLATE_DELAY = 9; +constexpr int DEEP_GAPER_RISE_CHECK_FRAMES = 4; +constexpr uint32_t DEEP_GAPER_RISE_MASK = 7; +constexpr int DEEP_GAPER_RISE_AFTER = 90; +constexpr float DEEP_GAPER_RISE_CLEARANCE = 60; +constexpr float DEEP_GAPER_STEER_SPEED = 1; +constexpr std::array DEEP_GAPER_AMBUSHES = {"Ambush1", "Ambush2"}; +constexpr int DEEP_GAPER_SPLASH_SOUND_DELAY = 10; + +// Out, it walks its grid path at 0.6 (fleeing when scared), groaning one time in 3 while it sees its prey. +constexpr float DEEP_GAPER_PATH_SPEED = 0.6f; +constexpr int DEEP_GAPER_PATH_MARKER = 900; +constexpr float DEEP_GAPER_WALK_THRESHOLD = 0.1f; +constexpr float DEEP_GAPER_FEAR_FRICTION = 0.8f; +constexpr uint32_t DEEP_GAPER_GROAN_ODDS = 3; +constexpr int DEEP_GAPER_GROAN_DELAY = 40; + +// Out of the water: walking, its head on. +static void deep_gaper_surface(Entity_NPC& npc) +{ + npc.state = NPC_STATE_MOVE; + npc.sprite.SetFrame("WalkVert", 0); + npc.sprite.PlayOverlay("Head"); +} + +// Its head, then whether it waits under the water (when spawned as the room is entered). +static void deep_gaper_init(Entity_NPC& npc) +{ + if (npc.subtype == 0) + { + RNG rng = {npc.initSeed, 1, 5, 16}; + if (rng.RandomInt(DEEP_GAPER_HEAD_ODDS) == 0) + npc.Morph(npc.type, npc.variant, (int)rng.RandomInt(DEEP_GAPER_HEADS) + 1, -1); + } + + Room& room = *g_game->room; + if (!room.isInitialized || g_game->frameCount != room.enterFrame) + { + deep_gaper_surface(npc); + npc.entityCollisionClass = ENTCOLL_ALL; + return; + } + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + npc.isCanShutDoors = false; + npc.state = NPC_STATE_IDLE; + npc.isInvincible = true; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.i1 = npc.championColorIdx; + npc.championColorIdx = CHAMPION_NONE; +} + +// Under the water: waiting for the fight, then rising out when the moment comes (or its controller says). +static void deep_gaper_wait(Entity_NPC& npc) +{ + bool isControlled = npc.controllerID != -1; + if (isControlled) + { + npc.pathfinder.FindGridPath({}, DEEP_GAPER_STEER_SPEED, 0, DIRECT_PATH_FAR); + npc.SpawnControlTarget(2, -1); + } + if (!npc.isCanShutDoors) + { + Room& room = *g_game->room; + bool isFightOn = npc.HasEntityFlags(FLAG_FRIENDLY) || + (npc.GetAliveEnemyCount() < 1 && room.roomClearDelay < DEEP_GAPER_PLATE_DELAY) || + g_game->GetCurrentRoomDesc()->flags & ROOM_DESCRIPTOR_FLAG_PRESSURE_PLATES_TRIGGERED; + if (!isFightOn) return; + npc.isCanShutDoors = true; + npc.stateFrame = 0; + return; + } + + if (isControlled) npc.UpdateChargeBar(DEEP_GAPER_RISE_AFTER, 0, (float)npc.stateFrame, true); + bool isRising = false; + if (npc.IsFrame(DEEP_GAPER_RISE_CHECK_FRAMES, 0)) + isRising = (Random() & DEEP_GAPER_RISE_MASK) == 0 || npc.stateFrame > DEEP_GAPER_RISE_AFTER; + if (!isRising && isControlled) + isRising = npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) || npc.stateFrame > DEEP_GAPER_RISE_AFTER; + if (isRising && !npc.IsPlayerInRadius(npc.pos, DEEP_GAPER_RISE_CLEARANCE)) + { + if (npc.chargeBarSprite.isLoaded) npc.chargeBarSprite.color._tint[3] = 0; + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play(DEEP_GAPER_AMBUSHES[npc.initSeed & 1]); + npc.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.isVisible = true; + npc.isInvincible = false; + npc.championColorIdx = npc.i1; + g_game->UpdateBackwardsPathStages(); + } + npc.stateFrame += npc_ticks_get(npc); +} + +// Walking after its prey, groaning now and then. +static void deep_gaper_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", DEEP_GAPER_WALK_THRESHOLD); + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), DEEP_GAPER_PATH_SPEED, DEEP_GAPER_PATH_MARKER, + DIRECT_PATH_FAR); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= DEEP_GAPER_FEAR_FRICTION; + } + + bool isGroaning = npc.controllerID == -1 ? npc.IsHostileTo(npc.GetPlayerTarget()) && + npc.pathfinder.hasDirectPath && + Random() % DEEP_GAPER_GROAN_ODDS == 0 + : npc.IsControllerActionPressed(CONTROLLER_ACTION_GROAN); + if (isGroaning) npc_sound_play(SOUND_ZOMBIE_WALKER_KID, 1, DEEP_GAPER_GROAN_DELAY, champion_pitch_get(npc)); +} + +// Rising out of the water with a splash on the "Splash" event, then walking. +static void deep_gaper_rise(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + if (anim.animData && anim.IsEventTriggered("Splash")) + { + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BIG_SPLASH, .seed = Random()}) + ->Update(); + npc_sound_play(SOUND_BOSS2_DIVE, 1, DEEP_GAPER_SPLASH_SOUND_DELAY, 1); + npc_sound_play(SOUND_ZOMBIE_WALKER_KID, 1, DEEP_GAPER_GROAN_DELAY, champion_pitch_get(npc)); + npc.entityCollisionClass = ENTCOLL_ALL; + } + if (!anim.animData || !anim.isPlaying) deep_gaper_surface(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. +void npc_deep_gaper_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) deep_gaper_init(npc); + else if (npc.state == NPC_STATE_IDLE) deep_gaper_wait(npc); + else if (npc.state == NPC_STATE_MOVE) deep_gaper_walk(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)"); +} diff --git a/src/npc_depths.h b/src/npc_depths.h new file mode 100644 index 0000000..da41ad8 --- /dev/null +++ b/src/npc_depths.h @@ -0,0 +1,17 @@ +#pragma once + +#include "npc_caves.h" + +// The Depths, Womb and alt path enemies' AIs the dispatcher (npc_ai_update) runs by type. +void npc_guts_update(Entity_NPC& npc); +void npc_nerve_ending_update(Entity_NPC& npc); +void npc_para_bite_update(Entity_NPC& npc); +void npc_deaths_head_update(Entity_NPC& npc); +void npc_needle_update(Entity_NPC& npc); +void npc_membrain_update(Entity_NPC& npc); +void npc_lump_update(Entity_NPC& npc); +void npc_swinger_update(Entity_NPC& npc); +void npc_blister_update(Entity_NPC& npc); +void npc_fat_sack_update(Entity_NPC& npc); +void npc_deep_gaper_update(Entity_NPC& npc); +void npc_blurb_update(Entity_NPC& npc); diff --git a/src/npc_fat_sack.cpp b/src/npc_fat_sack.cpp new file mode 100644 index 0000000..baeb84e --- /dev/null +++ b/src/npc_fat_sack.cpp @@ -0,0 +1,176 @@ +#include "npc_depths.h" +#include "entity_effect.h" +#include "game.h" +#include "room_grid.h" +#include "sfx_manager.h" + +// The Fat Sack walks its grid path at 0.3, groaning one time in 50. One time in 50 it leaps where its prey will be +// in 10 frames (or the nearest free spot within 120), gliding there 0.02 of the way more each frame after 10 frames +// up, and lands in a ring of 6 shots at 12 and 5 puddles of red creep twice as big within 50. +constexpr float FAT_SACK_PATH_SPEED = 0.3f; +constexpr int FAT_SACK_PATH_MARKER = 900; +constexpr float FAT_SACK_WALK_THRESHOLD = 0.1f; +constexpr float FAT_SACK_FEAR_FRICTION = 0.8f; +constexpr uint32_t FAT_SACK_GROAN_ODDS = 50; +constexpr float FAT_SACK_GROAN_VOLUME = 0.8f; +constexpr int FAT_SACK_GROAN_DELAY = 40; +constexpr uint32_t FAT_SACK_LEAP_ODDS = 50; +constexpr float FAT_SACK_LEAD_FRAMES = 10; +constexpr float FAT_SACK_LANDING_SEARCH = 120; +constexpr int FAT_SACK_GLIDE_AFTER = 10; +constexpr float FAT_SACK_GLIDE_STEP = 0.02f; +constexpr float FAT_SACK_JUMP_FRICTION = 0.8f; +constexpr float FAT_SACK_LAND_FRICTION = 0.7f; +constexpr float FAT_SACK_RING_SPEED = 12; +constexpr float FAT_SACK_RING_SHOTS = 6; +constexpr int FAT_SACK_PUDDLES = 5; +constexpr float FAT_SACK_PUDDLE_RANGE = 50; +constexpr float FAT_SACK_PUDDLE_SCALE = 2; +constexpr float FAT_SACK_THUD_VOLUME = 2; + +// A controlled Fat Sack steers its leap, and the longer it holds a direction (up to 30 frames) the farther it goes. +constexpr float FAT_SACK_DEADZONE = 0.1f; +constexpr float FAT_SACK_HOLD_MAX = 30; +constexpr float FAT_SACK_STEER = 0.1f; + +// Dying (unless blown apart past 25 overkill), it rises again as a Blubber one time in 3, waiting 20 to 39 frames. +constexpr float FAT_SACK_GIBBED_HEALTH = -25; +constexpr uint32_t FAT_SACK_RISE_ODDS = 3; +constexpr uint32_t FAT_SACK_RISE_WAIT_RANGE = 20; +constexpr int FAT_SACK_RISE_WAIT = 20; + +// Walking after its prey, and leaping now and then. +static void fat_sack_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", FAT_SACK_WALK_THRESHOLD); + npc.aiFloat = FAT_SACK_PATH_SPEED; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), FAT_SACK_PATH_SPEED, FAT_SACK_PATH_MARKER, + DIRECT_PATH_FAR); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= FAT_SACK_FEAR_FRICTION; + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= FAT_SACK_FEAR_FRICTION; + } + + if (Random() % FAT_SACK_GROAN_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, FAT_SACK_GROAN_VOLUME, FAT_SACK_GROAN_DELAY, false, 1); + bool isLeaping = npc.controllerID == -1 ? Random() % FAT_SACK_LEAP_ODDS == 0 + : npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT); + if (!isLeaping || npc.HasEntityFlags(FLAG_DISTRACTED)) return; + + npc.PlaySound(SOUND_FETUS_JUMP, 1, 2, false, 1); + npc.state = NPC_STATE_JUMP; + Vector at = npc.GetPlayerTarget()->pos; + Entity* target = npc.GetPlayerTarget(); + npc.targetPosition = vector_make(target->velocity.x * FAT_SACK_LEAD_FRAMES + at.x, + target->velocity.y * FAT_SACK_LEAD_FRAMES + at.y); + if (room_grid_collision_at(npc.targetPosition) != 0) + npc.targetPosition = room_free_pickup_position_find({npc.targetPosition, FAT_SACK_LANDING_SEARCH}); + npc.v1.x = 0; + npc.stateFrame = 0; +} + +// The landing's splash: a ring of shots and puddles of creep around it. +static void fat_sack_splash(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + ProjectileParams params; + Random(); + params = ProjectileParams(); + npc.FireProjectiles(npc.pos, vector_make(FAT_SACK_RING_SPEED, FAT_SACK_RING_SHOTS), PROJECTILES_RING, params); + + for (int i = 0; i < FAT_SACK_PUDDLES; i++) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float distance = random_unit() * FAT_SACK_PUDDLE_RANGE; + Vector at = vector_make(std::cos(angle) * distance + npc.pos.x, std::sin(angle) * distance + npc.pos.y); + Entity* creep = g_game->Spawn( + {.position = at, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = seed}); + creep->sprite.scale = vector_make(FAT_SACK_PUDDLE_SCALE, FAT_SACK_PUDDLE_SCALE); + } +} + +// Leaping: gliding toward its landing spot (or steered), then landing with a splash. +static void fat_sack_leap(Entity_NPC& npc) +{ + if (npc.stateFrame > FAT_SACK_GLIDE_AFTER) + { + npc.v1.x = std::min(npc.v1.x + FAT_SACK_GLIDE_STEP, 1.0f); + float glide = npc.v1.x; + if (npc.controllerID == -1) + { + npc.pos.y = (1 - glide) * npc.pos.y + glide * npc.targetPosition.y; + npc.pos.x = glide * npc.targetPosition.x + (1 - glide) * npc.pos.x; + } + else + { + if (!npc.sprite.WasEventTriggered("Hit")) + reconstruction_missing("NpcAI::ENTITY_FAT_SACK 00530a80: apply_controller_movement 006d9320"); + else + { + Vector input = npc.GetControllerInput(0); + npc.velocity.x = input.x * FAT_SACK_STEER * npc.speedMultiplier + npc.velocity.x; + npc.velocity.y = input.y * FAT_SACK_STEER * npc.speedMultiplier + npc.velocity.y; + } + npc.targetPosition = npc.pos; + } + } + npc.stateFrame += npc_ticks_get(npc); + + AnimationState& anim = npc.sprite.animState; + if (npc.state == NPC_STATE_JUMP) + { + npc.sprite.Play("Jump"); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.friction *= FAT_SACK_JUMP_FRICTION; + if (!anim.animData || !anim.isPlaying) npc.state = NPC_STATE_STOMP; + return; + } + if (npc.state != NPC_STATE_STOMP) return; + + npc.sprite.Play("Land"); + npc.friction *= FAT_SACK_LAND_FRICTION; + if (npc.sprite.IsEventTriggered("Splash")) fat_sack_splash(npc); + if (anim.animData && anim.IsEventTriggered("Hit")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.PlaySound(SOUND_MEAT_JUMPS, FAT_SACK_THUD_VOLUME, 2, false, 1); + } + if (!anim.animData || !anim.isPlaying) npc.state = NPC_STATE_MOVE; +} + +// 00530a80 The Fat Sack's AI: it walks after its prey and leaps onto where it will be, landing in a splash of shots +// and creep. It may rise again as a Blubber. +void npc_fat_sack_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + return; + } + if (npc.isDead) + { + if (npc.health <= FAT_SACK_GIBBED_HEALTH || Random() % FAT_SACK_RISE_ODDS != 0) return; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.Morph(ENTITY_BLUBBER, 0, 0, -1); + npc.isDead = false; + npc.health = npc.maxHitPoints; + npc.projectileCooldown = (int)(Random() % FAT_SACK_RISE_WAIT_RANGE) + FAT_SACK_RISE_WAIT; + return; + } + + if (npc.controllerID != -1) + { + bool isHeld = !vector_is_zero(npc.GetControllerInput(FAT_SACK_DEADZONE)); + npc.v2.x = isHeld ? std::min(npc.v2.x + 1, FAT_SACK_HOLD_MAX) : 0; + } + if (npc.state == NPC_STATE_MOVE) fat_sack_walk(npc); + else fat_sack_leap(npc); +} diff --git a/src/npc_guts.cpp b/src/npc_guts.cpp new file mode 100644 index 0000000..2d675f9 --- /dev/null +++ b/src/npc_guts.cpp @@ -0,0 +1,555 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "manager.h" +#include "room_descriptor.h" +#include "sfx_manager.h" +#include + +// The crawlers' variants: Guts and the Scarred Guts and the charging Slog. The Wall Hugger and the shooting Cyst +// crawl the same way. +constexpr int SCARRED_GUTS = 1; +constexpr int GUTS_SLOG = 2; +constexpr ColorMod SLOG_SPLAT = {{1, 1, 1, 1}, {0.2f, 0.2f, 0.2f, 1}, {0, 0, 0}}; +constexpr ColorMod WALL_HUGGER_SPLAT = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; + +// The four crawling directions (down, right, up, left), turning one way along the table. The low byte of i2 marks a +// crawler that just turned, the next one a crawler hugging the other side. +constexpr int GUTS_DIRECTION_COUNT = 4; +constexpr std::array, GUTS_DIRECTION_COUNT> GUTS_DIRECTIONS = {{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}}; +constexpr int GUTS_TURNED = 0xff; +constexpr int GUTS_REVERSED = 0xff00; +constexpr int GUTS_TURN_BACK = 3; +constexpr int GUTS_CELL = 40; +constexpr int GUTS_BLOCKED_PATH = 950; +constexpr uint32_t GUTS_COLLISION_BLOCKED = 3; +constexpr float GUTS_QUARTER_TURN = 1.5707964f; +constexpr float GUTS_DEADZONE = 0.1f; + +// It crawls at 3 (the Scarred Guts 3.3, the Slog 2.45) toward the next cell along its wall, settling onto the cell's +// line. Reaching within 10, or stuck a quarter second (within 2 of the same distance), it picks the next cell. +constexpr int GUTS_FIRST_COOLDOWN = 60; +constexpr float GUTS_FRICTION = 0.6f; +constexpr float GUTS_IDLE_FRICTION = 0.9f; +constexpr float GUTS_ARRIVED = 10; +constexpr float GUTS_PASSED = -10; +constexpr float GUTS_STUCK_SLACK = 2; +constexpr float GUTS_STUCK_STEP = 0.033333335f; +constexpr float GUTS_STUCK_LIMIT = 0.25f; +constexpr float GUTS_SPEED = 3; +constexpr float SCARRED_GUTS_SPEED = 3.3f; +constexpr float SLOG_SPEED = 2.45f; +constexpr float GUTS_ALIGN = 0.4f; + +// The Wall Hugger grows its spikes 30 frames in, unless the room's plates are pressed or a player has the Flat File. +constexpr int WALL_HUGGER_SPIKE_FRAMES = 30; +constexpr float WALL_HUGGER_SPIKE_VOLUME = 1.5f; + +// The Slog watches its prey (the nearest within 5000, every other frame) with its eye 2 off, and charges down its row +// or column once the prey's next 5 frames lie on it. It winds up, slowing by a tenth a frame to 0.1, then rams at 1.8 +// one cell on and on until it hits a wall, and rests 60 frames. +constexpr float SLOG_TARGET_RANGE = 5000; +constexpr float SLOG_EYE_SHIFT = 2; +constexpr float SLOG_LEAD_FRAMES = 5; +constexpr int SLOG_WINDING = -1; +constexpr int SLOG_RAMMING = -2; +constexpr float SLOG_WIND_SLOW = 0.1f; +constexpr float SLOG_WIND_MIN = 0.1f; +constexpr float SLOG_RAM_SPEED = 1.8f; +constexpr float SLOG_HIT_SPEED = 0.1f; +constexpr float SLOG_RECOVER = 0.05f; +constexpr int SLOG_RUMBLE_FRAMES = 4; +constexpr float SLOG_RUMBLE_VOLUME = 0.4f; +constexpr float SLOG_RUMBLE_PITCH = 0.7f; +constexpr int SLOG_LANE_PATH_MAX = 650; +constexpr int LINE_CELL_BLOCKED_MAX = 8; + +// The Cyst shoots at 10 every 30 frames, from a blood poof 14 up. +constexpr int CYST_SHOT_FRAMES = 30; +constexpr float CYST_SHOT_SPEED = 10; +constexpr float CYST_POOF_HEIGHT = -14; +constexpr float CYST_POOF_DEPTH = 5; +constexpr float CYST_RANGE = 1000; +constexpr int CYST_RANGE_FRAMES = 7; + +// They leave a splat up to 0.7 big every 5 frames. The Scarred Guts leaves red creep every 2, the Slog black creep +// every 4 and while ramming every frame, throwing dark splashes back 2 to 10 fast within 20 degrees. +constexpr int GUTS_TRAIL_FRAMES = 5; +constexpr int SCARRED_GUTS_TRAIL_FRAMES = 2; +constexpr int SLOG_TRAIL_FRAMES = 4; +constexpr float GUTS_SPLAT_SIZE = 0.7f; +constexpr float GUTS_CREEP_SCALE = 0.75f; +constexpr float GUTS_CREEP_START = 0.1f; +constexpr int SCARRED_GUTS_CREEP_FRAMES = 20; +constexpr int SLOG_CREEP_FRAMES = 150; +constexpr float SLOG_SPLASH_BACK = 4; +constexpr float SLOG_SPLASH_SPREAD = 40; +constexpr float SLOG_SPLASH_SPEED = 2; +constexpr float SLOG_SPLASH_SPEED_RANGE = 8; +constexpr float SLOG_SPLASH_GROWTH = 1.5f; +constexpr int SLOG_SPLASH_SUBTYPE = 1; +constexpr ColorMod SLOG_SPLASH_COLOR = tint_color_make(0.01f, 0.01f, 0.01f, 1); + +// Marks the crawler as just turned, or not. +static void guts_turned_set(Entity_NPC& npc, bool isTurned) +{ + npc.i2 = (npc.i2 & ~GUTS_TURNED) | (isTurned ? 1 : 0); +} + +// One cell's step along a direction. +static Vector guts_step(int direction, float scale) +{ + return vector_make((float)GUTS_DIRECTIONS[direction][0] * scale, (float)GUTS_DIRECTIONS[direction][1] * scale); +} + +// The direction a cardinal step points along. +static int guts_direction_of(Vector step) +{ + if (std::abs(step.x) <= std::abs(step.y)) return step.y < 0 ? 2 : 0; + return step.x < 0 ? 3 : 1; +} + +// 00515010 The grid collision of the cell under a position, the cells other crawlers hold counting as blocks. +static uint32_t guts_cell_collision_get(Vector position) +{ + Room& room = *g_game->room; + int index = room.GetGridIndex(position); + uint32_t collision = room.GetGridCollision(index); + if (index >= 0 && index < ROOM_GRID_CELLS && room.gridPaths[index] == GUTS_BLOCKED_PATH) + return GUTS_COLLISION_BLOCKED; + return collision; +} + +// Room::CheckLine's stop position in its cell mode: a step short of the first blocked cell from start toward end, or +// of the end when the line crosses more than 8 cells with any grid path, else the end itself. +static Vector line_cell_stop_get(Vector start, Vector end) +{ + Room& room = *g_game->room; + Vector gap = vector_sub(start, end); + float length = vector_length(gap); + if (length <= 0) return end; + + Vector step = vector_make(gap.x / length * LINE_STEP, gap.y / length * LINE_STEP); + int startIndex = room.GetGridIndex(start); + int blocked = 0; + Vector at = start; + for (float walked = 0; walked < length; walked += LINE_STEP) + { + at = vector_sub(at, step); + int index = room.GetGridIndex(at); + if (room.GetGridCollision(index) != 0) return vector_add(at, step); + if (index != startIndex && room.GetGridPath(index) > 0) blocked++; + } + return blocked > LINE_CELL_BLOCKED_MAX ? vector_add(at, step) : end; +} + +// 005150b0 The unit step from one position to another in its row or column, when every cell between is open and +// lightly walked. None otherwise. +static Vector room_grid_line_direction(Vector from, Vector to) +{ + Room& room = *g_game->room; + if (!room.IsPositionInRoom(from, 0) || !room.IsPositionInRoom(to, 0)) return {}; + + int column = (int)((from.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((from.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + int toColumn = (int)((to.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int toRow = (int)((to.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + if ((column == toColumn) == (row == toRow)) return {}; + + int stepColumn = (toColumn > column) - (toColumn < column); + int stepRow = (toRow > row) - (toRow < row); + int steps = std::max(std::abs(toColumn - column), std::abs(toRow - row)); + for (int i = 0; i < steps - 1; i++) + { + column += stepColumn; + row += stepRow; + int index = room.GetGridIndexByTile(column, row); + if (room.GetGridCollision(index) != 0) return {}; + if (index >= 0 && index < ROOM_GRID_CELLS && room.gridPaths[index] > SLOG_LANE_PATH_MAX) return {}; + } + return vector_make((float)stepColumn, (float)stepRow); +} + +// The Slog and the Cyst bend every layer as their overlay's "Deform" null does, or set them straight. +static void guts_deform(Entity_NPC& npc) +{ + AnimationState& overlay = npc.sprite.overlayAnimState; + const NullFrame* deform = overlay.animData ? overlay.GetNullFrame("Deform") : nullptr; + for (LayerState& layer : npc.sprite.layerStates) + { + layer.pos = deform ? deform->pos : Vector{}; + layer.size = deform ? deform->scale : vector_make(1, 1); + layer.rotation = deform ? deform->rotation : 0; + } +} + +// The Slog's prey, picked anew every other frame while it keeps its wits, and its eye turned toward it. +// The original scores the players by its own measure (FUN_00515290, the distance cut where the prey's next steps lie +// on a lane), which game_nearest_target_player does not take yet: it scores them by distance. +static Entity* slog_target_get(Entity_NPC& npc) +{ + Entity* target = nullptr; + bool isRetargeting = !npc.HasEntityFlags(FLAG_DISTRACTED | FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused() && + g_game->frameCount % 2 == 0; + if (isRetargeting) + { + if (npc.HasEntityFlags(FLAG_CHARM)) + reconstruction_missing("NpcAI::ENTITY_GUTS 005153b0: a charmed Slog's prey (Game::GetNearestEnemy)"); + target = game_nearest_target_player(npc.pos, &npc, npc.HasEntityFlags(FLAG_FRIENDLY), + npc.decoyTargetTimer >= 0, SLOG_TARGET_RANGE); + npc.target = target; + } + if (!target) target = npc.GetPlayerTarget(); + + Vector look = vector_scale(vector_normalized(vector_sub(target->pos, npc.pos)), SLOG_EYE_SHIFT); + if (npc.sprite.isFlipX) look.x = -look.x; + LayerState& eye = npc.sprite.layerStates[1]; + eye.pos = vector_add(look, eye.pos); + return target; +} + +// Rolling for the crawlers, spikes out or in for the Wall Hugger (harmless while in). +static void guts_animate(Entity_NPC& npc, bool isPlatesPressed) +{ + if (npc.type == ENTITY_GUTS || npc.type == ENTITY_CYST) return npc_anim_loop(npc.sprite, "Roll"); + if (npc.type != ENTITY_WALL_HUGGER) return; + + int age = g_game->frameCount - npc.spawnFrame; + if (age < WALL_HUGGER_SPIKE_FRAMES || isPlatesPressed || g_game->playerManager.AnyoneHasTrinket(TRINKET_FLAT_FILE)) + { + npc_anim_loop(npc.sprite, "No-Spikes"); + npc.collisionDamage = 0; + return; + } + if (age == WALL_HUGGER_SPIKE_FRAMES) + { + npc.PlaySound(SOUND_GOOATTACH0, WALL_HUGGER_SPIKE_VOLUME, 2, false, 1); + npc.collisionDamage = npc.config->collisionDamage; + } + npc_anim_loop(npc.sprite, "Spikes"); +} + +// Setting out: no wall picked yet (or the one its subtype names), resting, facing right. The Wall Hugger cannot be +// hurt or affected and shows no health bar. +static void guts_init(Entity_NPC& npc) +{ + npc.i1 = -1; + guts_turned_set(npc, false); + npc.projectileCooldown = GUTS_FIRST_COOLDOWN; + npc.targetPosition = {}; + npc.sprite.isFlipX = true; + npc.state = NPC_STATE_MOVE; + npc.aiFloat = 1; + if (npc.type == ENTITY_GUTS && npc.variant == GUTS_SLOG) npc.splatColor = SLOG_SPLAT; + else if (npc.type == ENTITY_CYST) npc.splatColor = COLOR_GREEN_SPLAT; + + if (npc.type == ENTITY_WALL_HUGGER) + { + npc.AddEntityFlags(FLAG_HIDE_HP_BAR | FLAG_NO_STATUS_EFFECTS); + npc.ClearEntityFlags(FLAG_APPEAR); + npc.isInvincible = true; + npc.splatColor = WALL_HUGGER_SPLAT; + } + if (npc.subtype != 0) + npc.i1 = GUTS_DIRECTION_COUNT - (int)std::min((uint32_t)npc.subtype, (uint32_t)GUTS_DIRECTION_COUNT); + npc.v1 = {}; +} + +// A controlled crawler steers into a side opening along its wall. The direction steered, or -1 for none. +static int guts_steer(Entity_NPC& npc) +{ + if (npc.controllerID == -1 || npc.projectileCooldown < 0) return -1; + Vector input = npc.GetControllerInput(GUTS_DEADZONE); + if (vector_is_zero(input)) return -1; + + Vector cardinal = vector_cardinal(input); + int steered = guts_direction_of(cardinal); + float cosine = std::cos(GUTS_QUARTER_TURN); + float sine = std::sin(GUTS_QUARTER_TURN); + Vector across = vector_make(cosine * cardinal.x - sine * cardinal.y, cosine * cardinal.y + sine * cardinal.x); + if ((steered + GUTS_DIRECTION_COUNT - npc.i1) % 2 != 1) return steered; + + auto cellAt = [&](Vector offset) { + return guts_cell_collision_get(vector_add(vector_scale(offset, GUTS_CELL), npc.pos)) != 0; + }; + if (cellAt(cardinal)) return steered; + if (!cellAt(vector_add(across, cardinal)) && !cellAt(vector_sub(cardinal, across))) return steered; + if (steered == npc.i1) return steered; + + npc.i1 = steered; + guts_turned_set(npc, true); + return steered; +} + +// Heading on: the next cell ahead when open, else turning away from the wall it met (a ramming Slog crashes). +static void guts_advance(Entity_NPC& npc, int steered) +{ + Room& room = *g_game->room; + Vector ahead = vector_add(guts_step(npc.i1, GUTS_CELL), npc.pos); + if (guts_cell_collision_get(ahead) == 0) + { + npc.targetPosition = room.GetGridPosition(room.GetGridIndex(ahead)); + guts_turned_set(npc, false); + return; + } + + if (npc.projectileCooldown == SLOG_RAMMING) + { + npc.projectileCooldown = GUTS_FIRST_COOLDOWN; + npc.sprite.PlayOverlay(npc.i1 == 0 || npc.i1 == 2 ? "HitVert" : "HitHori"); + npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, champion_pitch_get(npc)); + npc.aiFloat = SLOG_HIT_SPEED; + } + bool isCrosswise = steered >= 0 && (steered + GUTS_DIRECTION_COUNT - npc.i1) % 2 == 1; + if (isCrosswise) npc.i1 = steered; + else npc.i1 += npc.i2 & GUTS_REVERSED ? GUTS_TURN_BACK : 1; +} + +// Picking the next cell: around the corner when the wall behind ends and the side is open, else ahead. +static void guts_turn(Entity_NPC& npc) +{ + bool isReversed = npc.i2 & GUTS_REVERSED; + int forward = GUTS_DIRECTIONS[npc.i1][0]; + int side = GUTS_DIRECTIONS[isReversed ? (npc.i1 + 1) % GUTS_DIRECTION_COUNT : npc.i1][1]; + Vector behind = vector_make((float)((forward + side) * -GUTS_CELL) + npc.pos.x, + (float)((forward - side) * GUTS_CELL) + npc.pos.y); + Vector beside = vector_make(npc.pos.x - (float)(side * GUTS_CELL), (float)(forward * GUTS_CELL) + npc.pos.y); + bool isBehindBlocked = guts_cell_collision_get(behind) != 0; + bool isBesideBlocked = guts_cell_collision_get(beside) != 0; + + int steered = guts_steer(npc); + bool isCornering = isBehindBlocked && !isBesideBlocked && !(npc.i2 & GUTS_TURNED) && npc.projectileCooldown >= 0 && + npc.i1 != steered; + if (!isCornering) return guts_advance(npc, steered); + + npc.i1 += isReversed ? 1 : GUTS_TURN_BACK; + guts_turned_set(npc, true); +} + +// Moving toward its cell, giving it up when there or stuck, and settling onto the cell's line. +static void guts_move(Entity_NPC& npc) +{ + Vector gap = vector_sub(npc.pos, npc.targetPosition); + float distance = vector_length(gap); + if (npc.projectileCooldown != SLOG_WINDING) + { + if (distance < GUTS_ARRIVED) npc.targetPosition = {}; + else if (std::abs(distance - npc.v1.x) >= GUTS_STUCK_SLACK) npc.v1 = vector_make(distance, 0); + else + { + npc.v1.y += GUTS_STUCK_STEP; + if (npc.v1.y >= GUTS_STUCK_LIMIT) npc.targetPosition = {}; + } + } + + float speed = GUTS_SPEED; + if (npc.type == ENTITY_GUTS && npc.variant == SCARRED_GUTS) speed = SCARRED_GUTS_SPEED; + else if (npc.type == ENTITY_GUTS && npc.variant == GUTS_SLOG) speed = SLOG_SPEED; + 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); + 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; +} + +// Crawling along the walls. An idle Wall Hugger slides to a stop on the ground instead. +static void guts_crawl(Entity_NPC& npc, bool isActive) +{ + if (npc.i1 < 0 && isActive) + { + for (npc.i1 = 0; npc.i1 < GUTS_DIRECTION_COUNT; npc.i1++) + if (guts_cell_collision_get(vector_add(guts_step(npc.i1, GUTS_CELL), npc.pos)) != 0) break; + if (npc.i1 == GUTS_DIRECTION_COUNT) npc.i1 = (int)(Random() & 3); + npc.friction *= GUTS_FRICTION; + } + else if (!isActive) + { + npc.friction *= GUTS_IDLE_FRICTION; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + } + else npc.friction *= GUTS_FRICTION; + + auto isPassed = [&]() { + Vector past = vector_sub(npc.pos, npc.targetPosition); + const std::array& heading = GUTS_DIRECTIONS[npc.i1]; + return past.y * (float)heading[1] + (float)heading[0] * past.x > GUTS_PASSED; + }; + if (!vector_is_zero(npc.targetPosition) && isActive && npc.projectileCooldown != SLOG_WINDING && isPassed()) + npc.targetPosition = {}; + if (vector_is_zero(npc.targetPosition) && isActive) guts_turn(npc); + + if (npc.i1 >= GUTS_DIRECTION_COUNT) npc.i1 -= GUTS_DIRECTION_COUNT; + else if (npc.i1 < 0) npc.i1 += GUTS_DIRECTION_COUNT; + if (!vector_is_zero(npc.targetPosition) && isActive) guts_move(npc); +} + +// The lane the Slog may charge down: toward where its prey will be, or where its controller steers into an open +// cell. +static Vector slog_lane_get(Entity_NPC& npc, Entity* target) +{ + if (npc.controllerID == -1) + { + if (!target) return {}; + Vector lead = vector_add(vector_scale(target->velocity, SLOG_LEAD_FRAMES), target->pos); + return room_grid_line_direction(npc.pos, line_cell_stop_get(target->pos, lead)); + } + + Vector input = npc.GetControllerMovementInput(GUTS_DEADZONE); + if (vector_is_zero(input)) return {}; + Vector cardinal = vector_cardinal(input); + Vector at = vector_make(cardinal.x * GUTS_CELL + npc.pos.x, cardinal.y * GUTS_CELL + npc.pos.y); + Room& room = *g_game->room; + if (room_grid_collision_at(at) != 0 || room.GetGridPath(room.GetGridIndex(at)) >= GUTS_BLOCKED_PATH) return {}; + return cardinal; +} + +// The Slog's charge: spotting a lane, winding up, then ramming a cell on at a time with a rumble, and recovering. +static void slog_charge(Entity_NPC& npc, Entity* target) +{ + Room& room = *g_game->room; + if (npc.projectileCooldown == 0) + { + Vector lane = slog_lane_get(npc, target); + if (!vector_is_zero(lane)) + { + npc.sprite.PlayOverlay("ChargeStart"); + npc.targetPosition = room.GetGridPosition(room.GetGridIndex(npc.pos)); + npc.projectileCooldown = SLOG_WINDING; + npc.v2 = lane; + npc.aiFloat = 1; + npc.i1 = guts_direction_of(lane); + } + } + else if (npc.projectileCooldown == SLOG_WINDING) + { + float slowed = npc.aiFloat - npc.speedMultiplier * SLOG_WIND_SLOW; + npc.aiFloat = slowed <= SLOG_WIND_MIN ? SLOG_WIND_MIN : slowed; + if (!npc.sprite.overlayAnimState.animData || !npc.sprite.overlayAnimState.isPlaying) + { + npc.sprite.PlayOverlay("ChargeLoop"); + Vector next = vector_add(vector_scale(npc.v2, GUTS_CELL), npc.targetPosition); + npc.targetPosition = room.GetGridPosition(room.GetGridIndex(next)); + npc.projectileCooldown = SLOG_RAMMING; + npc.aiFloat = SLOG_RAM_SPEED; + } + } + else if (npc.projectileCooldown == SLOG_RAMMING && npc.GetIntervalTicks(SLOG_RUMBLE_FRAMES, 0) != 0) + npc.PlaySound(SOUND_BOSS2_BUBBLES, SLOG_RUMBLE_VOLUME, 2, false, SLOG_RUMBLE_PITCH); + + if (npc.projectileCooldown < 0) return; + if (npc.aiFloat < 1) npc.aiFloat = std::min(npc.speedMultiplier * SLOG_RECOVER + npc.aiFloat, 1.0f); + if (npc.projectileCooldown > 0) + npc.projectileCooldown = std::max((int)npc.prevUpdateTime - (int)npc.updateTime + npc.projectileCooldown, 0); +} + +// The Cyst's shot every 30 frames at its target (or where its controller aims), out of a blood poof. +static void cyst_shoot(Entity_NPC& npc) +{ + if (npc.projectileDelay < CYST_SHOT_FRAMES) + { + npc.projectileDelay += npc_ticks_get(npc); + return; + } + if (npc.controllerID != -1 && !npc.IsTargetInAttackRange(CYST_RANGE, CYST_RANGE_FRAMES, false)) return; + + auto* poof = static_cast(g_game->Spawn( + {.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BULLET_POOF, .seed = Random()})); + poof->posOffset = vector_make(0, CYST_POOF_HEIGHT); + poof->parent = &npc; + poof->state = 1; + poof->renderDepthOffset = CYST_POOF_DEPTH; + + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.controllerMovement = npc.controllerID == -1 ? Vector{} : npc.GetControllerMovementInput(GUTS_DEADZONE); + if (!vector_is_zero(npc.controllerMovement)) aim = npc.controllerMovement; + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_scale(aim, CYST_SHOT_SPEED), PROJECTILES_SINGLE, params); + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + if (npc.sprite.SetOverlayAnimation("Shoot", SWITCH_KEEP_FRAME)) + { + npc.sprite.overlayAnimState.Rewind(); + npc.sprite.overlayAnimState.isPlaying = true; + } + npc.projectileDelay = 0; +} + +// A crawler's creep puddle, growing from a tenth of its size. +static void guts_creep_spawn(Entity_NPC& npc, int variant, int frames) +{ + auto* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = variant, .seed = Random()})); + creep->scale = GUTS_CREEP_SCALE; + creep->timeout = frames; + creep->lifespan = frames; + creep->sprite.scale = vector_make(GUTS_CREEP_START, GUTS_CREEP_START); +} + +// A dark splash a ramming Slog throws back. +static void slog_splash_spawn(Entity_NPC& npc) +{ + Vector back = vector_scale(npc.v2, -1); + uint32_t seed = Random(); + float angle = (random_unit() * SLOG_SPLASH_SPREAD - SLOG_SPLASH_SPREAD / 2) * DEGREES_TO_RADIANS; + float cosine = std::cos(angle); + float sine = std::sin(angle); + float speed = random_unit() * SLOG_SPLASH_SPEED_RANGE + SLOG_SPLASH_SPEED; + Entity* splash = g_game->Spawn({.position = vector_add(vector_scale(back, SLOG_SPLASH_BACK), npc.pos), + .velocity = vector_make((cosine * back.x - sine * back.y) * speed, + (cosine * back.y + sine * back.x) * speed), + .subType = SLOG_SPLASH_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_WATER_SPLASH, + .seed = seed}); + splash->sprite.scale = vector_scale(splash->sprite.scale, random_unit() * SLOG_SPLASH_GROWTH + 1); + splash->sprite.color = SLOG_SPLASH_COLOR; + splash->Update(); +} + +// The trail the crawlers leave as they roll: splats, the Scarred Guts' red creep, the Slog's black creep. +static void guts_trail(Entity_NPC& npc) +{ + int frames = npc.variant == SCARRED_GUTS ? SCARRED_GUTS_TRAIL_FRAMES : GUTS_TRAIL_FRAMES; + if (npc.variant == GUTS_SLOG) frames = npc.projectileCooldown == SLOG_RAMMING ? 1 : SLOG_TRAIL_FRAMES; + if (npc.type != ENTITY_GUTS && npc.type != ENTITY_CYST) return; + if (npc.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused()) return; + if ((g_game->frameCount + (int)npc.index) % frames != 0) return; + + if (npc.variant == SCARRED_GUTS) return guts_creep_spawn(npc, EFFECT_CREEP_RED, SCARRED_GUTS_CREEP_FRAMES); + if (npc.variant == GUTS_SLOG) + { + if (frames == 1) slog_splash_spawn(npc); + guts_creep_spawn(npc, EFFECT_CREEP_BLACK, SLOG_CREEP_FRAMES); + } + npc.MakeSplat(random_unit() * GUTS_SPLAT_SIZE)->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// 005153b0 The crawlers' AI, for Guts, the Scarred Guts, the Slog, the Wall Hugger and the Cyst: they cling to the +// walls and roll along them cell by cell, turning at corners. The Slog charges down lanes at its prey, the Cyst +// shoots, and the Wall Hugger rests with its spikes in while the room's plates are pressed, its cell kept from +// spawning again once it dies. +void npc_guts_update(Entity_NPC& npc) +{ + RoomDescriptor* descriptor = g_game->GetRoomByIdx(g_game->currentRoomIdx, g_game->currentDimensionIdx); + bool isPlatesPressed = descriptor->flags & ROOM_DESCRIPTOR_FLAG_PRESSURE_PLATES_TRIGGERED; + bool isActive = npc.type != ENTITY_WALL_HUGGER || !isPlatesPressed; + if (npc.type == ENTITY_WALL_HUGGER && npc.isDead && npc.spawnGridIndex >= 0) + g_game->GetRoomByIdx(g_game->currentRoomIdx, -1)->restrictedGridIndexes.insert(npc.spawnGridIndex); + + bool isSlog = npc.type == ENTITY_GUTS && npc.variant == GUTS_SLOG; + if (isSlog || npc.type == ENTITY_CYST) guts_deform(npc); + Entity* target = isSlog ? slog_target_get(npc) : nullptr; + guts_animate(npc, isPlatesPressed); + if (npc.state == NPC_STATE_INIT) return guts_init(npc); + + if (isActive && g_game->frameCount == npc.spawnFrame) + { + npc.friction *= GUTS_FRICTION; + return; + } + guts_crawl(npc, isActive); + if (isSlog) slog_charge(npc, target); + if (npc.type == ENTITY_CYST) cyst_shoot(npc); + guts_trail(npc); +} diff --git a/src/npc_hive.cpp b/src/npc_hive.cpp index 15fddb5..d1faaa3 100644 --- a/src/npc_hive.cpp +++ b/src/npc_hive.cpp @@ -12,10 +12,6 @@ constexpr int HIVE_DROWNED = 1; constexpr int HIVE_HOLY = 2; constexpr int HIVE_TAINTED = 3; -// What they let loose: flies (a Pooter or attack fly now and then), drowned chargers, holy babies, rings of flies, -// spiders, big spiders and Trites, Willos and leeches. -constexpr int ENTITY_EMBRYO = 77; - // How they fidget: evading their target with a buzz now and then, and resting 20 to 69 frames once 4 to 8 enemies // are about. Within 300 they attack, then rest 75 (the Nest 130 to 149, the tainted Hive 210), else 3. constexpr int SOUND_HIVE_BUZZ = 143; diff --git a/src/npc_hopper.cpp b/src/npc_hopper.cpp index 39e8ccb..0e237d5 100644 --- a/src/npc_hopper.cpp +++ b/src/npc_hopper.cpp @@ -1,6 +1,8 @@ #include "npc_basement.h" +#include "boss_ai.h" #include "game.h" #include "room.h" +#include "room_grid.h" // The hoppers this AI runs: the Hopper (with the Trite, Eggy and the tainted hopper as its variants), the Leaper, // the flaming hopper, the Keeper, Rag Man's Ragling, Ministro and Pon. @@ -68,6 +70,25 @@ constexpr uint64_t RAGLING_SHOT_FLAGS = 1ull << 11 | 1ull << 13; constexpr int RAGLING_GRID_PATH = 500; constexpr int EFFECT_POOF = 15; +// The Leaper's big jump: one time in 7 at rest it leaps at its target (a free spot within 120 when that is blocked), +// drifting there 2 percent more of the way each frame in the air, and lands with a burst of shots. The sticky one +// leaves black creep for 300 frames and lobs grey shots. +constexpr uint32_t BIG_JUMP_ODDS = 7; +constexpr float BIG_JUMP_SEARCH = 120; +constexpr float BIG_JUMP_DRIFT = 0.02f; +constexpr float BIG_JUMP_FRICTION = 0.8f; +constexpr float BIG_JUMP_LAND_VOLUME = 2; +constexpr float BIG_JUMP_BLOOD_DEPTH = -10; +constexpr float BIG_JUMP_SHOT_SPEED = 9; +constexpr float BIG_JUMP_HARD_SHOT_SPEED = 12; +constexpr int LEAPER_STICKY = 1; +constexpr float STICKY_CREEP_SCALE = 2; +constexpr int STICKY_CREEP_TIMEOUT = 300; +constexpr int STICKY_SHOTS = 6; +constexpr float STICKY_SHOT_SCALE = 0.7f; +constexpr float STICKY_SHOT_TRAJECTORY = 10; +constexpr ColorMod STICKY_SHOT_COLOR = {{1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, 1}, {0, 0, 0}}; + // The animations a hopper plays: its idle, hop and shot. struct HopperAnims { @@ -314,6 +335,91 @@ static void hopper_hop_update(Entity_NPC& npc, const HopperAnims& anims) if (npc.type == ENTITY_MINISTRO) npc.sprite.isFlipX = npc.velocity.x < 0; } +// The Leaper's landing: a thud and a burst of blood, then shots in a plus, or the sticky one's creep and grey lobs. +static void leaper_land(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_HOPPER_LAND, BIG_JUMP_LAND_VOLUME, 2, false, 1); + npc.PlaySound(SOUND_SHOOT, 1, 2, false, 1); + if (npc.type == ENTITY_LEAPER && npc.variant == LEAPER_STICKY) + { + auto* creep = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_BLACK, + .seed = Random()})); + creep->sprite.scale = vector_make(STICKY_CREEP_SCALE, STICKY_CREEP_SCALE); + creep->timeout = STICKY_CREEP_TIMEOUT; + creep->lifespan = STICKY_CREEP_TIMEOUT; + creep->Update(); + blood_explosion_spawn(2, npc.pos, {}, npc.splatColor, {})->renderDepthOffset = BIG_JUMP_BLOOD_DEPTH; + + ProjectileParams params; + params.color = STICKY_SHOT_COLOR; + params.scale = STICKY_SHOT_SCALE; + npc.FireBossProjectiles(STICKY_SHOTS, {}, STICKY_SHOT_TRAJECTORY, params); + return; + } + + blood_explosion_spawn(2, npc.pos, {}, COLOR_DEFAULT, {})->renderDepthOffset = BIG_JUMP_BLOOD_DEPTH; + bool isHard = g_game->difficulty == DIFFICULTY_HARD || g_game->difficulty == DIFFICULTY_GREEDIER; + float speed = isHard ? BIG_JUMP_HARD_SHOT_SPEED : BIG_JUMP_SHOT_SPEED; + npc.FireProjectiles(npc.pos, vector_make(speed, 0), PROJECTILES_PLUS, ProjectileParams()); +} + +// In the air the Leaper passes over everything, drifting a growing share of the way to its spot. +static void leaper_drift(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.v1.x += BIG_JUMP_DRIFT; + float share = npc.v1.x; + npc.pos.y = (1 - share) * npc.pos.y + share * npc.targetPosition.y; + npc.pos.x = (1 - share) * npc.pos.x + share * npc.targetPosition.x; +} + +// On the ground the Leaper collides again and slows. +static void leaper_ground(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.friction *= BIG_JUMP_FRICTION; +} + +// The big jump: it crouches until its Jump event, drifts up until the rise ends, then drifts down until its Land event +// and rests once the fall ends. +static void leaper_big_jump_update(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + if (npc.state == NPC_STATE_JUMP) + { + if (!anim.animData || !anim.WasEventTriggered("Jump")) return leaper_ground(npc); + leaper_drift(npc); + if (anim.animData && anim.isPlaying) return; + npc.state = NPC_STATE_STOMP; + npc.stateFrame = 0; + npc.renderZOffset = 0; + return; + } + + if (!anim.animData || !anim.WasEventTriggered("Land")) leaper_drift(npc); + else leaper_ground(npc); + if (!anim.animData) return hopper_idle_reset(npc); + if (anim.IsEventTriggered("Land")) leaper_land(npc); + if (!anim.isPlaying) hopper_idle_reset(npc); +} + +// A resting Leaper leaps at aim, or at a free spot near it when aim is blocked. +static void leaper_big_jump_start(Entity_NPC& npc, const Vector& aim) +{ + npc.targetPosition = aim; + npc.v2.y = 0; + if (room_grid_collision_at(npc.targetPosition) != 0) + npc.targetPosition = room_free_pickup_position_find({.position = npc.targetPosition, .step = BIG_JUMP_SEARCH}); + npc.v1.x = 0; + npc.stateFrame = 0; + npc.state = NPC_STATE_JUMP; +} + // Rag Man's Ragling marks its cell for the pathfinder, and dies in a poof once Rag Man is gone. static void ragling_update(Entity_NPC& npc) { @@ -361,14 +467,13 @@ void npc_hopper_update(Entity_NPC& npc) else if (npc.state == NPC_STATE_ATTACK) hopper_shoot_update(npc, toward); int state = npc.state; - if (state == NPC_STATE_JUMP || state == NPC_STATE_STOMP) - reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: the Leaper's big jump"); - if (state == NPC_STATE_IDLE) hopper_hop_start(npc, jump, anims, aim, toward); + if (state == NPC_STATE_JUMP || state == NPC_STATE_STOMP) leaper_big_jump_update(npc); + else if (state == NPC_STATE_IDLE) hopper_hop_start(npc, jump, anims, aim, toward); else if (state == NPC_STATE_MOVE) hopper_hop_update(npc, anims); - if (npc.type == ENTITY_LEAPER && vector_is_zero(npc.targetPosition) && Random() % 7 == 0 && + if (npc.type == ENTITY_LEAPER && vector_is_zero(npc.targetPosition) && Random() % BIG_JUMP_ODDS == 0 && !npc.HasEntityFlags(FLAG_DISTRACTED)) - reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: the Leaper's big jump"); + leaper_big_jump_start(npc, aim); if (npc.state == NPC_STATE_IDLE) npc.entityGridCollisionClass = GRIDCOLL_GROUND; if (npc.type == ENTITY_RAGLING && npc.variant == RAGLING_RAG_MAN) ragling_update(npc); if (npc.state == NPC_STATE_IDLE && !vector_is_zero(npc.targetPosition)) npc.targetPosition = {}; diff --git a/src/npc_lump.cpp b/src/npc_lump.cpp new file mode 100644 index 0000000..78e303b --- /dev/null +++ b/src/npc_lump.cpp @@ -0,0 +1,222 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "entity_combat.h" +#include "entity_player.h" +#include "sfx_manager.h" + +// The Lump shakes in place, spits 3 shots at 7 at a prey within 260 (63 frames apart), and after 36 frames out hides +// one time in 50, popping up again one time in 20 in a free cell 200 to 400 from the nearest player. It marks the cell +// it stands in. +constexpr float LUMP_FRICTION = 0.7f; +constexpr int LUMP_HIDE_AFTER = 35; +constexpr uint32_t LUMP_HIDE_ODDS = 50; +constexpr uint32_t LUMP_APPEAR_ODDS = 20; +constexpr int LUMP_MARK_PATH = 900; +constexpr int LUMP_MARK_PATH_MAX = 950; +constexpr float LUMP_SPIT_RANGE = 260; +constexpr int LUMP_RANGE_FRAMES = 7; +constexpr int LUMP_SPIT_COOLDOWN = 63; +constexpr int LUMP_APPEAR_COOLDOWN = 12; +constexpr float LUMP_SHOT_SPEED = 7; +constexpr float LUMP_SPOT_MARGIN = 20; +constexpr float LUMP_SPOT_OFF_AXIS = 20; +constexpr float LUMP_SPOT_NEAR_SQUARED = 40000; +constexpr float LUMP_SPOT_FAR_SQUARED = 160000; +constexpr int LUMP_SPOT_PATH_MAX = 500; +constexpr float LUMP_DEADZONE = 0.1f; +constexpr float LUMP_STEER_DEADZONE = 0.4f; + +// Controlled, it may stay hidden 90 frames, then hurts itself for 5 every 30 frames more. It surfaces where it is on +// command (in a free cell under path 900, no player within 60), steering at 3 while hidden. +constexpr float LUMP_BREATH = 90; +constexpr float LUMP_SUFFOCATED = -30; +constexpr float LUMP_SUFFOCATE_DAMAGE = 5; +constexpr int LUMP_SUFFOCATE_COUNTDOWN = 30; +constexpr float LUMP_GIB_SPREAD = 20; +constexpr float LUMP_SUFFOCATE_VOLUME = 0.5f; +constexpr float LUMP_SUFFOCATE_PITCH = 2; +constexpr float LUMP_STEER_SPEED = 3; +constexpr float LUMP_CONTROLLED_RANGE = 1000; +constexpr int LUMP_SURFACE_PATH_MAX = 900; +constexpr float LUMP_SURFACE_CLEARANCE = 60; +constexpr float LUMP_FLIP_SPEED = 1; + +// 00812de0 Room::GetClampedGridIndex: the cell under a position, pulled onto the grid when off it. +static int room_clamped_grid_index_get(Room& room, Vector position) +{ + int column = std::max((int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f), 0); + int row = std::max((int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f), 0); + return std::min(row, room.gridHeight - 1) * room.gridWidth + std::min(column, room.gridWidth - 1); +} + +// Starting to spit at its prey (or where its controller aims). +static void lump_spit_start(Entity_NPC& npc) +{ + npc.sprite.Play("Spit"); + npc.isVisible = true; + float toward = npc.GetPlayerTarget()->pos.x - npc.pos.x; + npc.controllerMovement = npc.controllerID == -1 ? Vector{} : npc.GetControllerMovementInput(LUMP_DEADZONE); + if (npc.controllerID != -1) toward = npc.controllerMovement.x; + npc.sprite.isFlipX = toward > 0; + npc.state = NPC_STATE_ATTACK; + npc.projectileCooldown = LUMP_SPIT_COOLDOWN; +} + +// Hidden, it picks a spot to come up at. The original measures the cell from the spot's offset to the player on x +// and the spot itself on y, which this keeps. +static void lump_spot_pick(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector spot = room.GetRandomPosition(LUMP_SPOT_MARGIN); + Entity_Player* nearest = game_nearest_player(spot); + spot.x -= nearest->pos.x; + float offsetY = spot.y - nearest->pos.y; + float distance = offsetY * offsetY + spot.x * spot.x; + bool isOffAxis = std::abs(spot.x) >= LUMP_SPOT_OFF_AXIS && std::abs(offsetY) >= LUMP_SPOT_OFF_AXIS; + if (!(isOffAxis || distance >= LUMP_SPOT_FAR_SQUARED) || distance < LUMP_SPOT_NEAR_SQUARED) return; + + int index = room_clamped_grid_index_get(room, spot); + if ((uint32_t)index >= ROOM_GRID_CELLS || room.gridPaths[index] < LUMP_SPOT_PATH_MAX) + npc.targetPosition = room.GetGridPosition(index); +} + +// Coming up through the ground. +static void lump_appear(Entity_NPC& npc) +{ + npc.state = NPC_STATE_JUMP; + npc.sprite.Play("Appear"); + npc.isVisible = true; + npc.UpdateDirtColor(true); +} + +// Controlled and hidden: steering, running out of breath, and surfacing on command. +static void lump_controlled_hide(Entity_NPC& npc) +{ + npc.SpawnControlTarget(2, -1); + npc.v1.x -= npc.speedMultiplier; + if (npc.v1.x <= LUMP_SUFFOCATED) + { + npc.v1.x = 0; + npc.TakeDamage(LUMP_SUFFOCATE_DAMAGE, 0, EntityRef(), LUMP_SUFFOCATE_COUNTDOWN); + gibs_spawn({.position = npc.pos, .spawner = &npc, .spread = LUMP_GIB_SPREAD, .amount = 1, .gibFlags = 1}); + npc.PlaySound(SOUND_MEATY_DEATHS, LUMP_SUFFOCATE_VOLUME, 2, false, LUMP_SUFFOCATE_PITCH); + } + npc.pathfinder.FindGridPath({}, LUMP_STEER_SPEED, 0, DIRECT_PATH_FAR); + + bool isCalled = npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) || + npc.IsTargetInAttackRange(LUMP_CONTROLLED_RANGE, LUMP_RANGE_FRAMES, false); + Room& room = *g_game->room; + bool isFree = isCalled && room_grid_collision_at(npc.pos) == 0 && + room.GetGridPath(room.GetGridIndex(npc.pos)) < LUMP_SURFACE_PATH_MAX && + !npc.IsPlayerInRadius(npc.pos, LUMP_SURFACE_CLEARANCE); + if (isFree) + { + npc.targetPosition = npc.pos; + lump_appear(npc); + } + if (std::abs(npc.velocity.x) > LUMP_FLIP_SPEED) npc.sprite.isFlipX = npc.velocity.x > 0; +} + +// Hiding: once under, it picks a spot and comes up there now and then. Whether it holds its spot this frame. +static bool lump_hide(Entity_NPC& npc) +{ + npc.sprite.Play("Hide"); + bool isUnder = !npc.sprite.animState.animData || !npc.sprite.animState.isPlaying; + if (isUnder) + { + npc.isVisible = false; + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (isUnder && npc.controllerID == -1) + { + lump_spot_pick(npc); + if (Random() % LUMP_APPEAR_ODDS == 0) + { + lump_appear(npc); + npc.i1 = 0; + npc.projectileCooldown = std::max(npc.projectileCooldown, LUMP_APPEAR_COOLDOWN); + } + } + if (npc.controllerID == -1) return true; + + bool isMasked = npc.isVisible && !vector_is_zero(npc.GetNullOffset("OverlayEffect")); + if (isMasked) return true; + lump_controlled_hide(npc); + return false; +} + +// The spit on the "Shoot" event, and back to shaking (or hiding, after 36 frames) once the animation ends. +static void lump_animation_update(Entity_NPC& npc) +{ + AnimationState& anim = npc.sprite.animState; + if (anim.animData && anim.IsEventTriggered("Sound")) + npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, champion_pitch_get(npc)); + if (npc.state == NPC_STATE_ATTACK && (!anim.animData || !anim.WasEventTriggered("Shoot"))) + npc.UpdateControllerMovement(false); + if (npc.controllerID != -1 && npc.state == NPC_STATE_JUMP && anim.animData && anim.WasEventTriggered("Shoot")) + anim.AdvancePosition(anim.animData->length - 1); + + if (anim.animData && anim.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_MEATHEADSHOOT, 1, 2, champion_pitch_get(npc)); + Vector aim = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.controllerID != -1) aim = npc.controllerMovement; + float length = vector_length(aim); + if (length > 0) aim = vector_make(aim.x * (LUMP_SHOT_SPEED / length), aim.y * (LUMP_SHOT_SPEED / length)); + ProjectileParams params; + npc.FireProjectiles(npc.pos, aim, PROJECTILES_THREE, params); + npc.i1 = 0; + } + if (anim.animData && anim.isPlaying) return; + + if (npc.state == NPC_STATE_JUMP) npc.state = NPC_STATE_IDLE; + else if (npc.state == NPC_STATE_ATTACK) + npc.state = (uint32_t)npc.i1 <= LUMP_HIDE_AFTER ? NPC_STATE_IDLE : NPC_STATE_MOVE; +} + +// 00522430 The Lump's AI: it shakes in place, spits at its prey, and hides to pop up elsewhere. A controlled Lump +// moves about hidden for as long as its breath lasts. +void npc_lump_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.v1.x = LUMP_BREATH; + npc.targetPosition = npc.pos; + npc.state = NPC_STATE_IDLE; + return npc.UpdateDirtColor(true); + } + + npc.i1++; + npc.friction *= LUMP_FRICTION; + if (npc.state == NPC_STATE_IDLE) + { + npc.sprite.Play("Shake"); + bool isHiding = (uint32_t)npc.i1 > LUMP_HIDE_AFTER && + (npc.controllerID == -1 ? Random() % LUMP_HIDE_ODDS == 0 + : npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) || + !vector_is_zero(npc.GetControllerInput(LUMP_STEER_DEADZONE))); + if (isHiding) npc.state = NPC_STATE_MOVE; + } + + Room& room = *g_game->room; + int cell = room.GetGridIndex(npc.pos); + bool isMarking = (npc.controllerID == -1 || npc.isVisible) && cell >= 0 && cell < ROOM_GRID_CELLS && + room.gridPaths[cell] <= LUMP_MARK_PATH_MAX; + if (isMarking) room.gridPaths[cell] = LUMP_MARK_PATH; + if (npc.controllerID != -1 && npc.v1.x < LUMP_BREATH) npc.UpdateChargeBar(0, LUMP_BREATH, npc.v1.x, true); + else if (npc.controllerID != -1 && npc.chargeBarSprite.isLoaded) npc.chargeBarSprite.color._tint[3] = 0; + + bool isCooled = npc.projectileCooldown < 1 || (npc.projectileCooldown -= npc_ticks_get(npc)) < 1; + bool isSpitting = isCooled && npc.IsTargetInAttackRange(LUMP_SPIT_RANGE, LUMP_RANGE_FRAMES, false) && + (npc.controllerID == -1 || npc.state == NPC_STATE_IDLE); + if (isSpitting) lump_spit_start(npc); + npc.pathfinder.UpdateGridIndex(); + if (npc.isVisible) npc.v1.x = std::min(std::max(npc.speedMultiplier + npc.v1.x, 0.0f), LUMP_BREATH); + + bool isHolding = true; + if (npc.state == NPC_STATE_MOVE) isHolding = lump_hide(npc); + else npc.entityCollisionClass = ENTCOLL_ALL; + lump_animation_update(npc); + if (isHolding) npc.velocity = vector_sub(npc.targetPosition, npc.pos); + npc.UpdateDirtColor(false); +} diff --git a/src/npc_membrain.cpp b/src/npc_membrain.cpp new file mode 100644 index 0000000..0ebf831 --- /dev/null +++ b/src/npc_membrain.cpp @@ -0,0 +1,165 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "sfx_manager.h" + +// The Membrain, Mama Guts and Dead Meat (which splits into Cysts), and the Dinga, which splits into Squirts. +constexpr int MEMBRAIN_DEAD_MEAT = 2; +constexpr ColorMod DINGA_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; + +// They wander, and one time in 30 (with under 8 enemies about) stop to burst: a ring of 8 shots at 10 (Dead Meat's +// ring of 8 bouncing, wall crossing ones at 8), the Dinga 2 Dips 30 apart instead (with under 6 enemies about, six +// times in seven), pushing every Dip within 150 away by a tenth of how near it is. +constexpr float MEMBRAIN_FRICTION = 0.8f; +constexpr uint32_t MEMBRAIN_ATTACK_ODDS = 30; +constexpr int MEMBRAIN_CROWD = 8; +constexpr float MEMBRAIN_RANGE = 1000; +constexpr int MEMBRAIN_RANGE_FRAMES = 7; +constexpr float MEMBRAIN_DEADZONE = 0.1f; +constexpr float MEMBRAIN_SHOT_VOLUME = 0.8f; +constexpr float MEMBRAIN_SHOT_SCALE = 1.4f; +constexpr float MEMBRAIN_SHOT_SPEED = 10; +constexpr float DEAD_MEAT_SHOT_SPEED = 8; +constexpr float DEAD_MEAT_SHOT_COUNT = 8; +constexpr float DEAD_MEAT_SHOT_FALL = -0.07f; +constexpr float DEAD_MEAT_RING_ANGLE = 0.3926991f; +constexpr int DINGA_SHOT_VARIANT = 3; +constexpr int DINGA_CROWD = 6; +constexpr uint32_t DINGA_SHOT_ODDS = 7; +constexpr float DINGA_DIP_SPREAD = 30; +constexpr float DINGA_PUSH_RANGE = 150; +constexpr float DINGA_PUSH_SHARE = 0.1f; + +// The Dinga drips a splat 0.2 to 1.2 big one time in ten. Dying (not to a champion's regrowth), each splits in two +// 10 apart. +constexpr uint32_t DINGA_SPLAT_ODDS = 10; +constexpr float DINGA_SPLAT_SIZE = 0.2f; +constexpr float MEMBRAIN_SPLIT_SPREAD = 10; + +// The Dinga's burst: two Dips (or a ring of shots), and every Dip pushed away. +static void dinga_burst(Entity_NPC& npc) +{ + bool isDipping = false; + if (npc.GetAliveEnemyCount() < DINGA_CROWD) + isDipping = npc.controllerID == -1 ? Random() % DINGA_SHOT_ODDS != 0 : vector_is_zero(npc.controllerMovement); + if (isDipping) + { + Vector spread = vector_scale(random_direction(), DINGA_DIP_SPREAD); + for (float side : {1.0f, -1.0f}) + { + uint32_t seed = Random(); + Vector at = vector_make(npc.pos.x + side * spread.x, npc.pos.y + side * spread.y); + Entity* dip = g_game->Spawn({.position = at, .spawner = &npc, .type = ENTITY_DIP, .seed = seed}); + dip->ClearEntityFlags(FLAG_APPEAR); + } + } + else + { + ProjectileParams params; + params.scale = MEMBRAIN_SHOT_SCALE; + params.variant = DINGA_SHOT_VARIANT; + npc.FireProjectiles(npc.pos, vector_make(MEMBRAIN_SHOT_SPEED, 0), PROJECTILES_EIGHT, params); + } + + for (Entity* dip : entity_query(ENTITY_DIP, -1)) + { + Vector away = vector_sub(dip->pos, npc.pos); + float distance = vector_length(away); + float strength = std::max(DINGA_PUSH_RANGE - distance, 0.0f); + if (distance > 0) away = vector_scale(away, strength * DINGA_PUSH_SHARE / distance); + npc_push(*dip, away); + } +} + +// The burst on the "Shoot" event, then back to wandering once the animation ends. +static void membrain_attack(Entity_NPC& npc) +{ + npc.sprite.Play("Attack"); + AnimationState& anim = npc.sprite.animState; + if (anim.animData && anim.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, MEMBRAIN_SHOT_VOLUME, 2, false, 1); + if (npc.type == ENTITY_DINGA) dinga_burst(npc); + else + { + ProjectileParams params; + params.scale = MEMBRAIN_SHOT_SCALE; + if (npc.variant == MEMBRAIN_DEAD_MEAT) + { + params.bulletFlags |= PROJECTILE_NO_WALL_COLLIDE | PROJECTILE_BOUNCE; + params.fallingAccelModifier = DEAD_MEAT_SHOT_FALL; + params.circleAngle = DEAD_MEAT_RING_ANGLE; + npc.FireProjectiles(npc.pos, vector_make(DEAD_MEAT_SHOT_SPEED, DEAD_MEAT_SHOT_COUNT), PROJECTILES_RING, + params); + } + else npc.FireProjectiles(npc.pos, vector_make(MEMBRAIN_SHOT_SPEED, 0), PROJECTILES_EIGHT, params); + } + } + if (!anim.animData || !anim.isPlaying) npc.state = NPC_STATE_MOVE; + npc.stateFrame++; +} + +// Wandering (or fleeing), and stopping to burst now and then. +static void membrain_wander(Entity_NPC& npc) +{ + bool isControlled = npc.controllerID != -1; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || isControlled) npc.pathfinder.MoveRandomly(STATUS_OBEYED); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= MEMBRAIN_FRICTION; + } + + bool isReady = isControlled ? npc.IsTargetInAttackRange(MEMBRAIN_RANGE, MEMBRAIN_RANGE_FRAMES, false) || + npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) + : Random() % MEMBRAIN_ATTACK_ODDS == 0 && npc.GetAliveEnemyCount() < MEMBRAIN_CROWD; + if (isReady && !npc.HasEntityFlags(FLAG_DISTRACTED)) + { + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + npc.controllerMovement = isControlled ? npc.GetControllerMovementInput(MEMBRAIN_DEADZONE) : Vector{}; + } + npc.sprite.Play("Wiggle"); +} + +// Dying, it splits in two: Brains from the Membrain, Cysts from Dead Meat, Guts from Mama Guts, Squirts from the Dinga. +static void membrain_split(Entity_NPC& npc) +{ + Vector spread = vector_scale(random_direction(), MEMBRAIN_SPLIT_SPREAD); + int type = ENTITY_SQUIRT; + if (npc.type == ENTITY_MEMBRAIN && npc.variant == 0) type = ENTITY_BRAIN; + else if (npc.type == ENTITY_MEMBRAIN && npc.variant == MEMBRAIN_DEAD_MEAT) type = ENTITY_CYST; + else if (npc.type == ENTITY_MEMBRAIN) type = ENTITY_GUTS; + else if (npc.type != ENTITY_DINGA) return; + + for (float side : {1.0f, -1.0f}) + { + uint32_t seed = Random(); + Vector at = side > 0 ? vector_make(spread.x + npc.pos.x, spread.y + npc.pos.y) + : vector_make(npc.pos.x - spread.x, npc.pos.y - spread.y); + g_game->Spawn({.position = at, .spawner = &npc, .type = type, .seed = seed}); + } +} + +// 0051c040 The Membrain's AI, for the Membrain, Mama Guts, Dead Meat and the Dinga: they wander and stop to burst into +// shots (the Dinga into Dips), and split in two as they die. +void npc_membrain_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + if (npc.type == ENTITY_DINGA) npc.splatColor = DINGA_SPLAT; + else if (npc.type == ENTITY_MEMBRAIN && npc.variant == MEMBRAIN_DEAD_MEAT) npc.splatColor = COLOR_GREEN_SPLAT; + return; + } + + npc.friction *= MEMBRAIN_FRICTION; + if (npc.state != NPC_STATE_MOVE) membrain_attack(npc); + else membrain_wander(npc); + + if (npc.type == ENTITY_DINGA && Random() % DINGA_SPLAT_ODDS == 0) + { + Entity_Effect* splat = npc.MakeSplat(random_unit() + DINGA_SPLAT_SIZE); + splat->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + if (npc.isDead && npc.championRegenCount == 0) membrain_split(npc); +} diff --git a/src/npc_needle.cpp b/src/npc_needle.cpp new file mode 100644 index 0000000..c5a535d --- /dev/null +++ b/src/npc_needle.cpp @@ -0,0 +1,232 @@ +#include "npc_depths.h" +#include "entity_effect_combat.h" +#include "entity_player.h" +#include "entity_config.h" +#include "game.h" +#include "room.h" +#include "room_grid.h" +#include "sfx_manager.h" + +// The Needle and the Pasty, which leaves no blood and throws a cross of shots as it leaps. +constexpr int NEEDLE_PASTY = 1; + +// Buried 30 to 89 frames at first (20 to 59 later), it comes up in a free spot 60 to 310 from the room's middle, one +// time in two, when that lies 120 to 240 from the nearest player. +constexpr uint32_t NEEDLE_FIRST_WAIT_RANGE = 60; +constexpr int NEEDLE_FIRST_WAIT = 30; +constexpr uint32_t NEEDLE_WAIT_RANGE = 40; +constexpr int NEEDLE_WAIT = 20; +constexpr float NEEDLE_BURIED_FRICTION = 0.95f; +constexpr float NEEDLE_SPOT_RANGE = 250; +constexpr float NEEDLE_SPOT_MIN = 60; +constexpr float NEEDLE_SPOT_MARGIN = 20; +constexpr float NEEDLE_SPOT_NEAR_SQUARED = 14400; +constexpr float NEEDLE_SPOT_FAR_SQUARED = 57600; +constexpr float NEEDLE_DIG_VOLUME = 0.8f; +constexpr float NEEDLE_LEAP_PITCH = 1.2f; +constexpr int NEEDLE_LEAP_SOUND_DELAY = 4; + +// Out, it leaps at its target at 8, rising at 5 and falling 0.4 a frame faster, pushed on at 3.2. It cannot be +// touched below 6 high and dives back under past 8. A trail of up to 20 points follows it. +constexpr float NEEDLE_LEAP_SPEED = 8; +constexpr float NEEDLE_LEAP_RISE = -5; +constexpr float NEEDLE_LEAP_HEIGHT = 2; +constexpr float NEEDLE_GRAVITY = 0.4f; +constexpr float NEEDLE_SURFACE = -6; +constexpr float NEEDLE_DIVE = 8; +constexpr float NEEDLE_PUSH = 3.2f; +constexpr float NEEDLE_LEAP_FRICTION = 0.6f; +constexpr int NEEDLE_SHOT_DELAY = 4; +constexpr float NEEDLE_SHOT_SPEED = 7; +constexpr float NEEDLE_TRAIL_STEP = 3; +constexpr float NEEDLE_TRAIL_HIGH = 16; +constexpr size_t NEEDLE_TRAIL_LENGTH = 20; +constexpr float NEEDLE_PILE_DEPTH = 4; +constexpr int NEEDLE_ROCK_COUNT = 3; +constexpr float NEEDLE_ROCK_SPEED = 5; +constexpr int NEEDLE_ROCK_SUBTYPE = 0x20000; + +// A bomb knocks it down by 4 and slows it to 0.4 (30 frames apart), a hit by 3 and to 0.8 of its speed (10 apart). +constexpr int NEEDLE_BOMB_GUARD = 30; +constexpr float NEEDLE_BOMB_KNOCK = 4; +constexpr int NEEDLE_HIT_GUARD = 10; +constexpr float NEEDLE_HIT_KNOCK = 3; +constexpr float NEEDLE_SLOWEST = 0.4f; +constexpr float NEEDLE_HIT_SLOW = 0.8f; + +// Buried: counting down, then coming up somewhere near a player, then leaping once out. +static void needle_buried_update(Entity_NPC& npc) +{ + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.friction *= NEEDLE_BURIED_FRICTION; + if (npc.stateFrame >= 1) + { + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + + Vector aim = vector_sub(npc.CalcTargetPosition(0), npc.pos); + float length = vector_length(aim); + npc.velocity = vector_make(aim.x / length * NEEDLE_LEAP_SPEED, aim.y / length * NEEDLE_LEAP_SPEED); + npc.v1 = vector_make(NEEDLE_LEAP_RISE, NEEDLE_LEAP_HEIGHT); + npc.state = NPC_STATE_JUMP; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.v2 = vector_make(aim.x / length, aim.y / length); + npc.vectorDeque1 = {npc.pos}; + npc.vectorDeque2 = {vector_make(0, npc.v1.y)}; + npc.shadowSize = npc.config->shadowSize; + npc.PlaySound(SOUND_SHOVEL_DIG, NEEDLE_DIG_VOLUME, NEEDLE_LEAP_SOUND_DELAY, false, NEEDLE_LEAP_PITCH); + npc.projectileDelay = NEEDLE_SHOT_DELAY; + return; + } + + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + if (npc.stateFrame < 0) npc.stateFrame = std::min(npc_ticks_get(npc) + npc.stateFrame, 0); + if (npc.stateFrame != 0) return; + + Room& room = *g_game->room; + Vector middle = vector_make((room.topLeftPos.x + room.bottomRightPos.x) * 0.5f, + (room.bottomRightPos.y + room.topLeftPos.y) * 0.5f); + Vector direction = random_direction(); + float distance = random_unit() * NEEDLE_SPOT_RANGE + NEEDLE_SPOT_MIN; + Vector spot = vector_make(middle.x + distance * direction.x, middle.y + distance * direction.y); + spot = room.GetClampedPositionImpl(spot, NEEDLE_SPOT_MARGIN, NEEDLE_SPOT_MARGIN, NEEDLE_SPOT_MARGIN, + NEEDLE_SPOT_MARGIN); + spot = room_free_pickup_position_find({.position = spot, .isAvoidActiveEntities = true}); + float playerDistance = vector_length_squared(vector_sub(spot, game_nearest_player(spot)->pos)); + bool isFit = (Random() & 1) == 0 && playerDistance > NEEDLE_SPOT_NEAR_SQUARED && + playerDistance < NEEDLE_SPOT_FAR_SQUARED; + if (!isFit) return; + + npc.velocity = {}; + npc.targetPosition = spot; + npc.pos = spot; + npc.UpdateDirtColor(false); + npc.PlaySound(SOUND_BIRD_FLAP, NEEDLE_DIG_VOLUME, 2, false, 1); + npc.sprite.Play("DigOut"); + npc.stateFrame = 1; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.isVisible = true; +} + +// Leaping: harmless high up, keeping its trail, the Pasty's cross of shots, and diving back under past the ground. +static void needle_leap_update(Entity_NPC& npc) +{ + npc.isVisible = true; + if (npc.v1.x > 0 && npc.v1.y > NEEDLE_SURFACE && npc.entityCollisionClass == ENTCOLL_ALL) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.shadowSize = 0; + npc.PlaySound(SOUND_MAGGOT_ENTER_GROUND, NEEDLE_DIG_VOLUME, NEEDLE_LEAP_SOUND_DELAY, false, NEEDLE_LEAP_PITCH); + } + if (npc.isCollidesWithGrid) npc.v2 = vector_resized(npc.velocity, vector_length(npc.v2)); + npc.entityCollisionClass = npc.v1.y > NEEDLE_SURFACE ? ENTCOLL_NONE : ENTCOLL_ALL; + + if (npc.projectileDelay > 0) + { + npc.projectileDelay -= npc_ticks_get(npc); + if (npc.projectileDelay < 1 && npc.variant == NEEDLE_PASTY) + { + ProjectileParams params; + npc.FireProjectiles(npc.pos, vector_make(NEEDLE_SHOT_SPEED, 0), PROJECTILES_CROSS, params); + } + } + npc.sprite.Play(npc.velocity.y < 0 ? "IdleBack" : "Idle"); + + bool isTrailMoved = vector_length(vector_sub(npc.pos, npc.vectorDeque1.front())) > NEEDLE_TRAIL_STEP; + if (isTrailMoved || npc.v1.y > NEEDLE_TRAIL_HIGH) + { + npc.vectorDeque1.push_back(npc.pos); + npc.vectorDeque2.push_back(vector_make(0, npc.v1.y)); + } + while (npc.vectorDeque1.size() > NEEDLE_TRAIL_LENGTH) + { + npc.vectorDeque1.pop_back(); + npc.vectorDeque2.pop_back(); + } + + if (npc.v1.y > NEEDLE_DIVE) + { + npc.state = NPC_STATE_IDLE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.isVisible = false; + npc.stateFrame = -NEEDLE_WAIT - (int)(Random() % NEEDLE_WAIT_RANGE); + } + npc.friction *= NEEDLE_LEAP_FRICTION; + if (npc.friction == 0) return; + float speed = npc.speedMultiplier; + npc.velocity.y = speed * npc.v2.y * NEEDLE_PUSH / npc.friction + npc.velocity.y; + npc.velocity.x = speed * npc.v2.x * NEEDLE_PUSH / npc.friction + npc.velocity.x; +} + +// Its arc while leaping: rising and falling, its body hidden below ground, kicking up dirt as it crosses it. +static void needle_arc_update(Entity_NPC& npc) +{ + if (npc.state != NPC_STATE_JUMP) + { + npc.posOffset.y = 0; + npc.v1.y = 0; + npc.sprite.layerStates[0].isVisible = true; + return; + } + + float previous = npc.v1.y; + npc.v1.x = npc.speedMultiplier * NEEDLE_GRAVITY + npc.v1.x; + npc.v1.y = npc.v1.x * npc.speedMultiplier + previous; + npc.posOffset.y = npc.v1.y; + npc.sprite.layerStates[0].isVisible = npc.v1.y <= NEEDLE_SURFACE; + if ((previous <= NEEDLE_SURFACE) == (npc.v1.y <= NEEDLE_SURFACE)) return; + + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_DIRT_PILE, .seed = Random()}) + ->renderDepthOffset = NEEDLE_PILE_DEPTH; + game_particles_spawn({.position = npc.pos, + .speed = NEEDLE_ROCK_SPEED, + .count = NEEDLE_ROCK_COUNT, + .subType = NEEDLE_ROCK_SUBTYPE, + .variant = EFFECT_ROCK_PARTICLE}); +} + +// A knock: it drops by some height and slows down to a share of its speed, but not below 0.4, then is guarded a +// while. +static void needle_knock(Entity_NPC& npc, int guard, float knock, bool isBomb) +{ + if (npc.i1 > 0) return; + if (isBomb && vector_length(npc.v2) <= NEEDLE_SLOWEST) return; + + npc.i1 = guard; + npc.v1.x -= knock; + float speed = vector_length(npc.v2); + float share = NEEDLE_SLOWEST / speed; + if (isBomb && speed > 0) npc.v2 = vector_make(npc.v2.x * share, share * npc.v2.y); + else if (!isBomb && speed > NEEDLE_SLOWEST) npc.v2 = vector_scale(npc.v2, NEEDLE_HIT_SLOW); +} + +// 0054eb80 The Needle's AI, for the Needle and the Pasty: it waits buried, comes up near a player and leaps at it, +// diving back under. Hits and bombs knock it down and slow it. +void npc_needle_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_COLLISION) + { + if (npc.collisionEntity->type == ENTITY_BOMB) needle_knock(npc, NEEDLE_BOMB_GUARD, NEEDLE_BOMB_KNOCK, true); + return; + } + + if (npc.state == NPC_STATE_INIT) + { + npc.isVisible = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.state = NPC_STATE_IDLE; + uint32_t wait = Random() % NEEDLE_FIRST_WAIT_RANGE; + npc.aiCallFlags |= AI_CALL_COLLISION; + npc.stateFrame = -NEEDLE_FIRST_WAIT - (int)wait; + npc.ClearEntityFlags(FLAG_APPEAR); + if (npc.variant == NEEDLE_PASTY) npc.AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + } + if (npc.i1 > 0) npc.i1 -= npc_ticks_get(npc); + + if (npc.state == NPC_STATE_IDLE) needle_buried_update(npc); + else if (npc.state == NPC_STATE_JUMP) needle_leap_update(npc); + needle_arc_update(npc); + if (npc.pendingDamage > 0) needle_knock(npc, NEEDLE_HIT_GUARD, NEEDLE_HIT_KNOCK, false); +} diff --git a/src/npc_nerve_ending.cpp b/src/npc_nerve_ending.cpp new file mode 100644 index 0000000..2a8b5e4 --- /dev/null +++ b/src/npc_nerve_ending.cpp @@ -0,0 +1,98 @@ +#include "npc_depths.h" +#include "entity_tear.h" +#include "game.h" +#include "room_grid.h" +#include "sfx_manager.h" + +// The Nerve Ending stays rooted to its spot. Its second variant lashes at a prey (or its controller's aim) within 80 +// across and 20 up or down while idle, hurting everything in an 80 by 40 box 40 out to that side for 15 (players +// for 1, under the 50 that makes it 2). +constexpr float NERVE_FRICTION = 0.5f; +constexpr float NERVE_DEADZONE = 0.1f; +constexpr float NERVE_REACH = 80; +constexpr float NERVE_REACH_HEIGHT = 20; +constexpr float NERVE_BOX_HALF_WIDTH = 40; +constexpr float NERVE_BOX_HALF_HEIGHT = 20; +constexpr float NERVE_BOX_SHIFT = 40; +constexpr float NERVE_DAMAGE = 15; +constexpr float NERVE_PLAYER_THRESHOLD = 50; +constexpr int NERVE_DAMAGE_COUNTDOWN = 30; +constexpr float NERVE_TEAR_DAMAGE = 3.5f; +constexpr float NERVE_HIT_PITCH = 0.8f; + +// 006fefd0 The lash: everything collidable inside the box is hurt, players and familiars unless the lasher is friendly, +// enemies (with the tear effects) only when it is charmed or friendly. The box's bottom is cut at its right edge's x, +// as in the original. Deathmatch players are not told apart. +static void nerve_ending_lash(Entity_NPC& npc, Vector low, Vector high) +{ + EntityRef source(&npc); + bool isHitPlayers = !npc.HasEntityFlags(FLAG_FRIENDLY); + bool isHitEnemies = npc.HasEntityFlags(FLAG_CHARM | FLAG_FRIENDLY); + Vector center = vector_make((high.x + low.x) * 0.5f, (high.y + low.y) * 0.5f); + float radius = vector_length(vector_sub(high, low)) * 0.5f; + + for (Entity* entity : entity_query_radius(center, radius, QUERY_ALL)) + { + bool isInside = std::min(std::max(entity->pos.x, low.x), high.x) == entity->pos.x && + std::min(std::max(entity->pos.y, low.y), high.x) == entity->pos.y; + if (!isInside || entity->entityCollisionClass == ENTCOLL_NONE) continue; + + bool isPlayerSide = entity->type == ENTITY_PLAYER || entity->type == ENTITY_FAMILIAR; + if (isPlayerSide && isHitPlayers) + entity->TakeDamage(NERVE_DAMAGE < NERVE_PLAYER_THRESHOLD ? 1 : 2, 0, source, NERVE_DAMAGE_COUNTDOWN); + else if (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENTITY_LAST_ENEMY && isHitEnemies) + { + entity->TakeDamage(NERVE_DAMAGE, 0, source, NERVE_DAMAGE_COUNTDOWN); + Entity_Tear::ApplyTearFlagEffects(entity, center, TearFlags{}, &npc, NERVE_TEAR_DAMAGE); + } + } +} + +// The lashing Nerve Ending swings toward its prey while idle, and hurts what it sweeps on the "Hit" event. +static void nerve_ending_swing(Entity_NPC& npc) +{ + ANM2& sprite = npc.sprite; + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (sprite.animState.animData && sprite.animState.animData->isLooping) + { + if (npc.controllerID != -1) toward = npc.GetControllerMovementInput(NERVE_DEADZONE); + bool isInReach = + toward.x != 0 && std::abs(toward.y) < NERVE_REACH_HEIGHT && std::abs(toward.x) < NERVE_REACH; + PlayMode mode = !sprite.animState.animData || !sprite.animState.isPlaying ? PLAY_FORCED : PLAY_UNFORCED; + if (isInReach) sprite.Play(toward.x <= 0 ? "SwingLeft" : "SwingRight", mode); + } + if (!sprite.animState.animData) return sprite.Play("Idle"); + + if (sprite.animState.IsEventTriggered("Hit")) + { + npc_sound_play(SOUND_SCAMPER, 1, 2, 1); + npc_sound_play(SOUND_SPLATTER, 1, 2, NERVE_HIT_PITCH); + float shift = sprite.IsPlaying("SwingRight") ? NERVE_BOX_SHIFT : -NERVE_BOX_SHIFT; + Vector low = vector_make(npc.pos.x - NERVE_BOX_HALF_WIDTH + shift, npc.pos.y - NERVE_BOX_HALF_HEIGHT); + Vector high = vector_make(npc.pos.x + NERVE_BOX_HALF_WIDTH + shift, npc.pos.y + NERVE_BOX_HALF_HEIGHT); + nerve_ending_lash(npc, low, high); + } + if (!sprite.animState.animData || !sprite.animState.isPlaying) sprite.Play("Idle"); +} + +// 00537e20 The Nerve Ending's AI, for both Nerve Endings and the training Dummy: rooted to its spot, the second +// Nerve Ending lashing out to its sides. The Dummy never loses health and tallies the damage it takes in v1. +void npc_nerve_ending_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.AddEntityFlags(FLAG_DONT_COUNT_BOSS_HP); + npc.state = NPC_STATE_IDLE; + npc.targetPosition = npc.pos; + return; + } + + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + npc.friction *= NERVE_FRICTION; + if (npc.type == ENTITY_NERVE_ENDING && npc.variant != 0) nerve_ending_swing(npc); + else if (npc.type == ENTITY_NERVE_ENDING) npc.sprite.Play("Idle"); + if (npc.type != ENTITY_DUMMY) return; + + npc.health = npc.maxHitPoints; + for (const DamageEvent& hit : npc.damageEvents) npc.v1.x += hit.damage; +} diff --git a/src/npc_para_bite.cpp b/src/npc_para_bite.cpp new file mode 100644 index 0000000..7c78e33 --- /dev/null +++ b/src/npc_para_bite.cpp @@ -0,0 +1,165 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "entity_player.h" +#include "sfx_manager.h" + +// The Scarred Para-Bite, which spits as it walks. +constexpr int SCARRED_PARA_BITE = 1; + +// It walks its grid path at 0.8, dripping a splat 0.2 to 0.7 big one time in ten. Out of its prey's sight it burrows +// one time in 30, popping up in a free cell (path under 500) 130 to 1000 from the nearest player, or where its +// controller aims (not within 80 of a player). It cannot be touched until frame 3 of "DigOut" nor after frame 7 of +// "DigIn". +constexpr uint32_t PARA_BITE_SPLAT_ODDS = 10; +constexpr float PARA_BITE_SPLAT_SIZE = 0.2f; +constexpr float PARA_BITE_SPLAT_RANGE = 0.5f; +constexpr float PARA_BITE_PATH_SPEED = 0.8f; +constexpr float PARA_BITE_FEAR_FRICTION = 0.8f; +constexpr float PARA_BITE_DIG_FRICTION = 0.7f; +constexpr float PARA_BITE_WALK_SQUARED = 1; +constexpr uint32_t PARA_BITE_BURROW_ODDS = 30; +constexpr float PARA_BITE_SPOT_MARGIN = 20; +constexpr float PARA_BITE_SPOT_NEAR_SQUARED = 16900; +constexpr float PARA_BITE_SPOT_FAR_SQUARED = 1e6f; +constexpr int PARA_BITE_SPOT_PATH_MAX = 500; +constexpr float PARA_BITE_AIM_CLEARANCE = 80; +constexpr int PARA_BITE_OUT_FRAME = 3; +constexpr int PARA_BITE_IN_FRAME = 7; + +// The Scarred Para-Bite spits a lobbed shot at 7 along its walk every 40 to 59 frames (5 to 24 at first). +constexpr uint32_t PARA_BITE_FIRST_COOLDOWN_RANGE = 20; +constexpr int PARA_BITE_FIRST_COOLDOWN = 5; +constexpr uint32_t PARA_BITE_COOLDOWN_RANGE = 20; +constexpr int PARA_BITE_COOLDOWN = 40; +constexpr float PARA_BITE_SHOT_SPEED = 7; +constexpr float PARA_BITE_SHOT_HEIGHT = 5; +constexpr float PARA_BITE_SHOT_FALL = -5; +constexpr float PARA_BITE_SHOT_ACCEL = 0.3f; + +// Walking or standing, facing the way it goes. +static void para_bite_walk_animate(Entity_NPC& npc) +{ + npc.sprite.Play(vector_length_squared(npc.velocity) > PARA_BITE_WALK_SQUARED ? "Walk" : "Idle"); + npc.sprite.isFlipX = npc.velocity.x < 0; +} + +// The Scarred Para-Bite's spit along its walk. +static void para_bite_spit(Entity_NPC& npc) +{ + if (npc.projectileCooldown >= 1) + { + npc.projectileCooldown -= npc_ticks_get(npc); + return; + } + + float speed = vector_length(npc.velocity); + Vector heading = speed > 0 ? vector_make(npc.velocity.x / speed, npc.velocity.y / speed) : Vector{}; + if (vector_is_zero(heading)) return; + + npc.projectileCooldown = (int)(Random() % PARA_BITE_COOLDOWN_RANGE) + PARA_BITE_COOLDOWN; + ProjectileParams params; + params.fallingAccelModifier = PARA_BITE_SHOT_ACCEL; + params.fallingSpeedModifier = PARA_BITE_SHOT_FALL; + params.heightModifier = PARA_BITE_SHOT_HEIGHT; + npc.FireProjectiles(vector_add(npc.pos, npc.velocity), vector_scale(heading, PARA_BITE_SHOT_SPEED), + PROJECTILES_SINGLE, params); + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); +} + +// Walking: after its prey (or away when scared), and burrowing now and then out of its sight. +static void para_bite_move(Entity_NPC& npc) +{ + npc.UpdateDirtColor(false); + if (Random() % PARA_BITE_SPLAT_ODDS == 0) + npc.MakeSplat(random_unit() * PARA_BITE_SPLAT_RANGE + PARA_BITE_SPLAT_SIZE); + bool isControlled = npc.controllerID != -1; + if (npc.HasEntityFlags(FLAG_CONFUSION) && !isControlled) + { + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return para_bite_walk_animate(npc); + } + + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || isControlled) + { + npc.pathfinder.FindGridPath(npc.GetPlayerTarget()->pos, PARA_BITE_PATH_SPEED, 0, DIRECT_PATH_FAR); + if (npc.variant == SCARRED_PARA_BITE) para_bite_spit(npc); + } + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= PARA_BITE_FEAR_FRICTION; + } + para_bite_walk_animate(npc); + + if (!isControlled) + { + if (Random() % PARA_BITE_BURROW_ODDS == 0 && !npc.pathfinder.hasDirectPath) npc.state = NPC_STATE_JUMP; + return; + } + if (!npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT)) return; + Vector aim = npc.GetAimTargetPosition(); + if (vector_is_zero(aim) || room_grid_collision_at(aim) != 0 || npc.IsPlayerInRadius(aim, PARA_BITE_AIM_CLEARANCE)) + return; + npc.state = NPC_STATE_JUMP; + npc.targetPosition = aim; +} + +// Burrowing: picking a free spot well away from the nearest player to come up at. +static void para_bite_spot_pick(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector spot = room.GetRandomPosition(PARA_BITE_SPOT_MARGIN); + float distance = vector_length_squared(vector_sub(spot, game_nearest_player(spot)->pos)); + if (distance <= PARA_BITE_SPOT_NEAR_SQUARED || distance >= PARA_BITE_SPOT_FAR_SQUARED) return; + + int index = room.GetGridIndex(spot); + if ((uint32_t)index >= ROOM_GRID_CELLS || room.gridPaths[index] < PARA_BITE_SPOT_PATH_MAX) + npc.targetPosition = room.GetGridPosition(index); +} + +// The frame its animation is on, rounded down, or -1 without one. +static int para_bite_frame_get(Entity_NPC& npc) +{ + return npc.sprite.animState.animData ? (int)std::floor(npc.sprite.animState.animFrame) : -1; +} + +// 005240a0 The Para-Bite's AI, for both Para-Bites: it walks after its prey and burrows to pop up elsewhere. +void npc_para_bite_update(Entity_NPC& npc) +{ + int previous = npc.state; + if (previous == NPC_STATE_INIT) + { + npc.UpdateDirtColor(true); + npc.state = NPC_STATE_MOVE; + npc.projectileCooldown = (int)(npc.dropRNG.Next() % PARA_BITE_FIRST_COOLDOWN_RANGE) + PARA_BITE_FIRST_COOLDOWN; + return; + } + + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) npc.state = NPC_STATE_MOVE; + npc.SpawnControlTarget(0, -1); + if (npc.state == NPC_STATE_JUMP) + { + npc.sprite.Play("DigIn"); + if (npc.controllerID == -1) para_bite_spot_pick(npc); + } + if (npc.state != previous && previous == NPC_STATE_JUMP && !vector_is_zero(npc.targetPosition)) + { + npc.UpdateDirtColor(true); + npc.pos = npc.targetPosition; + npc.state = NPC_STATE_SPECIAL; + npc.sprite.Play("DigOut"); + npc.targetPosition = {}; + npc.ClearChild(); + } + + int frame = para_bite_frame_get(npc); + bool isUnder = npc.state == NPC_STATE_SPECIAL ? frame < PARA_BITE_OUT_FRAME + : npc.state == NPC_STATE_JUMP && frame > PARA_BITE_IN_FRAME; + npc.entityCollisionClass = isUnder ? ENTCOLL_NONE : ENTCOLL_ALL; + if (npc.state == NPC_STATE_MOVE) return para_bite_move(npc); + + bool isDigSound = (npc.state == NPC_STATE_SPECIAL && frame == PARA_BITE_OUT_FRAME) || + (npc.state == NPC_STATE_JUMP && frame == PARA_BITE_IN_FRAME); + if (isDigSound) npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, champion_pitch_get(npc)); + npc.friction *= PARA_BITE_DIG_FRICTION; +} diff --git a/src/npc_swinger.cpp b/src/npc_swinger.cpp new file mode 100644 index 0000000..05c0669 --- /dev/null +++ b/src/npc_swinger.cpp @@ -0,0 +1,163 @@ +#include "npc_depths.h" +#include "game.h" + +// The Swinger's parts: its body, the head it swings on a cord, and the cord's links. +constexpr int SWINGER_HEAD = 1; +constexpr int SWINGER_CORD = 10; +constexpr int SWINGER_CORD_LINKS = 12; +constexpr float SWINGER_CORD_STEPS = 11; +constexpr int SWINGER_CORD_DEPTH = -500; + +// The body walks its grid path at 0.25 (fleeing when scared), dripping a splat 0.2 to 0.7 big one time in ten. +constexpr float SWINGER_FRICTION = 0.7f; +constexpr float SWINGER_FEAR_FRICTION = 0.8f; +constexpr float SWINGER_PATH_SPEED = 0.25f; +constexpr int SWINGER_PATH_MARKER = 100; +constexpr uint32_t SWINGER_SPLAT_ODDS = 10; +constexpr float SWINGER_SPLAT_SIZE = 0.2f; +constexpr float SWINGER_SPLAT_RANGE = 0.5f; + +// The head swings around the body on a cord paying out to 100 (by 100 a second), a full turn every 100 frames, a +// controller speeding it up or slowing it by up to half (changing by 0.05 a frame). The cord sags 10 in its middle. +constexpr float SWINGER_REACH = 100; +constexpr float SWINGER_PAYOUT_FRAMES = 60; +constexpr float SWINGER_SWING_LIMIT = 0.5f; +constexpr float SWINGER_SWING_STEP = 0.05f; +constexpr float SWINGER_TURN_FRAMES = 50; +constexpr float SWINGER_FULL_TURN = 6.2831855f; +constexpr float SWINGER_CORD_SAG = 10; +constexpr float SWINGER_CORD_DROP = 7; + +// A part whose partner died goes too, turned into what is left: the body into a Globin, the head into a Maw, which +// take over its controller. +static void swinger_part_kill(Entity_NPC& npc, int type) +{ + npc.ClearEntityFlags(FLAG_NO_DEATH_TRIGGER); + npc.Kill(EntityRef()); + Entity* spawned = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = type, .seed = Random()}); + auto* left = static_cast(spawned); + left->Update(); + if (npc.controllerID != -1) npc.TransferControl(left); +} + +// The body, its head and the 12 links of the cord between them. +static void swinger_init(Entity_NPC& npc) +{ + npc.sprite.Play("Body"); + Entity* head = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = npc.type, .variant = SWINGER_HEAD, .seed = Random()}); + head->parent = &npc; + npc.child = head; + head->Update(); + + for (int i = 0; i < SWINGER_CORD_LINKS; i++) + { + auto* link = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = npc.type, .variant = SWINGER_CORD, .seed = Random()})); + link->parent = &npc; + link->child = head; + link->ClearEntityFlags(FLAG_APPEAR); + link->v1.y = (float)i / SWINGER_CORD_STEPS; + link->Update(); + link->AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + } +} + +// The body walks after its prey. +static void swinger_body_update(Entity_NPC& npc) +{ + if (!npc.child) return swinger_part_kill(npc, ENTITY_GLOBIN); + + npc.friction = SWINGER_FRICTION; + bool isControlled = npc.controllerID != -1; + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && !isControlled) + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= SWINGER_FEAR_FRICTION; + } + else if (npc.HasEntityFlags(FLAG_CONFUSION) && !isControlled) npc.pathfinder.MoveRandomly(STATUS_OBEYED); + else + npc.pathfinder.FindGridPath(npc.GetPlayerTarget()->pos, SWINGER_PATH_SPEED, SWINGER_PATH_MARKER, + DIRECT_PATH_FAR); + + if (Random() % SWINGER_SPLAT_ODDS == 0) npc.MakeSplat(random_unit() * SWINGER_SPLAT_RANGE + SWINGER_SPLAT_SIZE); +} + +// The head swings around the body, passing its confusion on. +static void swinger_head_update(Entity_NPC& npc) +{ + Entity* body = npc.parent; + npc.friction = SWINGER_FRICTION; + if (!body) return swinger_part_kill(npc, ENTITY_MAW); + + float reach = std::min(npc.speedMultiplier * SWINGER_REACH / SWINGER_PAYOUT_FRAMES + npc.v2.y, SWINGER_REACH); + npc.v2.y = reach; + float angle = npc.v1.x; + npc.velocity = vector_make((float)std::cos((double)angle) * reach + body->pos.x - npc.pos.x, + (float)std::sin((double)angle) * reach + body->pos.y - npc.pos.y); + + float swing = 0; + if (npc.ParentNPC()) + swing = std::min(std::max(npc.GetControllerMovementInput(0).x * SWINGER_SWING_LIMIT, -SWINGER_SWING_LIMIT), + SWINGER_SWING_LIMIT); + float step = npc.speedMultiplier * SWINGER_SWING_STEP; + if (std::abs(npc.v2.x - swing) > step) swing = swing <= npc.v2.x ? npc.v2.x - step : step + npc.v2.x; + npc.v2.x = swing; + npc.v1.x = (swing + 1) * npc.speedMultiplier * PI_F / SWINGER_TURN_FRAMES + npc.v1.x; + while (npc.v1.x > SWINGER_FULL_TURN) npc.v1.x -= SWINGER_FULL_TURN; + + if (!npc.HasEntityFlags(FLAG_CONFUSION)) return; + body->AddEntityFlags(FLAG_CONFUSION); + npc.ParentNPC()->confusionCountdown = npc.confusionCountdown; +} + +// A cord link hangs at its share of the way from the head to the body, sagging toward the middle. +static void swinger_cord_update(Entity_NPC& npc) +{ + Entity* body = npc.parent; + Entity* head = npc.child; + if (!body || !head) return npc.Remove(); + + float share = npc.v1.y; + float bow = std::abs(share - 0.5f) + std::abs(share - 0.5f); + Vector offset = npc.sprite.offset; + npc.velocity.x = (((body->pos.x - offset.x) - head->pos.x) * share + head->pos.x + 0) - npc.pos.x; + npc.velocity.y = (((body->pos.y - offset.y) - head->pos.y) * share + (1 - bow * bow) * SWINGER_CORD_SAG + + head->pos.y + SWINGER_CORD_DROP) - + npc.pos.y; +} + +// 00536d00 The Swinger's AI, for its body, head and cord: the body walks after its prey swinging its head around +// on the cord. A head left alone becomes a Maw, a body without its head a Globin. +void npc_swinger_update(Entity_NPC& npc) +{ + if (npc.state != NPC_STATE_INIT) + { + if (npc.variant == 0) return swinger_body_update(npc); + if (npc.variant == SWINGER_HEAD) return swinger_head_update(npc); + if (npc.variant == SWINGER_CORD) swinger_cord_update(npc); + return; + } + + if (npc.variant == SWINGER_HEAD && !npc.parent) + { + npc.Morph(npc.type, 0, npc.subtype, npc.championColorIdx); + npc.health = npc.maxHitPoints; + } + npc.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + npc.state = NPC_STATE_MOVE; + if (npc.variant == 0) return swinger_init(npc); + if (npc.variant == SWINGER_HEAD) + { + npc.sprite.Play("Head"); + npc.v1.x = 0; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + } + else if (npc.variant == SWINGER_CORD) + { + npc.sprite.Play("Cord"); + npc.renderZOffset = SWINGER_CORD_DEPTH; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + } +} diff --git a/src/path_finder.cpp b/src/path_finder.cpp index 8d01866..3552f82 100644 --- a/src/path_finder.cpp +++ b/src/path_finder.cpp @@ -4,6 +4,7 @@ #include "npc_ai.h" #include "npc_basement.h" #include "room.h" +#include "room_grid.h" #include #include #include @@ -749,10 +750,48 @@ void PathFinder::MoveRandomlyAxisAligned(float speed, StatusMode mode) if (!vector_is_zero(movementTarget)) axis_steer(*this, speed, elapsed); } -// 007e6650 -void PathFinder::MoveRandomlyBoss(StatusMode) +// How a boss wanders: pushed at half its speed along its heading, veering one time in 30, turning back off walls every +// 5 frames, and trying up to 5 new headings while the cell 10 ahead is blocked. +constexpr float BOSS_WANDER_PUSH = 0.5f; +constexpr uint32_t BOSS_WANDER_TURN_ODDS = 30; +constexpr int BOSS_WANDER_BOUNCE_FRAMES = 5; +constexpr int BOSS_WANDER_TRIES = 5; +constexpr float BOSS_WANDER_LOOKAHEAD = 10; + +// 007e6650 Wanders like a boss along moveDirection. Stuck inside a wall it now and then heads for a free spot instead. +// Unless told to ignore its status, a friendly owner paths to its target and a feared or shrunk one flees. +void PathFinder::MoveRandomlyBoss(StatusMode mode) { - reconstruction_missing("PathFinder::MoveRandomlyBoss 007e6650"); + if (entity->minecart) return; + if (mode == STATUS_OBEYED && is_entity_friendly()) + return FindGridPath(static_cast(entity)->CalcTargetPosition(0), WANDER_FRIENDLY_SPEED, 0, + DIRECT_PATH_FAR); + if (mode == STATUS_OBEYED && entity->HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + return EvadeTarget(static_cast(entity)->GetPlayerTarget()->pos, STATUS_OBEYED); + + if (vector_is_zero(moveDirection)) moveDirection = random_direction(); + npc_push(*entity, vector_scale(moveDirection, BOSS_WANDER_PUSH)); + + Room& room = *g_game->room; + if (room_grid_collision_at(entity->pos) != 0) + { + if (Random() % BOSS_WANDER_TURN_ODDS != 0) return; + Vector spot = room_free_pickup_position_find({.position = entity->pos}); + moveDirection = vector_normalized(vector_sub(spot, entity->pos)); + return; + } + + if (Random() % BOSS_WANDER_TURN_ODDS == 0) + moveDirection = vector_normalized(vector_add(moveDirection, random_direction())); + if (entity->isCollidesWithGrid && entity->IsFrame(BOSS_WANDER_BOUNCE_FRAMES, 0)) + moveDirection = vector_scale(moveDirection, -1); + for (int triesLeft = BOSS_WANDER_TRIES; triesLeft > 0; triesLeft--) + { + Vector ahead = vector_add(entity->pos, vector_scale(moveDirection, BOSS_WANDER_LOOKAHEAD)); + if (room.GetGridCollision(room.GetGridIndex(ahead)) == 0) return; + moveDirection = vector_normalized(vector_sub(random_direction(), moveDirection)); + entity->velocity = {}; + } } // 007e6b90 diff --git a/src/persistent_game_data.cpp b/src/persistent_game_data.cpp index b268c71..bce67b7 100644 --- a/src/persistent_game_data.cpp +++ b/src/persistent_game_data.cpp @@ -33,20 +33,6 @@ constexpr int ENTITY_TYPE_URIEL = 271; constexpr int ENTITY_TYPE_GABRIEL = 272; constexpr int ENTITY_TYPE_PORTAL = 306; constexpr int ENTITY_TYPE_LITTLE_HORN = 404; -constexpr int EVENT_COUNTER_MOM_KILLS = 1; -constexpr int EVENT_COUNTER_ISAAC_KILLS = 11; -constexpr int EVENT_COUNTER_SATAN_KILLS = 13; -constexpr int EVENT_COUNTER_BLUE_BABY_KILLS = 24; -constexpr int EVENT_COUNTER_LAMB_KILLS = 25; -constexpr int EVENT_COUNTER_MEGA_SATAN_KILLS = 26; -constexpr int EVENT_COUNTER_GREED_DONATIONS = 115; -constexpr int EVENT_COUNTER_HUSH_KILLS = 158; -constexpr int EVENT_COUNTER_DELIRIUM_KILLS = 187; -constexpr int EVENT_COUNTER_RUN_MASK_LOW = 188; -constexpr int EVENT_COUNTER_DAILIES_PLAYED = 190; -constexpr int EVENT_COUNTER_MOTHER_KILLS = 491; -constexpr int EVENT_COUNTER_BEAST_KILLS = 492; -constexpr int EVENT_COUNTER_RUN_MASK_HIGH = 496; constexpr int GREED_DONATION_STEP = 1000; constexpr int GREED_DONATION_HALF = 500; constexpr uint32_t DAILIES_PLAYED_NEEDED = 31; diff --git a/src/persistent_game_data.h b/src/persistent_game_data.h index efb6aa0..ca97211 100644 --- a/src/persistent_game_data.h +++ b/src/persistent_game_data.h @@ -17,6 +17,7 @@ constexpr int ACHIEVEMENT_THE_POLAROID = 57; constexpr int ACHIEVEMENT_THE_NEGATIVE = 78; constexpr int ACHIEVEMENT_KRAMPUS = 142; constexpr int ACHIEVEMENT_THE_VOID = 320; +constexpr int ACHIEVEMENT_RERUN = 337; constexpr int BOSS_COUNT = 104; constexpr int CHALLENGE_COUNT = 46; constexpr int COLLECTIBLE_SEEN_COUNT = 733; @@ -26,6 +27,31 @@ constexpr int LEVEL_COUNTER_COUNT = 14; constexpr int MINIBOSS_COUNT = 7; constexpr int SPECIAL_SEED_COUNT = 80; +// The event counters the game reads by id (Lua's EventCounter where it names them). +enum EventCounter : int +{ + EVENT_COUNTER_MOM_KILLS = 1, + EVENT_COUNTER_DEATHS = 10, + EVENT_COUNTER_ISAAC_KILLS = 11, + EVENT_COUNTER_SATAN_KILLS = 13, + EVENT_COUNTER_STREAK = 22, + EVENT_COUNTER_BEST_STREAK = 23, + EVENT_COUNTER_BLUE_BABY_KILLS = 24, + EVENT_COUNTER_LAMB_KILLS = 25, + EVENT_COUNTER_MEGA_SATAN_KILLS = 26, + EVENT_COUNTER_BOSSRUSHS_CLEARED = 111, + EVENT_COUNTER_NEGATIVE_STREAK = 113, + EVENT_COUNTER_GREED_DONATIONS = 115, + EVENT_COUNTER_HUSH_KILLS = 158, + EVENT_COUNTER_DELIRIUM_KILLS = 187, + EVENT_COUNTER_RUN_MASK_LOW = 188, + EVENT_COUNTER_DAILIES_PLAYED = 190, + EVENT_COUNTER_MOTHER_KILLS = 491, + EVENT_COUNTER_BEAST_KILLS = 492, + EVENT_COUNTER_RUN_MASK_HIGH = 496, + EVENT_COUNTER_ONLINE_BEST_STREAK = 498 +}; + // How a Checksum folds bytes in: 4-byte words added to the state rotated right by 1, or CRC-32. enum ChecksumMode { diff --git a/src/player_hud.cpp b/src/player_hud.cpp index d608775..64877a7 100644 --- a/src/player_hud.cpp +++ b/src/player_hud.cpp @@ -4,9 +4,11 @@ #include "game.h" #include "hud.h" #include "item_config.h" +#include "item_pool.h" #include "log.h" #include "manager.h" #include "menu_manager.h" +#include "menu_special_seeds.h" #include "render_passes.h" #include "seeds.h" #include @@ -108,6 +110,41 @@ constexpr int NECRONOMICON_FORM = 15; constexpr int NECRONOMICON_FORM_COUNT = 3; constexpr int POCKET_ACTIVE_SLOT = 2; +// The pockets: the small ones behind the first (stacked in the normal HUD, in a row in the others), the first's card +// front, its name and Tarot Cloth's glow, the pocket active's icon and the Bag of Crafting's table. +constexpr float POCKET_BACK_X = 4; +constexpr float POCKET_BACK_RISE = -6; +constexpr float POCKET_BACK_STEP = 10; +constexpr float POCKET_BACK_ROW_STEP = 8; +constexpr float POCKET_BACK_ROW_X = 2; +constexpr float POCKET_BACK_ROW_Y = 12; +constexpr float POCKET_BACK_ACTIVE_X = -12; +constexpr float POCKET_BACK_ROW_ACTIVE_X = -4; +constexpr float POCKET_BACK_ACTIVE_Y = -8; +constexpr int CARD_FRONT_COUNT = 98; +constexpr float CARD_FRONT_SHIFT = -3; +constexpr float POCKET_TEXT_X = -16; +constexpr float POCKET_ROW_TEXT_X = 13; +constexpr float POCKET_TEXT_Y = -8; +constexpr float POCKET_SHOWN_TEXT_Y = -10; +constexpr float POCKET_ACTIVE_TEXT_SHIFT = -4; +constexpr float POCKET_ROW_ACTIVE_TEXT_SHIFT = 6; +constexpr float POCKET_ACTIVE_X = 24; +constexpr float POCKET_ACTIVE_Y = 18; +constexpr float POCKET_ROW_ACTIVE_X = 9; +constexpr float POCKET_ROW_ACTIVE_Y = 8; +constexpr float CRAFTING_TABLE_X = 14; +constexpr float CRAFTING_TABLE_Y = -3; +constexpr float CRAFTING_ROW_TABLE_X = 50; +constexpr float CRAFTING_ROW_TABLE_Y = 27; +constexpr float POCKET_SECOND_TWIN_SHIFT = 12; +constexpr float TAROT_GLOW_SPEED = 0.2f; +constexpr float TAROT_GLOW_RED_PHASE = 0.5f; +constexpr float TAROT_GLOW_GREEN_PHASE = 0.25f; +constexpr float TAROT_GLOW_RED = 0.17f; +constexpr float TAROT_GLOW_GREEN = 0.1f; +constexpr float TAROT_GLOW_BLUE = 0.25f; + // An active item with its own HUD icon. struct ActiveIcon { @@ -150,7 +187,6 @@ constexpr int SUBCHARGES_PER_CHARGE = 450; // The actives whose icon shows a counter, a state or a glow of its own. constexpr int COLLECTIBLE_JAR_OF_FLIES = 434; constexpr int COLLECTIBLE_MAMA_MEGA = 483; -constexpr int COLLECTIBLE_D_INFINITY = 489; constexpr int COLLECTIBLE_JAR_OF_WISPS = 685; constexpr int COLLECTIBLE_HOLD = 715; constexpr int JAR_HEARTS_SHOWN = 10; @@ -1209,25 +1245,188 @@ void PlayerHUD::RenderTrinket(int trinketSlot, Vector at, float trinketScale, bo for (; pushed > 0; pushed--) graphics.shader_pop(); } -// 008471c0 Draws the pockets at their size and alpha: the cards, pills and pocket actives past the first, then the -// first with its name. The pocket sprites and the HUD's card sprite go back to full size after, the card sprite keeping -// the alpha. -void PlayerHUD::RenderPocketItems(Vector, PlayerHudLayout, float alpha, float pocketScale) +// The pockets behind the first, small: their cards and pills, or the pocket active at half size. The normal HUD stacks +// them up from the corner, the others line them along the bottom. +static void pockets_back_render(PlayerHUD& hud, Vector at, PlayerHudLayout layout, float alpha, float size) { + Entity_Player* player = hud.player; + bool isNormal = layout == HUD_LAYOUT_NORMAL; + for (int i = isNormal ? POCKET_SLOT_COUNT - 1 : 1; isNormal ? i > 0 : i < POCKET_SLOT_COUNT; i += isNormal ? -1 : 1) + { + PocketItem& held = player->pocketItems[i]; + if (held.id == 0) continue; + + Vector spot = isNormal ? vector_make(at.x + POCKET_BACK_X, at.y + (POCKET_BACK_RISE - (float)i * POCKET_BACK_STEP * size)) + : vector_make(at.x + ((float)i * POCKET_BACK_ROW_STEP * size - POCKET_BACK_ROW_X), + at.y + size * POCKET_BACK_ROW_Y); + if (held.type == POCKET_ACTIVE) + { + Vector itemAt = vector_make(spot.x + size * (isNormal ? POCKET_BACK_ACTIVE_X : POCKET_BACK_ROW_ACTIVE_X), + spot.y + size * POCKET_BACK_ACTIVE_Y); + hud.RenderActiveItem(held.id - 1, itemAt, isNormal ? HUD_LAYOUT_NORMAL : layout, size * 0.5f, alpha); + continue; + } + ANM2& sprite = hud.pocketItems[i].sprite; + if (!sprite.isLoaded) continue; + sprite.SetFrame("HUDSmall", 0); + sprite.Render({spot, {}, {}}); + } +} + +// Sets the first pocket's card front on the card sheet. True when it shows: a vanilla card whose frame draws a layer, +// or any modded card. +static bool card_front_set(HUD& hud, int id) +{ + ANM2& cards = hud.cardsPillsSprite; + if (id >= CARD_FRONT_COUNT) return true; + + cards.SetFrame("CardFronts", id); + for (int layer = 0; layer < (int)cards.layerStates.size(); layer++) + { + const AnimationFrame* frame = cards.animState.GetLayerFrame(layer); + if (frame && frame->isVisible) return true; + } + return false; +} + +// The first pocket's name: a card's or pill's, a pocket active's (its description while the map is held), or the +// question marks the mystery seeds show. Unidentified pills show question marks too. +static std::string pocket_name_get(Entity_Player& player, const PocketItem& held) +{ + StringTable& table = g_manager->stringTable; + Seeds& seeds = g_game->seedEffects; + auto is_map_held = [&] { return input_is_action_pressed(ACTION_MAP, player.controllerIndex, nullptr); }; + bool isMystery = (seeds.HasSeedEffect(SEED_PILLS_NEVER_IDENTIFY) && held.type == POCKET_PILL) || + (seeds.HasSeedEffect(SEED_MYSTERY_TAROT_CARDS) && held.type == POCKET_CARD); + std::string name; + + if (held.type == POCKET_CARD) + { + ItemConfig_Card* card = g_manager->itemConfig.GetCard(held.id); + if (card) name = is_map_held() ? card->description_get() : card->GetName(); + } + else if (held.type == POCKET_PILL) + { + uint32_t color = (uint32_t)(held.id & PILL_COLOR_MASK); + if (!g_game->itemPool.IsPillIdentified(color)) isMystery = true; + else if (ItemConfig_Pill* pill = g_manager->itemConfig.GetPillEffect(g_game->itemPool.GetPillEffect(color, &player))) + name = pill->GetName(); + } + else if (ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(player.activeItems[held.id - 1].item)) + name = is_map_held() ? item->description_get() : item->GetLocalizedName(); + if (!isMystery) return name; + + bool isMissing = false; + std::string_view marks = table.get_string("PocketItems", table.language, "QUESTION_MARKS_NAME", &isMissing); + return isMissing ? "#QUESTION_MARKS_NAME" : std::string(marks); +} + +// 008471c0 Draws the pockets at their size and alpha: those behind the first small, then the first with its name. A +// card shows its front (or the pickup's HUD frame), a pill its HUD frame and a pocket active its icon, the Bag of +// Crafting's table in place of a name. The Dyslexia seed scrambles the name, and Esau's second HUD sets it left of the +// pocket. The pocket sprites and the HUD's card sprite go back to full size after. Netplay's remote check of the map +// button is offline, and a TMTRAINER pocket active stops the game. +void PlayerHUD::RenderPocketItems(Vector at, PlayerHudLayout layout, float alpha, float pocketScale) +{ + Entity_Player& shown = *player; + ANM2& cards = hud->cardsPillsSprite; float size = std::abs(pocketScale); - ANM2& cardsSprite = hud->cardsPillsSprite; - cardsSprite.scale = vector_make(size, size); - cardsSprite.color._tint[3] = alpha; + cards.scale = vector_make(size, size); + cards.color._tint[3] = alpha; for (PlayerHUDPocketItem& pocket : pocketItems) { pocket.sprite.scale = vector_make(size, size); pocket.sprite.color._tint[3] = alpha; } + Entity_Player* twin = shown.twin_get(); + bool isSecondTwin = twin && twin->playerIndex != -1 && shown.playerIndex > twin->playerIndex && twin != &shown; + pockets_back_render(*this, at, layout, alpha, size); - for (PocketItem& held : player->pocketItems) - if (held.id != 0) reconstruction_missing("PlayerHUD::RenderPocketItems 008471c0: a card, pill or pocket active"); + PocketItem& held = shown.pocketItems[0]; + bool isActive = held.type == POCKET_ACTIVE; + if (isActive && held.id - 1U < ACTIVE_SLOT_COUNT && shown.activeItems[held.id - 1].item < 0) + reconstruction_missing("PlayerHUD::RenderPocketItems 008471c0: a TMTRAINER pocket active"); + ItemConfig_Card* card = held.type == POCKET_CARD ? g_manager->itemConfig.GetCard(held.id) : nullptr; + bool isShown = held.id != 0 && (!isActive || (held.id - 1U < ACTIVE_SLOT_COUNT && + g_manager->itemConfig.GetCollectible(shown.activeItems[held.id - 1].item))); + if (isShown) + { + bool isFrontShown = held.type == POCKET_CARD && !g_game->seedEffects.HasSeedEffect(SEED_MYSTERY_TAROT_CARDS) && + card_front_set(*hud, held.id); + bool isGlowing = card && (card->cardType == CARD_TAROT || card->cardType == CARD_TAROT_REVERSE) && + shown.HasCollectible(COLLECTIBLE_TAROT_CLOTH); + std::string name = pocket_name_get(shown, held); + bool isNormal = layout == HUD_LAYOUT_NORMAL; + float cardX = isFrontShown && isNormal ? CARD_FRONT_SHIFT : 0; + float textX = isNormal ? POCKET_TEXT_X : POCKET_ROW_TEXT_X; + float textY = POCKET_TEXT_Y; + Vector spot = vector_make(at.x + cardX, at.y); - cardsSprite.scale = vector_make(1, 1); + if (isActive) + { + int slot = held.id - 1; + textX += isNormal ? POCKET_ACTIVE_TEXT_SHIFT : POCKET_ROW_ACTIVE_TEXT_SHIFT; + Vector itemAt = isNormal ? vector_make(spot.x - POCKET_ACTIVE_X, spot.y - POCKET_ACTIVE_Y) + : vector_make(spot.x - POCKET_ROW_ACTIVE_X, spot.y - POCKET_ROW_ACTIVE_Y); + RenderActiveItem(slot, itemAt, isNormal ? HUD_LAYOUT_NORMAL : layout, size, alpha); + if (isNormal) textY = POCKET_SHOWN_TEXT_Y; + if (shown.activeItems[slot].item == COLLECTIBLE_BAG_OF_CRAFTING) + { + name.clear(); + Vector tableAt = isNormal ? vector_make((textX - CRAFTING_TABLE_X) * size + at.x, size * CRAFTING_TABLE_Y + at.y) + : vector_make((textX + CRAFTING_ROW_TABLE_X) * size + at.x, + size * CRAFTING_ROW_TABLE_Y + at.y); + RenderCraftingTable(tableAt, size); + } + } + else if (!isFrontShown) + { + textY = POCKET_SHOWN_TEXT_Y; + ANM2& sprite = pocketItems[0].sprite; + if (sprite.isLoaded) + { + sprite.SetFrame("HUD", 0); + sprite.Render({spot, {}, {}}); + } + } + else + { + if (isGlowing) + { + float phase = (float)g_game->frameCount * TAROT_GLOW_SPEED; + cards.color = COLOR_DEFAULT; + cards.color._tint[3] = alpha; + cards.color._offset[0] = std::sin(phase + TAROT_GLOW_RED_PHASE) * TAROT_GLOW_RED + TAROT_GLOW_RED; + cards.color._offset[1] = std::sin(phase + TAROT_GLOW_GREEN_PHASE) * TAROT_GLOW_GREEN + TAROT_GLOW_GREEN; + cards.color._offset[2] = std::sin(phase) * TAROT_GLOW_BLUE + TAROT_GLOW_BLUE; + } + bool isModdedFront = held.id >= CARD_FRONT_COUNT && card && !card->hudAnim.empty(); + if (!isModdedFront) cards.Render({spot, {}, {}}); + else if (card->moddedCardFront) + { + card->moddedCardFront->Play(card->hudAnim); + card->moddedCardFront->Render({spot, {}, {}}); + } + cards.color = COLOR_DEFAULT; + textY = POCKET_SHOWN_TEXT_Y; + } + + if (!name.empty()) + { + if (g_game->seedEffects.HasSeedEffect(SEED_DYSLEXIA)) name = string_scramble_seeded(name); + Font& font = g_manager->font9_PFTempestaSevenCondensedAgain; + float x = at.x + textX * size; + if (isNormal) x -= (float)font.GetStringWidth(name) * size; + else if (layout == HUD_LAYOUT_JACOB_ESAU && isSecondTwin) + x -= (float)font.GetStringWidth(name) * size + POCKET_SECOND_TWIN_SHIFT; + Vector shake = g_game->screenShakeOffset; + FontSettings settings; + font.DrawString(name, vector_make(x + shake.x, at.y + textY * size + shake.y), vector_make(size, size), + kcolor_rgba(1, 1, 1, alpha), settings); + } + } + + cards.scale = vector_make(1, 1); for (PlayerHUDPocketItem& pocket : pocketItems) { pocket.sprite.scale = vector_make(1, 1); diff --git a/src/player_manager.cpp b/src/player_manager.cpp index 33b1e58..e3527f6 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -1012,10 +1012,6 @@ void PlayerManager::Update() sfx.AdjustPitch(SOUND_STATIC_BUILDUP, 1); } -void PlayerManager::unlock_completion_mark(int) -{ - reconstruction_missing("PlayerManager::unlock_completion_mark 0095a7b0"); -} void PlayerManager::remove_coplayer_slot(int*, Entity_Player*) { reconstruction_missing("PlayerManager::remove_coplayer_slot 0083bc50"); diff --git a/src/rail_manager.cpp b/src/rail_manager.cpp index 082b318..46246d4 100644 --- a/src/rail_manager.cpp +++ b/src/rail_manager.cpp @@ -3,10 +3,16 @@ #include "game.h" #include "grid_entity.h" #include "log.h" +#include "npc_ai.h" #include "room.h" // The row and the columns where an L room's walls step in around its missing quarter. constexpr int L_ROW = 7; +constexpr int RAIL_TRACK_POINTS = 8; +constexpr int RAIL_TRACK_COUNT = 11; +constexpr int RAIL_DEAD_END_FIRST = 7; +constexpr int RAIL_DEAD_END_LAST = 10; +constexpr float RAIL_ALIGNMENT_WEIGHT = 10; constexpr int L_LEFT_COLUMN = 13; constexpr int L_RIGHT_COLUMN = 14; @@ -106,8 +112,85 @@ void RailManager::Render(Vector offset) } } -// 009e38a0 The point of a cell's rail nearest a minecart, for its rail following. -void RailManager::get_closest_rail_point() +// A point of a track from the cell's center. +struct RailOffset { - reconstruction_missing("RailManager::get_closest_rail_point 009e38a0"); + float x = 0; + float y = 0; +}; + +// A rail piece's track as segments from the cell's center, a SEGMENT_BREAK point separating two tracks (the crossing). +struct RailTrack +{ + int count = 0; + std::array points{}; +}; + +constexpr float RAIL_REACH = 13; +constexpr float RAIL_BEND = 4; +constexpr RailOffset SEGMENT_BREAK = {999, 999}; +constexpr std::array RAIL_TRACKS = {{ + {2, {{{-RAIL_REACH, 0}, {RAIL_REACH, 0}}}}, + {2, {{{0, -RAIL_REACH}, {0, RAIL_REACH}}}}, + {3, {{{0, RAIL_REACH}, {RAIL_BEND, RAIL_BEND}, {RAIL_REACH, 0}}}}, + {3, {{{0, RAIL_REACH}, {-RAIL_BEND, RAIL_BEND}, {-RAIL_REACH, 0}}}}, + {3, {{{0, -RAIL_REACH}, {RAIL_BEND, -RAIL_BEND}, {RAIL_REACH, 0}}}}, + {3, {{{0, -RAIL_REACH}, {-RAIL_BEND, -RAIL_BEND}, {-RAIL_REACH, 0}}}}, + {5, {{{-RAIL_REACH, 0}, {RAIL_REACH, 0}, SEGMENT_BREAK, {0, -RAIL_REACH}, {0, RAIL_REACH}}}}, + {2, {{{RAIL_REACH, 0}, {-RAIL_BEND, 0}}}}, + {2, {{{-RAIL_REACH, 0}, {RAIL_BEND, 0}}}}, + {2, {{{0, RAIL_REACH}, {0, -RAIL_BEND}}}}, + {2, {{{0, -RAIL_REACH}, {0, RAIL_BEND}}}}, +}}; + +static bool is_segment_break(RailOffset point) +{ + return point.x == SEGMENT_BREAK.x && point.y == SEGMENT_BREAK.y; +} + +// 009e38a0 The point of a cell's track nearest a minecart moving with velocity: each segment's projection, clamped to +// it where another segment joins on that side, scored by distance less how well it runs along the velocity. The +// direction turns to the travel (an odd cell keeps it when square to it). A dead end's far end counts as passed once +// reached going on. The original read past its eleven tracks for the other pieces, here they have none. +RailPoint RailManager::get_closest_rail_point(Vector position, Vector velocity, int gridIndex, int railType) +{ + RailPoint closest; + if (railType < 0 || railType >= RAIL_TRACK_COUNT) return closest; + + const RailTrack& track = RAIL_TRACKS[railType]; + Vector cell = g_game->room->GetGridPosition(gridIndex); + Vector heading = vector_normalized(velocity); + bool isDeadEnd = railType >= RAIL_DEAD_END_FIRST && railType <= RAIL_DEAD_END_LAST; + + for (int i = 0; i < track.count - 1; i++) + { + if (is_segment_break(track.points[i]) || is_segment_break(track.points[i + 1])) continue; + + RailOffset from = track.points[i]; + RailOffset to = track.points[i + 1]; + Vector start = vector_make(from.x + cell.x, from.y + cell.y); + Vector segment = vector_make(to.x - from.x, to.y - from.y); + float lengthSquared = vector_dot(segment, segment); + float t = vector_dot(vector_sub(position, start), segment) / lengthSquared; + float length = std::sqrt(lengthSquared); + Vector along = length > 0 ? vector_scale(segment, 1 / length) : segment; + float alignment = std::abs(vector_dot(along, heading)); + + bool isJoinedBefore = i > 0 && !is_segment_break(track.points[i - 1]); + bool isJoinedAfter = i < track.count - 2 && !is_segment_break(track.points[i + 2]); + if (t < 0 && isJoinedBefore) t = 0; + else if (t > 1 && isJoinedAfter) t = 1; + + Vector point = vector_add(start, vector_scale(segment, t)); + Vector gap = vector_sub(position, point); + float score = vector_dot(gap, gap) - alignment * RAIL_ALIGNMENT_WEIGHT; + if (!(score < closest.score)) continue; + + closest = {.direction = along, .point = point, .score = score, .t = t}; + } + + float travel = vector_dot(closest.direction, velocity); + closest.isPastEnd = isDeadEnd && closest.t >= 1 && travel > 0; + if (travel < 0 || (travel == 0 && !(gridIndex & 1))) closest.direction = vector_scale(closest.direction, -1); + return closest; } diff --git a/src/rail_manager.h b/src/rail_manager.h index 21adf7e..c48eb8b 100644 --- a/src/rail_manager.h +++ b/src/rail_manager.h @@ -25,6 +25,18 @@ constexpr uint8_t RAIL_VERTICAL = 1; constexpr uint8_t RAIL_END_UP = 9; constexpr uint8_t RAIL_END_DOWN = 10; +// Where a rail cell's track runs nearest a position: the point, the track's direction along the way it is travelled, +// how far along its segment the point lies, how close it is (lower is closer, favouring a segment along the travel) +// and whether a dead end's far end was passed. +struct RailPoint +{ + Vector direction{}; + Vector point{}; + float score = 1e16f; + float t = 0; + bool isPastEnd = false; +}; + // Construction, copies and destruction (009e27c0) are the defaults. // The rails of a room (Room's railManager, Lua's Room:GetRail): a rail piece byte per grid cell, the walls' bumpers // around the floor, and the sprite each piece draws from by its frame. @@ -35,5 +47,5 @@ struct RailManager void init(); void Render(Vector offset); - void get_closest_rail_point(); + RailPoint get_closest_rail_point(Vector position, Vector velocity, int gridIndex, int railType); }; diff --git a/src/room.cpp b/src/room.cpp index e88a91f..14e57bb 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -10,11 +10,14 @@ #include "log.h" #include "lua_engine.h" #include "manager.h" +#include "menu_options.h" +#include "mines.h" #include "room_render.h" #include "seeds.h" #include "texture_cache.h" #include #include +#include extern "C" { @@ -198,9 +201,8 @@ constexpr int ROOM_MIRROR_IDX = -100; constexpr int ROOM_MINESHAFT_IDX = -101; constexpr int ACHIEVEMENT_MEGA_SATAN = 155; -// The effects pressure plates and rain spawn, and a minecart enemy on its rail. +// The effects pressure plates and rain spawn, and a minecart on its rail. constexpr int EFFECT_RAIN_DROP = 135; -constexpr int MINECART_ENEMY = 10; constexpr int MINECART_VERTICAL = 4; constexpr float MINECART_SPEED = 0.2f; @@ -367,6 +369,22 @@ static void room_reset(Room& room) room.floorColor = COLOR_DEFAULT; } +// The banner a miniboss room shows while its miniboss lives: the first player (with a twin, both, joined by "+") +// against the miniboss, like "Jacob+Esau VS Sloth". Tainted Forgotten and Lazarus show their own name alone. +static void miniboss_title_show(RoomConfig_Room& config) +{ + constexpr std::string_view VERSUS_KEY = "#VS"; + Entity_Player& player = *g_game->GetPlayer(0); + Entity_Player* twin = player.twin_get(); + bool isAlone = !twin || player.playerType == PLAYER_THEFORGOTTEN_B || player.playerType == PLAYER_LAZARUS_B || + player.playerType == PLAYER_LAZARUS2_B; + std::string miniboss = g_game->roomConfig.GetMinibossName((uint32_t)config.subtype); + std::string title = player.name + (isAlone ? "" : "+" + twin->name); + + title += " " + std::string(string_table_translate(g_manager->stringTable, VERSUS_KEY)) + " " + miniboss; + g_game->hud.ShowStackedItemTextCustom(title.c_str(), ""); +} + // 007f2800 Enters a room: resets what a visit keeps, lays out the config's grid, doors, walls and entities from the // descriptor's seeds (what a past visit saved restored on top), floods, darkens or tints it as its backdrop and // flags say, decorates a first visit, and sets the camera on it. @@ -536,8 +554,7 @@ void Room::Init(RoomConfig_Room& config, RoomDescriptor& roomDescriptor) if (GetAliveEnemiesCount() < 1 && roomClearDelay == 0 && !IsClear() && g_game->deathmatchManager.state < DEATHMATCH_INTRO) descriptor->flags |= ROOM_DESCRIPTOR_FLAG_CLEAR; - if (!IsClear() && config.type == ROOM_MINIBOSS) - reconstruction_missing("Room::Init 007f2800: a miniboss's versus title (HUD::ShowStackedItemTextCustomUTF16)"); + if (!IsClear() && config.type == ROOM_MINIBOSS) miniboss_title_show(config); if (IsClear()) isDeathsListDone = true; isRedHeartDamaged = false; init_rain(); @@ -1441,7 +1458,9 @@ Vector Room::GetCenterPos() return room.GetGridPosition(centerIndex); } -// 0081e9d0 A random position on the floor a margin inside it. +// 0081e9d0 A random position on the floor a margin inside it. An L-shaped room picks one of its two rectangles, +// weighed by their areas, split at the narrower one's edge. There the margin widens the rectangles instead, as in the +// original. Vector Room::GetRandomPosition(float margin) { if (!IsLShapedRoom()) @@ -1452,18 +1471,51 @@ Vector Room::GetRandomPosition(float margin) (bottomRightPos.y - topLeftPos.y) * y + topLeftPos.y); return GetClampedPositionImpl(position, margin, margin, margin, margin); } - reconstruction_missing("Room::GetRandomPosition 0081e9d0: L-shaped rooms"); + + LRoomAreaDesc areas = GetLRoomAreaDesc(); + float leftA = areas.topLeftA.x - margin; + float leftB = areas.topLeftB.x - margin; + float topA = areas.topLeftA.y - margin; + float widthA = (areas.bottomRightA.x + margin) - leftA; + float widthB = (areas.bottomRightB.x + margin) - leftB; + float split = widthA < widthB ? areas.topLeftB.y - margin : areas.bottomRightA.y + margin; + float heightA = split - topA; + float heightB = (areas.bottomRightB.y + margin) - split; + float areaA = std::abs(heightA * widthA); + bool isFirst = random_unit() < areaA / (std::abs(heightB * widthB) + areaA); + + float x = random_unit(); + float y = random_unit(); + if (isFirst) return vector_make(widthA * x + leftA, y * heightA + topA); + return vector_make(widthB * x + leftB, y * heightB + split); } -// 0081ecc0 A random floor cell from a seed. L-shaped rooms are not reconstructed yet. +// 0081ecc0 (with LRoomTileDesc::GetRandomTile 0081fb70) A random floor cell from a seed. An L-shaped room first +// picks one of its two rectangles, weighed by their areas. The far row and column are never picked. int Room::GetRandomTileIndex(uint32_t seed) { - if (IsLShapedRoom()) reconstruction_missing("Room::GetRandomTileIndex 0081ecc0: L-shaped rooms (LRoomTileDesc)"); - LRoomTileDesc tiles = GetLRoomTileDesc(); RNG rng = {seed, 1, 9, 29}; - int column = (int)rng.RandomInt(tiles.bottomRightAX - tiles.topLeftAX) + tiles.topLeftAX; - int row = (int)rng.RandomInt(tiles.bottomRightAY - tiles.topLeftAY) + tiles.topLeftAY; + int left = tiles.topLeftAX; + int top = tiles.topLeftAY; + int width = tiles.bottomRightAX - left; + int height = tiles.bottomRightAY - top; + + if (IsLShapedRoom()) + { + int widthB = tiles.bottomRightBX - tiles.topLeftBX; + int heightB = tiles.bottomRightBY - tiles.topLeftBY; + uint32_t areaA = (uint32_t)std::abs(width * height); + if (rng.RandomInt(areaA + (uint32_t)std::abs(widthB * heightB)) >= areaA) + { + left = tiles.topLeftBX; + top = tiles.topLeftBY; + width = widthB; + height = heightB; + } + } + int column = (int)rng.RandomInt(width) + left; + int row = (int)rng.RandomInt(height) + top; return GetGridIndexByTile(column, row); } @@ -2451,10 +2503,10 @@ void Room::attach_minecarts() for (size_t i = 0; i < entityList.updateEL.size(); i++) { Entity& entity = *entityList.updateEL[i]; - bool isCart = entity.type == ENTITY_MINECART && entity.variant == MINECART_ENEMY; + bool isCart = entity.type == ENTITY_MINECART && entity.variant == MINECART_VARIANT_ENTRANCE; bool isEnemy = (g_game->deathmatchManager.is_active() && entity.type == ENTITY_PLAYER) || (entity.type >= ENTITY_FIRST_ENEMY && entity.type < ENTITY_EFFECT); - bool isRider = !(entity.type == ENTITY_MINECART && entity.variant == 0) && !entity.minecart; + bool isRider = !(entity.type == ENTITY_MINECART && entity.variant == MINECART_VARIANT_RIDDEN) && !entity.minecart; if (!isEnemy || entity.spawnGridIndex < 0 || (!isRider && !isCart)) continue; int column = entity.spawnGridIndex % gridWidth; diff --git a/src/room.h b/src/room.h index 99ae179..154e9fe 100644 --- a/src/room.h +++ b/src/room.h @@ -75,6 +75,13 @@ enum BrokenWatchState : int BROKEN_WATCH_FAST }; +// Whether RemoveGridEntity leaves a decoration where it is. +enum DecorationRemoval +{ + DECORATION_REMOVED, + DECORATION_KEPT +}; + // The world rectangle of an L-shaped room's two arms (REPENTOGON's LRoomAreaDesc). struct LRoomAreaDesc { @@ -333,6 +340,7 @@ public: void MakeDoor(int slot); void make_walls(); bool SpawnGridEntity(int gridIndex, GridEntityType type, int variant, uint32_t seed, int varData); + void RemoveGridEntity(int gridIndex, int pathTrail, DecorationRemoval removal); 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 d1802ea..ccac9c5 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -30,7 +30,6 @@ constexpr int COLLECTIBLE_GUPPYS_TAIL = 134; constexpr int COLLECTIBLE_CONTRACT_FROM_BELOW = 241; constexpr int COLLECTIBLE_THERES_OPTIONS = 249; constexpr int COLLECTIBLE_DEEP_POCKETS_CLEAR = 416; -constexpr int COLLECTIBLE_GLYPH_OF_BALANCE = 464; constexpr int COLLECTIBLE_BROKEN_SHOVEL_2 = 551; constexpr int COLLECTIBLE_OPTIONS = 670; constexpr int COLLECTIBLE_SWARM = 693; @@ -59,8 +58,6 @@ constexpr int ACHIEVEMENT_LITTLE_CHAD = 25; constexpr int ACHIEVEMENT_LITTLE_GISH = 23; constexpr int ACHIEVEMENT_LITTLE_STEVEN = 24; constexpr int ACHIEVEMENT_BOOK_OF_REVELATIONS = 7; -constexpr int EVENT_COUNTER_LAMB_KILLS = 25; -constexpr int EVENT_COUNTER_BOSSRUSHS_CLEARED = 111; constexpr int ULTRA_GREED_BOSS = 62; constexpr int BABY_PLUM_BOSS = 84; constexpr int GREED_WAVES = 10; @@ -76,6 +73,12 @@ constexpr uint32_t VOID_PORTAL_ODDS = 20; constexpr int VOID_PORTAL_ITEMS = 20; constexpr float VOID_PORTAL_DAMAGE = 100; constexpr float VOID_PORTAL_SPREAD = 80; + +// Mom's Heart opens a Void portal one kill in 10. The Womb's ways on open 40 to each side of the middle, at y 280. +constexpr uint32_t HEART_VOID_PORTAL_ODDS = 10; +constexpr float WOMB_EXIT_SPACING = 40; +constexpr float WOMB_EXIT_ROW = 280; + constexpr int ACHIEVEMENT_MONSTROS_LUNG = 13; constexpr int ACHIEVEMENT_LIL_CHUBBY = 14; constexpr int ACHIEVEMENT_STEVEN = 16; @@ -832,6 +835,16 @@ static void moms_items_spawn(Room& room, ClearAward& award) } } +// A Void portal (a trapdoor) opens on a free cell 80 out from the reward. +static void void_portal_spawn(Room& room, ClearAward& award) +{ + int gridIndex = room.GetGridIndex(room_free_pickup_position_find({.position = award.reward, + .step = VOID_PORTAL_SPREAD, + .isAvoidActiveEntities = true})); + room_spawn_cell_clear(room, gridIndex); + room.SpawnGridEntity(gridIndex, GRID_TRAPDOOR, 0, Random(), TRAPDOOR_VOID_PORTAL); +} + // One Mom kill in 20 opens a Void portal beside the reward, on a run that may reach the Void with 20 items or 100 // damage on a main player. static void moms_void_portal_roll(Room& room, ClearAward& award) @@ -846,12 +859,7 @@ static void moms_void_portal_roll(Room& room, ClearAward& award) } if (award.rng.RandomInt(VOID_PORTAL_ODDS) != 0 || (items < VOID_PORTAL_ITEMS && damage <= VOID_PORTAL_DAMAGE)) return; - - int gridIndex = room.GetGridIndex(room_free_pickup_position_find({.position = award.reward, - .step = VOID_PORTAL_SPREAD, - .isAvoidActiveEntities = true})); - room_spawn_cell_clear(room, gridIndex); - room.SpawnGridEntity(gridIndex, GRID_TRAPDOOR, 0, Random(), TRAPDOOR_VOID_PORTAL); + void_portal_spawn(room, award); } // Mom's floor's last boss: her first kill ends the run with her ending and unlocks the Womb (unless a challenge goes @@ -886,6 +894,91 @@ static void moms_award_spawn(Room& room, ClearAward& award, bool isContinuing) for (int achievement : MOM_UNLOCKS) data.TryUnlock(achievement); } +// 007fa0e0 Room::clear_grid_for_pickup: destroys what stands on a cell (a poop left standing is trodden and taken +// away next update) and trades a cell that still collides for a free one, or -1 off the grid. +static void pickup_cell_clear(Room& room, int& gridIndex) +{ + if ((uint32_t)gridIndex < ROOM_GRID_CELLS && room.gridEntities[gridIndex]) spawn_cell_destroy(gridIndex); + GridEntity* standing = (uint32_t)gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + if (standing && standing->type == GRID_POOP) + { + room.gridPaths[gridIndex] = GRID_PATH_TRODDEN; + room.pendingGridRemovals.insert(gridIndex); + } + if (room.GetGridCollision(gridIndex) == COLLISION_NONE) return; + gridIndex = room.GetGridIndex(room_free_pickup_position_find({.position = room.GetGridPosition(gridIndex)})); +} + +// The way on from the Womb's or the Blue Womb's last boss: a trapdoor to Sheol left of the middle and a light to the +// Cathedral right of it, as the run's end allows, or a trophy at a challenge's end. +static void womb_exits_spawn(Room& room, ClearAward& award, bool isContinuing) +{ + Game& game = *g_game; + if (!isContinuing) + { + Vector spot = award.reward; + reward_spot_clear(room, spot); + game.Spawn({.position = spot, .type = ENTITY_PICKUP, .variant = PICKUP_TROPHY, .seed = Random()}); + return; + } + + Vector center = Room::GetCenterPos(); + if (Level::IsStageWithinEnd(STAGE_SHEOL, false)) + { + int gridIndex = room.GetGridIndex(vector_make(center.x - WOMB_EXIT_SPACING, WOMB_EXIT_ROW)); + room_spawn_cell_clear(room, gridIndex); + room.SpawnGridEntity(gridIndex, GRID_TRAPDOOR, 0, Random(), 0); + } + if (!Level::IsStageWithinEnd(STAGE_SHEOL, true)) return; + int gridIndex = room.GetGridIndex(vector_make(center.x + WOMB_EXIT_SPACING, WOMB_EXIT_ROW)); + pickup_cell_clear(room, gridIndex); + uint32_t seed = Random(); + game.Spawn({.position = room.GetGridPosition(gridIndex), .type = ENTITY_EFFECT, + .variant = EFFECT_HEAVEN_LIGHT_DOOR, .seed = seed}); +} + +// The Womb's last boss (Mom's Heart or It Lives) and the Blue Womb's (Hush). Until It Lives is unlocked (until Hush +// is first beaten), a big chest ends the run unless a challenge goes on past here (a trophy at a challenge's end). +// Otherwise the ways on open. Mom's Heart counts the kill, marks the character's completion and one time in 10 opens +// a Void portal. Hush marks it, unlocks the Void and ends the Blue Womb. +static void womb_award_spawn(Room& room, ClearAward& award, int stage, bool isContinuing) +{ + Game& game = *g_game; + PersistentGameData& data = g_manager->persistentGameData; + ChallengeParam& params = game.GetChallengeParams(); + bool isEarlyKill = stage == STAGE_WOMB_II ? !data.Unlocked(ACHIEVEMENT_IT_LIVES) + : data.eventCounters[EVENT_COUNTER_HUSH_KILLS] == 0; + bool isEndingAllowed = !params.isPathTypeSet || (!params.isMegaSatan && params.endStage <= stage); + + if (isEarlyKill && isEndingAllowed) + { + Vector spot = award.reward; + reward_spot_clear(room, spot); + if (!isContinuing) + game.Spawn({.position = spot, .type = ENTITY_PICKUP, .variant = PICKUP_TROPHY, .seed = Random()}); + else + { + g_manager->achievementOverlay.isPopupBlocked = true; + game.Spawn({.position = spot, .type = ENTITY_PICKUP, .variant = PICKUP_BIGCHEST, .seed = award.rng.Next()}); + } + } + else womb_exits_spawn(room, award, isContinuing); + + if (stage == STAGE_BLUE_WOMB) + { + PlayerManager::unlock_completion_mark(COMPLETION_HUSH); + data.IncreaseEventCounter(EVENT_COUNTER_HUSH_KILLS, 1); + data.TryUnlock(ACHIEVEMENT_THE_VOID); + game.gameStateFlags |= 1ull << GAME_STATE_BLUEWOMB_DONE; + return; + } + data.IncreaseEventCounter(EVENT_COUNTER_MOM_KILLS, 1); + PlayerManager::unlock_completion_mark(COMPLETION_MOMS_HEART); + if (award.rng.RandomInt(HEART_VOID_PORTAL_ODDS) == 0 && isContinuing && is_void_reachable() && + params.endStage != STAGE_VOID) + void_portal_spawn(room, award); +} + // The kill records a boss clear keeps: each floor's boss kills (Steven, Chad and Gish at 40 Basement, 30 Caves and // 20 Depths kills), the first Monstro's Lung, Lil Chubby and angel unlocks, and the no-damage runs to a last boss. static void boss_kill_records(int stage, bool isLastBoss) @@ -927,7 +1020,7 @@ static int boss_stage_get() } // A boss room's award: Boss Rush's records, the pits some layouts fill, the co-op ghosts revived at the last boss, -// the trapdoor and the boss's items. The final bosses' endings are not reconstructed yet. +// the trapdoor and the boss's items. The endings past the Womb are not reconstructed yet. static void boss_award_spawn(Room& room, ClearAward& award) { Game& game = *g_game; @@ -965,6 +1058,8 @@ static void boss_award_spawn(Room& room, ClearAward& award) } else if (isMomsFloor) boss_items_spawn(room, award); else if (stage == STAGE_DEPTHS_II && room.bossId != BOSS_MEGA_SATAN_ID) moms_award_spawn(room, award, isContinuing); + else if ((stage == STAGE_WOMB_II || stage == STAGE_BLUE_WOMB) && room.bossId != BOSS_MEGA_SATAN_ID) + womb_award_spawn(room, award, stage, isContinuing); else reconstruction_missing("Room::SpawnClearAward 007fb250: the final bosses' endings and chests"); boss_kill_records(stage, isLastBoss); } diff --git a/src/room_config.cpp b/src/room_config.cpp index b42dbbf..a66a59e 100644 --- a/src/room_config.cpp +++ b/src/room_config.cpp @@ -32,6 +32,7 @@ constexpr char STB_MAGIC[] = "STB1"; constexpr int STB_MAGIC_SIZE = 4; constexpr std::string_view STAGES_CATEGORY = "Stages"; constexpr std::string_view CURSES_CATEGORY = "Curses"; +constexpr std::string_view MINIBOSSES_CATEGORY = "Minibosses"; constexpr std::string_view GENERATED_ROOM_NAME = "generated"; constexpr char LOCALIZED_KEY_PREFIX = '#'; constexpr int CURSE_SLOTS = 9; @@ -54,7 +55,6 @@ constexpr float PICKED_WEIGHT_MIN = 1e-7f; constexpr uint32_t ENTITY_CONSTANT_STONE_SHOOTER = 202; constexpr uint32_t ENTITY_QUAKE_GRIMACE = 804; constexpr uint32_t ENTITY_SPIKEBALL = 852; -constexpr uint32_t ENTITY_CYST = 862; constexpr uint32_t ENTITY_DUSTY_DEATHS_HEAD = 887; constexpr uint32_t ENTITY_ENVIRONMENT = 970; constexpr short ROOM_GRID_WIDTH = 13; @@ -836,6 +836,14 @@ std::string RoomConfig::GetCurseName(uint32_t curseIndex) return localized_get(CURSES_CATEGORY, curses[curseIndex].displayName, LANGUAGE_CURRENT); } +// Part of 007f2800 A miniboss's name by its room subtype, its #key looked up in the "Minibosses" string table. Empty +// for a subtype past the table. +std::string RoomConfig::GetMinibossName(uint32_t subtype) +{ + if (subtype >= MINIBOSS_SLOTS) return ""; + return localized_get(MINIBOSSES_CATEGORY, minibosses[subtype].displayName, LANGUAGE_CURRENT); +} + // 0082d030 The stage id of a floor: its level stage and stage type (4 and 5 the alternate paths), in Greed's // numbering when the mode (or the game's difficulty) is Greed's. Unsigned wrapping is the original's. int RoomConfig::GetStageID(int levelStage, int stageType, RoomMode mode) diff --git a/src/room_config.h b/src/room_config.h index 023828a..8526784 100644 --- a/src/room_config.h +++ b/src/room_config.h @@ -207,6 +207,7 @@ public: std::string GetStageDisplayName(int stageId, int language); std::string GetCurseName(uint32_t curseIndex); + std::string GetMinibossName(uint32_t subtype); static int GetStageID(int levelStage, int stageType, RoomMode mode); static int room_type_find(std::string_view name); static int get_door_from_position(short x, short y, RoomShape shape); diff --git a/src/room_grid.cpp b/src/room_grid.cpp index 54e796a..5ecfe96 100644 --- a/src/room_grid.cpp +++ b/src/room_grid.cpp @@ -233,3 +233,14 @@ Vector room_free_tile_position_find(const Vector& position, float distanceThresh } return best; } + +// 0081e930 Queues the grid entity on a cell for removal at the room's next update, leaving the cell's path at +// pathTrail. A decoration stays when asked to. +void Room::RemoveGridEntity(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; + pendingGridRemovals.insert(gridIndex); +} diff --git a/src/room_render.cpp b/src/room_render.cpp index 12ac739..534bb09 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -3,6 +3,7 @@ #include "entity_player.h" #include "entity_tear.h" #include "game.h" +#include "gl.h" #include "grid_entity_door.h" #include "grid_entity_rock.h" #include "log.h" @@ -32,6 +33,17 @@ constexpr int ROOM_SURFACE_HEIGHT = 468; constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; constexpr const char* SHOCKWAVE_SHADER = "Shockwave"; +// The effect surfaces' shaders: the Utero water overlay's and the Beast's heat wave's ripple once a second, dizziness +// and the mirror world wave over 600 frames, two steps a frame. Their Ratio gives the texture in screen points of 1024. +constexpr const char* DIZZY_SHADER = "Dizzy"; +constexpr const char* HEAT_WAVE_SHADER = "HeatWave"; +constexpr const char* MIRROR_SHADER = "Mirror"; +constexpr const char* WATER_OVERLAY_SHADER = "WaterOverlay"; +constexpr int OVERLAY_FRAMES = 60; +constexpr int SURFACE_WAVE_FRAMES = 600; +constexpr float SURFACE_WAVE_STEPS = 120; +constexpr float SURFACE_RATIO_POINTS = 1024; + // The Shockwave shader's ripple scale for a 520 by 280 screen, the fade of a wave's strength over its duration, and // the place it gives a wave that is not running. constexpr float SHOCKWAVE_RATIO_X = 0.66015625f; @@ -60,6 +72,16 @@ constexpr KColor BLACK = kcolor_rgba(0, 0, 0, 1); constexpr KColor GREED_FLOOR_COLOR = kcolor_rgba(0.2784314f, 0.18039216f, 0.101960786f, 1); constexpr KColor SHADOW_TINT = kcolor_rgba(1, 1, 1, 0.24f); constexpr KColor LIGHTNING_TINT = kcolor_rgba(0.85f, 0.9f, 1, 1); +constexpr KColor MAGENTA = kcolor_rgba(1, 0, 1, 1); +constexpr float TEXEL_CHANNEL_MAX = 255; + +// A step in ash erases a 20 wide patch of the floor's second surface by a quarter. +constexpr float ASH_STEP_SIZE = 20; +constexpr KColor ASH_STEP_TINT = kcolor_rgba(1, 1, 1, 0.24f); +constexpr KAGE::Graphics::BlendMode ASH_ERASE_BLEND = {KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_ZERO, + KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA, + KAGE::Graphics::FACTOR_ZERO, + KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA}; constexpr ColorMod NIGHT_LIGHT_COLOR = {{1, 1, 1, 0.2f}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod GLOW_COLOR = {{0.4f, 0.6f, 1, 0}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod BABY_GLOW_COLOR = {{1, 1, 0.9f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; @@ -825,13 +847,141 @@ static Vector surface_texcoord_get(Room& room, Vector world, const KAGE::Graphic (float)surface.height / g_screenHeight * screen.y / (float)surface.textureHeight); } -// Draws the room into its shockwave surface until shockwave_surface_resolve. -static void shockwave_surface_begin() +// 00a69700 (an image's texel read, slot 11 of its table) The color of an image's texel, read back from its texture +// through a framebuffer: white past its edges, opaque for an RGB image, magenta for a format without texels. An +// indexed image is read as RGB after a complaint, as the original does. +KColor image_texel_get(KAGE::Graphics::ImageBase& image, uint32_t x, uint32_t y) +{ + if (x >= (uint32_t)image.width || y >= (uint32_t)image.height) return WHITE; + + std::array texel = {}; + KAGE::Graphics::manager.render_target_push(&image, KAGE::Graphics::TARGET_OWN_SIZE, KAGE::Graphics::PRESENT_FLUSH); + gl.ReadPixels((GLint)x, (GLint)y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, texel.data()); + KAGE::Graphics::manager.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); + + if (image.format == KAGE::Graphics::IMAGE_INDEXED) + log_printf(LOG_ERROR, "Cannot get texel color from an indexed texture\n"); + else if (image.format != KAGE::Graphics::IMAGE_RGB && image.format != KAGE::Graphics::IMAGE_RGBA) return MAGENTA; + float alpha = image.format == KAGE::Graphics::IMAGE_RGBA ? texel[3] / TEXEL_CHANNEL_MAX : 1; + return kcolor_rgba(texel[0] / TEXEL_CHANNEL_MAX, texel[1] / TEXEL_CHANNEL_MAX, texel[2] / TEXEL_CHANNEL_MAX, alpha); +} + +// Part of 007b8cb0 (Entity_Player::update_footprints) A step in ash: the ash mask wipes a patch 20 wide a quarter of +// the way clear of the floor's second surface under the foot. +void room_ash_step_clear(Room& room, Vector foot) { KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; - graphics.render_target_push(roomSurfaces.shockwave.get(), KAGE::Graphics::TARGET_SCREEN_SIZE, + float pixelScale = g_displayPixelRatio * g_screenPointScale; + auto snap = [pixelScale](float value) { return std::floor(value * pixelScale + 0.5f) / pixelScale; }; + + graphics.render_target_push(room.backdrop.floorSurface2.get(), KAGE::Graphics::TARGET_OWN_SIZE, KAGE::Graphics::PRESENT_FLUSH); - graphics.Clear(); + KAGE::Graphics::BlendMode saved = graphics.blendMode; + graphics.blendMode = ASH_ERASE_BLEND; + + Vector screen = render_position_get(foot, RENDER_SNAPPED); + float half = ASH_STEP_SIZE * 0.5f; + Vector corner = vector_make(screen.x - snap(room.renderSurfaceTopLeft.x) - half, + screen.y - snap(room.renderSurfaceTopLeft.y) - half); + shader_select(COLOR_OFFSET_SHADER); + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *roomSurfaces.ashMask); + roomSurfaces.ashMask->Render( + KAGE::Graphics::color_quad_rect(corner, vector_make(ASH_STEP_SIZE, ASH_STEP_SIZE), WHITE), + ASH_STEP_TINT); + + graphics.render_target_pop(KAGE::Graphics::PRESENT_FINISH); + graphics.blendMode = saved; + graphics.shader_default_set(); +} + +// Draws the room into one of its effect surfaces, the screen's size, until that surface's resolve. +static void effect_surface_begin(KAGE::Graphics::ImagePtr& surface) +{ + surface_begin(surface, KAGE::Graphics::TARGET_SCREEN_SIZE); + KAGE::Graphics::manager.blend_set(KAGE::Graphics::BLEND_NORMAL); +} + +// The whole of a surface as a source quad, in fractions of it. +static SourceQuad whole_source_quad() +{ + SourceQuad whole = KAGE::Graphics::source_quad_rect({}, vector_make(1, 1)); + whole._coordinateSpace = KAGE::Graphics::COORDINATES_NORMALIZED; + return whole; +} + +// Ends an effect surface and makes its shader current (the current one stays when it is not loaded), giving it the +// surface's Ratio: the texture in screen points of 1024, and the room floor's corner on the screen, scrolled and +// shaken, as a fraction of the texture. With a wave it also gets the texture's used share and the wave's time: two +// steps a frame over 600 frames, the half step between updates while the game runs. +static KAGE::Graphics::Shader* effect_surface_end(Room& room, KAGE::Graphics::ImageBase& surface, const char* shader, + bool isWave) +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + float points = g_screenPointScale * SURFACE_RATIO_POINTS; + float textureWidth = (float)surface.textureWidth; + float textureHeight = (float)surface.textureHeight; + Vector scroll = vector_add(room.renderScrollOffset, g_game->screenShakeOffset); + Vector corner = vector_add(scroll, render_position_get(room.topLeftPos, RENDER_SNAPPED)); + std::array ratio = {textureWidth / points, textureHeight / points, + corner.x * g_screenPointScale / textureWidth, + corner.y * g_screenPointScale / textureHeight}; + + surface_end(); + graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); + shader_select(shader); + KAGE::Graphics::Shader* current = graphics.currentShader; + if (!current) return nullptr; + + if (isWave) + { + std::array textureSize = {(float)surface.width / textureWidth, (float)surface.height / textureHeight}; + int halfStep = g_game->IsPaused() ? 0 : (int)((g_manager->framecount + 1) % 2); + float time = (float)(halfStep + g_game->frameCount % SURFACE_WAVE_FRAMES * 2) / SURFACE_WAVE_STEPS; + current->set_uniform("TextureSize", KAGE::Graphics::UNIFORM_VEC2, textureSize.data()); + current->set_uniform("Ratio", KAGE::Graphics::UNIFORM_VEC4, ratio.data()); + current->set_uniform("Time", KAGE::Graphics::UNIFORM_FLOAT, &time); + } + else current->set_uniform("Ratio", KAGE::Graphics::UNIFORM_VEC4, ratio.data()); + return current; +} + +// Draws the Utero water overlay's or the Beast's heat wave's surface back over the screen, rippling once a second. +static void overlay_surface_resolve(Room& room, KAGE::Graphics::ImagePtr& surface, const char* shader) +{ + float amount = (float)(g_game->frameCount % OVERLAY_FRAMES) / (float)OVERLAY_FRAMES; + if (KAGE::Graphics::Shader* current = effect_surface_end(room, *surface, shader, false)) + current->set_uniform("Amount", KAGE::Graphics::UNIFORM_FLOAT, &amount); + surface->Render(whole_source_quad(), screen_quad(WHITE), WHITE); + KAGE::Graphics::manager.shader_default_set(); +} + +// Draws the dizzy surface back over the screen, swaying and tinted as strongly as the dizziness. +static void dizzy_surface_resolve(Room& room, float dizziness) +{ + KAGE::Graphics::ImageBase& surface = *roomSurfaces.dizzy; + if (KAGE::Graphics::Shader* current = effect_surface_end(room, surface, DIZZY_SHADER, true)) + current->set_uniform("Amount", KAGE::Graphics::UNIFORM_FLOAT, &dizziness); + surface.Render(whole_source_quad(), screen_quad(WHITE), WHITE); +} + +// Draws the mirror world's surface back over the screen flipped sideways, waving through the Mirror shader with the +// water overlay on, else plainly through the color offset shader. +static void mirror_surface_resolve(Room& room) +{ + KAGE::Graphics::ImageBase& surface = *roomSurfaces.mirror; + SourceQuad flipped = whole_source_quad(); + std::swap(flipped._topLeft, flipped._topRight); + std::swap(flipped._bottomLeft, flipped._bottomRight); + + if (g_manager->optionsConfig.render.isWaterOverlayEnabled) effect_surface_end(room, surface, MIRROR_SHADER, true); + else + { + surface_end(); + KAGE::Graphics::manager.blend_set(KAGE::Graphics::BLEND_NORMAL); + shader_select(COLOR_OFFSET_SHADER); + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, surface); + } + surface.Render(flipped, screen_quad(WHITE), WHITE); } // Draws the shockwave surface back over the cleared screen through the Shockwave shader, rippling at the room's two @@ -876,10 +1026,7 @@ static void shockwave_surface_resolve(Room& room, Vector surfaceOffset) shader->set_uniform("Shockwave2", KAGE::Graphics::UNIFORM_VEC4, waves[1].data()); shader->set_uniform("Ratio", KAGE::Graphics::UNIFORM_VEC2, ratio.data()); } - SourceQuad whole = KAGE::Graphics::source_quad_rect({}, vector_make(1, 1)); - whole._coordinateSpace = KAGE::Graphics::COORDINATES_NORMALIZED; - Vector screenSize = vector_make(g_screenWidth, g_screenHeight); - surface.Render(whole, KAGE::Graphics::color_quad_rect({}, screenSize, WHITE), WHITE); + surface.Render(whole_source_quad(), screen_quad(WHITE), WHITE); graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); } @@ -887,9 +1034,9 @@ static void shockwave_surface_resolve(Room& room, Vector surfaceOffset) // the doors, shading and shadows, the players' glows, the grid entities and entities by depth, the players' extra // bodies and Night Lights, the lighting overlay, the foreground and overlay layers, and the Ashpit's dust. Retro // Vision or the game's pixelation timer pixelate the sprites meanwhile, and Dataminer garbles them. -// With shockwaves running the room draws through the shockwave surface, rippled back onto the screen. The other effect -// surfaces (the mirror world's, dizziness, Utero's water overlay and the Beast's heat wave), the water surface and the -// debug overlays are not reconstructed yet. +// The room draws through effect surfaces, each drawn back onto the screen through its shader: the mirror world's +// (flipped), dizziness, the shockwaves' ripples, Utero's water overlay and the Beast's heat wave. The water surface and +// the debug overlays are not reconstructed yet. void Room::Render() { KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; @@ -903,26 +1050,32 @@ void Room::Render() bool isHeatWave = backdropType == BACKDROP_DUNGEON_BEAST && render.isWaterOverlayEnabled; bool isShockwaveSurface = render.isShockwaveEnabled && is_shockwave_active(); bool isWaterShown = waterAmount > 0 && render.isWaterSurfaceEnabled; + float dizziness = game.dizzyIntensity; + bool isAnySurface = isMirrorWorld || dizziness > 0 || isShockwaveSurface || isUteroSurface || isHeatWave; Vector surfaceOffset = vector_add(vector_add(renderSurfaceTopLeft, game.screenShakeOffset), renderScrollOffset); spriteShaderParams.pixelationAmount = pixelation_amount(game); if (isDataminer) DAT_00c7977f = 1; - if (isMirrorWorld || game.dizzyIntensity > 0 || isUteroSurface || isHeatWave) - reconstruction_missing("Room::Render 0080f200: the mirror, dizzy and water overlay surfaces"); - if (isShockwaveSurface) shockwave_surface_begin(); + if (isMirrorWorld) effect_surface_begin(roomSurfaces.mirror); + if (dizziness > 0) effect_surface_begin(roomSurfaces.dizzy); + if (isShockwaveSurface) effect_surface_begin(roomSurfaces.shockwave); + if (isUteroSurface) effect_surface_begin(roomSurfaces.waterOverlay); + if (isHeatWave) effect_surface_begin(roomSurfaces.heatWave); if (backdropType == BACKDROP_DUNGEON_BEAST) render_beast_arena_background(&beastArena, BEAST_PASS_BACKGROUND); graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); fxLayers.behind_layers_render(); - if (!isShockwaveSurface) floor_quad_render(*this, surfaceOffset); + if (!isAnySurface) floor_quad_render(*this, surfaceOffset); if (!render.isShockwaveEnabled && !IsClear()) shockwaves_radial_render(*this, renderScrollOffset); KAGE::Graphics::BlendMode floorBlend = graphics.blendMode; floor_render(*this, surfaceOffset, isWaterShown); if (roomType != ROOM_DUNGEON) walls_render(*this, surfaceOffset, isWaterShown, floorBlend); entityList.render_up_to(DEPTH_GRID, renderScrollOffset); + if (isHeatWave) overlay_surface_resolve(*this, roomSurfaces.heatWave, HEAT_WAVE_SHADER); if (backdropType == BACKDROP_DUNGEON_BEAST) render_beast_arena_background(&beastArena, BEAST_PASS_ENTITIES); doors_shading_render(*this, surfaceOffset); + if (isUteroSurface) overlay_surface_resolve(*this, roomSurfaces.waterOverlay, WATER_OVERLAY_SHADER); lightSprite.color = COLOR_DEFAULT; litGridIndices.clear(); @@ -941,6 +1094,8 @@ void Room::Render() if (isShockwaveSurface) shockwave_surface_resolve(*this, surfaceOffset); if (isDataminer) DAT_00c7977f = 0; fxLayers.overlay_layers_render(); + if (dizziness > 0) dizzy_surface_resolve(*this, dizziness); + if (isMirrorWorld) mirror_surface_resolve(*this); spriteShaderParams.pixelationAmount = 0; graphics.shader_default_set(); diff --git a/src/room_render.h b/src/room_render.h index a0e12f0..1486784 100644 --- a/src/room_render.h +++ b/src/room_render.h @@ -57,6 +57,8 @@ extern std::array roomShockwaves; void room_surfaces_init(); Vector RandomVector(uint32_t seed); 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); diff --git a/src/room_special.cpp b/src/room_special.cpp index 169c527..ca6c811 100644 --- a/src/room_special.cpp +++ b/src/room_special.cpp @@ -9,6 +9,7 @@ #include "lua_engine.h" #include "manager.h" #include "npc_ai.h" +#include "npc_basement.h" #include "room.h" #include "room_grid.h" #include @@ -788,15 +789,31 @@ void npc_shopkeeper_update(Entity_NPC& npc) } constexpr int SOUND_COIN_SLOT = 45; -constexpr int SOUND_MEATY_DEATHS = 77; -constexpr int SOUND_WOOD_PLANK_BREAK = 481; constexpr int SOUND_MIRROR_BREAK = 610; -constexpr int MUSIC_JINGLE_SECRETROOM_FIND = 85; constexpr int FAMILIAR_KNIFE_FULL = 223; constexpr int TRINKET_PAPER_CLIP_ID = 19; constexpr int TRINKET_STORE_KEY_ID = 83; constexpr int EVENT_DOORS_BOMBED = 199; constexpr int MIRROR_LUCK_PENALTY = -7; +constexpr int PHOTO_HOLDER_CHECKS = 3; +constexpr int STRANGE_DOOR_LAYER_LOCK = 1; +constexpr int STRANGE_DOOR_LAYER_FADED = 2; +constexpr int STRANGE_DOOR_LAYER_EYE = 4; +constexpr std::string_view ANIM_DOOR_FEED = "Feed"; +constexpr float MAUSOLEUM_DOOR_DAMAGE = 2; +constexpr uint64_t MAUSOLEUM_DOOR_DAMAGE_FLAGS = DAMAGE_SPIKES | DAMAGE_INVINCIBLE | DAMAGE_NO_MODIFIERS | DAMAGE_NO_PENALTIES; +constexpr int MAUSOLEUM_DOOR_SOURCE = 10003; +constexpr int MAUSOLEUM_DOOR_COUNTDOWN = 30; +constexpr int BLOOD_SPLAT_SUBTYPE = 3; +constexpr int BLOOD_SLOW_DROPS = 2; +constexpr int BLOOD_DROPS_MIN = 8; +constexpr uint32_t BLOOD_DROPS_SPREAD = 10; +constexpr float BLOOD_SPREAD = 30; +constexpr float BLOOD_SPEED_MIN = 5; +constexpr float BLOOD_SPEED_RANGE = 15; +constexpr float BLOOD_SLOW_SCALE = 0.2f; +constexpr int BLOOD_ARC_SUBTYPE = 99; +constexpr float BLOOD_ARC_FALL = -8; constexpr int GAME_STATE_MOMS_HEART_DOOR_CUT = 52; constexpr int GAME_STATE_KEY_PIECE_DOOR_OPENED = 49; constexpr int NETPLAY_DOOR_WAIT = 30; @@ -891,7 +908,7 @@ bool GridEntity_Door::TryBlowOpen(bool isFromExplosion, Entity* source) bool isSecretTarget = targetRoomType == ROOM_SECRET || targetRoomType == ROOM_SUPERSECRET || targetRoomType == ROOM_ULTRASECRET; if (isSecretTarget && game.GetRoomByIdx(targetRoomIdx)->visitedCount == 0 && variant == DOOR_HIDDEN) - g_manager->musicManager.PlayJingle(MUSIC_JINGLE_SECRETROOM_FIND); + g_manager->musicManager.PlayJingle(MUSIC_JINGLE_SECRET_ROOM_FIND); if (variant == DOOR_HIDDEN || variant == DOOR_UNSPECIFIED) game.UncoverHiddenDoor(game.currentRoomIdx, slot); if (!CanBlowOpen()) @@ -990,6 +1007,109 @@ void GridEntity_Door::SpawnDust() } } +// The player holding the strange door's key, the Faded Polaroid, The Polaroid or The Negative, and which it is: the +// player, else the twin a main twin leads, else the other form of Tainted Lazarus. The original walks these forever +// when the forms point back at each other, here each player is asked once. +static Entity_Player* photo_holder_find(Entity_Player* player, int& item) +{ + for (int i = 0; player && player->isValid && i < PHOTO_HOLDER_CHECKS; i++) + { + if (player->HasTrinket(TRINKET_FADED_POLAROID, ITEM_CHECK_OWNED)) return item = TRINKET_FADED_POLAROID, player; + if (player->HasCollectible(COLLECTIBLE_POLAROID, ITEM_CHECK_OWNED)) return item = COLLECTIBLE_POLAROID, player; + if (player->HasCollectible(COLLECTIBLE_NEGATIVE, ITEM_CHECK_OWNED)) return item = COLLECTIBLE_NEGATIVE, player; + + bool isLazarus = player->playerType == PLAYER_LAZARUS_B || player->playerType == PLAYER_LAZARUS2_B; + Entity_Player* twin = player->GetMainTwin() == player ? player->twin_get() : nullptr; + player = twin ? twin : isLazarus ? player->backupPlayer : nullptr; + } + return nullptr; +} + +// The strange door at the top of Depths II opens to a photo, using up a Faded Polaroid, with a page turn and its +// jingle. The door shows the faded photo only for that trinket. +static bool strange_door_unlock(GridEntity_Door& door, Entity_Player& player) +{ + int item = 0; + Entity_Player* holder = photo_holder_find(&player, item); + if (!holder) return false; + + holder->TryRemoveTrinket(item); + grid_sound_play(SOUND_BOOK_PAGE_TURN_12); + g_manager->musicManager.PlayJingle(MUSIC_JINGLE_STRANGE_DOOR); + door.state = DOOR_STATE_OPEN; + door.UpdateAnimation(); + door.variant = DOOR_UNLOCKED; + door.sprite.GetLayer(STRANGE_DOOR_LAYER_LOCK)->isVisible = false; + door.sprite.GetLayer(STRANGE_DOOR_LAYER_FADED)->isVisible = item == TRINKET_FADED_POLAROID; + door.sprite.GetLayer(STRANGE_DOOR_LAYER_EYE)->isVisible = false; + return true; +} + +// Sprays the Mausoleum door's blood out of the wall: a splat on the door and drops thrown into the room, the first few +// slow, the rest arcing high. +static void mausoleum_door_bleed(GridEntity_Door& door) +{ + Vector inward = vector_from_direction(door.direction); + Vector cell = door.Position(); + + g_game->Spawn({.position = cell, + .subType = BLOOD_SPLAT_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + + uint32_t roll = Random(); + int slowCount = (int)(roll & 1) + BLOOD_SLOW_DROPS; + int count = (int)(roll & 1) + BLOOD_DROPS_MIN + (int)(Random() % BLOOD_DROPS_SPREAD); + for (int i = 0; i < count; i++) + { + float angle = (random_unit() * BLOOD_SPREAD - BLOOD_SPREAD / 2) * DEGREES_TO_RADIANS; + float speed = random_unit() * BLOOD_SPEED_RANGE + BLOOD_SPEED_MIN; + Vector velocity = vector_make((-inward.x * std::cos(angle) + inward.y * std::sin(angle)) * speed, + (-inward.y * std::cos(angle) - inward.x * std::sin(angle)) * speed); + Vector position = vector_make(cell.x + velocity.x, cell.y + velocity.y); + bool isSlow = i < slowCount; + Vector dropVelocity = isSlow ? vector_scale(velocity, BLOOD_SLOW_SCALE) : velocity; + auto* drop = static_cast(g_game->Spawn({.position = position, + .velocity = dropVelocity, + .subType = isSlow ? 0 : BLOOD_ARC_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, + .seed = Random()})); + drop->Update(); + if (!isSlow) drop->fallingSpeed = BLOOD_ARC_FALL; + } +} + +// The Mausoleum's heart door feeds on blood: each touch costs a heart (spikes damage, no penalties) and bleeds, and the +// second opens it. Soul-only and cursed players, and the invincibility seed, open it at once. Not while it feeds. +static bool mausoleum_door_feed(GridEntity_Door& door, Entity_Player& player) +{ + if (door.sprite.animState.animData && door.sprite.animState.isPlaying && door.sprite.IsPlaying(ANIM_DOOR_FEED)) + return false; + + bool isBloodless = player.GetHealthType() == HEALTH_NO_HEALTH || player.HasInstantDeathCurse() || + g_game->seedEffects.HasSeedEffect(SEED_INVINCIBLE); + if (isBloodless) door.varData = 0; + else + { + EntityRef source; + + source.variant = MAUSOLEUM_DOOR_SOURCE; + player.damageCooldown = 0; + if (!player.TakeDamage(MAUSOLEUM_DOOR_DAMAGE, MAUSOLEUM_DOOR_DAMAGE_FLAGS, source, MAUSOLEUM_DOOR_COUNTDOWN)) + return false; + mausoleum_door_bleed(door); + } + + door.state = door.varData != 0 ? DOOR_STATE_HALF_OPEN : DOOR_STATE_OPEN; + door.UpdateAnimation(); + if (door.varData < 1) door.variant = DOOR_UNLOCKED; + else door.varData--; + grid_sound_play(SOUND_MEAT_JUMPS); + return true; +} + // Whether a key, coins, the Store Key or a strong Paper Clip pays the lock: coin locks take a coin, the Blue Womb's // boss door is free, and key locks take a key. static bool door_lock_pay(GridEntity_Door& door, Entity_Player& player) @@ -1013,7 +1133,7 @@ bool GridEntity_Door::TryUnlock(Entity_Player& player, bool isForce) if ((doorFlags & DOOR_FLAG_MIRROR) || player.isCoopGhost) return false; if (!isForce && variant == DOOR_LOCKED && targetRoomType == ROOM_SECRET_EXIT && get_secret_exit_kind() == SECRET_EXIT_MAUSOLEUM) - reconstruction_missing("GridEntity_Door::TryUnlock 00710480: the Mausoleum's heart door"); + return doorFlags & DOOR_FLAG_PHOTO ? strange_door_unlock(*this, player) : mausoleum_door_feed(*this, player); if (isForce && variant == DOOR_LOCKED_KEYFAMILIAR) game.gameStateFlags |= 1ull << GAME_STATE_KEY_PIECE_DOOR_OPENED; bool isKeyLock = variant == DOOR_LOCKED || variant == DOOR_LOCKED_DOUBLE; diff --git a/src/room_transition.cpp b/src/room_transition.cpp index 36772f9..90ac62a 100644 --- a/src/room_transition.cpp +++ b/src/room_transition.cpp @@ -1,4 +1,5 @@ #include "room_transition.h" +#include "entity_familiar.h" #include "entity_npc.h" #include "entity_player.h" #include "fx_layers.h" @@ -42,7 +43,6 @@ constexpr int TELEPORT_SOUND_FRAME = 8; constexpr int SOUND_ONE_UP = 1; constexpr int SOUND_TELEPORT_LAND = 214; constexpr int ITEM_STATE_HELD = 604; -constexpr int PITFALL_GONE = 4; constexpr int MINECART_RIDDEN = 10; constexpr int NPC_STATE_MINECART_MOVING = 4; constexpr int COLLECTIBLE_GLOWING_HOURGLASS = 422; @@ -53,6 +53,7 @@ constexpr float SCREEN_CELL_SIZE = 26; constexpr int ROOM_CELLS_ACROSS = 13; constexpr int ROOM_CELLS_DOWN = 7; constexpr int DEATH_CERTIFICATE_DIMENSION = 2; +constexpr float TELEPORTER_SCATTER = 10; constexpr int DOGMA_ROOM_VARIANT = 1000; constexpr uint32_t BOSS_DOGMA = 99; @@ -194,6 +195,35 @@ void RoomTransition::slide_offset_set(Vector distance, Vector oldScroll) } } +// The players arriving by teleporter on the pad they were sent to (the first of its number): the one who teleported on +// it, switched on, the others scattered 10 around it, and the Blood Babies (Clots) moved onto it. +static void teleporter_arrival_place(Room& room, int target) +{ + PlayerManager& players = g_game->playerManager; + Entity_Player* traveller = players.roomTransitionPlayer ? players.roomTransitionPlayer : g_game->GetPlayer(0); + + for (int i = 0; i < room.gridWidth * room.gridHeight && i < ROOM_GRID_CELLS; i++) + { + GridEntity* teleporter = room.gridEntities[i]; + if (!teleporter || teleporter->type != GRID_TELEPORTER || teleporter->variant != target - 1) continue; + + Vector at = teleporter->Position(); + traveller->Teleport(at, false, false); + if (teleporter->state == 0) teleporter->state = 1; + for (Entity_Player* player : players.playerList) + { + if (player == traveller) continue; + float angle = (float)Random() * RANDOM_UNIT * RANDOM_PI; + angle += angle; + float x = std::cos(angle) * TELEPORTER_SCATTER + at.x; + float y = std::sin(angle) * TELEPORTER_SCATTER + at.y; + player->Teleport(vector_make(x, y), false, false); + } + for (Entity_Familiar* clot : familiar_query(Entity_Familiar::BLOOD_BABY)) clot->pos = at; + return; + } +} + // Puts the players in the new room. A teleport keeps them hidden, else the main players not held show. The Forgotten's // body, the Death Certificate's floor, a teleporter's pad and the Ventricle Razor's portals place them. void RoomTransition::arrival_place() @@ -230,7 +260,7 @@ void RoomTransition::arrival_place() player->isControlsEnabled = false; } else if (animation == TRANSITION_TELEPORT && teleporterTarget > 0 && isTeleporterRoom) - reconstruction_missing("RoomTransition::ChangeRoom 00830950: Entity_Player::Teleport 007cd950 to a teleporter"); + teleporter_arrival_place(room, teleporterTarget); } // 00830950 Takes the players into the target room (the Glowing Hourglass rewinds the room instead), their controls on diff --git a/src/room_update.cpp b/src/room_update.cpp index d8680c0..3722486 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -121,7 +121,6 @@ constexpr uint32_t RNG_SHIFT_COUPON_2 = 27; // The entities with ambient loops of their own (Lua's EntityType, EffectVariant and laser variants). constexpr int AMBIENT_FLY_TYPES[] = {13, 14, 18, 25, 61, 80, 214, 222, 249, 256, 281, 296, 808, 819, 838, 868}; -constexpr int ENTITY_PORTAL = 306; constexpr int ENTITY_VIS_FATTY = 886; constexpr int BEAST_FLY_VARIANTS[] = {11, 21}; constexpr int DOGMA_ANGEL = 2; diff --git a/src/sfx_manager.h b/src/sfx_manager.h index e091fe1..15cc2d4 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -24,6 +24,7 @@ enum SoundLoop // The sounds several files play (Lua's SoundEffect). enum SoundId : int { + SOUND_BIRD_FLAP = 2, SOUND_BLOOD_LASER = 5, SOUND_BLOOD_LASER_SMALL = 6, SOUND_BLOOD_LASER_LARGE = 7, @@ -39,8 +40,10 @@ enum SoundId : int SOUND_CHEST_OPEN = 22, SOUND_CUTE_GRUNT = 25, SOUND_DEATH_BURST_LARGE = 28, + SOUND_BOSS1_EXPLOSIONS = 28, SOUND_DEATH_REVERSE = 29, SOUND_FART = 37, + SOUND_FETUS_JUMP = 38, SOUND_FETUS_LAND = 40, SOUND_FIREDEATH_HISS = 43, SOUND_COIN_INSERT = 45, @@ -52,8 +55,16 @@ enum SoundId : int SOUND_DIP_HURT = 60, SOUND_MAGGOT_BURST_OUT = 64, SOUND_MAGGOT_ENTER_GROUND = 66, + SOUND_MEAT_IMPACTS = 69, SOUND_MEAT_JUMPS = 72, + SOUND_MEATY_DEATHS = 77, + SOUND_BLACK_POOF = 80, SOUND_MOM_VOX_DEATH = 82, + SOUND_MOM_VOX_EVILLAUGH = 84, + SOUND_MOM_VOX_FILTERED_DEATH_1 = 85, + SOUND_MOM_VOX_FILTERED_EVILLAUGH = 86, + SOUND_MOM_VOX_FILTERED_HURT = 87, + SOUND_MOM_VOX_FILTERED_ISAAC = 90, SOUND_MOM_VOX_GRUNT = 93, SOUND_MOM_VOX_HURT = 97, SOUND_MOM_VOX_ISAAC = 101, @@ -65,13 +76,16 @@ enum SoundId : int SOUND_MONSTER_ROAR_0 = 115, SOUND_MONSTER_ROAR_1 = 116, SOUND_MONSTER_ROAR_2 = 117, + SOUND_MONSTER_ROAR_3 = 118, SOUND_MONSTER_YELL_A = 119, + SOUND_MONSTER_YELL_B = 122, SOUND_POWERUP1 = 128, SOUND_POWERUP_SPEWER = 132, SOUND_REDLIGHTNING_ZAP = 133, SOUND_REDLIGHTNING_ZAP_WEAK = 134, SOUND_REDLIGHTNING_ZAP_STRONG = 135, SOUND_ROCK_CRUMBLE = 137, + SOUND_SMB_LARGE_CHEWS_4 = 142, SOUND_SHAKEY_KID_ROAR = 146, SOUND_SINK_DRAIN_GURGLE = 149, SOUND_TEAR_IMPACTS = 150, @@ -80,6 +94,7 @@ enum SoundId : int SOUND_VAMP_GULP = 157, SOUND_WHEEZY_COUGH = 158, SOUND_SPIDER_COUGH = 159, + SOUND_ZOMBIE_WALKER_KID = 165, SOUND_ANGRY_GURGLE = 167, SOUND_BATTERYCHARGE = 170, SOUND_BEEP = 171, @@ -87,6 +102,7 @@ enum SoundId : int SOUND_BOIL_HATCH = 181, SOUND_BOSS2_BUBBLES = 185, SOUND_ERROR_BUZZ = 187, + SOUND_GOOATTACH0 = 205, SOUND_SATAN_HAND_LASER = 211, SOUND_HEARTIN = 212, SOUND_HEARTOUT = 213, @@ -95,6 +111,7 @@ enum SoundId : int SOUND_ISAACDIES = 217, SOUND_LEECH = 221, SOUND_MAGGOTCHARGE = 224, + SOUND_MEATHEADSHOOT = 226, SOUND_METAL_BLOCKBREAK = 229, SOUND_PLOP = 237, SOUND_SCAMPER = 249, @@ -112,39 +129,62 @@ enum SoundId : int SOUND_ANGEL_BEAM = 276, SOUND_MEGA_BLAST_START = 278, SOUND_MEGA_BLAST_END = 280, + SOUND_SUMMON_POOF = 286, SOUND_BOO_MAD = 300, SOUND_FART_GURG = 301, + SOUND_FAT_GRUNT = 302, SOUND_FAT_WIGGLE = 303, SOUND_FIRE_RUSH = 304, SOUND_GHOST_ROAR = 305, SOUND_GHOST_SHOOT = 306, + SOUND_GRROOWL = 307, + SOUND_GURG_BARF = 308, SOUND_LOW_INHALE = 310, + SOUND_MEGA_PUKE = 311, SOUND_MOUTH_FULL = 312, SOUND_MULTI_SCREAM = 313, SOUND_SKIN_PULL = 314, SOUND_WHISTLE = 315, + SOUND_DEVILROOM_DEAL = 316, SOUND_WORM_SPIT = 318, SOUND_LITTLE_SPIT = 319, + SOUND_HEARTBEAT = 321, + SOUND_HEARTBEAT_FASTER = 322, + SOUND_HEARTBEAT_FASTEST = 323, SOUND_WET_FEET = 398, SOUND_DANGLE_WHISTLE = 413, SOUND_LITTLE_HORN_COUGH = 414, SOUND_LITTLE_HORN_GRUNT_1 = 415, SOUND_LITTLE_HORN_GRUNT_2 = 416, SOUND_THE_STAIN_BURST = 419, + SOUND_BONE_SNAP = 462, SOUND_SHOVEL_DIG = 464, SOUND_GOLD_HEART_DROP = 466, + SOUND_BOSS2_DIVE = 474, SOUND_DEMON_HIT = 477, + SOUND_WOOD_PLANK_BREAK = 481, SOUND_FLAME_BURST = 483, SOUND_BATTERYDISCHARGE = 493, SOUND_FREEZE = 496, SOUND_FREEZE_SHATTER = 498, SOUND_POOP_LASER = 589, + SOUND_RAILROAD_TRACK_RAISE = 596, + SOUND_RAILROAD_TRACK_RAISE_FAR = 597, SOUND_MOM_AND_DAD_1 = 598, SOUND_MOM_AND_DAD_2 = 599, SOUND_MOM_AND_DAD_3 = 600, SOUND_MOM_AND_DAD_4 = 601, SOUND_VAMP_DOUBLE = 614, + SOUND_GFUEL_AIR_HORN = 828, SOUND_POOP_THROW = 865, + SOUND_SUMMON_WAVE = 872, + SOUND_CAGE_DEATH = 918, + SOUND_CAGE_JUMP = 919, + SOUND_CAGE_RIBS = 920, + SOUND_CAGE_ROLL_START = 921, + SOUND_CAGE_PREP_SHOOT = 922, + SOUND_CAGE_ROLL_STOP = 923, + SOUND_CAGE_ROLL_BOUNCE = 924, SOUND_GURDY_FACE_ATTACK_APPEAR = 939, SOUND_GURDY_FACE_ATTACK_HIDE = 940, SOUND_GURDY_FACE_SMILE_APPEAR = 941, @@ -160,6 +200,11 @@ enum SoundId : int SOUND_LOKI_JUMP_IN = 951, SOUND_LOKI_SHOOT = 952, SOUND_LOKI_SHOOT_8 = 953, + SOUND_MASKINFAMY_MAD = 954, + SOUND_MASKINFAMY_DASH = 955, + SOUND_MEGAFATTY_GULP = 956, + SOUND_MEGAFATTY_SUCKIN = 957, + SOUND_MEGAFATTY_VOMIT = 958, SOUND_STAIN_ATTACK_VOX = 959, SOUND_TERATOMA_BOUNCE_BIG = 968, SOUND_TERATOMA_BOUNCE_MEDIUM = 969, @@ -170,7 +215,14 @@ enum SoundId : int SOUND_FISTULA_GROWL_LARGE = 978, SOUND_FISTULA_GROWL_MEDIUM = 979, SOUND_FISTULA_GROWL_SMALL = 980, + SOUND_BLASTOCYST_JUMP_BIG = 987, + SOUND_BLASTOCYST_JUMP = 988, + SOUND_BLASTOCYST_JUMP_SMALL = 989, SOUND_POOP_DROP = 990, + SOUND_CARRION_QUEEN_BOUNCE = 991, + SOUND_CARRION_QUEEN_DIAGONAL_START = 992, + SOUND_CARRION_QUEEN_DIAGONAL_VOX = 993, + SOUND_CARRION_QUEEN_ROAR = 994, SOUND_HAUNT_CHARGE = 995, SOUND_HAUNT_DEATH = 996, SOUND_HAUNT_ROAR = 997, @@ -178,12 +230,15 @@ enum SoundId : int SOUND_LARRY_JR_DEATH_1 = 999, SOUND_LARRY_JR_DEATH_2 = 1000, SOUND_LARRY_JR_ROAR = 1001, + SOUND_MEGA_FATTY_MEGA_FART = 1002, SOUND_HOLLOW_DEATH_1 = 1003, SOUND_HOLLOW_DEATH_2 = 1004, SOUND_HOLLOW_ROAR = 1005, SOUND_MONSTERS_NEXT_DOOR = 1008, SOUND_IMMACULATE_CONCEPTION = 1010, SOUND_SHINYROCK_SHIMMER = 1014, + SOUND_TRAP_DOOR_LEVEL = 1052, + SOUND_GIANT_CHEST_OPEN = 1075, SOUND_BRAIN_MOVE = 1080, SOUND_POISON_MIND_HURT = 1081, SOUND_BUTTLICKER_GROWL = 1085 diff --git a/src/stage_transition.cpp b/src/stage_transition.cpp index 32a3263..88a8ec2 100644 --- a/src/stage_transition.cpp +++ b/src/stage_transition.cpp @@ -28,7 +28,6 @@ constexpr int GRID_COLUMN_OFFSET = 40; constexpr int GRID_ROW_OFFSET = 120; constexpr float GRID_CELL = 40; -constexpr int COLLECTIBLE_FORGET_ME_NOW = 127; constexpr int SOUND_ASCENT_START = 615; constexpr int ACHIEVEMENT_NO_HEARTS_STAGES = 42; constexpr int ACHIEVEMENT_NO_DAMAGE_STAGES = 67; @@ -292,9 +291,16 @@ static void start_update(StageTransition& transition) transition.state = STAGE_TRANSITION_OUT; room_ambient_sounds_stop(); g_manager->sfxManager.StopLoopingSounds(); - if (transition.type == STAGE_TRANSITION_ENDING) - reconstruction_missing("StageTransition::Update 0092f1c0: " - "get_stage_ending_id 006f9d20 and the run's ending"); + if (transition.type != STAGE_TRANSITION_ENDING) return; + GameEnding ending = stage_ending_get(ENDING_PHOTOS_CHECKED); + if (ending == ENDING_NONE) return; + if (ending == ENDING_UNKNOWN) + { + log_printf(LOG_INFO, "[warn] No ending for big chest!\n"); + challenge_finish(); + } + else game_end(ending); + transition.state = STAGE_TRANSITION_LANDING; } // The floor changes two frames before the fade out ends: to the type's stage, or the next one (the endless basement's diff --git a/src/weapon.cpp b/src/weapon.cpp index 037e146..8433016 100644 --- a/src/weapon.cpp +++ b/src/weapon.cpp @@ -1,10 +1,13 @@ #include "weapon.h" #include "weapon_lasers.h" +#include "weapon_knives.h" #include "entity_familiar.h" #include "entity_player.h" #include "entity_tear.h" #include "game.h" +#include "item_config.h" #include "log.h" +#include "manager.h" #include "menu_manager.h" #include #include @@ -26,10 +29,10 @@ constexpr float RANDOM_UNIT = 2.3283064e-10f; constexpr float SHOT_ROTATION_STEP = 45; constexpr float FULL_TURN = 360; constexpr float SHOT_SPEED_BASE = 10; -constexpr float SHOTS_PER_SECOND = 30; constexpr float TEAR_SPEED_SPREAD = 0.2f; constexpr float TEAR_SPEED_MIN = 0.8f; constexpr float CHARGE_BAR_FULL = 1; +constexpr float WEAPON_DAMAGE_DEFAULT = 3.5f; constexpr int FIRE_BLINK_BASE = 7; constexpr int FIRE_BLINK_MIN = 11; constexpr int MAX_SHOTS_PER_FRAME = 8; @@ -51,6 +54,17 @@ constexpr int MARKED_OCCULT_TARGET = 153; // Pencil. constexpr int TEAR_TRIGGER_ITEMS[] = {217, 573, 616, 495, 450, COLLECTIBLE_LEAD_PENCIL}; +// The null costumes that count as Brimstone's: Azazel's head, Brimstone's second costume, Tainted Azazel and Azazel's +// Rage. +constexpr std::array BRIMSTONE_NULL_COSTUMES = {11, 45, 86, 99}; + +// Which of a player's costume layers a search covers: all, or the head's without the body layers. +enum CostumeLayers +{ + COSTUME_LAYERS_ALL, + COSTUME_LAYERS_HEAD +}; + // A random float in [0, 1), as the game turns Random() into one. static float random_unit() { return (float)Random() * RANDOM_UNIT; } @@ -73,12 +87,15 @@ static Vector vector_scale(Vector v, float scale) { return vector_make(v.x * sca static bool is_zero(Vector v) { return v.x == 0 && v.y == 0; } -// 009f9020 Makes the weapon of a type for an owner through the type's maker, written for tears (009f9260) and the -// lasers (weapon_laser_make). +// 009f9020 Makes the weapon of a type for an owner through the type's maker, written for tears (009f9260), the +// lasers (weapon_laser_make) and the knife (weapon_knife_make). WeaponPtr weapon_create(WeaponType type, Entity* owner) { - WeaponPtr weapon(type == WEAPON_TEARS ? new Weapon_Tears() : weapon_laser_make(type)); - if (!weapon) reconstruction_missing("Isaac::CreateWeapon 009f9020 (weapons other than tears and lasers)"); + Weapon* made = type == WEAPON_TEARS ? new Weapon_Tears() : weapon_laser_make(type); + if (!made) made = weapon_knife_make(type); + if (!made) reconstruction_missing("Isaac::CreateWeapon 009f9020 (weapons other than tears, lasers and knives)"); + + WeaponPtr weapon(made); weapon->Init(type, owner); return weapon; @@ -191,9 +208,6 @@ Vector Weapon::get_aim_direction(const Vector& defaultDirection) // 009f3bd0 Where the owner stands. Vector Weapon::get_owner_position() { return owner ? owner->pos : Vector{}; } -float Weapon::get_damage() { reconstruction_missing("Weapon::get_damage 009f3c80"); } -TearFlags Weapon::get_owner_tear_flags() { reconstruction_missing("Weapon::get_owner_tear_flags 009f3d00"); } -ColorMod Weapon::get_tear_color() { reconstruction_missing("Weapon::get_tear_color 009f3db0"); } // 009f41c0 How the owner's volley spreads, or a volley of none without a player. Weapon_MultiShotParams Weapon::GetMultiShotParams() @@ -347,17 +361,232 @@ void Weapon::TriggerTearEffects(const Vector&, int count) } } -bool Weapon::is_held_item(ANM2&, std::string_view, void*) { reconstruction_missing("Weapon::is_held_item 0075a2b0"); } -void Weapon::stop_costume_item_anim(int) { reconstruction_missing("Weapon::stop_costume_item_anim 009f4ff0"); } -bool Weapon::IsItemAnimFinished(int) { reconstruction_missing("Weapon::IsItemAnimFinished 009f50f0"); } -bool Weapon::is_c_section_anim_finished() { reconstruction_missing("Weapon::is_c_section_anim_finished 009f5510"); } -Entity_Bomb* Weapon::fire_bomb(Weapon&, const PosVel&) { reconstruction_missing("Weapon::fire_bomb 009f5d60"); } -Entity_Knife* Weapon::fire_knife(Entity*, int, bool, float) { reconstruction_missing("Weapon::fire_knife 009f6a60"); } -Entity_Knife* Weapon::FireSword(Entity*, int, float, bool, bool, int, Entity*) +// 009f3c80 The damage the weapon deals: its player's, or for a familiar half its player's (not for Lilith) and doubled +// by BFFS!, or a tear's 3.5 without either. +float Weapon::get_damage() { - reconstruction_missing("Weapon::FireSword 009f6c50"); + if (owner && owner->is_player()) return owner->ToPlayer()->damage; + + Entity_Player* player = owner_player(); + if (!player) return WEAPON_DAMAGE_DEFAULT; + + float damage = player->damage; + if (player->playerType != PLAYER_LILITH) damage *= 0.5f; + return player->HasCollectible(COLLECTIBLE_BFFS) ? damage + damage : damage; } +// 009f3d00 The tear flags the weapon fires with: its player's, homing for a familiar under Baby-Bender. +TearFlags Weapon::get_owner_tear_flags() +{ + Entity_Player* player = owner_player(); + if (!player) return {}; + + TearFlags flags = player->tearFlags; + if (owner->IsFamiliar() && player->HasTrinket(TRINKET_BABY_BENDER)) flags.set(TEAR_HOMING); + return flags; +} + +// 009f3db0 The color the weapon's tears take: its player's. A familiar's are recolored, which is not reconstructed +// yet. Online, another player's tears fade with the opacity option, which this offline build has no use for. +ColorMod Weapon::get_tear_color() +{ + Entity_Player* player = owner_player(); + if (!player) return COLOR_DEFAULT; + if (owner->IsFamiliar()) reconstruction_missing("Weapon::get_tear_color 009f3db0 (a familiar's tears)"); + return player->tearColor; +} + +// 0075a2b0 Whether a costume belongs to an item. Brimstone's is also Azazel's head and Rage, Brimstone's second +// costume, Brimstone itself and Azazel's Stump. Without an item, whether the costume has the animation. +bool Weapon::is_held_item(CostumeSpriteDesc& costume, std::string_view animName, ItemConfig_Item* item) +{ + if (!item) return !animName.empty() && costume.sprite.GetAnimationData(animName); + + bool isCollectible = item->type == ITEM_PASSIVE || item->type == ITEM_ACTIVE || item->type == ITEM_FAMILIAR; + if (!isCollectible || item->id != COLLECTIBLE_BRIMSTONE) return costume.item == item; + + ItemConfig_Item* worn = costume.item; + if (!worn) return false; + if (worn->type == ITEM_NULL) return std::ranges::find(BRIMSTONE_NULL_COSTUMES, worn->id) != BRIMSTONE_NULL_COSTUMES.end(); + if (worn->type == ITEM_TRINKET) return worn->id == TRINKET_AZAZELS_STUMP; + return worn->id == COLLECTIBLE_BRIMSTONE; +} + +// The costume sprites of a player's head layers that belong to an item, in layer order. +static std::vector item_costumes_get(Entity_Player& player, ItemConfig_Item* item, + CostumeLayers layers) +{ + std::vector costumes; + + for (PlayerCostumeMap& map : player.playerCostumeMap) + { + if (map.index < 0 || (layers == COSTUME_LAYERS_HEAD && map.isBodyLayer)) continue; + + CostumeSpriteDesc& costume = player.costumeSpriteDescs[map.index]; + if (Weapon::is_held_item(costume, "", item)) costumes.push_back(&costume); + } + return costumes; +} + +// 0075a700 Shows an animation on the costumes of an item (and their overlays), marked as playing an item animation: +// at a frame and stopped, played unforced at -1, or switched to keeping the frame below. A co-op baby or ghost shows +// it on its own sprite too. +void costume_item_anim_set(Entity_Player& player, ItemConfig_Item* item, std::string_view animName, int frame) +{ + std::string overlayName = std::string(animName) + "_Overlay"; + + for (CostumeSpriteDesc* costume : item_costumes_get(player, item, COSTUME_LAYERS_HEAD)) + { + costume->isItemAnimPlay = true; + if (frame >= 0) costume->sprite.SetFrame(animName, frame); + else if (frame == -1) costume->sprite.Play(animName); + else costume->sprite.SetAnimation(animName, SWITCH_KEEP_FRAME); + + if (!costume->isHasOverlay) continue; + if (frame >= 0) costume->sprite.SetOverlayFrame(overlayName, frame); + else if (frame == -1) costume->sprite.PlayOverlay(overlayName); + else costume->sprite.SetOverlayAnimation(overlayName, SWITCH_KEEP_FRAME); + } + + if (player.variant == PLAYER_VARIANT_PLAYER && !player.isCoopGhost) return; + if (frame >= 0) player.sprite.SetFrame(animName, frame); + else if (frame == -1) player.sprite.Play(animName); + else player.sprite.SetAnimation(animName, SWITCH_KEEP_FRAME); +} + +// 0075ad50 Moves the costumes of an item playing an animation (and their playing overlays) to a frame. +void costume_item_frame_set(Entity_Player& player, ItemConfig_Item* item, std::string_view animName, int frame) +{ + std::string overlayName = std::string(animName) + "_Overlay"; + + for (CostumeSpriteDesc* costume : item_costumes_get(player, item, COSTUME_LAYERS_HEAD)) + { + if (costume->sprite.IsPlaying(animName)) costume->sprite.SetFrame((float)frame); + if (costume->isHasOverlay && costume->sprite.IsOverlayPlaying(overlayName) && + costume->sprite.overlayAnimState.animData) + costume->sprite.overlayAnimState.SetFrameFloat((float)frame); + } +} + +// 0075abe0 The frame the first playing costume of an item is on, -1 without an animation, 0 when none plays. +int costume_item_frame_get(Entity_Player& player, ItemConfig_Item* item) +{ + for (CostumeSpriteDesc* costume : item_costumes_get(player, item, COSTUME_LAYERS_HEAD)) + if (costume->sprite.IsPlaying()) return costume->sprite.GetFrame(); + return 0; +} + +// 009f4280 Shows the owner's head charging an item's shot: a player's costumes charge at a frame, show the full +// charge, or shoot (and the head turns), a familiar floats charging, charged or shooting Brimstone and Monstro's Lung. +void Weapon::UpdateHeadChargeAnimation(int collectibleId, HeadCharge chargeType, const Vector& aim, float chargeFrame) +{ + constexpr std::string_view FAMILIAR_CHARGE[] = {"FloatChargeSide", "FloatChargeUp", "FloatChargeSide", + "FloatChargeDown"}; + constexpr std::string_view FAMILIAR_CHARGED[] = {"FloatChargedSide", "FloatChargedUp", "FloatChargedSide", + "FloatChargedDown"}; + constexpr std::string_view FAMILIAR_SHOOT[] = {"Shoot2Side", "Shoot2Up", "Shoot2Side", "Shoot2Down"}; + constexpr std::string_view HEAD_CHARGE[] = {"HeadLeftCharge", "HeadUpCharge", "HeadRightCharge", + "HeadDownCharge"}; + constexpr std::string_view HEAD_CHARGED[] = {"HeadLeftChargeFull", "HeadUpChargeFull", "HeadRightChargeFull", + "HeadDownChargeFull"}; + constexpr std::string_view HEAD_SHOOT[] = {"HeadLeftShoot", "HeadUpShoot", "HeadRightShoot", "HeadDownShoot"}; + constexpr std::string_view HEAD_SHOOT_ALT[] = {"HeadLeftShootAlt", "HeadUpShootAlt", "HeadRightShootAlt", + "HeadDownShootAlt"}; + Direction side = vector_to_direction(aim); + + if (owner && owner->IsFamiliar()) + { + Entity_Familiar& familiar = *static_cast(owner); + if (chargeType == HEAD_CHARGE_CHARGING) + familiar.sprite.SetFrame(FAMILIAR_CHARGE[side], (int)(chargeFrame * SHOTS_PER_SECOND / HEAD_CHARGE_FRAMES)); + else if (chargeType == HEAD_CHARGE_CHARGED) familiar.sprite.Play(FAMILIAR_CHARGED[side]); + else if (chargeType == HEAD_CHARGE_SHOOT && + (collectibleId == COLLECTIBLE_BRIMSTONE || collectibleId == COLLECTIBLE_MONSTROS_LUNG)) + familiar.sprite.Play(FAMILIAR_SHOOT[side]); + familiar.fireCooldown = 1; + familiar.sprite.isFlipX = side == DIRECTION_LEFT; + return; + } + if (!owner || !owner->is_player()) return; + + Entity_Player& player = *owner->ToPlayer(); + std::string_view animName; + switch (chargeType) + { + case HEAD_CHARGE_CHARGING: + animName = HEAD_CHARGE[side]; + break; + case HEAD_CHARGE_CHARGED: + animName = HEAD_CHARGED[side]; + break; + case HEAD_CHARGE_SHOOT: + animName = HEAD_SHOOT[side]; + break; + case HEAD_CHARGE_SHOOT_ALT: + animName = HEAD_SHOOT_ALT[side]; + break; + } + costume_item_anim_set(player, g_manager->itemConfig.GetCollectible(collectibleId), animName, (int)chargeFrame); + if (chargeType == HEAD_CHARGE_SHOOT) player.headAnim = PLAYER_HEAD_ANIMS[side]; +} + +// 009f4da0 Plays Brimstone's shot on the owning player's costumes at a frame. +void Weapon::play_brimstone_costume_shoot(const Vector& aim, float frame) +{ + constexpr std::string_view HEAD_SHOOT[] = {"HeadLeftShoot", "HeadUpShoot", "HeadRightShoot", "HeadDownShoot"}; + if (!owner || !owner->is_player()) return; + + costume_item_frame_set(*owner->ToPlayer(), g_manager->itemConfig.GetCollectible(COLLECTIBLE_BRIMSTONE), + HEAD_SHOOT[vector_to_direction(aim)], (int)frame); +} + +// 009f4ff0 Ends the item animation of a collectible's costumes, or a familiar's. +void Weapon::stop_costume_item_anim(int collectibleId) +{ + if (owner && owner->IsFamiliar()) + { + static_cast(owner)->fireCooldown = 0; + return; + } + if (!owner || !owner->is_player()) return; + + Entity_Player& player = *owner->ToPlayer(); + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); + if (player.isCoopGhost) return; + for (CostumeSpriteDesc* costume : item_costumes_get(player, item, COSTUME_LAYERS_ALL)) costume->isItemAnimPlay = false; +} + +// 009f50f0 Whether the item animation of a collectible's costumes ended: true once one stopped on a non-looping +// animation, false while any still plays it. A familiar's ends with its animation. +bool Weapon::IsItemAnimFinished(int collectibleId) +{ + if (owner && owner->IsFamiliar()) + { + Entity_Familiar& familiar = *static_cast(owner); + return !familiar.fireCooldown || !familiar.sprite.IsPlaying(); + } + if (!owner || !owner->is_player()) return true; + + bool isAllFinished = true; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); + for (CostumeSpriteDesc* costume : item_costumes_get(*owner->ToPlayer(), item, COSTUME_LAYERS_ALL)) + { + if (!costume->isItemAnimPlay) continue; + + const AnimationData* animation = costume->sprite.animState.animData; + if (costume->sprite.IsFinished() && (!animation || !animation->isLooping)) return true; + isAllFinished = false; + } + return isAllFinished; +} + +bool Weapon::is_c_section_anim_finished() { reconstruction_missing("Weapon::is_c_section_anim_finished 009f5510"); } +void Weapon::update_c_section_charge_anim(HeadCharge, const Vector&, float) +{ + reconstruction_missing("Weapon::update_c_section_charge_anim 009f52c0"); +} +Entity_Bomb* Weapon::fire_bomb(Weapon&, const PosVel&) { reconstruction_missing("Weapon::fire_bomb 009f5d60"); } + // 00a0d870 Counts both eyes' fire delays down at the owner's speed, outside interpolation frames. void Weapon_Tears::Update(bool isInterpolated) { diff --git a/src/weapon.h b/src/weapon.h index f2dc545..786d58a 100644 --- a/src/weapon.h +++ b/src/weapon.h @@ -3,7 +3,13 @@ #include "entity.h" #include +struct CostumeSpriteDesc; +struct lua_State; + constexpr float WEAPON_MAX_FIRE_DELAY_DEFAULT = 10; +// The game's update rate, which fire delays count in, and the frames a head's charge animation spans. +constexpr float SHOTS_PER_SECOND = 30; +constexpr float HEAD_CHARGE_FRAMES = 18; // What a player or familiar shoots (Lua's WeaponType). Slot 16 is the deathmatch's. enum WeaponType : int @@ -87,6 +93,15 @@ enum BrimstoneFireFlag : uint32_t BRIMSTONE_FIRE_C_SECTION = 1 << 11 }; +// Which head animation UpdateHeadChargeAnimation shows: charging at a frame, fully charged, the shot or the other shot. +enum HeadCharge +{ + HEAD_CHARGE_CHARGING, + HEAD_CHARGE_CHARGED, + HEAD_CHARGE_SHOOT, + HEAD_CHARGE_SHOOT_ALT +}; + // A Technology laser to fire (Entity_Player::FireTechLaser's arguments): from a position along a direction, from an // eye or another offset, once or lasting, and its damage scale. A source other than the player spawns it. struct TechLaserShot @@ -100,6 +115,28 @@ struct TechLaserShot bool isOneHit = false; }; +// A Tech X ring to fire (Entity_Player::FireTechXLaser's arguments): from a position at a velocity, its radius and +// damage multiplier. A source other than the player spawns it. +struct TechXShot +{ + Vector position{}; + Vector velocity{}; + Entity* source = nullptr; + float damageMultiplier = 1; + float radius = 0; +}; + +// A knife to fire (Entity_Player::FireKnife's arguments): its variant and subtype, the entity it hangs from, the +// angle it sits at around it, and whether the room may not overwrite it. +struct KnifeShot +{ + Entity* parent = nullptr; + float rotationOffset = 0; + int subType = 0; + int variant = 0; + bool isCantOverwrite = false; +}; + // A Brimstone beam to fire (Weapon::FireBrimstone's arguments): from an entity at a position along a direction, its // damage multiplier and BrimstoneFireFlags. struct BrimstoneShot @@ -213,15 +250,19 @@ struct Weapon Entity_Tear* fire_tear(const PosVel& shot, uint32_t fireFlags, float damageMultiplier, float positionStep); void TriggerTearEffects(const Vector& shootDirection, int count); - static bool is_held_item(ANM2& sprite, std::string_view animName, void* itemDesc); + static bool is_held_item(CostumeSpriteDesc& costume, std::string_view animName, ItemConfig_Item* item); + void UpdateHeadChargeAnimation(int collectibleId, HeadCharge chargeType, const Vector& aim, float chargeFrame); + void play_brimstone_costume_shoot(const Vector& aim, float frame); void stop_costume_item_anim(int collectibleId); bool IsItemAnimFinished(int collectibleId); bool is_c_section_anim_finished(); + void update_c_section_charge_anim(HeadCharge chargeType, const Vector& aim, float chargeFrame); Vector GetOwnerLaserOffset(int laserOffsetId, const Vector& shootDirection); static Entity_Bomb* fire_bomb(Weapon& weapon, const PosVel& shot); static Entity_Laser* FireBrimstone(const BrimstoneShot& shot); Entity_Laser* fire_brimstone_with_color(const Vector& shootDirection, float damageMultiplier, uint32_t fireFlags); Entity_Laser* fire_laser(const TechLaserShot& shot); + Entity_Laser* fire_tech_x_laser(const TechXShot& shot); Entity_Knife* fire_knife(Entity* knifeParent, int knifeVariant, bool isCantOverwrite, float rotationOffset); Entity_Knife* FireSword(Entity* swordParent, int swordVariant, float rotationOffset, bool isUnknown1, bool isUnknown2, int unknown3, Entity* unknown4); @@ -254,3 +295,9 @@ struct Weapon_Tears : Weapon }; WeaponPtr weapon_create(WeaponType type, Entity* owner); +void costume_item_anim_set(Entity_Player& player, ItemConfig_Item* item, std::string_view animName, int frame); +void costume_item_frame_set(Entity_Player& player, ItemConfig_Item* item, std::string_view animName, int frame); +int costume_item_frame_get(Entity_Player& player, ItemConfig_Item* item); +void weapon_lua_laser_register(lua_State* state); +void weapon_lua_knife_register(lua_State* state); +void weapon_lua_player_register(lua_State* state); diff --git a/src/weapon_knives.cpp b/src/weapon_knives.cpp new file mode 100644 index 0000000..7123ebd --- /dev/null +++ b/src/weapon_knives.cpp @@ -0,0 +1,276 @@ +#include "weapon_knives.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "log.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include +#include + +constexpr float KNIFE_CHARGE_DELAYS = 4; +constexpr float KNIFE_CHARGE_MINIMUM = 0.001f; +constexpr float KNIFE_RANGE_SHARE = 0.6f; +constexpr float KNIFE_RANGE_DEFAULT = 260; +constexpr float KNIFE_REACH = 300; +constexpr float KNIFE_ORBIT_REACH = 100000; +constexpr float KNIFE_MIN_RANGE = 0.1f; +constexpr float KNIFE_AIM_NEAR = 50; +constexpr float KNIFE_AIM_RANGE = 250; +constexpr float KNIFE_AIM_RELEASE_BASE = 5; +constexpr float KNIFE_FLYING_LIFT = -15; +constexpr float KNIFE_FAMILIAR_SCALE = 0.75f; +constexpr float KNIFE_FAMILIAR_LIFT = -20; +constexpr float KNIFE_RANDOM_TURN = 360; +constexpr int KNIFE_HELD_BLINK = 7; +constexpr int KNIFE_THROWN_BLINK = 15; +constexpr float KNIFE_THROWN_NEAR = 25; +constexpr int KNIFE_HEAD_LOCK = 2; +// The angles the knife slots sit at around the aim: ahead, behind (Mom's Eye) and both sides (Loki's Horns). +constexpr std::array KNIFE_SLOT_ANGLES = {0, 180, 90, -90}; + +// 009f9020's maker for the knife weapon (009f9540), or none for the other types. +Weapon* weapon_knife_make(WeaponType type) +{ + return type == WEAPON_KNIFE ? new Weapon_Knife() : nullptr; +} + +// 009f6a60 Fires a knife through the owning player (a familiar's player), spawned by the owner. +Entity_Knife* Weapon::fire_knife(Entity* knifeParent, int knifeVariant, bool isCantOverwrite, float rotationOffset) +{ + Entity_Player* player = owner_player(); + if (!player) return nullptr; + + Entity_Knife* knife = player->FireKnife({.parent = knifeParent, + .rotationOffset = rotationOffset, + .variant = knifeVariant, + .isCantOverwrite = isCantOverwrite}); + knife->spawnerEntity = owner; + return knife; +} + +// 00a04f90 Removes Technology 2's laser and the knives, and forgets them. +void Weapon_Knife::ClearReferences() +{ + Weapon::ClearReferences(); + for (EntityPtr& knife : knives) + { + if (!knife) continue; + knife->Remove(); + knife = nullptr; + } +} + +// 00a05010 The charge a full throw takes: four fire delays, none under Ludovico. +float Weapon_Knife::GetMaxCharge() +{ + if (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) return 0; + return std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM) * KNIFE_CHARGE_DELAYS; +} + +// The knife is what the camera follows under Ludovico (Weapon_Bombs::GetFocusEntity 009fa190, which knives share). +Entity* Weapon_Knife::GetFocusEntity() +{ + return (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) ? knives[0].get() : nullptr; +} + +// 009fef20 A new room brings the knives back to rest (Entity_Knife::Reset, inlined). The Forgotten's club shares it. +void Weapon_Knife::TriggerNewRoom() +{ + for (EntityPtr& knife : knives) + if (knife) static_cast(knife.get())->Reset(); +} + +// Marked's target (Weapon_Bombs::GetMarkedTargetVariant 009fa1b0, which knives share). +int Weapon_Knife::GetMarkedTargetVariant() +{ + return marked_target_variant(); +} + +// 00a05060 Knives ride a Tractor Beam unless Ludovico holds them. +bool Weapon_Knife::SupportsTractorBeam() +{ + return !(modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE); +} + +// 00a05070 Gives a knife the owner's look: lifted to the player's offset (higher while it flies or is lifted), its +// tear color and flags (and Ludovico's), its damage, smaller and higher for a familiar. +void Weapon_Knife::init_knife(Entity_Knife& knife) +{ + Vector offset = vector_make(0, KNIFE_LIFT); + if (Entity_Player* player = owner_player()) + { + offset = vector_add(player->posOffset, offset); + if (player->HasEntityFlags(FLAG_HELD)) offset.y += KNIFE_FLYING_LIFT; + int gridClass = player->entityGridCollisionClass; + if (gridClass == GRIDCOLL_NONE || gridClass == GRIDCOLL_WALLS || gridClass == GRIDCOLL_WALLS_X || + gridClass == GRIDCOLL_WALLS_Y) + offset = vector_add(offset, vector_scale(player->GetFlyingOffset(), 1 / LASER_SCREEN_SCALE)); + } + + knife.SetColor(get_tear_color(), -1, COLOR_PRIORITY_DEFAULT, false, true); + knife.tearFlags = get_owner_tear_flags(); + if (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) knife.tearFlags.set(TEAR_LUDOVICO); + knife.SetCollisionDamage(get_damage()); + if (owner && owner->IsFamiliar()) + { + knife.sprite.scale = vector_make(KNIFE_FAMILIAR_SCALE, KNIFE_FAMILIAR_SCALE); + offset.y = KNIFE_FAMILIAR_LIFT; + } + knife.posOffset = vector_make(0, offset.y); +} + +// The knives held this frame: the main one always, Mom's Eye's behind and Loki's Horns' on every side, spawned at +// their angle when missing and removed when their item is gone. +void Weapon_Knife::knives_hold(int variant) +{ + Entity_Player* player = owner_player(); + bool isLokisHorns = player && player->HasCollectible(COLLECTIBLE_LOKIS_HORNS); + bool isMomsEye = player && player->HasCollectible(COLLECTIBLE_MOMS_EYE); + + for (int slot = 0; slot < KNIFE_SLOT_COUNT; slot++) + { + EntityPtr& held = knives[slot]; + if (slot == 0 || (slot == 1 && isMomsEye) || isLokisHorns) + { + if (held) continue; + Entity_Knife* knife = fire_knife(owner, variant, true, 0); + held = knife; + knife->rotation = KNIFE_SLOT_ANGLES[slot]; + knife->Update(); + } + else if (held) + { + held->Remove(); + held = nullptr; + } + } +} + +// Turns the held knives toward an aim, each at its slot's angle. +void Weapon_Knife::knives_aim(const Vector& aim) +{ + for (int slot = 0; slot < KNIFE_SLOT_COUNT; slot++) + { + Entity_Knife* knife = static_cast(knives[slot].get()); + if (!knife) continue; + + knife->rotation = angle_wrap(vector_angle(aim) + KNIFE_SLOT_ANGLES[slot]); + knife->rotationOffset = 0; + } +} + +// Throws the held knives that fire this time (the side ones when the volley shoots sideways or backwards) with the +// charge, as far as the range allows, each with the volley's extra knives fanned around it, and the volley's random +// knives around the main one. +void Weapon_Knife::knives_throw(const KnifeThrow& knifeThrow) +{ + float maxShot = std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM) * KNIFE_CHARGE_DELAYS; + float chargeUsed = std::min(charge, maxShot); + Entity_Knife& main = *static_cast(knives[0].get()); + int variant = knifeThrow.variant; + TriggerTearEffects(knifeThrow.direction, 1); + + float reach = main.tearFlags[TEAR_ORBIT] ? KNIFE_ORBIT_REACH : KNIFE_REACH; + float throwRange = std::max(std::min(reach, knifeThrow.range), knifeThrow.minRange); + Entity_Player* player = owner_player(); + Weapon_MultiShotParams params; + params.numTears = 0; + if (player) params = player->GetMultiShotParams(weaponType); + float shotSpeed = player ? player->shotSpeed : 1; + + for (int slot = 0; slot < KNIFE_SLOT_COUNT; slot++) + { + Entity_Knife* knife = static_cast(knives[slot].get()); + if (!knife || (slot == 1 && !params.isShootingBackwards) || (slot >= 2 && !params.isShootingSideways)) + continue; + + knife->Shoot(chargeUsed / maxShot, throwRange); + for (int i = 0; i < params.numTears; i++) + { + PosVel shot = + Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_KNIFE, vector_make(1, 0), shotSpeed, params); + float angle = vector_angle(shot.velocity); + if (i == params.numTears / 2) knife->rotationOffset = angle_wrap(angle); + else fire_knife(knife, variant, false, angle)->Update(); + } + } + for (int i = 0; i < params.numRandomDirTears; i++) + fire_knife(knives[0], variant, false, random_unit() * KNIFE_RANDOM_TURN)->Update(); + charge = 0; + direction = {}; +} + +// 00a03f90 Holds, charges and throws Mom's Knife: the knives sit around the owner turned toward the aim, charge while +// shooting and fly off on release (or once Marked's aim has charged enough). A thrown knife keeps the head turned. +// Ludovico's knife is not reconstructed yet. +void Weapon_Knife::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Weapon::Fire(shootDirection, isShooting, isInterpolated); + Entity_Player* player = owner_player(); + Entity_Player* shooter = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + bool isTractorBeam = modifiers & WEAPON_MOD_TRACTOR_BEAM; + bool isMarked = player && player->HasCollectible(COLLECTIBLE_MARKED); + float maxCharge = std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM); + int variant = shooter && shooter->temporaryEffects.HasNullEffect(NULLITEM_BLOODY_BABYLON) ? KNIFE_SUMPTORIUM + : KNIFE_MOMS_KNIFE; + float range = (player ? player->tearRange : KNIFE_RANGE_DEFAULT) * KNIFE_RANGE_SHARE; + if (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) + reconstruction_missing("Weapon_Knife::Fire 00a03f90 (Ludovico's knife)"); + + Entity* markedTarget = player ? player->markedTarget : nullptr; + Vector target = markedTarget && isMarked ? markedTarget->pos : fixedDirection; + bool isAimFixed = !vector_is_zero(target); + bool isShootingNow = isShooting; + float minRange = KNIFE_MIN_RANGE; + if (!isInterpolated && isShooting && isAimFixed) + { + float distance = vector_length(vector_sub(target, get_owner_position())); + float share = std::clamp((distance - KNIFE_AIM_NEAR) / KNIFE_AIM_RANGE, 0.0f, 1.0f); + float release = (maxCharge * KNIFE_CHARGE_DELAYS - KNIFE_AIM_RELEASE_BASE) * share + KNIFE_AIM_RELEASE_BASE - 1; + if (release > 0) minRange = std::max(distance / (release / maxCharge * KNIFE_CHARGE_DELAYS), KNIFE_MIN_RANGE); + if (release < charge) isShootingNow = false; + } + + knives_hold(variant); + Entity_Knife* main = static_cast(knives[0].get()); + if (!main) return; + for (EntityPtr& knife : knives) + if (knife) init_knife(*static_cast(knife.get())); + + if (!main->isFlying || isTractorBeam || isAimFixed) + { + Vector aim = shootDirection; + if (!isShootingNow && !main->isFlying && charge > 0 && !isAimFixed) aim = direction; + if (vector_is_zero(aim)) + { + int facing = shooter ? (int)shooter->headDirection + : (owner && owner->IsFamiliar() ? static_cast(owner)->shootDirection + : (int)DIRECTION_NONE); + if (facing != DIRECTION_NONE) aim = vector_from_direction(facing); + } + if (isTractorBeam && !isAimFixed) aim = vector_cardinal(aim); + knives_aim(aim); + } + + if (!isShootingNow) + { + if (!main->isFlying && charge > 0) + knives_throw({.direction = shootDirection, .minRange = minRange, .range = range, .variant = variant}); + } + else if (!main->isFlying) + { + if (!isInterpolated) + charge = std::min(charge + (owner ? owner->speedMultiplier : 1), maxCharge * KNIFE_CHARGE_DELAYS); + direction = get_aim_direction(shootDirection); + } + + bool isThrownClose = main->isFlying && main->knifeDistance < KNIFE_THROWN_NEAR && main->knifeVelocity > 0; + SetBlinkTime(isThrownClose ? KNIFE_THROWN_BLINK : KNIFE_HELD_BLINK); + if (main->isFlying && !isAimFixed && !isTractorBeam) SetHeadLockTime(KNIFE_HEAD_LOCK); +} diff --git a/src/weapon_knives.h b/src/weapon_knives.h new file mode 100644 index 0000000..14586ab --- /dev/null +++ b/src/weapon_knives.h @@ -0,0 +1,56 @@ +#pragma once + +#include "weapon.h" +#include + +constexpr int KNIFE_SLOT_COUNT = 4; +// How far above its parent a knife hangs. +constexpr float KNIFE_LIFT = -10; + +// The knives (Lua's KnifeVariant): Mom's Knife, the Forgotten's swung weapons, Bloody Babylon's and the swords. +enum KnifeVariant : int +{ + KNIFE_MOMS_KNIFE, + KNIFE_BONE_CLUB, + KNIFE_BONE_SCYTHE, + KNIFE_DONKEY_JAWBONE, + KNIFE_BAG_OF_CRAFTING, + KNIFE_SUMPTORIUM, + KNIFE_NOTCHED_AXE = 9, + KNIFE_SPIRIT_SWORD = 10, + KNIFE_TECH_SWORD = 11 +}; + +// A throw of the held knives: the shot's direction, how far the range lets them fly (at least minRange) and the +// variant of the extra knives. +struct KnifeThrow +{ + Vector direction{}; + float minRange = 0; + float range = 0; + int variant = 0; +}; + +// Destruction (009f99b0) is the default. +// The weapon that holds and throws Mom's Knife: the main knife, Mom's Eye's knife behind and Loki's Horns' knives to +// the sides, charged while shooting and thrown on release (or steered by Ludovico). +struct Weapon_Knife : Weapon +{ + std::array knives; + + void Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) override; + void ClearReferences() override; + float GetMaxCharge() override; + Entity* GetFocusEntity() override; + void TriggerNewRoom() override; + int GetMarkedTargetVariant() override; + bool SupportsTractorBeam() override; + + void init_knife(Entity_Knife& knife); + void knives_hold(int variant); + void knives_aim(const Vector& aim); + void knives_throw(const KnifeThrow& knifeThrow); + void ludovico_update(const Vector& shootDirection, bool isShooting, bool isInterpolated); +}; + +Weapon* weapon_knife_make(WeaponType type); diff --git a/src/weapon_lasers.cpp b/src/weapon_lasers.cpp index 84d97ac..32a06ce 100644 --- a/src/weapon_lasers.cpp +++ b/src/weapon_lasers.cpp @@ -41,6 +41,31 @@ constexpr float FAMILIAR_BRIMSTONE_REACH = 10; constexpr float FAMILIAR_BRIMSTONE_LIFT = 4; constexpr float FAMILIAR_BRIMSTONE_HEIGHT = 23; constexpr const char* NULL_MOUTH = "Mouth"; +constexpr float RAPID_BEAM_DAMAGE = 0.2f; +constexpr float RAPID_CHOCOLATE_DAMAGE = 1.25f; +constexpr float CHOCOLATE_DAMAGE_MIN = 0.1f; +constexpr float CHOCOLATE_DAMAGE_MAX = 2.5f; +constexpr float CHOCOLATE_RELEASE_SHARE = 0.25f; +constexpr float CHOCOLATE_AIM_NEAR = 50; +constexpr float CHOCOLATE_AIM_RANGE = 250; +constexpr float TEAR_EFFECT_INTERVAL = 4; +constexpr float BEAM_SWEEP_SPEED = 8; +constexpr float HEAD_FRAME_KEEP = -2; +constexpr float HELD_BEAM_LOOP_START = 8; +constexpr int HELD_BEAM_LOOP_FRAME = 15; +constexpr int HELD_BEAM_TIMEOUT = 8; +constexpr int HELD_BEAM_MIN_TIMEOUT = 4; +constexpr int FAMILIAR_BEAM_BLINK = 10; +constexpr float LUDOVICO_RING_LIFT = -20; +constexpr float LUDOVICO_RETURN_PUSH = 0.15f; +constexpr float LUDOVICO_RETURN_DISTANCE_SQUARED = 10000; +constexpr float NO_RELEASE_CHARGE = -1000; +constexpr float TECH_X_RADIUS_MIN = 15; +constexpr float TECH_X_RADIUS_RANGE = 45; +constexpr float TECH_X_DAMAGE_MIN = 0.25f; +constexpr float TECH_X_DAMAGE_RANGE = 0.75f; +constexpr float TECH_X_RANDOM_SPREAD = 50; +constexpr int TECH_X_BLINK_MIN = 11; // 009f9020's makers for the laser weapons (009f94c0, 009f9640, 009f91f0): a fresh weapon of the type, or none for the // other types. @@ -267,7 +292,8 @@ bool Weapon_Laser::SupportsTractorBeam() return !(modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE); } -// 00a06330 Gives a laser the owner's tear flags, laser color and damage. +// 00a06330 Gives a laser the owner's tear flags, laser color and damage (Weapon_Brimstone::init_laser 00a00f90 is the +// same). void Weapon_Laser::init_laser(Weapon& weapon, Entity_Laser& laser) { laser.tearFlags = weapon.get_owner_tear_flags(); @@ -430,12 +456,339 @@ int Weapon_Brimstone::GetMarkedTargetVariant() return (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) ? 0 : marked_variant_get(weapon_player(owner)); } -// The charging and firing of Brimstone are not reconstructed yet. - -// 009ff360 -void Weapon_Brimstone::Fire(const Vector&, bool, bool) +// What Brimstone's Fire works out about the owner before it decides to charge or fire. +struct BrimstoneAim { - reconstruction_missing("Weapon_Brimstone::Fire 009ff360"); + Vector target{}; + Entity_Player* player = nullptr; + float maxCharge = 0; + float shotSpeed = 1; + bool isAimFixed = false; + bool isFullyCharged = false; + bool isHasBrimstone = false; + bool isHasMarked = false; + bool isRapid = false; + bool isRapidBeam = false; +}; + +// The charge part of Brimstone's Fire: a beam left on its parent goes, the head charges toward a full beam (unless +// the costume shoots its other shot) as the charge grows by the owner's speed, and the aim follows the input. +void Weapon_Brimstone::charge_update(const Vector& shootDirection, bool isCharging, bool isInterpolated) +{ + Entity* beam = mainLaser; + if (beam && beam->parent && beam->parent->type != ENTITY_EFFECT) beam->Remove(); + + bool isShootAlt = false; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BRIMSTONE); + if (owner && owner->is_player()) + for (PlayerCostumeMap& map : owner->ToPlayer()->playerCostumeMap) + { + if (map.index < 0 || map.isBodyLayer) continue; + + CostumeSpriteDesc& costume = owner->ToPlayer()->costumeSpriteDescs[map.index]; + if (!is_held_item(costume, "", item) || !costume.sprite.IsPlaying()) continue; + + isShootAlt = costume.sprite.GetAnimation().ends_with("ShootAlt"); + break; + } + + bool isCSection = modifiers & WEAPON_MOD_C_SECTION; + if (isCharging) + { + float maxCharge = GetMaxCharge(); + if (charge < maxCharge) + { + float frame = charge / maxCharge * HEAD_CHARGE_FRAMES; + if (!isCSection && !isShootAlt) + UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_CHARGING, shootDirection, frame); + else if (isCSection && is_c_section_anim_finished()) + update_c_section_charge_anim(HEAD_CHARGE_CHARGING, shootDirection, frame); + if (!isInterpolated) charge += owner ? owner->speedMultiplier : 1; + } + else if (isCSection) update_c_section_charge_anim(HEAD_CHARGE_CHARGED, shootDirection, -1); + else if (!isShootAlt) UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_CHARGED, shootDirection, -1); + } + + direction = IsAxisAligned() ? shootDirection : get_aim_direction(shootDirection); + SetBlinkTime(1); +} + +// Fires one beam of a volley along a direction and links it to the main beam, or makes it the main beam. +Entity_Laser* Weapon_Brimstone::fire_beam(const Vector& beamDirection, float damageScale, uint32_t fireFlags) +{ + Entity_Laser* laser = fire_brimstone_with_color(beamDirection, damageScale, fireFlags); + laser->parent = mainLaser; + laser->Update(); + return laser; +} + +// The release part of Brimstone's Fire: without enough charge the costume stops, otherwise the volley's beams fire +// (weak for a rapid fire, scaled by Chocolate Milk) along the aim, with the extra backward, sideways and random ones. +// A beam out triggers the tear effects, and under Marked or a rapid fire it sweeps the beams toward the aim. +void Weapon_Brimstone::release(const Vector& shootDirection, const BrimstoneAim& aim, bool isInterpolated) +{ + bool isChocolateMilk = modifiers & WEAPON_MOD_CHOCOLATE_MILK; + bool isCSection = modifiers & WEAPON_MOD_C_SECTION; + bool isAntiGravity = modifiers & WEAPON_MOD_ANTI_GRAVITY; + float threshold = isChocolateMilk ? std::max(aim.maxCharge * CHOCOLATE_RELEASE_SHARE, CHARGE_MINIMUM) : aim.maxCharge; + + if (charge < threshold) + { + int blink = 0; + if (owner && owner->is_player()) blink = owner->ToPlayer()->blinkTime; + else if (owner && owner->IsFamiliar()) blink = static_cast(owner)->headFrameDelay; + if (mainLaser || blink > 1) + { + if (owner && owner->is_player() && IsItemAnimFinished(COLLECTIBLE_BRIMSTONE)) + stop_costume_item_anim(COLLECTIBLE_BRIMSTONE); + } + else stop_costume_item_anim(COLLECTIBLE_BRIMSTONE); + if (!mainLaser && owner && owner->is_player() && isCSection && is_c_section_anim_finished()) + update_c_section_charge_anim(HEAD_CHARGE_CHARGING, shootDirection, 0); + } + else + { + uint32_t fireFlags = (aim.isRapid ? BRIMSTONE_FIRE_WEAK : 0) | (isCSection ? BRIMSTONE_FIRE_C_SECTION : 0); + Vector beamDirection = aim.isAimFixed ? shootDirection : direction; + beamDirection = IsAxisAligned() ? vector_cardinal(beamDirection) : vector_normalized(beamDirection); + + float damageScale = 1; + if (aim.isRapidBeam) + { + damageScale = SHOTS_PER_SECOND / (maxFireDelay + 1) * RAPID_BEAM_DAMAGE; + if (isChocolateMilk) damageScale *= RAPID_CHOCOLATE_DAMAGE; + } + else if (isChocolateMilk) + damageScale = std::clamp(charge / aim.maxCharge, CHOCOLATE_DAMAGE_MIN, CHOCOLATE_DAMAGE_MAX); + if (modifiers & WEAPON_MOD_AZAZELS_SNEEZE) + { + fireFlags |= BRIMSTONE_FIRE_BURST; + if (!aim.isHasBrimstone) damageScale *= 0.5f; + } + + Weapon_MultiShotParams params = GetMultiShotParams(); + aimAngle = vector_angle(beamDirection); + if (isCSection) update_c_section_charge_anim(HEAD_CHARGE_SHOOT, beamDirection, -1); + else UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_SHOOT, beamDirection, -1); + + Entity_Laser* first = nullptr; + for (int i = 0; i < params.numTears; i++) + { + PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_BRIMSTONE, beamDirection, + aim.shotSpeed, params); + Entity_Laser* laser = fire_brimstone_with_color(shot.velocity, damageScale, fireFlags); + laser->Update(); + if (first) laser->parent = first; + else mainLaser = first = laser; + } + for (int i = 0; i < params.numRandomDirTears; i++) fire_beam(random_direction(), damageScale, fireFlags); + if (params.isShootingBackwards) fire_beam(vector_scale(beamDirection, -1), damageScale, fireFlags); + if (params.isShootingSideways) + { + fire_beam(vector_make(-beamDirection.y, beamDirection.x), damageScale, fireFlags); + fire_beam(vector_make(beamDirection.y, -beamDirection.x), damageScale, fireFlags); + } + if (isAntiGravity && isCSection) fire_c_section_fetuses(); + } + + Entity* beam = mainLaser; + if (beam && !isInterpolated) + { + TriggerTearEffects(shootDirection, beam->GetIntervalTicks(TEAR_EFFECT_INTERVAL, 0)); + if (!isAntiGravity && beam->GetIntervalTicks(TEAR_EFFECT_INTERVAL, 0) && isCSection) fire_c_section_fetuses(); + if (aim.isHasMarked || (aim.isRapidBeam && aim.isFullyCharged)) sweep(shootDirection, aim); + else + { + SetHeadLockTime(2); + if (owner && owner->IsFamiliar()) SetBlinkTime(FAMILIAR_BEAM_BLINK); + } + } + charge = 0; +} + +// Turns the main beam and the beams on it toward the aim, by at most eight degrees a frame, facing them behind the +// head when aimed up. A rapid beam at full charge also follows the mouth and keeps going. The head shows the shot. +void Weapon_Brimstone::sweep(const Vector& shootDirection, const BrimstoneAim& aim) +{ + float targetAngle = vector_angle(shootDirection); + bool isHeld = aim.isRapidBeam && aim.isFullyCharged; + + for (Entity* entity : entity_query(ENTITY_LASER, -1)) + { + if (entity != mainLaser && entity->parent != mainLaser) continue; + + Entity_Laser& laser = *static_cast(entity); + laser.isActiveRotating = true; + laser.rotationDelay = 0; + laser.rotationDegrees = angle_difference(laser.angleDegrees, laser.angleDegrees - aimAngle + targetAngle); + laser.rotationSpd = laser.rotationDegrees >= 0 ? BEAM_SWEEP_SPEED : -BEAM_SWEEP_SPEED; + bool isFacingUp = std::sin(laser.angleDegrees * DEGREES_TO_RADIANS) <= -TECH_LASER_FACING; + laser.renderDepthOffset = isFacingUp ? TECH_LASER_BACK_DEPTH : TECH_LASER_FRONT_DEPTH; + if (!isHeld) continue; + + laser.posOffset = GetOwnerLaserOffset(LASER_OFFSET_BRIMSTONE, shootDirection); + laser.timeout = std::max(laser.timeout, HELD_BEAM_TIMEOUT); + } + + float step = std::clamp(angle_difference(aimAngle, targetAngle), -BEAM_SWEEP_SPEED, BEAM_SWEEP_SPEED); + aimAngle = angle_wrap(aimAngle + step); + if (IsItemAnimFinished(COLLECTIBLE_BRIMSTONE)) return; + + if (modifiers & WEAPON_MOD_C_SECTION) + { + update_c_section_charge_anim(HEAD_CHARGE_SHOOT, shootDirection, 0); + return; + } + UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_SHOOT, shootDirection, HEAD_FRAME_KEEP); + Entity_Player* player = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BRIMSTONE); + if (isHeld && player && costume_item_frame_get(*player, item) > HELD_BEAM_LOOP_FRAME) + play_brimstone_costume_shoot(shootDirection, HELD_BEAM_LOOP_START); +} + +// Ludovico's part of Brimstone's Fire: one ring beam that the input steers (or that drifts back to an owner in a +// clear room), remade when its variant changes, thicker with a second Brimstone, triggering tear effects as it +// moves. +void Weapon_Brimstone::ludovico_update(const Vector& shootDirection, const BrimstoneAim& aim, bool isShooting, + bool isInterpolated) +{ + Vector ownerPosition = get_owner_position(); + Entity* ring = mainLaser; + Vector ringPosition = ring ? ring->pos : ownerPosition; + float ringScale = 1; + + if (!isInterpolated) + { + bool isTechnology = aim.player && aim.player->HasCollectible(COLLECTIBLE_TECHNOLOGY); + int variant = isTechnology ? LASER_BRIM_TECH : LASER_THICK_RED; + if ((modifiers & WEAPON_MOD_AZAZELS_SNEEZE) && !aim.isHasBrimstone) ringScale = 0.5f; + if (aim.player && aim.player->GetCollectibleNum(COLLECTIBLE_BRIMSTONE) > 1) ringScale += ringScale; + if (owner && owner->IsFamiliar()) ringScale *= 0.5f; + if (ringScale > BRIMSTONE_THICKER_SCALE) + { + variant = variant == LASER_BRIM_TECH ? LASER_THICKER_BRIM_TECH : LASER_THICKER_RED; + ringScale *= 0.5f; + } + + if (ring && (ring->subtype != LASER_SUBTYPE_RING_LUDOVICO || ring->variant != variant)) + { + ring->Remove(); + mainLaser = ring = nullptr; + } + if (!ring) + { + Entity_Laser* laser = static_cast(g_game->Spawn({.position = ringPosition, + .spawner = owner, + .subType = LASER_SUBTYPE_RING_LUDOVICO, + .type = ENTITY_LASER, + .variant = variant, + .seed = Random()})); + laser->posOffset = vector_make(0, LUDOVICO_RING_LIFT); + laser->parent = owner; + laser->renderDepthOffset = TECH_LASER_FRONT_DEPTH; + laser->scale = ringScale; + laser->ResetSpriteScale(); + Weapon_Laser::init_laser(*this, *laser); + laser->Update(); + mainLaser = ring = laser; + } + } + if (!ring) return; + + if (isShooting) + { + Vector push = shootDirection; + if (vector_length_squared(push) > 1) push = vector_normalized(push); + ring->AddVelocity_divided(vector_scale(push, aim.shotSpeed), false); + } + else if (g_game->room->GetAliveEnemiesCount() < 1) + { + Vector away = vector_sub(ownerPosition, ring->pos); + if (vector_length_squared(away) > LUDOVICO_RETURN_DISTANCE_SQUARED) + ring->AddVelocity_divided(vector_scale(vector_normalized(away), LUDOVICO_RETURN_PUSH), false); + } + if (isInterpolated) return; + + Entity_Laser& laser = *static_cast(ring); + Weapon_Laser::init_laser(*this, laser); + laser.scale = ringScale; + laser.ResetSpriteScale(); + Entity* shooter = owner && owner->is_player() ? owner : nullptr; + if (!shooter || !shooter->GetIntervalTicks(aim.maxCharge, 0)) return; + + bool isApart = laser.pos.x != owner->pos.x || laser.pos.y != owner->pos.y; + TriggerTearEffects(isApart ? vector_normalized(vector_sub(laser.pos, owner->pos)) : random_direction(), 1); +} + +// What Brimstone's Fire decides from the owner: its player, shot speed and charge, the aim Marked's target or a +// fixed aim gives, and whether a rapid fire (Soy Milk or a fast fire delay) is already at full charge. +BrimstoneAim Weapon_Brimstone::aim_get(bool isShooting) +{ + BrimstoneAim aim; + aim.player = weapon_player(owner); + aim.shotSpeed = aim.player ? aim.player->shotSpeed : 1; + aim.maxCharge = std::max(maxFireDelay, CHARGE_MINIMUM); + aim.isHasBrimstone = aim.player && aim.player->HasCollectible(COLLECTIBLE_BRIMSTONE); + aim.isRapid = (modifiers & WEAPON_MOD_SOY_MILK) || maxFireDelay <= 1; + aim.isRapidBeam = aim.isRapid && !(modifiers & WEAPON_MOD_ANTI_GRAVITY); + aim.isHasMarked = aim.player && aim.player->HasCollectible(COLLECTIBLE_MARKED); + + bool isMarking = aim.player && (aim.isHasMarked || aim.player->HasCollectible(COLLECTIBLE_EYE_OF_THE_OCCULT)); + Entity* markedTarget = aim.player ? aim.player->markedTarget : nullptr; + aim.target = isMarking && markedTarget ? markedTarget->pos : fixedDirection; + aim.isAimFixed = !vector_is_zero(aim.target); + + Entity* beam = mainLaser; + bool isBeamHeld = beam && static_cast(beam)->timeout > HELD_BEAM_MIN_TIMEOUT; + aim.isFullyCharged = aim.isRapid && (aim.maxCharge <= charge || (isShooting && aim.isRapidBeam && isBeamHeld)); + return aim; +} + +// 009ff360 Charges and fires Brimstone: while shooting the head charges, on release (or once a fixed aim or Marked's +// charge is enough) the beams fire. A rapid fire keeps one beam going and sweeps it, Ludovico steers a ring beam. +// C Section's fetuses and Hemoptysis' sneeze are not reconstructed yet. With C Section, the body faces the beam. +void Weapon_Brimstone::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Weapon::Fire(shootDirection, isShooting, isInterpolated); + BrimstoneAim aim = aim_get(isShooting); + bool isShootingNow = isShooting; + + if (modifiers & WEAPON_MOD_LUDOVICO_TECHNIQUE) ludovico_update(shootDirection, aim, isShooting, isInterpolated); + else + { + bool isCharging = fireDelay < 0 || charge > 0; + if (!aim.isFullyCharged) + { + if (!isInterpolated && isShooting && aim.isAimFixed) + { + float threshold = aim.maxCharge; + if (modifiers & WEAPON_MOD_CHOCOLATE_MILK) + { + float distance = vector_length(vector_sub(aim.target, get_owner_position())); + float share = std::clamp((distance - CHOCOLATE_AIM_NEAR) / CHOCOLATE_AIM_RANGE, 0.0f, 1.0f); + threshold = (aim.maxCharge * CHOCOLATE_DAMAGE_MAX - aim.maxCharge * CHOCOLATE_RELEASE_SHARE) * + share + + aim.maxCharge * CHOCOLATE_RELEASE_SHARE; + } + if (threshold <= charge) isShootingNow = false; + } + Entity* beam = mainLaser; + if (beam && beam->parent && beam->parent->type != ENTITY_EFFECT && + (!aim.player || aim.isAimFixed || aim.player->twinPlayer)) + isShootingNow = false; + } + + bool isSneezing = modifiers & WEAPON_MOD_AZAZELS_SNEEZE; + bool isHeldCharge = isInterpolated || charge > 0 || fireDelay >= 0; + if (isSneezing && isShootingNow && !isHeldCharge && !aim.isFullyCharged) + reconstruction_missing("Weapon_Brimstone::Fire 009ff360 (Hemoptysis' sneeze, fire_hitscan 00a01020)"); + if (isShootingNow && !aim.isFullyCharged) charge_update(shootDirection, isCharging, isInterpolated); + else release(shootDirection, aim, isInterpolated); + } + + if (!(modifiers & WEAPON_MOD_C_SECTION)) return; + if (Entity* beam = mainLaser) bodyDirection = vector_from_angle(static_cast(beam)->angleDegrees); + else if (isShootingNow || is_c_section_anim_finished()) bodyDirection = shootDirection; } // 00a00d10 @@ -444,12 +797,6 @@ void Weapon_Brimstone::fire_c_section_fetuses() reconstruction_missing("Weapon_Brimstone::fire_c_section_fetuses 00a00d10"); } -// 00a00f90 -void Weapon_Brimstone::init_laser(Entity_Laser&) -{ - reconstruction_missing("Weapon_Brimstone::init_laser 00a00f90"); -} - // 00a01020 void Weapon_Brimstone::fire_hitscan() { @@ -474,8 +821,118 @@ int Weapon_TechX::GetMarkedTargetVariant() return marked_variant_get(weapon_player(owner)); } -// 00a0d9c0 The charging and firing of Tech X's rings are not reconstructed yet. -void Weapon_TechX::Fire(const Vector&, bool, bool) +// 00a0d9c0 Charges and fires Tech X's rings: the charge grows while shooting, and on release (or once a rapid fire, +// Marked's aim or a pee burst has charged enough) a volley of rings flies off, bigger and stronger the longer it +// charged, with the extra backward, mirrored and random ones. +void Weapon_TechX::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) { - reconstruction_missing("Weapon_TechX::Fire 00a0d9c0"); + Weapon::Fire(shootDirection, isShooting, isInterpolated); + if (isInterpolated) return; + + Entity_Player* player = weapon_player(owner); + float shotSpeed = player ? player->shotSpeed : 1; + bool isHasMarked = player && player->HasCollectible(COLLECTIBLE_MARKED); + bool isRapid = (modifiers & WEAPON_MOD_SOY_MILK) || maxFireDelay <= 0; + Entity* markedTarget = player ? player->markedTarget : nullptr; + Vector target = markedTarget && isHasMarked ? markedTarget->pos : fixedDirection; + + float releaseCharge = NO_RELEASE_CHARGE; + if (isShooting && isRapid) releaseCharge = maxFireDelay * TECH_X_CHARGE; + else if (isShooting && !vector_is_zero(target)) + { + float distance = vector_length(vector_sub(target, get_owner_position())); + float share = std::clamp((distance - CHOCOLATE_AIM_NEAR) / CHOCOLATE_AIM_RANGE, 0.0f, 1.0f); + releaseCharge = (maxFireDelay * TECH_X_CHARGE - maxFireDelay) * share + maxFireDelay; + } + if (owner && owner->is_player() && owner->ToPlayer()->peeBurstCooldown > 0) + releaseCharge = std::max(maxFireDelay, 1.0f); + bool isReleaseCharged = releaseCharge > NO_RELEASE_CHARGE && releaseCharge <= charge; + + Vector aim = isShooting ? shootDirection : direction; + aim = IsAxisAligned() ? vector_cardinal(aim) : vector_normalized(aim); + if (isShooting && !isReleaseCharged) + { + if (maxFireDelay * TECH_X_CHARGE <= charge) + UpdateHeadChargeAnimation(COLLECTIBLE_TECH_X, HEAD_CHARGE_CHARGED, shootDirection, -1); + else charge += owner ? owner->speedMultiplier : 1; + SetBlinkTime(1); + } + else + { + if (std::max(maxFireDelay, 1.0f) <= charge || isReleaseCharged) fire_rings(aim, shotSpeed); + charge = 0; + } + + if (isShooting) direction = IsAxisAligned() ? shootDirection : get_aim_direction(shootDirection); +} + +// Fires the charged volley of Tech X rings along an aim: their radius and damage grow from a quarter at one fire +// delay to full at three. +void Weapon_TechX::fire_rings(const Vector& aim, float shotSpeed) +{ + fireDelay = maxFireDelay; + SetBlinkTime(std::max(TECH_X_BLINK_MIN, LASER_BLINK_BASE - (int)(maxFireDelay * LASER_BLINK_SCALE))); + TriggerTearEffects(aim, 1); + + Vector position = get_owner_position(); + Vector velocity = vector_add(vector_scale(aim, LASER_AIM_SPEED), get_tear_movement_inheritance(aim)); + float fullDelay = maxFireDelay + 1; + float share = (std::min(charge + 1, fullDelay * TECH_X_CHARGE) - fullDelay) / (fullDelay + fullDelay); + float radius = share * TECH_X_RADIUS_RANGE + TECH_X_RADIUS_MIN; + float damageScale = share * TECH_X_DAMAGE_RANGE + TECH_X_DAMAGE_MIN; + Weapon_MultiShotParams params = GetMultiShotParams(); + auto fire_ring = [&](Vector ringPosition, Vector ringVelocity, float scale) { + fire_tech_x_laser({.position = ringPosition, + .velocity = ringVelocity, + .damageMultiplier = damageScale * scale, + .radius = radius * scale}) + ->Update(); + }; + + if (params.isShootingBackwards) fire_ring(position, vector_scale(velocity, -shotSpeed), 1); + if (params.isShootingSideways) + { + fire_ring(position, vector_make(velocity.x * shotSpeed, -velocity.y * shotSpeed), 1); + fire_ring(position, vector_make(-velocity.x * shotSpeed, velocity.y * shotSpeed), 1); + } + for (int i = 0; i < params.numRandomDirTears; i++) + { + float scale = random_unit() * 0.5f + 0.5f; + float angle = (random_unit() * TECH_X_RANDOM_SPREAD - TECH_X_RANDOM_SPREAD / 2) * DEGREES_TO_RADIANS; + Vector turned = vector_make(velocity.x * std::cos(angle) - velocity.y * std::sin(angle), + velocity.y * std::cos(angle) + velocity.x * std::sin(angle)); + fire_ring(position, vector_scale(turned, shotSpeed), scale); + } + for (int i = 0; i < params.numTears; i++) + { + PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_TECH_X, velocity, shotSpeed, params); + fire_ring(vector_add(position, shot.position), shot.velocity, 1); + } + + if (owner && owner->IsFamiliar()) static_cast(owner)->fireCooldown = 0; + else if (owner && owner->is_player()) owner->ToPlayer()->stop_costume_item_anims(); +} + +// 009f6980 Fires a Tech X ring: the owning player's, or a plain one from the owner. +Entity_Laser* Weapon::fire_tech_x_laser(const TechXShot& shot) +{ + if (Entity_Player* player = weapon_player(owner)) + { + TechXShot playerShot = shot; + playerShot.source = owner; + if (Entity_Laser* laser = player->FireTechXLaser(playerShot)) return laser; + } + + Entity_Laser* laser = static_cast(g_game->Spawn({.position = shot.position, + .velocity = shot.velocity, + .spawner = owner, + .subType = LASER_SUBTYPE_RING_PROJECTILE, + .type = ENTITY_LASER, + .variant = LASER_THIN_RED, + .seed = Random()})); + laser->posOffset = vector_make(0, LUDOVICO_RING_LIFT); + laser->parent = owner; + laser->renderDepthOffset = TECH_LASER_FRONT_DEPTH; + laser->radius = shot.radius; + return laser; } diff --git a/src/weapon_lasers.h b/src/weapon_lasers.h index 2a8d94a..cbf9357 100644 --- a/src/weapon_lasers.h +++ b/src/weapon_lasers.h @@ -36,8 +36,10 @@ struct Weapon_Laser : Weapon static void init_laser(Weapon& weapon, Entity_Laser& laser); }; +struct BrimstoneAim; + // Destruction (009f9a20) is the default. -// The weapon that charges and fires Brimstone's beams. +// The weapon that charges and fires Brimstone's beams. aimAngle is where the beams point, swept toward the aim. struct Weapon_Brimstone : Weapon { EntityPtr mainLaser; @@ -50,8 +52,13 @@ struct Weapon_Brimstone : Weapon Entity* GetMainEntity() override; int GetMarkedTargetVariant() override; + BrimstoneAim aim_get(bool isShooting); + void charge_update(const Vector& shootDirection, bool isCharging, bool isInterpolated); + void release(const Vector& shootDirection, const BrimstoneAim& aim, bool isInterpolated); + void sweep(const Vector& shootDirection, const BrimstoneAim& aim); + void ludovico_update(const Vector& shootDirection, const BrimstoneAim& aim, bool isShooting, bool isInterpolated); + Entity_Laser* fire_beam(const Vector& beamDirection, float damageScale, uint32_t fireFlags); void fire_c_section_fetuses(); - void init_laser(Entity_Laser& laser); void fire_hitscan(); void fire(float speed, bool isStatusIgnored); }; @@ -63,6 +70,8 @@ struct Weapon_TechX : Weapon void Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) override; float GetMaxCharge() override; int GetMarkedTargetVariant() override; + + void fire_rings(const Vector& aim, float shotSpeed); }; Weapon* weapon_laser_make(WeaponType type); diff --git a/src/weapon_lua.cpp b/src/weapon_lua.cpp new file mode 100644 index 0000000..fb8c830 --- /dev/null +++ b/src/weapon_lua.cpp @@ -0,0 +1,75 @@ +#include "entity_knife.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "lua_api.h" +#include "weapon.h" + +constexpr float LUA_ROTATE_SPEED = 8; +constexpr float LUA_TECH_X_DAMAGE = 1; + +// Adds Lua's EntityLaser functions that fire and turn beams to the class begun last. +void weapon_lua_laser_register(lua_State* state) +{ + lua_static(state, "ShootAngle", [](int variant, Vector position, float angle, int timeout, Vector offset, Entity* source) { + return Entity_Laser::ShootAngle({.position = position, + .posOffset = offset, + .source = source, + .angleDegrees = angle, + .timeout = timeout, + .variant = variant}); + }); + lua_static(state, "CalculateEndPoint", [](Vector start, Vector direction, Vector offset, Entity* parent, float margin) { + return Entity_Laser::CalculateEndPoint(start, direction, offset, parent, margin); + }); + lua_method(state, "SetActiveRotation", [](Entity_Laser& laser, int delay, float angle, float speed, bool isTimeout) { + laser.SetActiveRotation(delay, angle, speed, isTimeout); + }); + lua_method(state, "RotateToAngle", [](Entity_Laser& laser, float angle, LuaDefault speed) { + laser.RotateToAngle(angle, speed.value); + }); +} + +// Adds Lua's EntityKnife functions that bring a knife back to rest to the class begun last. +void weapon_lua_knife_register(lua_State* state) +{ + lua_method(state, "Reset", [](Entity_Knife& knife) { knife.Reset(); }); +} + +// Adds Lua's EntityPlayer functions that fire Technology's, Tech X's and Brimstone's lasers and Mom's Knife to the +// class begun last. +void weapon_lua_player_register(lua_State* state) +{ + lua_method(state, "FireTechLaser", + [](Entity_Player& player, Vector position, int offsetId, Vector direction, bool isLeftEye, bool isOneHit, + Entity* source, LuaDefault damageScale) { + return player.FireTechLaser({.direction = direction, + .position = position, + .source = source, + .damageScale = damageScale.value, + .offsetId = offsetId, + .isLeftEye = isLeftEye, + .isOneHit = isOneHit}); + }); + lua_method(state, "FireTechXLaser", + [](Entity_Player& player, Vector position, Vector velocity, float radius, Entity* source, + LuaDefault damageMultiplier) { + return player.FireTechXLaser({.position = position, + .velocity = velocity, + .source = source, + .damageMultiplier = damageMultiplier.value, + .radius = radius}); + }); + lua_method(state, "FireBrimstone", + [](Entity_Player& player, Vector direction, Entity* source, LuaDefault damageMultiplier) { + return player.FireBrimstone(direction, source, damageMultiplier.value); + }); + lua_method(state, "FireKnife", + [](Entity_Player& player, Entity* parent, LuaDefault rotationOffset, + LuaDefault isCantOverwrite, LuaDefault subType, LuaDefault variant) { + return player.FireKnife({.parent = parent, + .rotationOffset = rotationOffset.value, + .subType = subType.value, + .variant = variant.value, + .isCantOverwrite = isCantOverwrite.value}); + }); +}