diff --git a/generated-src/classes.h b/generated-src/classes.h index 8aac6c0..e3e9bbc 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -133,6 +133,7 @@ struct AnimationNullLayer; struct AnimationState; struct AnmCache; struct AnmFileData; +struct Attraction; struct Backdrop; struct BackdropConfig; struct BackwardsStageDesc; @@ -366,6 +367,7 @@ struct ItemOverlay; struct ItemPool; struct ItemPool_Item; struct ItemUse; +struct ItemsHit; struct KAGE_Filesys_File; struct KAGE_Filesys_FileManager; struct KAGE_Filesys_FileStream; @@ -482,6 +484,7 @@ struct OnlineUserStats; struct OptionsConfig; struct PMD; struct ParticleSpawn; +struct PassiveShot; struct PathFinder; struct PathNode; struct PauseScreen; @@ -507,6 +510,7 @@ struct PlayerProceduralItems; struct PngWriter; struct PocketItem; struct PocketItemConfig; +struct PocketUse; struct Point; struct PoolDesc; struct PoolItem; @@ -618,6 +622,7 @@ struct StringTableCategory; struct SubtitleCue; struct TargetSearch; struct TearParams; +struct TearSplash; struct TechLaserShot; struct TechXShot; struct TemporaryEffect; @@ -4001,122 +4006,6 @@ struct UserProfile { }; -struct Weapon_Deathmatch { - virtual ~Weapon_Deathmatch(); // 009f3260 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); // 00a031b0 slot 3 - virtual void Reset(); // 009f3480 slot 4 Weapon::Reset - virtual void ClearReferences(); // 009f3320 slot 5 Weapon::ClearReferences - virtual float GetMaxCharge(); // 00a036b0 slot 6 - virtual long double GetChargeBarAmount(); // 009f4150 slot 7 Weapon::GetChargeBarAmount - virtual void vfunc_8(); // 009f3130 slot 8 Weapon::GetMaxCharge - virtual uint32_t GetFocusEntity(); // 009f3140 slot 9 Weapon::GetFocusEntity - virtual void vfunc_10(); // 009f3140 slot 10 Weapon::GetFocusEntity - virtual void guard_check_icall(); // 0040c200 slot 11 ::guard_check_icall - virtual void vfunc_12(); // 009f3140 slot 12 Weapon::GetFocusEntity - virtual uint8_t CanShutDoors(); // 005ccc00 slot 13 Entity::CanShutDoors - virtual void vfunc_14(); // 005ccc00 slot 14 Entity::CanShutDoors - virtual void vfunc_15(); // 005ccc00 slot 15 Entity::CanShutDoors - virtual void vfunc_16(); // 005ccc00 slot 16 Entity::CanShutDoors - - uint8_t _pad_0x4[0x40]; -}; -LAYOUT32(sizeof(Weapon_Deathmatch) == 0x44); - -struct Weapon_MonstrosLung { - virtual ~Weapon_MonstrosLung(); // 009f3260 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(); // 00a07d50 slot 3 - virtual void Reset(); // 009f3480 slot 4 Weapon::Reset - virtual void ClearReferences(); // 009f3320 slot 5 Weapon::ClearReferences - virtual float GetMaxCharge(); // 00a08c80 slot 6 - virtual long double GetChargeBarAmount(); // 009f4150 slot 7 Weapon::GetChargeBarAmount - virtual void vfunc_8(); // 009f3130 slot 8 Weapon::GetMaxCharge - virtual uint32_t GetFocusEntity(); // 009f3140 slot 9 Weapon::GetFocusEntity - virtual uint32_t GetMainEntity(); // 009f3140 slot 10 Weapon::GetFocusEntity - virtual void guard_check_icall(); // 0040c200 slot 11 ::guard_check_icall - virtual uint32_t GetMarkedTargetVariant(); // 00a08cd0 slot 12 - virtual uint8_t CanTakeDamageFromTearEffects(); // 00709c30 slot 13 GridEntity::CanTakeDamageFromTearEffects - virtual uint8_t CanShutDoors(); // 005ccc00 slot 14 Entity::CanShutDoors - virtual uint8_t CanTriggerKidneyStone(); // 005ccc00 slot 15 Entity::CanShutDoors - virtual uint8_t CanOverrideForgottenThrow(); // 005ccc00 slot 16 Entity::CanShutDoors - static void FireBurst(uint32_t param_1, int param_2); // 00a08700 - - uint8_t _pad_0x4[0x40]; -}; -LAYOUT32(sizeof(Weapon_MonstrosLung) == 0x44); - -struct Weapon_SpiritSword { - virtual ~Weapon_SpiritSword(); // 009f9930 slot 0 Weapon_Laser::Free - 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); // 00a099e0 slot 3 - virtual void Reset(); // 00a0a6f0 slot 4 - virtual void ClearReferences(); // 00a063b0 slot 5 Weapon_Laser::ClearReferences - virtual long double GetMaxCharge(); // 00a0a700 slot 6 - virtual long double GetChargeBarAmount(); // 009f4150 slot 7 Weapon::GetChargeBarAmount - virtual void vfunc_8(); // 009f3130 slot 8 Weapon::GetMaxCharge - virtual uint32_t GetFocusEntity(); // 009f3140 slot 9 Weapon::GetFocusEntity - virtual Entity * GetMainEntity(); // 009f3150 slot 10 Weapon::GetMainEntity - virtual void guard_check_icall(); // 0040c200 slot 11 ::guard_check_icall - virtual void vfunc_12(); // 009f3140 slot 12 Weapon::GetFocusEntity - virtual uint8_t CanShutDoors(); // 005ccc00 slot 13 Entity::CanShutDoors - virtual void vfunc_14(); // 005ccc00 slot 14 Entity::CanShutDoors - virtual void vfunc_15(); // 005ccc00 slot 15 Entity::CanShutDoors - virtual void vfunc_16(); // 005ccc00 slot 16 Entity::CanShutDoors - - uint8_t _pad_0x4[0x4c]; -}; -LAYOUT32(sizeof(Weapon_SpiritSword) == 0x50); - -struct Weapon_UmbilicalWhip { - virtual ~Weapon_UmbilicalWhip(); // 009f9880 slot 0 Weapon_Bombs::Free - 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); // 00a0e270 slot 3 - virtual void guard_check_icall(); // 0040c200 slot 4 ::guard_check_icall - virtual void ClearReferences(); // 00a063b0 slot 5 Weapon_Laser::ClearReferences - virtual long double GetMaxCharge(); // 009f3130 slot 6 Weapon::GetMaxCharge - virtual void vfunc_7(); // 009f3130 slot 7 Weapon::GetMaxCharge - virtual void vfunc_8(); // 009f3130 slot 8 Weapon::GetMaxCharge - virtual uint32_t GetFocusEntity(); // 009f3140 slot 9 Weapon::GetFocusEntity - virtual Entity * GetMainEntity(); // 009f3150 slot 10 Weapon::GetMainEntity - virtual void vfunc_11(); // 0040c200 slot 11 ::guard_check_icall - virtual void vfunc_12(); // 009f3140 slot 12 Weapon::GetFocusEntity - virtual uint8_t CanTakeDamageFromTearEffects(); // 00709c30 slot 13 GridEntity::CanTakeDamageFromTearEffects - 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 - - uint8_t _pad_0x4[0x44]; -}; -LAYOUT32(sizeof(Weapon_UmbilicalWhip) == 0x48); - -struct Weapon_UrnOfSouls { - virtual ~Weapon_UrnOfSouls(); // 009f97e0 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); // 00a0e630 slot 3 - virtual void Reset(); // 00a0f410 slot 4 - virtual void ClearReferences(); // 00a0f420 slot 5 - virtual long double GetMaxCharge(); // 009f3130 slot 6 Weapon::GetMaxCharge - virtual void vfunc_7(); // 009f3130 slot 7 Weapon::GetMaxCharge - virtual void vfunc_8(); // 009f3130 slot 8 Weapon::GetMaxCharge - virtual uint32_t GetFocusEntity(); // 009f3140 slot 9 Weapon::GetFocusEntity - virtual Entity * GetMainEntity(); // 009f3170 slot 10 - virtual void guard_check_icall(); // 0040c200 slot 11 ::guard_check_icall - virtual void vfunc_12(); // 009f3140 slot 12 Weapon::GetFocusEntity - virtual uint8_t CanTakeDamageFromTearEffects(); // 00709c30 slot 13 GridEntity::CanTakeDamageFromTearEffects - 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 - - uint8_t _pad_0x4[0x50]; -}; -LAYOUT32(sizeof(Weapon_UrnOfSouls) == 0x54); - struct Window { int get_framebuffer_height(); // 00a193c0 }; @@ -5873,7 +5762,6 @@ void FUN_00436200(uint32_t param_1); // 00436200 void FUN_00436210(uint32_t param_1); // 00436210 void FUN_00436260(); // 00436260 void FUN_00436fb0(); // 00436fb0 -void FUN_0043d7f0(int param_1); // 0043d7f0 void FUN_0043e990(RNG *param_1); // 0043e990 void FUN_0043e9f0(); // 0043e9f0 void FUN_0043ed20(uint32_t *param_1, int *param_2); // 0043ed20 @@ -5986,7 +5874,6 @@ void Catch_All_004d7683(); // 004d7683 void FUN_004d76c0(); // 004d76c0 bool FUN_004d7760(); // 004d7760 Entity * spawn_small_maggot(Vector *position, float height, Vector *velocity, float heightVelocity); // 004d8b50 -void FUN_004e07a0(Vector *param_1); // 004e07a0 void FUN_004e46b0(); // 004e46b0 void FUN_004e46c0(); // 004e46c0 bool FUN_004e47b0(); // 004e47b0 @@ -6004,11 +5891,9 @@ uint32_t * FUN_00505ce0(); // 00505ce0 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 -void FUN_005579b0(Vector *param_1); // 005579b0 void FUN_00557b50(uint32_t param_1); // 00557b50 void FUN_00557b70(uint8_t *param_1); // 00557b70 bool FUN_00557bb0(int *param_1); // 00557bb0 -void collect_npcs_with_same_parent(Entity_NPC *npc); // 00557ce0 void FUN_00565dd0(uint32_t param_1); // 00565dd0 void FUN_00565de0(uint32_t param_1); // 00565de0 void FUN_00568980(char param_1); // 00568980 @@ -6039,13 +5924,11 @@ void FUN_005830e0(); // 005830e0 void FUN_00583110(char param_1); // 00583110 void FUN_00583170(); // 00583170 void FUN_00586b50(float *param_1, float param_2); // 00586b50 -void FUN_00589de0(Vector *param_1); // 00589de0 uint32_t FUN_0058ab60(); // 0058ab60 uint8_t FUN_0058e210(); // 0058e210 void FUN_0058e240(uint32_t param_1); // 0058e240 void FUN_00598260(Vector *param_1); // 00598260 uint32_t * FUN_00598290(uint32_t *param_1, uint32_t *param_2); // 00598290 -void FUN_0059a200(); // 0059a200 void FUN_005a6fb0(); // 005a6fb0 uint8_t FUN_005a7570(); // 005a7570 void FUN_005aae10(); // 005aae10 @@ -6172,7 +6055,6 @@ void FUN_005cd8c0(uint8_t param_1); // 005cd8c0 void FUN_005cda90(); // 005cda90 void FUN_005d2300(); // 005d2300 void FUN_005d23a0(uint8_t param_1); // 005d23a0 -void FUN_005d4210(); // 005d4210 void FUN_00607540(); // 00607540 void room_perimeter_to_position(float *param_1, float *param_2); // 0060ac70 void FUN_0060c350(); // 0060c350 @@ -6313,8 +6195,6 @@ void FUN_00665bf0(uint8_t param_1); // 00665bf0 void FUN_00665c00(); // 00665c00 uint8_t FUN_00665cc0(); // 00665cc0 void FUN_00676bd0(); // 00676bd0 -int FUN_0067adc0(); // 0067adc0 -void FUN_0067ae30(int *param_1); // 0067ae30 void FUN_0067af30(); // 0067af30 uint32_t FUN_0067d9b0(); // 0067d9b0 void FUN_0067dac0(int *param_1); // 0067dac0 @@ -6331,7 +6211,6 @@ void FUN_00680060(size_t param_1); // 00680060 void FUN_00682260(); // 00682260 void shader_stack_push(int shaderIndex); // 00682280 void FUN_00682350(); // 00682350 -float normalize_angle_degrees(float angle); // 00682740 uint32_t checksum_stream(void *stream, int offset, int trailingSize); // 00683580 void FUN_00683680(); // 00683680 void pop_render_target(); // 006836c0 @@ -6726,7 +6605,6 @@ int FUN_00759260(); // 00759260 void FUN_0075d9f0(uint32_t param_1); // 0075d9f0 uint32_t FUN_0075ef20(ANM2 *param_1, int param_2); // 0075ef20 void FUN_00770640(float *param_1); // 00770640 -uint8_t is_trinket_unpickable_id(int trinketId); // 007716c0 void FUN_007792f0(uint32_t param_1, uint32_t param_2); // 007792f0 uint32_t FUN_007826c0(); // 007826c0 void FUN_007829a0(); // 007829a0 @@ -6739,13 +6617,10 @@ uint32_t FUN_007ab0e0(); // 007ab0e0 void FUN_007ad610(); // 007ad610 uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2); // 007ad720 void FUN_007b8c00(int param_1); // 007b8c00 -void FUN_007b9a60(); // 007b9a60 -void FUN_007b9aa0(); // 007b9aa0 void FUN_007c2e80(); // 007c2e80 uint8_t FUN_007c7b10(uint32_t param_1, int param_2); // 007c7b10 char FUN_007c9080(); // 007c9080 void FUN_007cb4f0(); // 007cb4f0 -uint8_t teleport_to_random_room_of_types(Entity_Player *player, void *roomTypes, uint8_t isPreferUnvisited); // 007cdf30 void FUN_007cf940(); // 007cf940 long double FUN_007cf9a0(float *param_1, KColor *param_2, uint32_t param_3); // 007cf9a0 uint8_t * FUN_007cfa90(); // 007cfa90 @@ -6757,10 +6632,6 @@ uint32_t FUN_007da770(); // 007da770 uint32_t FUN_007dac30(); // 007dac30 void FUN_007dad80(); // 007dad80 int FUN_007dafb0(); // 007dafb0 -void FUN_007db0a0(); // 007db0a0 -uint32_t FUN_007db2d0(); // 007db2d0 -int FUN_007db360(); // 007db360 -uint32_t FUN_007dbe70(uint32_t *param_1); // 007dbe70 void FUN_007dc610(); // 007dc610 void FUN_007dc620(uint32_t *param_1); // 007dc620 void FUN_007dc650(); // 007dc650 @@ -9117,7 +8988,6 @@ void cutscene_render_skip_vote_count(void *cutscene, void *state); // 0095eb60 uint32_t * FUN_00960880(void *param_1, uint32_t *param_2); // 00960880 void FUN_00960bc0(); // 00960bc0 void FUN_0096d120(int *param_1); // 0096d120 -uint32_t FUN_0097e7c0(); // 0097e7c0 void pressure_plate_kill_enemies_timer_callback(int *param_1); // 00983f30 void FUN_0098b0a0(); // 0098b0a0 void FUN_0098b130(); // 0098b130 @@ -9163,13 +9033,6 @@ void FUN_009ba9a0(); // 009ba9a0 void FUN_009baa10(char param_1); // 009baa10 int FUN_009bac00(int param_1); // 009bac00 void entity_vector_set_flag_410(void *self, uint8_t value); // 009bea10 -void FUN_009bfc00(); // 009bfc00 -void FUN_009bfc20(); // 009bfc20 -void FUN_009bfc40(); // 009bfc40 -void FUN_009bfc80(); // 009bfc80 -void FUN_009bfcd0(); // 009bfcd0 -void FUN_009bfd00(); // 009bfd00 -void FUN_009bfd20(); // 009bfd20 void FUN_009c00c0(uint32_t param_1); // 009c00c0 long double FUN_009c0120(); // 009c0120 void FUN_009c22b0(uint32_t *param_1); // 009c22b0 @@ -9315,10 +9178,9 @@ void FUN_009f3c40(); // 009f3c40 void FUN_009f4130(); // 009f4130 Entity_Player * FUN_009f4fc0(); // 009f4fc0 void FUN_009f5810(uint8_t param_1); // 009f5810 -uint32_t * FUN_009f9080(); // 009f9080 -uint32_t * FUN_009f90f0(); // 009f90f0 -uint32_t * FUN_009f9170(); // 009f9170 -uint32_t * FUN_009f92d0(); // 009f92d0 +uint32_t FUN_009f5830(); // 009f5830 +uint32_t FUN_009f5850(); // 009f5850 +uint32_t FUN_009f5870(); // 009f5870 uint32_t * FUN_009f93d0(); // 009f93d0 uint32_t * FUN_00a06940(void *param_1, uint32_t *param_2); // 00a06940 void * operator_new(uint32_t size); // 00a0f4c0 @@ -21053,12 +20915,7 @@ void ENTITY_DEATH(Entity_NPC *npc); // 00459d20 void ENTITY_HEADLESS_HORSEMAN(Entity_NPC *npc); // 0045cd60 void ENTITY_DARK_ONE(Entity_NPC *npc); // 0045d7d0 void ENTITY_PIN(Entity_NPC *npc); // 00476860 -void ENTITY_BROWNIE(Entity_NPC *npc); // 0048c3b0 -void ENTITY_CORN_MINE(Entity_NPC *npc); // 0048ee30 void ENTITY_FORSAKEN(Entity_NPC *npc); // 0048f110 -void ENTITY_RAG_MAN(Entity_NPC *npc); // 00493200 -void ENTITY_RAG_MEGA(Entity_NPC *npc); // 00495610 -void ENTITY_SISTERS_VIS(Entity_NPC *npc); // 00496fb0 void ENTITY_BUMBINO(Entity_NPC *npc); // 00499de0 void ENTITY_CHIMERA_head_update(Entity_NPC *npc); // 0049cd90 void ENTITY_CHIMERA_body(Entity_NPC *npc); // 0049d130 @@ -21071,16 +20928,10 @@ void ENTITY_DOGMA(Entity_NPC *npc); // 004aafa0 void ENTITY_DOGMA_angel(Entity_NPC *npc); // 004ae4d0 Vector * ENTITY_DOGMA_angel_baby(Entity_NPC *npc); // 004b0200 void ENTITY_DOGMA_tv(Entity_NPC *npc); // 004b0a30 -void ENTITY_GIDEON(Entity_NPC *npc); // 004b1ee0 void ENTITY_HERETIC(Entity_NPC *npc); // 004b43c0 void ENTITY_HORNFEL_DOOR(Entity_NPC *npc); // 004bb9b0 void ENTITY_HORNY_BOYS(Entity_NPC *npc); // 004bd2a0 -void ENTITY_HUSH_BOIL(Entity_NPC *npc); // 004be6f0 -void ENTITY_HUSH_FLY(Entity_NPC *npc); // 004bf310 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_MIN_MIN(Entity_NPC *npc); // 004cf690 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 @@ -21098,7 +20949,6 @@ void ENTITY_WHIPPER(Entity_NPC *npc); // 004e5170 void ENTITY_GRUDGE(Entity_NPC *npc); // 004e6570 uint32_t ENTITY_BISHOP(Entity_NPC *npc); // 004e7ea0 uint8_t * ENTITY_BABY_BEGOTTEN(Entity_NPC *npc); // 004e8380 -void ENTITY_VIS_FATTY(Entity_NPC *npc); // 004ea3d0 void ENTITY_EXORCIST(Entity_NPC *npc); // 004ec240 void ENTITY_REVENANT(Entity_NPC *npc); // 004ecc10 void ENTITY_CULTIST(Entity_NPC *npc); // 004ed840 @@ -21111,7 +20961,6 @@ void ENTITY_MOCKULUS(Entity_NPC *npc); // 004f76f0 void ENTITY_MORNINGSTAR(Entity_NPC *npc); // 004f7e60 void ENTITY_FACELESS(Entity_NPC *npc); // 004faad0 void ENTITY_DANNY(Entity_NPC *npc); // 004fbd10 -void ENTITY_MOLE(Entity_NPC *npc); // 004fdf80 void ENTITY_GYRO(Entity_NPC *npc); // 004ff620 void ENTITY_BOUNCER(Entity_NPC *npc); // 00501f30 void ENTITY_FLESH_MAIDEN(Entity_NPC *npc); // 00502980 @@ -21121,28 +20970,20 @@ void ENTITY_BIG_BONY(Entity_NPC *npc); // 005041d0 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 -void ENTITY_SWARMER(Entity_NPC *npc); // 00518e20 void ENTITY_URIEL(Entity_NPC *npc); // 0051e0f0 void ENTITY_HEART(Entity_NPC *npc); // 0051f2f0 void ENTITY_DOPLE(Entity_NPC *npc); // 00525650 -void ENTITY_HOMUNCULUS(Entity_NPC *npc); // 00539b90 -void ENTITY_OOB(Entity_NPC *npc); // 0053ab40 void ENTITY_BLACK_MAW(Entity_NPC *npc); // 0053b2f0 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 -ColorMod * ENTITY_WRINKLY_BABY(Entity_NPC *npc); // 0054fa80 void ENTITY_SWARM_SPIDER(Entity_NPC *npc); // 005505c0 void ENTITY_COHORT(Entity_NPC *npc); // 005513a0 void ENTITY_GENERIC_PROP(Entity_NPC *npc); // 00551d30 void ENTITY_SHADY(Entity_NPC *npc); // 005522d0 void ENTITY_BLOOD_PUPPY(Entity_NPC *npc); // 00552d30 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 Entity_Projectile * ENTITY_BUBBLES(Entity_NPC *npc); // 0055ad20 @@ -21163,11 +21004,9 @@ void ENTITY_MOTHER_start_transition(Entity_NPC *npc); // 00568a90 void ENTITY_MOTHER(Entity_NPC *npc); // 00569170 void ENTITY_MOTHER_2(Entity_NPC *npc); // 0056cd60 void ENTITY_MOTHERS_SHADOW(Entity_NPC *npc); // 0056ffa0 -void ENTITY_POOP(Entity_NPC *npc); // 00571280 void ENTITY_CLUTCH(Entity_NPC *npc); // 00573030 void ENTITY_RAGLICH(Entity_NPC *npc); // 005769b0 void ENTITY_RAINMAKER(Entity_NPC *npc); // 00578a70 -void ENTITY_REAP_CREEP(Entity_NPC *npc); // 00579890 void ENTITY_ROTGUT_face(Entity_NPC *npc); // 0057bec0 void ENTITY_ROTGUT_maggot(Entity_NPC *npc); // 0057e4a0 void rotgut_fire_projectiles(Entity_NPC *npc); // 00581430 @@ -21187,9 +21026,6 @@ void ENTITY_BEAST(Entity_NPC *npc); // 00592460 void ENTITY_BEAST_stalactite(Entity_NPC *npc); // 00596120 void ENTITY_BEAST_rock_projectile(Entity_NPC *npc); // 00596c60 void ENTITY_BEAST_soul(Entity_NPC *npc); // 005971e0 -void ENTITY_TUFF_TWINS_head_anim(Entity_NPC *npc); // 00599b80 -void ENTITY_TUFF_TWINS_body_anim(Entity_NPC *npc); // 00599d70 -void ENTITY_TUFF_TWINS(Entity_NPC *npc); // 0059a2d0 void ENTITY_TURDLET_segments(Entity_NPC *npc); // 0059c5d0 void ENTITY_TURDLET(Entity_NPC *npc); // 0059c830 void ENTITY_ULTRA_GREED(Entity_NPC *npc); // 0059edb0 diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index 1ab861e..b196d3a 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -177,56 +177,6 @@ LAB_0049f8ee: return; } -// 004a1000 -void NpcHelper::chimera_render_child(Entity_NPC *npc, Vector *offset) -{ - int iVar1; - int iVar2; - int iVar3; - int iVar4; - int iVar5; - int iVar6; - int *piVar7; - void *layerFrame; - LayerState *pLVar8; - uint32_t frameX; - - if (((((npc->_type == 0x38e) && (npc->_variant == 1)) && (npc->_state == 0x10)) && - ((piVar7 = GHIDRA_CAST(npc->_child), piVar7 != GHIDRA_CAST(0x0) && (piVar7[0x2d9] == 0x10)))) && - (*GHIDRA_CAST((GHIDRA_CAST(piVar7) + 0x171)) == '\0')) { - layerFrame = AnimationState::GetLayerFrame(&(npc->_sprite)._animState,2); - if ((layerFrame != (void *)0x0) && (*GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x2c)) != '\0')) { - iVar1 = piVar7[0xcf]; - iVar2 = piVar7[0x37]; - iVar3 = piVar7[0x38]; - iVar4 = piVar7[0x39]; - iVar5 = piVar7[0x3a]; - piVar7[0xcf] = GHIDRA_INT((npc->_pos).x); - piVar7[0xd0] = GHIDRA_INT((npc->_pos).y); - iVar6 = *GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x14)); - pLVar8 = ANM2::GetLayer(&npc->_sprite,GHIDRA_CAST(0x2)); - frameX = *GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x10)); - if (pLVar8->_flipX != 0) { - frameX = frameX ^ 0x80000000; - } - piVar7[0x37] = frameX; - piVar7[0x38] = iVar6; - piVar7[0x39] = *GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x18)); - piVar7[0x3a] = *GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x1c)); - *GHIDRA_CAST((GHIDRA_CAST(piVar7) + 0x171)) = 1; - (**(code **)(*piVar7 + 0x14))(offset); - piVar7[0x39] = iVar6; - piVar7[0x3a] = iVar4; - piVar7[0x37] = iVar5; - piVar7[0x38] = iVar2; - piVar7[0xcf] = iVar3; - *GHIDRA_CAST((GHIDRA_CAST(piVar7) + 0x171)) = 0; - piVar7[0xd0] = iVar1; - } - } - return; -} - // 004a2940 Vector * NpcHelper::colostomia_pick_target(Entity_NPC *npc, Vector *outTarget, uint8_t *isPlayerPos) { @@ -1805,904 +1755,6 @@ switchD_004a998d_caseD_4a: goto switchD_004a998d_caseD_15; } -// 004b0fe0 -void NpcHelper::gideon_spawn_stairs(Entity_NPC *npc) -{ - code *pcVar1; - Room *pRVar2; - RoomConfig_Room *crawlspaceConfig; - uint32_t gridCollision; - GridEntity *stairs; - uint32_t uVar3; - RoomDescriptor *crawlspaceDesc; - RNG rng; - Room *local_18; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - Game *game; - uint32_t *oldGridEntity; - - game = g_game; - local_8 = 0xffffffff; - puStack_c = &LAB_00af3203; - local_10 = ExceptionList; - ExceptionList = &local_10; - if (-1 < npc->_projectileDelay) { - if (*GHIDRA_CAST((*GHIDRA_CAST(ThreadLocalStoragePointer) + 0xc)) < g_invalidRoomDescriptorGuard) { - _Init_thread_header(&g_invalidRoomDescriptorGuard, - __security_cookie ^ GHIDRA_INT(register0x00000010) - 4U); - if (g_invalidRoomDescriptorGuard == -1) { - local_8 = 0; - RoomDescriptor::constructor(&g_roomDescriptorDummy); - _atexit(FUN_00b15b30); - local_8 = 0xffffffff; - _Init_thread_footer(&g_invalidRoomDescriptorGuard); - } - } - crawlspaceDesc = &g_roomDescriptorDummy; - if (GHIDRA_UINT(game->_currentDimensionIdx) < 3) { - crawlspaceDesc = game->_roomList + 0x205; - } - if (crawlspaceDesc->Data == (void *)0x0) { - rng._seed = (game->_devilAngelRoomRNG)._seed; - rng._shift3 = 0x1b; - rng._shift1 = 1; - rng._shift2 = 0x1b; - Seeds::Init3(GHIDRA_CAST(crawlspaceDesc),&rng); - local_18 = GHIDRA_CAST(&g_game->_roomConfig); - local_14 = 0; - if (rng._seed == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - uVar3 = GHIDRA_UINT(rng._seed) >> ((uint8_t)rng._shift1 & 0x1f) ^ rng._seed; - uVar3 = uVar3 << ((uint8_t)rng._shift2 & 0x1f) ^ uVar3; - crawlspaceConfig = - RoomConfig::GetRandomRoom - (GHIDRA_CAST(local_18),uVar3 >> ((uint8_t)rng._shift3 & 0x1f) ^ uVar3,0,0,0x10, - 0xd,0,-1,0,0,&local_14,1,-1); - crawlspaceDesc->Data = crawlspaceConfig; - } - local_18 = g_game->_room; - local_14 = Random(); - uVar3 = npc->_projectileDelay; - if ((GHIDRA_INT(uVar3) < 0) || (0x1bf < GHIDRA_INT(uVar3))) { - KAGE_LogMessage(0x10,GHIDRA_CAST("SpawnGridEntity: Grid index invalid\n")); - } - pRVar2 = local_18; - if (uVar3 < 0x1c0) { - gridCollision = Room::GetGridCollision(local_18,uVar3); - if (GHIDRA_INT(gridCollision) < 1) { - stairs = operator_new(0x154); - local_8 = 0x12; - local_18 = GHIDRA_CAST(stairs); - if (stairs == GHIDRA_CAST(0x0)) { - stairs = GHIDRA_CAST(0x0); - } - else { - GridEntity::GridEntity(stairs); - *GHIDRA_CAST(stairs) = IsaacRepentancePlus::GridEntity_Stairs::vftable; - } - local_8 = 0xffffffff; - if (stairs != GHIDRA_CAST(0x0)) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((stairs)) + 0x4)))) = 0x12; - stairs->_gridIndex = uVar3; - oldGridEntity = pRVar2->_gridEntities[uVar3]; - if (oldGridEntity != GHIDRA_CAST(0x0)) { - (**(code **)*oldGridEntity)(1); - } - pRVar2->_gridEntities[uVar3] = stairs; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((stairs)) + 0x8)))) = 1; - stairs->_varData = 0; - GridEntity::Init(stairs,local_14); - } - } - } - } - ExceptionList = local_10; - return; -} - -// 004b1210 -void NpcHelper::gideon_choose_attack(Entity_NPC *npc) -{ - Entity_NPC *pEVar1; - RNG rng; - uint8_t *puVar2; - Entity_NPC *pEVar3; - uint8_t bVar4; - uint32_t *puVar5; - uint32_t uVar6; - int iVar7; - uint8_t *curAnimName; - uint32_t outcomeCount; - int iVar8; - uint8_t *wantedAnimName; - char *wantedAnimNameStr; - uint16_t newCooldown; - void *ptr; - bool isLess; - uint64_t uStack_40; - uint32_t uStack_38; - void *picker; - uint32_t *outcomesEnd; - uint32_t *outcomesCapacity; - float pitch; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - uint8_t *animData; - uint32_t *attack4Cooldown; - Manager *manager; - Entity_NPC *parent; - int *weight; - - puStack_20 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - local_14 = 0xffffffff; - puStack_18 = &LAB_00af322d; - local_1c = ExceptionList; - local_24 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 0x10U; - ExceptionList = &local_1c; - pEVar3 = GHIDRA_CAST(npc->_parent); - pEVar1 = npc; - while (parent = pEVar3, parent != GHIDRA_CAST(0x0)) { - pEVar1 = parent; - pEVar3 = GHIDRA_CAST(parent->_parent); - } - iVar7 = pEVar1->_child; - while (puVar2 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)), iVar7 != 0) { - if ((pEVar1 != npc) && ((pEVar1->_state == 0xb || (pEVar1->_state == 7)))) { - uVar6 = Random(); - attack4Cooldown = GHIDRA_CAST((GHIDRA_INT(&npc->_i2) + 2)); - newCooldown = (short)(uVar6 % 0x96) + 0x5a; - uStack_38 = GHIDRA_UINT(newCooldown); - puVar5 = &uStack_38; - if (newCooldown <= *GHIDRA_CAST(attack4Cooldown)) { - puVar5 = attack4Cooldown; - } - *GHIDRA_CAST(attack4Cooldown) = (uint16_t)*puVar5; - puVar2 = puStack_20; - break; - } - pEVar1 = GHIDRA_CAST(pEVar1->_child); - iVar7 = pEVar1->_child; - } - puStack_20 = puVar2; - picker = (void *)0x0; - outcomesEnd = GHIDRA_CAST(0x0); - outcomesCapacity = GHIDRA_CAST(0x0); - local_14 = 0; - uStack_40 = (uint64_t)GHIDRA_UINT(uStack_40); - uStack_38 = 1; - msvc::vector<8byte>::_Emplace_reallocate(0,GHIDRA_INT(&uStack_40) + 4); - if ((short)npc->_i2 == 0) { - uVar6 = 0; - outcomeCount = GHIDRA_INT(outcomesEnd) - GHIDRA_INT(picker) >> 3; - if (outcomeCount != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(picker) + uVar6 * 8)) == 1) { - weight = GHIDRA_CAST((GHIDRA_INT(picker) + uVar6 * 8 + 4)); - *weight = *weight + 1; - if (*weight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(picker) + uVar6 * 8 + 4)) = 0; - } - goto LAB_004b137f; - } - uVar6 = uVar6 + 1; - } while (uVar6 < outcomeCount); - } - uStack_40 = CONCAT44(1,GHIDRA_UINT(uStack_40)); - uStack_38 = 1; - if (outcomesEnd == outcomesCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesEnd,GHIDRA_INT(&uStack_40) + 4); - } - else { - *outcomesEnd = 1; - outcomesEnd[1] = 1; - outcomesEnd = outcomesEnd + 2; - } - } -LAB_004b137f: - if ((3 < npc->_stateFrame) && (*GHIDRA_CAST((GHIDRA_INT(&npc->_i1) + 1)) == '\0')) { - uVar6 = 0; - outcomeCount = GHIDRA_INT(outcomesEnd) - GHIDRA_INT(picker) >> 3; - if (outcomeCount != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(picker) + uVar6 * 8)) == 2) { - weight = GHIDRA_CAST((GHIDRA_INT(picker) + uVar6 * 8 + 4)); - *weight = *weight + 6; - if (*weight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(picker) + uVar6 * 8 + 4)) = 0; - } - goto LAB_004b13f7; - } - uVar6 = uVar6 + 1; - } while (uVar6 < outcomeCount); - } - uStack_40 = CONCAT44(2,GHIDRA_UINT(uStack_40)); - uStack_38 = 6; - if (outcomesEnd == outcomesCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesEnd,GHIDRA_INT(&uStack_40) + 4); - } - else { - *outcomesEnd = 2; - outcomesEnd[1] = 6; - outcomesEnd = outcomesEnd + 2; - } - } -LAB_004b13f7: - if (*GHIDRA_CAST((GHIDRA_INT(&npc->_i2) + 2)) == 0) { - iVar8 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x12c4)) + *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x12c0)); - iVar7 = 0; - if (0 < iVar8) { - iVar7 = iVar8; - } - if (iVar7 < 5) { - uVar6 = 0; - outcomeCount = GHIDRA_INT(outcomesEnd) - GHIDRA_INT(picker) >> 3; - if (outcomeCount != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(picker) + uVar6 * 8)) == 3) { - weight = GHIDRA_CAST((GHIDRA_INT(picker) + uVar6 * 8 + 4)); - *weight = *weight + 1; - if (*weight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(picker) + uVar6 * 8 + 4)) = 0; - } - goto LAB_004b1488; - } - uVar6 = uVar6 + 1; - } while (uVar6 < outcomeCount); - } - uStack_40 = CONCAT44(3,GHIDRA_UINT(uStack_40)); - uStack_38 = 1; - if (outcomesEnd == outcomesCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesEnd,GHIDRA_INT(&uStack_40) + 4); - } - else { - *outcomesEnd = 3; - outcomesEnd[1] = 1; - outcomesEnd = outcomesEnd + 2; - } - } - } -LAB_004b1488: - uVar6 = Random(); - uStack_40 = 0x900000005; - uStack_38 = 7; - rng._shift1 = 5; - rng._seed = uVar6 | 1; - rng._shift2 = 9; - rng._shift3 = 7; - uVar6 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&picker),rng); - manager = g_manager; - switch(uVar6) { - case 0: - npc->_state = 8; - animData = (npc->_sprite)._animState._animData; - if (animData == GHIDRA_CAST(0x0)) { -LAB_004b152e: - bVar4 = ANM2::SetAnimation(&npc->_sprite,s_Attack1,1); - if (bVar4 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } - } - else { - curAnimName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - curAnimName = *GHIDRA_CAST(animData); - } - wantedAnimName = s_Attack1; - do { - bVar4 = *curAnimName; - isLess = bVar4 < *wantedAnimName; - if (bVar4 != *wantedAnimName) { -LAB_004b1510: - uVar6 = -GHIDRA_UINT(isLess) | 1; - goto LAB_004b1515; - } - if (bVar4 == 0) break; - bVar4 = curAnimName[1]; - isLess = bVar4 < wantedAnimName[1]; - if (bVar4 != wantedAnimName[1]) goto LAB_004b1510; - curAnimName = curAnimName + 2; - wantedAnimName = wantedAnimName + 2; - } while (bVar4 != 0); - uVar6 = 0; -LAB_004b1515: - if ((uVar6 != 0) || ((animData[0x34] != 0 && ((npc->_sprite)._animState._isPlaying == 0)))) - goto LAB_004b152e; - } - pitch = 0.9; - if (npc->_championColorIdx == 0x12) { - pitch = 1.4; - } - else if (npc->_championColorIdx == 0x13) { - pitch = 0.45; - } - uStack_38 = 0x136; - break; - case 1: - npc->_state = 9; - animData = (npc->_sprite)._animState._animData; - if (animData == GHIDRA_CAST(0x0)) { -LAB_004b162e: - bVar4 = ANM2::SetAnimation(&npc->_sprite,GHIDRA_CAST("Attack2Start"),1); - if (bVar4 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } - } - else { - curAnimName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - curAnimName = *GHIDRA_CAST(animData); - } - wantedAnimNameStr = "Attack2Start"; - do { - bVar4 = *curAnimName; - isLess = bVar4 < (uint8_t)*wantedAnimNameStr; - if (bVar4 != *wantedAnimNameStr) { -LAB_004b1610: - uVar6 = -GHIDRA_UINT(isLess) | 1; - goto LAB_004b1615; - } - if (bVar4 == 0) break; - bVar4 = curAnimName[1]; - isLess = bVar4 < (uint8_t)wantedAnimNameStr[1]; - if (bVar4 != wantedAnimNameStr[1]) goto LAB_004b1610; - curAnimName = curAnimName + 2; - wantedAnimNameStr = wantedAnimNameStr + 2; - } while (bVar4 != 0); - uVar6 = 0; -LAB_004b1615: - if ((uVar6 != 0) || ((animData[0x34] != 0 && ((npc->_sprite)._animState._isPlaying == 0)))) - goto LAB_004b162e; - } - pitch = 0.9; - *GHIDRA_CAST(&npc->_i2) = 0x1c2; - if (npc->_championColorIdx == 0x12) { - pitch = 1.4; - uStack_38 = 0x138; - } - else { - if (npc->_championColorIdx == 0x13) { - pitch = 0.45; - } - uStack_38 = 0x138; - } - break; - case 2: - pitch = 0.9; - npc->_state = 10; - manager = g_manager; - if (npc->_championColorIdx == 0x12) { - pitch = 1.4; - } - else if (npc->_championColorIdx == 0x13) { - pitch = 0.45; - } - uStack_38 = 0x133; - seed_fart_sound_override(GHIDRA_CAST(&uStack_38)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(uStack_38,1.0,2,0,pitch,0.0); - animData = (npc->_sprite)._animState._animData; - if (animData == GHIDRA_CAST(0x0)) { -LAB_004b177e: - bVar4 = ANM2::SetAnimation(&npc->_sprite,&DAT_00b1d2e4,1); - if (bVar4 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } - } - else { - curAnimName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - curAnimName = *GHIDRA_CAST(animData); - } - wantedAnimName = &DAT_00b1d2e4; - do { - bVar4 = *curAnimName; - isLess = bVar4 < *wantedAnimName; - if (bVar4 != *wantedAnimName) { -LAB_004b1760: - uVar6 = -GHIDRA_UINT(isLess) | 1; - goto LAB_004b1765; - } - if (bVar4 == 0) break; - bVar4 = curAnimName[1]; - isLess = bVar4 < wantedAnimName[1]; - if (bVar4 != wantedAnimName[1]) goto LAB_004b1760; - curAnimName = curAnimName + 2; - wantedAnimName = wantedAnimName + 2; - } while (bVar4 != 0); - uVar6 = 0; -LAB_004b1765: - if ((uVar6 != 0) || ((animData[0x34] != 0 && ((npc->_sprite)._animState._isPlaying == 0)))) - goto LAB_004b177e; - } - *GHIDRA_CAST((GHIDRA_INT(&npc->_i1) + 1)) = 1; - goto switchD_004b14c5_default; - case 3: - pitch = 1.0; - if (npc->_championColorIdx == 0x12) { - pitch = 1.5; - } - else if (npc->_championColorIdx == 0x13) { - pitch = 0.5; - } - uStack_38 = 0x74; - seed_fart_sound_override(GHIDRA_CAST(&uStack_38)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(uStack_38,1.0,2,0,pitch,0.0); - animData = (npc->_sprite)._animState._animData; - if (animData == GHIDRA_CAST(0x0)) { -LAB_004b1874: - bVar4 = ANM2::SetAnimation(&npc->_sprite,GHIDRA_CAST("Attack4Start"),1); - if (bVar4 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } - } - else { - curAnimName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - curAnimName = *GHIDRA_CAST(animData); - } - wantedAnimNameStr = "Attack4Start"; - do { - bVar4 = *curAnimName; - isLess = bVar4 < (uint8_t)*wantedAnimNameStr; - if (bVar4 != *wantedAnimNameStr) { -LAB_004b1856: - uVar6 = -GHIDRA_UINT(isLess) | 1; - goto LAB_004b185b; - } - if (bVar4 == 0) break; - bVar4 = curAnimName[1]; - isLess = bVar4 < (uint8_t)wantedAnimNameStr[1]; - if (bVar4 != wantedAnimNameStr[1]) goto LAB_004b1856; - curAnimName = curAnimName + 2; - wantedAnimNameStr = wantedAnimNameStr + 2; - } while (bVar4 != 0); - uVar6 = 0; -LAB_004b185b: - if ((uVar6 != 0) || ((animData[0x34] != 0 && ((npc->_sprite)._animState._isPlaying == 0)))) - goto LAB_004b1874; - } - npc->_state = 0xb; - *GHIDRA_CAST((GHIDRA_INT(&npc->_i2) + 2)) = 600; - default: - goto switchD_004b14c5_default; - } - manager = g_manager; - seed_fart_sound_override(GHIDRA_CAST(&uStack_38)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(uStack_38,1.0,2,0,pitch,0.0); -switchD_004b14c5_default: - if (picker != (void *)0x0) { - uVar6 = GHIDRA_INT(outcomesCapacity) - GHIDRA_INT(picker) & 0xfffffff8; - ptr = picker; - if (0xfff < uVar6) { - ptr = *(void **)(GHIDRA_CAST(picker) + -4); - uVar6 = uVar6 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(picker) + (-4 - GHIDRA_INT(ptr))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(ptr,uVar6); - } - ExceptionList = local_1c; - return; -} - -// 004b1910 -void NpcHelper::gideon_spawn_wave() -{ - code *pcVar1; - uint32_t spawnVariant; - uint32_t stageType; - void **gridEntityCursor; - int gridX; - uint32_t *nextEntry; - int iVar3; - uint32_t *puVar4; - short *roomSpawn; - uint32_t uVar5; - uint32_t in_stack_ffffff38; - int in_stack_ffffff3c; - Vector local_9c; - uint64_t local_90; - Vector local_84; - uint32_t pitCount; - uint32_t waveDifficulty; - uint32_t *entriesCapacityEnd; - void *gideon; - uint32_t *entriesBegin; - uint32_t *entriesEnd; - uint32_t *local_64; - uint32_t local_60; - int local_5c; - uint32_t local_58; - Room *room; - uint32_t *local_50; - Game *local_4c; - uint32_t spawnEntry; - uint32_t uStack_44; - uint32_t local_40 [8]; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - Game *game; - Manager *manager; - float maxHitPoints; - uint16_t spawnVariant; - - puStack_20 = GHIDRA_CAST((local_40 + 0xf)); - local_14 = 0xffffffff; - puStack_18 = &LAB_00af326d; - local_1c = ExceptionList; - local_40[7] = __security_cookie ^ GHIDRA_UINT((local_40 + 0xc)); - ExceptionList = &local_1c; - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x3bc)) == 0) { - spawnVariant = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x410)); - local_4c = g_game; - if (6 < spawnVariant) { - spawnVariant = 6; - } - room = g_game->_room; - uVar5 = 0; - local_40[1] = 1; - local_40[2] = 5; - local_40[3] = 5; - local_40[4] = 10; - local_40[5] = 10; - local_40[6] = 0xf; - iVar3 = room->_gridWidth * room->_gridHeight; - waveDifficulty = local_40[spawnVariant]; - spawnVariant = 0; - pitCount = 0; - if (0 < iVar3) { - gridEntityCursor = room->_gridEntities; - do { - if (((spawnVariant < 0x1c0) && (*gridEntityCursor != (void *)0x0)) && - (*GHIDRA_CAST((GHIDRA_INT(*gridEntityCursor) + 4)) == 7)) { - uVar5 = uVar5 + 1; - } - spawnVariant = spawnVariant + 1; - gridEntityCursor = gridEntityCursor + 1; - } while (GHIDRA_INT(spawnVariant) < iVar3); - pitCount = uVar5; - } - spawnVariant = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x3dc)); - gideon = this; - puVar4 = local_40 + 0xf; - if (spawnVariant == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - spawnVariant = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x3dc)); - local_4c = g_game; - puVar4 = GHIDRA_CAST(puStack_20); - if (spawnVariant == 0) { - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - } - puStack_20 = GHIDRA_CAST(puVar4); - local_4c = g_game; - spawnVariant = spawnVariant >> ((uint8_t)*GHIDRA_CAST((GHIDRA_CAST(this) + 0x3e0)) & 0x1f) ^ spawnVariant; - local_90 = 0x900000005; - spawnVariant = spawnVariant << ((uint8_t)*GHIDRA_CAST((GHIDRA_CAST(this) + 0x3e4)) & 0x1f) ^ spawnVariant; - spawnVariant = spawnVariant >> ((uint8_t)*GHIDRA_CAST((GHIDRA_CAST(this) + 1000)) & 0x1f) ^ spawnVariant; - local_5c = 7; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x3dc)) = spawnVariant; - puVar4 = GHIDRA_CAST(0x0); - local_50 = GHIDRA_CAST(0x0); - entriesBegin = GHIDRA_CAST(0x0); - entriesEnd = GHIDRA_CAST(0x0); - entriesCapacityEnd = GHIDRA_CAST(0x0); - local_64 = GHIDRA_CAST(0x0); - local_14 = 0; - local_58 = 0; - while (local_50 == puVar4) { - local_84.y = (float)&local_4c->_roomConfig; - local_60 = 0; - local_9c.y = (float)Room::GetRoomShape(room); - if (local_4c->_challenge == 0x2c) { - stageType = Level::GetRoomStageType(GHIDRA_CAST(local_4c),local_4c->_currentRoomIdx); - uVar5 = local_4c->_stage; -LAB_004b1ace: - local_4c = GHIDRA_CAST(RoomConfig)::GetStageID(uVar5,stageType,-1); - } - else { - if (local_4c->_currentDimensionIdx != 2) { - stageType = local_4c->_stageType; - uVar5 = local_4c->_stage; - goto LAB_004b1ace; - } - local_4c = GHIDRA_CAST(0x23); - } - if (spawnVariant == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - spawnVariant = spawnVariant >> ((uint8_t)local_90 & 0x1f) ^ spawnVariant; - spawnVariant = spawnVariant << ((uint8_t)((uint64_t)local_90 >> 0x20) & 0x1f) ^ spawnVariant; - spawnVariant = spawnVariant >> ((uint8_t)local_5c & 0x1f) ^ spawnVariant; - local_4c = RoomConfig::GetRandomRoomWithFallbackStage - (GHIDRA_CAST(local_84.y),spawnVariant,1,GHIDRA_INT(local_4c),0,0xb,GHIDRA_INT(local_9c.y), - in_stack_ffffff38,in_stack_ffffff3c,waveDifficulty,waveDifficulty, - &local_60,0xc,local_5c); - if (local_4c == GHIDRA_CAST(0x0)) { - KAGE_LogMessage(0x10,GHIDRA_CAST("No enemy wave found for Gideon (difficulty: %d)\n")); - } - local_60 = 0; - if ((short)*GHIDRA_CAST((GHIDRA_CAST(local_4c) + 0x44)) != 0) { - local_50 = GHIDRA_CAST(0x0); - do { - roomSpawn = GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(local_4c) + 0x40)) + GHIDRA_INT(local_50))); - if (spawnVariant == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - spawnVariant = spawnVariant >> ((uint8_t)local_90 & 0x1f) ^ spawnVariant; - spawnVariant = spawnVariant << ((uint8_t)((uint64_t)local_90 >> 0x20) & 0x1f) ^ spawnVariant; - spawnVariant = spawnVariant >> ((uint8_t)local_5c & 0x1f) ^ spawnVariant; - puVar4 = (GHIDRA_CAST((roomSpawn)))->Spawn::PickEntry((float)((double)GHIDRA_INT(spawnVariant) + - __uint_to_double_fixup[-(GHIDRA_INT(spawnVariant) >> 0x1f)]) * - 2.3283062e-10); - spawnEntry = *puVar4; - uStack_44 = puVar4[1]; - local_40[0] = puVar4[2]; - iVar3 = roomSpawn[1] + 1; - gridX = *roomSpawn + 1; - if (((gridX < 0) || (room->_gridWidth <= gridX)) || - ((iVar3 < 0 || (room->_gridHeight <= iVar3)))) { - uVar5 = 0xffffffff; - } - else { - uVar5 = room->_gridWidth * iVar3 + gridX; - } - if (spawnVariant == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - spawnVariant = spawnVariant >> ((uint8_t)local_90 & 0x1f) ^ spawnVariant; - spawnVariant = spawnVariant << ((uint8_t)((uint64_t)local_90 >> 0x20) & 0x1f) ^ spawnVariant; - spawnVariant = spawnVariant >> ((uint8_t)local_5c & 0x1f) ^ spawnVariant; - Room::TransformEntry(room,&spawnEntry,uVar5,spawnVariant); - if (GHIDRA_INT(spawnEntry) < 1000) { - if ((spawnEntry == 0x339) && (pitCount < 6)) { - local_50 = entriesBegin; - entriesEnd = entriesBegin; - puVar4 = entriesBegin; - goto LAB_004b1ccf; - } - local_40[4] = spawnEntry; - local_40[5] = uStack_44; - local_40[6] = local_40[0]; - local_40[3] = uVar5; - if (entriesEnd == entriesCapacityEnd) { - msvc::vector::_Emplace_reallocate(entriesEnd,local_40 + 3); - entriesCapacityEnd = local_64; - } - else { - *entriesEnd = uVar5; - entriesEnd[1] = spawnEntry; - entriesEnd[2] = uStack_44; - entriesEnd[3] = local_40[0]; - entriesEnd = entriesEnd + 4; - } - } - local_60 = local_60 + 1; - local_50 = GHIDRA_CAST((GHIDRA_INT(local_50) + 0x10)); - } while (local_60 < (uint16_t)*GHIDRA_CAST((GHIDRA_CAST(local_4c) + 0x44))); - local_50 = entriesBegin; - puVar4 = entriesEnd; - } -LAB_004b1ccf: - local_58 = local_58 + 1; - if (9 < local_58) { - if (local_50 == puVar4) goto LAB_004b1e08; - break; - } - local_4c = g_game; - } - local_4c = GHIDRA_CAST((local_50 + 1)); - do { - local_84.x = (float)(GHIDRA_INT(*GHIDRA_CAST((GHIDRA_CAST(local_4c) + -4))) % room->_gridWidth) * 40.0 + 40.0; - local_84.y = (float)(GHIDRA_INT(*GHIDRA_CAST((GHIDRA_CAST(local_4c) + -4))) / room->_gridWidth) * 40.0 + 120.0; - Room::FindFreeTilePosition(room,&local_9c,&local_84,0.0); - if (spawnVariant == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - spawnVariant = spawnVariant >> ((uint8_t)local_90 & 0x1f) ^ spawnVariant; - spawnVariant = spawnVariant << ((uint8_t)((uint64_t)local_90 >> 0x20) & 0x1f) ^ spawnVariant; - spawnVariant = spawnVariant >> ((uint8_t)local_5c & 0x1f) ^ spawnVariant; - spawnVariant = (uint16_t)*GHIDRA_CAST((GHIDRA_CAST(local_4c) + 4)); - iVar3 = spawn_enemy_spawner_effect - (*GHIDRA_CAST(local_4c),spawnVariant,&local_9c,spawnVariant,gideon, - *GHIDRA_CAST((GHIDRA_CAST(local_4c) + 6)),spawnVariant,spawnVariant,0xffffffff); - if ((((g_game != GHIDRA_CAST(0x0)) && (1 < *GHIDRA_CAST(&g_game->_deathmatchManager))) && - (*GHIDRA_CAST(local_4c) == 1)) || (*GHIDRA_CAST(local_4c) - 10 < 0x3de)) { - *GHIDRA_CAST((iVar3 + 0x16c)) = *GHIDRA_CAST((iVar3 + 0x16c)) | 0x80; - *GHIDRA_CAST((iVar3 + 0x168)) = *GHIDRA_CAST((iVar3 + 0x168)); - } - nextEntry = GHIDRA_CAST((GHIDRA_INT(local_4c) + 0x10)); - puVar4 = GHIDRA_CAST((GHIDRA_INT(local_4c) + 0xc)); - local_4c = GHIDRA_CAST(nextEntry); - } while (puVar4 != entriesEnd); -LAB_004b1e08: - manager = g_manager; - local_58 = 0x367; - seed_fart_sound_override(GHIDRA_CAST(&local_58)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(local_58,1.0,2,0,1.0,0.0); - game = g_game; - maxHitPoints = *GHIDRA_CAST((GHIDRA_CAST(gideon) + 900)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((g_game->_hud))) + 0x54b8)))) = - (short)GHIDRA_INT(((maxHitPoints - *GHIDRA_CAST((GHIDRA_CAST(gideon) + 0x380))) + 1.0)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&((game->_hud))) + 0x54ba)))) = (short)GHIDRA_INT(maxHitPoints); - if (local_50 != GHIDRA_CAST(0x0)) { - spawnVariant = GHIDRA_INT(entriesCapacityEnd) - GHIDRA_INT(local_50) & 0xfffffff0; - puVar4 = local_50; - if (0xfff < spawnVariant) { - puVar4 = GHIDRA_CAST(local_50[-1]); - spawnVariant = spawnVariant + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(local_50) + (-4 - GHIDRA_INT(puVar4))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(puVar4,spawnVariant); - } - } - ExceptionList = local_1c; - return; -} - -// 004b3610 -void NpcHelper::gideon_update_death(Entity_NPC *npc) -{ - float fVar1; - float fVar2; - uint8_t bVar3; - ColorMod *color; - Entity *explosion; - ColorMod *color_00; - Color *pCVar4; - int *gridSlot; - uint32_t uVar5; - int gridSize; - int unusedInt; - uint8_t auStack_4c [7]; - uint8_t isDeathAnim; - int soundId; - float eventPitch; - float pitch; - Color local_38; - uint32_t local_c; - Game *game; - int gridEntity; - Manager *manager; - void *room; - - local_c = __security_cookie ^ GHIDRA_UINT(auStack_4c); - room = (npc->_sprite)._animState._animData; - if (room == (void *)0x0) { - local_38._tint[0] = 0.0; - local_38._colorize[1] = 2.10195e-44; - local_38._colorize[0] = 0.0; - } - else { - (GHIDRA_CAST((GHIDRA_CAST(&local_38))))->msvc::string::string(room); - } - fVar2 = local_38._colorize[1]; - fVar1 = local_38._tint[0]; - pCVar4 = &local_38; - if (0xf < GHIDRA_UINT(local_38._colorize[1])) { - pCVar4 = GHIDRA_CAST(local_38._tint[0]); - } - isDeathAnim = str_eq(GHIDRA_CAST(pCVar4),GHIDRA_UINT(local_38._colorize[0]),GHIDRA_CAST("Death"),5); - if (0xf < GHIDRA_UINT(fVar2)) { - uVar5 = GHIDRA_INT(fVar2) + 1; - pCVar4 = GHIDRA_CAST(fVar1); - if (0xfff < uVar5) { - pCVar4 = GHIDRA_CAST((GHIDRA_CAST((GHIDRA_INT(fVar1) + -0x2c)))->_offset[2]); - uVar5 = GHIDRA_INT(fVar2) + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(fVar1) + (-4 - GHIDRA_INT(pCVar4))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pCVar4,uVar5); - } - if (isDeathAnim == 0) { - return; - } - pitch = 1.0; - if ((npc->_sprite)._animState._animData != (void *)0x0) { - bVar3 = AnimationState::IsEventTriggered(&(npc->_sprite)._animState,GHIDRA_CAST("Sound")); - manager = g_manager; - if (bVar3 != 0) { - eventPitch = 1.0; - if (npc->_championColorIdx == 0x12) { - eventPitch = 1.5; - } - else if (npc->_championColorIdx == 0x13) { - eventPitch = 0.5; - } - soundId = 0x89; - seed_fart_sound_override(&soundId); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(soundId,1.0,2,0,eventPitch,0.0); - (GHIDRA_CAST((&local_38)))->Color::Color(); - Random(); - Game::SpawnParticles(g_game,&npc->_pos,4,4,5.0,color,100000.0,7); - } - if (((npc->_sprite)._animState._animData != (void *)0x0) && - ((npc->_sprite)._animState._isPlaying != 0)) { - return; - } - } - uVar5 = Random(); - explosion = Game::SpawnEx(g_game,1000,1,&npc->_pos,&g_vectorZero,GHIDRA_CAST(0x0),0,uVar5,0); - game = g_game; - (explosion->_sprite)._scale.x = 2.0; - (explosion->_sprite)._scale.y = 2.0; - Game::ShakeScreen(game,0xe); - manager = g_manager; - if (npc->_championColorIdx == 0x12) { - pitch = 1.5; - } - else if (npc->_championColorIdx == 0x13) { - pitch = 0.5; - } - soundId = 0x89; - seed_fart_sound_override(&soundId); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(soundId,1.0,2,0,pitch,0.0); - (GHIDRA_CAST((&local_38)))->Color::Color(); - uVar5 = Random(); - bVar3 = 7; - unusedInt = 0x47c35000; - Game::SpawnParticles(g_game,&npc->_pos,4,uVar5 % 3 + 0xc,9.0,color_00,100000.0,7); - if (npc->_deliriumBossType == 0) { - uVar5 = 0; - room = g_game->_room; - gridSize = *GHIDRA_CAST((GHIDRA_CAST(room) + 0x10)) * *GHIDRA_CAST((GHIDRA_CAST(room) + 0xc)); - if (0 < gridSize) { - gridSlot = GHIDRA_CAST((GHIDRA_INT(room) + 0x24)); - do { - if ((((uVar5 < 0x1c0) && (gridEntity = *gridSlot, gridEntity != 0)) && - (*GHIDRA_CAST((gridEntity + 4)) == 0x12)) && (*GHIDRA_CAST((gridEntity + 8)) == 1)) { - return; - } - uVar5 = uVar5 + 1; - gridSlot = gridSlot + 1; - } while (GHIDRA_INT(uVar5) < gridSize); - } - uVar5 = npc->_projectileDelay; - if ((-1 < GHIDRA_INT(uVar5)) && (uVar5 < 0x1c0)) { - *GHIDRA_CAST((GHIDRA_CAST(room) + uVar5 * 4 + 0x76c)) = 900; - } - (GHIDRA_CAST((GHIDRA_CAST(&g_manager->_musicManager))))->Music::PlayJingle(0x55,unusedInt,bVar3); - gideon_spawn_stairs(npc); - } - return; -} - // 004b3af0 Entity * NpcHelper::heretic_spawn_afterimage(Entity_NPC *npc) { @@ -3493,84 +2545,6 @@ void NpcHelper::hornfel_remove_doors() return; } -// 004b7c30 -void NpcHelper::hornfel_render_minecart(Entity_NPC *npc, ANM2 *minecartSprite, Vector *renderPos) -{ - void *pvVar1; - LayerState *pLVar2; - float *npcFrame; - ANM2 *npcSprite; - uint32_t renderLayer; - AnimationState *local_88; - uint32_t local_84; - uint8_t local_80; - Vector *renderPosLocal; - AnimationState *cartFrame; - AnimationState frameCopy [3]; - float local_8; - int frameIndex; - int layerIndex; - - local_8 = (float)(__security_cookie ^ GHIDRA_UINT(&frameCopy[3]._animFrame)); - renderPosLocal = renderPos; - if (npc->_visible != 0) { - if ((minecartSprite->_animState)._animData == (void *)0x0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("AnimationData is NULL\n")); - } - if (*GHIDRA_CAST((GHIDRA_INT((minecartSprite->_animState)._animation) + 0x80)) < 2) { - KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")); - } - pvVar1 = (minecartSprite->_animState)._animData; - if ((((pvVar1 != (void *)0x0) && - (0 < *GHIDRA_CAST((GHIDRA_INT((minecartSprite->_animState)._animation) + 0x80)))) && - (layerIndex = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x3c)), -1 < layerIndex)) && - (((layerIndex < *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x1c)) && - (frameIndex = *GHIDRA_CAST((GHIDRA_INT((minecartSprite->_animState)._layerFrames) + layerIndex * 4)), - -1 < frameIndex)) && - ((layerIndex = layerIndex * 0x10 + *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x18)), - frameIndex < *GHIDRA_CAST((layerIndex + 8)) && - (cartFrame = GHIDRA_CAST((frameIndex * 0x6c + *GHIDRA_CAST((layerIndex + 4)))), - cartFrame != GHIDRA_CAST(0x0))))))) { - if ((npc->_sprite)._animState._animData == (void *)0x0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("AnimationData is NULL\n")); - } - if (*GHIDRA_CAST((GHIDRA_INT((npc->_sprite)._animState._animation) + 0x80)) < 5) { - KAGE_LogMessage(0x10,GHIDRA_CAST("LayerId out of bounds\n")); - } - pvVar1 = (npc->_sprite)._animState._animData; - if ((((pvVar1 != (void *)0x0) && - (3 < *GHIDRA_CAST((GHIDRA_INT((npc->_sprite)._animState._animation) + 0x80)))) && - ((layerIndex = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x48)), -1 < layerIndex && - (((layerIndex < *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x1c)) && - (frameIndex = *GHIDRA_CAST((GHIDRA_INT((npc->_sprite)._animState._layerFrames) + layerIndex * 4)), - -1 < frameIndex)) && - (layerIndex = layerIndex * 0x10 + *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x18)), - frameIndex < *GHIDRA_CAST((layerIndex + 8)))))))) && - (npcFrame = GHIDRA_CAST((frameIndex * 0x6c + *GHIDRA_CAST((layerIndex + 4)))), - npcFrame != GHIDRA_CAST(0x0))) { - AnimationState::copy_assign(frameCopy,cartFrame); - local_88 = frameCopy; - npcSprite = &npc->_sprite; - local_84 = 1; - renderLayer = 4; - frameCopy[0]._animation = (void *)(((float)frameCopy[0]._animation - 0.0) + *npcFrame); - frameCopy[0]._animData = (void *)(((float)frameCopy[0]._animData - 224.0) + npcFrame[1]); - local_80 = 1; - pLVar2 = ANM2::GetLayer(npcSprite,&DAT_00000004); - pLVar2->_visible = 1; - pLVar2 = ANM2::GetLayer(npcSprite,&DAT_00000004); - (pLVar2->_color)._tint[3] = (minecartSprite->_color)._tint[3]; - AnimationLayer::RenderFrame - (GHIDRA_CAST(&renderLayer),renderPosLocal,0,&g_vectorZero,&g_vectorZero, - npcSprite); - pLVar2 = ANM2::GetLayer(npcSprite,&DAT_00000004); - pLVar2->_visible = 0; - } - } - } - return; -} - // 004b7e30 void NpcHelper::hornfel_charge(Entity_NPC *npc) { @@ -5170,153 +4144,6 @@ LAB_004bce05: return pEVar4; } -// 004bcfd0 -void NpcHelper::horny_boys_render(Entity_NPC *npc, Vector *offset) -{ - Vector *position; - int iVar1; - void *layerFrame; - AnimationState *secondState; - uint32_t dequeIndex; - float renderScale; - double dVar2; - double dVar3; - uint32_t layerIdx; - int layerOffset; - void *animData; - float offsetY; - - Entity::Render(GHIDRA_CAST(npc),offset); - renderScale = g_displayPixelRatio * g_screenPointScale; - dVar2 = floor((double)(((((npc->_posOffset).x + (npc->_pos).x) - 60.0) * 0.65 + - (g_screenWidth - 338.0) * 0.5) * renderScale + 0.5)); - dVar3 = floor((double)(((((npc->_pos).y + (npc->_posOffset).y) - 140.0) * 0.65 + - (g_screenHeight - 182.0) * 0.5) * renderScale + 0.5)); - position = &npc->_renderPosition; - offsetY = offset->y; - position->x = (float)dVar2 / renderScale + offset->x; - (npc->_renderPosition).y = (float)dVar3 / renderScale + offsetY; - animData = (npc->_sprite)._animState._animData; - if ((animData != (void *)0x0) && (layerIdx = 0, *GHIDRA_CAST((GHIDRA_CAST(animData) + 0x1c)) != 0)) { - layerOffset = 0; - do { - iVar1 = *GHIDRA_CAST((layerOffset + *GHIDRA_CAST((GHIDRA_CAST(animData) + 0x18)))); - layerFrame = AnimationState::GetLayerFrame(&(npc->_sprite)._animState,iVar1); - if ((((layerFrame != (void *)0x0) && (*GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x2c)) != '\0')) && - (iVar1 - 3U < 3)) && - (dequeIndex = ((npc->_entityDeque)._offset - 3) + iVar1, - iVar1 = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + - (dequeIndex >> 2 & (npc->_entityDeque)._mapSize - 1) * 4)) + - (dequeIndex & 3) * 4)), iVar1 != 0)) { - *GHIDRA_CAST((iVar1 + 0xdc)) = *GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x10)); - *GHIDRA_CAST((iVar1 + 0xe0)) = *GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x14)); - *GHIDRA_CAST((iVar1 + 0xec)) = *GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x5c)); - *GHIDRA_CAST((iVar1 + 0xe4)) = *GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x18)); - *GHIDRA_CAST((iVar1 + 0xe8)) = *GHIDRA_CAST((GHIDRA_CAST(layerFrame) + 0x1c)); - if (*GHIDRA_CAST((iVar1 + 0x151)) != '\0') { - if (*GHIDRA_CAST((iVar1 + 0xb8)) == '\0') { - AnimationState::Render - (GHIDRA_CAST((iVar1 + 0x78)),position,&g_vectorZero,&g_vectorZero); - secondState = GHIDRA_CAST((iVar1 + 0x98)); - } - else { - AnimationState::Render - (GHIDRA_CAST((iVar1 + 0x98)),position,&g_vectorZero,&g_vectorZero); - secondState = GHIDRA_CAST((iVar1 + 0x78)); - } - AnimationState::Render(secondState,position,&g_vectorZero,&g_vectorZero); - } - *GHIDRA_CAST((iVar1 + 0xdc)) = g_vectorZero.x; - *GHIDRA_CAST((iVar1 + 0xe0)) = g_vectorZero.y; - *GHIDRA_CAST((iVar1 + 0xec)) = 0; - *GHIDRA_CAST((iVar1 + 0xe4)) = g_vectorOne.x; - *GHIDRA_CAST((iVar1 + 0xe8)) = g_vectorOne.y; - } - layerIdx = layerIdx + 1; - layerOffset = layerOffset + 0x10; - } while (layerIdx < *GHIDRA_CAST((GHIDRA_CAST(animData) + 0x1c))); - } - return; -} - -// 004be670 -Entity * NpcHelper::query_nearest_other(void *queryList, Entity *exclude, Vector position) -{ - int *entityIt; - Entity *pEVar1; - int remaining; - float fVar2; - float dy; - float nearestDistSq; - Entity *candidate; - - remaining = *GHIDRA_CAST((GHIDRA_CAST(queryList) + 0xc)); - pEVar1 = GHIDRA_CAST(0x0); - nearestDistSq = 0.0; - if (remaining != 0) { - entityIt = *GHIDRA_CAST((GHIDRA_CAST(queryList) + 4)); - do { - candidate = GHIDRA_CAST(*entityIt); - if ((candidate != exclude) && - ((dy = position.y - (candidate->_pos).y, fVar2 = position.x - (candidate->_pos).x, - fVar2 = dy * dy + fVar2 * fVar2, fVar2 < nearestDistSq || (pEVar1 == GHIDRA_CAST(0x0))))) { - pEVar1 = candidate; - nearestDistSq = fVar2; - } - entityIt = entityIt + 1; - remaining = remaining + -1; - } while (remaining != 0); - } - return pEVar1; -} - -// 004cf5b0 -void NpcHelper::min_min_willo_count(Entity_NPC *minMin, int *outWilloCount, int *outOwnedCount) -{ - uint32_t uVar1; - uint64_t *allocCounter; - EntityList_EL willoList; - void *local_10; - uint8_t *puStack_c; - uint32_t uStack_8; - uint64_t allocatedBytes; - - uStack_8 = 0xffffffff; - puStack_c = &LAB_00af1690; - local_10 = ExceptionList; - ExceptionList = &local_10; - EntityList::QuerySublist(GHIDRA_CAST((GHIDRA_INT(g_game->_room) + 0x1218)),&willoList,0x328,-1,-1,0,0); - uVar1 = 0; - *outWilloCount = willoList._size; - *outOwnedCount = 0; - if (willoList._size != 0) { - do { - if (*GHIDRA_CAST((*GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(willoList)) + 0x4))) + uVar1 * 4)) + 0x3bc)) == minMin) { - *outOwnedCount = *outOwnedCount + 1; - } - uVar1 = uVar1 + 1; - } while (uVar1 < GHIDRA_UINT(willoList._size)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(willoList)) + 0x0))) == '\0') { - if (g_mainHeap == (void *)0x0) { - allocCounter = &g_allocatedBytesNoHeap; - } - else { - allocCounter = GHIDRA_CAST((GHIDRA_INT(g_mainHeap) + 0x30)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(willoList)) + 0x4))) != 0) { - uVar1 = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(willoList)) + 0x4))) + -4)); - allocatedBytes = *allocCounter; - *GHIDRA_CAST(allocCounter) = GHIDRA_UINT(*allocCounter) - uVar1; - *GHIDRA_CAST((GHIDRA_CAST(allocCounter) + 4)) = - *GHIDRA_CAST((GHIDRA_CAST(allocCounter) + 4)) - GHIDRA_UINT((GHIDRA_UINT(allocatedBytes) < uVar1)); - free((void *)((*GHIDRA_CAST((GHIDRA_CAST(&(willoList)) + 0x4))) + -4)); - } - } - ExceptionList = local_10; - return; -} - // 004d8d10 Entity_NPC * NpcHelper::gaper_l2_spawn_maggot(Vector *origin, float yOffset, Vector *velocity, float fallingSpeed) { @@ -5687,121 +4514,6 @@ uint8_t NpcHelper::whipper_is_target(Entity_NPC *npc, Entity *entity) return 0; } -// 004f5f20 -void NpcHelper::ball_and_chain_render_chain(float *param_1) -{ - LayerState *pLVar1; - ColorMod *color; - ColorMod *extraout_EAX; - int in_ECX; - float fVar2; - float fVar3; - float anchorOffsetX; - float anchorOffsetX; - double dVar5; - ColorMod *color_00; - uint8_t auStack_b4 [24]; - float local_9c; - Vector local_98; - float local_90; - float local_8c; - float snappedX; - float dirX; - float dirY; - float pixelScale; - Vector renderPos; - Color beamColor; - uint32_t securityCookie; - ANM2 *sprite; - - securityCookie = __security_cookie ^ GHIDRA_UINT(auStack_b4); - if ((*GHIDRA_CAST((in_ECX + 0x334)) != g_vectorZero.x) || - (*GHIDRA_CAST((in_ECX + 0x338)) != g_vectorZero.y)) { - local_8c = *GHIDRA_CAST((in_ECX + 0x33c)) - *GHIDRA_CAST((in_ECX + 0x334)); - local_90 = *GHIDRA_CAST((in_ECX + 0x340)) - *GHIDRA_CAST((in_ECX + 0x338)); - dirX = local_8c; - dirY = local_90; - fVar2 = sqrtf(local_90 * local_90 + local_8c * local_8c); - if (fVar2 <= 0.0) { - fVar3 = local_8c; - anchorOffsetX = local_90; - } - else { - local_90 = (1.0 / fVar2) * dirY; - local_8c = (1.0 / fVar2) * dirX; - fVar3 = dirX; - anchorOffsetX = dirY; - } - anchorOffsetX = local_8c * 4.0; - local_90 = (local_90 * 4.0 * 0.6 + *GHIDRA_CAST((in_ECX + 0x338))) - 8.0; - if (0.0 < fVar2) { - dirY = anchorOffsetX * (1.0 / fVar2); - dirX = fVar3 * (1.0 / fVar2); - } - local_8c = (g_screenHeight - 182.0) * 0.5; - local_98.x = (g_screenWidth - 338.0) * 0.5; - pixelScale = g_displayPixelRatio * g_screenPointScale; - local_9c = (((anchorOffsetX + *GHIDRA_CAST((in_ECX + 0x334)) + 0.0) - 60.0) * 0.65 + local_98.x) * - pixelScale + 0.5; - dVar5 = floor((double)local_9c); - snappedX = (float)dVar5 / pixelScale; - local_9c = ((local_90 - 140.0) * 0.65 + local_8c) * pixelScale + 0.5; - dVar5 = floor((double)local_9c); - local_90 = *param_1; - local_9c = param_1[1]; - renderPos.x = local_90 + snappedX; - renderPos.y = local_9c + (float)dVar5 / pixelScale; - local_98.x = ((((*GHIDRA_CAST((in_ECX + 0x33c)) - dirX * 10.0) + *GHIDRA_CAST((in_ECX + 0x34c))) - 60.0) - * 0.65 + local_98.x) * pixelScale + 0.5; - dVar5 = floor((double)local_98.x); - snappedX = (float)dVar5 / pixelScale; - local_98.x = ((((*GHIDRA_CAST((in_ECX + 0x340)) - dirY * 10.0) + *GHIDRA_CAST((in_ECX + 0x350))) - 140.0 - ) * 0.65 + local_8c) * pixelScale + 0.5; - dVar5 = floor((double)local_98.x); - sprite = GHIDRA_CAST((in_ECX + 0x48)); - local_98.x = local_90 + snappedX; - local_9c = local_9c + (float)dVar5 / pixelScale; - local_98.y = local_9c; - local_90 = local_98.x; - pLVar1 = ANM2::GetLayer(sprite,GHIDRA_CAST(0x1)); - pLVar1->_visible = 1; - DAT_00c78ef4 = 1; - (*GHIDRA_CAST((GHIDRA_CAST(&(DAT_00c78ef8)) + 0x0))) = 1; - g_beamRendererPointsEnd = g_beamRendererPoints; - DAT_00c78ef0 = sprite; - (GHIDRA_CAST((&beamColor)))->Color::Color(); - BeamRenderer::Add(&renderPos,color,1.0,0.0); - (GHIDRA_CAST((&beamColor)))->Color::Color(); - color_00 = extraout_EAX; - fVar2 = sqrtf((local_9c - renderPos.y) * (local_9c - renderPos.y) + - (local_90 - renderPos.x) * (local_90 - renderPos.x)); - BeamRenderer::Add(&local_98,color_00,1.0,fVar2); - BeamRenderer::End(); - pLVar1 = ANM2::GetLayer(sprite,GHIDRA_CAST(0x1)); - local_8c = g_displayPixelRatio; - pLVar1->_visible = 0; - local_8c = local_8c * g_screenPointScale; - local_98.x = (((*GHIDRA_CAST((in_ECX + 0x334)) + 0.0) - 60.0) * 0.65 + (g_screenWidth - 338.0) * 0.5 - ) * local_8c + 0.5; - dVar5 = floor((double)local_98.x); - snappedX = (float)dVar5 / local_8c; - local_98.x = (((*GHIDRA_CAST((in_ECX + 0x338)) - 8.0) - 140.0) * 0.65 + - (g_screenHeight - 182.0) * 0.5) * local_8c + 0.5; - dVar5 = floor((double)local_98.x); - renderPos.y = (float)dVar5 / local_8c + param_1[1]; - renderPos.x = snappedX + *param_1; - local_98.x = *GHIDRA_CAST((in_ECX + 0xec)); - *GHIDRA_CAST((in_ECX + 0xec)) = 0; - pLVar1 = ANM2::GetLayer(sprite,GHIDRA_CAST(0x2)); - pLVar1->_visible = 1; - (GHIDRA_CAST((GHIDRA_CAST(sprite))))->Sprite::RenderLayer(2,&renderPos,&g_vectorZero,&g_vectorZero); - pLVar1 = ANM2::GetLayer(sprite,GHIDRA_CAST(0x2)); - pLVar1->_visible = 0; - *GHIDRA_CAST((in_ECX + 0xec)) = local_98.x; - } - return; -} - // 00501e10 void NpcHelper::bouncer_death_gib(Entity_Effect *timer) { @@ -6407,595 +5119,6 @@ uint8_t NpcHelper::tarboy_is_creep_near(Entity_NPC *npc, Vector *position) return 0; } -// 00548720 -void NpcHelper::leper_flesh_ai(Entity_NPC *npc) -{ - code *pcVar1; - uint8_t bVar2; - Vector *pVVar3; - uint32_t uVar4; - uint8_t *pbVar5; - uint32_t uVar6; - Entity *pEVar7; - uint8_t *expectedName; - int extraout_ECX; - int extraout_ECX_00; - int unused; - bool isLess; - float fVar8; - float fVar9; - uint32_t sourceRef; - uint32_t local_114; - uint32_t local_110; - uint32_t local_10c; - float local_108; - float local_104; - float local_100; - float local_fc; - uint32_t local_f8; - uint32_t local_f4; - float local_f0; - uint32_t uStack_ec; - uint32_t uStack_e8; - uint32_t uStack_e4; - Vector local_d4; - float local_cc; - uint8_t *local_c8; - float local_c4; - ProjectileParams projParams; - float local_14; - - local_14 = (float)(__security_cookie ^ GHIDRA_UINT(&(&projParams)[1].CircleAngle)); - if (npc->_state != 0) { - if (npc->_state == 4) { - npc->_friction = npc->_friction * 0.95; - pVVar3 = Entity_NPC::CalcTargetPosition(npc,&local_d4,0.0); - local_c8 = GHIDRA_CAST((pVVar3->y - (npc->_pos).y)); - local_c4 = pVVar3->x - (npc->_pos).x; - fVar8 = sqrtf((float)local_c8 * (float)local_c8 + local_c4 * local_c4); - if (0.0 < fVar8) { - local_c4 = local_c4 * (1.0 / fVar8); - local_c8 = GHIDRA_CAST(((float)local_c8 * (1.0 / fVar8))); - } - if (npc->_controllerID != -1) { - pVVar3 = Entity_NPC::GetControllerInput(npc,&local_d4,0.0); - local_c4 = pVVar3->x; - local_c8 = GHIDRA_CAST(pVVar3->y); - } - uVar4 = Random(); - local_cc = (float)((double)GHIDRA_INT(uVar4) + __uint_to_double_fixup[-(GHIDRA_INT(uVar4) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_cc = local_cc + local_cc; - local_d4.y = cos(local_cc); - fVar9 = sin(local_cc); - fVar8 = npc->_speedMultiplier; - (npc->_velocity).y = (fVar9 + fVar9 + (float)local_c8) * 0.15 * fVar8 + (npc->_velocity).y; - (npc->_velocity).x = (local_d4.y + local_d4.y + local_c4) * 0.15 * fVar8 + (npc->_velocity).x; - } - goto LAB_00548a4b; - } - uVar4 = npc->_initSeed; - local_c4 = 2.10195e-44; - local_d4.y = (float)&npc->_sprite; - uStack_ec = 2; - uStack_e8 = 5; - if (uVar4 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - uVar4 = uVar4 >> 2 ^ uVar4; - uVar4 = uVar4 << 5 ^ uVar4; - uVar4 = uVar4 >> 0xf ^ uVar4; - local_c8 = (&PTR_DAT_00b614c0)[uVar4 % 6]; - pbVar5 = (npc->_sprite)._animState._animData; - if (pbVar5 == GHIDRA_CAST(0x0)) { -LAB_005489d8: - bVar2 = ANM2::SetAnimation(&npc->_sprite,local_c8,1); - if (bVar2 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } - } - else { - if (0xf < *GHIDRA_CAST((pbVar5 + 0x14))) { - pbVar5 = *GHIDRA_CAST(pbVar5); - } - expectedName = local_c8; - do { - bVar2 = *pbVar5; - isLess = bVar2 < *expectedName; - if (bVar2 != *expectedName) { -LAB_005489b8: - uVar6 = -GHIDRA_UINT(isLess) | 1; - goto LAB_005489bd; - } - if (bVar2 == 0) break; - bVar2 = pbVar5[1]; - isLess = bVar2 < expectedName[1]; - if (bVar2 != expectedName[1]) goto LAB_005489b8; - pbVar5 = pbVar5 + 2; - expectedName = expectedName + 2; - } while (bVar2 != 0); - uVar6 = 0; -LAB_005489bd: - if ((uVar6 != 0) || - ((*GHIDRA_CAST((GHIDRA_INT((npc->_sprite)._animState._animData) + 0x34)) != '\0' && - ((npc->_sprite)._animState._isPlaying == 0)))) goto LAB_005489d8; - } - npc->_state = 4; - if (uVar4 == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar1 = (code *)swi(3); - (*pcVar1)(); - return; - } - uVar4 = uVar4 >> ((uint8_t)uStack_ec & 0x1f) ^ uVar4; - uVar4 = uVar4 << ((uint8_t)uStack_e8 & 0x1f) ^ uVar4; - (npc->_sprite)._flipX = ~((uint8_t)(uVar4 >> (SUB41(local_c4,0) & 0x1f)) ^ (uint8_t)uVar4) & 1; - npc->_isKillOnTouch = 1; -LAB_00548a4b: - bVar2 = Entity::IsFrame(GHIDRA_CAST(npc),10,0); - if (bVar2 != 0) { - uVar4 = Random(); - Entity_NPC::MakeSplat - (npc,(float)((double)GHIDRA_INT(uVar4) + __uint_to_double_fixup[-(GHIDRA_INT(uVar4) >> 0x1f)]) * - 2.3283064e-10 * 0.4 + 0.4); - } - bVar2 = Entity::IsFrame(GHIDRA_CAST(npc),6,0); - local_f0 = 0.3; - uStack_ec = 0; - uStack_e8 = 0; - uStack_e4 = 0; - unused = extraout_ECX; - if (bVar2 != 0) { - uVar4 = Random(); - local_d4.y = (npc->_velocity).x; - local_cc = (npc->_velocity).y; - uVar6 = Random(); - fVar8 = (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_c8 = GHIDRA_CAST((fVar8 + fVar8)); - uVar6 = Random(); - local_c4 = (float)((double)GHIDRA_INT(uVar6) + __uint_to_double_fixup[-(GHIDRA_INT(uVar6) >> 0x1f)]) * - 2.3283064e-10; - fVar8 = cos((float)local_c8); - local_d4.x = fVar8 * local_c4 * 3.0 + local_d4.y * local_f0; - fVar8 = sin((float)local_c8); - local_d4.y = fVar8 * local_c4 * 3.0 + local_cc * local_f0; - pEVar7 = Game::Spawn(g_game,1000,0x6f,&npc->_pos,&local_d4,GHIDRA_CAST(0x0),0,uVar4); - uVar4 = Random(); - (pEVar7->_sprite)._playbackSpeed = - (float)((double)GHIDRA_INT(uVar4) + __uint_to_double_fixup[-(GHIDRA_INT(uVar4) >> 0x1f)]) * 2.3283064e-10 - * 0.6 + 0.5; - local_cc = npc->_scale * g_vectorOne.y; - local_d4.y = npc->_scale * g_vectorOne.x; - uVar4 = Random(); - fVar8 = (float)((double)GHIDRA_INT(uVar4) + __uint_to_double_fixup[-(GHIDRA_INT(uVar4) >> 0x1f)]) * - 2.3283064e-10 * 0.6 + 0.6; - (pEVar7->_sprite)._scale.x = local_d4.y * 0.5 * fVar8; - (pEVar7->_sprite)._scale.y = local_cc * 0.5 * fVar8; - (pEVar7->_posOffset).x = 0.0; - (pEVar7->_posOffset).y = -22.0; - pEVar7->_renderZOffset = -400; - unused = extraout_ECX_00; - } - if ((npc->_controllerID != -1) && - (bVar2 = input_is_action_pressed(9,npc->_controllerID,GHIDRA_CAST(npc),unused), bVar2 != 0)) { - sourceRef = 0; - local_114 = 0; - local_110 = 0; - local_10c = 0; - local_108 = g_vectorZero.x; - local_104 = g_vectorZero.y; - local_100 = g_vectorZero.x; - local_fc = g_vectorZero.y; - local_f8 = 0; - local_f4 = 0; - (**(code **)(*GHIDRA_CAST(npc) + 0x24))(&sourceRef); - } - if ((npc->_dead != 0) && ((npc->_flags & 0x1000000) == 0)) { - pEVar7 = Entity_NPC::GetPlayerTarget(npc); - local_c8 = GHIDRA_CAST((pEVar7->_velocity).x); - fVar8 = (npc->_pos).y - (pEVar7->_pos).y; - local_c4 = (pEVar7->_velocity).y; - fVar9 = (npc->_pos).x - (pEVar7->_pos).x; - fVar8 = sqrtf(fVar8 * fVar8 + fVar9 * fVar9); - local_c8 = GHIDRA_CAST((((float)local_c8 * 0.1 * fVar8 + (pEVar7->_pos).x) - (npc->_pos).x)); - local_c4 = (local_c4 * 0.1 * fVar8 + (pEVar7->_pos).y) - (npc->_pos).y; - fVar8 = sqrtf(local_c4 * local_c4 + (float)local_c8 * (float)local_c8); - if (fVar8 <= 0.0) { - pbVar5 = local_c8; - fVar8 = local_c4; - } - else { - pbVar5 = GHIDRA_CAST(((float)local_c8 * (1.0 / fVar8))); - fVar8 = local_c4 * (1.0 / fVar8); - } - local_d4.x = (float)pbVar5 * 10.0; - local_d4.y = fVar8 * 10.0; - ProjectileParams::ProjectileParams(&projParams); - projParams.Color._offset[2] = 0.0; - projParams.Color._tint[0] = 1.0; - projParams.Color._tint[1] = 1.0; - projParams.Color._tint[2] = 1.0; - projParams.Color._tint[3] = 1.0; - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.Color._offset)) + 0x0))) = ZEXT48(GHIDRA_UINT(local_f0)); - projParams.Color._colorize[0] = 0.0; - projParams.Color._colorize[1] = 0.0; - projParams.Color._colorize[2] = 0.0; - projParams.Color._colorize[3] = 0.0; - Entity_NPC::FireProjectiles(npc,&npc->_pos,&local_d4,0,&projParams); - } - return; -} - -// 00557f70 -Vector * NpcHelper::willo_slot(Entity_NPC *npc, Vector *outPos, int slot) -{ - uint32_t frameParity; - float radius; - float fVar1; - float local_14; - Vector targetPos; - - willo_get_target_pos(npc,&targetPos,&local_14); - frameParity = g_manager->_framecount & 0x80000001; - if (GHIDRA_INT(frameParity) < 0) { - frameParity = (frameParity - 1 | 0xfffffffe) + 1; - } - if (npc->_state == 8) { - local_14 = (npc->_v2).y; - } - else { - local_14 = (npc->_v2).x; - } - radius = (npc->_v1).y * (npc->_v1).x; - local_14 = local_14 - - ((float)GHIDRA_INT(frameParity) * 0.5 + (float)g_game->_frameCount + (float)slot) * 0.5 * - 3.1415927 * 0.035; - fVar1 = cos(local_14); - outPos->x = fVar1 * radius + targetPos.x; - fVar1 = sin(local_14); - outPos->y = fVar1 * radius * 0.84 + targetPos.y; - return outPos; -} - -// 00558070 -void NpcHelper::willo_get_target_pos(Entity_NPC *npc, Vector *outPos, float *outSpread) -{ - int iVar1; - int *playerSlot; - int iVar2; - int *spreadSlot; - float averageX; - float deltaX; - float averageY; - float fVar3; - float maxSpread; - int *playersEnd; - - iVar2 = npc->_parent; - if (iVar2 != 0) { - if (outSpread != GHIDRA_CAST(0x0)) { - *outSpread = 0.0; - iVar2 = npc->_parent; - } - fVar3 = *GHIDRA_CAST((iVar2 + 0x340)); - outPos->x = *GHIDRA_CAST((iVar2 + 0x33c)); - outPos->y = fVar3; - return; - } - iVar2 = 0; - fVar3 = 0.0; - maxSpread = 0.0; - playersEnd = (g_game->_playerManager)._playerList._end; - spreadSlot = (g_game->_playerManager)._playerList._begin; - averageX = g_vectorZero.x; - averageY = g_vectorZero.y; - for (playerSlot = spreadSlot; playerSlot != playersEnd; playerSlot = playerSlot + 1) { - iVar1 = *playerSlot; - if ((*GHIDRA_CAST((iVar1 + 0x2c)) == 0) && (*GHIDRA_CAST((iVar1 + 0x13c0)) != 0x23)) { - averageX = averageX + *GHIDRA_CAST((iVar1 + 0x33c)); - averageY = averageY + *GHIDRA_CAST((iVar1 + 0x340)); - iVar2 = iVar2 + 1; - } - } - averageX = averageX / (float)iVar2; - averageY = averageY / (float)iVar2; - if (outSpread != GHIDRA_CAST(0x0)) { - if (1 < iVar2) { - for (; spreadSlot != playersEnd; spreadSlot = spreadSlot + 1) { - iVar2 = *spreadSlot; - if ((*GHIDRA_CAST((iVar2 + 0x2c)) == 0) && (*GHIDRA_CAST((iVar2 + 0x13c0)) != 0x23)) { - deltaX = averageX - *GHIDRA_CAST((iVar2 + 0x33c)); - fVar3 = averageY - *GHIDRA_CAST((iVar2 + 0x340)); - fVar3 = sqrtf(fVar3 * fVar3 + deltaX * deltaX); - if (fVar3 <= maxSpread) { - fVar3 = maxSpread; - } - maxSpread = fVar3; - } - } - } - *outSpread = fVar3; - } - outPos->x = averageX; - outPos->y = averageY; - return; -} - -// 005581b0 -void NpcHelper::willo_orbit(Entity_NPC *npc) -{ - int *playerIt; - int player; - float fVar2; - float fVar3; - float fVar4; - float fVar5; - float fVar6; - Vector slotPos; - int player; - - if (npc->_subtype == 0) { - willo_slot(npc,&slotPos,0); - fVar3 = (npc->_pos).x; - fVar4 = slotPos.x - fVar3; - fVar2 = slotPos.y - (npc->_pos).y; - fVar2 = sqrtf(fVar2 * fVar2 + fVar4 * fVar4); - if ((fVar2 < 20.0) && (npc->_projectileDelay == 1)) { - npc->_projectileDelay = 0; - } - player = npc->_parent; - if (player == 0) { - player = 0; - fVar2 = g_vectorZero.x; - fVar4 = g_vectorZero.y; - for (playerIt = (g_game->_playerManager)._playerList._begin; - playerIt != (g_game->_playerManager)._playerList._end; playerIt = playerIt + 1) { - player = *playerIt; - if (*GHIDRA_CAST((player + 0x2c)) == 0) { - player = player + 1; - fVar5 = *GHIDRA_CAST((player + 0x360)) / *GHIDRA_CAST((player + 0x36c)); - fVar6 = *GHIDRA_CAST((player + 0x364)) / *GHIDRA_CAST((player + 0x36c)); - fVar2 = fVar2 + fVar5 + fVar5; - fVar4 = fVar4 + fVar6 + fVar6; - } - } - fVar2 = fVar2 / (float)player; - fVar4 = fVar4 / (float)player; - } - else { - fVar2 = *GHIDRA_CAST((player + 0x360)) / *GHIDRA_CAST((player + 0x36c)); - fVar4 = *GHIDRA_CAST((player + 0x364)) / *GHIDRA_CAST((player + 0x36c)); - fVar2 = fVar2 + fVar2 + g_vectorZero.x; - fVar4 = fVar4 + fVar4 + g_vectorZero.y; - } - fVar5 = (slotPos.x - (fVar3 + fVar2)) * 0.5; - fVar6 = (slotPos.y - (fVar4 + (npc->_pos).y)) * 0.5; - fVar3 = sqrtf(fVar6 * fVar6 + fVar5 * fVar5); - if (10.0 < fVar3) { - if (fVar3 <= 0.0) { - fVar5 = fVar5 * 10.0; - fVar6 = fVar6 * 10.0; - } - else { - fVar5 = fVar5 * (1.0 / fVar3) * 10.0; - fVar6 = fVar6 * (1.0 / fVar3) * 10.0; - } - } - fVar3 = npc->_friction; - (npc->_velocity).x = (fVar5 + fVar2) / fVar3; - (npc->_velocity).y = (fVar6 + fVar4) / fVar3; - } - return; -} - -// 005583d0 -void NpcHelper::willo_attack(Entity_NPC *npc) -{ - uint8_t isEventTriggered; - Entity *target; - float distance; - Vector shotVelocity; - float local_bc; - float local_b8; - ProjectileParams projParams; - float local_8; - Manager *manager; - - local_8 = (float)(__security_cookie ^ GHIDRA_UINT(&(&projParams)[1].CircleAngle)); - if (((npc->_sprite)._animState._animData == (void *)0x0) || - ((npc->_sprite)._animState._isPlaying == 0)) { - npc->_state = 3; - return; - } - isEventTriggered = AnimationState::IsEventTriggered(&(npc->_sprite)._animState,&DAT_00b6166c); - manager = g_manager; - if (isEventTriggered != 0) { - local_b8 = 1.0; - if (npc->_championColorIdx == 0x12) { - local_b8 = 1.5; - } - else if (npc->_championColorIdx == 0x13) { - local_b8 = 0.5; - } - local_bc = 6.60012e-43; - seed_fart_sound_override(GHIDRA_CAST(&local_bc)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_bc),1.0,2,0,local_b8,0.0); - } - if ((npc->_sprite)._animState._animData == (void *)0x0) { - return; - } - isEventTriggered = AnimationState::IsEventTriggered(&(npc->_sprite)._animState,GHIDRA_CAST("Shoot")); - manager = g_manager; - if (isEventTriggered == 0) { - return; - } - local_b8 = 1.0; - if (npc->_championColorIdx == 0x12) { - local_b8 = 1.5; - } - else if (npc->_championColorIdx == 0x13) { - local_b8 = 0.5; - } - local_bc = 2.14399e-43; - seed_fart_sound_override(GHIDRA_CAST(&local_bc)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_bc),1.0,2,0,local_b8,0.0); - target = Entity_NPC::GetPlayerTarget(npc); - ProjectileParams::ProjectileParams(&projParams); - local_bc = ((target->_pos).x + (target->_velocity).x) - (npc->_pos).x; - local_b8 = ((target->_pos).y + (target->_velocity).y) - (npc->_pos).y; - distance = sqrtf(local_bc * local_bc + local_b8 * local_b8); - shotVelocity.x = local_bc; - shotVelocity.y = local_b8; - if (0.0 < distance) { - shotVelocity.y = local_b8 * (1.0 / distance); - shotVelocity.x = local_bc * (1.0 / distance); - } - shotVelocity.x = shotVelocity.x * 10.0; - projParams.Color._offset[2] = DAT_00c33cd8; - shotVelocity.y = shotVelocity.y * 10.0; - projParams.Variant = 4; - projParams.Color._tint[0] = _DAT_00c33cb0; - projParams.Color._tint[1] = fRam00c33cb4; - projParams.Color._tint[2] = fRam00c33cb8; - projParams.Color._tint[3] = fRam00c33cbc; - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x0))) = 0x2000; - (*GHIDRA_CAST((GHIDRA_CAST(&(projParams.BulletFlags)) + 0x4))) = 0; - projParams.Color._colorize[0] = _DAT_00c33cc0; - projParams.Color._colorize[1] = fRam00c33cc4; - projParams.Color._colorize[2] = fRam00c33cc8; - projParams.Color._colorize[3] = fRam00c33ccc; - projParams.Color._offset[0] = (float)DAT_00c33cd0; - projParams.Color._offset[1] = (*GHIDRA_CAST((GHIDRA_CAST(&(DAT_00c33cd0)) + 0x4))); - if ((npc->_parent == 0) && (npc->_subtype == 0)) { - projParams.FallingSpeedModifier = projParams.FallingSpeedModifier + 4.0; - } - Entity_NPC::FireProjectiles(npc,&npc->_pos,&shotVelocity,0,&projParams); - return; -} - -// 00558fe0 -Entity_NPC * NpcHelper::min_min_spawn_willo(Vector *position, Entity_NPC *spawner, float v1X, int subType) -{ - uint8_t bVar1; - uint32_t flagsHigh; - Entity_NPC *willo; - uint8_t *curAnimName; - char *targetAnimName; - bool bVar3; - uint32_t *eraseKey; - float v1XLocal; - Vector *spawnPos; - uint8_t *animData; - uint32_t flagsHigh; - uint32_t *parentSlot; - - v1XLocal = v1X; - spawnPos = position; - flagsHigh = Random(); - willo = (Entity_NPC *) - Game::SpawnEx(g_game,0x328,0,position,&g_vectorZero,GHIDRA_CAST(spawner),subType & 0xff,flagsHigh - ,0); - if (spawner != GHIDRA_CAST(0x0)) { - parentSlot = &willo->_parent; - if (willo->_parent != 0) { - eraseKey = parentSlot; - msvc::multiset::erase(&eraseKey); - } - *parentSlot = spawner; - msvc::multiset::insert(parentSlot); - } - *GHIDRA_CAST(&willo->_flags) = GHIDRA_UINT(willo->_flags) & 0xfffffffb; - flagsHigh = *GHIDRA_CAST((GHIDRA_INT(&willo->_flags) + 4)); - (willo->_v1).x = v1XLocal; - (willo->_v1).y = 1.0; - *GHIDRA_CAST((GHIDRA_INT(&willo->_flags) + 4)) = flagsHigh; - if ((char)subType == '\0') { - willo->_state = 6; - animData = (willo->_sprite)._animState._animData; - if (animData != GHIDRA_CAST(0x0)) { - curAnimName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - curAnimName = *GHIDRA_CAST(animData); - } - targetAnimName = "UnderwaterSpawn"; - do { - bVar1 = *curAnimName; - bVar3 = bVar1 < (uint8_t)*targetAnimName; - if (bVar1 != *targetAnimName) { -LAB_00559170: - flagsHigh = -GHIDRA_UINT(bVar3) | 1; - goto LAB_00559175; - } - if (bVar1 == 0) break; - bVar1 = curAnimName[1]; - bVar3 = bVar1 < (uint8_t)targetAnimName[1]; - if (bVar1 != targetAnimName[1]) goto LAB_00559170; - curAnimName = curAnimName + 2; - targetAnimName = targetAnimName + 2; - } while (bVar1 != 0); - flagsHigh = 0; -LAB_00559175: - if (flagsHigh == 0) { - if (animData[0x34] == 0) { - return willo; - } - if ((willo->_sprite)._animState._isPlaying != 0) { - return willo; - } - } - } - bVar1 = ANM2::SetAnimation(&willo->_sprite,GHIDRA_CAST("UnderwaterSpawn"),1); - if (bVar1 != 0) { - AnimationState::Rewind(&(willo->_sprite)._animState); - (willo->_sprite)._animState._isPlaying = 1; - } - return willo; - } - willo->_state = 7; - animData = (willo->_sprite)._animState._animData; - if (animData != GHIDRA_CAST(0x0)) { - curAnimName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - curAnimName = *GHIDRA_CAST(animData); - } - targetAnimName = "UnderwaterAttack"; - do { - bVar1 = *curAnimName; - bVar3 = bVar1 < (uint8_t)*targetAnimName; - if (bVar1 != *targetAnimName) { -LAB_005590d0: - flagsHigh = -GHIDRA_UINT(bVar3) | 1; - goto LAB_005590d5; - } - if (bVar1 == 0) break; - bVar1 = curAnimName[1]; - bVar3 = bVar1 < (uint8_t)targetAnimName[1]; - if (bVar1 != targetAnimName[1]) goto LAB_005590d0; - curAnimName = curAnimName + 2; - targetAnimName = targetAnimName + 2; - } while (bVar1 != 0); - flagsHigh = 0; -LAB_005590d5: - if ((flagsHigh == 0) && ((animData[0x34] == 0 || ((willo->_sprite)._animState._isPlaying != 0)))) - goto LAB_00559108; - } - bVar1 = ANM2::SetAnimation(&willo->_sprite,GHIDRA_CAST("UnderwaterAttack"),1); - if (bVar1 != 0) { - AnimationState::Rewind(&(willo->_sprite)._animState); - (willo->_sprite)._animState._isPlaying = 1; - } -LAB_00559108: - (willo->_targetPosition).x = spawnPos->x; - (willo->_targetPosition).y = spawnPos->y; - willo->_projectileDelay = 0; - return willo; -} - // 0055a850 void NpcHelper::bubbles_death_geyser_tick(Entity *owner) { @@ -8397,60 +6520,6 @@ void NpcHelper::rainmaker_drop_timer_launch(Entity_Effect *timer) return; } -// 00579770 -int NpcHelper::ReapCreep_CountOtherEnemies() -{ - void *pvVar1; - int iVar2; - int bossCount; - int enemyCount; - - pvVar1 = g_game->_room; - iVar2 = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x12c8)) + *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x12cc)); - enemyCount = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x12c4)) + *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x12c0)); - bossCount = 0; - if (0 < iVar2) { - bossCount = iVar2; - } - iVar2 = 0; - if (0 < enemyCount) { - iVar2 = enemyCount; - } - return iVar2 - bossCount; -} - -// 005797b0 -Entity_Laser * NpcHelper::ReapCreep_ThinLaser(Entity_NPC *npc, float startAngle, float endAngle, int unused) -{ - Entity_Laser *pEVar1; - uint8_t *rotationSpeed; - Vector spawnPos; - Vector laserOffset; - float savedStartAngle; - float savedEndAngle; - - spawnPos.x = (npc->_pos).x + 0.0; - spawnPos.y = (npc->_pos).y + 4.0; - laserOffset.x = 0.0; - laserOffset.y = -32.0; - savedStartAngle = startAngle; - savedEndAngle = endAngle; - pEVar1 = Entity_Laser::ShootAngle(1,&spawnPos,startAngle,100,&laserOffset,GHIDRA_CAST(npc),0); - if (savedEndAngle <= savedStartAngle) { - rotationSpeed = &DAT_bf800000; - } - else { - rotationSpeed = GHIDRA_CAST(0x3f800000); - } - pEVar1->_isActiveRotating = 1; - pEVar1->_rotationDelay = 0x1e; - pEVar1->_rotationSpd = (float)rotationSpeed; - pEVar1->_renderDepthOffset = 1000.0; - pEVar1->_rotationDegrees = savedEndAngle - savedStartAngle; - (**(code **)(*GHIDRA_CAST(pEVar1) + 0xc))(); - return pEVar1; -} - // 00582f60 void NpcHelper::scourge_whip(Entity_NPC *npc) { @@ -9643,285 +7712,6 @@ void NpcHelper::beast_soul_render(Entity_NPC *npc, Vector *offset) return; } -// 00599950 -int NpcHelper::tuff_twins_spawn_count(Entity_NPC *npc) -{ - int *entityIt; - int count; - int remaining; - int entityType; - - count = 0; - remaining = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x1264)); - if (remaining != 0) { - entityIt = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x125c)); - do { - if (npc->_variant == 2) { - entityType = *GHIDRA_CAST((*entityIt + 0x28)); - if ((entityType == 0xd) || (entityType == 0x3d)) { -LAB_00599996: - count = count + 1; - } - } - else if ((npc->_variant == 3) && (*GHIDRA_CAST((*entityIt + 0x28)) == 0x333)) goto LAB_00599996; - entityIt = entityIt + 1; - remaining = remaining + -1; - } while (remaining != 0); - } - return count; -} - -// 005999b0 -void NpcHelper::tuff_twins_play_anim(Entity_NPC *npc, uint8_t *animName, int unused) -{ - uint8_t bVar1; - uint8_t ****ppppbVar2; - uint32_t grownCapacity; - uint8_t ****newBuffer; - uint8_t *pbVar3; - uint32_t uVar4; - uint8_t ****ptr; - uint8_t ****fullAnim [4]; - uint32_t fullAnimSize; - uint32_t fullAnimCapacity; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - uint8_t ***local_8; - uint32_t oldCapacity; - uint32_t oldSize; - - local_8 = GHIDRA_CAST(0xffffffff); - puStack_c = &LAB_00af32ed; - local_10 = ExceptionList; - local_14 = __security_cookie ^ GHIDRA_UINT((fullAnim + 10)); - ExceptionList = &local_10; - fullAnimSize = 0; - fullAnimCapacity = 0xf; - fullAnim[0] = GHIDRA_CAST(0x0); - pbVar3 = animName; - do { - bVar1 = *pbVar3; - pbVar3 = pbVar3 + 1; - } while (bVar1 != 0); - (GHIDRA_CAST((GHIDRA_CAST(fullAnim))))->msvc::string::assign(animName,GHIDRA_INT(pbVar3) - GHIDRA_INT((animName + 1))); - oldCapacity = fullAnimCapacity; - oldSize = fullAnimSize; - local_8 = GHIDRA_CAST(0x0); - if (npc->_i2 != 0) { - if (fullAnimSize < fullAnimCapacity) { - ppppbVar2 = GHIDRA_CAST(fullAnim); - if (0xf < fullAnimCapacity) { - ppppbVar2 = fullAnim[0]; - } - pbVar3 = GHIDRA_CAST((GHIDRA_INT(ppppbVar2) + fullAnimSize)); - fullAnimSize = fullAnimSize + 1; - pbVar3[0] = 0x42; - pbVar3[1] = 0; - } - else { - if (fullAnimSize == 0x7fffffff) { - /* WARNING: Subroutine does not return */ - msvc::string::_Xlen(); - } - uVar4 = fullAnimSize + 1 | 0xf; - if (uVar4 < 0x80000000) { - if (0x7fffffff - (fullAnimCapacity >> 1) < fullAnimCapacity) { - uVar4 = 0x7fffffff; - } - else { - grownCapacity = (fullAnimCapacity >> 1) + fullAnimCapacity; - if (uVar4 < grownCapacity) { - uVar4 = grownCapacity; - } - } - } - else { - uVar4 = 0x7fffffff; - } - newBuffer = msvc::_Allocate(uVar4 + 1); - ppppbVar2 = fullAnim[0]; - fullAnimSize = oldSize + 1; - pbVar3 = GHIDRA_CAST((GHIDRA_INT(newBuffer) + oldSize + 1)); - fullAnimCapacity = uVar4; - if (oldCapacity < 0x10) { - memcpy(newBuffer,fullAnim,oldSize); - *GHIDRA_CAST((GHIDRA_CAST(newBuffer) + oldSize)) = 0x42; - *pbVar3 = 0; - } - else { - memcpy(newBuffer,fullAnim[0],oldSize); - uVar4 = oldCapacity + 1; - *GHIDRA_CAST((GHIDRA_CAST(newBuffer) + oldSize)) = 0x42; - *pbVar3 = 0; - ptr = ppppbVar2; - if (0xfff < uVar4) { - ptr = GHIDRA_CAST(ppppbVar2[-1]); - uVar4 = oldCapacity + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(ppppbVar2) + (-4 - GHIDRA_INT(ptr))))) goto LAB_00599b4a; - } - operator_delete(ptr,uVar4); - } - fullAnim[0] = newBuffer; - } - } - ppppbVar2 = GHIDRA_CAST(fullAnim); - if (0xf < fullAnimCapacity) { - ppppbVar2 = fullAnim[0]; - } - ANM2::Play(&npc->_sprite,GHIDRA_CAST(ppppbVar2),0); - if (0xf < fullAnimCapacity) { - oldSize = fullAnimCapacity + 1; - ppppbVar2 = fullAnim[0]; - if (0xfff < oldSize) { - ppppbVar2 = GHIDRA_CAST(fullAnim[0][-1]); - oldSize = fullAnimCapacity + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(fullAnim[0]) + (-4 - GHIDRA_INT(ppppbVar2))))) { -LAB_00599b4a: - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(ppppbVar2,oldSize); - } - ExceptionList = local_10; - return; -} - -// 00599f80 -void NpcHelper::tuff_twins_body_attack_anim(Entity_NPC *npc) -{ - uint8_t bVar1; - uint8_t *****pppppbVar2; - int prefixCmp; - uint32_t uVar3; - uint8_t *****pppppbVar4; - int extraout_ECX; - int extraout_ECX_00; - int extraout_ECX_01; - int unused; - char *pcVar5; - uint8_t ****attackAnimEnd; - float dy; - float dx; - double dVar6; - int savedFrame; - uint8_t *****local_2c; - char *local_28; - char *local_24; - char *local_20; - char *local_1c; - char *local_18; - uint32_t local_14; - void *animData; - uint8_t ****attackAnim; - - local_14 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 0x10U; - local_2c = GHIDRA_CAST(0xb624dc); - local_28 = "Body1AttackVert"; - local_24 = "Body2AttackHori"; - local_20 = "Body2AttackVert"; - local_1c = "Body3AttackHori"; - local_18 = "Body3AttackVert"; - dx = *GHIDRA_CAST((npc->_parent + 0x33c)) - (npc->_pos).x; - dy = *GHIDRA_CAST((npc->_parent + 0x340)) - (npc->_pos).y; - if (ABS(dx) <= ABS(dy)) { - uVar3 = GHIDRA_UINT((0.0 <= dy)) * 2 + 1; - } - else { - uVar3 = 2; - if (dx < 0.0) { - uVar3 = 0; - } - } - attackAnim = GHIDRA_CAST((&local_2c)[(uVar3 & 1) + (GHIDRA_UINT(npc->_initSeed) % 3) * 2]); - (npc->_sprite)._flipX = uVar3 == 0; - animData = (npc->_sprite)._animState._animData; - if (animData == (void *)0x0) { - local_18 = GHIDRA_CAST(0xf); - local_2c = GHIDRA_CAST(0x0); - local_1c = GHIDRA_CAST(0x0); - } - else { - (GHIDRA_CAST((GHIDRA_CAST(&local_2c))))->msvc::string::string(animData); - } - pppppbVar2 = local_2c; - attackAnimEnd = attackAnim; - do { - bVar1 = *GHIDRA_CAST(attackAnimEnd); - attackAnimEnd = GHIDRA_CAST((GHIDRA_INT(attackAnimEnd) + 1)); - } while (bVar1 != 0); - pppppbVar4 = GHIDRA_CAST(&local_2c); - if (GHIDRA_CAST(0xf) < local_18) { - pppppbVar4 = local_2c; - } - bVar1 = str_eq(GHIDRA_CAST(pppppbVar4),GHIDRA_UINT(local_1c),GHIDRA_CAST(attackAnim), - GHIDRA_INT(attackAnimEnd) - GHIDRA_INT((GHIDRA_INT(attackAnim) + 1))); - if (GHIDRA_CAST(0xf) < local_18) { - pcVar5 = local_18 + 1; - pppppbVar4 = pppppbVar2; - if (GHIDRA_CAST(0xfff) < pcVar5) { - pppppbVar4 = GHIDRA_CAST(pppppbVar2[-1]); - pcVar5 = local_18 + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(pppppbVar2) + (-4 - GHIDRA_INT(pppppbVar4))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pppppbVar4,GHIDRA_UINT(pcVar5)); - } - if (bVar1 == 0) { - animData = (npc->_sprite)._animState._animData; - if (animData == (void *)0x0) { - local_2c = GHIDRA_CAST(0x0); - local_18 = GHIDRA_CAST(0xf); - local_1c = GHIDRA_CAST(0x0); - } - else { - (GHIDRA_CAST((GHIDRA_CAST(&local_2c))))->msvc::string::string(animData); - } - pppppbVar2 = GHIDRA_CAST(&local_2c); - if (GHIDRA_CAST(0xf) < local_18) { - pppppbVar2 = local_2c; - } - prefixCmp = strncmp(GHIDRA_CAST(pppppbVar2),GHIDRA_CAST(attackAnim),0xb); - unused = extraout_ECX; - if (GHIDRA_CAST(0xf) < local_18) { - pcVar5 = local_18 + 1; - pppppbVar2 = local_2c; - if (GHIDRA_CAST(0xfff) < pcVar5) { - pppppbVar2 = GHIDRA_CAST(local_2c[-1]); - pcVar5 = local_18 + 0x24; - if (GHIDRA_CAST(0x1f) < GHIDRA_CAST((GHIDRA_INT(local_2c) + (-4 - GHIDRA_INT(pppppbVar2))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pppppbVar2,GHIDRA_UINT(pcVar5)); - unused = extraout_ECX_00; - } - if (prefixCmp == 0) { - if ((npc->_sprite)._animState._animData == (void *)0x0) { - savedFrame = -1; - } - else { - dVar6 = floor((double)(npc->_sprite)._animState._animFrame); - savedFrame = GHIDRA_INT(dVar6); - unused = extraout_ECX_01; - } - tuff_twins_play_anim(npc,GHIDRA_CAST(attackAnim),unused); - if ((npc->_sprite)._animState._animData != (void *)0x0) { - AnimationState::SetFrameFloat(&(npc->_sprite)._animState,(float)savedFrame); - return; - } - } - else { - tuff_twins_play_anim(npc,GHIDRA_CAST(attackAnim),unused); - } - } - return; -} - // 0059e2a0 void NpcHelper::UltraGreed_Heal(Entity_NPC *npc, int amount) { @@ -11375,188 +9165,3 @@ LAB_006d1556: *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((npc)) + 0xc)))) = damageEventsBegin; return; } - -// 009bfd40 -float * NpcHelper::hush_fly_shape_build(float *outPath, int shape, float radius) -{ - float fVar1; - uint8_t *puVar2; - uint32_t pointCapacity; - float *pathEnd; - int iVar3; - float fVar4; - float distX; - float pointX; - float pointY; - float pointDistance; - float pointSegmentLength; - float sideCountF; - float angle; - float radiusLocal; - float *outPathLocal; - uint32_t pointIdx; - float circleX; - int sideCount; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - void *savedExceptionList; - - savedExceptionList = ExceptionList; - puStack_20 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - puStack_18 = &LAB_00b0ebd0; - local_1c = ExceptionList; - ExceptionList = &local_1c; - outPath[1] = 0.0; - outPath[2] = 0.0; - outPath[3] = 0.0; - local_14 = 0; - *outPath = 0.0; - if (shape == 0) { - ExceptionList = savedExceptionList; - return outPath; - } - radiusLocal = radius; - outPathLocal = outPath; - if (shape == 6) { - pointCapacity = 0x20; - sideCount = 0x1f; - } - else if (shape == 3) { - sideCount = shape; - pointCapacity = 4; - } - else if (shape == 4) { - sideCount = shape; - pointCapacity = 5; - } - else if (shape == 5) { - sideCount = shape; - pointCapacity = 6; - } - else if (shape == 1) { - sideCount = 10; - pointCapacity = 0xb; - } - else if (shape == 2) { - sideCount = 0xc; - pointCapacity = 0xd; - } - else { - sideCount = GHIDRA_INT(sideCountF); - pointCapacity = GHIDRA_INT(sideCountF) + 1; - puVar2 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - if (pointCapacity == 0) goto LAB_009bfdd2; - if (0xfffffff < pointCapacity) { - /* WARNING: Subroutine does not return */ - msvc::_Xlen(); - } - } - iVar3 = sideCount; - puStack_20 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - FUN_009c00c0(pointCapacity); - sideCountF = (float)iVar3; - puVar2 = puStack_20; -LAB_009bfdd2: - puStack_20 = puVar2; - pointIdx = 0; - if (-1 < GHIDRA_INT(sideCountF)) { - iVar3 = GHIDRA_INT(sideCountF); - sideCountF = (float)GHIDRA_INT(sideCountF); - do { - angle = ((float)GHIDRA_INT(pointIdx) * 6.2831855) / sideCountF; - circleX = cos(angle); - circleX = circleX * radiusLocal; - pointY = sin(angle); - pointY = pointY * radiusLocal; - pointX = circleX; - if (shape == 1) { - if ((pointIdx & 1) != 0) { - pointY = pointY * 0.382; - pointX = circleX * 0.382; - } - } - else if ((shape == 2) && ((pointIdx & 1) != 0)) { - pointX = circleX * 0.577; - pointY = pointY * 0.577; - } - pathEnd = GHIDRA_CAST(outPath[2]); - pointSegmentLength = 0.0; - if (GHIDRA_INT(pathEnd) - GHIDRA_INT(outPath[1]) >> 4 != 0) { - fVar1 = outPathLocal[2]; - fVar4 = pointY - *GHIDRA_CAST((GHIDRA_CAST(fVar1) + -0xc)); - distX = pointX - *GHIDRA_CAST((GHIDRA_CAST(fVar1) + -0x10)); - fVar4 = sqrtf(fVar4 * fVar4 + distX * distX); - *GHIDRA_CAST((GHIDRA_CAST(fVar1) + -4)) = fVar4; - *outPathLocal = fVar4 + *outPathLocal; - pathEnd = GHIDRA_CAST(outPath[2]); - iVar3 = sideCount; - } - pointDistance = *outPathLocal; - if (pathEnd == GHIDRA_CAST(outPath[3])) { - msvc::vector<16byte>::_Emplace_reallocate(pathEnd,&pointX); - } - else { - *pathEnd = pointX; - pathEnd[1] = pointY; - pathEnd[2] = pointDistance; - pathEnd[3] = pointSegmentLength; - outPath[2] = (float)(GHIDRA_INT(outPath[2]) + 0x10); - } - pointIdx = pointIdx + 1; - } while (GHIDRA_INT(pointIdx) <= iVar3); - } - ExceptionList = local_1c; - return outPathLocal; -} - -// 009bffb0 -void NpcHelper::path_point_at(void *path, Vector *outPoint, float share) -{ - float totalLength; - int pointIdx; - float *pointDistanceIt; - int points; - int segment; - int pointCount; - float segmentStart; - float segmentStart; - float totalLength; - - pointIdx = *GHIDRA_CAST((GHIDRA_CAST(path) + 8)); - if (GHIDRA_UINT((pointIdx - *GHIDRA_CAST((GHIDRA_CAST(path) + 4)) >> 4)) < 2) { - KAGE_LogMessage(0x10,GHIDRA_CAST("Path is incomplete")); - pointIdx = *GHIDRA_CAST((GHIDRA_CAST(path) + 8)); - } - segmentStart = fmodf(share,1.0); - points = *GHIDRA_CAST((GHIDRA_CAST(path) + 4)); - segment = 0; - totalLength = *GHIDRA_CAST(path); - pointCount = pointIdx - points >> 4; - pointIdx = 1; - if (1 < pointCount) { - pointDistanceIt = GHIDRA_CAST((points + 0x18)); - do { - if (segmentStart * totalLength < *pointDistanceIt) { - segment = pointIdx + -1; - break; - } - pointIdx = pointIdx + 1; - pointDistanceIt = pointDistanceIt + 4; - } while (pointIdx < pointCount); - } - totalLength = *GHIDRA_CAST((points + 0xc + segment * 0x10)); - segmentStart = *GHIDRA_CAST((points + 8 + segment * 0x10)); - if (totalLength == 0.0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("Start and End parameters cannot be the same!")); - points = *GHIDRA_CAST((GHIDRA_CAST(path) + 4)); - } - totalLength = ((segmentStart * totalLength - segmentStart) - 0.0) / (totalLength - 0.0); - outPoint->x = (*GHIDRA_CAST((points + 0x10 + segment * 0x10)) - *GHIDRA_CAST((points + segment * 0x10))) * - totalLength + *GHIDRA_CAST((points + segment * 0x10)); - outPoint->y = (*GHIDRA_CAST((points + 0x14 + segment * 0x10)) - - *GHIDRA_CAST((points + 4 + segment * 0x10))) * totalLength + - *GHIDRA_CAST((points + 4 + segment * 0x10)); - return; -} diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index cb13f2b..bc83112 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -9223,23 +9223,17 @@ void NetworkManager::receive_packet(uint64_t *sender, void *buffer, int size) { void * NetworkManager::get_peer(void *outPeer, uint64_t *userId) { generated_stub("NetworkManager::get_peer 00a790b0"); } int * NpcHelper::chub_nearest_segment(int *param_1, int param_2) { generated_stub("NpcHelper::chub_nearest_segment 00499a50"); } void NpcHelper::chimera_charge_begin(Entity_NPC *npc, Vector *target, float speed) { generated_stub("NpcHelper::chimera_charge_begin 0049f870"); } -void NpcHelper::chimera_render_child(Entity_NPC *npc, Vector *offset) { generated_stub("NpcHelper::chimera_render_child 004a1000"); } Vector * NpcHelper::colostomia_pick_target(Entity_NPC *npc, Vector *outTarget, uint8_t *isPlayerPos) { generated_stub("NpcHelper::colostomia_pick_target 004a2940"); } void NpcHelper::colostomia_pick_dive_target(Entity_NPC *npc) { generated_stub("NpcHelper::colostomia_pick_dive_target 004a2ce0"); } void NpcHelper::delirium_remove_minions(int type, int variant, Entity *self, Entity *other) { generated_stub("NpcHelper::delirium_remove_minions 004a6240"); } void NpcHelper::delirium_spawn_form_parts(Entity_NPC *npc, float maxHealth) { generated_stub("NpcHelper::delirium_spawn_form_parts 004a8680"); } void NpcHelper::delirium_fire_pattern(Entity_NPC *npc) { generated_stub("NpcHelper::delirium_fire_pattern 004a8b70"); } void NpcHelper::delirium_morph_update(Entity_NPC *npc) { generated_stub("NpcHelper::delirium_morph_update 004a9860"); } -void NpcHelper::gideon_spawn_stairs(Entity_NPC *npc) { generated_stub("NpcHelper::gideon_spawn_stairs 004b0fe0"); } -void NpcHelper::gideon_choose_attack(Entity_NPC *npc) { generated_stub("NpcHelper::gideon_choose_attack 004b1210"); } -void NpcHelper::gideon_spawn_wave() { generated_stub("NpcHelper::gideon_spawn_wave 004b1910"); } -void NpcHelper::gideon_update_death(Entity_NPC *npc) { generated_stub("NpcHelper::gideon_update_death 004b3610"); } Entity * NpcHelper::heretic_spawn_afterimage(Entity_NPC *npc) { generated_stub("NpcHelper::heretic_spawn_afterimage 004b3af0"); } int NpcHelper::heretic_count_out_fires() { generated_stub("NpcHelper::heretic_count_out_fires 004b3ec0"); } void NpcHelper::heretic_choose_attack(Entity_NPC *npc) { generated_stub("NpcHelper::heretic_choose_attack 004b40d0"); } void NpcHelper::hornfel_spawn_doors() { generated_stub("NpcHelper::hornfel_spawn_doors 004b70c0"); } void NpcHelper::hornfel_remove_doors() { generated_stub("NpcHelper::hornfel_remove_doors 004b78f0"); } -void NpcHelper::hornfel_render_minecart(Entity_NPC *npc, ANM2 *minecartSprite, Vector *renderPos) { generated_stub("NpcHelper::hornfel_render_minecart 004b7c30"); } void NpcHelper::hornfel_charge(Entity_NPC *npc) { generated_stub("NpcHelper::hornfel_charge 004b7e30"); } Entity * NpcHelper::hornfel_pick_spawn() { generated_stub("NpcHelper::hornfel_pick_spawn 004b7ee0"); } void NpcHelper::hornfel_minecart(Entity_NPC *npc) { generated_stub("NpcHelper::hornfel_minecart 004b8190"); } @@ -9255,25 +9249,15 @@ void NpcHelper::hornfel_room_controller(Entity_Effect *effect) { generated_stub( uint8_t NpcHelper::horny_boys_pick_position(Entity_NPC *npc) { generated_stub("NpcHelper::horny_boys_pick_position 004bc680"); } Entity * NpcHelper::horny_boys_pull_entity(Entity_NPC *npc, int slot, Vector *targetPos) { generated_stub("NpcHelper::horny_boys_pull_entity 004bc8c0"); } 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::min_min_willo_count(Entity_NPC *minMin, int *outWilloCount, int *outOwnedCount) { generated_stub("NpcHelper::min_min_willo_count 004cf5b0"); } 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"); } void NpcHelper::gutted_fatty_burst_projectiles(Entity *timer) { generated_stub("NpcHelper::gutted_fatty_burst_projectiles 004e0930"); } uint8_t NpcHelper::candler_is_free_cell(Vector *position) { generated_stub("NpcHelper::candler_is_free_cell 004e4870"); } uint8_t NpcHelper::whipper_is_target(Entity_NPC *npc, Entity *entity) { generated_stub("NpcHelper::whipper_is_target 004e50d0"); } -void NpcHelper::ball_and_chain_render_chain(float *param_1) { generated_stub("NpcHelper::ball_and_chain_render_chain 004f5f20"); } void NpcHelper::bouncer_death_gib(Entity_Effect *timer) { generated_stub("NpcHelper::bouncer_death_gib 00501e10"); } void NpcHelper::migraine_timer_spawn(Entity *timer) { generated_stub("NpcHelper::migraine_timer_spawn 00528ec0"); } uint8_t NpcHelper::tarboy_is_creep_near(Entity_NPC *npc, Vector *position) { generated_stub("NpcHelper::tarboy_is_creep_near 005441e0"); } -void NpcHelper::leper_flesh_ai(Entity_NPC *npc) { generated_stub("NpcHelper::leper_flesh_ai 00548720"); } -Vector * NpcHelper::willo_slot(Entity_NPC *npc, Vector *outPos, int slot) { generated_stub("NpcHelper::willo_slot 00557f70"); } -void NpcHelper::willo_get_target_pos(Entity_NPC *npc, Vector *outPos, float *outSpread) { generated_stub("NpcHelper::willo_get_target_pos 00558070"); } -void NpcHelper::willo_orbit(Entity_NPC *npc) { generated_stub("NpcHelper::willo_orbit 005581b0"); } -void NpcHelper::willo_attack(Entity_NPC *npc) { generated_stub("NpcHelper::willo_attack 005583d0"); } -Entity_NPC * NpcHelper::min_min_spawn_willo(Vector *position, Entity_NPC *spawner, float v1X, int subType) { generated_stub("NpcHelper::min_min_spawn_willo 00558fe0"); } void NpcHelper::bubbles_death_geyser_tick(Entity *owner) { generated_stub("NpcHelper::bubbles_death_geyser_tick 0055a850"); } uint8_t NpcHelper::polty_target_set(int gridIndex) { generated_stub("NpcHelper::polty_target_set 0055d070"); } uint8_t NpcHelper::polty_is_target_liftable(Entity_NPC *npc) { generated_stub("NpcHelper::polty_is_target_liftable 0055d0b0"); } @@ -9288,8 +9272,6 @@ void NpcHelper::clutch_render(Entity_NPC *npc, Vector *offset) { generated_stub( void NpcHelper::raglich_pick_target_pos(Entity_NPC *npc, float speed) { generated_stub("NpcHelper::raglich_pick_target_pos 00576090"); } void NpcHelper::raglich_slam_spawn_grid(Entity_NPC *npc) { generated_stub("NpcHelper::raglich_slam_spawn_grid 00576450"); } void NpcHelper::rainmaker_drop_timer_launch(Entity_Effect *timer) { generated_stub("NpcHelper::rainmaker_drop_timer_launch 005785a0"); } -int NpcHelper::ReapCreep_CountOtherEnemies() { generated_stub("NpcHelper::ReapCreep_CountOtherEnemies 00579770"); } -Entity_Laser * NpcHelper::ReapCreep_ThinLaser(Entity_NPC *npc, float startAngle, float endAngle, int unused) { generated_stub("NpcHelper::ReapCreep_ThinLaser 005797b0"); } void NpcHelper::scourge_whip(Entity_NPC *npc) { generated_stub("NpcHelper::scourge_whip 00582f60"); } void NpcHelper::scourge_chain_shoot() { generated_stub("NpcHelper::scourge_chain_shoot 00587480"); } void NpcHelper::singe_explode_at(Entity_NPC *npc, Vector *position) { generated_stub("NpcHelper::singe_explode_at 0058ac10"); } @@ -9299,9 +9281,6 @@ int NpcHelper::siren_charmed_count(Entity_NPC *npc) { generated_stub("NpcHelper: void NpcHelper::siren_pick(Entity_NPC *npc) { generated_stub("NpcHelper::siren_pick 0058e680"); } void NpcHelper::siren_familiar_orbit(Entity_NPC *siren, Entity_Familiar *familiar) { generated_stub("NpcHelper::siren_familiar_orbit 00592050"); } void NpcHelper::beast_soul_render(Entity_NPC *npc, Vector *offset) { generated_stub("NpcHelper::beast_soul_render 00597d00"); } -int NpcHelper::tuff_twins_spawn_count(Entity_NPC *npc) { generated_stub("NpcHelper::tuff_twins_spawn_count 00599950"); } -void NpcHelper::tuff_twins_play_anim(Entity_NPC *npc, uint8_t *animName, int unused) { generated_stub("NpcHelper::tuff_twins_play_anim 005999b0"); } -void NpcHelper::tuff_twins_body_attack_anim(Entity_NPC *npc) { generated_stub("NpcHelper::tuff_twins_body_attack_anim 00599f80"); } void NpcHelper::UltraGreed_Heal(Entity_NPC *npc, int amount) { generated_stub("NpcHelper::UltraGreed_Heal 0059e2a0"); } void NpcHelper::UltraGreed_Smash(Entity_NPC *npc, Vector position) { generated_stub("NpcHelper::UltraGreed_Smash 0059e730"); } void NpcHelper::visage_spawn_particles(Vector *position, Vector *direction) { generated_stub("NpcHelper::visage_spawn_particles 005a7010"); } @@ -9315,8 +9294,6 @@ uint8_t NpcHelper::visage_handle_collision(Entity_NPC *npc, Entity *collider, in Entity * NpcHelper::wormwood_spawn_splash(Entity_NPC *npc) { generated_stub("NpcHelper::wormwood_spawn_splash 005ae140"); } uint8_t NpcHelper::is_target_valid(Entity *target) { generated_stub("NpcHelper::is_target_valid 006be7e0"); } void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) { generated_stub("NpcHelper::fireplace_moveable_update 006d0ec0"); } -float * NpcHelper::hush_fly_shape_build(float *outPath, int shape, float radius) { generated_stub("NpcHelper::hush_fly_shape_build 009bfd40"); } -void NpcHelper::path_point_at(void *path, Vector *outPoint, float share) { generated_stub("NpcHelper::path_point_at 009bffb0"); } void OnlineChat::render(Vector *position, uint8_t isInputLine, uint8_t isCursorVisible, float alpha) { generated_stub("OnlineChat::render 0091d2b0"); } void OnlineChat::destructor() { generated_stub("OnlineChat::destructor 0091db20"); } void OnlineChat::render_all(Vector *pos, uint8_t isFocused) { generated_stub("OnlineChat::render_all 0091e650"); } @@ -9405,92 +9382,6 @@ void TexturePtr::release() { generated_stub("TexturePtr::release 0040c440"); } UmbilicalBabyData::~UmbilicalBabyData() { generated_stub("UmbilicalBabyData::~UmbilicalBabyData 00431790"); } uint32_t UmbilicalBabyData::last_point() { generated_stub("UmbilicalBabyData::last_point 00435590"); } void UserProfile::find_or_create() { generated_stub("UserProfile::find_or_create 00a23ae0"); } -Weapon_Deathmatch::~Weapon_Deathmatch() { generated_stub("Weapon_Deathmatch::~Weapon_Deathmatch 009f3260"); } -void Weapon_Deathmatch::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_Deathmatch::Init 009f34d0"); } -void Weapon_Deathmatch::Update(char param_2) { generated_stub("Weapon_Deathmatch::Update 009f34f0"); } -void Weapon_Deathmatch::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) { generated_stub("Weapon_Deathmatch::Fire 00a031b0"); } -void Weapon_Deathmatch::Reset() { generated_stub("Weapon_Deathmatch::Reset 009f3480"); } -void Weapon_Deathmatch::ClearReferences() { generated_stub("Weapon_Deathmatch::ClearReferences 009f3320"); } -float Weapon_Deathmatch::GetMaxCharge() { generated_stub("Weapon_Deathmatch::GetMaxCharge 00a036b0"); } -long double Weapon_Deathmatch::GetChargeBarAmount() { generated_stub("Weapon_Deathmatch::GetChargeBarAmount 009f4150"); } -void Weapon_Deathmatch::vfunc_8() { generated_stub("Weapon_Deathmatch::vfunc_8 009f3130"); } -uint32_t Weapon_Deathmatch::GetFocusEntity() { generated_stub("Weapon_Deathmatch::GetFocusEntity 009f3140"); } -void Weapon_Deathmatch::vfunc_10() { generated_stub("Weapon_Deathmatch::vfunc_10 009f3140"); } -void Weapon_Deathmatch::guard_check_icall() { generated_stub("Weapon_Deathmatch::guard_check_icall 0040c200"); } -void Weapon_Deathmatch::vfunc_12() { generated_stub("Weapon_Deathmatch::vfunc_12 009f3140"); } -uint8_t Weapon_Deathmatch::CanShutDoors() { generated_stub("Weapon_Deathmatch::CanShutDoors 005ccc00"); } -void Weapon_Deathmatch::vfunc_14() { generated_stub("Weapon_Deathmatch::vfunc_14 005ccc00"); } -void Weapon_Deathmatch::vfunc_15() { generated_stub("Weapon_Deathmatch::vfunc_15 005ccc00"); } -void Weapon_Deathmatch::vfunc_16() { generated_stub("Weapon_Deathmatch::vfunc_16 005ccc00"); } -Weapon_MonstrosLung::~Weapon_MonstrosLung() { generated_stub("Weapon_MonstrosLung::~Weapon_MonstrosLung 009f3260"); } -void Weapon_MonstrosLung::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_MonstrosLung::Init 009f34d0"); } -void Weapon_MonstrosLung::Update(char param_2) { generated_stub("Weapon_MonstrosLung::Update 009f34f0"); } -void Weapon_MonstrosLung::Fire() { generated_stub("Weapon_MonstrosLung::Fire 00a07d50"); } -void Weapon_MonstrosLung::Reset() { generated_stub("Weapon_MonstrosLung::Reset 009f3480"); } -void Weapon_MonstrosLung::ClearReferences() { generated_stub("Weapon_MonstrosLung::ClearReferences 009f3320"); } -float Weapon_MonstrosLung::GetMaxCharge() { generated_stub("Weapon_MonstrosLung::GetMaxCharge 00a08c80"); } -long double Weapon_MonstrosLung::GetChargeBarAmount() { generated_stub("Weapon_MonstrosLung::GetChargeBarAmount 009f4150"); } -void Weapon_MonstrosLung::vfunc_8() { generated_stub("Weapon_MonstrosLung::vfunc_8 009f3130"); } -uint32_t Weapon_MonstrosLung::GetFocusEntity() { generated_stub("Weapon_MonstrosLung::GetFocusEntity 009f3140"); } -uint32_t Weapon_MonstrosLung::GetMainEntity() { generated_stub("Weapon_MonstrosLung::GetMainEntity 009f3140"); } -void Weapon_MonstrosLung::guard_check_icall() { generated_stub("Weapon_MonstrosLung::guard_check_icall 0040c200"); } -uint32_t Weapon_MonstrosLung::GetMarkedTargetVariant() { generated_stub("Weapon_MonstrosLung::GetMarkedTargetVariant 00a08cd0"); } -uint8_t Weapon_MonstrosLung::CanTakeDamageFromTearEffects() { generated_stub("Weapon_MonstrosLung::CanTakeDamageFromTearEffects 00709c30"); } -uint8_t Weapon_MonstrosLung::CanShutDoors() { generated_stub("Weapon_MonstrosLung::CanShutDoors 005ccc00"); } -uint8_t Weapon_MonstrosLung::CanTriggerKidneyStone() { generated_stub("Weapon_MonstrosLung::CanTriggerKidneyStone 005ccc00"); } -uint8_t Weapon_MonstrosLung::CanOverrideForgottenThrow() { generated_stub("Weapon_MonstrosLung::CanOverrideForgottenThrow 005ccc00"); } -void Weapon_MonstrosLung::FireBurst(uint32_t param_1, int param_2) { generated_stub("Weapon_MonstrosLung::FireBurst 00a08700"); } -Weapon_SpiritSword::~Weapon_SpiritSword() { generated_stub("Weapon_SpiritSword::~Weapon_SpiritSword 009f9930"); } -void Weapon_SpiritSword::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_SpiritSword::Init 009f34d0"); } -void Weapon_SpiritSword::Update(char param_2) { generated_stub("Weapon_SpiritSword::Update 009f34f0"); } -void Weapon_SpiritSword::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) { generated_stub("Weapon_SpiritSword::Fire 00a099e0"); } -void Weapon_SpiritSword::Reset() { generated_stub("Weapon_SpiritSword::Reset 00a0a6f0"); } -void Weapon_SpiritSword::ClearReferences() { generated_stub("Weapon_SpiritSword::ClearReferences 00a063b0"); } -long double Weapon_SpiritSword::GetMaxCharge() { generated_stub("Weapon_SpiritSword::GetMaxCharge 00a0a700"); } -long double Weapon_SpiritSword::GetChargeBarAmount() { generated_stub("Weapon_SpiritSword::GetChargeBarAmount 009f4150"); } -void Weapon_SpiritSword::vfunc_8() { generated_stub("Weapon_SpiritSword::vfunc_8 009f3130"); } -uint32_t Weapon_SpiritSword::GetFocusEntity() { generated_stub("Weapon_SpiritSword::GetFocusEntity 009f3140"); } -Entity * Weapon_SpiritSword::GetMainEntity() { generated_stub("Weapon_SpiritSword::GetMainEntity 009f3150"); } -void Weapon_SpiritSword::guard_check_icall() { generated_stub("Weapon_SpiritSword::guard_check_icall 0040c200"); } -void Weapon_SpiritSword::vfunc_12() { generated_stub("Weapon_SpiritSword::vfunc_12 009f3140"); } -uint8_t Weapon_SpiritSword::CanShutDoors() { generated_stub("Weapon_SpiritSword::CanShutDoors 005ccc00"); } -void Weapon_SpiritSword::vfunc_14() { generated_stub("Weapon_SpiritSword::vfunc_14 005ccc00"); } -void Weapon_SpiritSword::vfunc_15() { generated_stub("Weapon_SpiritSword::vfunc_15 005ccc00"); } -void Weapon_SpiritSword::vfunc_16() { generated_stub("Weapon_SpiritSword::vfunc_16 005ccc00"); } -Weapon_UmbilicalWhip::~Weapon_UmbilicalWhip() { generated_stub("Weapon_UmbilicalWhip::~Weapon_UmbilicalWhip 009f9880"); } -void Weapon_UmbilicalWhip::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_UmbilicalWhip::Init 009f34d0"); } -void Weapon_UmbilicalWhip::Update(char param_2) { generated_stub("Weapon_UmbilicalWhip::Update 009f34f0"); } -void Weapon_UmbilicalWhip::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) { generated_stub("Weapon_UmbilicalWhip::Fire 00a0e270"); } -void Weapon_UmbilicalWhip::guard_check_icall() { generated_stub("Weapon_UmbilicalWhip::guard_check_icall 0040c200"); } -void Weapon_UmbilicalWhip::ClearReferences() { generated_stub("Weapon_UmbilicalWhip::ClearReferences 00a063b0"); } -long double Weapon_UmbilicalWhip::GetMaxCharge() { generated_stub("Weapon_UmbilicalWhip::GetMaxCharge 009f3130"); } -void Weapon_UmbilicalWhip::vfunc_7() { generated_stub("Weapon_UmbilicalWhip::vfunc_7 009f3130"); } -void Weapon_UmbilicalWhip::vfunc_8() { generated_stub("Weapon_UmbilicalWhip::vfunc_8 009f3130"); } -uint32_t Weapon_UmbilicalWhip::GetFocusEntity() { generated_stub("Weapon_UmbilicalWhip::GetFocusEntity 009f3140"); } -Entity * Weapon_UmbilicalWhip::GetMainEntity() { generated_stub("Weapon_UmbilicalWhip::GetMainEntity 009f3150"); } -void Weapon_UmbilicalWhip::vfunc_11() { generated_stub("Weapon_UmbilicalWhip::vfunc_11 0040c200"); } -void Weapon_UmbilicalWhip::vfunc_12() { generated_stub("Weapon_UmbilicalWhip::vfunc_12 009f3140"); } -uint8_t Weapon_UmbilicalWhip::CanTakeDamageFromTearEffects() { generated_stub("Weapon_UmbilicalWhip::CanTakeDamageFromTearEffects 00709c30"); } -uint8_t Weapon_UmbilicalWhip::CanShutDoors() { generated_stub("Weapon_UmbilicalWhip::CanShutDoors 005ccc00"); } -void Weapon_UmbilicalWhip::vfunc_15() { generated_stub("Weapon_UmbilicalWhip::vfunc_15 005ccc00"); } -void Weapon_UmbilicalWhip::vfunc_16() { generated_stub("Weapon_UmbilicalWhip::vfunc_16 005ccc00"); } -Weapon_UrnOfSouls::~Weapon_UrnOfSouls() { generated_stub("Weapon_UrnOfSouls::~Weapon_UrnOfSouls 009f97e0"); } -void Weapon_UrnOfSouls::Init(uint32_t param_2, uint32_t param_3) { generated_stub("Weapon_UrnOfSouls::Init 009f34d0"); } -void Weapon_UrnOfSouls::Update(char param_2) { generated_stub("Weapon_UrnOfSouls::Update 009f34f0"); } -void Weapon_UrnOfSouls::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) { generated_stub("Weapon_UrnOfSouls::Fire 00a0e630"); } -void Weapon_UrnOfSouls::Reset() { generated_stub("Weapon_UrnOfSouls::Reset 00a0f410"); } -void Weapon_UrnOfSouls::ClearReferences() { generated_stub("Weapon_UrnOfSouls::ClearReferences 00a0f420"); } -long double Weapon_UrnOfSouls::GetMaxCharge() { generated_stub("Weapon_UrnOfSouls::GetMaxCharge 009f3130"); } -void Weapon_UrnOfSouls::vfunc_7() { generated_stub("Weapon_UrnOfSouls::vfunc_7 009f3130"); } -void Weapon_UrnOfSouls::vfunc_8() { generated_stub("Weapon_UrnOfSouls::vfunc_8 009f3130"); } -uint32_t Weapon_UrnOfSouls::GetFocusEntity() { generated_stub("Weapon_UrnOfSouls::GetFocusEntity 009f3140"); } -Entity * Weapon_UrnOfSouls::GetMainEntity() { generated_stub("Weapon_UrnOfSouls::GetMainEntity 009f3170"); } -void Weapon_UrnOfSouls::guard_check_icall() { generated_stub("Weapon_UrnOfSouls::guard_check_icall 0040c200"); } -void Weapon_UrnOfSouls::vfunc_12() { generated_stub("Weapon_UrnOfSouls::vfunc_12 009f3140"); } -uint8_t Weapon_UrnOfSouls::CanTakeDamageFromTearEffects() { generated_stub("Weapon_UrnOfSouls::CanTakeDamageFromTearEffects 00709c30"); } -uint8_t Weapon_UrnOfSouls::CanShutDoors() { generated_stub("Weapon_UrnOfSouls::CanShutDoors 005ccc00"); } -void Weapon_UrnOfSouls::vfunc_15() { generated_stub("Weapon_UrnOfSouls::vfunc_15 005ccc00"); } -void Weapon_UrnOfSouls::vfunc_16() { generated_stub("Weapon_UrnOfSouls::vfunc_16 005ccc00"); } msvc::exception::~exception() { generated_stub("msvc::exception::~exception 0040ce20"); } char * msvc::exception::FUN_0040d0d0() { generated_stub("msvc::exception::FUN_0040d0d0 0040d0d0"); } luabridge::LuaException::~LuaException() { generated_stub("luabridge::LuaException::~LuaException 0085c210"); } @@ -9951,7 +9842,6 @@ void FUN_00436200(uint32_t param_1) { generated_stub("FUN_00436200 00436200"); } void FUN_00436210(uint32_t param_1) { generated_stub("FUN_00436210 00436210"); } void FUN_00436260() { generated_stub("FUN_00436260 00436260"); } void FUN_00436fb0() { generated_stub("FUN_00436fb0 00436fb0"); } -void FUN_0043d7f0(int param_1) { generated_stub("FUN_0043d7f0 0043d7f0"); } void FamiliarHelper::wisp_mine_crafter_update(Entity_Familiar *wisp) { generated_stub("FamiliarHelper::wisp_mine_crafter_update 0043d850"); } void FUN_0043e990(RNG *param_1) { generated_stub("FUN_0043e990 0043e990"); } void FUN_0043e9f0() { generated_stub("FUN_0043e9f0 0043e9f0"); } @@ -10018,12 +9908,7 @@ void NpcAI::ENTITY_HEADLESS_HORSEMAN(Entity_NPC *npc) { generated_stub("NpcAI::E void NpcAI::ENTITY_DARK_ONE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DARK_ONE 0045d7d0"); } 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_BROWNIE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BROWNIE 0048c3b0"); } -void NpcAI::ENTITY_CORN_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CORN_MINE 0048ee30"); } void NpcAI::ENTITY_FORSAKEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FORSAKEN 0048f110"); } -void NpcAI::ENTITY_RAG_MAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_RAG_MAN 00493200"); } -void NpcAI::ENTITY_RAG_MEGA(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_RAG_MEGA 00495610"); } -void NpcAI::ENTITY_SISTERS_VIS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SISTERS_VIS 00496fb0"); } void FUN_00498f80() { generated_stub("FUN_00498f80 00498f80"); } void _range_to_span(uint32_t *param_1) { generated_stub("_range_to_span 00499270"); } int FUN_00499330() { generated_stub("FUN_00499330 00499330"); } @@ -10065,7 +9950,6 @@ void NpcAI::ENTITY_DOGMA(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA void NpcAI::ENTITY_DOGMA_angel(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA_angel 004ae4d0"); } Vector * NpcAI::ENTITY_DOGMA_angel_baby(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA_angel_baby 004b0200"); } void NpcAI::ENTITY_DOGMA_tv(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOGMA_tv 004b0a30"); } -void NpcAI::ENTITY_GIDEON(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GIDEON 004b1ee0"); } void FUN_004b3950() { generated_stub("FUN_004b3950 004b3950"); } void FUN_004b3d50() { generated_stub("FUN_004b3d50 004b3d50"); } void FUN_004b3f10() { generated_stub("FUN_004b3f10 004b3f10"); } @@ -10086,20 +9970,15 @@ void NpcAI::ENTITY_HORNFEL_DOOR(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY uint32_t FUN_004bc660() { generated_stub("FUN_004bc660 004bc660"); } Entity * FUN_004bcb30(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_004bcb30 004bcb30"); } void NpcAI::ENTITY_HORNY_BOYS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HORNY_BOYS 004bd2a0"); } -void NpcAI::ENTITY_HUSH_BOIL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HUSH_BOIL 004be6f0"); } -void NpcAI::ENTITY_HUSH_FLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HUSH_FLY 004bf310"); } void FUN_004bfd20() { generated_stub("FUN_004bfd20 004bfd20"); } void FUN_004c5850(uint8_t *param_1) { generated_stub("FUN_004c5850 004c5850"); } void FUN_004c5980(float *param_1, Vector *param_2) { generated_stub("FUN_004c5980 004c5980"); } void NpcAI::ENTITY_MATRIARCH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MATRIARCH 004c59d0"); } -void NpcAI::ENTITY_MEGA_SATAN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEGA_SATAN 004c8090"); } -void NpcAI::ENTITY_MEGA_SATAN_hand(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MEGA_SATAN_hand 004cca10"); } void FUN_004cdce0() { generated_stub("FUN_004cdce0 004cdce0"); } uint32_t FUN_004ce0f0() { generated_stub("FUN_004ce0f0 004ce0f0"); } 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 NpcAI::ENTITY_MOMS_HEART_mausoleum_death(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOMS_HEART_mausoleum_death 004d64f0"); } @@ -10125,7 +10004,6 @@ void NpcAI::ENTITY_SPIKEBALL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SP void NpcAI::ENTITY_UNBORN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_UNBORN 004dca90"); } void * NpcAI::ENTITY_GASBAG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GASBAG 004dd7f0"); } void NpcAI::ENTITY_EVIS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EVIS 004df3f0"); } -void FUN_004e07a0(Vector *param_1) { generated_stub("FUN_004e07a0 004e07a0"); } void NpcAI::ENTITY_GUTTED_FATTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GUTTED_FATTY 004e0dd0"); } uint32_t NpcAI::ENTITY_GAPER_L2(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GAPER_L2 004e2b40"); } void NpcAI::ENTITY_CHARGER_L2(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CHARGER_L2 004e38c0"); } @@ -10138,7 +10016,6 @@ void NpcAI::ENTITY_WHIPPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WHIP void NpcAI::ENTITY_GRUDGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GRUDGE 004e6570"); } uint32_t NpcAI::ENTITY_BISHOP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BISHOP 004e7ea0"); } uint8_t * NpcAI::ENTITY_BABY_BEGOTTEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BABY_BEGOTTEN 004e8380"); } -void NpcAI::ENTITY_VIS_FATTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VIS_FATTY 004ea3d0"); } void NpcAI::ENTITY_EXORCIST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EXORCIST 004ec240"); } void NpcAI::ENTITY_REVENANT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_REVENANT 004ecc10"); } void NpcAI::ENTITY_CULTIST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CULTIST 004ed840"); } @@ -10157,7 +10034,6 @@ uint32_t FUN_004f88e0() { generated_stub("FUN_004f88e0 004f88e0"); } uint32_t FUN_004f8930() { generated_stub("FUN_004f8930 004f8930"); } void NpcAI::ENTITY_FACELESS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FACELESS 004faad0"); } void NpcAI::ENTITY_DANNY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DANNY 004fbd10"); } -void NpcAI::ENTITY_MOLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOLE 004fdf80"); } void NpcAI::ENTITY_GYRO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GYRO 004ff620"); } void NpcAI::ENTITY_BOUNCER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOUNCER 00501f30"); } void NpcAI::ENTITY_FLESH_MAIDEN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLESH_MAIDEN 00502980"); } @@ -10171,36 +10047,26 @@ void set_byte_0x101(void *self, uint8_t value) { generated_stub("set_byte_0x101 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"); } long double FUN_00515290(Vector *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00515290 00515290"); } -void NpcAI::ENTITY_SWARMER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SWARMER 00518e20"); } 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_DOPLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOPLE 00525650"); } -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"); } float NpcAI::ENTITY_TARBOY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TARBOY 005442a0"); } void NpcAI::ENTITY_FISTULOID(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FISTULOID 00545f70"); } void npc_distribute_orbit_angles(Entity_NPC *npc) { generated_stub("npc_distribute_orbit_angles 00547040"); } -void NpcAI::ENTITY_GUSH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GUSH 00547330"); } -void NpcAI::ENTITY_LEPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_LEPER 00547b60"); } void NpcAI::ENTITY_MR_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MR_MINE 005492c0"); } 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"); } -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"); } void NpcAI::ENTITY_GENERIC_PROP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GENERIC_PROP 00551d30"); } void NpcAI::ENTITY_SHADY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SHADY 005522d0"); } void NpcAI::ENTITY_BLOOD_PUPPY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLOOD_PUPPY 00552d30"); } void NpcAI::ENTITY_PEEPER_FATTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_PEEPER_FATTY 005562b0"); } -void FUN_005579b0(Vector *param_1) { generated_stub("FUN_005579b0 005579b0"); } void FUN_00557b50(uint32_t param_1) { generated_stub("FUN_00557b50 00557b50"); } void FUN_00557b70(uint8_t *param_1) { generated_stub("FUN_00557b70 00557b70"); } bool FUN_00557bb0(int *param_1) { generated_stub("FUN_00557bb0 00557bb0"); } -void collect_npcs_with_same_parent(Entity_NPC *npc) { generated_stub("collect_npcs_with_same_parent 00557ce0"); } -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"); } Entity_Projectile * NpcAI::ENTITY_BUBBLES(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BUBBLES 0055ad20"); } @@ -10229,7 +10095,6 @@ bool FUN_0056ff60(uint32_t param_1) { generated_stub("FUN_0056ff60 0056ff60"); } void NpcAI::ENTITY_MOTHERS_SHADOW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOTHERS_SHADOW 0056ffa0"); } void FUN_00571170() { generated_stub("FUN_00571170 00571170"); } void FUN_00571230(void *param_1, int param_2) { generated_stub("FUN_00571230 00571230"); } -void NpcAI::ENTITY_POOP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POOP 00571280"); } void FUN_005729a0(int *param_1) { generated_stub("FUN_005729a0 005729a0"); } void FUN_00572c10(int param_1) { generated_stub("FUN_00572c10 00572c10"); } void NpcAI::ENTITY_CLUTCH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CLUTCH 00573030"); } @@ -10239,7 +10104,6 @@ void FUN_005784e0() { generated_stub("FUN_005784e0 005784e0"); } void NpcAI::ENTITY_RAINMAKER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_RAINMAKER 00578a70"); } void FUN_00579700() { generated_stub("FUN_00579700 00579700"); } uint32_t FUN_00579760() { generated_stub("FUN_00579760 00579760"); } -void NpcAI::ENTITY_REAP_CREEP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_REAP_CREEP 00579890"); } void FUN_0057be30(uint32_t param_1) { generated_stub("FUN_0057be30 0057be30"); } void FUN_0057be60(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_0057be60 0057be60"); } void FUN_0057be90(int param_1) { generated_stub("FUN_0057be90 0057be90"); } @@ -10264,7 +10128,6 @@ void NpcAI::ENTITY_SCOURGE_main(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY void FUN_00586b50(float *param_1, float param_2) { generated_stub("FUN_00586b50 00586b50"); } void NpcAI::ENTITY_SCOURGE_projectile_attack(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SCOURGE_projectile_attack 00586c40"); } void NpcAI::ENTITY_SCOURGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SCOURGE 00587aa0"); } -void FUN_00589de0(Vector *param_1) { generated_stub("FUN_00589de0 00589de0"); } uint32_t FUN_0058ab60() { generated_stub("FUN_0058ab60 0058ab60"); } void NpcAI::ENTITY_SINGE_body(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SINGE_body 0058aed0"); } void NpcAI::ENTITY_SINGE_ball(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SINGE_ball 0058d8b0"); } @@ -10281,10 +10144,6 @@ void NpcAI::ENTITY_BEAST_rock_projectile(Entity_NPC *npc) { generated_stub("NpcA void NpcAI::ENTITY_BEAST_soul(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BEAST_soul 005971e0"); } void FUN_00598260(Vector *param_1) { generated_stub("FUN_00598260 00598260"); } uint32_t * FUN_00598290(uint32_t *param_1, uint32_t *param_2) { generated_stub("FUN_00598290 00598290"); } -void NpcAI::ENTITY_TUFF_TWINS_head_anim(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TUFF_TWINS_head_anim 00599b80"); } -void NpcAI::ENTITY_TUFF_TWINS_body_anim(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TUFF_TWINS_body_anim 00599d70"); } -void FUN_0059a200() { generated_stub("FUN_0059a200 0059a200"); } -void NpcAI::ENTITY_TUFF_TWINS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TUFF_TWINS 0059a2d0"); } void NpcAI::ENTITY_TURDLET_segments(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TURDLET_segments 0059c5d0"); } void NpcAI::ENTITY_TURDLET(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TURDLET 0059c830"); } void NpcAI::ENTITY_ULTRA_GREED(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ULTRA_GREED 0059edb0"); } @@ -10424,7 +10283,6 @@ void FUN_005cd8c0(uint8_t param_1) { generated_stub("FUN_005cd8c0 005cd8c0"); } void FUN_005cda90() { generated_stub("FUN_005cda90 005cda90"); } void FUN_005d2300() { generated_stub("FUN_005d2300 005d2300"); } void FUN_005d23a0(uint8_t param_1) { generated_stub("FUN_005d23a0 005d23a0"); } -void FUN_005d4210() { generated_stub("FUN_005d4210 005d4210"); } void FUN_00607540() { generated_stub("FUN_00607540 00607540"); } void room_perimeter_to_position(float *param_1, float *param_2) { generated_stub("room_perimeter_to_position 0060ac70"); } void FUN_0060c350() { generated_stub("FUN_0060c350 0060c350"); } @@ -10590,8 +10448,6 @@ void FUN_00665bf0(uint8_t param_1) { generated_stub("FUN_00665bf0 00665bf0"); } void FUN_00665c00() { generated_stub("FUN_00665c00 00665c00"); } uint8_t FUN_00665cc0() { generated_stub("FUN_00665cc0 00665cc0"); } void FUN_00676bd0() { generated_stub("FUN_00676bd0 00676bd0"); } -int FUN_0067adc0() { generated_stub("FUN_0067adc0 0067adc0"); } -void FUN_0067ae30(int *param_1) { generated_stub("FUN_0067ae30 0067ae30"); } void FUN_0067af30() { generated_stub("FUN_0067af30 0067af30"); } uint32_t FUN_0067d9b0() { generated_stub("FUN_0067d9b0 0067d9b0"); } void FUN_0067dac0(int *param_1) { generated_stub("FUN_0067dac0 0067dac0"); } @@ -10609,7 +10465,6 @@ void FUN_00680060(size_t param_1) { generated_stub("FUN_00680060 00680060"); } void FUN_00682260() { generated_stub("FUN_00682260 00682260"); } void shader_stack_push(int shaderIndex) { generated_stub("shader_stack_push 00682280"); } void FUN_00682350() { generated_stub("FUN_00682350 00682350"); } -float normalize_angle_degrees(float angle) { generated_stub("normalize_angle_degrees 00682740"); } uint32_t checksum_stream(void *stream, int offset, int trailingSize) { generated_stub("checksum_stream 00683580"); } void FUN_00683680() { generated_stub("FUN_00683680 00683680"); } void pop_render_target() { generated_stub("pop_render_target 006836c0"); } @@ -11008,7 +10863,6 @@ int FUN_00759260() { generated_stub("FUN_00759260 00759260"); } void FUN_0075d9f0(uint32_t param_1) { generated_stub("FUN_0075d9f0 0075d9f0"); } uint32_t FUN_0075ef20(ANM2 *param_1, int param_2) { generated_stub("FUN_0075ef20 0075ef20"); } void FUN_00770640(float *param_1) { generated_stub("FUN_00770640 00770640"); } -uint8_t is_trinket_unpickable_id(int trinketId) { generated_stub("is_trinket_unpickable_id 007716c0"); } void FUN_007792f0(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_007792f0 007792f0"); } uint32_t FUN_007826c0() { generated_stub("FUN_007826c0 007826c0"); } void FUN_007829a0() { generated_stub("FUN_007829a0 007829a0"); } @@ -11021,13 +10875,10 @@ uint32_t FUN_007ab0e0() { generated_stub("FUN_007ab0e0 007ab0e0"); } void FUN_007ad610() { generated_stub("FUN_007ad610 007ad610"); } uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2) { generated_stub("FUN_007ad720 007ad720"); } void FUN_007b8c00(int param_1) { generated_stub("FUN_007b8c00 007b8c00"); } -void FUN_007b9a60() { generated_stub("FUN_007b9a60 007b9a60"); } -void FUN_007b9aa0() { generated_stub("FUN_007b9aa0 007b9aa0"); } void FUN_007c2e80() { generated_stub("FUN_007c2e80 007c2e80"); } uint8_t FUN_007c7b10(uint32_t param_1, int param_2) { generated_stub("FUN_007c7b10 007c7b10"); } char FUN_007c9080() { generated_stub("FUN_007c9080 007c9080"); } void FUN_007cb4f0() { generated_stub("FUN_007cb4f0 007cb4f0"); } -uint8_t teleport_to_random_room_of_types(Entity_Player *player, void *roomTypes, uint8_t isPreferUnvisited) { generated_stub("teleport_to_random_room_of_types 007cdf30"); } void FUN_007cf940() { generated_stub("FUN_007cf940 007cf940"); } long double FUN_007cf9a0(float *param_1, KColor *param_2, uint32_t param_3) { generated_stub("FUN_007cf9a0 007cf9a0"); } uint8_t * FUN_007cfa90() { generated_stub("FUN_007cfa90 007cfa90"); } @@ -11039,10 +10890,6 @@ uint32_t FUN_007da770() { generated_stub("FUN_007da770 007da770"); } uint32_t FUN_007dac30() { generated_stub("FUN_007dac30 007dac30"); } void FUN_007dad80() { generated_stub("FUN_007dad80 007dad80"); } int FUN_007dafb0() { generated_stub("FUN_007dafb0 007dafb0"); } -void FUN_007db0a0() { generated_stub("FUN_007db0a0 007db0a0"); } -uint32_t FUN_007db2d0() { generated_stub("FUN_007db2d0 007db2d0"); } -int FUN_007db360() { generated_stub("FUN_007db360 007db360"); } -uint32_t FUN_007dbe70(uint32_t *param_1) { generated_stub("FUN_007dbe70 007dbe70"); } uint32_t _Entity_Player::SpawnTrinketRandomPickup() { generated_stub("_Entity_Player::SpawnTrinketRandomPickup 007dc2d0"); } void FUN_007dc610() { generated_stub("FUN_007dc610 007dc610"); } void FUN_007dc620(uint32_t *param_1) { generated_stub("FUN_007dc620 007dc620"); } @@ -13413,7 +13260,6 @@ void cutscene_render_skip_vote_count(void *cutscene, void *state) { generated_st uint32_t * FUN_00960880(void *param_1, uint32_t *param_2) { generated_stub("FUN_00960880 00960880"); } void FUN_00960bc0() { generated_stub("FUN_00960bc0 00960bc0"); } void FUN_0096d120(int *param_1) { generated_stub("FUN_0096d120 0096d120"); } -uint32_t FUN_0097e7c0() { generated_stub("FUN_0097e7c0 0097e7c0"); } void pressure_plate_kill_enemies_timer_callback(int *param_1) { generated_stub("pressure_plate_kill_enemies_timer_callback 00983f30"); } void FUN_0098b0a0() { generated_stub("FUN_0098b0a0 0098b0a0"); } void FUN_0098b130() { generated_stub("FUN_0098b130 0098b130"); } @@ -13460,13 +13306,6 @@ void FUN_009ba9a0() { generated_stub("FUN_009ba9a0 009ba9a0"); } void FUN_009baa10(char param_1) { generated_stub("FUN_009baa10 009baa10"); } int FUN_009bac00(int param_1) { generated_stub("FUN_009bac00 009bac00"); } void entity_vector_set_flag_410(void *self, uint8_t value) { generated_stub("entity_vector_set_flag_410 009bea10"); } -void FUN_009bfc00() { generated_stub("FUN_009bfc00 009bfc00"); } -void FUN_009bfc20() { generated_stub("FUN_009bfc20 009bfc20"); } -void FUN_009bfc40() { generated_stub("FUN_009bfc40 009bfc40"); } -void FUN_009bfc80() { generated_stub("FUN_009bfc80 009bfc80"); } -void FUN_009bfcd0() { generated_stub("FUN_009bfcd0 009bfcd0"); } -void FUN_009bfd00() { generated_stub("FUN_009bfd00 009bfd00"); } -void FUN_009bfd20() { generated_stub("FUN_009bfd20 009bfd20"); } void FUN_009c00c0(uint32_t param_1) { generated_stub("FUN_009c00c0 009c00c0"); } long double FUN_009c0120() { generated_stub("FUN_009c0120 009c0120"); } void FUN_009c22b0(uint32_t *param_1) { generated_stub("FUN_009c22b0 009c22b0"); } @@ -13612,10 +13451,9 @@ void FUN_009f3c40() { generated_stub("FUN_009f3c40 009f3c40"); } void FUN_009f4130() { generated_stub("FUN_009f4130 009f4130"); } Entity_Player * FUN_009f4fc0() { generated_stub("FUN_009f4fc0 009f4fc0"); } void FUN_009f5810(uint8_t param_1) { generated_stub("FUN_009f5810 009f5810"); } -uint32_t * FUN_009f9080() { generated_stub("FUN_009f9080 009f9080"); } -uint32_t * FUN_009f90f0() { generated_stub("FUN_009f90f0 009f90f0"); } -uint32_t * FUN_009f9170() { generated_stub("FUN_009f9170 009f9170"); } -uint32_t * FUN_009f92d0() { generated_stub("FUN_009f92d0 009f92d0"); } +uint32_t FUN_009f5830() { generated_stub("FUN_009f5830 009f5830"); } +uint32_t FUN_009f5850() { generated_stub("FUN_009f5850 009f5850"); } +uint32_t FUN_009f5870() { generated_stub("FUN_009f5870 009f5870"); } uint32_t * FUN_009f93d0() { generated_stub("FUN_009f93d0 009f93d0"); } uint32_t * FUN_00a06940(void *param_1, uint32_t *param_2) { generated_stub("FUN_00a06940 00a06940"); } void * operator_new(uint32_t size) { generated_stub("operator_new 00a0f4c0"); } diff --git a/generated-src/weapon_deathmatch.cpp b/generated-src/weapon_deathmatch.cpp deleted file mode 100644 index 8493bf1..0000000 --- a/generated-src/weapon_deathmatch.cpp +++ /dev/null @@ -1,177 +0,0 @@ -#include "classes.h" - -// 00a031b0 -void Weapon_Deathmatch::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) -{ - uint8_t bVar1; - Vector *pVVar2; - uint32_t rngResult; - Vector *position; - Entity_Bomb *bomb; - int iVar3; - uint32_t scaleRoll; - int unused; - int unused_00; - long double maxCharge; - float fVar4; - float fVar5; - float fVar6; - float maxCharge; - uint8_t auVar8 [12]; - float fVar9; - uint8_t *charge; - int ownerPlayer; - Vector bombVelocity; - Vector VStack_18; - Vector VStack_10; - - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)) = 0x41a00000; - Weapon::Fire(this,direction,isShooting,isInterpolated); - if (isInterpolated != 0) { - return; - } - ownerPlayer = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (ownerPlayer != 0) { - if (*GHIDRA_CAST((ownerPlayer + 0x28)) == 1) goto LAB_00a03209; - if (*GHIDRA_CAST((ownerPlayer + 0x28)) == 3) { - ownerPlayer = *GHIDRA_CAST((ownerPlayer + 0x410)); - goto LAB_00a03209; - } - } - ownerPlayer = 0; -LAB_00a03209: - fVar9 = 0.001; - if (0.001 <= *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10))) { - fVar9 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)); - } - maxCharge = (long double)this->GetMaxCharge(); - VStack_10.x = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)); - VStack_10.y = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)); - fVar4 = (float)maxCharge; - bVar1 = Weapon::IsAxisAligned(this); - fVar5 = 1.0; - if (bVar1 == 0) { - pVVar2 = Weapon::get_aim_direction(this,&VStack_18,&VStack_10); - maxCharge = pVVar2->x; - fVar6 = pVVar2->y; - fVar5 = sqrtf(maxCharge * maxCharge + fVar6 * fVar6); - if (0.0 < fVar5) { - maxCharge = pVVar2->x * (1.0 / fVar5); - fVar6 = pVVar2->y * (1.0 / fVar5); - } - fVar5 = 1.0; - VStack_10.x = maxCharge; - } - else { - pVVar2 = Vector::ToCardinal(&VStack_18,&VStack_10); - fVar6 = pVVar2->y; - VStack_10.x = pVVar2->x; - } - maxCharge = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)); - VStack_10.y = fVar6; - if (isShooting == 0) { - auVar8 = ZEXT812(0x3a83126f); - if ((*GHIDRA_CAST((GHIDRA_CAST(&(auVar8)) + 0x0))) <= fVar9) { - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar8)) + 0x4))) = (*GHIDRA_CAST((GHIDRA_CAST(&(auVar8)) + 0x4))); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar8)) + 0x0))) = fVar9; - } - fVar9 = (*GHIDRA_CAST((GHIDRA_CAST(&(auVar8)) + 0x0))); - if (fVar9 <= maxCharge) { - Weapon::UpdateHeadChargeAnimation(this,0xe5,2,&VStack_10,-1.0); - if (fVar4 <= *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14))) { - fVar4 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)); - } - if (fVar9 <= fVar4) { - fVar4 = fVar9; - } - unused = 7 - GHIDRA_INT((fVar4 * -0.45)); - iVar3 = 0xb; - if (0xb < unused) { - iVar3 = unused; - } - Weapon::SetBlinkTime(this,iVar3,unused); - pVVar2 = Weapon::get_tear_movement_inheritance(this,&VStack_18,&VStack_10); - bombVelocity.x = pVVar2->x; - fVar9 = pVVar2->y; - VStack_18.x = fVar9; - FUN_009f3c40(); - rngResult = Random(); - fVar4 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - fVar4 = fVar4 + fVar4; - rngResult = Random(); - fVar5 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10; - rngResult = Random(); - fVar6 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 0.6 + 0.4; - maxCharge = cos(fVar4); - bombVelocity.x = (maxCharge * fVar5 * 3.5 + (VStack_10.x * 10.0 + bombVelocity.x) * fVar9) * fVar6 - ; - fVar4 = sin(fVar4); - pVVar2 = &bombVelocity; - bombVelocity.y = (fVar4 * fVar5 * 3.5 + (VStack_10.y * 10.0 + VStack_18.x) * fVar9) * fVar6; - position = Weapon::get_owner_position(this,&VStack_10); - bomb = Weapon::fire_bomb(this,position,pVVar2); - if (ownerPlayer != 0) { - bomb->_fallAcceleration = 0.8; - rngResult = Random(); - bomb->_fallSpeed = - -1.0 - (float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10 * 8.0; - rngResult = Random(); - iVar3 = bomb->_explosionCountdown1 - rngResult % 0xf; - if (iVar3 < 0xf) { - iVar3 = 0xf; - } - bomb->_explosionCountdown1 = iVar3; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((bomb)) + 0x414)))) = iVar3; - } - rngResult = Random(); - scaleRoll = Random(); - bomb->_loadCostumes = 1; - bomb->_explosionDamage = 25.0; - fVar9 = (float)((double)GHIDRA_INT(scaleRoll) + __uint_to_double_fixup[-(GHIDRA_INT(scaleRoll) >> 0x1f)]) * - 2.3283064e-10 * 0.15 + ((float)(rngResult & 1) + 0.0) * 0.2 + 0.4; - bomb->_radiusMultiplier = fVar9 * bomb->_radiusMultiplier; - bomb->_scale = fVar9 * bomb->_scale; - } - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) = 0; - bVar1 = Weapon::IsItemAnimFinished(this,0xe5); - if (bVar1 != 0) { - FUN_009f4fc0(); - return; - } - } - else { - if (fVar4 <= maxCharge) { - charge = &DAT_bf800000; - iVar3 = 1; - } - else { - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) != 0) { - fVar5 = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x39c)); - } - iVar3 = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x14)) = fVar5 + maxCharge; - charge = GHIDRA_CAST((((fVar5 + maxCharge) / fVar4) * 18.0)); - } - Weapon::UpdateHeadChargeAnimation(this,0xe5,iVar3,direction,(float)charge); - Weapon::SetBlinkTime(this,1,unused_00); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)) = direction->x; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)) = direction->y; - } - return; -} - -// 00a036b0 -float Weapon_Deathmatch::GetMaxCharge() -{ - float maxCharge; - - maxCharge = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)); - if (maxCharge < 0.001) { - maxCharge = 0.001; - } - return maxCharge; -} diff --git a/generated-src/weapon_monstros_lung.cpp b/generated-src/weapon_monstros_lung.cpp deleted file mode 100644 index 77c6f61..0000000 --- a/generated-src/weapon_monstros_lung.cpp +++ /dev/null @@ -1,221 +0,0 @@ -#include "classes.h" - -// 00a08700 -void Weapon_MonstrosLung::FireBurst(uint32_t param_1, int param_2) -{ - BitSet128 flags; - uint8_t isHasCollectible; - uint32_t rngResult; - Entity_Bomb *bomb; - int fuseTime; - uint32_t rngResult2; - Entity_Tear *tear; - Weapon *in_ECX; - float *extraout_EDX; - float in_XMM0_Da; - float angle; - float spreadScale; - float velocityX; - float fVar1; - float fVar2; - float in_XMM3_Da; - uint32_t in_stack_ffffff94; - Entity_Player *player; - int shotsLeft; - Vector local_30; - Vector firePos; - uint32_t local_20; - uint32_t uStack_1c; - uint32_t uStack_18; - uint32_t uStack_14; - Entity_Player *owner; - - owner = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x4)))); - if (owner != GHIDRA_CAST(0x0)) { - if (owner->_type == 1) { - firePos.x = (owner->_pos).x; - firePos.y = (owner->_pos).y; - player = owner; - goto LAB_00a08780; - } - if (owner->_type == 3) { - player = *GHIDRA_CAST(&owner->_isControlsEnabled); - firePos.x = (owner->_pos).x; - firePos.y = (owner->_pos).y; - goto LAB_00a08780; - } - } - player = GHIDRA_CAST(0x0); - if (owner == GHIDRA_CAST(0x0)) { - player = GHIDRA_CAST(0x0); - firePos.x = g_vectorZero.x; - firePos.y = g_vectorZero.y; - } - else { - firePos.x = (owner->_pos).x; - firePos.y = (owner->_pos).y; - } -LAB_00a08780: - shotsLeft = param_2; - if (0 < param_2) { - do { - FUN_009f3c40(); - fVar1 = *extraout_EDX; - fVar2 = extraout_EDX[1]; - rngResult = Random(); - angle = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - angle = angle + angle; - rngResult = Random(); - spreadScale = (float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10; - velocityX = cos(angle); - velocityX = velocityX * spreadScale * 3.5 + fVar1 * in_XMM0_Da; - local_30.x = velocityX; - fVar1 = sin(angle); - fVar1 = fVar1 * spreadScale * 3.5 + fVar2 * in_XMM0_Da; - local_30.y = fVar1; - if (player == GHIDRA_CAST(0x0)) { -LAB_00a08a1b: - tear = Weapon::fire_tear(in_ECX,&firePos,&local_30,0,in_stack_ffffff94,in_XMM3_Da,0.0); - if (1 < *GHIDRA_CAST(&g_game->_deathmatchManager)) { - local_20 = GHIDRA_UINT((tear->_tearFlags)._l) | _DAT_00c34b10; - in_stack_ffffff94 = *GHIDRA_CAST((GHIDRA_INT(&(tear->_tearFlags)._l) + 4)) | DAT_00c34b14; - uStack_18 = GHIDRA_UINT((tear->_tearFlags)._h) | _DAT_00c34b18; - uStack_14 = *GHIDRA_CAST((GHIDRA_INT(&(tear->_tearFlags)._h) + 4)) | DAT_00c34b1c; - (*GHIDRA_CAST((GHIDRA_CAST(&(flags._l)) + 0x4))) = in_stack_ffffff94; - (*GHIDRA_CAST((GHIDRA_CAST(&(flags._l)) + 0x0))) = local_20; - (*GHIDRA_CAST((GHIDRA_CAST(&(flags._h)) + 0x0))) = uStack_18; - (*GHIDRA_CAST((GHIDRA_CAST(&(flags._h)) + 0x4))) = uStack_14; - uStack_1c = in_stack_ffffff94; - Entity_Tear::SetTearFlags(tear,flags); - } - if (player != GHIDRA_CAST(0x0)) { - if (0.0 < player->_tearfallaccel) { - rngResult = Random(); - tear->_fallingSpeed = - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 * -10.0 - tear->_fallingSpeed; - } - else { - tear->_fallingAccel = player->_tearfallaccel + 0.5; - in_stack_ffffff94 = 0xa08af7; - isHasCollectible = Entity_Player::HasCollectible(player,0x95,0); - if (isHasCollectible == 0) { - in_stack_ffffff94 = 0xa08b09; - isHasCollectible = Entity_Player::HasCollectible(player,0x213,0); - if (isHasCollectible != 0) goto LAB_00a08b44; - rngResult = Random(); - fVar2 = 5.0; - fVar1 = (float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10 * - 15.0; - } - else { -LAB_00a08b44: - rngResult = Random(); - fVar2 = -5.0; - fVar1 = (float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10 * - 10.0; - } - tear->_fallingSpeed = (fVar2 - fVar1) - player->_tearfallspeed; - } - } - rngResult = Random(); - rngResult2 = Random(); - in_XMM0_Da = (((float)(rngResult & 1) + 0.0) * 0.4 + 0.9 + - (float)((double)GHIDRA_INT(rngResult2) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult2) >> 0x1f)]) * 2.3283064e-10 * - 0.05) * tear->_fScale; - if (in_XMM0_Da <= 0.01) { - in_XMM0_Da = 0.01; - } - tear->_baseScale = in_XMM0_Da; - tear->_fScale = in_XMM0_Da; - Entity_Tear::ResetSpriteScale(tear); - } - else { - in_stack_ffffff94 = 0xa088a7; - isHasCollectible = Entity_Player::HasCollectible(player,0x34,0); - if (isHasCollectible == 0) goto LAB_00a08a1b; - rngResult = Random(); - local_30.y = (float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10 * 0.6 - + 0.4; - local_30.x = velocityX * local_30.y; - local_30.y = fVar1 * local_30.y; - in_stack_ffffff94 = 0xa08915; - bomb = Weapon::fire_bomb(in_ECX,&firePos,&local_30); - bomb->_fallAcceleration = 0.8; - rngResult = Random(); - bomb->_fallSpeed = - -1.0 - (float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10 * 8.0; - rngResult = Random(); - fuseTime = bomb->_explosionCountdown1 - rngResult % 0xf; - if (fuseTime < 0xf) { - fuseTime = 0xf; - } - bomb->_explosionCountdown1 = fuseTime; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((bomb)) + 0x414)))) = fuseTime; - rngResult = Random(); - rngResult2 = Random(); - bomb->_loadCostumes = 1; - fVar1 = (float)((double)GHIDRA_INT(rngResult2) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult2) >> 0x1f)] - ) * 2.3283064e-10 * 0.15 + ((float)(rngResult & 1) + 0.0) * 0.2 + 0.4; - in_XMM0_Da = fVar1 * bomb->_scale; - bomb->_radiusMultiplier = fVar1 * bomb->_radiusMultiplier; - bomb->_scale = in_XMM0_Da; - } - shotsLeft = shotsLeft + -1; - } while (shotsLeft != 0); - } - return; -} - -// 00a08c80 -float Weapon_MonstrosLung::GetMaxCharge() -{ - float baseCharge; - float chargeMultiplier; - - chargeMultiplier = 1.0; - if ((this->_modifiers & 1) != 0) { - chargeMultiplier = 2.5; - } - baseCharge = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))); - if (baseCharge < 0.001) { - baseCharge = 0.001; - } - return baseCharge * chargeMultiplier; -} - -// 00a08cd0 -uint32_t Weapon_MonstrosLung::GetMarkedTargetVariant() -{ - uint8_t isHasItem; - uint32_t targetVariant; - Entity_Player *player; - - player = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))); - if (player != GHIDRA_CAST(0x0)) { - if (player->_type == 1) goto LAB_00a08cf6; - if (player->_type == 3) { - player = *GHIDRA_CAST(&player->_isControlsEnabled); - goto LAB_00a08cf6; - } - } - player = GHIDRA_CAST(0x0); -LAB_00a08cf6: - isHasItem = Entity_Player::HasCollectible(player,0x18a,0); - if (isHasItem == 0) { - return 0; - } - isHasItem = Entity_Player::HasCollectible(player,0x23c,0); - targetVariant = 0x1e; - if (isHasItem != 0) { - targetVariant = 0x99; - } - return targetVariant; -} diff --git a/generated-src/weapon_spirit_sword.cpp b/generated-src/weapon_spirit_sword.cpp deleted file mode 100644 index 72e8a2e..0000000 --- a/generated-src/weapon_spirit_sword.cpp +++ /dev/null @@ -1,592 +0,0 @@ -#include "classes.h" - -// 00a099e0 -void Weapon_SpiritSword::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) -{ - void *maskedFlags = this; - uint8_t bVar1; - uint8_t bVar2; - Vector *clampedScale; - Vector *pVVar3; - int iVar4; - float *clampedCharge; - Entity_Knife *knife; - Vector **ppVVar5; - BitSet128 *maskedFlags; - uint8_t *animName; - Entity *unusedArg; - Entity_Player *extraout_EDX; - Entity_Player *extraout_EDX_00; - Entity_Player *player; - uint32_t uVar6; - void *pvVar7; - float *pfVar8; - float fVar9; - float fVar10; - float nextCharge; - undefined3 in_stack_00000009; - undefined3 in_stack_0000000d; - Entity aEStackY_7ffffc64 [2064887]; - uint32_t uVar11; - uint32_t uVar12; - short *outParams; - short *psVar13; - Entity *player; - short multiShotParams [14]; - char isShootingBackwards; - char isShootingSideways; - uint16_t numRandomDirKnives; - uint8_t knifeFlags [4]; - void *pvStack_60; - Vector VStack_5c; - Vector local_54; - uint8_t flagTest [8]; - Vector local_44; - float minPitch; - float scalePitch; - Vector local_34; - Vector local_2c; - uint32_t swordVariant; - Entity_Player *ownerPlayer; - float speedMultiplier; - float swordScale; - char isMomsKnife; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - Game *game; - Manager *manager; - int *swordKnife; - - local_8 = 0xffffffff; - puStack_c = &LAB_00b108cd; - local_10 = ExceptionList; - ExceptionList = &local_10; - pVVar3 = direction; - local_34.y = (float)maskedFlags; - Weapon::Fire(maskedFlags,direction,isShooting,isInterpolated); - bVar2 = (uint8_t)pVVar3; - local_2c.y = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 4)); - ownerPlayer = GHIDRA_CAST(local_2c.y); - if (GHIDRA_CAST(local_2c.y) == GHIDRA_CAST(0x0)) { - speedMultiplier = 1.0; -LAB_00a09a65: - ownerPlayer = GHIDRA_CAST(0x0); - if (GHIDRA_CAST(local_2c.y) != GHIDRA_CAST(0x0)) { - ownerPlayer = GHIDRA_CAST(0x0); - if ((GHIDRA_CAST(local_2c.y))->_type == 1) goto LAB_00a09a88; - } -LAB_00a09a81: - local_2c.y = 0.0; - } - else { - speedMultiplier = (GHIDRA_CAST(local_2c.y))->_speedMultiplier; - if ((GHIDRA_CAST(local_2c.y))->_type != 1) { - if ((GHIDRA_CAST(local_2c.y))->_type != 3) goto LAB_00a09a65; - ownerPlayer = *GHIDRA_CAST(&(GHIDRA_CAST(local_2c.y))->_isControlsEnabled); - goto LAB_00a09a81; - } - } -LAB_00a09a88: - player = ownerPlayer; - if (ownerPlayer == GHIDRA_CAST(0x0)) { -LAB_00a09aaf: - swordVariant = 10; - isMomsKnife = '\0'; - if (player != GHIDRA_CAST(0x0)) goto LAB_00a09abe; - } - else { - Entity_Player::HasCollectible(ownerPlayer,0x18a,0); - bVar2 = 0xa5; - bVar1 = Entity_Player::HasCollectible(player,0x72,0); - if (bVar1 == 0) goto LAB_00a09aaf; - isMomsKnife = '\x01'; -LAB_00a09abe: - bVar2 = 0xc9; - bVar1 = Entity_Player::HasCollectible(player,0x44,0); - swordVariant = 10; - if (bVar1 != 0) { - swordVariant = 0xb; - } - } - iVar4 = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 4)); - swordScale = 1.0; - if (iVar4 != 0) { - if (GHIDRA_CAST(local_2c.y) == GHIDRA_CAST(0x0)) { - pVVar3 = GHIDRA_CAST((iVar4 + 0xe4)); - clampedScale = &local_34; - if (*GHIDRA_CAST((iVar4 + 0x28)) != 3) { - if (1.0 < pVVar3->x) { - clampedScale = pVVar3; - } - goto LAB_00a09b5e; - } - local_34.x = pVVar3->x * 0.8; - local_2c.x = 0.8; - if (local_34.x <= 0.8) { - clampedScale = &local_2c; - } - } - else { - local_54.x = (GHIDRA_CAST((GHIDRA_INT(local_2c.y) + 0x14f0)))->x; - local_54.y = (GHIDRA_CAST((GHIDRA_INT(local_2c.y) + 0x14f0)))->y; - clampedScale = &local_54; - if (local_54.x <= 1.0) { - clampedScale = &local_34; - } -LAB_00a09b5e: - local_34.x = 1.0; - } - swordScale = clampedScale->x; - } - if (player != GHIDRA_CAST(0x0)) { - bVar2 = TemporaryEffects::HasCollectibleEffect(&player->_temporaryeffects,0x271); - if (bVar2 != 0) { - swordScale = swordScale * 4.0; - } - bVar2 = 0xa6; - bVar1 = Entity_Player::HasCollectible(player,0xa9,0); - if (bVar1 == 0) { - bVar2 = 200; - bVar1 = Entity_Player::HasCollectible(player,0x213,0); - if (bVar1 != 0) { - swordScale = swordScale * 1.5; - } - } - else { - swordScale = swordScale + swordScale; - } - } - minPitch = 0.5; - scalePitch = 1.0 / (swordScale * 0.5 + 0.5); - pfVar8 = &scalePitch; - if (scalePitch <= 0.5) { - pfVar8 = &minPitch; - } - if ((isInterpolated == 0) && (0.0 < *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x48)))) { - *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x48)) = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x48)) - speedMultiplier; - } - if (isShooting == 0) { - *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x4c)) = 0; - } - local_54.y = direction->y; - local_54.x = direction->x; - if (local_54.y == 0.0) { - if (local_54.x == 0.0) { - local_54.x = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x20)); - local_54.y = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x24)); - } - if (((local_54.y == 0.0) && (local_54.x == 0.0)) && - (GHIDRA_CAST(local_2c.y) != GHIDRA_CAST(0x0))) { - switch(*GHIDRA_CAST((GHIDRA_CAST(local_2c.y) + 0x1628))) { - case 0: - local_54.x = (float)&DAT_bf800000; - break; - case 1: - local_54.y = (float)&DAT_bf800000; - break; - case 2: - local_54.x = 1.0; - break; - case 3: - local_54.y = 1.0; - } - } - } - local_2c.x = (float)pfVar8; - bVar1 = Weapon::IsAxisAligned(maskedFlags); - if (bVar1 == 0) { - local_34.x = local_54.y; - } - else { - pVVar3 = Vector::ToCardinal(&VStack_5c,&local_54); - local_54.x = pVVar3->x; - local_34.x = pVVar3->y; - } - direction = GHIDRA_CAST(local_54.x); - local_54.y = local_34.x; - if ((((GHIDRA_CAST(local_2c.y) != GHIDRA_CAST(0x0)) && - (iVar4 = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 4)), iVar4 != 0)) && (*GHIDRA_CAST((iVar4 + 0x28)) == 1)) && - ((0 < *GHIDRA_CAST((iVar4 + 0x145c)) || - ((*GHIDRA_CAST((iVar4 + 0x2c)) == 1 && (*GHIDRA_CAST((iVar4 + 0x1aec)) == 8)))))) { - local_2c.y = (float)GHIDRA_INT(*GHIDRA_CAST((iVar4 + 0x1578))) * 45.0 * 0.017453292; - local_44.y = cos(local_2c.y); - fVar9 = sin(local_2c.y); - local_54.x = local_44.y * (float)direction - fVar9 * local_34.x; - local_54.y = fVar9 * (float)direction + local_44.y * local_34.x; - } - if (isInterpolated != 0) { - ExceptionList = local_10; - return; - } - if ((SUB41(_isShooting,0) != '\0') && (*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0xc)) <= 0.0)) { - swordKnife = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)); - local_2c.y = (float)(GHIDRA_INT(maskedFlags) + 0x44); - if (swordKnife != GHIDRA_CAST(0x0)) { - if (*GHIDRA_CAST((GHIDRA_CAST(swordKnife) + 0x466)) != '\0') goto LAB_00a0a43d; - (**(code **)(*swordKnife + 0x28))(); - } - game = g_game; - if (*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x4c)) == '\0') { - *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0xc)) = 0x3f800000; - *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x14)) = 0; - if (1 < *GHIDRA_CAST(&game->_deathmatchManager)) { - *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0xc)) = 0x41f00000; - } - *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x4c)) = 1; - if ((ownerPlayer == GHIDRA_CAST(0x0)) || - (ownerPlayer->_soulHearts + ownerPlayer->_redHearts < ownerPlayer->_maxHearts)) { - iVar4 = FUN_009f57f0(); - player = GHIDRA_CAST(-iVar4); - uVar12 = 0xa09e81; - FUN_009f5810(player); - _isInterpolated = GHIDRA_CAST((GHIDRA_UINT(_isInterpolated) & 0xffffff)); - player = extraout_EDX_00; - if (extraout_EDX_00 != GHIDRA_CAST(0x0)) goto LAB_00a09e89; - } - else { - _isInterpolated = GHIDRA_CAST(CONCAT13(1,_isInterpolated)); - iVar4 = FUN_009f57f0(); - FUN_009f5810(-iVar4); - player = extraout_EDX; -LAB_00a09e89: - player = GHIDRA_CAST(0x0); - uVar12 = 0xde; - bVar2 = 0x97; - bVar1 = Entity_Player::HasCollectible(player,0xde,0); - if (bVar1 != 0) { - uVar6 = 0; - pvVar7 = g_game->_room; - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar7) + 0x1264)) != 0) { - do { - iVar4 = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvVar7) + 0x125c)) + uVar6 * 4)); - if ((((iVar4 != 0) && (*GHIDRA_CAST((iVar4 + 0x28)) == 2)) && - (*GHIDRA_CAST((iVar4 + 0x2c)) == 0x2f)) && - ((*GHIDRA_CAST((iVar4 + 0x3c8)) == *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 4)) && - (1 < *GHIDRA_CAST((iVar4 + 0x438)))))) { - *GHIDRA_CAST((iVar4 + 0x438)) = 1; - } - uVar6 = uVar6 + 1; - } while (uVar6 < *GHIDRA_CAST((GHIDRA_CAST(pvVar7) + 0x1264))); - pfVar8 = GHIDRA_CAST(local_2c.x); - } - } - } - pVVar3 = direction; - direction = GHIDRA_CAST((GHIDRA_UINT(direction) & 0xffffff)); - if (((*GHIDRA_CAST((GHIDRA_CAST(&(in_stack_0000000d)) + 0x2))) != '\0') && (*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x48)) <= 0.0)) { - _isInterpolated = - GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x10)) + *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x10)))); - local_44.y = 60.0; - direction = GHIDRA_CAST(CONCAT13(1,(int3)pVVar3)); - clampedCharge = GHIDRA_CAST(&isInterpolated); - if (60.0 <= (float)_isInterpolated) { - clampedCharge = &local_44.y; - } - *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x48)) = *clampedCharge; - } - if (*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)) != GHIDRA_CAST(0x0)) { - player = GHIDRA_CAST(0xa09f46); - (**(code **)(**GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)) + 0x28))(); - } - pvStack_60 = (void *)0x0; - VStack_5c.x = 0.0; - VStack_5c.y = 0.0; - local_8 = 0; - local_44.y = (float)Weapon::FireSword(maskedFlags,*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 4)),swordVariant,0.0,1, - bVar2,uVar12,player); - knife = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)); - _isInterpolated = GHIDRA_CAST((GHIDRA_INT(maskedFlags) + 0x44)); - if (knife != GHIDRA_CAST(local_44.y)) { - if (knife != GHIDRA_CAST(0x0)) { - msvc::multiset::erase(&isInterpolated); - } - *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)) = local_44.y; - knife = GHIDRA_CAST(local_44.y); - if (GHIDRA_CAST(local_44.y) != GHIDRA_CAST(0x0)) { - _isInterpolated = GHIDRA_CAST(local_44.y); - msvc::multiset::insert(GHIDRA_CAST((GHIDRA_INT(maskedFlags) + 0x44))); - knife = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)); - } - } - _isInterpolated = knife; - fVar9 = atan2f(local_54.y,local_54.x); - _isInterpolated->_rotation = fVar9 * 57.295776; - if ((*GHIDRA_CAST((GHIDRA_CAST(&(direction)) + 0x3))) != '\0') { - iVar4 = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)); - *GHIDRA_CAST((iVar4 + 0x168)) = *GHIDRA_CAST((iVar4 + 0x168)) | 0x400000; - *GHIDRA_CAST((iVar4 + 0x16c)) = *GHIDRA_CAST((iVar4 + 0x16c)); - } - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)) + 0x4ec)) = 1; - _isInterpolated = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)); - msvc::vector::_Emplace_reallocate(0,&isInterpolated); - outParams = multiShotParams; - uVar11 = 0xa0a02d; - player = unusedArg; - Weapon::GetMultiShotParams(maskedFlags,outParams,GHIDRA_INT(unusedArg)); - if (isShootingBackwards != '\0') { - knife = Weapon::FireSword(maskedFlags,*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)),swordVariant,180.0,0, - (uint8_t)uVar11,GHIDRA_UINT(outParams),player); - player = GHIDRA_CAST(0xa0a061); - _isInterpolated = knife; - fVar9 = atan2f(local_54.y,local_54.x); - knife->_rotation = fVar9 * 57.295776; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((knife)) + 0x4ec)))) = 1; - if (VStack_5c.x == VStack_5c.y) { - player = GHIDRA_CAST(&isInterpolated); - uVar11 = 0xa0a09d; - outParams = GHIDRA_CAST(VStack_5c.x); - msvc::vector::_Emplace_reallocate(VStack_5c.x,player); - } - else { - *GHIDRA_CAST(VStack_5c.x) = _isInterpolated; - VStack_5c.x = (float)(GHIDRA_INT(VStack_5c.x) + 4); - } - } - psVar13 = GHIDRA_CAST(VStack_5c.x); - if (isShootingSideways != '\0') { - _isInterpolated = - Weapon::FireSword(GHIDRA_CAST(local_34.y),*GHIDRA_CAST(local_2c.y),swordVariant,90.0,0, - (uint8_t)uVar11,GHIDRA_UINT(outParams),player); - player = GHIDRA_CAST(0xa0a0d9); - fVar9 = atan2f(local_54.y,local_54.x); - _isInterpolated->_rotation = fVar9 * 57.295776; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((_isInterpolated)) + 0x4ec)))) = 1; - if (psVar13 == GHIDRA_CAST(VStack_5c.y)) { - player = GHIDRA_CAST(&isInterpolated); - uVar11 = 0xa0a112; - msvc::vector::_Emplace_reallocate(psVar13,player); - } - else { - *GHIDRA_CAST(psVar13) = _isInterpolated; - VStack_5c.x = (float)psVar13 + 2; - psVar13 = outParams; - } - outParams = GHIDRA_CAST(VStack_5c.x); - _isInterpolated = - Weapon::FireSword(GHIDRA_CAST(local_34.y),*GHIDRA_CAST(local_2c.y),swordVariant,-90.0,0, - (uint8_t)uVar11,GHIDRA_UINT(psVar13),player); - fVar9 = atan2f(local_54.y,local_54.x); - _isInterpolated->_rotation = fVar9 * 57.295776; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((_isInterpolated)) + 0x4ec)))) = 1; - if (outParams == GHIDRA_CAST(VStack_5c.y)) { - uVar11 = 0xa0a17d; - msvc::vector::_Emplace_reallocate(outParams,&isInterpolated); - } - else { - *GHIDRA_CAST(outParams) = _isInterpolated; - VStack_5c.x = (float)outParams + 2; - outParams = psVar13; - } - } - fVar9 = local_34.y; - direction = GHIDRA_CAST(GHIDRA_UINT(numRandomDirKnives)); - if (direction != GHIDRA_CAST(0x0)) { - do { - psVar13 = GHIDRA_CAST(VStack_5c.x); - player = GHIDRA_CAST(0xa0a197); - uVar12 = Random(); - _isInterpolated = - Weapon::FireSword(GHIDRA_CAST(fVar9),*GHIDRA_CAST((GHIDRA_CAST(fVar9) + 0x44)),swordVariant, - (float)((double)GHIDRA_INT(uVar12) + - __uint_to_double_fixup[-(GHIDRA_INT(uVar12) >> 0x1f)]) * - 2.3283064e-10 * 360.0,0,(uint8_t)uVar11,GHIDRA_UINT(outParams),player); - fVar10 = atan2f(local_54.y,local_54.x); - _isInterpolated->_rotation = fVar10 * 57.295776; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((_isInterpolated)) + 0x4ec)))) = 1; - if (psVar13 == GHIDRA_CAST(VStack_5c.y)) { - uVar11 = 0xa0a21c; - msvc::vector::_Emplace_reallocate(psVar13,&isInterpolated); - } - else { - *GHIDRA_CAST(psVar13) = _isInterpolated; - VStack_5c.x = (float)psVar13 + 2; - psVar13 = outParams; - } - direction = GHIDRA_CAST((GHIDRA_INT(&direction[-1].y) + 3)); - outParams = psVar13; - } while (direction != GHIDRA_CAST(0x0)); - direction = GHIDRA_CAST(0x0); - pfVar8 = GHIDRA_CAST(local_2c.x); - } - _isInterpolated = GHIDRA_CAST(0x0); - fVar9 = swordScale; - if (2 < g_game->_frameCount - *GHIDRA_CAST((*GHIDRA_CAST(local_2c.y) + 0x328))) { - fVar9 = *GHIDRA_CAST((*GHIDRA_CAST(local_2c.y) + 0xe4)); - fVar9 = (swordScale - fVar9) * 0.5 + fVar9; - } - uVar12 = 0; - uVar6 = GHIDRA_INT(VStack_5c.x) - GHIDRA_INT(pvStack_60) >> 2; - if (uVar6 != 0) { - do { - iVar4 = *GHIDRA_CAST((GHIDRA_CAST(pvStack_60) + uVar12 * 4)); - if ((((iVar4 != 0) && (*GHIDRA_CAST((iVar4 + 0x28)) == 8)) && (*GHIDRA_CAST((iVar4 + 0x30)) == 0)) && - ((*GHIDRA_CAST((iVar4 + 0x3bc)) == *GHIDRA_CAST(local_2c.y) || (iVar4 == *GHIDRA_CAST(local_2c.y))))) { - fVar10 = fVar9 * g_vectorOne.y; - *GHIDRA_CAST((iVar4 + 0xe4)) = fVar9 * g_vectorOne.x; - *GHIDRA_CAST((iVar4 + 0xe8)) = fVar10; - } - uVar12 = uVar12 + 1; - } while (uVar12 < uVar6); - uVar12 = 0; - do { - Entity_Knife::SetAttackAnimation(*GHIDRA_CAST((GHIDRA_CAST(pvStack_60) + uVar12 * 4))); - (**(code **)(**GHIDRA_CAST((GHIDRA_CAST(pvStack_60) + uVar12 * 4)) + 0xc))(); - direction = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(pvStack_60) + uVar12 * 4)) + 0x388)); - ppVVar5 = &direction; - if ((float)direction <= (float)_isInterpolated) { - ppVVar5 = GHIDRA_CAST(&isInterpolated); - } - uVar12 = uVar12 + 1; - _isInterpolated = GHIDRA_CAST(*ppVVar5); - } while (uVar12 < uVar6); - pfVar8 = GHIDRA_CAST(local_2c.x); - } - uVar12 = Random(); - manager = g_manager; - direction = GHIDRA_CAST(0xfc); - local_44.y = ((float)((double)GHIDRA_INT(uVar12) + __uint_to_double_fixup[-(GHIDRA_INT(uVar12) >> 0x1f)]) * - 2.3283064e-10 * 0.2 + 1.1) * *pfVar8; - seed_fart_sound_override(GHIDRA_CAST(&direction)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(direction),1.0,1,0,local_44.y,0.0); - if ((20.0 < (float)_isInterpolated) && (1.5 < swordScale)) { - Game::ShakeScreen(g_game,GHIDRA_INT((swordScale * 5.0))); - } - maskedFlags = (void *)local_34.y; - Weapon::TriggerTearEffects(GHIDRA_CAST(local_34.y),&local_54,1); - local_8 = 0xffffffff; - if (pvStack_60 != (void *)0x0) { - uVar12 = GHIDRA_INT(VStack_5c.y) - GHIDRA_INT(pvStack_60) & 0xfffffffc; - pvVar7 = pvStack_60; - if (0xfff < uVar12) { - pvVar7 = *(void **)(GHIDRA_CAST(pvStack_60) + -4); - uVar12 = uVar12 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvStack_60) + (-4 - GHIDRA_INT(pvVar7))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pvVar7,uVar12); - } - } - } -LAB_00a0a43d: - if (*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)) == 0) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(maskedFlags)))) + 0x14)))) = 0; - ExceptionList = local_10; - return; - } - if ((SUB41(_isShooting,0) != '\0') || - (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(maskedFlags)))) + 0x14)))) < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(maskedFlags)))) + 0x10)))) * 4.0)) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)) + 0x466)) = SUB41(_isShooting,0); - iVar4 = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)); - if (*GHIDRA_CAST((iVar4 + 0x466)) == '\0') { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(maskedFlags)))) + 0x14)))) = 0; - } - else { - fVar9 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(maskedFlags)))) + 0x10)))) * 4.0; - if (*GHIDRA_CAST((iVar4 + 0x465)) == '\0') { - nextCharge = speedMultiplier + *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(maskedFlags)))) + 0x14)))); - fVar10 = fVar9; - if (nextCharge <= fVar9) { - fVar10 = nextCharge; - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(maskedFlags)))) + 0x14)))) = fVar10; - *GHIDRA_CAST((iVar4 + 0x4e8)) = fVar9 <= fVar10; - } - else { - *GHIDRA_CAST((iVar4 + 0x4e8)) = fVar9 <= *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(maskedFlags)))) + 0x14)))); - } - } - } - else { - Weapon::GetMultiShotParams(maskedFlags,multiShotParams,GHIDRA_INT(_isShooting)); - Entity_Knife::SpinAttack(*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)),multiShotParams[0],0); - if ((isMomsKnife != '\0') && - (knife = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)), knife != GHIDRA_CAST(0x0))) { - if (ownerPlayer == GHIDRA_CAST(0x0)) { - fVar9 = 260.0; - } - else { - fVar9 = ownerPlayer->_tearrange; - } - knifeFlags = SUB84((knife->_tearFlags)._l,0); - pvStack_60 = *(void **)(GHIDRA_INT(&(knife->_tearFlags)._l) + 4); - VStack_5c.x = *GHIDRA_CAST(&(knife->_tearFlags)._h); - VStack_5c.y = *GHIDRA_CAST((GHIDRA_INT(&(knife->_tearFlags)._h) + 4)); - fVar9 = fVar9 * 0.6; - fVar10 = 300.0; - maskedFlags = BitSet128::operator_and - (GHIDRA_CAST(flagTest),GHIDRA_CAST(knifeFlags),&g_tearFlagOrbit); - bVar2 = (GHIDRA_CAST((maskedFlags)))->BitSet128::IsNonZero(); - if (bVar2 != 0) { - fVar10 = 100000.0; - } - if (fVar10 <= fVar9) { - fVar9 = fVar10; - } - Entity_Knife::Shoot(knife,1.0,fVar9); - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(((GHIDRA_CAST(maskedFlags)))) + 0x14)))) = 0; - Weapon::TriggerTearEffects(maskedFlags,&local_54,6); - } - animName = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)) + 0x7c)); - if (animName == GHIDRA_CAST(0x0)) { - animName = &s_empty; - } - else if (0xf < *GHIDRA_CAST((animName + 0x14))) { - animName = *GHIDRA_CAST(animName); - } - iVar4 = strncmp(GHIDRA_CAST(animName),"Spin",4); - if (iVar4 == 0) { - Entity::GetNullOffset(*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)),&local_44,&DAT_00b1d3b0); - fVar9 = local_44.y; - if (ABS(local_44.y) < ABS(local_44.x)) { - iVar4 = 2; - if (local_44.x < 0.0) { - iVar4 = 0; - } - goto LAB_00a0a674; - } - } - else { - _isShooting = (float)(*GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)))[1]._type * 0.017453292; - _isInterpolated = GHIDRA_CAST(cos(_isShooting)); - fVar9 = sin(_isShooting); - if (ABS(fVar9) < ABS((float)_isInterpolated)) { - iVar4 = 2; - if ((float)_isInterpolated < 0.0) { - iVar4 = 0; - } - goto LAB_00a0a674; - } - } - iVar4 = GHIDRA_UINT((0.0 <= fVar9)) * 2 + 1; -LAB_00a0a674: - Weapon::set_head_direction(maskedFlags,iVar4); - Weapon::SetHeadLockTime(maskedFlags,1); - swordKnife = *GHIDRA_CAST((GHIDRA_CAST(maskedFlags) + 0x44)); - if ((((char)swordKnife[0x119] == '\0') && (*GHIDRA_CAST((GHIDRA_CAST(swordKnife) + 0x465)) == '\0')) && - (*GHIDRA_CAST((GHIDRA_CAST(swordKnife) + 0x466)) == '\0')) { - (**(code **)(*swordKnife + 0x28))(); - ExceptionList = local_10; - return; - } - ExceptionList = local_10; - return; -} - -// 00a0a6f0 -void Weapon_SpiritSword::Reset() -{ - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) = 0; - return; -} - -// 00a0a700 -long double Weapon_SpiritSword::GetMaxCharge() -{ - int in_ECX; - - return (long double)*GHIDRA_CAST((in_ECX + 0x10)) * (long double)4.0; -} diff --git a/generated-src/weapon_umbilical_whip.cpp b/generated-src/weapon_umbilical_whip.cpp deleted file mode 100644 index a7020d5..0000000 --- a/generated-src/weapon_umbilical_whip.cpp +++ /dev/null @@ -1,144 +0,0 @@ -#include "classes.h" - -// 00a0e270 -void Weapon_UmbilicalWhip::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) -{ - uint8_t isAxisAligned; - Vector *vecResult; - uint32_t seed; - int *whip; - int *extraout_ECX; - int *unused; - Entity *whipEntity; - float fVar1; - float ownerY; - Entity_Player *local_2c; - Vector VStack_28; - Vector VStack_20; - Vector aimDirection; - Vector scratchVec; - uint32_t flagsHigh; - Manager *manager; - int owner; - - Weapon::Fire(this,direction,isShooting,isInterpolated); - local_2c = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (local_2c == GHIDRA_CAST(0x0)) { -LAB_00a0e2c3: - local_2c = GHIDRA_CAST(0x0); - } - else { - if (local_2c->_type != 1) { - if (local_2c->_type != 3) goto LAB_00a0e2c3; - local_2c = *GHIDRA_CAST(&local_2c->_isControlsEnabled); - if (local_2c == GHIDRA_CAST(0x0)) goto LAB_00a0e2cb; - } - Entity_Player::HasCollectible(local_2c,0x18a,0); - } -LAB_00a0e2cb: - whip = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)); - owner = 0; - if (whip != GHIDRA_CAST(0x0)) { - owner = (*GHIDRA_CAST((GHIDRA_CAST(whip) + 0x171)) != '\0') + 1; - } - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x1c)) = owner; - if ((isShooting != 0) && - (*GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) <= 0.0 && *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) != 0.0)) { - if (isInterpolated != 0) { - return; - } - unused = whip; - if ((whip != GHIDRA_CAST(0x0)) && (whip[0x362] == 1)) { - (**(code **)(*whip + 0x28))(); - whip = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)); - unused = extraout_ECX; - } - if (whip == GHIDRA_CAST(0x0)) { - fVar1 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x10)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0xc)) = fVar1 + fVar1; - Weapon::SetBlinkTime(this,7 - GHIDRA_INT((fVar1 * -0.45)),GHIDRA_INT(unused)); - aimDirection.x = direction->x; - aimDirection.y = direction->y; - isAxisAligned = Weapon::IsAxisAligned(this); - if (isAxisAligned == 0) { - (GHIDRA_CAST((&aimDirection)))->Vector::Normalize(); - } - else { - vecResult = Vector::ToCardinal(&VStack_20,&aimDirection); - aimDirection.x = vecResult->x; - aimDirection.y = vecResult->y; - } - VStack_28.x = aimDirection.x * 10.0; - VStack_20.x = aimDirection.y * 10.0; - vecResult = Weapon::get_tear_movement_inheritance(this,&scratchVec,&aimDirection); - VStack_28.x = vecResult->x * 0.4 + VStack_28.x; - VStack_28.y = vecResult->y * 0.4 + VStack_20.x; - vecResult = (GHIDRA_CAST((&VStack_28)))->Vector::Normalized(&scratchVec); - aimDirection.x = vecResult->x; - aimDirection.y = vecResult->y; - seed = Random(); - vecResult = Weapon::get_owner_position(this,&scratchVec); - VStack_28.x = (float)Game::SpawnEx(g_game,3,0xf0,vecResult,&g_vectorZero,GHIDRA_CAST(local_2c),0, - seed,0); - whipEntity = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)); - whip = GHIDRA_CAST((GHIDRA_INT(this) + 0x44)); - if (whipEntity != GHIDRA_CAST(VStack_28.x)) { - if (whipEntity != GHIDRA_CAST(0x0)) { - VStack_20.x = (float)whip; - msvc::multiset::erase(&VStack_20); - } - *whip = GHIDRA_INT(VStack_28.x); - whipEntity = GHIDRA_CAST(0x0); - if (GHIDRA_CAST(VStack_28.x) != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(whip); - whipEntity = GHIDRA_CAST(*whip); - } - } - flagsHigh = *GHIDRA_CAST((GHIDRA_INT(&whipEntity->_flags) + 4)); - *GHIDRA_CAST(&whipEntity->_flags) = GHIDRA_UINT(whipEntity->_flags) & 0xfffffffb; - *GHIDRA_CAST((GHIDRA_INT(&whipEntity->_flags) + 4)) = flagsHigh; - vecResult = (GHIDRA_CAST((&aimDirection)))->Vector::Normalized(&scratchVec); - fVar1 = vecResult->y; - owner = *whip; - *GHIDRA_CAST((owner + 0x334)) = vecResult->x; - *GHIDRA_CAST((owner + 0x338)) = fVar1; - (**(code **)(*GHIDRA_CAST(*whip) + 0xc))(); - manager = g_manager; - local_2c = GHIDRA_CAST(0x1ee); - seed_fart_sound_override(GHIDRA_CAST(&local_2c)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_2c),1.0,2,0,1.0,0.0); - Weapon::TriggerTearEffects(this,&aimDirection,1); - whip = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)); - } - } - if (whip == GHIDRA_CAST(0x0)) { - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x3c)) = g_vectorZero.x; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x40)) = g_vectorZero.y; - } - else { - owner = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (owner == 0) { - fVar1 = g_vectorZero.x; - ownerY = g_vectorZero.y; - } - else { - fVar1 = *GHIDRA_CAST((owner + 0x33c)); - ownerY = *GHIDRA_CAST((owner + 0x340)); - } - local_2c = GHIDRA_CAST(((float)whip[0xcf] - fVar1)); - VStack_28.x = (float)whip[0xd0] - ownerY; - fVar1 = sqrtf((float)local_2c * (float)local_2c + VStack_28.x * VStack_28.x); - if (fVar1 <= 0.0) { - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x3c)) = local_2c; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x40)) = VStack_28.x; - } - else { - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x3c)) = (float)local_2c * (1.0 / fVar1); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x40)) = VStack_28.x * (1.0 / fVar1); - } - } - if ((isShooting == 0) && (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) != 0)) { - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) + 0xd88)) = 1; - } - return; -} diff --git a/generated-src/weapon_urn_of_souls.cpp b/generated-src/weapon_urn_of_souls.cpp deleted file mode 100644 index d547f07..0000000 --- a/generated-src/weapon_urn_of_souls.cpp +++ /dev/null @@ -1,526 +0,0 @@ -#include "classes.h" - -// 009f3170 -Entity * Weapon_UrnOfSouls::GetMainEntity() -{ - return *GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)); -} - -// 00a0e630 -void Weapon_UrnOfSouls::Fire(Vector *direction, uint8_t isShooting, uint8_t isInterpolated) -{ - Entity_Laser *pEVar1; - Entity_Player *pEVar2; - Entity *spawner; - uint8_t auVar3 [16]; - uint8_t auVar4 [16]; - uint8_t bVar5; - Vector *pVVar6; - uint32_t rngValue; - Entity_Player *ownerPlayer; - Entity_Tear *pEVar7; - Entity_Laser *laser; - int *extraout_EDX; - float twinDx; - float twinDx; - float twinDy; - uint8_t *puVar9; - uint8_t *aimX; - float fVar10; - uint8_t auVar11 [16]; - uint8_t auVar12 [16]; - Entity_Tear *local_90; - Entity_Tear *local_8c; - Vector aimDir; - uint8_t *local_80; - Entity_Player *player; - Vector ownerPos; - Vector local_70; - Vector VStack_68; - Entity_Laser *pEStack_60; - uint32_t uStack_5c; - uint32_t uStack_58; - uint32_t uStack_54; - Vector local_48; - ColorMod soulColor; - Entity_NPC *flameLaser; - Manager *manager; - int ownerEntity; - Entity_Tear *soulTear; - BitSet128 temp_7df6acc38b0; - int *urnEffect; - uint32_t urnPosY; - int urnState; - - local_90 = GHIDRA_CAST(direction); - Weapon::Fire(this,direction,isShooting,isInterpolated); - pEVar2 = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - player = pEVar2; - if (pEVar2 == GHIDRA_CAST(0x0)) { -LAB_00a0e69d: - ownerPlayer = GHIDRA_CAST(0x0); - if ((pEVar2 == GHIDRA_CAST(0x0)) || (pEVar2->_type != 1)) { -LAB_00a0e6af: - player = GHIDRA_CAST(0x0); - if (pEVar2 == GHIDRA_CAST(0x0)) { - local_48.x = 1.0; - player = GHIDRA_CAST(0x0); - goto LAB_00a0e6d5; - } - } - local_48.x = pEVar2->_speedMultiplier; - } - else { - if (pEVar2->_type != 1) { - if (pEVar2->_type != 3) goto LAB_00a0e69d; - ownerPlayer = *GHIDRA_CAST(&pEVar2->_isControlsEnabled); - goto LAB_00a0e6af; - } - local_48.x = pEVar2->_speedMultiplier; - ownerPlayer = pEVar2; - } -LAB_00a0e6d5: - pEVar2 = player; - if (ownerPlayer != GHIDRA_CAST(0x0)) { - Entity_Player::HasCollectible(ownerPlayer,0x18a,0); - } - ownerPlayer = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - local_70.x = *GHIDRA_CAST(local_90); - local_80 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_90)) + 0x4)))); - if ((local_70.x == g_vectorZero.x) && ((float)local_80 == g_vectorZero.y)) { - local_70.x = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)); - local_80 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)); - } - aimDir.x = local_70.x; - aimDir.y = (float)local_80; - if ((local_70.x == g_vectorZero.x) && ((float)local_80 == g_vectorZero.y)) { - puVar9 = local_80; - aimX = GHIDRA_CAST(local_70.x); - if (pEVar2 == GHIDRA_CAST(0x0)) { - if (ownerPlayer->_type == 3) { - switch(ownerPlayer->_chargeBarSprites[5]._scale.x) { - case 0.0: - goto LAB_00a0e785; - case 1.4013e-45: - goto LAB_00a0e7a6; - case 2.8026e-45: - goto LAB_00a0e798; - case 4.2039e-45: - goto LAB_00a0e7ce; - } - } - } - else { - switch(pEVar2->_headDirection) { - case 0: -LAB_00a0e785: - aimX = &DAT_bf800000; - aimDir.x = (float)&DAT_bf800000; - break; - case 1: -LAB_00a0e7a6: - aimDir.y = (float)&DAT_bf800000; - puVar9 = &DAT_bf800000; - break; - case 2: -LAB_00a0e798: - aimDir.x = 1.0; - aimX = GHIDRA_CAST(0x3f800000); - break; - case 3: -LAB_00a0e7ce: - aimDir.y = 1.0; - puVar9 = GHIDRA_CAST(0x3f800000); - } - } - } - else { - twinDx = sqrtf(local_70.x * local_70.x + (float)local_80 * (float)local_80); - ownerPlayer = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (twinDx <= 0.0) { - puVar9 = local_80; - aimX = GHIDRA_CAST(local_70.x); - } - else { - aimDir.y = (1.0 / twinDx) * (float)local_80; - aimDir.x = (1.0 / twinDx) * local_70.x; - puVar9 = GHIDRA_CAST(aimDir.y); - aimX = GHIDRA_CAST(aimDir.x); - } - } - local_8c = GHIDRA_CAST(0x0); - if ((ownerPlayer != GHIDRA_CAST(0x0)) && (ownerPlayer->_type == 1)) { - bVar5 = Entity_Player::HasCollectible(ownerPlayer,0x3b,0); - local_8c = GHIDRA_CAST(GHIDRA_UINT((bVar5 != 0))); - puVar9 = GHIDRA_CAST(aimDir.y); - aimX = GHIDRA_CAST(aimDir.x); - } - urnEffect = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)); - soulTear = GHIDRA_CAST((GHIDRA_INT(this) + 0x4c)); - if (((urnEffect == GHIDRA_CAST(0x0)) || - ((GHIDRA_CAST(urnEffect[0xc]) != local_8c && - ((**(code **)(*urnEffect + 0x28))(), puVar9 = GHIDRA_CAST(aimDir.y), - aimX = GHIDRA_CAST(aimDir.x), *GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) == 0)))) && (isInterpolated == 0)) - { - local_90 = GHIDRA_CAST(Random()); - spawner = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - if (spawner == GHIDRA_CAST(0x0)) { - ownerPos.x = g_vectorZero.x; - ownerPos.y = g_vectorZero.y; - } - else { - ownerPos.x = (spawner->_pos).x; - ownerPos.y = (spawner->_pos).y; - } - local_8c = (Entity_Tear *) - Game::SpawnEx(g_game,1000,0xb2,&ownerPos,&g_vectorZero,spawner,GHIDRA_UINT(local_8c), - GHIDRA_UINT(local_90),0); - pEVar7 = *GHIDRA_CAST(soulTear); - if (pEVar7 != local_8c) { - if (pEVar7 != GHIDRA_CAST(0x0)) { - local_90 = soulTear; - msvc::multiset::erase(); - } - *GHIDRA_CAST(soulTear) = local_8c; - pEVar7 = GHIDRA_CAST(0x0); - if (local_8c != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(); - pEVar7 = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)); - } - } - local_70.x = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - local_8c = GHIDRA_CAST(&pEVar7->_parent); - if (*GHIDRA_CAST(local_8c) != 0) { - local_90 = local_8c; - msvc::multiset::erase(); - } - *GHIDRA_CAST(local_8c) = local_70.x; - if (GHIDRA_CAST(local_70.x) != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(); - } - *GHIDRA_CAST((*GHIDRA_CAST(soulTear) + 0x450)) = 0xfffffffc; - ownerEntity = *GHIDRA_CAST(soulTear); - *GHIDRA_CAST((ownerEntity + 0x34c)) = 0; - *GHIDRA_CAST((ownerEntity + 0x350)) = 0xc1700000; - ownerEntity = __RTDynamicCast(*GHIDRA_CAST((GHIDRA_CAST(this) + 4))); - if (((ownerEntity != 0) && (g_manager->_netplayManager != *GHIDRA_CAST((g_manager + 1)))) && - (bVar5 = NetplayManager::IsIdxLocalPlayer - (GHIDRA_CAST(&g_manager->_netplayManager), - *GHIDRA_CAST((ownerEntity + 0x1618))), bVar5 == 0)) { - ownerEntity = *GHIDRA_CAST(soulTear); - soulColor._tint[0] = *GHIDRA_CAST((ownerEntity + 0xf0)); - soulColor._tint[1] = *GHIDRA_CAST((ownerEntity + 0xf4)); - soulColor._tint[2] = *GHIDRA_CAST((ownerEntity + 0xf8)); - fVar10 = *GHIDRA_CAST((ownerEntity + 0xfc)); - soulColor._colorize[0] = *GHIDRA_CAST((ownerEntity + 0x100)); - soulColor._colorize[1] = *GHIDRA_CAST((ownerEntity + 0x104)); - soulColor._colorize[2] = *GHIDRA_CAST((ownerEntity + 0x108)); - soulColor._colorize[3] = *GHIDRA_CAST((ownerEntity + 0x10c)); - twinDx = *GHIDRA_CAST((ownerEntity + 0x110)); - soulColor._offset[1] = *GHIDRA_CAST((ownerEntity + 0x114)); - soulColor._offset[2] = *GHIDRA_CAST((ownerEntity + 0x118)); - soulColor._tint[3] = fVar10; - soulColor._offset[0] = twinDx; - FUN_00925df0(); - soulColor._tint[3] = twinDx * fVar10; - (**(code **)(*extraout_EDX + 0x3c))(&soulColor); - } - twinDx = atan2f(aimDir.y,aimDir.x); - twinDx = twinDx * 57.295776; - if (0.0 < twinDx) { - twinDx = twinDx + 90.0; - } - else { - twinDx = twinDx - 90.0; - } - *GHIDRA_CAST((*GHIDRA_CAST(soulTear) + 0xec)) = twinDx; - (**(code **)(**GHIDRA_CAST(soulTear) + 0xc))(); - puVar9 = GHIDRA_CAST(aimDir.y); - aimX = GHIDRA_CAST(aimDir.x); - } - if (*GHIDRA_CAST(soulTear) == 0) { - return; - } - twinDx = atan2f((float)puVar9,(float)aimX); - *GHIDRA_CAST((*GHIDRA_CAST(soulTear) + 0x474)) = twinDx * 57.295776; - ownerEntity = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x50)); - if (ownerEntity != 0) { - urnPosY = *GHIDRA_CAST((*GHIDRA_CAST(soulTear) + 0x340)); - *GHIDRA_CAST((ownerEntity + 0x33c)) = *GHIDRA_CAST((*GHIDRA_CAST(soulTear) + 0x33c)); - *GHIDRA_CAST((ownerEntity + 0x340)) = urnPosY; - ownerEntity = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x50)); - local_90 = *GHIDRA_CAST((ownerEntity + 0x41c)); - twinDx = LerpAngleDeg((float)local_90,*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) + 0xec)),0.15); - *GHIDRA_CAST((ownerEntity + 0x418)) = twinDx; - *GHIDRA_CAST((ownerEntity + 0x41c)) = twinDx; - *GHIDRA_CAST((ownerEntity + 0x420)) = local_90; - *GHIDRA_CAST((ownerEntity + 0xec)) = twinDx - 90.0; - } - if (isInterpolated != 0) { - return; - } - ownerEntity = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)); - urnState = *GHIDRA_CAST((ownerEntity + 0x450)); - if (urnState < 0) goto LAB_00a0f3a4; - if (((isShooting != 0) && (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) <= 0.0)) && - ((player != GHIDRA_CAST(0x0) && - ((0 < player->_urnSouls || (0 < player->_effectiveSoulCharge)))))) { - if ((urnState == 3) || (urnState == 4)) { - *GHIDRA_CAST((ownerEntity + 0x450)) = 3; - } - else if (urnState == 0) { - *GHIDRA_CAST((ownerEntity + 0x450)) = 1; - Weapon::get_owner_position(this,&ownerPos); - manager = g_manager; - local_8c = GHIDRA_CAST(0x216); - seed_fart_sound_override(GHIDRA_CAST(&local_8c)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_8c),1.6,1,0,1.0,0.0); - } - pEVar2 = player; - ownerEntity = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) + 0x450)); - if ((ownerEntity == 2) || (ownerEntity == 3)) { - if (player->_urnSouls < 1) { - if (0 < player->_effectiveSoulCharge) { - Entity_Player::AddSoulCharge(player,-1); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) = 0x41c80000; - } - } - else { - Entity_Player::AddUrnSouls(player,0xffffffff); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) = 0x41700000; - } - if ((0.0 < *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44))) && - (bVar5 = Entity_Player::HasCollectible(pEVar2,0x248,0), bVar5 != 0)) { - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar11)) + 0x8))) = 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar11)) + 0x4))) = &ownerPos; - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar11)) + 0x0))) = 0xa0ec9d; - pVVar6 = Weapon::get_owner_position(this,&ownerPos); - Entity_Player::AddWisp(pEVar2,0x280,pVVar6,auVar11[8],auVar11[0xc]); - } - } - } - ownerEntity = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)); - urnState = *GHIDRA_CAST((ownerEntity + 0x450)); - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) <= 0.0) { - if ((urnState == 2) || (urnState == 3)) { - Weapon::get_owner_position(this,&ownerPos); - manager = g_manager; - local_90 = GHIDRA_CAST(0x218); - seed_fart_sound_override(GHIDRA_CAST(&local_90)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_90),1.6,1,0,1.0,0.0); - manager = g_manager; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)) = g_vectorZero.x; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)) = g_vectorZero.y; - SFXManager::Stop(&manager->_sfxManager,0x216); - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) + 0x450)) = 4; - } - goto LAB_00a0f3a4; - } - if ((urnState != 2) && (urnState != 3)) goto LAB_00a0f3a4; - twinDx = local_48.x / 90.0 + *GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)); - local_70.x = 1.0; - if (twinDx <= 1.0) { - local_70.x = twinDx; - } - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)) = local_70.x; - Weapon::get_owner_position(this,&ownerPos); - local_90 = GHIDRA_CAST((*GHIDRA_CAST((ownerEntity + 0xec)) * 0.017453292)); - local_8c = GHIDRA_CAST(cos((float)local_90)); - local_90 = GHIDRA_CAST(sin((float)local_90)); - twinDx = local_70.x * 6.0 + 6.0; - local_70.x = twinDx * (float)local_90; - pEStack_60 = GHIDRA_CAST((twinDx * (float)local_8c)); - rngValue = Random(); - VStack_68.x = ((float)((double)GHIDRA_INT(rngValue) + __uint_to_double_fixup[-(GHIDRA_INT(rngValue) >> 0x1f)]) * - 2.3283064e-10 * 16.0 - 8.0) * 0.017453292; - local_80 = GHIDRA_CAST(cos(VStack_68.x)); - twinDx = sin(VStack_68.x); - pEVar2 = player; - ownerEntity = *GHIDRA_CAST((GHIDRA_CAST(this) + 4)); - fVar10 = (float)local_80 * (float)pEStack_60; - local_80 = GHIDRA_CAST(((float)local_80 * local_70.x + twinDx * (float)pEStack_60)); - VStack_68.x = fVar10 - twinDx * local_70.x; - fVar10 = (float)local_8c * -0.4 * local_48.x; - ownerPos.x = (float)local_8c + (float)local_8c + ownerPos.x; - twinDx = (float)local_90 * -0.4 * local_48.x; - ownerPos.y = (float)local_90 + (float)local_90 + ownerPos.y; - *GHIDRA_CAST((ownerEntity + 0x364)) = - *GHIDRA_CAST((ownerEntity + 0x39c)) * twinDx + *GHIDRA_CAST((ownerEntity + 0x364)); - *GHIDRA_CAST((ownerEntity + 0x360)) = - *GHIDRA_CAST((ownerEntity + 0x39c)) * fVar10 + *GHIDRA_CAST((ownerEntity + 0x360)); - if (((player != GHIDRA_CAST(0x0)) && (ownerEntity = player->_twinPlayer, ownerEntity != 0)) && - (twinDx = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x33c)) - *GHIDRA_CAST((ownerEntity + 0x33c)), - twinDy = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 4)) + 0x340)) - *GHIDRA_CAST((ownerEntity + 0x340)), - twinDy * twinDy + twinDx * twinDx < 6400.0)) { - *GHIDRA_CAST((ownerEntity + 0x364)) = - twinDx * *GHIDRA_CAST((ownerEntity + 0x39c)) + *GHIDRA_CAST((ownerEntity + 0x364)); - *GHIDRA_CAST((ownerEntity + 0x360)) = - *GHIDRA_CAST((ownerEntity + 0x39c)) * fVar10 + *GHIDRA_CAST((ownerEntity + 0x360)); - } - VStack_68.y = (float)local_80; - pEStack_60 = GHIDRA_CAST(VStack_68.x); - pVVar6 = Weapon::get_tear_movement_inheritance(this,&local_48,&VStack_68); - VStack_68.x = (float)pEStack_60 + pVVar6->x; - VStack_68.y = (float)local_80 + pVVar6->y; - if (*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) + 0x30)) == 1) { - twinDx = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)); - ownerEntity = _get_index_plus_one_if_kind_4_5(); - pEVar1 = GHIDRA_CAST((GHIDRA_INT(this) + 0x50)); - laser = *GHIDRA_CAST(pEVar1); - local_48.x = ((float)ownerEntity * 0.3 + 2.8) * 1.5 * (twinDx * 0.19999999 + 0.8); - if (laser == GHIDRA_CAST(0x0)) { - ownerEntity = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)); - local_70.x = *GHIDRA_CAST((ownerEntity + 0x33c)); - local_70.y = *GHIDRA_CAST((ownerEntity + 0x340)); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar12)) + 0x8))) = ownerEntity; - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar12)) + 0x4))) = &pEStack_60; - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar12)) + 0xc))) = 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar12)) + 0x0))) = 8; - uStack_5c = 0xc1700000; - pEStack_60 = laser; - twinDx = atan2f((float)local_90,(float)local_8c); - VStack_68.x = (float)Entity_Laser::ShootAngle - (1,&local_70,twinDx * 57.295776,(*GHIDRA_CAST((GHIDRA_CAST(&(auVar12)) + 0x0))),(*GHIDRA_CAST((GHIDRA_CAST(&(auVar12)) + 0x4))), - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar12)) + 0x8))),auVar12[0xc]); - laser = *GHIDRA_CAST(pEVar1); - if (laser != GHIDRA_CAST(VStack_68.x)) { - if (laser != GHIDRA_CAST(0x0)) { - pEStack_60 = pEVar1; - msvc::multiset::erase(); - } - *GHIDRA_CAST(pEVar1) = VStack_68.x; - laser = GHIDRA_CAST(0x0); - if (GHIDRA_CAST(VStack_68.x) != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(); - laser = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x50)); - } - } - laser->_spawnerType = 1; - *GHIDRA_CAST((*GHIDRA_CAST(pEVar1) + 0x38)) = 0; - (**(code **)(**GHIDRA_CAST(pEVar1) + 0x40))(); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar3)) + 0x4))) = (*GHIDRA_CAST((GHIDRA_CAST(&(g_tearFlagShielded._l)) + 0x4))); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar3)) + 0x0))) = GHIDRA_UINT(g_tearFlagShielded._l); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar3)) + 0x8))) = GHIDRA_UINT(g_tearFlagShielded._h); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar3)) + 0xc))) = (*GHIDRA_CAST((GHIDRA_CAST(&(g_tearFlagShielded._h)) + 0x4))); - *(uint8_t (*) [16])(*GHIDRA_CAST(pEVar1) + 0x428) = auVar3; - (**(code **)(**GHIDRA_CAST(pEVar1) + 0xc))(); - laser = *GHIDRA_CAST(pEVar1); - if (laser == GHIDRA_CAST(0x0)) goto LAB_00a0f2ba; - } - (**(code **)(*GHIDRA_CAST(laser) + 0x40))(); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar4)) + 0x4))) = (*GHIDRA_CAST((GHIDRA_CAST(&(g_tearFlagShielded._l)) + 0x4))); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar4)) + 0x0))) = GHIDRA_UINT(g_tearFlagShielded._l); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar4)) + 0x8))) = GHIDRA_UINT(g_tearFlagShielded._h); - (*GHIDRA_CAST((GHIDRA_CAST(&(auVar4)) + 0xc))) = (*GHIDRA_CAST((GHIDRA_CAST(&(g_tearFlagShielded._h)) + 0x4))); - *(uint8_t (*) [16])(*GHIDRA_CAST(pEVar1) + 0x428) = auVar4; - *GHIDRA_CAST((*GHIDRA_CAST(pEVar1) + 0x458)) = 8; - flameLaser = *GHIDRA_CAST(pEVar1); - twinDx = LerpAngleDeg((flameLaser->_pathfinder)._movementTarget.y, - *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) + 0xec)),0.3); - Entity_NPC::SetAimAngle(flameLaser,twinDx); - ownerEntity = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x50)); - twinDx = sin(*GHIDRA_CAST((ownerEntity + 0x41c)) * 0.017453292); - if (twinDx <= -0.5) { - *GHIDRA_CAST((ownerEntity + 0x358)) = 0xc1200000; - } - else { - *GHIDRA_CAST((ownerEntity + 0x358)) = 0x453b8000; - } - } - else { - rngValue = Random(); - local_90 = (Entity_Tear *) - Game::SpawnEx(g_game,2,0x2e,&ownerPos,&VStack_68,GHIDRA_CAST(pEVar2),0,rngValue,0); - VStack_68.x = (float)&local_90->_parent; - if (local_90->_parent != 0) { - pEStack_60 = GHIDRA_CAST(VStack_68.x); - msvc::multiset::erase(); - } - *GHIDRA_CAST(VStack_68.x) = pEVar2; - if (pEVar2 != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(); - } - soulTear = local_90; - Entity_Tear::SetTearFlags(local_90,g_tearFlagPiercing); - soulTear->_tearRange = 160.0; - rngValue = (GHIDRA_CAST((&soulTear->_dropRNG)))->RNG::RandomInt(8); - if (rngValue == 0) { - pEStack_60 = GHIDRA_CAST((GHIDRA_UINT((soulTear->_tearFlags)._l) | GHIDRA_UINT(g_tearFlagShielded._l))); - uStack_5c = *GHIDRA_CAST((GHIDRA_INT(&(soulTear->_tearFlags)._l) + 4)) | (*GHIDRA_CAST((GHIDRA_CAST(&(g_tearFlagShielded._l)) + 0x4))); - uStack_58 = GHIDRA_UINT((soulTear->_tearFlags)._h) | GHIDRA_UINT(g_tearFlagShielded._h); - uStack_54 = *GHIDRA_CAST((GHIDRA_INT(&(soulTear->_tearFlags)._h) + 4)) | (*GHIDRA_CAST((GHIDRA_CAST(&(g_tearFlagShielded._h)) + 0x4))); - (*GHIDRA_CAST((GHIDRA_CAST(&(temp_7df6acc38b0._l)) + 0x4))) = uStack_5c; - (*GHIDRA_CAST((GHIDRA_CAST(&(temp_7df6acc38b0._l)) + 0x0))) = pEStack_60; - (*GHIDRA_CAST((GHIDRA_CAST(&(temp_7df6acc38b0._h)) + 0x0))) = uStack_58; - (*GHIDRA_CAST((GHIDRA_CAST(&(temp_7df6acc38b0._h)) + 0x4))) = uStack_54; - Entity_Tear::SetTearFlags(soulTear,temp_7df6acc38b0); - } - twinDx = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)); - ownerEntity = _get_index_plus_one_if_kind_4_5(); - soulTear->_mass = 0.0; - pEStack_60 = GHIDRA_CAST((((float)ownerEntity * 0.3 + 2.3) * (twinDx * 0.19999999 + 0.8))); - twinDx = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)) * 0.40000004 + 0.7; - if (twinDx <= 0.01) { - twinDx = 0.01; - } - soulTear->_baseScale = twinDx; - soulTear->_fScale = twinDx; - Entity_Tear::ResetSpriteScale(soulTear); - (**(code **)(*GHIDRA_CAST(soulTear) + 0x40))(); - soulTear->_fallingAccel = 0.1; - (**(code **)(*GHIDRA_CAST(soulTear) + 0xc))(); - } -LAB_00a0f2ba: - Game::ShakeScreen(g_game,3); - Weapon::TriggerTearEffects(this,&aimDir,1); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) - 1.0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x20)) = aimDir.x; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x24)) = aimDir.y; -LAB_00a0f3a4: - ownerEntity = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)); - *GHIDRA_CAST((ownerEntity + 0x478)) = *GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)); - urnState = *GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) + 0x450)); - if (((urnState == 2) || (urnState == 3)) || (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x50)) != 0)) { - Weapon::SetBlinkTime(this,4,ownerEntity); - } - return; -} - -// 00a0f410 -void Weapon_UrnOfSouls::Reset() -{ - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x44)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x48)) = 0; - return; -} - -// 00a0f420 -void Weapon_UrnOfSouls::ClearReferences() -{ - int *local_8; - int *entityRef; - - 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) + 0x4c)); - if (*GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) != GHIDRA_CAST(0x0)) { - (**(code **)(**GHIDRA_CAST((GHIDRA_CAST(this) + 0x4c)) + 0x28))(); - if (*entityRef != 0) { - local_8 = entityRef; - msvc::multiset::erase(&local_8); - *entityRef = 0; - } - } - SFXManager::Stop(&g_manager->_sfxManager,0x216); - SFXManager::Stop(&g_manager->_sfxManager,0x217); - return; -} diff --git a/src/active_items.h b/src/active_items.h index cb3ff0a..012e1b1 100644 --- a/src/active_items.h +++ b/src/active_items.h @@ -23,6 +23,15 @@ enum ActiveSlot : int ACTIVE_SLOT_POCKET2 }; +// The kinds of battery (Lua's BatterySubType). +enum BatterySubType : int +{ + BATTERY_NORMAL = 1, + BATTERY_MICRO = 2, + BATTERY_MEGA = 3, + BATTERY_GOLDEN = 4 +}; + // How an active item's effect was triggered (Lua's UseFlag). enum UseFlag : uint32_t { diff --git a/src/boss_ai.h b/src/boss_ai.h index c9a7055..da720e6 100644 --- a/src/boss_ai.h +++ b/src/boss_ai.h @@ -106,6 +106,7 @@ struct FollowingEffect }; Entity_Effect* following_effect_spawn(Entity& parent, const FollowingEffect& effect); +Entity_Player* game_random_player(Game& game, Vector position, float radius); std::string npc_sheet_path_get(Entity_NPC& npc, const std::string& path); bool players_is_falling(); @@ -136,6 +137,9 @@ enum SpawnerQueryMode std::vector npc_query_spawner_type(int spawnerType, int entityType, SpawnerQueryMode mode); +// The Haunt's Lil Haunts, by variant. +constexpr int HAUNT_LIL_VARIANT = 10; + // Isaac's forms, by variant: Isaac in the Cathedral, ??? in the Chest, and the ??? whose death calls Hush. enum IsaacVariant { @@ -180,9 +184,22 @@ void boss_fallen_update(Entity_NPC& npc); void boss_music_crossfade(); void boss_isaac_update(Entity_NPC& npc); void npc_baby_update(Entity_NPC& npc); +void boss_rag_man_update(Entity_NPC& npc); +void boss_rag_mega_update(Entity_NPC& npc); +void boss_sisters_vis_update(Entity_NPC& npc); +void boss_reap_creep_update(Entity_NPC& npc); +void boss_brownie_update(Entity_NPC& npc); +void npc_wrinkly_baby_update(Entity_NPC& npc); void boss_lamb_update(Entity_NPC& npc); void npc_isaac_fly_update(Entity_NPC& npc); void boss_hush_update(Entity_NPC& npc); +void npc_hush_fly_update(Entity_NPC& npc); +void npc_hush_boil_update(Entity_NPC& npc); +void boss_mega_satan_update(Entity_NPC& npc); +void boss_mega_satan_hand_update(Entity_NPC& npc); + +// The fly group Hush keeps as a ring about him. +constexpr int HUSH_FLY_RING_GROUP = 1; // Gemini's baby, the variant its twin is tied to. constexpr int GEMINI_BABY = 10; diff --git a/src/boss_big_horn.cpp b/src/boss_big_horn.cpp new file mode 100644 index 0000000..d1a1483 --- /dev/null +++ b/src/boss_big_horn.cpp @@ -0,0 +1,66 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "room.h" + +// Big Horn's parts, by variant: its head in the big hole, its hand and its bomb ball. +constexpr int BIG_HORN_HAND = 1; +constexpr int BIG_HORN_BALL = 2; + +// Its splash in a flooded room: 12 to 21 drops thrown 3 to 8 fast from about its body, twice as big, rising 4 to 12. +constexpr float SPLASH_WATER_MIN = 0.2f; +constexpr float BIG_HORN_SPLASH_DEPTH = 0.65f; +constexpr int SPLASH_DROPS_MIN = 12; +constexpr int SPLASH_DROPS_RANGE = 10; +constexpr float BIG_HORN_SPLASH_SPEED_MIN = 3; +constexpr float BIG_HORN_SPLASH_SPEED_RANGE = 5; +constexpr int BIG_HORN_SPLASH_DROP_SUBTYPE = 1; +constexpr float SPLASH_DROP_SCALE = 2; +constexpr float SPLASH_RISE_MIN = -4; +constexpr float SPLASH_RISE_RANGE = 8; +constexpr float BIG_HORN_SPLASH_FALL = 1.5f; + +// 006c4b30 (Entity_NPC::Update's death start for Big Horn) Its part's death: the hand pulls back into its small hole +// (its HandDeath while its Main layer shows), the ball vanishes, and the head plays its Death unless closing its hole. +void big_horn_death_play(Entity_NPC& npc) +{ + if (npc.variant == BIG_HORN_BALL) + { + npc.isVisible = false; + return; + } + if (npc.variant != BIG_HORN_HAND) + { + if (npc.sprite.GetAnimation() != "BigHoleClose") npc.sprite.Play("Death"); + return; + } + + LayerState* main = npc.sprite.GetLayer("Main"); + const AnimationFrame* frame = main ? npc.sprite.animState.GetLayerFrame(main->layerData->id) : nullptr; + npc.sprite.Play(frame && frame->isVisible ? "HandDeath" : "SmallHoleClose"); +} + +// 006c4b30 (Entity_NPC::Update's Big Horn step) On its Poof event in a flooded room, Big Horn throws up a splash. +void big_horn_splash(Entity_NPC& npc) +{ + if (g_game->room->waterAmount <= SPLASH_WATER_MIN) return; + + Vector body = vector_make(npc.size, npc.size * BIG_HORN_SPLASH_DEPTH); + int drops = random_below(SPLASH_DROPS_RANGE) + SPLASH_DROPS_MIN; + for (int i = 0; i < drops; i++) + { + Vector direction = random_direction(); + Vector offset = vector_make(body.x * direction.x, body.y * direction.y); + float speed = random_unit() * BIG_HORN_SPLASH_SPEED_RANGE + BIG_HORN_SPLASH_SPEED_MIN; + Vector velocity = vector_make(offset.x * speed / body.x, offset.y * speed / body.y); + auto* drop = static_cast(g_game->Spawn({.position = vector_add(npc.pos, offset), + .velocity = velocity, + .subType = BIG_HORN_SPLASH_DROP_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_WATER_SPLASH, + .seed = Random()})); + drop->sprite.scale = vector_scale(drop->sprite.scale, SPLASH_DROP_SCALE); + drop->fallingSpeed = SPLASH_RISE_MIN - random_unit() * SPLASH_RISE_RANGE; + drop->fallingAcceleration = BIG_HORN_SPLASH_FALL; + drop->Update(); + } +} diff --git a/src/boss_brownie.cpp b/src/boss_brownie.cpp new file mode 100644 index 0000000..876dc6f --- /dev/null +++ b/src/boss_brownie.cpp @@ -0,0 +1,682 @@ +#include "boss_ai.h" +#include "entity_config.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "grid_entity.h" +#include "npc_basement.h" +#include "npc_caves.h" +#include "room_grid.h" +#include +#include +#include + +// Brownie's states: idle, the dash, the corkscrew chase (and its faster spin), the spin that rains corn shots, the +// fart and its death. Brownie's black subtype drops Chargers and Dank Squirts instead of dips. +constexpr int BROWNIE_CHASE = NPC_STATE_MOVE; +constexpr int BROWNIE_DASH = NPC_STATE_ATTACK; +constexpr int BROWNIE_FART = NPC_STATE_ATTACK2; +constexpr int BROWNIE_SPIN = NPC_STATE_ATTACK3; +constexpr int BROWNIE_FAST_CHASE = NPC_STATE_ATTACK4; +constexpr int BROWNIE_DYING = NPC_STATE_SPECIAL; +constexpr int BROWNIE_BLACK = 1; +constexpr uint8_t BROWNIE_NO_SHOT = 0xff; + +constexpr ColorMod BROWNIE_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; +constexpr int BROWNIE_DEPTH = 2000; +constexpr int BROWNIE_DASH_DEPTH = 1700; +constexpr float BROWNIE_FRICTION = 0.7f; +constexpr float BROWNIE_CHASE_FRICTION = 0.88f; +constexpr float BROWNIE_HAPPY = 0.6666667f; +constexpr float BROWNIE_UPSET = 0.33333334f; +constexpr int BROWNIE_IDLE_FRAMES = 31; +constexpr int BROWNIE_IDLE_ROLL_FRAMES = 30; + +constexpr float BROWNIE_SPAWN_STEP = 50; +constexpr float BROWNIE_FART_STEP = 10; +constexpr float BROWNIE_HEALTHY = 0.95f; +constexpr float BROWNIE_DYING_HEALTH = 0.25f; +constexpr int BROWNIE_HEALTHY_SPAWNS = 5; +constexpr int BROWNIE_DIP_LIMIT = 15; +constexpr int BROWNIE_CHARGER_LIMIT = 3; +constexpr int BROWNIE_DELIRIUM_LIMIT = 6; +constexpr float BROWNIE_SPAWN_REACH = 5; +constexpr float BROWNIE_SPAWN_SPEED = 7; +constexpr float BROWNIE_SPAWN_VOLUME = 0.8f; +constexpr int BROWNIE_SPAWN_SOUND_DELAY = 10; +constexpr int BROWNIE_LUNGE_DELAY = 30; + +constexpr int BROWNIE_ATTACK_ODDS = 4; +constexpr uint32_t BROWNIE_PERCENT = 100; +constexpr float BROWNIE_SPIN_ODDS_MAX = 80; +constexpr float BROWNIE_SPIN_ODDS_RANGE = 50; +constexpr uint32_t BROWNIE_SPIN_FIRST_RANGE = 10; +constexpr int BROWNIE_SPIN_FIRST_MIN = 3; +constexpr uint32_t BROWNIE_SPIN_NEXT_RANGE = 5; +constexpr int BROWNIE_SPIN_NEXT_MIN = 2; +constexpr uint32_t BROWNIE_CHASE_ATTACK_PERCENT = 70; +constexpr int BROWNIE_CHASE_FRAMES = 45; +constexpr int BROWNIE_DASH_FRAMES = 90; +constexpr float BROWNIE_FAST_SPIN = 2; + +constexpr uint32_t BROWNIE_SPIN_SLOTS = 12; +constexpr uint32_t BROWNIE_SHOTS_RANGE = 3; +constexpr int BROWNIE_SHOTS_MIN = 3; +constexpr float BROWNIE_SHOTS_PER_HURT = 6; +constexpr float BROWNIE_SPIN_PUSH = 2.5f; +constexpr float BROWNIE_SPIN_SHOT_SPEED = 10; +constexpr float BROWNIE_SHOT_SCALE = 1.1f; +constexpr float BROWNIE_SPIN_SHOT_HEIGHT = -35; +constexpr float BROWNIE_SPIN_SHOT_FALL = 4; +constexpr float BROWNIE_CREEP_SCALE = 3; +constexpr float BROWNIE_ABSORB_REACH = 1.1f; + +constexpr float BROWNIE_DASH_PUSH = 2.5f; +constexpr int BROWNIE_VOLLEY_SPACING = 3; +constexpr float BROWNIE_VOLLEY_SCATTER = 0.3f; +constexpr float BROWNIE_VOLLEY_SPEED = 10; +constexpr float BROWNIE_VOLLEY_SLOWDOWN = 0.95f; +constexpr int BROWNIE_VOLLEY_CHECK_FRAMES = 30; +constexpr uint32_t BROWNIE_VOLLEY_ODDS = 5; +constexpr int BROWNIE_VOLLEY_MIN = 3; + +constexpr int BROWNIE_STEER_FRAMES = 60; +constexpr float BROWNIE_STEER_MIN = 5; +constexpr float BROWNIE_STEER_RANGE = 5; +constexpr float BROWNIE_STEER = 0.15f; +constexpr float BROWNIE_STEER_KEEP = 0.8f; +constexpr int BROWNIE_CREEP_FRAMES = 8; +constexpr int BROWNIE_MINE_FRAMES = 20; +constexpr uint32_t BROWNIE_MINE_PERCENT = 60; +constexpr int BROWNIE_BUMP_SHAKE = 4; +constexpr float BROWNIE_BUMP_REACH = 200; +constexpr float BROWNIE_BUMP_SPREAD = 40; +constexpr float BROWNIE_BUMP_INWARD = -0.6f; +constexpr float BROWNIE_BUMP_SPLAT_MIN = 1.6f; + +constexpr float BROWNIE_FART_RADIUS = 160; +constexpr float BROWNIE_FART_DAMAGE = 15; +constexpr float BROWNIE_FART_THRESHOLD = 50; +constexpr float BROWNIE_FART_REACH = 120; +constexpr float BROWNIE_DANGLE_HEALTH = 0.2f; +constexpr float BROWNIE_DELIRIUM_HEALTH = 15; +constexpr float BROWNIE_SQUIRT_SPACING = 10; +constexpr int BROWNIE_SQUIRTS = 2; +constexpr int BROWNIE_TRAIL_FRAMES = 3; +constexpr float BROWNIE_TRAIL_SPEED = 1; +constexpr float BROWNIE_TRAIL_SIZE = 0.6f; +constexpr float BROWNIE_TRAIL_ALPHA = 0.5f; + +// What Brownie packs into i1, a byte each: the minion drops and the tenths of its health it lost, its step through +// a state, and the shots of its next volley. +struct BrownieCounters +{ + uint8_t drops = 0; + uint8_t tenths = 0; + uint8_t step = 0; + uint8_t shots = 0; +}; + +// What Brownie packs into i2, a byte each: its shot through a spin or volley, the spins left, and its last attack. +struct BrownieShots +{ + uint8_t shot = 0; + uint8_t spins = 0; + uint8_t lastAttack = 0; + uint8_t unused = 0; +}; + +// A frame of Brownie: its bytes, its minions (dips or Chargers), its creep, and the health marks it reacts to. +struct BrownieFrame +{ + std::vector minions; + BrownieCounters counters; + BrownieShots shots; + float fartHealth = 0; + float mood = 0; + float tenth = 0; + int creepVariant = EFFECT_CREEP_SLIPPERY_BROWN; + bool isBlack = false; +}; + +// The pitch of its farts, by its size. +static float brownie_pitch(Entity_NPC& npc) +{ + if (npc.championColorIdx == CHAMPION_TINY) return 1.5f; + return npc.championColorIdx == CHAMPION_GIANT ? 0.5f : 1; +} + +// A puddle of its creep, three times as big. +static void brownie_creep(Entity_NPC& npc, int variant) +{ + Entity* creep = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = variant, .seed = Random()}); + if (creep->type != ENTITY_EFFECT) return; + + creep->sprite.scale = vector_make(BROWNIE_CREEP_SCALE, BROWNIE_CREEP_SCALE); + creep->Update(); +} + +// A shot in its boss color. +static ProjectileParams brownie_shot_params(Entity_NPC& npc) +{ + ProjectileParams params; + params.variant = PROJECTILE_CORN; + params.scale = BROWNIE_SHOT_SCALE; + // The original also reads the color one past the last. + if (npc.bosscoloridx >= 0 && npc.bosscoloridx < (int)npc.config->bossColors.size()) + params.color = npc.config->bossColors[npc.bosscoloridx].color; + return params; +} + +// Drops minions as it is hurt, a fiftieth of its health at a time: one, or five while still healthy, up to its limit, +// flung out of it. +static void brownie_drop(Entity_NPC& npc, BrownieFrame& frame, int limit) +{ + int count = frame.isBlack ? 1 : npc.health > npc.maxHitPoints * BROWNIE_HEALTHY ? BROWNIE_HEALTHY_SPAWNS : 1; + int minions = (int)frame.minions.size(); + for (int i = 0; i < count && minions < limit; i++) + { + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = npc.size + BROWNIE_SPAWN_REACH}); + Entity* minion = g_game->Spawn({.position = spot, + .spawner = &npc, + .type = frame.isBlack ? ENTITY_CHARGER : ENTITY_DIP, + .variant = frame.isBlack ? 0 : DIP_BROWNIE, + .seed = seed}); + if (!minion) continue; + + minion->ClearEntityFlags(FLAG_APPEAR); + minions++; + minion->velocity = npc.velocity; + Vector away = vector_resized(vector_sub(minion->pos, npc.pos), BROWNIE_SPAWN_SPEED); + npc_push(*minion, vector_add(random_direction(), away)); + npc_sound_play(SOUND_PLOP, BROWNIE_SPAWN_VOLUME, BROWNIE_SPAWN_SOUND_DELAY, brownie_pitch(npc)); + } + frame.counters.drops++; +} + +// Its next attack once a tenth more of its health is gone: a spin (its odds growing as it weakens, halved right after +// a spin) or a dash. +static void brownie_attack_pick(Entity_NPC& npc, BrownieFrame& frame, int spinMin, uint32_t spinRange) +{ + uint32_t roll = Random() % BROWNIE_PERCENT; + frame.counters.tenths++; + if (npc.maxHitPoints == 0) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!"); + float health = std::clamp(npc.health / npc.maxHitPoints, 0.0f, 1.0f); + int odds = (int)(BROWNIE_SPIN_ODDS_MAX - health * BROWNIE_SPIN_ODDS_RANGE); + if (frame.shots.lastAttack == BROWNIE_SPIN) odds /= 2; + frame.counters.step = 0; + if ((int)roll >= odds) + { + npc.state = BROWNIE_DASH; + frame.shots.lastAttack = BROWNIE_DASH; + return; + } + npc.state = BROWNIE_SPIN; + frame.shots.lastAttack = BROWNIE_SPIN; + frame.shots.spins = (uint8_t)(Random() % spinRange + spinMin); + npc_sound_play(SOUND_BROWNIE_LAUGH, 1, 2, 1); +} + +// Idle: happy, upset or angry as its next tenth nears. Rested, it attacks once that tenth is gone, farts when freshly +// hurt while healthy, or now and then chases. +static void brownie_idle(Entity_NPC& npc, BrownieFrame& frame) +{ + npc.friction *= BROWNIE_FRICTION; + if (frame.mood >= BROWNIE_HAPPY) npc_anim_loop(npc.sprite, "Idle_Happy"); + else if (frame.mood >= BROWNIE_UPSET) npc_anim_loop(npc.sprite, "Idle_Upset"); + else npc_anim_loop(npc.sprite, "Idle_Angry"); + npc.renderZOffset = BROWNIE_DEPTH; + + if (npc.stateFrame >= BROWNIE_IDLE_FRAMES && npc.health <= frame.fartHealth) + { + brownie_attack_pick(npc, frame, BROWNIE_SPIN_FIRST_MIN, BROWNIE_SPIN_FIRST_RANGE); + npc.stateFrame++; + return; + } + if (npc.stateFrame >= BROWNIE_IDLE_FRAMES) + { + if (npc.pendingDamage > 0 && npc.health > npc.maxHitPoints * BROWNIE_HEALTHY) + { + npc.stateFrame++; + npc.state = BROWNIE_FART; + return; + } + if (npc.IsFrame(BROWNIE_IDLE_ROLL_FRAMES, (int)npc.index) && Random() % BROWNIE_ATTACK_ODDS == 0) + { + npc.state = (Random() & 1) == 0 ? BROWNIE_CHASE : BROWNIE_FAST_CHASE; + frame.counters.step = 0; + } + } + npc.stateFrame++; +} + +// The landing of a spin: a fart, a puddle of creep and the dips under it eaten for their health. +static void brownie_spin_land(Entity_NPC& npc, BrownieFrame& frame) +{ + npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, 1); + brownie_creep(npc, frame.creepVariant); + for (Entity* entity : entity_query_radius(npc.pos, npc.size * BROWNIE_ABSORB_REACH, QUERY_ALL)) + { + if (entity->type != ENTITY_DIP) continue; + + npc.health += entity->health; + entity->Kill(EntityRef(&npc)); + } +} + +// A corn shot of the spin from one of its twelve turns, as many as its volley allows per turn. +static void brownie_spin_shot(Entity_NPC& npc, BrownieFrame& frame) +{ + uint8_t slot = frame.shots.shot; + float wobble = (float)slot / BROWNIE_SPIN_SLOTS * PI_F; + float angle = (float)slot / BROWNIE_SPIN_SLOTS * -FULL_TURN_DEGREES * DEGREES_TO_RADIANS; + float cosine = std::cos(angle); + float sine = std::sin(angle); + Vector velocity = vector_make(cosine * 0.0f - sine * BROWNIE_SPIN_SHOT_SPEED, sine * 0.0f + cosine * BROWNIE_SPIN_SHOT_SPEED); + Vector from = vector_make(std::sin(wobble + wobble) * npc.size + npc.pos.x, npc.pos.y + 0.0f); + if (std::fmod((float)slot, (float)BROWNIE_SPIN_SLOTS / (float)frame.counters.shots) >= 1) return; + + ProjectileParams params = brownie_shot_params(npc); + params.heightModifier = BROWNIE_SPIN_SHOT_HEIGHT; + params.fallingSpeedModifier = BROWNIE_SPIN_SHOT_FALL; + npc.FireProjectiles(from, velocity, PROJECTILES_SINGLE, params); +} + +// The spin: it bounces off walls on its Shoot frames raining corn, lands, and spins again until its spins run out. +static void brownie_spin(Entity_NPC& npc, BrownieFrame& frame) +{ + npc.friction *= BROWNIE_FRICTION; + npc_anim_loop(npc.sprite, "SpinStart"); + npc.renderZOffset = BROWNIE_DEPTH; + if (frame.counters.step == 0) + { + frame.shots.shot = (uint8_t)(Random() % BROWNIE_SPIN_SLOTS); + float hurt = (1 - npc.health / npc.maxHitPoints) * BROWNIE_SHOTS_PER_HURT; + frame.counters.shots = (uint8_t)(Random() % BROWNIE_SHOTS_RANGE + (int)hurt + BROWNIE_SHOTS_MIN); + frame.counters.step = 1; + } + + if (!npc.sprite.animState.animData || !npc.sprite.animState.IsEventTriggered("Shoot")) + { + if (npc.entityCollisionClass == ENTCOLL_NONE) brownie_spin_land(npc, frame); + npc.entityCollisionClass = ENTCOLL_ALL; + npc.targetPosition = random_direction(); + } + else + { + if (npc.isCollidesWithGrid) + { + Vector normal = vector_normalized(npc.gridCollisionNormal); + float along = vector_dot(npc.targetPosition, normal); + npc.targetPosition = vector_sub(npc.targetPosition, vector_scale(normal, along + along)); + } + npc_push(npc, vector_scale(npc.targetPosition, BROWNIE_SPIN_PUSH)); + brownie_spin_shot(npc, frame); + npc.entityCollisionClass = ENTCOLL_NONE; + frame.shots.shot++; + } + + if (!npc_anim_is_done(npc)) return; + frame.counters.step = 0; + if (frame.shots.spins == 0) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + return; + } + frame.shots.spins--; + npc_anim_restart(npc.sprite, "SpinStart"); + npc.renderZOffset = BROWNIE_DEPTH; +} + +// Starts chasing a random spot. +static void brownie_chase_start(Entity_NPC& npc, BrownieFrame& frame) +{ + frame.counters.step = 1; + npc.stateFrame = 0; + npc.targetPosition = g_game->room->GetRandomPosition(0); + npc_sound_play(SOUND_BROWNIE_LAUGH, 1, 2, 1); +} + +// Chasing: spinning (faster in the fast chase) or dashing about until its time runs out, then most often an attack, +// else a fart. +static void brownie_chase_step(Entity_NPC& npc, BrownieFrame& frame) +{ + int limit = BROWNIE_DASH_FRAMES; + bool isFrameWanted = true; + if (npc.state == BROWNIE_DASH) + { + npc_anim_loop(npc.sprite, "Dashing"); + npc.renderZOffset = BROWNIE_DASH_DEPTH; + } + else + { + npc_anim_loop(npc.sprite, "Spinning"); + npc.renderZOffset = BROWNIE_DEPTH; + if (npc.state == BROWNIE_FAST_CHASE) npc.sprite.playbackSpeed = BROWNIE_FAST_SPIN; + limit = BROWNIE_CHASE_FRAMES; + isFrameWanted = npc.sprite.GetFrame() == 0 || npc.state == BROWNIE_FAST_CHASE; + } + + if (npc.stateFrame > limit && isFrameWanted) + { + npc.sprite.playbackSpeed = 1; + if (Random() % BROWNIE_PERCENT < BROWNIE_CHASE_ATTACK_PERCENT) + brownie_attack_pick(npc, frame, BROWNIE_SPIN_NEXT_MIN, BROWNIE_SPIN_NEXT_RANGE); + else + { + npc.state = BROWNIE_FART; + frame.counters.step = 0; + } + } + npc.stateFrame++; +} + +// The dash's windup: on its Dash event it lunges at its target, and once DashStart ends it chases. +static bool brownie_dash_start(Entity_NPC& npc, BrownieFrame& frame) +{ + npc_anim_loop(npc.sprite, "DashStart"); + npc.renderZOffset = BROWNIE_DASH_DEPTH; + bool isChasing = false; + if (npc.sprite.animState.animData) + { + isChasing = npc.sprite.animState.WasEventTriggered("Dash"); + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Dash")) + { + npc_push(npc, vector_resized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos), BROWNIE_DASH_PUSH)); + npc.PlaySound(SOUND_FART_GURG, 1, BROWNIE_LUNGE_DELAY, false, 1); + } + } + if (!npc_anim_is_done(npc)) return isChasing; + + brownie_chase_start(npc, frame); + frame.shots.shot = BROWNIE_NO_SHOT; + return isChasing; +} + +// The dash's volley: a scattered corn shot at its target every third frame until its shots run out, slowing it. Now +// and then (one roll in five each second) a new volley loads. +static void brownie_volley(Entity_NPC& npc, BrownieFrame& frame) +{ + if (npc.state != BROWNIE_DASH || frame.shots.shot == BROWNIE_NO_SHOT) + { + if (npc.IsFrame(BROWNIE_VOLLEY_CHECK_FRAMES, 0) && Random() % BROWNIE_VOLLEY_ODDS == 0) + { + frame.counters.shots = (uint8_t)(Random() % BROWNIE_VOLLEY_ODDS + BROWNIE_VOLLEY_MIN); + frame.shots.shot = 0; + } + return; + } + + if (frame.shots.shot % BROWNIE_VOLLEY_SPACING == 0) + { + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + Vector scatter = random_direction(); + float reach = random_unit() * BROWNIE_VOLLEY_SCATTER; + aim = vector_add(aim, vector_scale(scatter, reach)); + npc.FireProjectiles(npc.pos, vector_scale(aim, BROWNIE_VOLLEY_SPEED), PROJECTILES_SINGLE, brownie_shot_params(npc)); + npc.v2.x *= BROWNIE_VOLLEY_SLOWDOWN; + } + frame.shots.shot++; + if (frame.counters.shots <= frame.shots.shot / BROWNIE_VOLLEY_SPACING) frame.shots.shot = BROWNIE_NO_SHOT; +} + +// A splat where it bumps a wall, turned along that wall. +static void brownie_wall_splat(Entity_NPC& npc) +{ + Room& room = *g_game->room; + float margin = random_unit() * BROWNIE_BUMP_SPREAD * BROWNIE_BUMP_INWARD; + Vector reach = vector_add(npc.pos, vector_scale(npc.gridCollisionNormal, BROWNIE_BUMP_REACH)); + Vector spot = room.GetClampedPositionImpl(reach, margin, margin, margin, margin); + int column = (int)((spot.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((spot.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return; + uint32_t cell = (uint32_t)(row * room.gridWidth + column); + if (cell >= ROOM_GRID_CELLS || !room.gridEntities[cell]) return; + GridEntityType type = room.gridEntities[cell]->type; + if (type != GRID_WALL && type != GRID_DOOR) return; + + Entity_Effect* splat = npc.MakeSplat(random_unit() * 2 + BROWNIE_BUMP_SPLAT_MIN); + splat->pos = spot; + splat->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + Vector side = vector_cardinal(npc.gridCollisionNormal); + splat->AddEntityFlags(FLAG_RENDER_WALL); + splat->sprite.rotation = vector_angle(side) + RIGHT_ANGLE_DEGREES; + splat->Update(); +} + +// Chasing a spot (its first minion while it has some), steering with a speed rerolled each second, dropping creep +// and Corn Mines while dashing and bouncing off walls with a splat. +static void brownie_steer(Entity_NPC& npc, BrownieFrame& frame) +{ + if (vector_length(vector_sub(npc.targetPosition, npc.pos)) < npc.size) + npc.targetPosition = g_game->room->GetRandomPosition(0); + Vector toward = vector_sub(npc.targetPosition, npc.pos); + // The original keeps the first minion, meaning to keep the nearest. + if (!frame.minions.empty()) toward = vector_sub(frame.minions.front()->pos, npc.pos); + + if (npc.v2.x == 0 || npc.IsFrame(BROWNIE_STEER_FRAMES, (int)npc.index)) + { + npc.v2.x = random_unit() * BROWNIE_STEER_RANGE + BROWNIE_STEER_MIN; + if (npc.state == BROWNIE_FAST_CHASE) npc.v2.x *= 0.5f; + } + float speed = npc.v2.x; + Vector pulled = vector_add(npc.velocity, vector_scale(vector_normalized(toward), speed * BROWNIE_STEER)); + pulled = vector_add(pulled, vector_scale(vector_normalized(npc.velocity), speed * BROWNIE_STEER)); + Vector wanted = vector_resized(pulled, speed); + float keep = npc_friction_scaled(BROWNIE_STEER_KEEP, npc.speedMultiplier); + npc.velocity = vector_add(vector_scale(vector_sub(wanted, npc.velocity), 1 - keep), npc.velocity); + + if (npc.state == BROWNIE_DASH || npc.state == BROWNIE_FAST_CHASE) + { + if (npc.IsFrame(BROWNIE_CREEP_FRAMES, (int)npc.index)) brownie_creep(npc, frame.creepVariant); + if (npc.IsFrame(BROWNIE_MINE_FRAMES, (int)npc.index) && Random() % BROWNIE_PERCENT < BROWNIE_MINE_PERCENT) + { + uint32_t seed = Random(); + Vector around = random_direction(); + float reach = random_unit() * npc.size; + Vector spot = vector_add(npc.pos, vector_scale(around, reach)); + auto* mine = static_cast( + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_CORN_MINE, .seed = seed})); + mine->SetBossColorIdx(npc.bosscoloridx, 0); + } + } + if (!npc.isCollidesWithGrid) return; + + npc.targetPosition = g_game->room->GetRandomPosition(0); + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + game_shake_screen(BROWNIE_BUMP_SHAKE); + brownie_wall_splat(npc); +} + +// The dash and the chases: winding up, the run itself and its volley. +static void brownie_dash(Entity_NPC& npc, BrownieFrame& frame) +{ + bool isChasing = false; + bool isChase = npc.state == BROWNIE_CHASE || npc.state == BROWNIE_FAST_CHASE; + if (isChase && frame.counters.step == 0) brownie_chase_start(npc, frame); + if (frame.counters.step == 1) + { + isChasing = true; + brownie_chase_step(npc, frame); + } + else if (!isChase && frame.counters.step == 0) isChasing = brownie_dash_start(npc, frame); + brownie_volley(npc, frame); + + if (!isChasing) + { + npc.friction *= BROWNIE_FRICTION; + return; + } + npc.friction *= BROWNIE_CHASE_FRICTION; + brownie_steer(npc, frame); +} + +// The fart: a poison cloud on its Fart event, then idle, counting the tenths of health it lost meanwhile. +static void brownie_fart(Entity_NPC& npc, BrownieFrame& frame) +{ + npc.friction *= BROWNIE_FRICTION; + npc.sprite.Play("Fart"); + npc.renderZOffset = BROWNIE_DASH_DEPTH; + if (npc.sprite.IsEventTriggered("Fart")) + { + game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = BROWNIE_FART_RADIUS}); + TearFlags poison; + poison.set(TEAR_POISON); + damage_radius({.tearFlags = poison, + .position = npc.pos, + .source = &npc, + .damage = BROWNIE_FART_DAMAGE, + .playerDamageThreshold = BROWNIE_FART_THRESHOLD, + .radius = BROWNIE_FART_REACH}); + } + if (!npc_anim_is_done(npc)) return; + + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + frame.counters.step = 0; + for (float mark = frame.fartHealth; npc.health <= mark; mark -= frame.tenth) frame.counters.tenths++; +} + +// Its death: it bursts into two Dank Squirts (black) or turns into Dangle with a fifth of its health. True once it +// turned. +static bool brownie_death(Entity_NPC& npc, BrownieFrame& frame) +{ + npc.friction *= BROWNIE_FRICTION; + npc.sprite.Play("Death"); + if (!npc_anim_is_done(npc)) return false; + + npc.BloodExplode(); + if (frame.isBlack) + { + for (int i = 0; i < BROWNIE_SQUIRTS; i++) + { + uint32_t seed = Random(); + Vector spot = vector_add(npc.pos, vector_make((float)(i >> 1) * BROWNIE_SQUIRT_SPACING, (float)(i & 1) * BROWNIE_SQUIRT_SPACING)); + g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_SQUIRT, .variant = SQUIRT_DANK, .seed = seed}); + } + npc.state = NPC_STATE_DEATH; + return true; + } + + npc.Morph(ENTITY_DINGLE, DANGLE, 0, -1); + npc.isDead = false; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + { + npc.maxHitPoints = BROWNIE_DELIRIUM_HEALTH; + npc.health = BROWNIE_DELIRIUM_HEALTH; + ANM2::LoadDeliriumForm(npc.sprite, npc.type, npc.variant, true); + } + else + { + npc.health = npc.maxHitPoints * BROWNIE_DANGLE_HEALTH; + npc.maxHitPoints = npc.health; + } + g_game->room->lastAliveBossCount = 0; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.state = NPC_STATE_INIT; + return true; +} + +// Reads its counters and the health marks it reacts to: a drop each fiftieth lost, an attack each tenth, its mood +// between them. +static BrownieFrame brownie_frame_load(Entity_NPC& npc) +{ + BrownieFrame frame; + frame.counters = std::bit_cast(npc.i1); + frame.shots = std::bit_cast(npc.i2); + frame.isBlack = npc.subtype == BROWNIE_BLACK; + frame.creepVariant = frame.isBlack ? EFFECT_CREEP_BLACK : EFFECT_CREEP_SLIPPERY_BROWN; + if (npc.HasEntityFlags(FLAG_POISON)) frame.creepVariant = EFFECT_CREEP_GREEN; + if (npc.HasEntityFlags(FLAG_SLOW)) frame.creepVariant = EFFECT_CREEP_WHITE; + + frame.tenth = npc.maxHitPoints / BROWNIE_FART_STEP; + frame.fartHealth = npc.maxHitPoints - (float)(frame.counters.tenths + 1) * frame.tenth; + float nextMark = frame.fartHealth + frame.tenth; + if (frame.fartHealth == nextMark) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!"); + frame.mood = (npc.health - frame.fartHealth) / (nextMark - frame.fartHealth); + return frame; +} + +// 0048c3b0 Brownie (402): it idles until hurt, dropping dips (Chargers, black) as it loses health, then dashes with +// corn volleys, chases about leaving creep and Corn Mines, spins raining corn and farts poison. Near death it turns +// into Dangle (bursts, black). Only players' poison hurts it. +void boss_brownie_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.splatColor = BROWNIE_SPLAT_COLOR; + npc.i2 = std::bit_cast(BrownieShots{.shot = BROWNIE_NO_SHOT, .lastAttack = NPC_STATE_IDLE}); + npc.renderZOffset = BROWNIE_DEPTH; + return; + } + + BrownieFrame frame = brownie_frame_load(npc); + bool isDying = npc.health <= npc.maxHitPoints * BROWNIE_DYING_HEALTH || npc.isDead; + if (isDying && npc.state != BROWNIE_DYING && npc.deliriumBossType == 0 && !npc.HasEntityFlags(FLAG_NO_SPLIT)) + { + npc.isDead = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.state = BROWNIE_DYING; + } + + int minionType = frame.isBlack ? ENTITY_CHARGER : ENTITY_DIP; + int limit = frame.isBlack ? BROWNIE_CHARGER_LIMIT : BROWNIE_DIP_LIMIT; + if (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) frame.minions = entity_query(minionType, -1); + else + { + npc.CountRelatedEntities(minionType, -1, &frame.minions); + limit = BROWNIE_DELIRIUM_LIMIT; + } + float dropHealth = npc.maxHitPoints - (float)(frame.counters.drops + 1) * (npc.maxHitPoints / BROWNIE_SPAWN_STEP); + if (npc.health <= dropHealth && npc.state != BROWNIE_DYING) brownie_drop(npc, frame, limit); + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Splat")) + npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, brownie_pitch(npc)); + + bool isCalmed = npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && npc.state != NPC_STATE_IDLE && room_is_clear(); + if (isCalmed) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + } + switch (npc.state) + { + case NPC_STATE_IDLE: + brownie_idle(npc, frame); + break; + case BROWNIE_SPIN: + brownie_spin(npc, frame); + break; + case BROWNIE_DASH: + case BROWNIE_CHASE: + case BROWNIE_FAST_CHASE: + brownie_dash(npc, frame); + break; + case BROWNIE_DYING: + npc.i1 = std::bit_cast(frame.counters); + npc.i2 = std::bit_cast(frame.shots); + if (brownie_death(npc, frame)) return; + break; + case BROWNIE_FART: + brownie_fart(npc, frame); + break; + } + + if (npc.IsFrame(BROWNIE_TRAIL_FRAMES, (int)npc.index) && vector_length(npc.velocity) > BROWNIE_TRAIL_SPEED) + { + Entity_Effect* splat = npc.MakeSplat(random_unit() + BROWNIE_TRAIL_SIZE); + ColorMod color = npc.splatColor; + color._tint[3] = BROWNIE_TRAIL_ALPHA; + splat->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + if (npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + { + bool isFromPlayer = event.source.type == ENTITY_PLAYER || event.source.spawnerType == ENTITY_PLAYER; + if (!isFromPlayer && (event.damageFlags & DAMAGE_POISON_BURN)) event.damage = 0; + } + npc.v1 = npc.velocity; + npc.i1 = std::bit_cast(frame.counters); + npc.i2 = std::bit_cast(frame.shots); +} diff --git a/src/boss_dingle.cpp b/src/boss_dingle.cpp index d6722ed..887d262 100644 --- a/src/boss_dingle.cpp +++ b/src/boss_dingle.cpp @@ -5,7 +5,6 @@ #include // Dingle and Dangle (variant 1), and the subtypes that change what they summon and shoot. -constexpr int DANGLE = 1; constexpr int DINGLE_POOPER = 1; constexpr int DINGLE_SPIDERS = 2; constexpr int CORNY_DIP = 2; diff --git a/src/boss_gideon.cpp b/src/boss_gideon.cpp new file mode 100644 index 0000000..85d917b --- /dev/null +++ b/src/boss_gideon.cpp @@ -0,0 +1,746 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_effect_combat.h" +#include "entity_factory.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "grid_entity.h" +#include "loot_list.h" +#include "manager.h" +#include "music_manager.h" +#include "room_config.h" +#include "room_descriptor.h" +#include "room_grid.h" +#include + +// The Great Gideon: a wall of a face fixed in the Mines' floor, three cells wide and two high. It calls waves of +// enemies (challenge rooms of subtype 12, harder each time) whenever the room empties, losing a hit point a wave, and +// between them shoots, rains fire, sends a crackwave or pulls everything in. Several Gideons chain into one, the +// first holding the health bar. +constexpr float GIDEON_SIZE = 52; +constexpr float GIDEON_SIZE_MULTI_Y = 0.45f; +constexpr int GIDEON_GRID_POINTS = 8; +constexpr float GIDEON_FRICTION = 0.4f; +constexpr int GIDEON_RESTING = 1; +constexpr int GIDEON_BLOCKED_PATH = 3999; +constexpr int GIDEON_PATH_LIMIT = 951; +constexpr std::array, 6> GIDEON_CELLS = {{{-1, 0}, {0, 0}, {1, 0}, {-1, -1}, {0, -1}, {1, -1}}}; + +// Its idle: a wave is called once ready after 30 frames (1 in 8 a frame), else an attack after 90 (1 in 15). +constexpr int SUMMON_WAIT = 30; +constexpr int GIDEON_SUMMON_ODDS_MASK = 7; +constexpr int ATTACK_WAIT = 90; +constexpr int GIDEON_ATTACK_ODDS = 15; +constexpr float GIDEON_PITCH = 0.9f; + +// i1 holds whether a wave is due (its low byte, which a chained Gideon mirrors) and whether the crackwave was used. +constexpr int GIDEON_WAVE_DUE = 1; +constexpr int GIDEON_CRACKWAVE_USED = 1 << 8; +constexpr int GIDEON_MIRRORED = 0xff; + +// i2 holds two cooldowns: the fire rain's in its low half, the pull's in its high half. +constexpr int COOLDOWN_BITS = 16; +constexpr int COOLDOWN_MASK = 0xffff; +constexpr int RAIN_COOLDOWN = 450; +constexpr int PULL_COOLDOWN = 600; +constexpr int PULL_SHARED_COOLDOWN_MIN = 90; +constexpr int PULL_SHARED_COOLDOWN_RANGE = 150; +constexpr int CRACKWAVE_WAVES_MIN = 3; +constexpr int PULL_ENEMIES_MAX = 5; +constexpr int CRACKWAVE_WEIGHT = 6; + +// The attacks: three shots (the middle a big one bursting in 8), a rain of burning rocks for 50 frames, a crackwave +// down from it, and a 115 frame pull. +enum GideonAttack +{ + GIDEON_SHOTS, + GIDEON_RAIN, + GIDEON_CRACKWAVE, + GIDEON_PULL +}; + +constexpr float GIDEON_SHOT_SPEED = 10; +constexpr float GIDEON_SHOT_SPREAD = 20; +constexpr float BIG_SHOT_HEIGHT = -23; +constexpr float BIG_SHOT_SCALE = 2; +constexpr float BIG_SHOT_ACCELERATION = 0.94f; +constexpr ColorMod BIG_SHOT_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.2f, 0, 0}}; +constexpr int RAIN_FRAMES = 50; +constexpr float RAIN_RISE = 16; +constexpr float RAIN_RISE_RANGE = 4; +constexpr float RAIN_SPREAD = 2; +constexpr float RAIN_REACH_X = 30; +constexpr float RAIN_REACH_Y = 10; +constexpr float RAIN_FALL_ACCEL = 2; +constexpr float RAIN_FALL_SPEED = -48; +constexpr float RAIN_FALL_SPEED_RANGE = 53; +constexpr ColorMod RAIN_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 0.3f, 0}}; +constexpr float RAIN_START_VOLUME = 1.5f; +constexpr int CRACKWAVE_SHAKE = 14; +constexpr float CRACKWAVE_HEADING = 90; +constexpr int PULL_FRAMES = 115; + +// The pull: everything is drawn in by 2 / (1 + d² / 10000), players at most 0.8 (1.4 times that, heavier ones less), +// tears at 0.7 times it and its own rocks at 0.4. From frame 85 to 46 of it, every 6th, a rock rises at the wall it +// faces, in a fan swinging across 9 angles about straight down. A ring is drawn in every 6th frame, a trail every 3rd. +constexpr float PULL_STRENGTH = 2; +constexpr float PULL_FALLOFF = 0.0001f; +constexpr float PULL_PLAYER_SCALE = 1.4f; +constexpr float PULL_PLAYER_MAX = 0.8f; +constexpr float PULL_TEAR_SCALE = 0.7f; +constexpr float PULL_ROCK_STRENGTH = 0.4f; +constexpr int PULL_ROCKS_FIRST = 46; +constexpr int PULL_ROCKS_LAST = 85; +constexpr int PULL_ROCK_EVERY = 6; +constexpr int PULL_RING_EVERY = 6; +constexpr int PULL_TRAIL_EVERY = 3; +constexpr std::array PULL_ROCK_ANGLES = {-48, -24, 0, 24, 48, 36, 12, -12, -36}; +constexpr float PULL_ROCK_WALL_MARGIN = 20; +constexpr float PULL_ROCK_HEIGHT = -22; +constexpr float PULL_ROCK_HEIGHT_RANGE = 8; +constexpr float PULL_ROCK_LIFT = -0.06f; +constexpr float PULL_ROCK_LIFT_RANGE = 0.030000005f; +constexpr float PULL_ROCK_SCALE = 0.6f; +constexpr float PULL_ROCK_SCALE_RANGE = 1.1999999f; +constexpr float PULL_ROCK_DROP = 0.2f; +constexpr int PULL_ROCK_FADE_IN = 10; +constexpr int GIDEON_ROCK_VARIANT = 9; +constexpr ColorMod PULL_ROCK_FADE = {{1, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float PULL_RING_RAISE = -24; +constexpr int RING_COLOR_PRIORITY = 255; +constexpr int PULL_RING = 0; +constexpr int PULL_TRAIL = 1; + +// Its end: a closed face that crumbles into rock particles once it lies still. +constexpr int CRUMBLE_PARTICLES_MIN = 12; +constexpr int CRUMBLE_PARTICLES_RANGE = 3; +constexpr float CRUMBLE_SPEED = 9; +constexpr int DEATH_DUST_PARTICLES = 4; +constexpr float DEATH_DUST_SPEED = 5; +constexpr float DEATH_EXPLOSION_SCALE = 2; +constexpr int GIDEON_DEATH_SHAKE = 14; +constexpr int GIDEON_ROCK_PARTICLE_SUBTYPE = 7; +constexpr int STAIRS_GIDEON = 1; +constexpr int STAIRS_PATH = 900; + +// The waves: challenge rooms of subtype 12 of the stage (else the special rooms), harder each wave (1, 5, 5, 10, 10 +// then 15). A Fire Worm wave needs 6 pits. Ten tries at most. +constexpr int WAVE_ROOM_SUBTYPE = 12; +constexpr std::array WAVE_DIFFICULTY = {1, 1, 5, 5, 10, 10, 15}; +constexpr int WAVE_PITS_FOR_FIRE_WORMS = 6; +constexpr int WAVE_TRIES = 10; +constexpr int STAGE_ID_HOME_DIMENSION = 35; +constexpr int GIDEON_DIMENSION_DEATH_CERTIFICATE = 2; +constexpr float WAVE_ENTRY_SCALE = 2.3283062e-10f; +constexpr float CELL_SIZE = 40; +constexpr float CELL_ORIGIN_X = 40; +constexpr float CELL_ORIGIN_Y = 120; +constexpr RNG CRAWLSPACE_RNG_SHIFTS = {0, 1, 27, 27}; +constexpr int CRAWLSPACE_GIDEON = 1; + +static int cooldown_get(const Entity_NPC& npc, int shift) +{ + return (npc.i2 >> shift) & COOLDOWN_MASK; +} + +static void cooldown_set(Entity_NPC& npc, int shift, int frames) +{ + npc.i2 = (npc.i2 & ~(COOLDOWN_MASK << shift)) | (frames & COOLDOWN_MASK) << shift; +} + +// The pitches of its sounds, by its size. +static float gideon_pitch(const Entity_NPC& npc, float normal, float tiny, float giant) +{ + if (npc.championColorIdx == CHAMPION_TINY) return tiny; + return npc.championColorIdx == CHAMPION_GIANT ? giant : normal; +} + +// Shows the waves left in the boss bar's counter. +static void gideon_counter_update(Entity_NPC& npc) +{ + g_game->hud.bossCounter = (int16_t)(int)(npc.maxHitPoints - npc.health + 1); + g_game->hud.bossCounterTotal = (int16_t)(int)npc.maxHitPoints; +} + +// Closing its eyes for good, flat and uncounted. +static void gideon_rest(Entity_NPC& npc) +{ + npc.subtype = GIDEON_RESTING; + npc.state = NPC_STATE_SPECIAL; + npc.sprite.Play("ClosedEyes"); + npc.flags = (npc.flags & ~FLAG_APPEAR) | FLAG_BOSSDEATH_TRIGGERED; +} + +// Its rocks from the pull drop out of the air. +static void pull_rocks_drop(Entity_NPC& npc) +{ + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->type == ENTITY_PROJECTILE && entity->variant == GIDEON_ROCK_VARIANT && entity->spawnerType == npc.type) + static_cast(entity)->fallingAccel = PULL_ROCK_DROP; +} + +// 004b1210 Picks its next attack by weight: its shots always, the fire rain and the pull off cooldown (the pull also +// with fewer than 5 enemies about, and delayed while another Gideon of the chain pulls), the crackwave weighing 6 once +// three waves came, once. +static void gideon_attack_choose(Entity_NPC& npc) +{ + Entity_NPC* link = &npc; + while (link->ParentNPC()) link = link->ParentNPC(); + for (; link->child; link = link->ChildNPC()) + { + bool isPulling = link->state == NPC_STATE_ATTACK4 || link->state == NPC_STATE_STOMP; + if (link == &npc || !isPulling) continue; + + int delay = (int)(Random() % PULL_SHARED_COOLDOWN_RANGE) + PULL_SHARED_COOLDOWN_MIN; + cooldown_set(npc, COOLDOWN_BITS, std::max(delay, cooldown_get(npc, COOLDOWN_BITS))); + break; + } + + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(GIDEON_SHOTS, 1); + if (cooldown_get(npc, 0) == 0) picker.AddOutcomeWeight(GIDEON_RAIN, 1); + if (npc.stateFrame > CRACKWAVE_WAVES_MIN && !(npc.i1 & GIDEON_CRACKWAVE_USED)) + picker.AddOutcomeWeight(GIDEON_CRACKWAVE, CRACKWAVE_WEIGHT); + if (cooldown_get(npc, COOLDOWN_BITS) == 0 && g_game->room->GetAliveEnemiesCount() < PULL_ENEMIES_MAX) + picker.AddOutcomeWeight(GIDEON_PULL, 1); + + switch (picker.PickOutcome({Random() | 1, 5, 9, 7})) + { + case GIDEON_SHOTS: + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Attack1"); + return npc_sound_play(SOUND_LOW_INHALE, 1, 2, gideon_pitch(npc, GIDEON_PITCH, 1.4f, 0.45f)); + case GIDEON_RAIN: + npc.state = NPC_STATE_ATTACK2; + npc.sprite.Play("Attack2Start"); + cooldown_set(npc, 0, RAIN_COOLDOWN); + return npc_sound_play(SOUND_MOUTH_FULL, 1, 2, gideon_pitch(npc, GIDEON_PITCH, 1.4f, 0.45f)); + case GIDEON_CRACKWAVE: + npc.state = NPC_STATE_ATTACK3; + npc_sound_play(SOUND_GRROOWL, 1, 2, gideon_pitch(npc, GIDEON_PITCH, 1.4f, 0.45f)); + npc.sprite.Play("Attack3"); + npc.i1 |= GIDEON_CRACKWAVE_USED; + return; + case GIDEON_PULL: + npc_sound_play(SOUND_MONSTER_ROAR_1, 1, 2, champion_pitch_get(npc)); + npc.sprite.Play("Attack4Start"); + npc.state = NPC_STATE_ATTACK4; + cooldown_set(npc, COOLDOWN_BITS, PULL_COOLDOWN); + return; + } +} + +// The first Gideon's chain, or its own when it is the first. +static void gideon_chain_join(Entity_NPC& npc) +{ + for (Entity* other : entity_query(npc.type, -1)) + { + if (other == &npc) continue; + + Entity* last = other; + while (last->child) last = last->child; + npc.parent = last; + last->child = &npc; + break; + } + if (!npc.parent) return gideon_counter_update(npc); + + npc.AddEntityFlags(FLAG_DONT_COUNT_BOSS_HP | FLAG_BOSSDEATH_TRIGGERED); + npc.isCanShutDoors = false; +} + +// 006b8f30 (ClearReferences' Gideon part) Leaving its chain: its child takes its parent, and when it was the first +// its child takes the health bar and holds the doors. +void gideon_chain_unlink(Entity_NPC& npc) +{ + if (npc.child) npc.child->parent = npc.parent.get(); + if (npc.parent) npc.parent->child = npc.child.get(); + + Entity_NPC* next = npc.ChildNPC(); + if (!npc.parent && next) + { + gideon_counter_update(*next); + next->ClearEntityFlags(FLAG_DONT_COUNT_BOSS_HP); + if (npc.subtype == 0) next->ClearEntityFlags(FLAG_BOSSDEATH_TRIGGERED); + next->isCanShutDoors = !next->IsFriendly(); + } + npc.parent = nullptr; + npc.child = nullptr; +} + +// 004b1910 Calls a wave: a challenge room of its difficulty whose enemies rise from pentagrams on free cells where +// the room places them, with the summon's sound. Only the first of a chain calls. +static void gideon_wave_spawn(Entity_NPC& npc) +{ + if (npc.parent) return; + + Game& game = *g_game; + Room& room = *game.room; + int difficulty = WAVE_DIFFICULTY[std::min(npc.stateFrame, (int)WAVE_DIFFICULTY.size() - 1)]; + int pitCount = 0; + for (int cell = 0; cell < room.gridWidth * room.gridHeight; cell++) + { + GridEntity* grid = room.GetGridEntity(cell); + if (grid && grid->type == GRID_PIT) pitCount++; + } + + RNG rng = {npc.dropRNG.Next(), 5, 9, 7}; + std::vector> entries; + for (int tries = 0; entries.empty() && tries < WAVE_TRIES; tries++) + { + int stageId = STAGE_ID_HOME_DIMENSION; + if (game.challenge == CHALLENGE_RED_REDEMPTION) + stageId = RoomConfig::GetStageID(game.stage, game.GetRoomStageType(game.currentRoomIdx), ROOM_MODE_CURRENT); + else if (game.currentDimensionIdx != GIDEON_DIMENSION_DEATH_CERTIFICATE) + stageId = RoomConfig::GetStageID(game.stage, game.stageType, ROOM_MODE_CURRENT); + RoomQuery query = {.shape = (RoomShape)room.GetRoomShape(), + .maxDifficulty = difficulty, + .minDifficulty = difficulty, + .stageId = stageId, + .subtype = WAVE_ROOM_SUBTYPE, + .type = ROOM_CHALLENGE}; + RoomConfig_Room* wave = + game.roomConfig.GetRandomRoomWithFallbackStage(rng.Next(), WEIGHT_REDUCE, query, STAGE_ID_SPECIAL_ROOMS); + if (!wave) + { + KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"No enemy wave found for Gideon\n"); + return; + } + + for (RoomSpawn& spawn : wave->spawns) + { + RoomEntry entry = *spawn.PickEntry((float)rng.Next() * WAVE_ENTRY_SCALE); + int column = spawn.x + 1; + int row = spawn.y + 1; + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int cell = isInside ? row * room.gridWidth + column : -1; + room_entry_transform(room, entry, cell, rng.Next()); + if (entry.type >= ENTITY_EFFECT) continue; + if (entry.type == ENTITY_FIRE_WORM && pitCount < WAVE_PITS_FOR_FIRE_WORMS) + { + entries.clear(); + break; + } + entries.push_back({cell, entry}); + } + } + + for (auto& [cell, entry] : entries) + { + Vector at = vector_make((float)(cell % room.gridWidth) * CELL_SIZE + CELL_ORIGIN_X, + (float)(cell / room.gridWidth) * CELL_SIZE + CELL_ORIGIN_Y); + Vector free = room_free_tile_position_find(at, 0); + Entity_Effect* pentagram = pentagram_spawn({.position = free, + .spawner = &npc, + .subType = entry.subtype, + .type = (int)entry.type, + .variant = entry.variant, + .seed = rng.Next()}, + -1); + bool isVersusPlayer = game.deathmatchManager.is_active() && entry.type == ENTITY_PLAYER; + if (isVersusPlayer || (entry.type >= ENTITY_FIRST_ENEMY && entry.type < ENTITY_EFFECT)) + pentagram->AddEntityFlags(FLAG_AMBUSH); + } + npc_sound_play(SOUND_SUMMON_PENTA, 1, 2, 1); + gideon_counter_update(npc); +} + +// The pull's tug on one entity, or none for what it leaves alone: dead enemies and the room's props are spared, but +// players, tears, bombs, pickups and shots always come. +static float pull_strength_get(Entity_NPC& npc, Entity& entity, float strength) +{ + int type = entity.type; + bool isPulledAlways = type == ENTITY_PLAYER || type == ENTITY_TEAR || type == ENTITY_BOMB || + type == ENTITY_PROJECTILE || type == ENTITY_PICKUP; + bool isProp = type == ENTITY_FIREPLACE || type == ENTITY_SHOPKEEPER || type == ENTITY_MOVABLE_TNT || + type == ENTITY_GENERIC_PROP || type == ENTITY_MINECART || type == ENTITY_POOP; + bool isEnemy = type >= ENTITY_FIRST_ENEMY && type < ENTITY_EFFECT && !isProp; + if (type == ENTITY_CULTIST && entity.variant == 10) return 0; + if (g_game->deathmatchManager.is_active() && type == ENTITY_PLAYER) isEnemy = true; + if (!(isEnemy && !entity.isDead) && !isPulledAlways) return 0; + + if (type == ENTITY_PLAYER) return std::min(strength * PULL_PLAYER_SCALE, PULL_PLAYER_MAX) / std::min(entity.mass, 1.0f); + if (type == ENTITY_TEAR) return strength * PULL_TEAR_SCALE; + bool isOwnRock = type == ENTITY_PROJECTILE && entity.variant == GIDEON_ROCK_VARIANT && entity.spawnerType == npc.type; + return isOwnRock ? PULL_ROCK_STRENGTH : strength; +} + +// A ring (every 6th frame) or trail (every 3rd) drawn in to its mouth. +static void pull_ring_spawn(Entity_NPC& npc, int subType) +{ + Entity* ring = g_game->Spawn( + {.position = npc.pos, .subType = subType, .type = ENTITY_EFFECT, .variant = EFFECT_BIG_ATTRACT, .seed = Random()}); + ring->posOffset = vector_make(0, PULL_RING_RAISE); + ring->Update(); +} + +// A rock rising at the wall the fan points to, fading in, flying up and pulled in with the rest. +static void pull_rock_spawn(Entity_NPC& npc, int frame) +{ + float angle = (PULL_ROCK_ANGLES[(frame / PULL_ROCK_EVERY) % PULL_ROCK_ANGLES.size()] + CRACKWAVE_HEADING) * + DEGREES_TO_RADIANS; + Vector direction = vector_make(std::cos(angle), std::sin(angle)); + Vector wall = Entity_Laser::CalculateEndPoint(npc.pos, direction, {}, nullptr, PULL_ROCK_WALL_MARGIN); + auto* rock = static_cast(g_game->Spawn({.position = wall, + .spawner = &npc, + .type = ENTITY_PROJECTILE, + .variant = GIDEON_ROCK_VARIANT, + .seed = Random()})); + rock->fallingSpeed = 0; + rock->height = PULL_ROCK_HEIGHT - random_unit() * PULL_ROCK_HEIGHT_RANGE; + rock->fallingAccel = PULL_ROCK_LIFT - random_unit() * PULL_ROCK_LIFT_RANGE; + rock->projectileFlags = PROJECTILE_NO_WALL_COLLIDE; + rock->scale = random_unit() * PULL_ROCK_SCALE_RANGE + PULL_ROCK_SCALE; + if (npc.HasEntityFlags(FLAG_SLOW)) rock->projectileFlags |= PROJECTILE_SLOWED; + rock->SetColor(PULL_ROCK_FADE, PULL_ROCK_FADE_IN, RING_COLOR_PRIORITY, true, true); +} + +// Its pull: everything about drawn in, and for each tick rocks, rings and trails, until it ends and its rocks drop. +static void gideon_pull(Entity_NPC& npc) +{ + if (!npc.sprite.IsPlaying()) + { + npc.sprite.Play("Attack4Loop"); + npc.SetCollisionDamage(1); + } + + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity == &npc) continue; + + Vector away = vector_sub(npc.pos, entity->pos); + float strength = pull_strength_get(npc, *entity, PULL_STRENGTH / (vector_length_squared(away) * PULL_FALLOFF + 1)); + if (strength != 0) npc_push(*entity, vector_scale(vector_normalized(away), strength)); + } + + for (int tick = 0; tick < npc_ticks_get(npc); tick++) + { + int frame = npc.projectileCooldown; + if (frame > PULL_ROCKS_FIRST - 1 && frame < PULL_ROCKS_LAST + 1 && frame % PULL_ROCK_EVERY == 0) + pull_rock_spawn(npc, frame); + if (frame % PULL_RING_EVERY == 0) pull_ring_spawn(npc, PULL_RING); + if (frame % PULL_TRAIL_EVERY == 0) pull_ring_spawn(npc, PULL_TRAIL); + if (--npc.projectileCooldown < 1) + { + npc.SetCollisionDamage(0); + npc.sprite.Play("Attack4End"); + npc.state = NPC_STATE_IDLE; + npc.aiCounter = 0; + return pull_rocks_drop(npc); + } + } +} + +// Its rain: each frame a burning rock flung up out of its mouth, until the rain ends. +static void gideon_rain(Entity_NPC& npc) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Attack2Loop"); + + ProjectileParams params; + params.color = RAIN_COLOR; + params.bulletFlags = PROJECTILE_FIRE_SPAWN; + Entity_Projectile* rock = npc.FireBossProjectiles(1, {}, 0, params); + Vector direction = random_direction(); + float rise = random_unit(); + float spread = random_unit(); + rock->velocity = vector_make(spread * direction.x * RAIN_SPREAD, rise * RAIN_RISE_RANGE + RAIN_RISE); + rock->pos = vector_make(direction.x * RAIN_REACH_X + npc.pos.x, direction.y * RAIN_REACH_Y + npc.pos.y); + rock->fallingAccel = RAIN_FALL_ACCEL; + rock->scale = random_unit() + 1; + rock->fallingSpeed = random_unit() * RAIN_FALL_SPEED_RANGE + RAIN_FALL_SPEED; + + if (--npc.projectileCooldown > 0) return; + npc.sprite.Play("Attack2End"); + npc.state = NPC_STATE_IDLE; + npc.aiCounter = 0; +} + +// Its shots: a big shot at its target bursting in 8, with a plain shot 20 degrees to either side. +static void gideon_shots_fire(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_MONSTER_GRUNT_2, 1, 2, false, GIDEON_PITCH); + Vector aim = vector_scale(vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)), GIDEON_SHOT_SPEED); + for (int side = -1; side < 2; side++) + { + ProjectileParams params; + if (side != 0) + { + float angle = (float)side * GIDEON_SHOT_SPREAD * DEGREES_TO_RADIANS; + Vector turned = vector_make(std::cos(angle) * aim.x - std::sin(angle) * aim.y, + std::cos(angle) * aim.y + std::sin(angle) * aim.x); + npc.FireProjectiles(npc.pos, turned, PROJECTILES_SINGLE, params); + continue; + } + + params.acceleration = BIG_SHOT_ACCELERATION; + params.color = BIG_SHOT_COLOR; + params.bulletFlags = PROJECTILE_ACCELERATE_EX | PROJECTILE_BURST8; + Entity_Projectile* shot = npc.FireBossProjectiles(1, {}, 0, params); + shot->height = BIG_SHOT_HEIGHT; + shot->fallingAccel = 0; + shot->fallingSpeed = 0; + shot->scale = BIG_SHOT_SCALE; + shot->velocity = aim; + } +} + +// Back to idling once its animation stops. +static void gideon_idle_when_done(Entity_NPC& npc) +{ + if (npc.sprite.IsPlaying()) return; + npc.state = NPC_STATE_IDLE; + npc.aiCounter = 0; +} + +// A wave comes when the room empties: it loses a hit point, and with none left it closes its eyes and the fight ends. +// A chained Gideon follows the first's end. +static void gideon_wave_check(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Entity_NPC* first = npc.ParentNPC(); + if (first && first->subtype == GIDEON_RESTING) + { + npc.SetCollisionDamage(0); + npc.health = 0.5f; + room.TriggerBossDeath(npc); + npc.state = NPC_STATE_SPECIAL; + npc.sprite.Play("CloseEyes"); + npc.isCanShutDoors = false; + npc.subtype = GIDEON_RESTING; + return; + } + if (first || npc.health < 1 || (npc.i1 & GIDEON_WAVE_DUE) || room.GetAliveEnemiesCount() - 1 >= 1) return; + + npc.i1 |= GIDEON_WAVE_DUE; + npc.health -= 1; + if (npc.health > 0) return; + + if (npc.state == NPC_STATE_STOMP) pull_rocks_drop(npc); + npc.SetCollisionDamage(0); + npc.health = 0.5f; + room.TriggerBossDeath(npc); + npc.state = NPC_STATE_SPECIAL; + npc.sprite.Play("CloseEyes"); + npc.isCanShutDoors = false; + npc.subtype = GIDEON_RESTING; +} + +// Every other frame while pulling, it swallows the shots that reach its mouth. +static void gideon_shots_swallow(Entity_NPC& npc) +{ + if (!npc.IsFrame(2, npc.index)) return; + if (npc.state != NPC_STATE_STOMP && !npc.sprite.IsPlaying("Attack4End")) return; + + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity->type != ENTITY_PROJECTILE) continue; + float reach = std::min(entity->sizeMulti.x, entity->sizeMulti.y) * npc.size + entity->size; + if (vector_length(vector_sub(npc.pos, entity->pos)) < reach) entity->Remove(); + } +} + +// The pre-update: a chained Gideon mirrors the first's waves, wave flag and health and rests with it, and every +// Gideon blocks the cells it covers. +static void gideon_pre_update(Entity_NPC& npc) +{ + Entity_NPC* first = npc.ParentNPC(); + bool isActive = npc.state != NPC_STATE_INIT && npc.state != NPC_STATE_APPEAR; + if (isActive && first && first->type == npc.type) + { + if (first->state != NPC_STATE_DEATH) + { + npc.stateFrame = first->stateFrame; + npc.i1 = (npc.i1 & ~GIDEON_MIRRORED) | (first->i1 & GIDEON_MIRRORED); + npc.health = first->health; + } + if (npc.subtype == 0 && first->subtype == GIDEON_RESTING) gideon_rest(npc); + } + if (npc.projectileDelay < 0) return; + + Room& room = *g_game->room; + for (auto [dx, dy] : GIDEON_CELLS) + { + int column = npc.projectileDelay % room.gridWidth + dx; + int row = npc.projectileDelay / room.gridWidth + dy; + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) continue; + int cell = row * room.gridWidth + column; + if (cell < ROOM_GRID_CELLS && room.gridPaths[cell] < GIDEON_PATH_LIMIT) room.gridPaths[cell] = GIDEON_BLOCKED_PATH; + } +} + +// Its first frame: fixed in place, untargetable and invincible, it blocks its cells, chains to an earlier Gideon, +// and starts with a wave due. +static void gideon_init(Entity_NPC& npc) +{ + npc.SetSize(GIDEON_SIZE, vector_make(1, GIDEON_SIZE_MULTI_Y), GIDEON_GRID_POINTS); + npc.targetPosition = npc.pos; + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.state = NPC_STATE_IDLE; + npc.isInvincible = true; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + npc.i1 = GIDEON_WAVE_DUE; + npc.projectileDelay = g_game->room->GetGridIndex(npc.pos); + npc.aiCounter = 0; + npc.projectileCooldown = 0; + npc.stateFrame = 0; + npc.i2 = 0; + if (npc.subtype == GIDEON_RESTING) gideon_rest(npc); + gideon_chain_join(npc); +} + +// 004b1ee0 (NpcAI::ENTITY_GIDEON) The Great Gideon: its waves, attacks and rest, fixed where it stands. +void boss_gideon_update(Entity_NPC& npc) +{ + npc.friction *= GIDEON_FRICTION; + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return gideon_pre_update(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + gideon_init(npc); + break; + case NPC_STATE_IDLE: + { + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Idle"); + npc.aiCounter++; + bool isWaveReady = npc.aiCounter > SUMMON_WAIT && (npc.i1 & GIDEON_WAVE_DUE) && !npc.parent; + if (isWaveReady && (Random() & GIDEON_SUMMON_ODDS_MASK) == 0) + { + npc.PlaySound(SOUND_MONSTER_YELL_B, 1, 2, false, GIDEON_PITCH); + npc.state = NPC_STATE_SUMMON; + } + else if (!isWaveReady && npc.aiCounter > ATTACK_WAIT && Random() % GIDEON_ATTACK_ODDS == 0) + gideon_attack_choose(npc); + break; + } + case NPC_STATE_JUMP: + gideon_rain(npc); + break; + case NPC_STATE_STOMP: + gideon_pull(npc); + break; + case NPC_STATE_ATTACK: + if (npc.sprite.IsEventTriggered("Shoot")) gideon_shots_fire(npc); + gideon_idle_when_done(npc); + break; + case NPC_STATE_ATTACK2: + if (!npc.sprite.IsEventTriggered("Shoot")) break; + npc.state = NPC_STATE_JUMP; + npc.PlaySound(SOUND_GHOST_ROAR, 1, 2, false, GIDEON_PITCH); + npc.PlaySound(SOUND_FLAME_BURST, RAIN_START_VOLUME, 2, false, 1); + npc.projectileCooldown = RAIN_FRAMES; + break; + case NPC_STATE_ATTACK3: + if (npc.sprite.IsEventTriggered("Sound")) npc.PlaySound(SOUND_GOOATTACH0, 1, 2, false, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, false, 1); + auto* wave = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_CRACKWAVE, + .seed = npc.initSeed})); + wave->parent = &npc; + wave->rotation = CRACKWAVE_HEADING; + game_shake_screen(CRACKWAVE_SHAKE); + } + gideon_idle_when_done(npc); + break; + case NPC_STATE_ATTACK4: + if (!npc.sprite.IsEventTriggered("Shoot")) break; + npc.PlaySound(SOUND_FIRE_RUSH, 1, 2, false, 1); + npc.state = NPC_STATE_STOMP; + npc.projectileCooldown = PULL_FRAMES; + break; + case NPC_STATE_SUMMON: + npc.sprite.Play("Summon"); + if (npc.sprite.IsPlaying()) break; + npc.stateFrame++; + npc.state = NPC_STATE_IDLE; + gideon_wave_spawn(npc); + npc.i1 &= ~GIDEON_WAVE_DUE; + npc.aiCounter = 0; + break; + case NPC_STATE_SPECIAL: + if (npc.sprite.IsPlaying()) break; + npc.sprite.Play("ClosedEyes"); + if (!npc.parent && !npc.unknownF54) break; + npc.PlaySound(SOUND_ROCK_CRUMBLE, 1, 2, false, 1); + game_particles_spawn({.position = npc.pos, + .speed = CRUMBLE_SPEED, + .count = (int)(Random() % CRUMBLE_PARTICLES_RANGE) + CRUMBLE_PARTICLES_MIN, + .subType = GIDEON_ROCK_PARTICLE_SUBTYPE, + .variant = EFFECT_ROCK_PARTICLE}); + return npc.Remove(); + } + + gideon_wave_check(npc); + gideon_shots_swallow(npc); + if (cooldown_get(npc, 0) != 0) cooldown_set(npc, 0, cooldown_get(npc, 0) - 1); + if (cooldown_get(npc, COOLDOWN_BITS) != 0) cooldown_set(npc, COOLDOWN_BITS, cooldown_get(npc, COOLDOWN_BITS) - 1); + npc.velocity = vector_scale(vector_sub(npc.targetPosition, npc.pos), 1 / npc.friction); + if (npc.isDead) npc_sound_play(SOUND_MONSTER_ROAR_2, 1, 2, champion_pitch_get(npc)); +} + +// 004b0fe0 The crawlspace stairs where it stood: the crawlspace (a Gideon one) is drawn first when the floor has none. +static void gideon_stairs_spawn(Entity_NPC& npc) +{ + if (npc.projectileDelay < 0) return; + + Game& game = *g_game; + RoomDescriptor* crawlspace = game.GetRoomByIdx(ROOM_DUNGEON_IDX); + if (!crawlspace->data) + { + RNG rng = CRAWLSPACE_RNG_SHIFTS; + rng._seed = game.devilAngelRoomRNG._seed; + crawlspace->InitSeeds(rng); + RoomQuery query = {.stageId = STAGE_ID_SPECIAL_ROOMS, .subtype = CRAWLSPACE_GIDEON, .type = ROOM_DUNGEON}; + crawlspace->data = game.roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + } + game.room->SpawnGridEntity(npc.projectileDelay, GRID_STAIRS, STAIRS_GIDEON, Random(), 0); +} + +// 004b3610 Its death (Entity_NPC::Update's death states): dust on the Sound event, then once the Death animation ends +// a big explosion, a shake and a crumble, and (unless a Delirium form, or stairs already lie in the room) the secret's +// jingle and the stairs to its crawlspace. +void gideon_death_update(Entity_NPC& npc) +{ + if (npc.sprite.GetAnimation() != "Death") return; + + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("Sound")) + { + npc_sound_play(SOUND_ROCK_CRUMBLE, 1, 2, champion_pitch_get(npc)); + Random(); + game_particles_spawn({.position = npc.pos, + .speed = DEATH_DUST_SPEED, + .count = DEATH_DUST_PARTICLES, + .subType = GIDEON_ROCK_PARTICLE_SUBTYPE, + .variant = EFFECT_ROCK_PARTICLE}); + } + if (npc.sprite.IsPlaying()) return; + } + + Entity* explosion = g_game->Spawn( + {.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + explosion->sprite.scale = vector_make(DEATH_EXPLOSION_SCALE, DEATH_EXPLOSION_SCALE); + game_shake_screen(GIDEON_DEATH_SHAKE); + npc_sound_play(SOUND_ROCK_CRUMBLE, 1, 2, champion_pitch_get(npc)); + game_particles_spawn({.position = npc.pos, + .speed = CRUMBLE_SPEED, + .count = (int)(Random() % CRUMBLE_PARTICLES_RANGE) + CRUMBLE_PARTICLES_MIN, + .subType = GIDEON_ROCK_PARTICLE_SUBTYPE, + .variant = EFFECT_ROCK_PARTICLE}); + if (npc.deliriumBossType != 0) return; + + Room& room = *g_game->room; + for (int cell = 0; cell < room.gridWidth * room.gridHeight; cell++) + { + GridEntity* grid = room.GetGridEntity(cell); + if (grid && grid->type == GRID_STAIRS && grid->variant == STAIRS_GIDEON) return; + } + if (npc.projectileDelay >= 0 && npc.projectileDelay < ROOM_GRID_CELLS) room.gridPaths[npc.projectileDelay] = STAIRS_PATH; + g_manager->musicManager.PlayJingle(MUSIC_JINGLE_SECRET_ROOM_FIND); + gideon_stairs_spawn(npc); +} diff --git a/src/boss_haunt.cpp b/src/boss_haunt.cpp index a6035ee..9d2ba76 100644 --- a/src/boss_haunt.cpp +++ b/src/boss_haunt.cpp @@ -9,7 +9,6 @@ #include // The Haunt (variant 0) and its Lil Haunts (variant 10), and its black and pale subtypes. -constexpr int HAUNT_LIL_VARIANT = 10; constexpr int HAUNT_BLACK = 1; constexpr int HAUNT_PALE = 2; diff --git a/src/boss_hush.cpp b/src/boss_hush.cpp index 0748857..ed282c6 100644 --- a/src/boss_hush.cpp +++ b/src/boss_hush.cpp @@ -27,8 +27,6 @@ enum HushAttack // His minions and the effects he leaves, by type and variant. constexpr int HUSH_GAPER_VARIANT = 3; -constexpr int HUSH_LASER_VARIANT = 96; -constexpr int HUSH_BEAM_VARIANT = 101; // Which way his face looks (i1), indexing his face animations. constexpr std::array FACE_VANISH = {"FaceVanishFromLeft", "FaceVanishFromUp", "FaceVanishFromRight", @@ -123,7 +121,8 @@ constexpr float VOLLEY_DAMAGE = 2; constexpr int VOLLEYS_FRAMES = 150; constexpr float FACE_DEPTH = 20; constexpr float FACE_DEPTH_UP = 30; -constexpr std::array, FACE_COUNT> FACE_TINTS = {{{0.4f, 0.2f, 0}, {0, 0.2f, 0.4f}, {0.2f, 0.2f, 0}}}; +constexpr std::array, FACE_COUNT> FACE_TINTS = { + {{0.4f, 0.2f, 0}, {0, 0.2f, 0.4f}, {0.2f, 0.2f, 0}}}; // The volley patterns, with each face's turn spread across the active ones: aimed single shots speeding up or slowing, // a turning fan of 4 to 2, an aimed arc of 16 to 8, two curving rings, a decelerating ring turning into a curve, a @@ -227,7 +226,7 @@ constexpr int CREEP_FIRST_FRAME = 4; constexpr int CREEP_LAST_FRAME = 20; constexpr int CREEP_SOUND_DELAY = 20; constexpr float CREEP_REACH = 60; -constexpr float CREEP_SCALE_MIN = 2; +constexpr float HUSH_CREEP_SCALE_MIN = 2; constexpr int CREEP_SHAKE = 4; // Sliding concave: while one is near he pops back out. A turn ends once few of his shots are left (after 30 frames, @@ -254,7 +253,6 @@ constexpr int FLY_RING = 0; constexpr int FLY_SWARM = 1; constexpr int FLY_HOMING_SWARM = 2; constexpr int FLY_WEIGHT = 100; -constexpr int FLY_RING_GROUP = 1; constexpr size_t HUSH_FLY_RING_LIMIT = 10; constexpr int FLY_RNG_SKIP = 10; constexpr float FLY_HEADING = 2; @@ -491,7 +489,8 @@ static WeightedOutcomePicker attack_weights(Entity_NPC& npc, int phase, int gape if (phase > 1) { if (last != HUSH_CURVES) picker.AddOutcomeWeight(HUSH_CURVES, WEIGHT_CURVES); - bool isAfterMouth = last != HUSH_CURVES && (last == HUSH_GAPERS || last == HUSH_SLIDE || last == HUSH_SLIDE_VOLLEYS); + bool isAfterMouth = + last != HUSH_CURVES && (last == HUSH_GAPERS || last == HUSH_SLIDE || last == HUSH_SLIDE_VOLLEYS); bool isBlocked = isAfterMouth || last == HUSH_CHASE_VOLLEYS || gapers > GAPER_CROWD; if ((!isBlocked || isDelirium) && (!isDelirium || gapers == 0)) picker.AddOutcomeWeight(HUSH_GAPERS, WEIGHT_GAPERS); @@ -642,7 +641,8 @@ static void face_pattern_build(Entity_NPC& npc, FaceVolleys& faces, RNG& rng, co case 1: { count = 4; - volleys[0].params.circleAngle = (float)(f.face * 2) * PI_F / (float)f.mode + frame * FAN_SPIN / VOLLEY_SPIN_PERIOD; + volleys[0].params.circleAngle = + (float)(f.face * 2) * PI_F / (float)f.mode + frame * FAN_SPIN / VOLLEY_SPIN_PERIOD; bool isFlipped = f.face == 2 ? (rng.Next() & 1) != 0 : f.face == 1; for (int i = 0; i < count; i++) { @@ -798,7 +798,8 @@ static void face_volleys_fire(Entity_NPC& npc, const FaceVolleys& faces) ProjectileParams params = volley.params; params.variant = PROJECTILE_HUSH; - params.color = {{1, 1, 1, 1}, {0, 0, 0, 0}, {FACE_TINTS[face][0], FACE_TINTS[face][1], FACE_TINTS[face][2]}}; + const std::array& tint = FACE_TINTS[face]; + params.color = {{1, 1, 1, 1}, {0, 0, 0, 0}, {tint[0], tint[1], tint[2]}}; params.positionOffset = face_offset(*null); params.depthOffset = npc.i1 != 1 ? FACE_DEPTH : FACE_DEPTH_UP; params.targetPosition = vector_add(params.positionOffset, npc.pos); @@ -851,7 +852,8 @@ static void flies_update(Entity_NPC& npc) int group = (int)(first + first / UINT32_MAX); WeightedOutcomePicker picker; - if (Entity_NPC::QueryNPCsGroup(FLY_RING_GROUP).size() < HUSH_FLY_RING_LIMIT) picker.AddOutcomeWeight(FLY_RING, FLY_WEIGHT); + if (Entity_NPC::QueryNPCsGroup(HUSH_FLY_RING_GROUP).size() < HUSH_FLY_RING_LIMIT) + picker.AddOutcomeWeight(FLY_RING, FLY_WEIGHT); picker.AddOutcomeWeight(FLY_SWARM, FLY_WEIGHT); picker.AddOutcomeWeight(FLY_HOMING_SWARM, FLY_WEIGHT); bool isOdd = (g_game->frameCount - npc.spawnFrame) % 2 == 1; @@ -873,7 +875,7 @@ static void flies_update(Entity_NPC& npc) secondShape = FLY_RING_SECOND_SHAPE; reach = (int)(npc.size + FLY_RING_REACH); heading = Vector{}; - group = FLY_RING_GROUP; + group = HUSH_FLY_RING_GROUP; } else isHoming = outcome == FLY_HOMING_SWARM; size_t groupSize = Entity_NPC::QueryNPCsGroup(group).size(); @@ -893,7 +895,8 @@ static void flies_update(Entity_NPC& npc) for (int i = 0; i < flyCount; i++) { uint32_t seed = Random(); - Vector spot = vector_add(vector_make(npc.pos.x, npc.pos.y - FLY_MOUTH_RISE), vector_scale(random_direction(), FLY_MOUTH_REACH)); + Vector mouth = vector_make(npc.pos.x, npc.pos.y - FLY_MOUTH_RISE); + Vector spot = vector_add(mouth, vector_scale(random_direction(), FLY_MOUTH_REACH)); flies.push_back(static_cast( g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_HUSH_FLY, .seed = seed}))); } @@ -935,7 +938,8 @@ static void spit_update(Entity_NPC& npc) Vector from = face_offset(*null); params.bulletFlags = PROJECTILE_BURST3; params.heightModifier = from.y; - npc.FireProjectiles(vector_make(npc.pos.x + from.x, npc.pos.y), SPIT_VELOCITIES[face], PROJECTILES_SINGLE, params); + Vector spot = vector_make(npc.pos.x + from.x, npc.pos.y); + npc.FireProjectiles(spot, SPIT_VELOCITIES[face], PROJECTILES_SINGLE, params); } } @@ -953,7 +957,7 @@ static void hunters_spawn(Entity_NPC& npc) distance * (along.y * 0.5f + side.y * 0.5f) + npc.pos.y); spot = g_game->room->GetClampedPositionImpl(spot, 0, 0, 0, 0); auto* laser = static_cast(g_game->Spawn({.position = spot, .spawner = &npc, - .type = ENTITY_EFFECT, .variant = HUSH_LASER_VARIANT, + .type = ENTITY_EFFECT, .variant = EFFECT_HUSH_LASER, .seed = Random()})); laser->SetTimeout(-1); laser->parent = &npc; @@ -980,9 +984,12 @@ static void lasers_update(Entity_NPC& npc, int ticks, HushSurroundings& around) { const NullFrame* null = face_null(npc, eye); if (!null) continue; - auto* beam = static_cast(g_game->Spawn({.position = npc.pos, .spawner = &npc, - .type = ENTITY_EFFECT, - .variant = HUSH_BEAM_VARIANT, .seed = Random()})); + Entity* spawned = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_HUSH_LASER_UP, + .seed = Random()}); + auto* beam = static_cast(spawned); beam->sprite.offset = null->pos; beam->renderDepthOffset = BEAM_DEPTH; beam->SetTimeout(-1); @@ -1056,7 +1063,8 @@ static void gapers_update(Entity_NPC& npc, int ticks) float spread = std::clamp(random_unit(), 0.0f, 1.0f); Vector spot = vector_make((spread * GAPER_SPREAD - GAPER_SPREAD_LEFT) / HUSH_SPRITE_SCALE + npc.pos.x, npc.pos.y); spot = room_free_pickup_position_find({.position = spot, .isAvoidActiveEntities = true}); - Vector velocity = vector_scale(vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)), HUSH_GAPER_SPEED); + Vector toward = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + Vector velocity = vector_scale(toward, HUSH_GAPER_SPEED); Entity* gaper = g_game->Spawn({.position = spot, .velocity = velocity, .spawner = &npc, .type = ENTITY_HUSH_GAPER, .variant = HUSH_GAPER_VARIANT, .seed = Random()}); float aim = std::clamp(random_unit(), 0.0f, 1.0f); @@ -1113,7 +1121,8 @@ static void curves_update(Entity_NPC& npc, int ticks) const NullFrame* null = face_null(npc, face); if (!null) continue; float angle = (float)(npc.i1 - 2) * PI_F / 2 + CURVE_SPREADS[spread][face]; - params.bulletFlags &= ~(PROJECTILE_CURVE_LEFT | PROJECTILE_CURVE_RIGHT | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT); + params.bulletFlags &= + ~(PROJECTILE_CURVE_LEFT | PROJECTILE_CURVE_RIGHT | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT); if (face < 2) { params.changeFlags = params.bulletFlags | PROJECTILE_MEGA_WIGGLE; @@ -1181,9 +1190,12 @@ static void creep_update(Entity_NPC& npc) float angle = random_unit() * (to - from) + from; float reach = random_unit() * CREEP_REACH; spot = vector_add(spot, vector_make(std::cos(angle) * reach, std::sin(angle) * reach)); - Entity* creep = g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, + Entity* creep = g_game->Spawn({.position = spot, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_RED, .seed = Random()}); - float scale = random_unit() + CREEP_SCALE_MIN; + float scale = random_unit() + HUSH_CREEP_SCALE_MIN; creep->sprite.scale = vector_make(scale, scale); creep->Update(); game_shake_screen(CREEP_SHAKE); @@ -1257,7 +1269,8 @@ static void concave_update(Entity_NPC& npc, int ticks, size_t boils) bool isSliding = distance >= SLIDE_ARRIVED && entity_query(ENTITY_HUSH_GAPER, -1).size() > GAPER_CROWD; if (!isSliding) return pop_out(npc); } - else if (npc.state == HUSH_SLIDE_VOLLEYS) isLegDone = distance < SLIDE_ARRIVED || npc.stateFrame > SLIDE_VOLLEY_FRAMES; + else if (npc.state == HUSH_SLIDE_VOLLEYS) + isLegDone = distance < SLIDE_ARRIVED || npc.stateFrame > SLIDE_VOLLEY_FRAMES; else isLegDone = npc.stateFrame > SLIDE_VOLLEY_FRAMES; if (!isLegDone) @@ -1282,8 +1295,8 @@ void boss_hush_update(Entity_NPC& npc) HushSurroundings around{.gapers = entity_query(ENTITY_HUSH_GAPER, -1), .boils = entity_query(ENTITY_HUSH_BOIL, -1), - .lasers = entity_query(ENTITY_EFFECT, HUSH_LASER_VARIANT), - .beams = entity_query(ENTITY_EFFECT, HUSH_BEAM_VARIANT)}; + .lasers = entity_query(ENTITY_EFFECT, EFFECT_HUSH_LASER), + .beams = entity_query(ENTITY_EFFECT, EFFECT_HUSH_LASER_UP)}; shots_layer(npc); if (npc.state != HUSH_LASERS || npc.isDead) for (Entity* laser : around.lasers) laser->Kill(EntityRef()); diff --git a/src/boss_isaac.cpp b/src/boss_isaac.cpp index f1892bd..23ca14b 100644 --- a/src/boss_isaac.cpp +++ b/src/boss_isaac.cpp @@ -1190,7 +1190,7 @@ static void imp_dash(Entity_NPC& npc, Vector toTarget) // 0052ae30 The baby (38) and the Imp (259): drifting, shooting and blinking about, the Wrinkly Baby apart. void npc_baby_update(Entity_NPC& npc) { - if (npc.type == ENTITY_BABY && npc.variant == BABY_WRINKLY) return (void)NpcAI::ENTITY_WRINKLY_BABY(&npc); + if (npc.type == ENTITY_BABY && npc.variant == BABY_WRINKLY) return npc_wrinkly_baby_update(npc); if (npc.state == NPC_STATE_INIT) { npc.sprite.Play("Move"); diff --git a/src/boss_larry_jr.cpp b/src/boss_larry_jr.cpp index 4bbc677..4d76059 100644 --- a/src/boss_larry_jr.cpp +++ b/src/boss_larry_jr.cpp @@ -1,4 +1,5 @@ #include "boss_ai.h" +#include "npc_alt.h" #include "entity_player.h" #include "entity_config.h" #include "entity_pickup.h" @@ -443,7 +444,7 @@ static void head_update(Entity_NPC& npc) void boss_larry_jr_update(Entity_NPC& npc) { if (npc.type == ENTITY_LARRYJR && (npc.variant == LARRY_TUFF_TWINS || npc.variant == LARRY_TUFF_TWINS_ALT)) - return NpcAI::ENTITY_TUFF_TWINS(&npc); + return boss_tuff_twins_update(npc); Entity_NPC* head = chain_head(npc); if (npc.controllerID != -1 || (head && head->controllerID != -1)) reconstruction_missing("NpcAI::ENTITY_LARRYJR 0046a0f0: a segment a player controls"); diff --git a/src/boss_mega_satan.cpp b/src/boss_mega_satan.cpp new file mode 100644 index 0000000..afb112f --- /dev/null +++ b/src/boss_mega_satan.cpp @@ -0,0 +1,1407 @@ +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_familiar.h" +#include "grid_entity_door.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "grid_entity_trap_door.h" +#include "manager.h" +#include "npc_caves.h" +#include "room_grid.h" +#include +#include +#include +#include + +// His variants of type 274: the body and his left and right hands. +enum MegaSatanPart +{ + MEGA_SATAN_BODY, + MEGA_SATAN_LEFT_HAND, + MEGA_SATAN_RIGHT_HAND +}; + +// Mega Satan's states: rising, idle, the head smash, the laser, the streams, hiding between phases, the summon and +// dying. His hands share the idle, hiding and summon states and smash in two ways. +constexpr int MEGA_RISE = NPC_STATE_APPEAR_CUSTOM; +constexpr int MEGA_SMASH = NPC_STATE_STOMP; +constexpr int MEGA_LASER = NPC_STATE_ATTACK; +constexpr int MEGA_STREAMS = NPC_STATE_ATTACK2; +constexpr int MEGA_HIDE = NPC_STATE_SUMMON; +constexpr int MEGA_SUMMON = NPC_STATE_SUMMON2; +constexpr int MEGA_DEATH = NPC_STATE_SPECIAL; +constexpr int HAND_SMASH = NPC_STATE_ATTACK; +constexpr int HAND_QUAKE = NPC_STATE_ATTACK2; + +// The attack he made last (i2, and v2.x's bits for the one before): none yet, a hand's smash or both hands' quake. +constexpr int ATTACK_NONE = -1; +constexpr int ATTACK_HANDS = 0x1000; +constexpr int ATTACK_HAND = 0x1001; + +// i1's bytes: the phase, the step within a state, and the frames counted (by 30) before each lost hand comes back. +constexpr int I1_PHASE = 0; +constexpr int I1_STEP = 1; +constexpr int I1_LEFT_RETURN = 2; +constexpr int I1_RIGHT_RETURN = 3; +constexpr int HAND_RETURN_PERIOD = 30; +constexpr int HAND_RETURN_COUNT = 29; +constexpr int MEGA_STEP_REVEAL = 10; +constexpr int MEGA_STEP_END = 100; +constexpr int HAND_DEAD_MARK = -12345; +constexpr int QUAKE_LEFT_DELAY = -18; + +// He sits at (320, 260) over his floor, drawn 39 up. He rises to his spot over 15 frames from (320, 210), where the +// camera looks while he rises and dies. +static const Vector MEGA_HOME = vector_make(320, 260); +static const Vector MEGA_FOCUS = vector_make(320, 210); +constexpr float MEGA_SPRITE_RISE = 39; +constexpr float RISE_FRAMES = 15; +constexpr float SMOOTH_SLOPE = 6; +constexpr int RISE_SHAKE = 5; +constexpr int INTRO_SHAKE = 8; +constexpr float INTRO_TRIGGER_Y = 540; +constexpr float INTRO_MUSIC_FADE = 0.08f; + +// His hands sit 120 to either side and 100 below him. +static const Vector LEFT_HAND_SPOT = vector_make(-120, 100); +static const Vector RIGHT_HAND_SPOT = vector_make(120, 100); + +// The phases end at 80%, 60% and 40% of his health, which drops to 75%, 50% and 25% while he hides. +constexpr std::array PHASE_ENDS = {0.8f, 0.6f, 0.4f}; +constexpr std::array PHASE_HEALTHS = {0.75f, 0.5f, 0.25f}; +constexpr int PHASE_SOUND_DELAY = 120; + +// Idle at the first frame of "Idle" he blows his nose one roll in 10, in 2 below half health. Every 30 frames he picks +// an attack, 7 rolls in 10. +constexpr uint32_t NOSE_ODDS = 10; +constexpr uint32_t NOSE_ODDS_HURT = 2; +constexpr int ATTACK_PERIOD = 30; +constexpr uint32_t ATTACK_ROLL = 100; +constexpr uint32_t ATTACK_CHANCE = 70; +constexpr size_t SECOND_FORM_CROWD = 5; +constexpr float SECOND_FORM_CROWD_REACH = 360; + +// The attack weights: the laser 20 when his target is within 120 across (40 beyond 300 away, 20 more within 180, +// 50 more after both hands' quake, 30 more after the head smash, a tenth after a laser, 0.6 after one two back, none +// at first); the streams 25 (175 at first, 30 more after a laser or a smash, a tenth after streams and again after +// them two back); a hand 12 for the right and 9 for the left, 20 more within 260 (a quarter after a hand twice); the +// smash 20 (40 after a laser, a tenth after a smash, 20 after a hand twice); the summon 8 less 4 per enemy (1 per +// Hollow segment), 1.5 times beyond 300; both hands 15 (30 after streams). +constexpr float LASER_REACH_ACROSS = 120; +constexpr float FAR_REACH = 300; +constexpr float NEAR_REACH = 180; +constexpr float HAND_REACH = 260; +constexpr int WEIGHT_LASER = 20; +constexpr int WEIGHT_LASER_FAR = 40; +constexpr int WEIGHT_LASER_NEAR = 20; +constexpr int WEIGHT_LASER_AFTER_HANDS = 50; +constexpr int WEIGHT_AFTER_SMASH = 30; +constexpr float WEIGHT_AGAIN = 0.1f; +constexpr float WEIGHT_LASER_TWO_BACK = 0.6f; +constexpr int WEIGHT_STREAMS = 25; +constexpr int WEIGHT_STREAMS_FIRST = 175; +constexpr int WEIGHT_STREAMS_AFTER_LASER = 30; +constexpr int WEIGHT_RIGHT_HAND = 12; +constexpr int WEIGHT_LEFT_HAND = 9; +constexpr int WEIGHT_HAND_NEAR = 20; +constexpr float WEIGHT_HAND_TWICE = 0.25f; +constexpr int WEIGHT_SMASH = 20; +constexpr int WEIGHT_SMASH_AFTER_LASER = 40; +constexpr int WEIGHT_SUMMON = 8; +constexpr int WEIGHT_SUMMON_PER_ENEMY = 4; +constexpr float WEIGHT_SUMMON_FAR = 1.5f; +constexpr int WEIGHT_BOTH_HANDS = 15; +constexpr int WEIGHT_BOTH_HANDS_AFTER_STREAMS = 30; +constexpr int WEIGHT_SECOND_FORM = 100000; +constexpr uint32_t HAND_PICK_ROLL = 10; +constexpr uint32_t HAND_PICK_RIGHT = 5; +constexpr uint32_t SMASH_PICKS = 3; + +// The laser: a 40 frame brimstone straight down from 40 below him, drawn over everything. +constexpr int MEGA_LASER_VARIANT = 6; +constexpr float MEGA_LASER_ANGLE = 90; +constexpr int MEGA_LASER_TIMEOUT = 40; +static const Vector MEGA_LASER_OFFSET = vector_make(0, 40); +constexpr float MEGA_LASER_DEPTH = 10000; +constexpr float CHARGE_VOLUME = 1.2f; +constexpr float CHARGE_VOLUME_STREAMS = 0.5f; +constexpr int CHARGE_DELAY = 60; + +// The streams: rings of 1.8 shots from his mouth (12 down in his second form, 24 for its purple shots, scaled to the +// sprite), floating 5 up, 9 patterns in the first form and 26 in the second, for 150 frames unless a pattern says. +constexpr int FIRST_FORM_PATTERNS = 9; +constexpr int SECOND_FORM_PATTERNS = 26; +constexpr int PATTERN_FIRST = 2; +constexpr int STREAM_DURATION = 150; +constexpr int STREAM_PERIOD = 5; +constexpr int STREAM_HALF_PERIOD = 60; +constexpr float STREAM_SPEED = 6; +constexpr float STREAM_SWEEP_FRAMES = 240; +constexpr float STREAM_HEIGHT = 5; +constexpr float STREAM_SCALE = 1.8f; +constexpr float STREAM_FALL_ACCEL = -0.06f; +constexpr float STREAM_FALL_ACCEL_WIGGLE = -0.085f; +constexpr float STREAM_FALL_SPEED = -2; +constexpr float STREAM_DOT_LIMIT = 0.2f; +static const Vector STREAM_DIRECTION_LIMIT = vector_make(0, 1); +constexpr float SECOND_FORM_MOUTH = 12; +constexpr float SECOND_FORM_MOUTH_PURPLE = 24; +constexpr float SECOND_FORM_MOUTH_SCALE = 1.5384616f; +constexpr int PURPLE_VARIANT = 2; +constexpr float PURPLE_PULSE_RATE = 0.1f; +constexpr int MEGA_SPIT_DELAY_MIN = 30; +constexpr uint32_t MEGA_SPIT_DELAY_RANGE = 40; +constexpr int SLOW_COUNTDOWN_MIN = 3; +constexpr float CURVE_SHADE_MIN = -0.002f; +constexpr float CURVE_SHADE_RANGE = 0.004f; + +// The head smash: 50 shots of 1.5 thrown from 10 up (25 for the third smash, 20 for the fifth), with a shake of 12. +constexpr int SMASH_SHOTS = 50; +constexpr int SMASH_SHOTS_THIRD = 25; +constexpr int SMASH_SHOTS_FIFTH = 20; +constexpr float SMASH_HEIGHT = 10; +constexpr float SMASH_SCALE = 1.5f; +constexpr float SMASH_SPEED = 1.2f; +constexpr int SMASH_SHAKE = 12; +constexpr float SMASH_VOLUME = 0.4f; + +// His summons and waves spread along the room's bottom, 60 in from its walls, kept off players by 40. +constexpr float WAVE_MARGIN = 60; +constexpr float WAVE_PLAYER_GAP = 40; +constexpr uint32_t SUMMON_KINDS = 5; +constexpr int HOLLOW_SEGMENTS = 4; +constexpr int SUPER_SIN = 1; + +// Dying he blasts and kills every other enemy, his projectiles within 1000 gone at once. His second form is untinted +// on its layer 1. +constexpr float DEATH_PITCH = 0.5f; +constexpr int DEATH_SOUND_DELAY = 100; +constexpr float SHOT_CLEAR_REACH = 1000; +constexpr float SECOND_FORM_PITCH = 0.8f; +constexpr int SECOND_FORM_UNTINTED_LAYER = 1; + +// He drifts after his target's x within 90 every 60 frames, between 220 and 420, at 1.2 under friction 0.8. +constexpr int MEGA_DRIFT_PERIOD = 60; +constexpr float MEGA_DRIFT_SPREAD = 180; +constexpr float MEGA_DRIFT_LEFT = 220; +constexpr float MEGA_DRIFT_RIGHT = 420; +constexpr float MEGA_DRIFT_SPEED = 1.2f; +constexpr float MEGA_DRIFT_ARRIVED = 20; +constexpr float MEGA_DRIFT_STEER = 0.1f; +constexpr float MEGA_FRICTION = 0.8f; + +// A hand rests between its spot and one 35 across and 120 (110 for the right) down as its target comes within 70 +// past 260 below him. It hurts him 100 when it dies. +static const Vector LEFT_HAND_NEAR = vector_make(-35, 120); +static const Vector RIGHT_HAND_NEAR = vector_make(35, 110); +constexpr float HAND_NEAR_START = 260; +constexpr float HAND_NEAR_SPAN = 70; +constexpr float HAND_DEATH_DAMAGE = 100; +constexpr int HAND_DEATH_COUNTDOWN = 30; +constexpr int HAND_RENDER_Z = -1200; + +// A hand's smash: a 120 shockwave (320 for the quake, which follows its target within 150), bomb damage 50, a shake +// of 15 (10), a ripple through the room, and friction cut to a tenth. +constexpr float HAND_SMASH_DAMAGE = 50; +constexpr float HAND_SHOCKWAVE_REACH = 120; +constexpr float QUAKE_SHOCKWAVE_REACH = 320; +constexpr int HAND_SHOCKWAVE_FRAMES = 20; +constexpr int QUAKE_SHOCKWAVE_FRAMES = 50; +constexpr int HAND_SMASH_SHAKE = 15; +constexpr int QUAKE_SHAKE = 10; +constexpr float QUAKE_FOLLOW = 150; +constexpr float QUAKE_VOLUME = 0.5f; +constexpr float QUAKE_VOLUME_RANGE = 0.4f; +constexpr float SMASH_FRICTION = 0.1f; +constexpr float MEGA_RIPPLE_AMPLITUDE = 0.05f; +constexpr float MEGA_RIPPLE_SPEED = 0.025f; +constexpr int MEGA_RIPPLE_FRAMES = 25; +constexpr int QUAKE_LOOPS = 3; + +// A hand moves at 0.5 toward its spot, at 5 at most, its friction easing from 0.5 to 1 between 5 and 30 away. +constexpr float HAND_PUSH = 0.5f; +constexpr float HAND_MAX_SPEED = 5; +constexpr float HAND_EASE_START = 5; +constexpr float HAND_EASE_SPAN = 25; +constexpr float HAND_FRICTION_MIN = 0.5f; + +// One pattern of his streams: each stream fires a ring every period frames from its offset, turning by its angle +// step, curving by its strength. halfPeriod paces the sweeping patterns. +struct StreamPattern +{ + std::array angleSteps{}; + std::array curving{}; + std::array offsets{}; + float speed = STREAM_SPEED; + int duration = STREAM_DURATION; + int halfPeriod = STREAM_HALF_PERIOD; + int period = STREAM_PERIOD; + int ringCount = 0; + int streams = 1; +}; + +// His hands, found anew each frame. +struct MegaSatanHands +{ + Entity_NPC* left = nullptr; + Entity_NPC* right = nullptr; +}; + +// A wave or summon to spread along the room's bottom: what to spawn, how many make up the row and which one this is. +struct WaveSpawn +{ + int type = 0; + int variant = 0; + int count = 1; + int index = 0; +}; + +// One byte of i1. +static int i1_byte(const Entity_NPC& npc, int index) +{ + return npc.i1 >> (index * 8) & 0xff; +} + +// Sets one byte of i1. +static void i1_byte_set(Entity_NPC& npc, int index, int value) +{ + npc.i1 = (int)(((uint32_t)npc.i1 & ~(0xffu << (index * 8))) | (uint32_t)(value & 0xff) << (index * 8)); +} + +// The attack before the last, kept as v2.x's bits. +static int attack_before_get(const Entity_NPC& npc) +{ + return std::bit_cast(npc.v2.x); +} + +// The colorize of a shot's color. +static void colorize_set(ColorMod& color, float red, float green, float blue, float amount) +{ + color._colorize[0] = red; + color._colorize[1] = green; + color._colorize[2] = blue; + color._colorize[3] = amount; +} + +// The first NPC of a type and variant in the room. +static Entity_NPC* npc_find(int type, int variant) +{ + std::vector found = entity_query(type, variant); + return found.empty() ? nullptr : dynamic_cast(found.front()); +} + +// The smooth step from 0 to 1 a rise or a fall eases along, and its slope. +static float smooth_step(float t) +{ + return (3 - (t + t)) * t * t; +} + +// The animation's frame, -1 without one. +static int anim_frame_get(const Entity_NPC& npc) +{ + return npc.sprite.animState.animData ? (int)std::floor(npc.sprite.animState.animFrame) : -1; +} + +// Moves him between the focus point and his spot along the smooth step of t, his velocity its slope. +static void mega_glide(Entity_NPC& npc, Vector from, Vector to, float t) +{ + float s = smooth_step(t); + float slope = t * -SMOOTH_SLOPE * (t - 1); + + npc.pos = vector_make((to.x - from.x) * s + from.x, (to.y - from.y) * s + from.y); + npc.velocity = vector_make((to.x - from.x) / RISE_FRAMES * slope, (to.y - from.y) / RISE_FRAMES * slope); +} + +// The enemies he counts before summoning (not his own, Dark Esau or friends) and the summon's weight they leave. +static int enemies_count(int& summonWeight) +{ + int count = 0; + + summonWeight = WEIGHT_SUMMON; + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isRival = g_game->deathmatchManager.is_active() && entity->type == ENTITY_PLAYER; + if (!isRival && (uint32_t)(entity->type - 10) >= 990) continue; + if (!entity->CanShutDoors() || entity->type == ENTITY_DARK_ESAU || entity->HasEntityFlags(FLAG_FRIENDLY)) + continue; + if (entity->type == ENTITY_MEGA_SATAN || entity->type == ENTITY_MEGA_SATAN_2) continue; + + count++; + summonWeight -= entity->type == ENTITY_LARRYJR ? 1 : WEIGHT_SUMMON_PER_ENEMY; + } + summonWeight = std::max(summonWeight, 0); + return count; +} + +// Spawns one of a wave or summon along the room's bottom, kept off the nearest player. +static Entity* wave_spawn(Entity_NPC& npc, const WaveSpawn& spawn) +{ + Room& room = *g_game->room; + float left = room.topLeftPos.x + WAVE_MARGIN; + float right = room.bottomRightPos.x - WAVE_MARGIN; + float t = std::clamp((float)spawn.index / (float)std::max(spawn.count - 1, 1), 0.0f, 1.0f); + Vector spot = room_free_pickup_position_find({.position = vector_make((right - left) * t + left, + room.bottomRightPos.y - WAVE_MARGIN)}); + Entity_Player* player = game_nearest_player(spot); + EntityConfig_Entity* config = g_manager->entityConfig.GetEntity(spawn.type, spawn.variant, 0); + float radius = std::max(config->collisionRadiusMulti.x, config->collisionRadiusMulti.y) * config->collisionRadius + + player->size + WAVE_PLAYER_GAP; + + if (vector_length_squared(vector_sub(spot, player->pos)) < radius * radius) + spot = room_free_pickup_position_find({.position = player->pos, .step = radius}); + return g_game->Spawn({.position = spot, .spawner = &npc, .type = spawn.type, .variant = spawn.variant, + .seed = Random()}); +} + +// Plays a sound of his at his size's pitch through the fart seeds. +static void mega_sound_play(Entity_NPC& npc, int sound, float volume, int delay) +{ + npc_sound_play(sound, volume, delay, champion_pitch_get(npc)); +} + +// 004cca10 (part) A hand dying hurts him 100, once. +static void hand_death_check(Entity_NPC& hand, Entity_NPC* body) +{ + if (!hand.isDead || hand.stateFrame == HAND_DEAD_MARK) return; + + mega_sound_play(hand, SOUND_SATAN_HURT, 1, 2); + if (body) body->TakeDamage(HAND_DEATH_DAMAGE, 0, EntityRef(&hand), HAND_DEATH_COUNTDOWN); + hand.stateFrame = HAND_DEAD_MARK; +} + +// A hand's resting spot: between its own and the near one by how far below him its target is, or its own while he +// fires his laser, or with no other hand the near one straight below. +static void hand_rest_spot_set(Entity_NPC& hand, Entity_NPC& body, Entity_NPC* other) +{ + bool isLeft = hand.variant == MEGA_SATAN_LEFT_HAND; + Vector far = isLeft ? LEFT_HAND_SPOT : RIGHT_HAND_SPOT; + Vector near = isLeft ? LEFT_HAND_NEAR : RIGHT_HAND_NEAR; + + if (!other) near.x = 0; + float t = std::clamp((hand.GetPlayerTarget()->pos.y - body.pos.y - HAND_NEAR_START) / HAND_NEAR_SPAN, 0.0f, 1.0f); + hand.targetPosition = vector_make((near.x - far.x) * t + far.x, (near.y - far.y) * t + far.y); + if (body.state == MEGA_LASER) hand.targetPosition = far; + hand.targetPosition = vector_add(body.pos, hand.targetPosition); +} + +// A hand's smash lands: the shockwave, bomb damage and a ripple through the room. +static void hand_smash_land(Entity_NPC& hand, int variant, float reach, int frames) +{ + hand.targetPosition = hand.pos; + hand.friction *= SMASH_FRICTION; + + auto* wave = static_cast(g_game->Spawn({.position = hand.pos, .spawner = &hand, + .type = ENTITY_EFFECT, .variant = variant, + .seed = Random()})); + wave->parent = &hand; + wave->minRadius = hand.size; + wave->maxRadius = reach; + wave->timeout = frames; + wave->lifespan = frames; +} + +// The hand's smash and quake. +static void hand_smash_damage(Entity_NPC& hand) +{ + explosion_damage({.position = hand.pos, .source = &hand, .damage = HAND_SMASH_DAMAGE, .radius = hand.size, + .isLineCheck = false}); + shockwave_make(hand.pos, MEGA_RIPPLE_AMPLITUDE, MEGA_RIPPLE_SPEED, MEGA_RIPPLE_FRAMES); +} + +// 004cca10 NpcAI::ENTITY_MEGA_SATAN_hand: one of his hands (variant 1 left, 2 right). It rests below him, smashes where +// its target was, quakes (both together), hides and reveals with him and raises itself while he summons. It hurts +// him when it dies. +void boss_mega_satan_hand_update(Entity_NPC& hand) +{ + Entity_NPC* body = npc_find(ENTITY_MEGA_SATAN, MEGA_SATAN_BODY); + Entity_NPC* other = npc_find(ENTITY_MEGA_SATAN, 3 - hand.variant); + + hand_death_check(hand, body); + if (hand.state == NPC_STATE_INIT) + { + hand.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + hand.renderZOffset = HAND_RENDER_Z; + hand.targetPosition = hand.pos; + hand.entityGridCollisionClass = GRIDCOLL_WALLS; + if (hand.variant == MEGA_SATAN_RIGHT_HAND) hand.sprite.isFlipX = true; + hand.ClearEntityFlags(FLAG_APPEAR); + hand.isVisible = false; + hand.state = MEGA_RISE; + } + if (hand.state == MEGA_RISE) + { + hand.isInvincible = true; + hand.entityCollisionClass = ENTCOLL_NONE; + if (hand.sprite.IsFinished("Appear")) + { + hand.state = NPC_STATE_IDLE; + hand.isInvincible = false; + hand.entityCollisionClass = ENTCOLL_ALL; + } + if (body && body->state != NPC_STATE_APPEAR && body->isVisible) + { + hand.isVisible = true; + hand.sprite.Play("Appear"); + } + } + else if (body && body->state == MEGA_HIDE && hand.state != MEGA_HIDE) + { + hand.state = MEGA_HIDE; + hand.stateFrame = 0; + } + if (hand.state == NPC_STATE_IDLE) + { + if (body) hand_rest_spot_set(hand, *body, other); + hand.sprite.Play("Idle"); + } + + if (hand.state == HAND_SMASH) + { + hand.sprite.Play("SmashHand1"); + if (hand.stateFrame == 0) hand.targetPosition = hand.GetPlayerTarget()->pos; + hand.entityCollisionClass = hand.sprite.WasEventTriggered("Smash") ? ENTCOLL_ALL : ENTCOLL_NONE; + if (hand.sprite.IsEventTriggered("Smash")) + { + game_shake_screen(HAND_SMASH_SHAKE); + hand_smash_land(hand, EFFECT_SHOCKWAVE, HAND_SHOCKWAVE_REACH, HAND_SHOCKWAVE_FRAMES); + mega_sound_play(hand, SOUND_HELLBOSS_GROUNDPOUND, 1, 2); + hand_smash_damage(hand); + } + hand.stateFrame++; + if (npc_anim_is_done(hand)) + { + hand.state = NPC_STATE_IDLE; + if (body) body->stateFrame = 0; + hand.stateFrame = 0; + } + } + + if (hand.state == HAND_QUAKE) + { + if (body) + { + hand.targetPosition = + vector_add(body->pos, hand.variant == MEGA_SATAN_LEFT_HAND ? LEFT_HAND_SPOT : RIGHT_HAND_SPOT); + Vector target = hand.GetPlayerTarget()->pos; + bool isNear = vector_length(vector_sub(target, hand.targetPosition)) < QUAKE_FOLLOW; + if (isNear && !hand.sprite.WasEventTriggered("Smash") && hand.stateFrame >= 0) hand.targetPosition = target; + } + if (hand.stateFrame >= 0) + { + hand.sprite.Play("SmashQuake"); + hand.entityCollisionClass = hand.sprite.WasEventTriggered("Smash") ? ENTCOLL_ALL : ENTCOLL_NONE; + } + if (hand.sprite.IsEventTriggered("Smash")) + { + game_shake_screen(QUAKE_SHAKE); + hand_smash_land(hand, EFFECT_SHOCKWAVE_DIRECTIONAL, QUAKE_SHOCKWAVE_REACH, QUAKE_SHOCKWAVE_FRAMES); + hand.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, random_unit() * QUAKE_VOLUME_RANGE + QUAKE_VOLUME, 2, false, 1); + hand_smash_damage(hand); + } + + int length = hand.sprite.animState.GetAnimationLength(); + bool isLastFrame = !hand.sprite.animState.animData || anim_frame_get(hand) == length - 1; + if (hand.stateFrame >= length * QUAKE_LOOPS - QUAKE_LOOPS && isLastFrame) + { + hand.state = NPC_STATE_IDLE; + hand.stateFrame = 0; + if (body) body->stateFrame = 0; + hand.sprite.Play("Idle"); + } + hand.stateFrame++; + } + + if (hand.state == MEGA_HIDE) + { + hand.isInvincible = true; + hand.entityCollisionClass = ENTCOLL_NONE; + if (body) + hand.targetPosition = + vector_add(body->pos, hand.variant == MEGA_SATAN_LEFT_HAND ? LEFT_HAND_NEAR : RIGHT_HAND_NEAR); + if (hand.stateFrame == 0) + { + hand.sprite.Play("Hide"); + if (npc_anim_is_done(hand)) hand.stateFrame = 1; + } + if (hand.stateFrame == 1) + { + hand.sprite.Play("Hiding"); + if (body && body->state != MEGA_HIDE) hand.stateFrame = 2; + } + if (hand.stateFrame == 2) + { + hand.sprite.Play("Reveal"); + if (npc_anim_is_done(hand)) + { + hand.state = NPC_STATE_IDLE; + hand.isInvincible = false; + hand.entityCollisionClass = ENTCOLL_ALL; + } + } + } + else if (hand.state == MEGA_SUMMON) + { + hand.sprite.Play("Summon"); + if (npc_anim_is_done(hand)) hand.state = NPC_STATE_IDLE; + hand.entityCollisionClass = ENTCOLL_ALL; + } + + if (vector_is_zero(hand.targetPosition)) return; + Vector toward = vector_sub(hand.targetPosition, hand.pos); + float distance = vector_length(toward); + + hand.friction = std::clamp((distance - HAND_EASE_START) / HAND_EASE_SPAN, 0.0f, 1.0f) * HAND_FRICTION_MIN + + HAND_FRICTION_MIN; + Vector push = distance > HAND_PUSH ? vector_scale(toward, HAND_PUSH / distance) : toward; + if (hand.friction != 0) + hand.velocity = vector_add(hand.velocity, vector_scale(push, hand.speedMultiplier / hand.friction)); + if (vector_length(hand.velocity) > HAND_MAX_SPEED) hand.velocity = vector_resized(hand.velocity, HAND_MAX_SPEED); +} + +// The pattern of his streams: its rings, their speed, turn and curve, how often each stream fires and for how long. +// The second form's versions of the first's patterns are faster. Patterns 15 to 17 change over their 240 frames. +static StreamPattern stream_pattern_get(const Entity_NPC& npc, int kind) +{ + bool isSecond = npc.type == ENTITY_MEGA_SATAN_2; + float sweep = std::clamp((float)npc.stateFrame / STREAM_SWEEP_FRAMES, 0.0f, 1.0f); + StreamPattern p; + + switch (kind) + { + case 2: + p = {.angleSteps = {0.020943951f, 0.010471975f}, .offsets = {0, isSecond ? 6 : 5}, .ringCount = 6, + .streams = 2}; + p.period = isSecond ? 12 : 10; + if (isSecond) p.speed = 9; + break; + case 3: + p = {.angleSteps = {0.015707964f, -0.015707964f}, .offsets = {0, isSecond ? 5 : 4}, .ringCount = 5, + .streams = 2}; + p.period = isSecond ? 10 : 8; + if (isSecond) p.speed = 9; + break; + case 4: + p = {.angleSteps = {0.14660765f}, .period = 2, .ringCount = 3}; + if (isSecond) p.speed = 9; + break; + case 5: + p = {.angleSteps = {isSecond ? 0.41887903f : 0.62831855f}, .speed = isSecond ? 14.400001f : 12, + .ringCount = 6}; + p.period = isSecond ? 4 : 2; + break; + case 6: + p = {.angleSteps = {isSecond ? 0.52359879f : 0.62831855f}, .speed = isSecond ? 10.8f : 9, .halfPeriod = 90, + .ringCount = 8}; + p.period = isSecond ? 4 : 2; + break; + case 7: + p = {.angleSteps = {isSecond ? 0.62831855f : 0.52359879f}, .speed = isSecond ? 9.6f : 8, .halfPeriod = 120, + .ringCount = 9}; + p.period = isSecond ? 4 : 2; + break; + case 8: + p = {.angleSteps = {isSecond ? 0.73303831f : 0.41887903f}, .speed = isSecond ? 8.400001f : 7, + .halfPeriod = 120, .ringCount = 12}; + p.period = isSecond ? 4 : 2; + break; + case 9: + p = {.angleSteps = {0.0023038348f, 0.0023038348f, 0.0023038348f}, + .offsets = isSecond ? std::array{0, 5, 10} : std::array{0, 3, 6}, + .speed = isSecond ? 12.0f : 8.0f, + .period = isSecond ? 30 : 20, + .ringCount = isSecond ? 20 : 30, + .streams = 3}; + break; + case 10: + p = {.angleSteps = {0.012566371f}, .speed = 4, .period = isSecond ? 25 : 30, .ringCount = 10}; + break; + case 11: + p = {.angleSteps = {0.0010471976f, 0.0010471976f}, .curving = {0.002f, 0.002f}, .offsets = {0, 10}, + .speed = 3, .duration = 240, .period = 20, .ringCount = 20, .streams = 2}; + break; + case 12: + p = {.angleSteps = {-0.0052359877f, 0.0052359877f}, .curving = {0.003f, 0.003f}, .speed = 3, + .duration = 240, .period = 20, .ringCount = 14, .streams = 2}; + break; + case 13: + p = {.angleSteps = {-0.0020943952f, -0.0020943952f}, .curving = {0.0035f, 0.0035f}, .offsets = {0, 10}, + .speed = 3, .duration = 240, .period = 12, .ringCount = 20, .streams = 2}; + break; + case 14: + p = {.curving = {0.0035f, 0.0035f}, .offsets = {0, 5}, .speed = 4, .period = 10, .ringCount = 10, + .streams = 2}; + break; + case 15: + { + float curve = 0.0035f / (1 - sweep * 0.6f); + p = {.curving = {curve, curve}, .offsets = {0, 3}, .speed = 7, .duration = 240, .period = 6, + .ringCount = 10, .streams = 2}; + break; + } + case 16: + { + float curve = std::cos(sweep * 12.566371f + 0) * 0.0035f; + p = {.curving = {curve, curve}, .offsets = {0, 5}, .speed = 5, .duration = 240, .period = 10, + .ringCount = 8, .streams = 2}; + break; + } + case 17: + { + float turn = sweep * (2 * PI_F) + 0; + float cosine = std::cos(turn); + p = {.curving = {std::sin(turn) * 0.007f}, .speed = (cosine * cosine * 0.19999999f + 0.8f) * 8, + .duration = 240, .period = 2, .ringCount = 6}; + break; + } + case 18: p = {.angleSteps = {0.0062831854f}, .speed = 3, .period = 12, .ringCount = 10}; break; + case 19: + p = {.angleSteps = {0.50265485f}, .speed = 5, .duration = 240, .halfPeriod = 120, .period = 3, + .ringCount = 6}; + break; + case 20: p = {.speed = 3, .period = 50, .ringCount = 25}; break; + case 21: p = {.angleSteps = {0.034903094f}, .ringCount = 3}; break; + case 22: + p = {.angleSteps = {0.39269909f}, .speed = 9, .duration = 120, .halfPeriod = 120, .ringCount = 6}; + break; + case 23: + p = {.offsets = {0, 10}, .speed = 9, .halfPeriod = 120, .period = 20, .ringCount = 5, .streams = 2}; + break; + case 24: p = {.angleSteps = {1.5707964f}, .speed = 5, .halfPeriod = 61, .period = 2, .ringCount = 4}; break; + case 25: + p = {.angleSteps = {0.39269909f, 0.39269909f}, .offsets = {0, 18}, .speed = 5, .halfPeriod = 36, + .period = 36, .ringCount = 20, .streams = 2}; + break; + case 26: p = {.speed = 5, .period = 10, .ringCount = 15}; break; + case 27: p = {.speed = 5, .halfPeriod = 150, .ringCount = 10}; break; + default: p = {.period = 10, .ringCount = 6}; break; + } + return p; +} + +// Fires one stream's ring: turned by the pattern (steadily, sweeping, in steps, or on a wave), curving, bursting or +// wiggling as the pattern says and shaded to match, purple in the second form's plain patterns. +static void stream_fire(Entity_NPC& npc, const StreamPattern& p, int kind, int stream) +{ + ProjectileParams params; + uint64_t flags = params.bulletFlags | PROJECTILE_HIT_ENEMIES; + float frame = (float)npc.stateFrame; + float step = p.angleSteps[stream]; + float wave = std::cos(frame * (2 * PI_F) / (float)p.halfPeriod) * step; + + params.heightModifier = STREAM_HEIGHT; + params.scale = STREAM_SCALE; + params.fallingAccelModifier = STREAM_FALL_ACCEL; + params.fallingSpeedModifier = STREAM_FALL_SPEED; + params.fireDirectionLimit = STREAM_DIRECTION_LIMIT; + params.dotProductLimit = STREAM_DOT_LIMIT; + if (kind <= 4) params.circleAngle = frame * step; + else if (kind <= 8) + { + int half = p.halfPeriod / 2; + params.circleAngle = (float)std::abs(npc.stateFrame % p.halfPeriod - half) * step / (float)half; + } + else if (kind == 9) params.circleAngle = (float)(npc.stateFrame - npc.stateFrame % p.period) * step; + else if (kind == 10) + { + params.circleAngle = frame * step; + flags |= PROJECTILE_BURST; + } + else if (kind <= 17) + { + params.circleAngle = frame * step; + flags |= stream % 2 == 0 ? PROJECTILE_CURVE_RIGHT : PROJECTILE_CURVE_LEFT; + params.curvingStrength = p.curving[stream]; + if (kind == 14) flags |= PROJECTILE_MEGA_WIGGLE; + if (kind != 15 && kind != 17) params.fallingAccelModifier = STREAM_FALL_ACCEL_WIGGLE; + } + else if (kind <= 20) + { + params.circleAngle = kind == 19 ? wave : step * frame; + params.fallingAccelModifier = STREAM_FALL_ACCEL_WIGGLE; + flags |= PROJECTILE_MEGA_WIGGLE; + } + else if (kind <= 23) + { + params.circleAngle = step * frame; + if (kind != 21) + { + params.circleAngle = wave; + if (stream % 2 == 0) params.circleAngle += PI_F / (float)p.ringCount; + } + params.fallingAccelModifier = STREAM_FALL_ACCEL_WIGGLE; + flags |= PROJECTILE_SAWTOOTH_WIGGLE; + } + else if (kind == 24) + { + params.circleAngle = wave; + params.fallingAccelModifier = STREAM_FALL_ACCEL_WIGGLE; + } + else if (kind <= 27) + { + if (kind == 25) params.circleAngle = wave; + if (kind != 25 || stream != 1) flags |= PROJECTILE_SINE_VELOCITY; + if (kind == 27) flags |= PROJECTILE_MEGA_WIGGLE; + } + + if (flags & PROJECTILE_BURST) colorize_set(params.color, 1, 0.4f, 0, 1); + if (flags & PROJECTILE_MEGA_WIGGLE) colorize_set(params.color, 2, 2, 2, 1); + if (flags & PROJECTILE_SINE_VELOCITY) colorize_set(params.color, 0.6f, 0.6f, 0.6f, 1); + if (flags & PROJECTILE_SAWTOOTH_WIGGLE) colorize_set(params.color, 2, 2, 2, 1); + if (flags & (PROJECTILE_CURVE_LEFT | PROJECTILE_CURVE_RIGHT)) + { + float curve = (flags & PROJECTILE_CURVE_RIGHT) ? -params.curvingStrength : params.curvingStrength; + colorize_set(params.color, 0.6f, 0.6f, 0.6f, + std::clamp((curve - CURVE_SHADE_MIN) / CURVE_SHADE_RANGE, 0.0f, 1.0f) + 0); + } + params.bulletFlags = flags; + + bool isSecond = npc.type == ENTITY_MEGA_SATAN_2; + bool isPlain = flags == PROJECTILE_HIT_ENEMIES && kind != 2 && kind != 3 && kind != 25; + if (kind == 17 || (isSecond && isPlain)) + { + params.variant = PURPLE_VARIANT; + colorize_set(params.color, 1, std::sin(frame * PURPLE_PULSE_RATE) * 0.75f + 0.5f, 0, 0.8f); + } + + float drop = 0; + if (isSecond) + { + drop = SECOND_FORM_MOUTH; + if (params.variant == PURPLE_VARIANT) + { + drop = SECOND_FORM_MOUTH_PURPLE; + params.isRenderedAtGround = true; + } + drop *= SECOND_FORM_MOUTH_SCALE; + } + npc.FireProjectiles(vector_make(npc.pos.x + 0, drop + npc.pos.y), vector_make(p.speed, (float)p.ringCount), + PROJECTILES_RING, params); +} + +// The idle animation of his form: "Idle", or the second form's by how hurt it is. +static const char* idle_anim_get(const Entity_NPC& npc, const char* first, const char* second, const char* third) +{ + if (npc.health > (npc.maxHitPoints + npc.maxHitPoints) / 3) return first; + return npc.health > npc.maxHitPoints / 3 ? second : third; +} + +// His room's floor opening: once a player walks up past 540 on the open floor its intro plays with his music. While +// it plays the screen shakes and the players are held. After it the floor closes and he appears. +static void floor_intro_update(Entity_NPC& npc) +{ + ANM2& floor = g_game->room->backdrop.floorSprite; + const AnimationData* shown = floor.animState.animData; + if (!shown) return; + + bool isIntro = shown->name == "Intro"; + if (floor.animState.isPlaying) + { + if (!isIntro) return; + game_shake_screen(INTRO_SHAKE); + for (Entity_Player* player : g_game->playerManager.playerList) player->isControlsEnabled = false; + return; + } + if (isIntro) + { + floor.Play("Idle2", PLAY_FORCED); + for (Entity_Player* player : g_game->playerManager.playerList) player->isControlsEnabled = true; + npc.sprite.Play("Appear"); + npc.isVisible = true; + return mega_sound_play(npc, SOUND_SATAN_GROW, 1, 2); + } + if (shown->name != "Idle1") return; + + for (size_t i = 0; i < g_game->playerManager.playerList.size(); i++) + { + Entity_Player& player = *g_game->GetPlayer((int)i); + if (player.variant != 0 || player.pos.y >= INTRO_TRIGGER_Y) continue; + + floor.Play("Intro"); + mega_sound_play(npc, SOUND_SATAN_APPEAR, 1, 2); + return g_manager->musicManager.Crossfade(MUSIC_SATAN_BOSS, INTRO_MUSIC_FADE); + } +} + +// Rising: the second form rises from below over the last 15 frames of "Appear", shaking the screen before. He takes +// his place once "Appear" ends. +static void rise_update(Entity_NPC& npc) +{ + npc.isInvincible = true; + npc.entityCollisionClass = ENTCOLL_NONE; + if (npc.type == ENTITY_MEGA_SATAN_2) + { + float end = (float)(npc.sprite.animState.animData ? npc.sprite.animState.GetAnimationLength() : 0); + float start = end - RISE_FRAMES; + int frame = anim_frame_get(npc); + + if (start == end) log_printf(LOG_ASSERT, "Start and End parameters cannot be the same!"); + mega_glide(npc, MEGA_FOCUS, npc.targetPosition, std::clamp(((float)frame - start) / (end - start), 0.0f, 1.0f)); + if ((float)frame < start) + { + game_shake_screen(RISE_SHAKE); + g_game->room->camera->SetFocusPosition(MEGA_FOCUS); + } + } + floor_intro_update(npc); + if (npc.type == ENTITY_MEGA_SATAN && npc.sprite.IsPlaying("Appear")) + g_game->room->camera->SetFocusPosition(MEGA_FOCUS); + if (!npc.sprite.IsFinished("Appear")) return; + + npc.state = NPC_STATE_IDLE; + npc.isInvincible = false; + npc.entityCollisionClass = ENTCOLL_ALL; +} + +// Picks his next attack by the weights his last two attacks, his target's place, his hands and the enemies about set. +// The second form only ever fires its streams. +static void attack_pick(Entity_NPC& npc, MegaSatanHands& hands, int summonWeight) +{ + Entity* target = npc.GetPlayerTarget(); + float distance = vector_length(vector_sub(npc.pos, target->pos)); + int last = npc.i2; + int before = attack_before_get(npc); + int laser = 0; + + if (std::abs(target->pos.x - npc.pos.x) < LASER_REACH_ACROSS) + { + laser = distance > FAR_REACH ? WEIGHT_LASER_FAR : WEIGHT_LASER; + if (distance < NEAR_REACH) laser += WEIGHT_LASER_NEAR; + if (last == ATTACK_HANDS) laser += WEIGHT_LASER_AFTER_HANDS; + if (last == MEGA_SMASH) laser += WEIGHT_AFTER_SMASH; + if (last == MEGA_LASER) laser = (int)((float)laser * WEIGHT_AGAIN); + if (before == MEGA_LASER) laser = (int)((float)laser * WEIGHT_LASER_TWO_BACK); + if (last == ATTACK_NONE) laser = 0; + } + + int streams = last != ATTACK_NONE ? WEIGHT_STREAMS : WEIGHT_STREAMS_FIRST; + if (last == MEGA_LASER) streams += WEIGHT_STREAMS_AFTER_LASER; + if (last == MEGA_SMASH) streams += WEIGHT_STREAMS_AFTER_LASER; + if (last == MEGA_STREAMS) streams = (int)((float)streams * WEIGHT_AGAIN); + if (before == MEGA_STREAMS) streams = (int)((float)streams * WEIGHT_AGAIN); + + int hand = (hands.right ? WEIGHT_RIGHT_HAND : 0) + (hands.left ? WEIGHT_LEFT_HAND : 0); + if ((hands.right || hands.left) && distance < HAND_REACH) hand += WEIGHT_HAND_NEAR; + + int smash = WEIGHT_SMASH; + if (before == ATTACK_HAND && last == ATTACK_HAND) hand = (int)((float)hand * WEIGHT_HAND_TWICE); + else + { + smash = last == MEGA_LASER ? WEIGHT_SMASH_AFTER_LASER : WEIGHT_SMASH; + if (last == MEGA_SMASH) smash = (int)((float)smash * WEIGHT_AGAIN); + } + if (distance > FAR_REACH) summonWeight = (int)((float)summonWeight * WEIGHT_SUMMON_FAR); + int both = last == MEGA_STREAMS ? WEIGHT_BOTH_HANDS_AFTER_STREAMS : WEIGHT_BOTH_HANDS; + if (!hands.right || !hands.left) both = 0; + + std::array limits = {laser, laser + streams, laser + streams + hand, 0, 0, 0}; + limits[3] = limits[2] + smash; + limits[4] = limits[3] + summonWeight; + limits[5] = limits[4] + both; + if (npc.type == ENTITY_MEGA_SATAN_2) limits = {0, WEIGHT_SECOND_FORM, WEIGHT_SECOND_FORM, WEIGHT_SECOND_FORM, + WEIGHT_SECOND_FORM, WEIGHT_SECOND_FORM}; + int roll = limits[5] != 0 ? (int)(Random() % (uint32_t)limits[5]) : 0; + + npc.v2.x = std::bit_cast(npc.i2); + if (roll < limits[0]) + { + npc.state = MEGA_LASER; + npc.stateFrame = 0; + i1_byte_set(npc, I1_STEP, 0); + npc.i2 = MEGA_LASER; + } + else if (roll < limits[1]) + { + npc.state = MEGA_STREAMS; + npc.stateFrame = 0; + i1_byte_set(npc, I1_STEP, npc.type == ENTITY_MEGA_SATAN_2 ? 1 : 0); + npc.i2 = MEGA_STREAMS; + } + else if (roll < limits[2]) + { + Entity_NPC* chosen = Random() % HAND_PICK_ROLL <= HAND_PICK_RIGHT ? hands.right : hands.left; + if (!chosen) chosen = hands.right ? hands.right : hands.left; + if (chosen) + { + chosen->state = HAND_SMASH; + chosen->stateFrame = 0; + npc.PlaySound(SOUND_SATAN_BLAST, 0.6f, 2, false, 1); + } + npc.i2 = ATTACK_HAND; + } + else if (roll < limits[3]) + { + npc.state = MEGA_SMASH; + i1_byte_set(npc, I1_STEP, (int)(Random() % SMASH_PICKS) * 2 + 1); + npc.stateFrame = 0; + npc.i2 = MEGA_SMASH; + } + else if (roll < limits[4]) + { + npc.state = MEGA_SUMMON; + npc.stateFrame = 0; + i1_byte_set(npc, I1_STEP, 0); + for (Entity_NPC* each : {hands.right, hands.left}) + if (each) each->state = MEGA_SUMMON; + npc.i2 = MEGA_SUMMON; + } + else if (roll < limits[5]) + { + if (hands.right) + { + hands.right->stateFrame = 0; + hands.right->state = HAND_QUAKE; + } + if (hands.left) + { + hands.left->stateFrame = QUAKE_LEFT_DELAY; + hands.left->state = HAND_QUAKE; + } + npc.PlaySound(SOUND_SATAN_GROW, 1, 2, false, 1); + npc.i2 = ATTACK_HANDS; + } +} + +// Idle he waits, blowing his nose now and then, and every 30 frames may pick an attack once his hands are at rest +// (or hiding) and, in his second form, few of his shots are about. +static void idle_update(Entity_NPC& npc, MegaSatanHands& hands, int summonWeight) +{ + uint32_t noseOdds = npc.health < npc.maxHitPoints * 0.5f ? NOSE_ODDS_HURT : NOSE_ODDS; + const AnimationState& anim = npc.sprite.animState; + + if (anim.animData && anim.isPlaying && anim.animData->name == "Idle" && anim_frame_get(npc) == 0 && + Random() % noseOdds == 0 && npc.type == ENTITY_MEGA_SATAN) + npc.sprite.Play("NoseBlow"); + if (!npc.sprite.IsPlaying("NoseBlow")) + npc.sprite.Play(npc.type == ENTITY_MEGA_SATAN ? "Idle" : idle_anim_get(npc, "Idle1", "Idle2", "Idle3")); + + bool isHandsReady = true; + if (hands.right && hands.right->state != NPC_STATE_IDLE) isHandsReady = hands.right->state == MEGA_HIDE; + if (hands.left && hands.left->state != NPC_STATE_IDLE && hands.left->state != MEGA_HIDE) isHandsReady = false; + bool isCalm = npc.type != ENTITY_MEGA_SATAN_2 || + entity_query_radius(npc.pos, SECOND_FORM_CROWD_REACH, QUERY_PROJECTILES).size() <= SECOND_FORM_CROWD; + if (!isHandsReady || !isCalm) return; + + if (npc.stateFrame < 1 || npc.stateFrame % ATTACK_PERIOD != 0 || Random() % ATTACK_ROLL >= ATTACK_CHANCE) + npc.stateFrame++; + else attack_pick(npc, hands, summonWeight); +} + +// The laser: he charges, then fires a brimstone straight down. +static void laser_update(Entity_NPC& npc) +{ + if (i1_byte(npc, I1_STEP) == 0) + { + npc.sprite.Play("Charging"); + mega_sound_play(npc, SOUND_SATAN_CHARGE_UP, CHARGE_VOLUME, CHARGE_DELAY); + if (npc_anim_is_done(npc)) i1_byte_set(npc, I1_STEP, 1); + return; + } + if (i1_byte(npc, I1_STEP) != 1) return; + + npc.sprite.Play("Shoot1"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = npc.pos, .posOffset = MEGA_LASER_OFFSET, + .source = &npc, .angleDegrees = MEGA_LASER_ANGLE, + .timeout = MEGA_LASER_TIMEOUT, .variant = MEGA_LASER_VARIANT}); + laser->renderDepthOffset = MEGA_LASER_DEPTH; + } + if (!npc_anim_is_done(npc)) return; + + npc.state = NPC_STATE_IDLE; + i1_byte_set(npc, I1_STEP, 0); + npc.stateFrame = 0; +} + +// The streams: he charges, opens his mouth, picks a pattern and spits its streams until it runs out, then closes. +static void streams_update(Entity_NPC& npc) +{ + bool isSecond = npc.type == ENTITY_MEGA_SATAN_2; + int step = i1_byte(npc, I1_STEP); + + if (step == 0) + { + npc.sprite.Play("Charging"); + if (npc_anim_is_done(npc)) i1_byte_set(npc, I1_STEP, 1); + return mega_sound_play(npc, SOUND_SATAN_CHARGE_UP, CHARGE_VOLUME_STREAMS, CHARGE_DELAY); + } + if (step == 1) + { + npc.sprite.Play(isSecond ? idle_anim_get(npc, "Shoot1Start", "Shoot2Start", "Shoot3Start") : "Shoot2Start"); + if (!npc_anim_is_done(npc)) return; + int patterns = isSecond ? SECOND_FORM_PATTERNS : FIRST_FORM_PATTERNS; + return i1_byte_set(npc, I1_STEP, (int)(Random() % (uint32_t)patterns) + PATTERN_FIRST); + } + if (step == MEGA_STEP_END) + { + npc.sprite.Play(isSecond ? idle_anim_get(npc, "Shoot1End", "Shoot2End", "Shoot3End") : "Shoot2End"); + if (!npc_anim_is_done(npc)) return; + npc.state = NPC_STATE_IDLE; + i1_byte_set(npc, I1_STEP, 0); + npc.stateFrame = 0; + return; + } + if (step > MEGA_STEP_END) return; + + npc.sprite.Play(isSecond ? idle_anim_get(npc, "Shoot1Loop", "Shoot2Loop", "Shoot3Loop") : "Shoot2Loop"); + npc.PlaySound(SOUND_SATAN_SPIT, 1, (int)(Random() % MEGA_SPIT_DELAY_RANGE) + MEGA_SPIT_DELAY_MIN, false, 1); + + StreamPattern pattern = stream_pattern_get(npc, step); + for (int stream = 0; stream < pattern.streams; stream++) + if ((npc.stateFrame - pattern.offsets[stream]) % pattern.period == 0) stream_fire(npc, pattern, step, stream); + if (pattern.duration < npc.stateFrame) i1_byte_set(npc, I1_STEP, MEGA_STEP_END); + if (npc.HasEntityFlags(FLAG_SLOW) && npc.slowingCountdown < SLOW_COUNTDOWN_MIN) + npc.slowingCountdown = SLOW_COUNTDOWN_MIN; + npc.stateFrame++; +} + +// The kinds of a phase's waves, by phase and wave: the horsemen two at a time, the super sins one, two then four, then +// Uriel and Gabriel. Empty past a phase's last wave. +static std::vector phase_wave_get(int phase, int wave) +{ + switch (phase * 10 + wave) + { + case 1: return {{ENTITY_FAMINE, 0, 2, 0}, {ENTITY_PESTILENCE, 0, 2, 1}}; + case 2: return {{ENTITY_WAR, 0, 2, 0}, {ENTITY_DEATH, 0, 2, 1}}; + case 11: return {{ENTITY_ENVY, SUPER_SIN, 1, 0}}; + case 12: return {{ENTITY_LUST, SUPER_SIN, 2, 0}, {ENTITY_WRATH, SUPER_SIN, 2, 1}}; + case 13: + return {{ENTITY_GREED, SUPER_SIN, 4, 0}, + {ENTITY_SLOTH, SUPER_SIN, 4, 1}, + {ENTITY_PRIDE, SUPER_SIN, 4, 2}, + {ENTITY_GLUTTONY, SUPER_SIN, 4, 3}}; + case 21: return {{ENTITY_URIEL, 1, 1, 0}}; + case 22: return {{ENTITY_GABRIEL, 1, 1, 0}}; + default: return {}; + } +} + +// Hiding between phases: he hides while his phase's waves come one at a time, each once the room has no enemies left, +// then reveals himself into the next phase. +static void hide_update(Entity_NPC& npc, MegaSatanHands& hands, int enemies) +{ + npc.isInvincible = true; + npc.entityCollisionClass = ENTCOLL_NONE; + if (i1_byte(npc, I1_STEP) == 0) + { + npc.sprite.Play("Hide"); + if (npc_anim_is_done(npc)) i1_byte_set(npc, I1_STEP, 1); + } + + int step = i1_byte(npc, I1_STEP); + if (step >= 1 && step <= 9) + { + npc.sprite.Play("Hiding"); + if (enemies == 0) + { + std::vector wave = phase_wave_get(i1_byte(npc, I1_PHASE), step); + + for (const WaveSpawn& spawn : wave) + if (Entity* spawned = wave_spawn(npc, spawn)) spawned->Update(); + i1_byte_set(npc, I1_STEP, step + 1); + if (wave.empty()) + { + i1_byte_set(npc, I1_STEP, MEGA_STEP_REVEAL); + for (Entity_NPC* hand : {hands.left, hands.right}) + if (hand) hand->stateFrame = 2; + } + } + } + if (i1_byte(npc, I1_STEP) != MEGA_STEP_REVEAL) return; + + npc.sprite.Play("Reveal"); + if (!npc_anim_is_done(npc)) return; + npc.state = NPC_STATE_IDLE; + i1_byte_set(npc, I1_PHASE, i1_byte(npc, I1_PHASE) + 1); + npc.isInvincible = false; + npc.entityCollisionClass = ENTCOLL_ALL; +} + +// The summon: one of five groups of sins (or a Hollow) along the room's bottom. +static void summon_update(Entity_NPC& npc) +{ + static const std::array, SUMMON_KINDS> SUMMONS = {{ + {{ENTITY_LUST, 0, 1, 0}}, + {{ENTITY_SLOTH, 0, 2, 0}, {ENTITY_PRIDE, 0, 2, 1}}, + {{ENTITY_GLUTTONY, 0, 2, 0}, {ENTITY_ENVY, 0, 2, 1}}, + {{ENTITY_GREED, 0, 2, 0}, {ENTITY_WRATH, 0, 2, 1}}, + {{ENTITY_LARRYJR, 1, 1, 0}}, + }}; + + npc.sprite.Play("Summon"); + if (npc.sprite.IsEventTriggered("Summon")) + { + npc.PlaySound(SOUND_SATAN_RISE_UP, 1, PHASE_SOUND_DELAY, false, 1); + for (const WaveSpawn& spawn : SUMMONS[Random() % SUMMON_KINDS]) + { + if (spawn.type != ENTITY_LARRYJR) + { + wave_spawn(npc, spawn); + continue; + } + Room& room = *g_game->room; + Vector spot = vector_make(room.topLeftPos.x + WAVE_MARGIN, room.bottomRightPos.y - WAVE_MARGIN); + for (int i = 0; i < HOLLOW_SEGMENTS; i++) + g_game->Spawn({.position = spot, .spawner = &npc, .type = spawn.type, .variant = spawn.variant, + .seed = Random()}); + } + } + if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + } +} + +// The head smash: his head slams down (one of three smashes) throwing a burst of shots. +static void smash_update(Entity_NPC& npc) +{ + int smash = i1_byte(npc, I1_STEP); + + if (smash == 1) npc.sprite.Play("SmashHead"); + if (smash == 3) npc.sprite.Play("SmashHead3"); + if (smash == 5) npc.sprite.Play("SmashHead5"); + if (npc.sprite.IsEventTriggered("Smash")) + { + game_shake_screen(SMASH_SHAKE); + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, SMASH_VOLUME, 2, false, 1); + + ProjectileParams params; + params.bulletFlags |= PROJECTILE_HIT_ENEMIES; + params.heightModifier = SMASH_HEIGHT; + params.scale = SMASH_SCALE; + params.velocityMulti = SMASH_SPEED; + int shots = smash == 3 ? SMASH_SHOTS_THIRD : SMASH_SHOTS; + if (smash == 5) shots = SMASH_SHOTS_FIFTH; + npc.FireBossProjectiles(shots, {}, 0, params); + } + if (!npc_anim_is_done(npc)) return; + + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; +} + +// Dying he sinks back to the focus point, killing every other enemy. The first form then rises again as the second; +// the second's death ends the fight. +static void death_update(Entity_NPC& npc) +{ + npc.sprite.Play("Death"); + npc.PlaySound(SOUND_SATAN_BLAST, 1, DEATH_SOUND_DELAY, false, DEATH_PITCH); + game_shake_screen(RISE_SHAKE); + g_game->room->camera->SetFocusPosition(MEGA_FOCUS); + + std::vector& entities = g_game->room->entityList.updateEL; + for (size_t i = 0; i < entities.size(); i++) + { + Entity* entity = entities[i]; + if (!entity->is_valid_boss_enemy() || entity->type == ENTITY_MEGA_SATAN || entity->type == ENTITY_MEGA_SATAN_2) + continue; + entity->Kill(EntityRef(&npc)); + } + mega_glide(npc, npc.targetPosition, MEGA_FOCUS, + std::clamp(((float)anim_frame_get(npc) - 0) / RISE_FRAMES, 0.0f, 1.0f)); + + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.isInvincible = true; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.RemoveStatusEffects(); + if (!npc.sprite.IsFinished("Death")) return; + if (npc.type == ENTITY_MEGA_SATAN_2) return npc.trigger_kill_item_effects(); + + npc.velocity = {}; + npc.Morph(ENTITY_MEGA_SATAN_2, npc.variant, 0, -1); + npc.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.health = npc.maxHitPoints; + npc.state = MEGA_RISE; + npc.sprite.Play("Appear"); + npc.PlaySound(SOUND_SATAN_GROW, 1, 2, false, SECOND_FORM_PITCH); + npc.sprite.GetLayer(SECOND_FORM_UNTINTED_LAYER)->bitflags |= ANIM_RENDER_UNTINTED; +} + +// His drift: every 60 frames a new spot near his target's x, home while hiding; he steers toward it at 1.2, his height +// held to it. +static void drift_update(Entity_NPC& npc) +{ + if (g_game->frameCount % MEGA_DRIFT_PERIOD == 0) + { + npc.targetPosition = MEGA_HOME; + npc.targetPosition.x = npc.GetPlayerTarget()->pos.x; + float drift = random_unit() * MEGA_DRIFT_SPREAD - MEGA_DRIFT_SPREAD / 2 + npc.targetPosition.x; + npc.targetPosition.x = std::clamp(drift, MEGA_DRIFT_LEFT, MEGA_DRIFT_RIGHT); + } + if (npc.state == MEGA_HIDE) npc.targetPosition = MEGA_HOME; + + npc.friction *= MEGA_FRICTION; + if (vector_is_zero(npc.targetPosition) || npc.state == MEGA_DEATH || npc.state == MEGA_RISE) return; + + Vector toward = vector_sub(npc.targetPosition, npc.pos); + if (vector_length(toward) > MEGA_DRIFT_ARRIVED) + { + toward = vector_resized(toward, MEGA_DRIFT_SPEED); + Vector steer = vector_sub(vector_make(toward.x / npc.friction, toward.y / npc.friction), npc.velocity); + + npc.velocity = vector_add(npc.velocity, vector_scale(steer, MEGA_DRIFT_STEER)); + } + npc.pos.y = npc.targetPosition.y; +} + +// His death begins: his hands die, his shots vanish and he falls. +static void death_start(Entity_NPC& npc, MegaSatanHands& hands) +{ + for (Entity_NPC* hand : {hands.left, hands.right}) + if (hand) hand->Kill(EntityRef()); + npc.state = MEGA_DEATH; + npc.targetPosition = npc.pos; + npc.isDead = false; + for (Entity* shot : entity_query_radius(npc.pos, SHOT_CLEAR_REACH, QUERY_PROJECTILES)) shot->isDead = true; + g_manager->persistentGameData.AddBestiaryKill(npc.type, npc.variant); +} + +// A lost hand comes back after 30 counts of 30 frames. +static Entity_NPC* hand_return_update(Entity_NPC& npc, Entity_NPC* hand, int side) +{ + int byteIndex = side == MEGA_SATAN_LEFT_HAND ? I1_LEFT_RETURN : I1_RIGHT_RETURN; + if (hand) + { + i1_byte_set(npc, byteIndex, 0); + return hand; + } + + int count = i1_byte(npc, byteIndex); + if (g_game->frameCount % HAND_RETURN_PERIOD == 0) i1_byte_set(npc, byteIndex, ++count); + if ((count & 0xff) <= HAND_RETURN_COUNT) return nullptr; + + Vector spot = vector_add(npc.pos, side == MEGA_SATAN_LEFT_HAND ? LEFT_HAND_SPOT : RIGHT_HAND_SPOT); + auto* spawned = dynamic_cast(g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_MEGA_SATAN, .variant = side, .seed = Random()})); + spawned->Update(); + return spawned; +} + +// The phase ends at each fifth of his health lost: he heals a little, cries out and hides with his hands. +static void phase_check(Entity_NPC& npc, MegaSatanHands& hands) +{ + int phase = i1_byte(npc, I1_PHASE); + if (phase >= (int)PHASE_ENDS.size() || npc.health >= npc.maxHitPoints * PHASE_ENDS[phase]) return; + + npc.health = npc.maxHitPoints * PHASE_HEALTHS[phase]; + npc.state = MEGA_HIDE; + npc.stateFrame = 0; + i1_byte_set(npc, I1_STEP, 0); + mega_sound_play(npc, SOUND_SATAN_HURT, 1, PHASE_SOUND_DELAY); + mega_sound_play(npc, SOUND_SATAN_RISE_UP, 1, PHASE_SOUND_DELAY); + for (Entity_NPC* hand : {hands.left, hands.right}) + if (hand) + { + hand->state = MEGA_HIDE; + hand->stateFrame = 0; + } +} + +// 004c8090 NpcAI::ENTITY_MEGA_SATAN: Mega Satan (274) and his second form (275). He rises once the floor's intro +// ends, then lasers, spits streams of rings, smashes his head, summons sins and sends his hands. Each fifth of his +// health he hides through a phase's waves. Dying he becomes the second form, which only spits streams. +void boss_mega_satan_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + npc.sprite.offset = vector_make(0, MEGA_SPRITE_RISE); + npc.pos = MEGA_HOME; + npc.targetPosition = MEGA_HOME; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.stateFrame = 1; + npc.i1 = 0; + npc.i2 = ATTACK_NONE; + npc.v2.x = std::bit_cast(ATTACK_NONE); + npc.ClearEntityFlags(FLAG_APPEAR); + npc.state = MEGA_RISE; + npc.isVisible = false; + } + + MegaSatanHands hands{npc_find(ENTITY_MEGA_SATAN, MEGA_SATAN_LEFT_HAND), + npc_find(ENTITY_MEGA_SATAN, MEGA_SATAN_RIGHT_HAND)}; + if (npc.type == ENTITY_MEGA_SATAN && !npc.isDead && npc.state != MEGA_DEATH) + { + hands.left = hand_return_update(npc, hands.left, MEGA_SATAN_LEFT_HAND); + hands.right = hand_return_update(npc, hands.right, MEGA_SATAN_RIGHT_HAND); + } + if (npc.isDead) death_start(npc, hands); + + int summonWeight = 0; + int enemies = enemies_count(summonWeight); + if (npc.state != MEGA_HIDE && npc.type == ENTITY_MEGA_SATAN) phase_check(npc, hands); + + if (npc.state == MEGA_RISE) rise_update(npc); + if (npc.state == NPC_STATE_IDLE) idle_update(npc, hands, summonWeight); + if (npc.state == MEGA_LASER) laser_update(npc); + if (npc.state == MEGA_STREAMS) streams_update(npc); + if (npc.state == MEGA_HIDE) hide_update(npc, hands, enemies); + if (npc.state == MEGA_SUMMON) summon_update(npc); + else if (npc.state == MEGA_SMASH) smash_update(npc); + else if (npc.state == MEGA_DEATH) + { + death_update(npc); + if (npc.type == ENTITY_MEGA_SATAN_2 && npc.state == MEGA_RISE) return; + } + drift_update(npc); +} + +// Dad's Key flies to the Mega Satan door, turned up to 90 degrees by 2 a frame, from its middle 13.85 left and 7.69 +// up. +constexpr float KEY_TURN_STEP = 2; +constexpr float KEY_TURN_END = 90; +constexpr float KEY_DOOR_LEFT = 13.846154f; +constexpr float KEY_DOOR_UP = 7.692308f; +constexpr float KEY_DOOR_REACH = 3; + +// 0061d6b0 The full key: in a cleared room with the Mega Satan door it flies into its lock, opens it, takes Key Piece 1 +// and 2 from their owners and is gone. Elsewhere it floats after the player. +void Entity_Familiar::ai_key_full() +{ + Room& room = *g_game->room; + GridEntity_Door* door = nullptr; + + if (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR) + for (GridEntity_Door* each : room.doors) + if (each && each->variant == DOOR_LOCKED_KEYFAMILIAR && !door) door = each; + if (!door) + { + if (!isFollower) AddToFollowers(); + sprite.GetLayer(0)->rotation = 0; + sprite.Play("Float"); + return FollowParent(); + } + + if (isFollower) RemoveFromFollowers(); + sprite.Play("Idle"); + + float column = (float)(door->gridIndex % room.gridWidth); + float row = (float)(door->gridIndex / room.gridWidth); + Vector lock = vector_make(column * GRID_CELL_SIZE + GRID_ORIGIN_X - KEY_DOOR_LEFT, + row * GRID_CELL_SIZE + GRID_ORIGIN_Y - KEY_DOOR_UP); + FollowPosition(lock); + + LayerState& layer = *sprite.GetLayer(0); + if (layer.rotation < KEY_TURN_END) + { + layer.rotation = std::min(layer.rotation + KEY_TURN_STEP, KEY_TURN_END); + return; + } + if (vector_length_squared(vector_sub(pos, lock)) >= KEY_DOOR_REACH * KEY_DOOR_REACH) return; + + npc_sound_play(SOUND_GOLDENKEY, 1, 2, 1); + if (door->variant != DOOR_LOCKED_BARRED) + { + if (door->variant == DOOR_LOCKED_KEYFAMILIAR) + g_game->gameStateFlags |= 1ull << GAME_STATE_MEGA_SATAN_DOOR_OPENED; + door->variant = DOOR_UNLOCKED; + door->UpdateAnimation(); + } + door->Open(); + Remove(); + for (int keyPiece : {COLLECTIBLE_KEY_PIECE_1, COLLECTIBLE_KEY_PIECE_2}) + if (Entity_Player* owner = g_game->playerManager.FirstCollectibleOwner(keyPiece, LAZARUS_SHARE_IGNORE)) + owner->RemoveCollectible(keyPiece, false, 0, true); +} diff --git a/src/boss_min_min.cpp b/src/boss_min_min.cpp new file mode 100644 index 0000000..98339c9 --- /dev/null +++ b/src/boss_min_min.cpp @@ -0,0 +1,884 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_config.h" +#include "entity_effect_combat.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "manager.h" +#include + +// The Willo, a will-o'-wisp orbiting its Min-Min (its parent) or the players. Its slot on the ring turns with the game's +// frames, its spot on the ring (v2.x) is spread evenly among its siblings, and v1 holds its ring's radius and stretch. +constexpr float WILLO_RING_RADIUS = 120; +constexpr float WILLO_RING_TURN = 0.035f; +constexpr float WILLO_RING_FLATTEN = 0.84f; +constexpr float WILLO_ARRIVED = 20; +constexpr float WILLO_STEER = 0.5f; +constexpr float WILLO_STEER_MAX = 10; +constexpr float WILLO_RING_OUTSIDE = 1.15f; +constexpr int WILLO_START_DELAY = 40; +constexpr int WILLO_SPAWN_SLOT = 12; + +// It attacks 1 time in 9 a frame, when near its slot, in the room, not confused, feared or shrunk, and alone. +constexpr uint32_t WILLO_ATTACK_ODDS = 9; +constexpr float WILLO_ATTACK_REACH_SQUARED = 400; +constexpr uint64_t WILLO_DAZED = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; +constexpr float WILLO_SHOT_SPEED = 10; +constexpr float WILLO_SHOT_DROP = 4; +constexpr float WILLO_RING_SHOT_SPEED = 8; +constexpr int WILLO_RING_SWELL_FRAMES = 16; +constexpr float WILLO_RING_SWELL = 0.8f; +constexpr float WILLO_HURL_DRAG = 0.9f; +constexpr float WILLO_DIVE_FRICTION = 0.5f; +constexpr ColorMod WILLO_SHOT_COLOR = {{1, 1, 1, 1}, {1, 0.8f, 0.1f, 1}, {0.3f, 0.25f, 0.05f}}; +constexpr ColorMod WILLO_SPLASH_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {1, 192 / 255.0f, 1 / 255.0f}}; + +// The Willo's own states beyond the shared ones: rising from the water, an attack from under it, hurled by Min-Min, +// shooting a ring with the others, and diving under. +constexpr int WILLO_RISE = NPC_STATE_JUMP; +constexpr int WILLO_UNDERWATER_ATTACK = NPC_STATE_STOMP; +constexpr int WILLO_ATTACK = NPC_STATE_ATTACK; +constexpr int WILLO_HURLED = NPC_STATE_ATTACK2; +constexpr int WILLO_RING_ATTACK = NPC_STATE_ATTACK3; +constexpr int WILLO_DIVE = NPC_STATE_SUMMON; +constexpr int WILLO_FREE = 1; + +// Min-Min: below 40% health it turns (i1), stronger. It walks, spits Willos one or four at a time, spins them into a +// ring attack, throws its head for them to follow (variant 10), or dives under and has them burst from the water. +constexpr int MIN_MIN_HEAD = 10; +constexpr float MIN_MIN_FRICTION = 0.7f; +constexpr float MIN_MIN_TURN_SHARE = 0.4f; +constexpr float MIN_MIN_TURN_FRICTION = 0.6f; +constexpr ColorMod MIN_MIN_SPLAT_COLOR = {{1, 1, 1, 1}, {8, 6, 0, 1}, {0, 0, 0}}; +constexpr int MIN_MIN_SHAKE = 6; + +// Its walk: toward its target (0.6 fast), or nowhere while charmed, confused, feared or shrunk or with three Willos. +constexpr uint64_t MIN_MIN_DAZED = FLAG_CHARM | FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; +constexpr float MIN_MIN_WALK_SPEED = 0.6f; +constexpr float MIN_MIN_WANDER_SPEED = 0.5f; +constexpr int MIN_MIN_WANDER_FRAMES = 10; +constexpr int MIN_MIN_WANDER_TRIES = 10; +constexpr float MIN_MIN_WANDER_MARGIN = 20; +constexpr int MIN_MIN_GUARD = 2; + +// Its attacks come 1 time in 4 once its delay runs out: spitting one Willo (to 4 of its own, 8 turned, 1 in 3, 1 in 2 +// turned) or four (to 2, 4 turned, 1 in 3), or diving once turned (1 in 4), all while fewer than 5 (7 turned) Willos +// are about. With three Willos and its shot cooldown done, 1 time in 3 it spins them or throws its head. +constexpr int MIN_MIN_ATTACK_MASK = 3; +constexpr int MIN_MIN_WILLOS_MAX = 5; +constexpr int MIN_MIN_WILLOS_MAX_TURNED = 2; +constexpr int SPIT_OWN_MAX = 4; +constexpr int SPIT_OWN_MAX_TURNED = 4; +constexpr int MIN_MIN_SPIT_ODDS = 2; +constexpr int SPIT_FOUR_OWN_MAX = 2; +constexpr int SPIT_FOUR_OWN_MAX_TURNED = 2; +constexpr uint32_t SPIT_FOUR_ODDS = 3; +constexpr int DIVE_ODDS_MASK = 3; +constexpr uint32_t SPIN_ODDS = 3; +constexpr uint32_t SPIT_DELAY_RANGE = 60; +constexpr int SPIT_DELAY_MIN = 15; +constexpr uint32_t ATTACK_DELAY_RANGE = 90; +constexpr int ATTACK_DELAY_MIN = 90; + +// Its spit: a Willo (half again as tough) flung at its target 25 fast, 15 degrees to a side, or four on the ring. +constexpr float SPAWN_RING_RADIUS = 80; +constexpr float SPIT_WILLO_HEALTH = 1.5f; +constexpr float MIN_MIN_SPIT_SPEED = 25; +constexpr float SPIT_ANGLE = 15; +constexpr int SPIT_ATTACK_FRAME = 4; +constexpr int MIN_MIN_SPIT_COOLDOWN = 45; +constexpr int SPIT_FOUR = 4; + +// Its spin: the Willos swing in to half their ring and shoot a ring at once from frame 17 of their attack. +constexpr float SPIN_RING_STRETCH = 0.5f; +constexpr int SPIN_ATTACK_FRAME = 17; + +// Its throw: the head flies 7 fast at where its target will be, turning back to Min-Min (3 degrees a frame, more over +// time) after 20 frames, the Willos following it until it is back within 14. +constexpr float MIN_MIN_THROW_SPEED = 7; +constexpr float THROW_LEAD = 0.1f; +constexpr float HEAD_TURN = 3; +constexpr float HEAD_TURN_GROWTH = 0.05f; +constexpr float HEAD_STRAIGHT_FRAMES = 20; +constexpr float HEAD_GROW_FRAMES = 40; +constexpr float HEAD_CATCH = 14; + +// Its dive: under the water, it lays groups of 1 to 5 Willo spawners (near its target 1 time in 3 for the first +// five tries) on its first 9 frames, then every 15th frame wakes a group, coming back up 30 frames after the last. +constexpr int DIVE_WILLO_COOLDOWN = 30; +constexpr int DIVE_COOLDOWN_EVERY = 10; +constexpr int DIVE_LAYING_FRAMES = 9; +constexpr int DIVE_WAKE_FIRST = 8; +constexpr int DIVE_WAKE_EVERY = 15; +constexpr int DIVE_SPOT_TRIES = 10; +constexpr int DIVE_NEAR_TRIES = 5; +constexpr uint32_t DIVE_NEAR_ODDS = 3; +constexpr float DIVE_NEAR_MIN = 40; +constexpr float DIVE_NEAR_RANGE = 80; +constexpr float DIVE_SPOT_MARGIN = 30; +constexpr float DIVE_SPOT_SPACING_SQUARED = 100; +constexpr uint32_t DIVE_GROUP_RANGE = 5; +constexpr float DIVE_GROUP_RADIUS = 30; +constexpr float DIVE_GROUP_FLATTEN = 0.6f; +constexpr int DIVE_RETURN_FRAMES = 29; +constexpr float DIVE_RISE_RADIUS = 0.1f; + +// collect_npcs_with_same_parent's turn: a full turn in radians, wrapped as if it were degrees. +constexpr float SIBLING_TURN = 6.2831855f; + +// 00557ce0 collect_npcs_with_same_parent: the live Willos sharing the Willo's parent spread evenly around their ring. +static void willo_siblings_spread(Entity_NPC& npc) +{ + std::vector siblings; + float lowest = DEGREES_PER_TURN; + + for (Entity* entity : entity_query(ENTITY_WILLO, -1)) + { + auto* willo = static_cast(entity); + if (willo->subtype != 0 || willo->isDead || willo->parent.get() != npc.parent.get()) continue; + siblings.push_back(willo); + lowest = std::min(lowest, willo->v2.x); + } + if (siblings.size() < 2) return; + + float step = SIBLING_TURN / (float)siblings.size(); + for (size_t i = 0; i < siblings.size(); i++) siblings[i]->v2.x = angle_wrap((float)i * step + lowest); +} + +// 00558070 Where a Willo circles: its parent, or the players' middle (Tainted Forgotten's body aside), and how far +// apart the players stand. +static Vector willo_center(Entity_NPC& npc, float* spread) +{ + if (npc.parent) + { + if (spread) *spread = 0; + return npc.parent->pos; + } + + std::vector players; + Vector sum{}; + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->variant == PLAYER_VARIANT_PLAYER && player->playerType != PLAYER_THEFORGOTTEN_B) + { + players.push_back(player); + sum = vector_add(sum, player->pos); + } + + Vector center = vector_scale(sum, 1 / (float)players.size()); + if (!spread) return center; + + *spread = 0; + if (players.size() > 1) + for (Entity_Player* player : players) *spread = std::max(*spread, vector_length(vector_sub(center, player->pos))); + return center; +} + +// 00557f70 A Willo's spot on its ring: turning with the frames from its own angle (the attack's while attacking), +// flattened, with a slot shifting it further on. +Vector willo_slot(Entity_NPC& npc, int slot) +{ + Vector center = willo_center(npc, nullptr); + float frame = (float)(g_manager->framecount % 2) * 0.5f + (float)g_game->frameCount + (float)slot; + float base = npc.state == WILLO_ATTACK ? npc.v2.y : npc.v2.x; + float angle = base - frame * 0.5f * PI_F * WILLO_RING_TURN; + float radius = npc.v1.y * npc.v1.x; + return vector_make(std::cos(angle) * radius + center.x, std::sin(angle) * radius * WILLO_RING_FLATTEN + center.y); +} + +// A Willo placed on the edge of its ring, along its spot. +static void willo_place(Entity_NPC& npc, int slot, float distance) +{ + Vector center = willo_center(npc, nullptr); + Vector along = vector_normalized(vector_sub(willo_slot(npc, slot), center)); + npc.pos = vector_add(center, vector_scale(along, distance)); +} + +// The way what it circles moves: its parent's velocity against its friction, or the players' on average, doubled. +static Vector willo_drift(Entity_NPC& npc) +{ + if (npc.parent) return vector_scale(npc.parent->velocity, 2 / npc.parent->friction); + + Vector sum{}; + int count = 0; + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->variant == PLAYER_VARIANT_PLAYER) + { + sum = vector_add(sum, vector_scale(player->velocity, 2 / player->friction)); + count++; + } + return vector_scale(sum, 1 / (float)count); +} + +// 005581b0 A bound Willo steers to its slot (at most 10 a frame) on top of the drift of what it circles, its first +// approach done once within 20. +static void willo_orbit(Entity_NPC& npc) +{ + if (npc.subtype != 0) return; + + Vector slot = willo_slot(npc, 0); + if (vector_length(vector_sub(slot, npc.pos)) < WILLO_ARRIVED && npc.projectileDelay == 1) npc.projectileDelay = 0; + + Vector drift = willo_drift(npc); + Vector steer = vector_scale(vector_sub(slot, vector_add(npc.pos, drift)), WILLO_STEER); + if (vector_length(steer) > WILLO_STEER_MAX) steer = vector_scale(vector_normalized(steer), WILLO_STEER_MAX); + npc.velocity = vector_scale(vector_add(steer, drift), 1 / npc.friction); +} + +// The fire shot Willos throw: a tear shot through walls. +static ProjectileParams willo_shot_params() +{ + ProjectileParams params; + params.color = WILLO_SHOT_COLOR; + params.variant = PROJECTILE_TEAR; + params.bulletFlags = PROJECTILE_NO_WALL_COLLIDE; + return params; +} + +// 005583d0 Its attack animation: a crackle on Warn, a shot 10 fast at where its target is heading on Shoot (falling +// later from a free Willo), and back to floating once over. +static void willo_attack(Entity_NPC& npc) +{ + if (!npc.sprite.IsPlaying()) + { + npc.state = NPC_STATE_IDLE; + return; + } + if (npc.sprite.IsEventTriggered("Warn")) npc_sound_play(SOUND_CANDLE_LIGHT, 1, 2, champion_pitch_get(npc)); + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc_sound_play(SOUND_TEARS_FIRE, 1, 2, champion_pitch_get(npc)); + Entity* target = npc.GetPlayerTarget(); + Vector aim = vector_scale(vector_normalized(vector_sub(vector_add(target->pos, target->velocity), npc.pos)), + WILLO_SHOT_SPEED); + ProjectileParams params = willo_shot_params(); + if (!npc.parent && npc.subtype == 0) params.fallingSpeedModifier += WILLO_SHOT_DROP; + npc.FireProjectiles(npc.pos, aim, PROJECTILES_SINGLE, params); +} + +// The ripple a Willo leaves rising from or sinking into the water. +static void willo_splash(Entity_NPC& npc) +{ + Entity* ripple = g_game->Spawn( + {.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_RIPPLE, .seed = Random()}); + ripple->SetColor(WILLO_SPLASH_COLOR, -1, 255, false, true); +} + +// Whether another bound Willo is attacking or hurled already. +static bool willo_is_other_attacking() +{ + for (Entity* entity : entity_query(ENTITY_WILLO, -1)) + { + auto* willo = static_cast(entity); + if (willo->subtype == 0 && !willo->isDead && (willo->state == WILLO_ATTACK || willo->state == WILLO_HURLED)) + return true; + } + return false; +} + +// Floating on its ring, now and then (1 in 9) it attacks: a free Willo always, a bound one only when it is near its +// slot, low, in the room, clear headed and no other attacks. +static void willo_float(Entity_NPC& npc, int ticks) +{ + npc.sprite.Play("Fly"); + willo_orbit(npc); + if (npc.projectileDelay > 1) npc.projectileDelay = std::max(npc.projectileDelay - ticks, 1); + if (Random() % WILLO_ATTACK_ODDS != 0) return; + + if (npc.subtype != WILLO_FREE) + { + if (npc.projectileCooldown > 0 || npc.posOffset.y < 0) return; + Vector slot = willo_slot(npc, 0); + if (vector_length_squared(vector_sub(slot, npc.pos)) > WILLO_ATTACK_REACH_SQUARED) return; + if (!g_game->room->IsPositionInRoom(npc.pos, 0) || npc.HasEntityFlags(WILLO_DAZED)) return; + if (willo_is_other_attacking()) return; + } + npc.state = WILLO_ATTACK; + npc.v2.y = npc.v2.x; +} + +// The ring attack: swelling out over 16 frames and back, a shot outward from the ring on frames 2, 5 and 8. +static void willo_ring_attack(Entity_NPC& npc) +{ + willo_orbit(npc); + int frame = npc.stateFrame++; + float swell = std::clamp((float)(frame + 1) / WILLO_RING_SWELL_FRAMES, 0.0f, 1.0f); + npc.v1.y = std::sin(swell * PI_F) * WILLO_RING_SWELL + 1; + + if (frame == 2 || frame == 5 || frame == 8) + { + npc.PlaySound(SOUND_TEARS_FIRE, 1, 2, false, 1); + Vector outward = vector_sub(willo_slot(npc, 0), willo_center(npc, nullptr)); + npc.FireProjectiles(npc.pos, vector_scale(vector_normalized(outward), WILLO_RING_SHOT_SPEED), + PROJECTILES_SINGLE, willo_shot_params()); + } + if (npc.sprite.IsPlaying()) return; + npc.v1.y = 1; + npc.state = NPC_STATE_IDLE; +} + +// 005586b0 (NpcAI::ENTITY_WILLO) The Willo: it floats on its ring, rises from and dives under the water at Min-Min's +// call, is flung, shoots alone or in a ring, and once dead its siblings close the gap. +void npc_willo_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + if (npc.projectileCooldown > 0) npc.projectileCooldown = std::max(npc.projectileCooldown - ticks, 0); + + switch (npc.state) + { + case NPC_STATE_INIT: + { + npc.AddEntityFlags(FLAG_NO_PLAYER_CONTROL); + npc.v1 = vector_make(WILLO_RING_RADIUS, 1); + npc.projectileDelay = WILLO_START_DELAY; + willo_siblings_spread(npc); + Room& room = *g_game->room; + if (room.isInitialized && g_game->frameCount == room.enterFrame) + for (Entity* willo : entity_query(ENTITY_WILLO, -1)) + { + auto& other = *static_cast(willo); + willo_place(other, WILLO_SPAWN_SLOT, other.v1.x * WILLO_RING_OUTSIDE); + } + npc.state = NPC_STATE_IDLE; + break; + } + case NPC_STATE_IDLE: + willo_float(npc, ticks); + break; + case WILLO_RISE: + npc.sprite.Play("UnderwaterSpawn"); + npc.entityCollisionClass = ENTCOLL_NONE; + willo_orbit(npc); + if (npc.sprite.GetFrame() == 1) + { + willo_splash(npc); + npc.isVisible = true; + npc.shadowSize = npc.config->shadowSize; + } + if (npc.sprite.IsPlaying()) break; + npc.state = NPC_STATE_IDLE; + npc.entityCollisionClass = ENTCOLL_ALL; + break; + case WILLO_UNDERWATER_ATTACK: + npc.sprite.Play("UnderwaterAttack"); + if (!npc.sprite.IsPlaying()) + { + willo_splash(npc); + npc.Remove(); + } + else + { + if (npc.sprite.GetFrame() == 1) willo_splash(npc); + willo_attack(npc); + } + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + break; + case WILLO_ATTACK: + npc.sprite.Play("Attack"); + willo_attack(npc); + willo_orbit(npc); + break; + case WILLO_HURLED: + willo_attack(npc); + npc.velocity = npc.targetPosition; + npc.targetPosition = vector_scale(npc.targetPosition, WILLO_HURL_DRAG); + break; + case WILLO_RING_ATTACK: + willo_ring_attack(npc); + break; + case WILLO_DIVE: + npc.friction *= WILLO_DIVE_FRICTION; + npc.sprite.Play("UnderwaterDive"); + if (npc.sprite.IsPlaying() || npc.entityCollisionClass == ENTCOLL_NONE) break; + willo_splash(npc); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isVisible = false; + npc.shadowSize = 0; + break; + } + if (npc.isDead) willo_siblings_spread(npc); +} + +// 00558fe0 A Willo rising for Min-Min (or a spawner) on a ring of a radius: from under the water, or (subtype 1) an +// attack from under it where it rose. +Entity_NPC* willo_spawn(const Vector& position, Entity* spawner, float ringRadius, int subType) +{ + auto* willo = static_cast(g_game->Spawn({.position = position, + .spawner = spawner, + .subType = subType, + .type = ENTITY_WILLO, + .seed = Random()})); + if (spawner) willo->parent = spawner; + willo->ClearEntityFlags(FLAG_APPEAR); + willo->v1 = vector_make(ringRadius, 1); + if (subType == 0) + { + willo->state = WILLO_RISE; + willo->sprite.Play("UnderwaterSpawn"); + return willo; + } + + willo->state = WILLO_UNDERWATER_ATTACK; + willo->sprite.Play("UnderwaterAttack"); + willo->targetPosition = position; + willo->projectileDelay = 0; + return willo; +} + +// 004cf5b0 NpcHelper::min_min_willo_count: how many Willos there are, and how many are its own. +static int min_min_willos_count(Entity_NPC& npc, int& total) +{ + std::vector willos = entity_query(ENTITY_WILLO, -1); + total = (int)willos.size(); + return (int)std::ranges::count_if(willos, [&](Entity* willo) { return willo->parent.get() == &npc; }); +} + +// Its bound Willos. +static std::vector min_min_willos(Entity_NPC& npc) +{ + std::vector own; + for (Entity* willo : entity_query(ENTITY_WILLO, -1)) + if (willo->subtype == 0 && willo->parent.get() == &npc) own.push_back(static_cast(willo)); + return own; +} + +// The head it throws: it flies on, turning back after 20 frames ever faster, its Willos following, and gone once its +// Willos are gone or it is back at Min-Min, which takes them back. +static void min_min_head_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.ClearEntityFlags(FLAG_APPEAR); + npc.isVisible = false; + npc.shadowSize = 0; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.isInvincible = true; + npc.isCanShutDoors = false; + npc.isBoss = false; + npc.state = NPC_STATE_IDLE; + npc.v1.x = 0; + return; + } + if (!npc.parent) return; + + if (npc.updateTime > HEAD_GROW_FRAMES) npc.v1.x += npc.v1.x <= 0 ? -HEAD_TURN_GROWTH : HEAD_TURN_GROWTH; + if (npc.updateTime > HEAD_STRAIGHT_FRAMES) + { + if (npc.v1.x == 0) + { + Entity* target = npc.ParentNPC()->GetPlayerTarget(); + float distance = vector_length(vector_sub(npc.pos, target->pos)); + Vector lead = vector_add(target->pos, vector_scale(target->velocity, distance * THROW_LEAD)); + npc.v1.x = angle_wrap(vector_angle(vector_sub(lead, npc.pos)) - npc.v2.x) <= 0 ? -HEAD_TURN : HEAD_TURN; + } + float home = vector_angle(vector_sub(npc.parent->pos, npc.pos)); + float turn = npc.v1.x * npc.speedMultiplier; + npc.v2.x = std::abs(turn) <= std::abs(angle_wrap(npc.v2.x - home)) ? angle_wrap(npc.v2.x + turn) : home; + if (min_min_willos(npc).empty()) npc.Remove(); + } + + npc.velocity = vector_scale(vector_from_angle(npc.v2.x), npc.v2.y); + if (vector_length(vector_sub(npc.pos, npc.parent->pos)) >= HEAD_CATCH || npc.updateTime <= HEAD_STRAIGHT_FRAMES) + return; + for (Entity_NPC* willo : min_min_willos(npc)) willo->parent = npc.parent.get(); + npc.Remove(); +} + +// A spot for a group of spawners: near its target (1 in 3, the first five tries) or anywhere, clear of its other +// spawners, at most ten tries (the last kept). +static Vector dive_spot_find(Entity_NPC& npc, const std::vector& spawners) +{ + Room& room = *g_game->room; + Vector spot{}; + bool isFree = false; + for (int tries = 0; !isFree && tries < DIVE_SPOT_TRIES; tries++) + { + if (tries < DIVE_NEAR_TRIES && Random() % DIVE_NEAR_ODDS == 0) + { + Vector targetPos = npc.GetPlayerTarget()->pos; + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float distance = random_unit() * DIVE_NEAR_RANGE + DIVE_NEAR_MIN; + Vector near = vector_add(targetPos, vector_make(std::cos(angle) * distance, std::sin(angle) * distance)); + spot = room.GetClampedPositionImpl(near, DIVE_SPOT_MARGIN, DIVE_SPOT_MARGIN, DIVE_SPOT_MARGIN, + DIVE_SPOT_MARGIN); + } + else spot = room.GetRandomPosition(DIVE_SPOT_MARGIN); + + isFree = std::ranges::none_of(spawners, [&](Entity* spawner) { + return spawner->parent.get() == &npc && + vector_length_squared(vector_sub(spot, spawner->pos)) < DIVE_SPOT_SPACING_SQUARED; + }); + } + return spot; +} + +// A group of 1 to 5 Willo spawners in a flattened ring about a free spot, the first leading the others. +static void dive_group_lay(Entity_NPC& npc) +{ + Vector spot = dive_spot_find(npc, entity_query(ENTITY_EFFECT, EFFECT_WILLO_SPAWNER)); + int count = (int)(Random() % DIVE_GROUP_RANGE) + 1; + float startAngle = random_unit() * DEGREES_PER_TURN; + + Entity* leader = nullptr; + for (int i = 0; i < count; i++) + { + Vector at = spot; + if (count > 1) + { + Vector around = vector_from_angle((float)i * DEGREES_PER_TURN / (float)count + startAngle); + at = vector_add(spot, vector_make(around.x * DIVE_GROUP_RADIUS, + around.y * DIVE_GROUP_RADIUS * DIVE_GROUP_FLATTEN)); + } + auto* spawner = static_cast(g_game->Spawn( + {.position = at, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_WILLO_SPAWNER, .seed = Random()})); + spawner->parent = &npc; + if (leader) spawner->target = leader; + spawner->state = SPAWNER_WAITING; + spawner->Update(); + if (!leader) leader = spawner; + } +} + +// Wakes one waiting group (a leader picked at random), or with none left ends the laying. +static void dive_group_wake(Entity_NPC& npc) +{ + std::vector spawners = entity_query(ENTITY_EFFECT, EFFECT_WILLO_SPAWNER); + std::vector leaders; + for (Entity* spawner : spawners) + if (spawner->parent.get() == &npc && !spawner->target && static_cast(spawner)->state == 0) + leaders.push_back(spawner); + if (leaders.empty()) + { + npc.i2++; + npc.stateFrame = 0; + return; + } + + Entity* chosen = leaders[random_below((int)leaders.size())]; + for (Entity* spawner : spawners) + if (spawner == chosen || spawner->target.get() == chosen) + static_cast(spawner)->state = SPAWNER_WOKEN; +} + +// The dive: sinking, then laying and waking spawners each tick (its Willos held from shooting), then rising again +// 30 frames on with its diving Willos rising beside it. +static void min_min_dive(Entity_NPC& npc) +{ + if (npc.i2 == 0) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.shadowSize = 0; + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (npc.sprite.IsPlaying()) return; + npc.i2++; + npc.stateFrame = 0; + return; + } + if (npc.i2 == 1) + { + for (int tick = 0; tick < npc_ticks_get(npc); tick++, npc.stateFrame++) + { + if (npc.stateFrame % DIVE_COOLDOWN_EVERY == 0) + for (Entity* willo : entity_query(ENTITY_WILLO, -1)) + if (willo->subtype == 0) static_cast(willo)->projectileCooldown = DIVE_WILLO_COOLDOWN; + + if (npc.stateFrame < DIVE_LAYING_FRAMES) + { + if (npc.stateFrame % 2 == 0) dive_group_lay(npc); + } + else if ((npc.stateFrame - DIVE_WAKE_FIRST) % DIVE_WAKE_EVERY == 0) dive_group_wake(npc); + } + return; + } + if (npc.i2 == 2) + { + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame <= DIVE_RETURN_FRAMES) return; + npc.i2 = 3; + npc.sprite.Play("Back"); + for (Entity_NPC* willo : min_min_willos(npc)) + { + if (willo->state != WILLO_DIVE) continue; + willo->state = WILLO_RISE; + willo_place(*willo, WILLO_SPAWN_SLOT, DIVE_RISE_RADIUS); + } + return; + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.shadowSize = npc.config->shadowSize; + } + if (!npc.sprite.IsPlaying()) npc.state = NPC_STATE_IDLE; +} + +// Its spit of one Willo, flung at its target. +static void min_min_spit(Entity_NPC& npc) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc.PlaySound(SOUND_LITTLE_SPIT, 1, 2, false, 1); + Entity_NPC* willo = willo_spawn(npc.pos, &npc, SPAWN_RING_RADIUS, 0); + willo->maxHitPoints *= SPIT_WILLO_HEALTH; + willo->health = willo->maxHitPoints; + willo_siblings_spread(*willo); + + Vector aim = vector_scale(vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)), MIN_MIN_SPIT_SPEED); + float angle = ((Random() & 1) == 0 ? -SPIT_ANGLE : SPIT_ANGLE) * DEGREES_TO_RADIANS; + Vector fling = vector_make(aim.x * std::cos(angle) - aim.y * std::sin(angle), + aim.x * std::sin(angle) + aim.y * std::cos(angle)); + willo->targetPosition = fling; + willo->velocity = fling; + willo->sprite.Play("Attack", PLAY_FORCED); + willo->sprite.SetFrame((float)SPIT_ATTACK_FRAME); + willo->state = WILLO_HURLED; + npc.projectileCooldown = MIN_MIN_SPIT_COOLDOWN; +} + +// Its spit of four Willos onto their ring, then a spin or (turned) a throw. +static void min_min_spit_four(Entity_NPC& npc) +{ + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + std::array willos{}; + for (Entity_NPC*& willo : willos) + { + willo = willo_spawn(npc.pos, &npc, SPAWN_RING_RADIUS, 0); + willo->maxHitPoints *= SPIT_WILLO_HEALTH; + willo->health = willo->maxHitPoints; + } + willo_siblings_spread(*willos[0]); + for (Entity_NPC* willo : willos) willo_place(*willo, WILLO_SPAWN_SLOT, willo->v1.x * WILLO_RING_OUTSIDE); + } + if (npc.sprite.IsPlaying()) return; + } + npc.state = npc.i1 == 0 ? WILLO_ATTACK : (~Random() & 1) | NPC_STATE_ATTACK; +} + +// Its spin: its Willos swing in on its first frame and all shoot their ring on Shoot. +static void min_min_spin(Entity_NPC& npc) +{ + npc.sprite.Play(npc.i1 < 1 ? "Spin" : "Spin2"); + if (npc.stateFrame == 0) + { + for (Entity_NPC* willo : min_min_willos(npc)) willo->v1.y = SPIN_RING_STRETCH; + npc.stateFrame++; + } + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc.PlaySound(SOUND_FLAME_BURST, 1, 2, false, 1); + for (Entity_NPC* willo : min_min_willos(npc)) + { + willo->sprite.Play("Attack", PLAY_FORCED); + willo->sprite.SetFrame((float)SPIN_ATTACK_FRAME); + willo->state = WILLO_RING_ATTACK; + willo->stateFrame = 0; + } +} + +// Its throw: the head flung at where its target will be, its Willos following it. +static void min_min_throw(Entity_NPC& npc) +{ + npc.sprite.Play("Throw"); + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + Entity* target = npc.GetPlayerTarget(); + float distance = vector_length(vector_sub(npc.pos, target->pos)); + Vector lead = vector_add(target->pos, vector_scale(target->velocity, distance * THROW_LEAD)); + Vector aim = vector_scale(vector_normalized(vector_sub(lead, npc.pos)), MIN_MIN_THROW_SPEED); + auto* head = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_MIN_MIN, .variant = MIN_MIN_HEAD, .seed = Random()})); + head->parent = &npc; + npc.child = head; + head->v2 = vector_make(vector_angle(aim), vector_length(aim)); + for (Entity_NPC* willo : min_min_willos(npc)) willo->parent = head; + head->isVisible = false; + head->Update(); +} + +// Its walk, and 1 time in 4 once rested the choice of an attack by how many Willos are about. +static void min_min_walk(Entity_NPC& npc) +{ + npc.sprite.Play(npc.i1 < 1 ? "Walk" : "Walk2"); + Vector goal = npc.CalcTargetPosition(0); + int total = 0; + if (npc.HasEntityFlags(MIN_MIN_DAZED)) npc.targetPosition = {}; + else if (npc.IsFrame(MIN_MIN_WANDER_FRAMES, 0)) + { + if (min_min_willos_count(npc, total) > MIN_MIN_GUARD) npc.targetPosition = {}; + else + for (int i = 0; i < MIN_MIN_WANDER_TRIES; i++) g_game->room->GetRandomPosition(MIN_MIN_WANDER_MARGIN); + } + float speed = MIN_MIN_WALK_SPEED; + if (!vector_is_zero(npc.targetPosition)) + { + speed = MIN_MIN_WANDER_SPEED; + goal = {}; + } + npc.pathfinder.FindGridPath(goal, speed, 0, DIRECT_PATH_FAR); + if (npc.child || npc.projectileDelay >= 1 || (Random() & MIN_MIN_ATTACK_MASK) != 0) return; + + int own = min_min_willos_count(npc, total); + bool isTurned = npc.i1 > 0; + npc.stateFrame = 0; + npc.i2 = 0; + if (total < MIN_MIN_WILLOS_MAX + (isTurned ? MIN_MIN_WILLOS_MAX_TURNED : 0)) + { + if (own < SPIT_OWN_MAX + (isTurned ? SPIT_OWN_MAX_TURNED : 0) && random_below(MIN_MIN_SPIT_ODDS + isTurned) == 0) + { + npc.state = NPC_STATE_SUMMON; + npc.sprite.Play(npc.i1 < 1 ? "Spit" : "Spit2"); + npc.projectileDelay = (int)(Random() % SPIT_DELAY_RANGE) + SPIT_DELAY_MIN; + } + else if (own < SPIT_FOUR_OWN_MAX + (isTurned ? SPIT_FOUR_OWN_MAX_TURNED : 0) && Random() % SPIT_FOUR_ODDS == 0) + { + npc.state = NPC_STATE_SUMMON2; + npc.sprite.Play(npc.i1 < 1 ? "Spit" : "Spit2"); + npc.projectileDelay = (int)(Random() % ATTACK_DELAY_RANGE) + ATTACK_DELAY_MIN; + } + else if (isTurned && (Random() & DIVE_ODDS_MASK) == 0) + { + npc.state = NPC_STATE_JUMP; + npc.sprite.Play("Dive"); + for (Entity_NPC* willo : min_min_willos(npc)) willo->state = WILLO_DIVE; + npc.projectileDelay = (int)(Random() % ATTACK_DELAY_RANGE) + ATTACK_DELAY_MIN; + } + } + if (npc.state != NPC_STATE_IDLE || npc.projectileCooldown >= 1 || own <= MIN_MIN_GUARD || Random() % SPIN_ODDS != 0) + return; + npc.state = npc.i1 == 0 ? NPC_STATE_ATTACK : (~Random() & 1) | NPC_STATE_ATTACK; + npc.projectileDelay = (int)(Random() % ATTACK_DELAY_RANGE) + ATTACK_DELAY_MIN; +} + +// Its turn below 40%: it rises again stronger, its Willos back to their full ring. +static void min_min_turn_check(Entity_NPC& npc) +{ + float threshold = npc.maxHitPoints * MIN_MIN_TURN_SHARE; + if (npc.i1 != 0 || npc.health >= threshold) return; + + npc.i1 = 1; + npc.state = NPC_STATE_SPECIAL; + npc.sprite.Play("Transition"); + npc.entityCollisionClass = ENTCOLL_NONE; + for (Entity_NPC* willo : min_min_willos(npc)) willo->v1.y = 1; +} + +// Its last frames: its spawners and thrown heads go, and its Willos and their followers die with it. +static void min_min_death_clear(Entity_NPC& npc) +{ + for (Entity* entity : g_game->room->entityList.updateEL) + { + Entity* parent = entity->parent.get(); + if (parent != &npc && (!parent || parent->parent.get() != &npc)) continue; + + if (entity->IsType(ENTITY_EFFECT, EFFECT_WILLO_SPAWNER, -1) || entity->type == ENTITY_MIN_MIN) entity->Remove(); + else if (entity->type == ENTITY_WILLO) entity->Kill(EntityRef()); + } +} + +// 004cf690 (NpcAI::ENTITY_MIN_MIN) Min-Min and its thrown head: walking, spitting and spinning its Willos, throwing +// its head, diving, and turning below 40% health. +void boss_min_min_update(Entity_NPC& npc) +{ + if (npc.variant == MIN_MIN_HEAD) min_min_head_update(npc); + else + { + npc.friction *= MIN_MIN_FRICTION; + min_min_turn_check(npc); + if (npc.projectileDelay > 0 && npc.pendingDamage > 0) + npc.projectileDelay = std::max((int)((float)npc.projectileDelay - npc.pendingDamage), 0); + + bool isEndChecked = true; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_IDLE; + npc.splatColor = MIN_MIN_SPLAT_COLOR; + npc.shadowSize = npc.config->shadowSize * 2; + npc.mass = npc.config->mass * 2; + isEndChecked = false; + break; + case NPC_STATE_IDLE: + min_min_walk(npc); + isEndChecked = false; + break; + case NPC_STATE_JUMP: + min_min_dive(npc); + isEndChecked = false; + break; + case NPC_STATE_ATTACK: + min_min_spin(npc); + break; + case NPC_STATE_ATTACK2: + min_min_throw(npc); + break; + case NPC_STATE_SUMMON: + min_min_spit(npc); + break; + case NPC_STATE_SUMMON2: + min_min_spit_four(npc); + isEndChecked = false; + break; + case NPC_STATE_SPECIAL: + npc.friction *= MIN_MIN_TURN_FRICTION; + if (!npc.sprite.IsEventTriggered("Shoot")) break; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.shadowSize = npc.config->shadowSize; + npc.mass = npc.config->mass; + npc.PlaySound(SOUND_ROCKET_BLAST_DEATH, 1, 2, false, 1); + game_shake_screen(MIN_MIN_SHAKE); + npc.MakeBloodPoof(npc.pos, npc.splatColor, 1); + break; + default: + isEndChecked = false; + break; + } + if (isEndChecked && !npc.sprite.IsPlaying()) npc.state = NPC_STATE_IDLE; + } + + int ticks = npc_ticks_get(npc); + if (npc.projectileCooldown > 0) npc.projectileCooldown -= ticks; + if (npc.projectileDelay > 0) npc.projectileDelay -= ticks; + if (npc.isDead) min_min_death_clear(npc); +} + +// Min-Min's death bursts: a splash of blood from its BloodGuide on each Shoot, and on its last frame a poof and a +// brief orange flash there. +constexpr int DEATH_BLOOD_SUBTYPE = 2; +constexpr float DEATH_FLASH_GREEN = 0.6f; +constexpr float DEATH_FLASH_SCALE = 0.75f; +constexpr int DEATH_FLASH_FRAMES = 3; +constexpr float MIN_MIN_SCREEN_SCALE = 0.65f; + +// 006c4b30 (Entity_NPC::Update's death events for Min-Min) Its blood bursts and, at the end, its poof and flash. +void min_min_death_update(Entity_NPC& npc) +{ + const NullFrame* guide = npc.sprite.IsEventTriggered("Shoot") ? npc.sprite.GetNullFrame("BloodGuide") : nullptr; + if (!guide) return; + + Entity* blood = g_game->Spawn({.position = npc.pos, + .subType = DEATH_BLOOD_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->sprite.offset = guide->pos; + blood->SetColor(npc.splatColor, -1, 255, false, true); + npc_sound_play(SOUND_DEATH_BURST_SMALL, 1, 2, 1); + if (npc.sprite.GetFrame() < npc.sprite.animState.animData->length - 1) return; + + npc_sound_play(SOUND_STEAM_HALFSEC, 1, 2, 1); + Entity* poof = g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->sprite.offset = guide->pos; + Entity_Effect* flash = effect_light_create({.color = kcolor_rgba(1, DEATH_FLASH_GREEN, 0, 1), + .position = npc.pos, + .scale = DEATH_FLASH_SCALE, + .fadeFrames = DEATH_FLASH_FRAMES, + .timeout = DEATH_FLASH_FRAMES}); + flash->posOffset = vector_scale(guide->pos, 1 / MIN_MIN_SCREEN_SCALE); + flash->sprite.SetFrame(1.0f); + layer_additive_set(*flash->sprite.GetLayer(0)); +} diff --git a/src/boss_rag_man.cpp b/src/boss_rag_man.cpp new file mode 100644 index 0000000..70a7ec5 --- /dev/null +++ b/src/boss_rag_man.cpp @@ -0,0 +1,901 @@ +#include "boss_ai.h" +#include "npc_caves.h" +#include "entity_player.h" +#include "player_manager.h" +#include "room_grid.h" +#include +#include + +// Rag Man's parts: the boss and his rolling head. Rag Mega's: the boss, its purple balls and its rebirth pillars. +constexpr int RAG_MAN_HEAD = 1; +constexpr int RAG_MEGA_BALL = 1; +constexpr int RAG_MEGA_PILLAR = 2; + +// Rag Man's subtypes: the plain one, the one that summons and revives only, and the one whose heads turn to spiders. +constexpr int RAG_MAN_SUMMONER = 1; +constexpr int RAG_MAN_SPIDERS = 2; + +// Rag Man's states: walking, headless, shooting, throwing his head and reviving his Raglings. +constexpr int RAG_MAN_HEADLESS = NPC_STATE_IDLE; +constexpr int RAG_MAN_SHOOT = NPC_STATE_ATTACK; +constexpr int RAG_MAN_THROW = NPC_STATE_SUMMON; +constexpr int RAG_MAN_REBIRTH = NPC_STATE_SUMMON2; +constexpr int RAGLING_DEAD = NPC_STATE_SPECIAL; +constexpr int RAGLING_REGEN = NPC_STATE_APPEAR_CUSTOM; + +constexpr ColorMod RAG_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.35f, 0.11f, 0.36f}}; + +constexpr float RAG_MAN_WALL_MARGIN = 80; +constexpr float RAG_MAN_PATH_SPEED = 1.05f; +constexpr int RAG_MAN_PATH_MARKER = 900; +constexpr float RAG_MAN_IDLE_SPEED = 1; +constexpr int RAG_MAN_REBIRTH_READY = 120; +constexpr float RAG_MAN_REBIRTH_REACH = 70; +constexpr float RAG_MAN_GUARD_OFFSET = 60; +constexpr float RAG_MAN_CLAMP_MARGIN = 60; +constexpr float RAG_MAN_FAR = 9999999; +constexpr uint32_t RAG_MAN_SPIDER_REBIRTH_ODDS = 100; +constexpr int RAG_MAN_SHOOT_CHECK_FRAMES = 15; +constexpr uint32_t RAG_MAN_SHOOT_PERCENT = 20; +constexpr uint32_t RAG_MAN_PERCENT = 100; +constexpr float RAG_MAN_FRICTION = 0.8f; +constexpr float RAG_MAN_HEADLESS_FRICTION = 0.75f; +constexpr float RAG_MAN_WANDER_DRAG = 1.1f; +constexpr int RAG_MAN_COOLDOWN_MIN = 40; +constexpr uint32_t RAG_MAN_COOLDOWN_RANGE = 20; +constexpr int RAG_MAN_SHOOT_COOLDOWN = 90; +constexpr float RAG_MAN_TRAIL_SPEED = 5; +constexpr float RAG_MAN_TRAIL_FALL_ACCEL = 0.3f; +constexpr float RAG_MAN_TRAIL_FALL_SPEED = -5; +constexpr float RAG_MAN_SHOT_SPEED = 7; +constexpr float RAG_MAN_SHOT_OFFSET = 16; +constexpr float RAG_MAN_HEAD_OFFSET = 57; +constexpr float RAG_MAN_HEAD_SPEED = 10; +constexpr float RAG_MAN_DELIRIUM_HEAD_HEALTH = 8; +constexpr float RAG_MAN_HEAL = 0.05f; +constexpr float RAG_MAN_REVIVE_REACH = 100; +constexpr float RAG_MAN_REVIVE_SHOT_CURVE = 10; +constexpr int RAG_MAN_REVIVE_SHOTS = 3; +constexpr float RAGLING_HEAL = 0.25f; + +constexpr int HEAD_ROLL_MIN = 60; +constexpr float RAG_HEAD_ROLL_RANGE = 45; +constexpr float HEAD_SLOW_START = 75; +constexpr float HEAD_SLOW_END = 15; +constexpr float HEAD_FAST_SPEED = 10; +constexpr float HEAD_SLOWDOWN = 8; +constexpr float HEAD_STEER = 0.15f; +constexpr float HEAD_SPIN_SPEED = 10; +constexpr int HEAD_DAMAGE_COUNTDOWN = 30; +constexpr float HEAD_SUMMONER_HEALTH = 0.66f; +constexpr float HEAD_RAGLING_MIN_HEALTH = 0.5f; + +constexpr float MEGA_WALL_MARGIN = 40; +constexpr float MEGA_DRIFT = 0.4f; +constexpr float MEGA_SPIDER_FRICTION = 0.9f; +constexpr float MEGA_FLEE_REACH = 180; +constexpr float MEGA_FLEE_SCALE = 0.02f; +constexpr int MEGA_BALLS = 3; +constexpr float MEGA_BALL_ORBIT = 50; +constexpr int MEGA_RAGLING_LIMIT = 3; +constexpr uint32_t MEGA_SUMMON_ODDS_PER_RAGLING = 100; +constexpr uint32_t MEGA_REBIRTH_ODDS = 70; +constexpr uint32_t MEGA_COVER_ODDS = 45; +constexpr int MEGA_COVER_MIN = 60; +constexpr uint32_t MEGA_COVER_RANGE = 30; +constexpr int MEGA_COVER_GUARD_FRAMES = 20; +constexpr int MEGA_ATTACK_FRAME = 20; +constexpr float MEGA_PUFF_ANGLE = 90; +constexpr float MEGA_PUFF_HEIGHT = -40; +constexpr ColorMod MEGA_PUFF_COLOR = {{0, 0, 0, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float MEGA_RAGLING_DROP = 10; +constexpr float MEGA_DELIRIUM_RAGLING_HEALTH = 15; +constexpr float MEGA_PILLAR_SPEED = 10; +constexpr float MEGA_PILLAR_REACH = 40; + +constexpr ColorMod BALL_COLOR = {{1.3f, 0.8f, 1.3f, 1}, {0, 0, 0, 0}, {0.2f, 0, 0.2f}}; +constexpr ColorMod MEGA_BALL_SPLAT_COLOR = {{0, 0, 0, 1.1f}, {0, 0, 0, 0}, {0.5f, 0, 0.5f}}; +constexpr ColorMod BALL_BARE_SPLAT_COLOR = {{0, 0, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float BALL_HEIGHT = -40; +constexpr float BALL_FRICTION = 0.8f; +constexpr float BALL_DRAG = 1.1764705f; +constexpr float BALL_CHASE = 0.5f; +constexpr float MEGA_BALL_MASS = 8; +constexpr float BALL_GLOW_FRAMES = 30; +constexpr float BALL_SPACING = 100; +constexpr float BALL_SPACING_PUSH = 0.003f; +constexpr float BALL_LAUNCH_SPEED = 10; +constexpr int BALL_ORBIT_BLEND_FRAMES = 25; +constexpr float BALL_ORBIT_BLEND = 30; +constexpr float BALL_TRAIL_BACK = -0.5f; +constexpr float BALL_TRAIL_SCATTER = 0.4f; +constexpr int BALL_TRAIL = 2; + +// What Rag Man sees each frame: his Raglings (and spiders), his heads still rolling, and where to walk or revive. +struct RagManView +{ + std::vector raglings; + Vector destination{}; + Vector reviveSpot = vector_make(RAG_MAN_FAR, RAG_MAN_FAR); + int active = 0; + int children = 0; + int heads = 0; + int maxActive = 0; + int maxChildren = 0; + bool isDestinationFound = false; + bool isThrowLeft = false; +}; + +// Raises a Ragling playing dead, or heals a standing one by a quarter of its health. +static void ragling_revive(Entity& ragling) +{ + auto& npc = static_cast(ragling); + if (npc.state == RAGLING_DEAD) + { + npc.state = RAGLING_REGEN; + return; + } + npc.health = std::min(npc.health + npc.maxHitPoints * RAGLING_HEAL, npc.maxHitPoints); +} + +// Rag Man's limits for his health: Raglings and heads out at once (all four for the summoner). +static void rag_man_limits(Entity_NPC& npc, RagManView& view) +{ + float health = npc.health; + float maxHealth = npc.maxHitPoints; + view.maxChildren = health < maxHealth; + if (health < maxHealth * 0.75f) view.maxChildren = 2; + if (health < maxHealth * 0.55f) view.maxChildren = 3; + if (health < maxHealth * 0.35f) view.maxChildren = 4; + view.maxActive = health < maxHealth; + if (health < maxHealth * 0.6f) view.maxActive = 2; + if (npc.subtype != RAG_MAN_SUMMONER) return; + + view.maxChildren = 4; + view.maxActive = 4; +} + +// Counts Rag Man's heads, Raglings and spiders, and picks where to walk: the nearest Ragling playing dead once he +// may revive, else beside the nearest standing one, on its far side from the target. +static RagManView rag_man_look(Entity_NPC& npc, const Vector& targetPos) +{ + RagManView view; + rag_man_limits(npc, view); + view.raglings = entity_query(ENTITY_RAGLING, RAGLING_RAG_MAN); + for (Entity* head : entity_query(ENTITY_RAG_MAN, -1)) + if (head->variant == RAG_MAN_HEAD && head->parent.get() == &npc) view.heads++; + + int dead = 0; + for (Entity* ragling : view.raglings) + { + if (ragling->parent.get() == &npc) view.children++; + if (static_cast(ragling)->state == RAGLING_DEAD) dead++; + } + if (npc.subtype == RAG_MAN_SPIDERS) + for (Entity* spider : entity_query(ENTITY_SPIDER, -1)) + if (spider->parent.get() == &npc) view.children++; + view.active = view.children - dead; + + float closest = RAG_MAN_FAR; + bool isReviveFound = false; + for (Entity* ragling : view.raglings) + { + float distance = vector_length(vector_sub(ragling->pos, npc.pos)); + if (static_cast(ragling)->state == RAGLING_DEAD) + { + if ((isReviveFound && distance >= closest) || npc.i1 < RAG_MAN_REBIRTH_READY || view.active >= view.maxActive) + continue; + view.destination = ragling->pos; + view.reviveSpot = ragling->pos; + view.isDestinationFound = true; + isReviveFound = true; + closest = distance; + } + else if (distance < closest && !isReviveFound) + { + Vector away = vector_normalized(vector_sub(ragling->pos, targetPos)); + Vector guard = vector_add(ragling->pos, vector_scale(away, RAG_MAN_GUARD_OFFSET)); + view.destination = g_game->room->GetClampedPositionImpl(guard, RAG_MAN_CLAMP_MARGIN, RAG_MAN_CLAMP_MARGIN, + RAG_MAN_CLAMP_MARGIN, RAG_MAN_CLAMP_MARGIN); + view.isDestinationFound = true; + closest = distance; + } + } + return view; +} + +// Walking: toward his chosen spot, then a head throw while he may have more out, a rebirth beside a fallen Ragling, +// now and then a volley at a target lined up sideways. +static void rag_man_walk(Entity_NPC& npc, const RagManView& view, bool isTargetSideways, bool isTargetLeft) +{ + Vector goal = npc.CalcTargetPosition(0); + if (view.isDestinationFound && !npc.HasEntityFlags(FLAG_DISTRACTED | FLAG_CHARM)) goal = view.destination; + npc.pathfinder.movementTarget = {}; + npc.pathfinder.moveDirection = {}; + npc.pathfinder.FindGridPath(goal, RAG_MAN_PATH_SPEED, RAG_MAN_PATH_MARKER, DIRECT_PATH_FAR); + + npc.sprite.isFlipX = false; + if (vector_length(npc.velocity) <= RAG_MAN_IDLE_SPEED) npc_anim_loop(npc.sprite, "Idle"); + else if (std::abs(npc.velocity.x) <= std::abs(npc.velocity.y)) npc_anim_loop(npc.sprite, "WalkVert"); + else npc_anim_loop(npc.sprite, npc.velocity.x >= 0 ? "WalkRight" : "WalkLeft"); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + + if (npc.i1 >= RAG_MAN_REBIRTH_READY || npc.subtype == RAG_MAN_SUMMONER) + { + if (view.children < view.maxChildren && view.active < view.maxActive) + { + npc.state = RAG_MAN_THROW; + npc_sound_play(SOUND_RAGMAN_3, 1, 2, 1); + return; + } + if (npc.i1 >= RAG_MAN_REBIRTH_READY && vector_length(vector_sub(npc.pos, view.reviveSpot)) < RAG_MAN_REBIRTH_REACH) + { + npc.state = RAG_MAN_REBIRTH; + return; + } + } + + if (npc.subtype == RAG_MAN_SPIDERS && Random() % RAG_MAN_SPIDER_REBIRTH_ODDS == 0) + { + npc.state = RAG_MAN_REBIRTH; + return; + } + if (!npc.IsFrame(RAG_MAN_SHOOT_CHECK_FRAMES, (int)npc.index)) return; + if (Random() % RAG_MAN_PERCENT >= RAG_MAN_SHOOT_PERCENT || !isTargetSideways) return; + if (npc.projectileCooldown >= 1 || npc.subtype == RAG_MAN_SUMMONER) return; + + npc.state = RAG_MAN_SHOOT; + npc.sprite.isFlipX = isTargetLeft; +} + +// The throw: his head flies off toward the side he faces on Spawn, rolling on as a head of his own. +static void rag_man_throw(Entity_NPC& npc, bool isThrowLeft) +{ + const AnimationData* data = npc.sprite.animState.animData; + bool isThrowing = data && npc.sprite.animState.isPlaying && + (data->name == "HeadThrowLeft" || data->name == "HeadThrowRight"); + if (isThrowing) isThrowLeft = data->name == "HeadThrowLeft"; + else if (!data || (data->name != "HeadThrowLeft" && data->name != "HeadThrowRight")) + npc_anim_loop(npc.sprite, isThrowLeft ? "HeadThrowLeft" : "HeadThrowRight"); + else isThrowLeft = false; + + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Spawn")) + { + float side = isThrowLeft ? -1.0f : 1.0f; + auto* head = static_cast(g_game->Spawn({.position = vector_make(npc.pos.x + side * RAG_MAN_HEAD_OFFSET, npc.pos.y), + .velocity = vector_make(side * RAG_MAN_HEAD_SPEED, 0), + .spawner = &npc, + .subType = npc.subtype, + .type = ENTITY_RAG_MAN, + .variant = RAG_MAN_HEAD, + .seed = Random()})); + head->parent.Set(&npc); + head->ClearEntityFlags(FLAG_APPEAR); + if (head->bosscoloridx != npc.bosscoloridx) + { + head->bosscoloridx = npc.bosscoloridx; + head->load_graphics(true); + head->sprite.SetFrame(head->sprite.GetDefaultAnimationName(), 0); + } + head->ResetColor(); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + { + head->health = RAG_MAN_DELIRIUM_HEAD_HEALTH; + head->maxHitPoints = RAG_MAN_DELIRIUM_HEAD_HEALTH; + } + } + + npc.TakeDamage(-1, 0, EntityRef(), HEAD_DAMAGE_COUNTDOWN); + if (!npc_anim_is_done(npc)) return; + + npc.state = RAG_MAN_HEADLESS; + npc.projectileCooldown = (int)(Random() % RAG_MAN_COOLDOWN_RANGE) + RAG_MAN_COOLDOWN_MIN; +} + +// Headless: wandering (fleeing when feared) and dribbling a falling shot now and then, until his head pops back once +// none of his heads still rolls. +static void rag_man_headless(Entity_NPC& npc, int heads) +{ + npc.friction *= RAG_MAN_HEADLESS_FRICTION; + const AnimationData* data = npc.sprite.animState.animData; + bool isPopping = data && data->name == "HeadPop"; + if (isPopping && !npc.sprite.animState.isPlaying) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.projectileCooldown = 0; + return; + } + if (isPopping) return; + + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + { + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + npc.velocity = vector_scale(npc.velocity, npc_friction_scaled(RAG_MAN_WANDER_DRAG, npc.speedMultiplier)); + } + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= RAG_MAN_FRICTION; + } + if (std::abs(npc.velocity.x) <= std::abs(npc.velocity.y)) npc_anim_loop(npc.sprite, "WalkNoHeadVert"); + else npc_anim_loop(npc.sprite, npc.velocity.x >= 0 ? "WalkNoHeadRight" : "WalkNoHeadLeft"); + + if (npc.projectileCooldown < 1 && !npc.HasEntityFlags(FLAG_DISTRACTED) && npc.subtype != RAG_MAN_SUMMONER) + { + npc.projectileCooldown = (int)(Random() % RAG_MAN_COOLDOWN_RANGE) + RAG_MAN_COOLDOWN_MIN; + ProjectileParams params; + params.fallingAccelModifier = RAG_MAN_TRAIL_FALL_ACCEL; + params.fallingSpeedModifier = RAG_MAN_TRAIL_FALL_SPEED; + params.bulletFlags = PROJECTILE_SMART; + npc.FireProjectiles(npc.pos, vector_scale(vector_normalized(npc.velocity), RAG_MAN_TRAIL_SPEED), + PROJECTILES_SINGLE, params); + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + } + if (heads == 0) npc_anim_loop(npc.sprite, "HeadPop"); +} + +// The volley's pick: one, three or five homing shots, more as he weakens. +static void rag_man_shoot_pick(Entity_NPC& npc) +{ + int pick = (int)(Random() % 3); + if (npc.maxHitPoints * 2 / 3 < npc.health) pick--; + if (npc.health < npc.maxHitPoints / 3) pick++; + + if (pick <= 0) + { + npc.sprite.Play("Shooting1"); + npc_sound_play(SOUND_RAGMAN_1, 1, 2, 1); + } + else if (pick == 1) + { + npc.sprite.Play("Shooting3"); + npc_sound_play(SOUND_RAGMAN_4, 1, 2, 1); + } + else + { + npc.sprite.Play("Shooting5"); + npc_sound_play(SOUND_RAGMAN_2, 1, 2, 1); + } +} + +// The volley: a homing shot at the target from his facing side on each Shoot event, then a long pause. +static void rag_man_shoot(Entity_NPC& npc, const Vector& targetPos) +{ + const AnimationData* data = npc.sprite.animState.animData; + bool isShooting = data && (data->name == "Shooting1" || data->name == "Shooting3" || data->name == "Shooting5"); + if (!isShooting) rag_man_shoot_pick(npc); + + bool isFlipped = npc.sprite.isFlipX; + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_BLOODSHOOT, 1, 2, 1); + ProjectileParams params; + params.bulletFlags = PROJECTILE_SMART; + params.homingStrength = 1; + Vector aim = vector_normalized(vector_sub(targetPos, npc.pos)); + Vector from = vector_make(npc.pos.x + (isFlipped ? -RAG_MAN_SHOT_OFFSET : RAG_MAN_SHOT_OFFSET), npc.pos.y); + npc.FireProjectiles(from, vector_scale(aim, RAG_MAN_SHOT_SPEED), PROJECTILES_SINGLE, params); + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + } + npc.projectileCooldown = RAG_MAN_SHOOT_COOLDOWN; + npc.state = NPC_STATE_MOVE; +} + +// The rebirth: on Revive his Raglings near him rise or heal (the spider one fires a burst instead) and he heals a +// little, past his full health if he must. +static void rag_man_rebirth(Entity_NPC& npc, const std::vector& raglings) +{ + npc_anim_loop(npc.sprite, "Rebirth"); + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("Revive")) + { + npc_sound_play(SOUND_SUMMONSOUND, 1, 2, 1); + npc_sound_play(SOUND_RAGMAN_2, 1, 2, 1); + if (npc.subtype == RAG_MAN_SPIDERS) + { + Vector aim = game_random_player(*g_game, npc.pos, RAG_MAN_FAR)->pos; + npc.FireBossProjectiles(RAG_MAN_REVIVE_SHOTS, aim, RAG_MAN_REVIVE_SHOT_CURVE, ProjectileParams()); + } + else + for (Entity* ragling : raglings) + if (vector_length(vector_sub(ragling->pos, npc.pos)) < RAG_MAN_REVIVE_REACH) ragling_revive(*ragling); + npc.health += npc.maxHitPoints * RAG_MAN_HEAL; + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + } + npc.i1 = 0; + npc.state = NPC_STATE_MOVE; +} + +// Rag Man (405.0): walking with his Raglings, throwing his head to raise more, shooting and reviving the fallen. +// His Raglings die with him. +static void rag_man_update(Entity_NPC& npc) +{ + Vector targetPos = npc.GetPlayerTarget()->pos; + Room& room = *g_game->room; + // The original compares the target's own coordinates, not its offset from Rag Man. + bool isTargetSideways = std::abs(targetPos.y) < std::abs(targetPos.x); + bool isTargetLeft = targetPos.x - npc.pos.x < 0; + bool isThrowLeft = room.topLeftPos.x + RAG_MAN_WALL_MARGIN <= npc.pos.x && isTargetLeft; + if (room.bottomRightPos.x - RAG_MAN_WALL_MARGIN < npc.pos.x) isThrowLeft = true; + + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.i1 = 0; + npc.splatColor = RAG_SPLAT_COLOR; + return; + } + + RagManView view = rag_man_look(npc, targetPos); + npc.i1 = view.active < view.maxActive ? npc.i1 + 1 : 0; + if (npc.projectileCooldown > 0) npc.projectileCooldown--; + + bool isSlowed = true; + switch (npc.state) + { + case NPC_STATE_MOVE: + rag_man_walk(npc, view, isTargetSideways, isTargetLeft); + break; + case RAG_MAN_THROW: + rag_man_throw(npc, isThrowLeft); + break; + case RAG_MAN_SHOOT: + rag_man_shoot(npc, targetPos); + break; + case RAG_MAN_REBIRTH: + rag_man_rebirth(npc, view.raglings); + break; + case RAG_MAN_HEADLESS: + rag_man_headless(npc, view.heads); + isSlowed = false; + break; + default: + isSlowed = false; + } + if (isSlowed) npc.friction *= RAG_MAN_FRICTION; + if (!npc.isDead || npc.IsFriendly()) return; + + for (Entity* ragling : entity_query(ENTITY_RAGLING, RAGLING_RAG_MAN)) + if (!ragling->IsFriendly()) ragling->Kill(EntityRef(&npc)); +} + +// His head drops what it rolled into: a Ragling (two thirds as tough for the summoner, hurt as he is hurt) or, for +// the spider one, a spider or two. A head dying while he lives leaves a Ragling playing dead. +static void rag_man_head_drop(Entity_NPC& npc) +{ + uint32_t seed = Random(); + if (npc.subtype == RAG_MAN_SPIDERS) + { + for (uint32_t i = (seed & 1) + 1; i > 0; i--) + { + Entity* spider = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_SPIDER, .seed = Random()}); + spider->parent.Set(npc.parent.get()); + } + return; + } + + auto* ragling = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = npc.velocity, + .spawner = &npc, + .type = ENTITY_RAGLING, + .variant = RAGLING_RAG_MAN, + .seed = seed})); + if (!ragling) return; + + ragling->parent.Set(npc.parent.get()); + ragling->SetBossColorIdx(npc.bosscoloridx, 0); + if (!npc.isDead) + { + float health = ragling->maxHitPoints; + if (npc.subtype == RAG_MAN_SUMMONER) + { + health *= HEAD_SUMMONER_HEALTH; + ragling->maxHitPoints = health; + ragling->health = health; + } + float hurt = std::clamp(npc.health / npc.maxHitPoints, 0.0f, 1.0f); + ragling->health = (health - health * HEAD_RAGLING_MIN_HEALTH) * hurt + health * HEAD_RAGLING_MIN_HEALTH; + } + else if (!npc.parent.get()) ragling->Remove(); + else + { + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + ragling->ClearEntityFlags(FLAG_APPEAR); + ragling->Update(); + ragling->isDead = true; + } +} + +// Rag Man's head (405.1): it rolls at the target, fast at first and slowing, passing its hurts to him, then drops +// what it carries. A charmed head keeps rolling. +static void rag_man_head_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.i1 = HEAD_ROLL_MIN + (int)(random_unit() * RAG_HEAD_ROLL_RANGE); + npc.splatColor = RAG_SPLAT_COLOR; + return; + } + + int slowStart = (int)((float)npc.i1 - HEAD_SLOW_START); + int slowEnd = (int)((float)npc.i1 - HEAD_SLOW_END); + Entity* parent = npc.parent.get(); + if (parent && npc.spawnerType != ENTITY_RAG_MEGA) + for (DamageEvent& event : npc.damageEvents) + parent->TakeDamage(event.damage, event.damageFlags, event.source, HEAD_DAMAGE_COUNTDOWN); + + npc.stateFrame++; + if (npc.HasEntityFlags(FLAG_CHARM)) + { + npc.stateFrame = 0; + npc.state = NPC_STATE_MOVE; + } + if (npc.state == NPC_STATE_MOVE) + { + if (slowStart == slowEnd) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!"); + float slowdown = std::clamp((float)(npc.stateFrame - slowStart) / (float)(slowEnd - slowStart), 0.0f, 1.0f); + float speed = HEAD_FAST_SPEED - slowdown * HEAD_SLOWDOWN; + Vector toTarget = vector_normalized(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + Vector heading = vector_normalized(npc.velocity); + Vector steer = vector_add(vector_add(vector_scale(toTarget, speed * HEAD_STEER), npc.velocity), + vector_scale(heading, speed * HEAD_STEER)); + steer = vector_resized(steer, speed); + float keep = npc_friction_scaled(RAG_MAN_FRICTION, npc.speedMultiplier); + npc.velocity = vector_add(vector_scale(vector_sub(steer, npc.velocity), 1 - keep), npc.velocity); + + constexpr std::string_view ROLLS[] = {"RollLeft", "RollUp", "RollRight"}; + int direction = npc.get_velocity_direction(); + npc.sprite.Play(direction >= 0 && direction < 3 ? ROLLS[direction] : "RollDown"); + if (npc.stateFrame > slowEnd) npc.state = NPC_STATE_IDLE; + } + + bool isRolling = (npc.state != NPC_STATE_IDLE || npc.stateFrame <= npc.i1) && !npc.isDead; + if (isRolling) + { + npc.sprite.playbackSpeed = std::clamp(vector_length(npc.velocity) / HEAD_SPIN_SPEED, 0.0f, 1.0f) * 2; + npc.friction *= RAG_MAN_FRICTION; + return; + } + rag_man_head_drop(npc); + npc.Remove(); +} + +// 00493200 Rag Man (405): the boss and his rolling head. +void boss_rag_man_update(Entity_NPC& npc) +{ + if (npc.variant == 0) return rag_man_update(npc); + if (npc.variant == RAG_MAN_HEAD) rag_man_head_update(npc); +} + +// Rag Mega's purple balls fly free (spawning a Ragling each fall) as it weakens, or circle it while it is strong. +static void mega_ball_orbit(Entity_NPC& npc) +{ + Entity_NPC* mega = npc.ParentNPC(); + if (!mega) return; + + int count = std::max(1, mega->i1); + float health = mega->health / mega->maxHitPoints; + int orbiting = mega->i1; + bool isLaunch = health < 0.25f; + bool isCounted = (health >= 0.25f && health < 0.5f && npc.i1 > 0) || (health >= 0.5f && health < 0.75f && npc.i1 == 2); + if (isCounted) + { + isLaunch = true; + mega->i1--; + } + if (isLaunch) + { + npc.state = NPC_STATE_MOVE; + npc.PlaySound(SOUND_RAGMEGA_BALL_ATTACK, 1, 2, false, 1); + npc_push(npc, vector_resized(vector_sub(npc.pos, mega->pos), BALL_LAUNCH_SPEED)); + } + else + { + if (npc.i2 != orbiting) + { + npc.stateFrame = BALL_ORBIT_BLEND_FRAMES; + npc.i2 = orbiting; + } + float frames = (float)(g_game->frameCount - npc.spawnFrame); + float angle = (((float)npc.i1 / (float)count) * 360 + frames + frames) * DEGREES_TO_RADIANS; + float blend = 1 - (float)npc.stateFrame / BALL_ORBIT_BLEND; + Vector spot = vector_make(std::cos(angle) * MEGA_BALL_ORBIT + mega->pos.x, std::sin(angle) * MEGA_BALL_ORBIT + mega->pos.y); + npc.velocity = vector_scale(vector_sub(spot, npc.pos), blend); + } +} + +// A free ball chases the target, keeping 100 from its fellows, its glow fading as it loses its guard. +static void mega_ball_chase(Entity_NPC& npc) +{ + npc.friction *= BALL_FRICTION; + Vector toTarget = vector_sub(npc.CalcTargetPosition(0), npc.pos); + npc.velocity = vector_scale(npc.velocity, npc_friction_scaled(BALL_DRAG, npc.speedMultiplier)); + npc_push(npc, vector_scale(vector_normalized(toTarget), BALL_CHASE)); + npc.mass = MEGA_BALL_MASS; + if (npc.v2.y > 0) + { + npc.v2.y -= npc.speedMultiplier; + float glow = std::clamp(npc.v2.y / BALL_GLOW_FRAMES, 0.0f, 1.0f); + npc.sprite.GetLayer(0)->color = color_lerp(COLOR_DEFAULT, BALL_COLOR, glow); + if (glow < 0.5f) + { + npc.splatColor = BALL_BARE_SPLAT_COLOR; + npc.isInvincible = false; + } + } + + for (Entity* other : entity_query(npc.type, npc.variant)) + { + Vector away = vector_sub(npc.pos, other->pos); + float distance = vector_length(away); + if (other == &npc || distance >= BALL_SPACING) continue; + if (distance > 0) away = vector_scale(away, (BALL_SPACING - distance) / distance); + npc_push(npc, vector_scale(away, BALL_SPACING_PUSH)); + } +} + +// A ball's trail: a smoke particle in its own color drifting back from it, scattered by its speed. +static void mega_ball_trail(Entity_NPC& npc) +{ + Entity* smoke = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = BALL_TRAIL, + .type = ENTITY_EFFECT, + .variant = EFFECT_DARK_BALL_SMOKE_PARTICLE, + .seed = Random()}); + smoke->SetColor(npc.sprite.GetLayer(0)->color, -1, COLOR_PRIORITY_DEFAULT, false, true); + smoke->velocity = vector_scale(npc.velocity, BALL_TRAIL_BACK); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float scatter = random_unit() * vector_length(npc.velocity) * BALL_TRAIL_SCATTER; + npc_push(*smoke, vector_make(std::cos(angle) * scatter, std::sin(angle) * scatter)); + smoke->posOffset = vector_make(0, BALL_HEIGHT); +} + +// Rag Mega's purple ball (409.1): circling it, then chasing the target, dying with it. +static void mega_ball_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.sprite.GetLayer(0)->color = BALL_COLOR; + npc.splatColor = MEGA_BALL_SPLAT_COLOR; + npc.posOffset.y = BALL_HEIGHT; + npc.state = NPC_STATE_IDLE; + npc.i2 = MEGA_BALLS; + return; + } + if (npc.state == NPC_STATE_MOVE) mega_ball_chase(npc); + else if (npc.state == NPC_STATE_IDLE) + { + mega_ball_orbit(npc); + if (npc.stateFrame > 0) npc.stateFrame--; + } + + if (!npc.parent.get()) npc.Kill(EntityRef()); + mega_ball_trail(npc); + npc_anim_loop(npc.sprite, "Idle"); +} + +// Rag Mega's rebirth pillar (409.2): sliding off, it raises or heals the Raglings it passes, gone at a wall or once +// its animation ends. +static void mega_pillar_update(Entity_NPC& npc) +{ + npc.state = NPC_STATE_IDLE; + for (Entity* ragling : entity_query(ENTITY_RAGLING, RAGLING_RAG_MAN)) + if (vector_length(vector_sub(ragling->pos, npc.pos)) < MEGA_PILLAR_REACH) ragling_revive(*ragling); + if (npc.isCollidesWithGrid) npc.Remove(); + npc_anim_loop(npc.sprite, "Rebirth Pillar"); + if (npc_anim_is_done(npc)) npc.Remove(); +} + +// Rag Mega drifts diagonally, bouncing off the walls (the top kept 40 clear), fleeing a target near it when feared. +static void mega_drift(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector clamped = room.GetClampedPositionImpl(npc.pos, MEGA_WALL_MARGIN, 0, 0, 0); + npc.pos.y = clamped.y; + if (clamped.x == room.bottomRightPos.x) npc.velocity.x = -1; + if (clamped.x == room.topLeftPos.x) npc.velocity.x = 1; + if (npc.pos.y == room.bottomRightPos.y) npc.velocity.y = -1; + if (npc.pos.y == room.topLeftPos.y + MEGA_WALL_MARGIN) npc.velocity.y = 1; + + npc.friction *= RAG_MAN_FRICTION; + if (npc.HasEntityFlags(FLAG_CONFUSION) && !npc.HasEntityFlags(FLAG_CHARM)) + { + if (npc.subtype == RAG_MAN_SPIDERS) npc.friction *= MEGA_SPIDER_FRICTION; + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return; + } + + Vector drift = vector_make(npc.velocity.x > 0 ? 1 : -1, npc.velocity.y < 0.1f ? -1 : 1); + npc_push(npc, vector_scale(drift, MEGA_DRIFT)); + if (npc.subtype == RAG_MAN_SPIDERS) npc.friction *= MEGA_SPIDER_FRICTION; + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) return; + + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float distance = vector_length(away); + float flee = std::clamp((MEGA_FLEE_REACH - distance) * MEGA_FLEE_SCALE, 0.0f, 1.0f); + if (distance > 0) away = vector_scale(away, flee / distance); + npc_push(npc, away); +} + +// Rag Mega's start: three purple balls around it. +static void mega_init(Entity_NPC& npc) +{ + for (int i = 0; i < MEGA_BALLS; i++) + { + uint32_t seed = Random(); + float angle = ((float)i / MEGA_BALLS) * 360 * DEGREES_TO_RADIANS; + Vector spot = vector_make(std::cos(angle) * MEGA_BALL_ORBIT + npc.pos.x, std::sin(angle) * MEGA_BALL_ORBIT + npc.pos.y); + auto* ball = static_cast(g_game->Spawn( + {.position = spot, .spawner = &npc, .type = ENTITY_RAG_MEGA, .variant = RAG_MEGA_BALL, .seed = seed})); + ball->parent.Set(&npc); + ball->ClearEntityFlags(FLAG_APPEAR); + ball->i1 = i; + ball->isInvincible = true; + ball->entityGridCollisionClass = GRIDCOLL_NONE; + ball->entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + ball->Update(); + } + npc.i1 = MEGA_BALLS; + npc.state = NPC_STATE_MOVE; + npc.splatColor = RAG_SPLAT_COLOR; +} + +// Walking: a Ragling summon the fewer it has (none past three), a rebirth when one lies fallen, or its cover. +static void mega_walk(Entity_NPC& npc) +{ + std::vector raglings = entity_query(ENTITY_RAGLING, RAGLING_RAG_MAN); + bool isRaglingDown = false; + for (Entity* ragling : raglings) + if (static_cast(ragling)->state == RAGLING_DEAD) + { + isRaglingDown = true; + break; + } + + npc.stateFrame = 0; + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return npc_anim_loop(npc.sprite, "Walk"); + + uint32_t summonOdds = (uint32_t)raglings.size() * MEGA_SUMMON_ODDS_PER_RAGLING; + if ((summonOdds == 0 || Random() % summonOdds == 0) && raglings.size() < MEGA_RAGLING_LIMIT) + { + npc.state = NPC_STATE_SUMMON; + npc_anim_restart(npc.sprite, "Attack01"); + npc.PlaySound(SOUND_RAGMEGA_INHALE, 1, 2, false, 1); + } + else if (Random() % MEGA_REBIRTH_ODDS == 0 && isRaglingDown) + { + npc.state = NPC_STATE_SUMMON2; + npc_anim_restart(npc.sprite, "Attack02"); + } + else if (Random() % MEGA_COVER_ODDS == 0) + { + npc.state = NPC_STATE_ATTACK; + npc_anim_restart(npc.sprite, "Cover"); + npc.PlaySound(SOUND_RAGMEGA_INVINCIBLE_ON, 1, 2, false, 1); + } + else npc_anim_loop(npc.sprite, "Walk"); +} + +// The cover: invincible under its rags for 60 to 89 frames, then uncovering. False while it holds. +static bool mega_cover(Entity_NPC& npc) +{ + const AnimationData* data = npc.sprite.animState.animData; + if (data && !npc.sprite.animState.isPlaying && data->name == "Cover") + { + npc.sprite.Play("Covered"); + npc.isInvincible = true; + npc.stateFrame = (int)(Random() % MEGA_COVER_RANGE) + MEGA_COVER_MIN; + } + if (npc.stateFrame > 0) + { + if (--npc.stateFrame != 0) return false; + npc.sprite.Play("Uncover"); + npc.PlaySound(SOUND_RAGMEGA_INVINCIBLE_OFF, 1, 2, false, 1); + return false; + } + if (npc.sprite.GetFrame() > MEGA_COVER_GUARD_FRAMES) npc.isInvincible = false; + return true; +} + +// The summon: two dark puffs either side and a Ragling dropped below it. +static void mega_summon(Entity_NPC& npc) +{ + if (npc.stateFrame == MEGA_ATTACK_FRAME) + { + npc.PlaySound(SOUND_RAGMEGA_EXHALE, 1, 2, false, 1); + for (int i = 0; i < 2; i++) + { + auto* puff = static_cast( + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()})); + puff->rotation = i == 0 ? MEGA_PUFF_ANGLE : -MEGA_PUFF_ANGLE; + puff->SetColor(MEGA_PUFF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + puff->posOffset = vector_make(0, MEGA_PUFF_HEIGHT); + puff->Update(); + } + + Entity* ragling = g_game->Spawn({.position = vector_make(npc.pos.x, npc.pos.y + MEGA_RAGLING_DROP), + .velocity = vector_make(0, MEGA_RAGLING_DROP), + .spawner = &npc, + .type = ENTITY_RAGLING, + .variant = RAGLING_RAG_MAN, + .seed = Random()}); + ragling->parent.Set(&npc); + ragling->ClearEntityFlags(FLAG_APPEAR); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + { + ragling->health = MEGA_DELIRIUM_RAGLING_HEALTH; + ragling->maxHitPoints = MEGA_DELIRIUM_RAGLING_HEALTH; + } + } + npc.stateFrame++; +} + +// The rebirth: three pillars sliding out at even angles from a random start. +static void mega_rebirth(Entity_NPC& npc) +{ + if (npc.stateFrame == MEGA_ATTACK_FRAME) + { + float start = random_unit() * 360; + for (int i = 0; i < MEGA_BALLS; i++) + { + uint32_t seed = Random(); + float angle = (((float)i / MEGA_BALLS) * 360 + start) * DEGREES_TO_RADIANS; + auto* pillar = static_cast(g_game->Spawn( + {.position = npc.pos, + .velocity = vector_make(std::cos(angle) * MEGA_PILLAR_SPEED, std::sin(angle) * MEGA_PILLAR_SPEED), + .spawner = &npc, + .type = ENTITY_RAG_MEGA, + .variant = RAG_MEGA_PILLAR, + .seed = seed})); + pillar->parent.Set(&npc); + pillar->ClearEntityFlags(FLAG_APPEAR); + pillar->entityCollisionClass = ENTCOLL_NONE; + pillar->entityGridCollisionClass = GRIDCOLL_WALLS; + pillar->shadowSize = 0; + pillar->Update(); + } + npc.PlaySound(SOUND_RAGMEGA_BEAM, 1, 2, false, 1); + } + npc.stateFrame++; + npc_anim_loop(npc.sprite, "Rebirth"); +} + +// 00495610 Rag Mega (409): the boss bouncing about the room with its purple balls, summoning and reviving Raglings and +// covering itself, and its balls and pillars. +void boss_rag_mega_update(Entity_NPC& npc) +{ + if (npc.variant == RAG_MEGA_BALL) return mega_ball_update(npc); + if (npc.variant == RAG_MEGA_PILLAR) return mega_pillar_update(npc); + if (npc.variant != 0) return; + + mega_drift(npc); + switch (npc.state) + { + case NPC_STATE_INIT: + return mega_init(npc); + case NPC_STATE_MOVE: + return mega_walk(npc); + case NPC_STATE_ATTACK: + if (!mega_cover(npc)) return; + break; + case NPC_STATE_SUMMON: + mega_summon(npc); + break; + case NPC_STATE_SUMMON2: + mega_rebirth(npc); + break; + default: + return; + } + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_MOVE; +} diff --git a/src/boss_reap_creep.cpp b/src/boss_reap_creep.cpp new file mode 100644 index 0000000..ba2c6bb --- /dev/null +++ b/src/boss_reap_creep.cpp @@ -0,0 +1,743 @@ +#include "boss_ai.h" +#include "entity_laser.h" +#include "entity_projectile.h" +#include "level.h" +#include "npc_alt.h" +#include "npc_caves.h" +#include "room_grid.h" +#include +#include + +// Reap Creep's states: idle on the top wall, its leap in, the dash along the wall, its fountain, spray and beam +// attacks, its two summons and the transition between its three phases. +constexpr int REAP_JUMP = NPC_STATE_JUMP; +constexpr int REAP_DASH = NPC_STATE_STOMP; +constexpr int REAP_FOUNTAIN = NPC_STATE_ATTACK; +constexpr int REAP_SPRAY = NPC_STATE_ATTACK2; +constexpr int REAP_BEAM = NPC_STATE_ATTACK3; +constexpr int REAP_WALL_CREEP = NPC_STATE_SUMMON; +constexpr int REAP_SPIDERS = NPC_STATE_SUMMON2; +constexpr int REAP_TRANSITION = NPC_STATE_SPECIAL; +constexpr int REAP_LAST_PHASE = 2; + +constexpr float REAP_FRICTION = 0.6f; +constexpr float REAP_DASH_FRICTION = 0.8f; +constexpr float REAP_WALL_DROP = 8; +constexpr float REAP_JUMP_PULL = 0.25f; +constexpr int REAP_REST_MIN = 30; +constexpr uint32_t REAP_REST_RANGE = 30; +constexpr int REAP_SPRAY_REST_MIN = 60; +constexpr uint32_t REAP_SPRAY_REST_RANGE = 60; +constexpr int REAP_DASH_ENEMY_LIMIT = 3; +constexpr int REAP_SPIDER_ENEMY_LIMIT = 4; + +constexpr float REAP_STRAFE_SPEED = 0.5f; +constexpr float REAP_STRAFE_FAST = 1; +constexpr float REAP_STRAFE_PHASE2 = 0.7f; +constexpr float REAP_STRAFE_THIN_BEAM = 0.4f; +constexpr float REAP_STRAFE_WIDE_BEAM = 0.42f; +constexpr float REAP_STRAFE_PUSH = 5; +constexpr float REAP_STRAFE_MARGIN = 80; +constexpr float REAP_STRAFE_SLACK = 40; +constexpr float REAP_STRAFE_LEAD = 120; +constexpr float REAP_STRAFE_ATTACK_LEAD = 20; +constexpr float REAP_STRAFE_ROW = 32; +constexpr int REAP_STRAFE_HOLD = 6; +constexpr int REAP_WANDER_MIN = 10; +constexpr uint32_t REAP_WANDER_RANGE = 30; +constexpr float REAP_WALK_SPEED = 1; + +constexpr float REAP_DASH_PUSH = 8; +constexpr float REAP_DASH_SLAM_VOLUME = 2; +constexpr int REAP_DASH_SHAKE = 15; +constexpr int REAP_DASH_RAIN = 22; +constexpr float REAP_RAIN_MARGIN = 10; +constexpr float REAP_RAIN_STEP = 64; +constexpr uint32_t REAP_RAIN_SPIDER_ODDS = 3; +constexpr float REAP_RAIN_SPIDER_SPREAD = 20; +constexpr float REAP_RAIN_HEIGHT = -400; +constexpr float REAP_RAIN_FALL_ACCEL = 2; +constexpr float REAP_RAIN_SCALE = 1.2f; +constexpr float REAP_RAIN_SCALE_RANGE = 0.40000004f; +constexpr float REAP_RAIN_FALL_RANGE = 10; + +constexpr int REAP_FOUNTAIN_FRAMES = 60; +constexpr float REAP_FOUNTAIN_PITCH = 0.8f; +constexpr float REAP_FOUNTAIN_SPEED = 12; +constexpr float REAP_FOUNTAIN_HEIGHT = -24; +constexpr float REAP_FOUNTAIN_SCALE = 1.8f; +constexpr float REAP_FOUNTAIN_SCALE_RANGE = 0.79999995f; +constexpr float REAP_FOUNTAIN_FALL = 2; +constexpr float REAP_FOUNTAIN_SPREAD = 13; +constexpr float REAP_FOUNTAIN_DROP = 5; +constexpr float REAP_RIGHT_ANGLE = 1.5707964f; + +constexpr float REAP_SPRAY_JITTER = 20; +constexpr float REAP_SPRAY_LOW = 30; +constexpr float REAP_SPRAY_HIGH = 150; +constexpr float REAP_SPRAY_CLAMP_LOW = 75; +constexpr float REAP_SPRAY_CLAMP_HIGH = 105; +constexpr float REAP_SPRAY_DOWN = 90; +constexpr int REAP_SPRAY_SWEEP_CENTER = 4; +constexpr int REAP_SPRAY_NARROW_STEP = 30; +constexpr int REAP_SPRAY_NARROW_SWEEP = 13; +constexpr int REAP_SPRAY_WIDE_STEP = 20; +constexpr int REAP_SPRAY_WIDE_SWEEP = 8; +constexpr int REAP_SPRAY_HALF_ARC = 45; +constexpr float REAP_SPRAY_SPEED = 8; +constexpr float REAP_SPRAY_LEAD = 3; +constexpr uint32_t REAP_SPRAY_GAP_ODDS = 10; +constexpr float REAP_SPRAY_SCALE = 1.1f; +constexpr float REAP_SPRAY_HEIGHT = -24; +constexpr float REAP_SPRAY_FALL = 1.5f; +constexpr float REAP_SPRAY_WIDE_ACCEL = 0.3f; +constexpr float REAP_SPRAY_WIDE_SCALE = 0.9f; +constexpr float REAP_SPRAY_WIDE_FALL = 17; +constexpr float REAP_SPRAY_WIDE_FALL_MIN = 12; + +constexpr int REAP_THIN_CHARGE = -10; +constexpr int REAP_WIDE_CHARGE = -30; +constexpr int REAP_BEAM_ON = 1; +constexpr int REAP_BEAM_OFF = 2; +constexpr int REAP_THIN_VARIANT = 1; +constexpr int REAP_THIN_TIMEOUT = 100; +constexpr int REAP_THIN_DELAY = 30; +constexpr int REAP_WIDE_VARIANT = 11; +constexpr int REAP_WIDE_TIMEOUT = 50; +constexpr int REAP_BEAM_END_TIMEOUT = 5; +constexpr float REAP_BEAM_DEPTH = 1000; +constexpr float REAP_BEAM_DROP = 4; +constexpr float REAP_BEAM_HEIGHT = -32; +constexpr float REAP_BEAM_DOWN = 90; + +constexpr uint32_t REAP_WALL_LEFT_ODDS = 2; +constexpr uint32_t REAP_WALL_SIDE_ODDS = 4; +constexpr uint32_t REAP_WALL_ODDS = 5; +constexpr float REAP_WALL_MARGIN = 20; +constexpr int REAP_SUMMON_SPIDERS = 3; +constexpr float REAP_SUMMON_ARC = 90; +constexpr float REAP_SUMMON_ARC_START = 45; +constexpr float REAP_SPIDER_REACH = 200; +constexpr float REAP_TRITE_REACH_MIN = 100; +constexpr float REAP_FREE_TILE_REACH = 64; +constexpr float REAP_SPIDER_HEIGHT = -32; +constexpr int REAP_TRITE_HOP_FRAME = 5; + +constexpr float REAP_GORE_HEIGHT = -24; +constexpr int REAP_GORE_PARTICLES = 8; +constexpr uint32_t REAP_GORE_PARTICLE_RANGE = 3; +constexpr float REAP_GORE_SPEED_MIN = 2; +constexpr float REAP_GORE_SPEED_RANGE = 4; +constexpr float REAP_TRANSITION_HURT = 0.1f; +constexpr int REAP_PHASES = 3; + +constexpr std::string_view REAP_TRANSITIONS[] = {"Transition1", "Transition2"}; +constexpr std::string_view REAP_OPEN_TRANSITIONS[] = {"Transition1Alt", "Transition2Alt"}; + +// What Reap Creep packs into its i1 a byte each: its mouth open, its phase, the way it strafes (or dashes) and the +// attacks it made this phase. +struct ReapBytes +{ + int8_t isMouthOpen = 0; + int8_t phase = 0; + int8_t direction = 0; + int8_t attacks = 0; +}; + +// What a frame of Reap Creep carries: its bytes, the room, how fast it strafes and how much friction it keeps. +struct ReapFrame +{ + ReapBytes bytes; + Room& room; + float friction = REAP_FRICTION; + float strafe = REAP_STRAFE_SPEED; +}; + +// 00579770 (NpcHelper::ReapCreep_CountOtherEnemies) The enemies alive that are not bosses. +static int reap_other_enemies_count() +{ + Room& room = *g_game->room; + return room.GetAliveEnemiesCount() - room.GetAliveBossesCount(); +} + +// A rest of a random length before its next attack. +static void reap_rest(Entity_NPC& npc, int min, uint32_t range) +{ + npc.state = NPC_STATE_IDLE; + npc.projectileCooldown = (int)(Random() % range) + min; +} + +// Rests once its animation ends. +static void reap_rest_when_done(Entity_NPC& npc) +{ + if (npc_anim_is_done(npc)) reap_rest(npc, REAP_REST_MIN, REAP_REST_RANGE); +} + +// Starts an attack from idle, counting it. +static void reap_attack_start(Entity_NPC& npc, ReapFrame& frame, int state, std::string_view anim) +{ + npc.state = state; + npc.projectileCooldown = 0; + npc.sprite.Play(anim); + frame.bytes.attacks++; +} + +// Idle: once rested it picks the attack of its phase. The first a fountain (a Wall Creep summon when alone), the +// second a spray (spiders or a Trite when alone), the third a dash along the wall (first, or one time in four) or a +// beam. +static void reap_idle(Entity_NPC& npc, ReapFrame& frame) +{ + constexpr std::string_view IDLES[] = {"Idle1", "Idle2", "Idle3"}; + frame.strafe = frame.bytes.phase == 1 ? REAP_STRAFE_PHASE2 : REAP_STRAFE_FAST; + npc.sprite.Play(IDLES[std::min(frame.bytes.phase, REAP_LAST_PHASE)]); + if (npc.projectileCooldown >= 1) + { + npc.projectileCooldown--; + return; + } + + if (frame.bytes.phase == 0) + { + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + if (reap_other_enemies_count() < 1 && (Random() & 3) != 0) + return reap_attack_start(npc, frame, REAP_WALL_CREEP, "Summon1"); + return reap_attack_start(npc, frame, REAP_FOUNTAIN, "Attack1Start"); + } + if (frame.bytes.phase == 1) + { + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + if (reap_other_enemies_count() < 1 && (Random() & 1) != 0) + return reap_attack_start(npc, frame, REAP_SPIDERS, "Summon2"); + npc.i2 = (int)(Random() & 1); + return reap_attack_start(npc, frame, REAP_SPRAY, "Attack2"); + } + + bool isDash = frame.bytes.attacks == 0 || (Random() & 3) == 0; + if (isDash && reap_other_enemies_count() < REAP_DASH_ENEMY_LIMIT) + { + float toLeft = std::abs(npc.pos.x - frame.room.topLeftPos.x); + float toRight = std::abs(npc.pos.x - frame.room.bottomRightPos.x); + frame.bytes.direction = toLeft <= toRight ? 1 : -1; + return reap_attack_start(npc, frame, REAP_DASH, toRight < toLeft ? "DashLeftStart" : "DashRightStart"); + } + npc.i2 = (int)(Random() & 1); + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + reap_attack_start(npc, frame, REAP_BEAM, "Attack3Start"); +} + +// The leap in: it flies to its spot on the top wall between Jump and Land, then rests. +static void reap_jump(Entity_NPC& npc) +{ + npc_anim_loop(npc.sprite, "Jump"); + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Jump")) + npc.PlaySound(SOUND_BOSS_LITE_ROAR, 1, 2, false, 1); + + Vector toSpot = vector_sub(npc.targetPosition, npc.pos); + if (npc.sprite.animState.animData && npc.sprite.animState.WasEventTriggered("Land")) + { + npc.velocity = toSpot; + if (npc_anim_is_done(npc)) reap_rest(npc, REAP_REST_MIN, REAP_REST_RANGE); + return; + } + if (!npc.sprite.WasEventTriggered("Jump")) return; + + npc.velocity = vector_scale(toSpot, REAP_JUMP_PULL); + if (!npc.sprite.IsEventTriggered("Land")) return; + + npc_sound_play(SOUND_FORESTBOSS_STOMPS, 1, 2, 1); + npc.pos = npc.targetPosition; + npc.velocity = {}; +} + +// A rock (one time in three a spider, a rock spider in the Mines) falling on a free spot while the dash shakes the room. +static void reap_rock_rain(Entity_NPC& npc, Room& room) +{ + Vector spot = room_free_pickup_position_find({.position = room.GetRandomPosition(REAP_RAIN_MARGIN), .step = REAP_RAIN_STEP}); + if (Random() % REAP_RAIN_SPIDER_ODDS == 0 && reap_other_enemies_count() < REAP_SPIDER_ENEMY_LIMIT) + { + int stage = g_game->GetStageID(); + Vector from = vector_sub(spot, vector_scale(random_direction(), REAP_RAIN_SPIDER_SPREAD)); + if (stage == STAGE_ID_MINES || stage == STAGE_ID_ASHPIT) + rock_spider_throw(from, {}, &npc, SPIDER_THROW_ROCK, REAP_RAIN_HEIGHT); + else Entity_NPC::ThrowSpider(from, &npc, from, false, REAP_RAIN_HEIGHT); + return; + } + + ProjectileParams params; + params.heightModifier = REAP_RAIN_HEIGHT; + params.fallingAccelModifier = REAP_RAIN_FALL_ACCEL; + params.scale = REAP_RAIN_SCALE - random_unit() * REAP_RAIN_SCALE_RANGE; + params.variant = PROJECTILE_ROCK; + params.fallingSpeedModifier = random_unit() * REAP_RAIN_FALL_RANGE; + npc.FireProjectiles(spot, {}, PROJECTILES_SINGLE, params); +} + +// The dash: along the top wall until it slams the far side, shaking the room into a rain of rocks and spiders. +// The original steps one past its next position whichever way it goes. +static void reap_dash(Entity_NPC& npc, ReapFrame& frame) +{ + int direction = frame.bytes.direction; + if (direction == 0) reap_rest_when_done(npc); + else + { + if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_MONSTER_ROAR_0, 1, 2, false, 1); + if (npc.sprite.WasEventTriggered("Shoot") || npc.sprite.animState.IsLoopingAnimation()) + { + if (npc_anim_is_done(npc)) npc.sprite.Play(direction < 0 ? "DashLeftLoop" : "DashRightLoop"); + float nextX = npc.velocity.x + npc.pos.x + (float)(direction * direction); + bool isSlam = (direction < 0 && nextX < frame.room.topLeftPos.x) || + (direction > 0 && nextX > frame.room.bottomRightPos.x); + if (isSlam) + { + npc.velocity.x = -npc.velocity.x; + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, REAP_DASH_SLAM_VOLUME, 2, false, 1); + game_shake_screen(REAP_DASH_SHAKE); + npc.projectileCooldown = REAP_DASH_RAIN; + npc.sprite.Play("DashEnd"); + frame.bytes.direction = 0; + } + else npc.velocity.x += (float)direction * npc.speedMultiplier * REAP_DASH_PUSH; + } + } + + if (npc.projectileCooldown > 0) + { + if ((npc.projectileCooldown & 1) == 0) reap_rock_rain(npc, frame.room); + npc.projectileCooldown--; + } + frame.friction = REAP_DASH_FRICTION; +} + +// The fountain: a minute of shots tossed up every other frame, falling around it, then a rest. +static void reap_fountain(Entity_NPC& npc, ReapFrame& frame) +{ + if (npc.projectileCooldown == 0) + { + frame.strafe = 0; + if (!npc_anim_is_done(npc)) return; + + npc.PlaySound(SOUND_SPIDER_SPIT_ROAR, 1, 2, false, REAP_FOUNTAIN_PITCH); + npc.projectileCooldown = REAP_FOUNTAIN_FRAMES; + npc.sprite.Play("Attack1Fire"); + return; + } + if (npc.projectileCooldown < 1) + { + frame.strafe = 0; + return reap_rest_when_done(npc); + } + + if ((npc.projectileCooldown & 1) == 0) + { + npc.GetPlayerTarget(); + float size = random_unit(); + Vector up = vector_make(std::cos(REAP_RIGHT_ANGLE) * REAP_FOUNTAIN_SPEED, std::sin(REAP_RIGHT_ANGLE) * REAP_FOUNTAIN_SPEED); + ProjectileParams params; + params.heightModifier = REAP_FOUNTAIN_HEIGHT; + params.scale = REAP_FOUNTAIN_SCALE - size * REAP_FOUNTAIN_SCALE_RANGE; + params.fallingSpeedModifier = REAP_FOUNTAIN_FALL; + Vector direction = random_direction(); + float reach = random_unit() * REAP_FOUNTAIN_SPREAD; + Vector from = vector_make(reach * direction.x + npc.pos.x, direction.y * reach + npc.pos.y + REAP_FOUNTAIN_DROP); + npc.FireProjectiles(from, up, PROJECTILES_SINGLE, params); + npc.PlaySound(SOUND_TEARS_FIRE, 1, 2, false, 1); + } + if (--npc.projectileCooldown < 1) + { + npc.sprite.Play("Attack1End"); + npc.projectileCooldown = -1; + } +} + +// Aims the spray at its target, jittered. Aimed off its downward arc it aims straight at it, kept within 75 to 105, +// marked below zero. +static void reap_spray_aim(Entity_NPC& npc) +{ + Entity* target = npc.GetPlayerTarget(); + Vector toTarget = vector_sub(target->pos, npc.pos); + npc.v1.y = vector_angle(toTarget) + (random_unit() - 0.5f) * REAP_SPRAY_JITTER; + if (npc.v1.y >= REAP_SPRAY_LOW && npc.v1.y <= REAP_SPRAY_HIGH) return; + + float angle = std::clamp(vector_angle(toTarget), REAP_SPRAY_CLAMP_LOW, REAP_SPRAY_CLAMP_HIGH); + npc.v1.y = angle - FULL_TURN_DEGREES; +} + +// A fan of the spray, sweeping across as it goes: 30 apart, a shot in ten missing, or 20 apart, slower and scattered +// for the wide kind (i2). +static void reap_spray_fan(Entity_NPC& npc) +{ + bool isWide = npc.i2 != 0 && npc.v1.y >= 0; + int sweep = npc.projectileCooldown / 2; + bool isDown = npc.v1.y >= REAP_SPRAY_DOWN; + int step = isWide ? REAP_SPRAY_WIDE_STEP : REAP_SPRAY_NARROW_STEP; + int center = isWide ? (isDown ? sweep - REAP_SPRAY_SWEEP_CENTER : REAP_SPRAY_SWEEP_CENTER - sweep) * REAP_SPRAY_WIDE_SWEEP + : (isDown ? sweep - REAP_SPRAY_SWEEP_CENTER : REAP_SPRAY_SWEEP_CENTER - sweep) * REAP_SPRAY_NARROW_SWEEP; + + for (int angle = center - REAP_SPRAY_HALF_ARC; angle <= center + REAP_SPRAY_HALF_ARC; angle += step) + { + Vector velocity = vector_scale(vector_from_angle((float)angle + npc.v1.y), REAP_SPRAY_SPEED); + ProjectileParams params; + uint32_t roll = Random(); + if (!isWide) + { + if (roll % REAP_SPRAY_GAP_ODDS == 0) continue; + params.scale = REAP_SPRAY_SCALE; + params.heightModifier = REAP_SPRAY_HEIGHT; + params.fallingSpeedModifier = REAP_SPRAY_FALL; + } + else + { + params.heightModifier = REAP_SPRAY_HEIGHT; + params.fallingAccelModifier = REAP_SPRAY_WIDE_ACCEL; + params.scale = (float)roll * RANDOM_UNIT_SCALE * REAP_SPRAY_WIDE_SCALE + REAP_FRICTION; + params.fallingSpeedModifier = random_unit() * REAP_SPRAY_WIDE_FALL - REAP_SPRAY_WIDE_FALL_MIN; + velocity = vector_scale(velocity, random_unit() * 0.5f + 0.5f); + } + npc.FireProjectiles(vector_add(npc.pos, vector_scale(velocity, REAP_SPRAY_LEAD)), velocity, PROJECTILES_SINGLE, + params); + } +} + +// The spray: from Shoot to EndShoot a fan every other frame, then a long rest. +static void reap_spray(Entity_NPC& npc, ReapFrame& frame) +{ + frame.strafe = 0; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_BOSS_SPIT_BLOB_BARF, 1, 2, false, 1); + npc.projectileCooldown = 1; + reap_spray_aim(npc); + } + if (npc.sprite.IsEventTriggered("EndShoot")) npc.projectileCooldown = 0; + else if (npc.projectileCooldown > 0 && (++npc.projectileCooldown & 1) != 0) reap_spray_fan(npc); + if (npc_anim_is_done(npc)) reap_rest(npc, REAP_SPRAY_REST_MIN, REAP_SPRAY_REST_RANGE); +} + +// 005797b0 (NpcHelper::ReapCreep_ThinLaser) A thin beam from its mouth turning from one angle to another after 30 +// frames. +static Entity_Laser* reap_thin_laser(Entity_NPC& npc, float startAngle, float endAngle) +{ + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = vector_add(npc.pos, vector_make(0, REAP_BEAM_DROP)), + .posOffset = vector_make(0, REAP_BEAM_HEIGHT), + .source = &npc, + .angleDegrees = startAngle, + .timeout = REAP_THIN_TIMEOUT, + .variant = REAP_THIN_VARIANT}); + laser->isActiveRotating = true; + laser->rotationDelay = REAP_THIN_DELAY; + laser->rotationSpd = endAngle <= startAngle ? -1.0f : 1.0f; + laser->renderDepthOffset = REAP_BEAM_DEPTH; + laser->rotationDegrees = endAngle - startAngle; + laser->Update(); + return laser; +} + +// The beam's firing: four thin beams closing in (i2 0) or one wide beam straight down. +static void reap_beam_fire(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_GHOST_ROAR, 1, 2, false, 1); + if (npc.i2 == 0) + { + constexpr float SWEEPS[][2] = {{135, 106}, {45, 74}, {150, 111}, {30, 69}}; + npc.child = reap_thin_laser(npc, SWEEPS[0][0], SWEEPS[0][1]); + for (int i = 1; i < 4; i++) reap_thin_laser(npc, SWEEPS[i][0], SWEEPS[i][1]); + return; + } + + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = vector_add(npc.pos, vector_make(0, REAP_BEAM_DROP)), + .posOffset = vector_make(0, REAP_BEAM_HEIGHT), + .source = &npc, + .angleDegrees = REAP_BEAM_DOWN, + .timeout = REAP_WIDE_TIMEOUT, + .variant = REAP_WIDE_VARIANT}); + laser->renderDepthOffset = REAP_BEAM_DEPTH; + laser->Update(); + npc.child = laser; +} + +// The beam: a charge (shorter for the thin beams) once its mouth closes, the beams, then a rest as they fade. +static void reap_beam(Entity_NPC& npc, ReapFrame& frame) +{ + frame.strafe = 0; + if (npc.projectileCooldown < 1) + { + if (npc.sprite.IsEventTriggered("Close")) + { + npc.GetPlayerTarget(); + npc.i2 = (int)(Random() & 1); + npc.projectileCooldown = npc.i2 != 0 ? REAP_THIN_CHARGE : REAP_WIDE_CHARGE; + npc.PlaySound(npc.i2 != 1 ? SOUND_MOUTH_FULL : SOUND_LOW_INHALE, 1, 2, false, 1); + } + if (npc_anim_is_done(npc)) npc.sprite.Play("Attack3Charge"); + if (npc.projectileCooldown < 0 && ++npc.projectileCooldown == 0) + { + npc.sprite.Play("Attack3BeamStart"); + npc.projectileCooldown = REAP_BEAM_ON; + } + return; + } + if (npc.projectileCooldown != REAP_BEAM_ON) return reap_rest_when_done(npc); + + if (npc.sprite.IsEventTriggered("Shoot")) reap_beam_fire(npc); + if (npc_anim_is_done(npc)) npc.sprite.Play("Attack3BeamLoop"); + Entity* beam = npc.child.get(); + if (beam) frame.strafe = npc.i2 == 0 ? REAP_STRAFE_THIN_BEAM : REAP_STRAFE_WIDE_BEAM; + bool isBeamGone = !beam || beam->type != ENTITY_LASER || + static_cast(beam)->timeout < REAP_BEAM_END_TIMEOUT; + if (!npc.sprite.animState.IsLoopingAnimation() || !isBeamGone) return; + + npc.sprite.Play("Attack3End"); + npc.projectileCooldown = REAP_BEAM_OFF; +} + +// A spot along a wall of the room: the left, the right (two in five each) or the bottom one. +static Vector reap_wall_spot(Room& room, uint32_t& seed) +{ + uint32_t wall = Random() % REAP_WALL_ODDS; + seed = Random(); + float along = random_unit(); + Vector topLeft = room.topLeftPos; + Vector bottomRight = room.bottomRightPos; + if (wall >= REAP_WALL_SIDE_ODDS) + return vector_make((bottomRight.x - REAP_WALL_MARGIN - (topLeft.x + REAP_WALL_MARGIN)) * along + topLeft.x + REAP_WALL_MARGIN, + bottomRight.y); + + float y = (bottomRight.y - REAP_WALL_MARGIN - (topLeft.y + REAP_WALL_MARGIN)) * along + topLeft.y + REAP_WALL_MARGIN; + return vector_make(wall < REAP_WALL_LEFT_ODDS ? topLeft.x : bottomRight.x, y); +} + +// The first summon: a Wall Creep climbing out of a wall once it roars. +static void reap_wall_creep_summon(Entity_NPC& npc, ReapFrame& frame) +{ + frame.strafe = 0; + if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_MONSTER_YELL_B, 1, 2, false, 1); + if (!npc_anim_is_done(npc)) return; + + reap_rest(npc, REAP_REST_MIN, REAP_REST_RANGE); + uint32_t seed = 0; + Vector spot = reap_wall_spot(frame.room, seed); + g_game->Spawn({.position = spot, .type = ENTITY_WALL_CREEP, .seed = seed})->Update(); + npc.PlaySound(SOUND_SUMMONSOUND, 1, 2, false, 1); +} + +// A free tile at a random angle below it, within reach (beyond a minimum). +static Vector reap_summon_spot(Entity_NPC& npc, float reachMin, float reachRange) +{ + float angle = (random_unit() * REAP_SUMMON_ARC + REAP_SUMMON_ARC_START) * DEGREES_TO_RADIANS; + float reach = random_unit() * reachRange + reachMin; + Vector spot = vector_make(std::cos(angle) * reach + npc.pos.x, std::sin(angle) * reach + npc.pos.y); + return room_free_tile_position_find(spot, REAP_FREE_TILE_REACH); +} + +// The second summon: three spiders spat below it, or a Trite hopping out of its mouth. +static void reap_spider_summon(Entity_NPC& npc, ReapFrame& frame) +{ + frame.strafe = 0; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_BOSS_SPIT_BLOB_BARF, 1, 2, false, 1); + if ((Random() & 1) == 0) + for (int i = 0; i < REAP_SUMMON_SPIDERS; i++) + Entity_NPC::ThrowSpider(npc.pos, &npc, reap_summon_spot(npc, 0, REAP_SPIDER_REACH), false, + REAP_SPIDER_HEIGHT); + else + { + auto* trite = static_cast(g_game->Spawn({.position = vector_add(npc.pos, vector_make(0, REAP_BEAM_DROP)), + .type = ENTITY_HOPPER, + .variant = HOPPER_TRITE, + .seed = Random()})); + trite->targetPosition = reap_summon_spot(npc, REAP_TRITE_REACH_MIN, REAP_SPIDER_REACH); + trite->state = NPC_STATE_MOVE; + trite->stateFrame = REAP_TRITE_HOP_FRAME; + trite->sprite.Play("Hop", PLAY_FORCED); + trite->sprite.SetFrame((float)REAP_TRITE_HOP_FRAME); + } + } + reap_rest_when_done(npc); +} + +// Its gore between phases: a blood explosion, a splat and 8 to 10 drops flying off. +static void reap_gore(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_MONSTER_GRUNT_4, 1, 2, false, 1); + npc_sound_play(SOUND_DEATH_BURST_SMALL, 1, 2, 1); + Entity* explosion = g_game->Spawn({.position = npc.pos, .subType = 3, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + explosion->posOffset = vector_make(0, REAP_GORE_HEIGHT); + explosion->Update(); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()})->Update(); + + for (uint32_t count = Random() % REAP_GORE_PARTICLE_RANGE + REAP_GORE_PARTICLES; count > 0; count--) + { + Vector around = random_direction(); + Vector position = vector_make(around.x * 0.5f * npc.size + npc.pos.x, around.y * 0.5f * npc.size + npc.pos.y); + Vector direction = random_direction(); + float speed = random_unit() * REAP_GORE_SPEED_RANGE + REAP_GORE_SPEED_MIN; + Entity* drop = g_game->Spawn({.position = position, .velocity = vector_scale(direction, speed), + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_PARTICLE, .seed = Random()}); + drop->posOffset = vector_make(0, REAP_GORE_HEIGHT); + drop->Update(); + } +} + +// Losing a third of its health: it lands if it was leaping, bursts and starts the next phase's transition. +static void reap_transition_start(Entity_NPC& npc, ReapFrame& frame) +{ + if (npc.state == REAP_JUMP) + { + npc_sound_play(SOUND_FORESTBOSS_STOMPS, 1, 2, 1); + npc.pos = npc.targetPosition; + npc.velocity = {}; + } + reap_gore(npc); + const auto& names = frame.bytes.isMouthOpen ? REAP_OPEN_TRANSITIONS : REAP_TRANSITIONS; + npc_anim_loop(npc.sprite, names[frame.bytes.phase]); + npc.state = REAP_TRANSITION; + npc.projectileCooldown = 0; +} + +// The transition: hurt a tenth as much until it ends, then the next phase begins. +static void reap_transition(Entity_NPC& npc, ReapFrame& frame) +{ + frame.strafe = 0; + if (npc_anim_is_done(npc)) + { + frame.bytes.isMouthOpen = 0; + npc.projectileCooldown = (int)(Random() % REAP_REST_RANGE) + REAP_REST_MIN; + frame.bytes.phase++; + frame.bytes.attacks = 0; + npc.state = NPC_STATE_IDLE; + return; + } + npc.pendingDamage = 0; + for (DamageEvent& event : npc.damageEvents) + { + event.damage *= REAP_TRANSITION_HURT; + npc.pendingDamage += event.damage; + } +} + +// It walks along the top wall: toward its target (ahead of it, or at a wandering spot in its second phase), faster in +// line with it, held to its way for 6 frames. +static void reap_strafe(Entity_NPC& npc, ReapFrame& frame) +{ + Room& room = frame.room; + Entity* target = npc.GetPlayerTarget(); + float left = room.topLeftPos.x + REAP_STRAFE_MARGIN; + float right = room.bottomRightPos.x - REAP_STRAFE_MARGIN; + float gap = 0; + if (frame.bytes.phase == 1) gap = (right - left) * (npc.v1.x + 1) * 0.5f + left - npc.pos.x; + else + { + gap = target->pos.x - npc.pos.x; + if (npc.state == REAP_FOUNTAIN || npc.state == REAP_BEAM) + { + if (gap < 0) gap -= REAP_STRAFE_ATTACK_LEAD; + else if (gap > 0) gap += REAP_STRAFE_ATTACK_LEAD; + } + else gap += npc.v1.x * REAP_STRAFE_LEAD; + } + if (--npc.projectileDelay < 1) + { + npc.v1.x = random_unit() * 2 - 1; + npc.projectileDelay = (int)(Random() % REAP_WANDER_RANGE) + REAP_WANDER_MIN; + } + + int way = gap > REAP_STRAFE_SLACK ? 1 : gap < -REAP_STRAFE_SLACK ? -1 : 0; + if (way != 0 && (frame.bytes.direction == way || frame.bytes.direction == 0)) + { + frame.bytes.direction = (int8_t)way; + npc.stateFrame = REAP_STRAFE_HOLD; + } + else if (--npc.stateFrame < 1) frame.bytes.direction = 0; + if (frame.strafe <= 0) return; + + if (frame.bytes.phase != 1 && std::abs(npc.GetPlayerTarget()->pos.y - npc.pos.y) < REAP_STRAFE_ROW) + frame.strafe = REAP_WALK_SPEED; + float push = frame.strafe * REAP_STRAFE_PUSH * npc.speedMultiplier; + if (frame.bytes.direction >= 1 && npc.pos.x < right) npc.velocity.x += push; + if (frame.bytes.direction < 0 && npc.pos.x > left) npc.velocity.x -= push; +} + +// Its arrival: overlay drawn first, it leaps over everything to its spot on the top wall. +static void reap_init(Entity_NPC& npc, ReapFrame& frame) +{ + npc.sprite.isOverlayRenderFirst = true; + npc.state = REAP_JUMP; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.targetPosition = vector_make(npc.pos.x, frame.room.topLeftPos.y + REAP_WALL_DROP); + frame.bytes = {}; + npc.i2 = 0; + npc.stateFrame = 0; + npc.projectileCooldown = 0; + npc.v1 = {}; + npc.projectileDelay = 0; +} + +// 00579890 Reap Creep (900): it leaps onto the top wall and strafes along it, its attacks changing over three phases +// (a fountain, a spray, then dashes and beams), opening its mouth to attack. +void boss_reap_creep_update(Entity_NPC& npc) +{ + ReapFrame frame{.bytes = std::bit_cast(npc.i1), .room = *g_game->room}; + float phaseHealth = (float)(REAP_LAST_PHASE - frame.bytes.phase) * npc.maxHitPoints / REAP_PHASES; + bool isPhaseOver = npc.state != REAP_TRANSITION && frame.bytes.phase <= 1 && npc.health < phaseHealth; + if (isPhaseOver) + { + reap_transition_start(npc, frame); + reap_transition(npc, frame); + } + else switch (npc.state) + { + case NPC_STATE_INIT: + reap_init(npc, frame); + break; + case NPC_STATE_IDLE: + reap_idle(npc, frame); + break; + case REAP_JUMP: + reap_jump(npc); + npc.friction *= REAP_FRICTION; + npc.i1 = std::bit_cast(frame.bytes); + return; + case REAP_DASH: + reap_dash(npc, frame); + break; + case REAP_FOUNTAIN: + reap_fountain(npc, frame); + break; + case REAP_SPRAY: + reap_spray(npc, frame); + break; + case REAP_BEAM: + reap_beam(npc, frame); + break; + case REAP_WALL_CREEP: + reap_wall_creep_summon(npc, frame); + break; + case REAP_SPIDERS: + reap_spider_summon(npc, frame); + break; + case REAP_TRANSITION: + reap_transition(npc, frame); + break; + } + + bool isAttacking = npc.state == REAP_FOUNTAIN || npc.state == REAP_SPRAY || npc.state == REAP_BEAM; + if (isAttacking && npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Open")) + { + npc.PlaySound(SOUND_SKIN_PULL, 1, 2, false, 1); + frame.bytes.isMouthOpen = 1; + } + else if (npc.sprite.animState.IsEventTriggered("Close")) frame.bytes.isMouthOpen = 0; + } + if (npc.state != REAP_JUMP) + { + npc.velocity.y = frame.room.topLeftPos.y + REAP_WALL_DROP - npc.pos.y; + npc.sprite.PlayOverlay(npc.velocity.x > 1 ? "WalkRight" : npc.velocity.x < -1 ? "WalkLeft" : "WalkIdle"); + } + if (npc.state != REAP_DASH) reap_strafe(npc, frame); + npc.friction *= frame.friction; + npc.i1 = std::bit_cast(frame.bytes); +} diff --git a/src/boss_sisters_vis.cpp b/src/boss_sisters_vis.cpp new file mode 100644 index 0000000..e385f3c --- /dev/null +++ b/src/boss_sisters_vis.cpp @@ -0,0 +1,717 @@ +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "npc_caves.h" +#include + +// The Sisters Vis' states: idle, the leap across the room and its landing, the twin beam, the roll, and their three +// solo attacks (a sweeping beam, a beam, a spray of shots) and summons. +constexpr int SISTERS_LEAP = NPC_STATE_JUMP; +constexpr int SISTERS_LAND = NPC_STATE_STOMP; +constexpr int SISTERS_ROLL = NPC_STATE_ATTACK; +constexpr int SISTERS_TWIN_BEAM = NPC_STATE_ATTACK2; +constexpr int SISTERS_BEAM = NPC_STATE_ATTACK3; +constexpr int SISTERS_SWEEP = NPC_STATE_ATTACK4; +constexpr int SISTERS_SPRAY = NPC_STATE_ATTACK5; +constexpr int SISTERS_SUMMON_BEGOTTEN = NPC_STATE_SUMMON; +constexpr int SISTERS_SUMMON_VIS = NPC_STATE_SUMMON2; + +// A step's progress through an attack (i1): its start, its loop, waiting on the beam, and its end. +constexpr int STEP_START = 0; +constexpr int STEP_LOOP = 1; +constexpr int STEP_WAIT = 2; +constexpr int STEP_END = 3; +constexpr int SPRAY_END = 2; + +constexpr ColorMod SISTERS_SPLAT_COLOR = { + {0.039215688f, 0.3137255f, 0.039215688f, 1}, {0, 0, 0, 0}, {0.3921569f, 0.3921569f, 0.3137255f}}; +constexpr ColorMod SISTERS_RAGE_COLOR = {{1, 0.3f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod SISTERS_SUMMON_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.42f, 0.43f, 0.35f}}; +constexpr ColorMod SISTERS_TRACER_COLOR = {{0.6f, 0.05f, 0, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float SISTERS_WIDTH = 1.2f; +constexpr float SISTERS_HEIGHT = 0.5f; + +constexpr float SISTERS_SPAWN_REACH = 40; +constexpr float SISTERS_RAGE_GAP = 300; +constexpr int SISTERS_RAGE_FRAMES = 120; +constexpr float SISTERS_RAGE_DAMAGE = 1.5f; +constexpr float SISTERS_BEAM_HURT = 1.5f; +constexpr float SISTERS_FRICTION = 0.5f; +constexpr int SISTERS_IDLE_FRAMES = 20; +constexpr uint32_t SISTERS_MOVE_ODDS = 5; +constexpr uint32_t SISTERS_PERCENT = 100; +constexpr uint32_t SISTERS_LEAP_PERCENT = 35; +constexpr uint32_t SISTERS_SUMMON_PERCENT = 84; +constexpr int SISTERS_SUMMON_LIMIT = 2; +constexpr uint32_t SISTERS_BEGOTTEN_ODDS = 3; +constexpr float SISTERS_LEAD_FRAMES = 10; +constexpr float SISTERS_LEAP_STEP = 0.02f; +constexpr float SISTERS_LEAP_ARRIVE_SQUARED = 2; + +constexpr float SISTERS_SUMMON_DROP = 20; +constexpr float SISTERS_SUMMON_SPEED = 5; +constexpr int SISTERS_SPLATS_MIN = 2; +constexpr uint32_t SISTERS_SPLATS_RANGE = 3; + +constexpr float SISTERS_ROLL_SPEED = 16; +constexpr float SISTERS_RAGE_ROLL_SPEED = 24; +constexpr int SISTERS_CREEP_FRAMES = 3; +constexpr float SISTERS_CREEP_SCALE = 2; +constexpr int SISTERS_CREEP_TIMEOUT = 5; +constexpr int SISTERS_ROLL_MIN = 65; +constexpr uint32_t SISTERS_ROLL_STOP_ODDS = 35; +constexpr uint32_t SISTERS_BEAM_PERCENT = 60; +constexpr uint32_t SISTERS_SWEEP_PERCENT = 70; + +constexpr float SISTERS_BEAM_HEIGHT = -30; +constexpr float SISTERS_BEAM_SIDE = 35; +constexpr float SISTERS_TRACER_HEIGHT = -40; +constexpr float SISTERS_TRACER_SCALE = 8; +constexpr int SISTERS_TRACER_TIMEOUT = 40; +constexpr int SISTERS_TWIN_TRACER_TIMEOUT = 42; +constexpr int SISTERS_BEAM_TIMEOUT = 30; +constexpr int SISTERS_TWIN_BEAM_TIMEOUT = 15; +constexpr int SISTERS_SWEEP_TIMEOUT = 60; +constexpr int SISTERS_BEAM_VARIANT = 6; +constexpr float SISTERS_BEAM_BACK_DEPTH = -10; +constexpr float SISTERS_BEAM_FRONT_DEPTH = 3000; +constexpr float SISTERS_TWIN_BEAM_REACH = 57; +constexpr float SISTERS_TWIN_GAP_ACROSS = 157; +constexpr float SISTERS_TWIN_GAP_DOWN = 87; +constexpr float SISTERS_SWEEP_TURN = 2; +constexpr float SISTERS_FAR = 9999999; + +constexpr float SISTERS_SPRAY_SPEED = 6; +constexpr float SISTERS_RAGE_SPRAY_SPEED = 8; +constexpr float SISTERS_SPRAY_SIDE = 30; +constexpr float SISTERS_SPRAY_HEIGHT = -15; +constexpr int SISTERS_SPRAY_FRAMES = 30; +constexpr float SISTERS_SPRAY_THIRD = 33; +constexpr float SISTERS_SPRAY_TWO_THIRDS = 66; +constexpr int SISTERS_SPRAY_PERIOD = 5; + +constexpr std::string_view LASER_START[] = {"LaserStartSide", "LaserStartUp", "LaserStartSide", "LaserStartDown"}; +constexpr std::string_view LASER_LOOP[] = {"LaserLoopSide", "LaserLoopUp", "LaserLoopSide", "LaserLoopDown"}; +constexpr std::string_view LASER_END[] = {"LaserEndSide", "LaserEndUp", "LaserEndSide", "LaserEndDown"}; + +// What a sister knows of the other each frame: her, whether this one spawned first, and whether either is hindered. +struct SistersView +{ + Entity_NPC* sister = nullptr; + bool isFirst = false; + bool isSecond = false; + bool isImpaired = false; + bool isSisterInactive = false; +}; + +// 00682740 An angle in degrees brought into -180 to 180. +float normalize_angle_degrees(float angle) +{ + if (std::abs(angle) > FULL_TURN_DEGREES) angle = std::fmod(angle, FULL_TURN_DEGREES); + if (angle > HALF_TURN_DEGREES) return angle - FULL_TURN_DEGREES; + if (angle < -HALF_TURN_DEGREES) angle += FULL_TURN_DEGREES; + return angle; +} + +// The angle a sister faces along a direction (left, up, right, down). +static float sisters_direction_angle(int direction) +{ + return normalize_angle_degrees((float)direction * RIGHT_ANGLE_DEGREES + HALF_TURN_DEGREES); +} + +// Both sisters back to idle. +static void sisters_reset(Entity_NPC& npc, Entity_NPC* sister) +{ + npc.state = NPC_STATE_IDLE; + npc.i1 = 0; + npc.stateFrame = 0; + if (!sister) return; + + sister->state = NPC_STATE_IDLE; + sister->i1 = 0; + sister->stateFrame = 0; +} + +// Its beam hurts it half again as much while it fires. +static void sisters_beam_hurt(Entity_NPC& npc) +{ + if (npc.pendingDamage <= 0) return; + + for (DamageEvent& event : npc.damageEvents) event.damage *= SISTERS_BEAM_HURT; +} + +// A tracer showing where the beam will fire, once per attack (in the first slot of its entity queue). +static Entity_Effect* sisters_tracer_spawn(Entity_NPC& npc, int direction, int timeout) +{ + return following_effect_spawn(npc, {.offset = vector_make(0, SISTERS_TRACER_HEIGHT), + .targetPosition = vector_from_angle(sisters_direction_angle(direction)), + .color = SISTERS_TRACER_COLOR, + .scale = SISTERS_TRACER_SCALE, + .timeout = timeout}); +} + +// The queued tracer, once it is gone. +static void sisters_tracer_keep(Entity_NPC& npc, int direction) +{ + if (npc.entityDeque.front().get()) return; + + npc.entityDeque.front() = sisters_tracer_spawn(npc, direction, SISTERS_TWIN_TRACER_TIMEOUT); +} + +// A beam from its mouth along a direction, in front of it unless it fires up. +static Entity_Laser* sisters_beam_fire(Entity_NPC& npc, int direction, int timeout) +{ + Vector offset = vector_make(0, SISTERS_BEAM_HEIGHT); + if (direction == 0) offset.x = -SISTERS_BEAM_SIDE; + else if (direction == 2) offset.x = SISTERS_BEAM_SIDE; + + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = npc.pos, + .posOffset = offset, + .source = &npc, + .angleDegrees = sisters_direction_angle(direction), + .timeout = timeout, + .variant = SISTERS_BEAM_VARIANT}); + laser->renderDepthOffset = direction == 1 ? SISTERS_BEAM_BACK_DEPTH : SISTERS_BEAM_FRONT_DEPTH; + return laser; +} + +// The second sister, spawned beside the first and tied to her (as tough as a Delirium form). +static void sisters_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + npc.sizeMulti = vector_make(SISTERS_WIDTH, SISTERS_HEIGHT); + npc.splatColor = SISTERS_SPLAT_COLOR; + npc.i2 = 0; + npc.entityDeque.resize(1); + if (npc.spawnerType == npc.type) return; + + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Entity* sister = g_game->Spawn({.position = vector_make(std::cos(angle) * SISTERS_SPAWN_REACH + npc.pos.x, + std::sin(angle) * SISTERS_SPAWN_REACH + npc.pos.y), + .velocity = npc.velocity, + .spawner = &npc, + .subType = npc.subtype, + .type = npc.type, + .variant = npc.variant, + .seed = seed}); + if (npc.type != ENTITY_SISTERS_VIS) return; + + npc.child = sister; + sister->child = &npc; + if (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) return; + + sister->health = npc.health; + sister->maxHitPoints = npc.maxHitPoints; +} + +// The leap: the sisters jump to opposite walls, the first to the top or left one past where her target heads. +static void sisters_leap_start(Entity_NPC& npc, Entity_NPC& sister) +{ + Room& room = *g_game->room; + npc.state = SISTERS_LEAP; + Vector lead = vector_scale(npc.GetPlayerTarget()->velocity, SISTERS_LEAD_FRAMES); + npc.targetPosition = vector_add(npc.CalcTargetPosition(0), lead); + bool isAcross = Random() & 1; + if (isAcross) npc.targetPosition.x = room.topLeftPos.x; + else npc.targetPosition.y = room.topLeftPos.y; + npc.targetPosition = room.GetClampedPositionImpl(npc.targetPosition, npc.size, npc.size, npc.size, npc.size); + npc.v1.x = 0; + npc.i1 = 0; + + sister.state = SISTERS_LEAP; + sister.i1 = 0; + sister.v1.x = 0; + sister.targetPosition = npc.targetPosition; + if (isAcross) sister.targetPosition.x = room.bottomRightPos.x; + else sister.targetPosition.y = room.bottomRightPos.y; + sister.targetPosition = room.GetClampedPositionImpl(sister.targetPosition, npc.size, npc.size, npc.size, npc.size); +} + +// Whether the room has room for a summon: under two other enemies, or under two of its own minions for a Delirium +// form. +static bool sisters_is_summon_allowed(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + return (uint32_t)(npc.CountRelatedEntities(ENTITY_BEGOTTEN, 0, nullptr) + npc.CountRelatedEntities(ENTITY_VIS, 0, nullptr)) < + SISTERS_SUMMON_LIMIT; + Room& room = *g_game->room; + return room.GetAliveEnemiesCount() - room.GetAliveBossesCount() < SISTERS_SUMMON_LIMIT; +} + +// Idle: after 20 frames, one roll in five (the first sister leading, neither hindered) picks a leap, a summon or a +// roll for both. +static void sisters_idle(Entity_NPC& npc, const SistersView& view) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc_anim_loop(npc.sprite, "Idle"); + if (npc.HasEntityFlags(FLAG_DELIRIUM_FORM) && room_is_clear()) return; + if (npc.stateFrame++ <= SISTERS_IDLE_FRAMES) return; + if (Random() % SISTERS_MOVE_ODDS != 0 || (!view.isFirst && view.sister) || view.isImpaired) return; + + uint32_t roll = Random() % SISTERS_PERCENT; + if (roll < SISTERS_LEAP_PERCENT && !view.isSisterInactive) return sisters_leap_start(npc, *view.sister); + if (roll > SISTERS_SUMMON_PERCENT) + { + if (!sisters_is_summon_allowed(npc)) return; + + npc.state = Random() % SISTERS_BEGOTTEN_ODDS != 0 ? SISTERS_SUMMON_VIS : SISTERS_SUMMON_BEGOTTEN; + if (npc.child.get() && !view.isSisterInactive) view.sister->state = npc.state; + return; + } + + npc.state = SISTERS_ROLL; + npc.i1 = 0; + npc.PlaySound(SOUND_FAT_WIGGLE, 1, 2, false, 1); + if (view.isSisterInactive) return; + + view.sister->state = SISTERS_ROLL; + view.sister->i1 = 0; +} + +// The summon: a Begotten or a Vis dropped on Shoot, with a few gray splats under it. +static void sisters_summon(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc_anim_loop(npc.sprite, "Attack1"); + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + int type = npc.state == SISTERS_SUMMON_BEGOTTEN ? ENTITY_BEGOTTEN : ENTITY_VIS; + Vector drop = vector_make(npc.pos.x, npc.pos.y + SISTERS_SUMMON_DROP); + g_game->Spawn({.position = drop, .velocity = vector_make(0, SISTERS_SUMMON_SPEED), .spawner = &npc, .type = type, .seed = Random()}) + ->Update(); + npc.PlaySound(SOUND_SKIN_PULL, 1, 2, false, 1); + + int splats = (int)(Random() % SISTERS_SPLATS_RANGE) + SISTERS_SPLATS_MIN; + for (int i = 0; i < splats; i++) + { + Entity_Effect* splat = npc.MakeSplat(random_unit() * 0.5f + 0.5f); + splat->pos = i == 0 ? drop : vector_make(npc.pos.x, random_unit() * SISTERS_SUMMON_DROP + npc.pos.y); + splat->SetColor(SISTERS_SUMMON_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + } + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + } + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; +} + +// The roll's start: once curled up, a shove at the target (away from it for the second sister). +static void sisters_roll_start(Entity_NPC& npc, const SistersView& view, float speed) +{ + npc_anim_loop(npc.sprite, "RollStart"); + if (!npc_anim_is_done(npc)) return; + + npc.i1++; + npc.velocity = vector_add(npc.velocity, vector_scale(vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)), speed)); + npc.stateFrame = 0; + if (view.isSecond) npc.velocity = vector_scale(npc.velocity, -1); +} + +// Rolling at full speed, leaving creep (green for the first, brown for the second), until both roll and, past 65 +// frames, one roll in 35 on screen picks the next attack: a beam, a sweep or a spray. +static void sisters_roll_loop(Entity_NPC& npc, const SistersView& view, float speed) +{ + if (npc.sprite.GetFrame() % SISTERS_CREEP_FRAMES == 0) + { + auto* creep = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = view.isSecond ? EFFECT_CREEP_SLIPPERY_BROWN : EFFECT_CREEP_GREEN, + .seed = Random()})); + creep->sprite.scale = vector_make(SISTERS_CREEP_SCALE, SISTERS_CREEP_SCALE); + creep->timeout = SISTERS_CREEP_TIMEOUT; + creep->lifespan = SISTERS_CREEP_TIMEOUT; + creep->Update(); + } + npc.sprite.Play("RollLoop"); + if (!vector_is_zero(npc.velocity)) npc.velocity = vector_scale(vector_normalized(npc.velocity), speed); + + Entity_NPC* sister = view.sister; + if (sister && (sister->state != SISTERS_ROLL || sister->i1 != STEP_LOOP)) return; + if (npc.stateFrame++ <= SISTERS_ROLL_MIN && !view.isImpaired) return; + if (Random() % SISTERS_ROLL_STOP_ODDS != 0 || !g_game->room->camera->IsPosVisible(npc.pos)) return; + + uint32_t roll = Random() % SISTERS_PERCENT; + if (roll < SISTERS_BEAM_PERCENT) npc.i1 = 2; + else npc.i1 = roll < SISTERS_SWEEP_PERCENT ? 3 : 4; +} + +// The roll's end: a taunt, then the attack the roll picked. +static void sisters_roll_end(Entity_NPC& npc, const SistersView& view) +{ + npc.sprite.Play("Taunt"); + if (!npc_anim_is_done(npc)) return; + if (view.isImpaired) return sisters_reset(npc, view.sister); + + int next = npc.i1; + if (next < 2 || next > 4) return; + + npc.targetPosition = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + npc.i1 = 0; + npc.stateFrame = 0; + if (next == 3) npc.state = SISTERS_SWEEP; + else if (next == 4) npc.state = SISTERS_SPRAY; + else + { + npc.state = SISTERS_BEAM; + sisters_tracer_spawn(npc, vector_to_direction(npc.targetPosition), SISTERS_TRACER_TIMEOUT); + } +} + +// The roll: curling up, rolling about the room and ending in an attack. +static void sisters_roll(Entity_NPC& npc, const SistersView& view) +{ + float speed = npc.i2 != 0 ? SISTERS_RAGE_ROLL_SPEED : SISTERS_ROLL_SPEED; + if (npc.i1 == 0) return sisters_roll_start(npc, view, speed); + if (npc.i1 == 1) return sisters_roll_loop(npc, view, speed); + sisters_roll_end(npc, view); +} + +// The beam: from its mouth toward where its target stood, then both back to idle. +static void sisters_beam(Entity_NPC& npc, const SistersView& view) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + int direction = vector_to_direction(npc.targetPosition); + npc.sprite.isFlipX = direction == 0; + switch (npc.i1) + { + case STEP_START: + npc.sprite.Play(LASER_START[direction]); + if (npc_anim_is_done(npc)) npc.i1++; + return; + case STEP_LOOP: + { + sisters_beam_hurt(npc); + npc.sprite.Play(LASER_LOOP[direction]); + Entity_Laser* laser = sisters_beam_fire(npc, direction, SISTERS_BEAM_TIMEOUT); + npc.entityRef = laser; + laser->Update(); + npc.i1++; + return; + } + case STEP_WAIT: + if (!npc.entityRef.get()) npc.i1 = STEP_END; + return; + case STEP_END: + npc.sprite.Play(LASER_END[direction]); + if (npc_anim_is_done(npc)) sisters_reset(npc, view.sister); + return; + } +} + +// The twin beam: after landing, each fires at the other (or a player when alone), the beam reaching halfway. +static void sisters_twin_beam(Entity_NPC& npc, const SistersView& view) +{ + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.entityCollisionClass = ENTCOLL_ALL; + Vector aim = game_random_player(*g_game, npc.pos, SISTERS_FAR)->pos; + if (view.sister) aim = view.sister->pos; + float across = std::abs(npc.pos.x - aim.x); + float down = std::abs(npc.pos.y - aim.y); + bool isAcross = down < across; + int direction = 0; + if (across <= down) direction = (npc.pos.y < aim.y) * 2 + 1; + else if (npc.pos.x < aim.x) direction = 2; + npc.sprite.isFlipX = direction == 0; + + switch (npc.i1) + { + case STEP_START: + npc.sprite.Play(LASER_START[direction]); + sisters_tracer_keep(npc, direction); + if (npc_anim_is_done(npc)) npc.i1++; + return; + case STEP_LOOP: + { + sisters_beam_hurt(npc); + npc.sprite.Play(LASER_LOOP[direction]); + Entity_Laser* laser = sisters_beam_fire(npc, direction, SISTERS_TWIN_BEAM_TIMEOUT); + laser->maxDistance = SISTERS_TWIN_BEAM_REACH; + if (view.sister) + { + float gap = isAcross ? std::abs(npc.pos.x - view.sister->pos.x) - SISTERS_TWIN_GAP_ACROSS + : std::abs(npc.pos.y - view.sister->pos.y) - SISTERS_TWIN_GAP_DOWN; + laser->maxDistance = gap * 0.5f; + } + laser->Update(); + npc.entityRef = laser; + npc.i1++; + return; + } + case STEP_WAIT: + if (!npc.entityRef.get()) npc.i1 = STEP_END; + return; + case STEP_END: + npc.sprite.Play(LASER_END[direction]); + if (!npc_anim_is_done(npc)) return; + npc.state = NPC_STATE_IDLE; + npc.i1 = 0; + npc.stateFrame = 0; + return; + } +} + +// The spray: shots along its facing in pairs, threes or fours (one of three, faster when enraged), for 30 frames. +static void sisters_spray(Entity_NPC& npc, const SistersView& view) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + int direction = vector_to_direction(npc.targetPosition); + if (npc.i1 == STEP_START) + { + npc.sprite.isFlipX = direction == 0; + npc.sprite.Play(LASER_START[direction]); + if (!npc_anim_is_done(npc)) return; + npc.PlaySound(SOUND_BOSS_SPIT_BLOB_BARF, 1, 2, false, 1); + npc.i1++; + npc.v1.x = (float)(Random() % SISTERS_PERCENT); + return; + } + if (npc.i1 == SPRAY_END) + { + npc.sprite.Play(LASER_END[direction]); + if (npc_anim_is_done(npc)) sisters_reset(npc, view.sister); + return; + } + if (npc.i1 != STEP_LOOP) return; + + npc.stateFrame++; + float pick = npc.v1.x; + int period = SISTERS_SPRAY_PERIOD + (npc.i2 == 0) * 2; + ProjectilesMode mode = PROJECTILES_FOUR; + if (pick < SISTERS_SPRAY_THIRD) + { + period += 2; + mode = PROJECTILES_TWO; + } + else if (pick < SISTERS_SPRAY_TWO_THIRDS) + { + period += 1; + mode = PROJECTILES_THREE_WIDE; + } + if (npc.stateFrame % period == 0) + { + float speed = npc.i2 != 0 ? SISTERS_RAGE_SPRAY_SPEED : SISTERS_SPRAY_SPEED; + Vector velocity = vector_scale(vector_from_direction(direction), speed); + float side = direction == 0 ? -SISTERS_SPRAY_SIDE : direction == 2 ? SISTERS_SPRAY_SIDE : 0; + ProjectileParams params; + params.depthOffset = direction == 1 ? SISTERS_BEAM_BACK_DEPTH : SISTERS_BEAM_FRONT_DEPTH; + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + npc.FireProjectiles(vector_make(npc.pos.x + side, npc.pos.y + SISTERS_SPRAY_HEIGHT), velocity, mode, params); + } + if (npc.stateFrame > SISTERS_SPRAY_FRAMES) npc.i1++; +} + +// Whether a sweeping beam turned past the edge of its quarter (and turns back), or ended its sweep. The edges are +// 150 to 210 facing left, 240 to 300 up, 330 to 30 right and 60 to 120 down. +static void sisters_sweep_turn(Entity_NPC& npc, Entity_Laser& laser, int direction) +{ + float angle = laser.angleDegrees; + if (angle < 0) angle += FULL_TURN_DEGREES; + angle += npc.i1 == 3 ? SISTERS_SWEEP_TURN : -SISTERS_SWEEP_TURN; + + bool isWrapped = true; + switch (direction) + { + case 0: + if (angle >= 210) npc.i1 = 2; + else if (angle <= 150) npc.i1 = 3; + break; + case 1: + if (angle >= 300) npc.i1 = 2; + else if (angle <= 240) npc.i1 = 3; + break; + case 2: + if (angle >= 30 && angle < 180) npc.i1 = 2; + else if (angle > 180 && angle <= 330) npc.i1 = 3; + else if (angle <= 180) isWrapped = false; + break; + case 3: + if (angle >= 120) npc.i1 = 2; + else if (angle <= 60) npc.i1 = 3; + break; + } + if (isWrapped && angle > HALF_TURN_DEGREES) angle -= FULL_TURN_DEGREES; + laser.set_aim_angle(normalize_angle_degrees(angle)); +} + +// The sweep: a long beam swinging back and forth across its quarter until it fades. +static void sisters_sweep(Entity_NPC& npc, const SistersView& view) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + int direction = vector_to_direction(npc.targetPosition); + if (npc.i1 == STEP_START) + { + npc.sprite.isFlipX = direction == 0; + npc.sprite.Play(LASER_START[direction]); + sisters_tracer_keep(npc, direction); + if (npc_anim_is_done(npc)) npc.i1++; + return; + } + if (npc.i1 == STEP_LOOP) + { + sisters_beam_hurt(npc); + npc.sprite.Play(LASER_LOOP[direction]); + Entity_Laser* laser = sisters_beam_fire(npc, direction, SISTERS_SWEEP_TIMEOUT); + laser->Update(); + npc.entityRef = laser; + npc.i1 = (int)(Random() & 1) + 2; + return; + } + if (npc.i1 == 4) + { + npc.sprite.Play(LASER_END[direction]); + if (npc_anim_is_done(npc)) sisters_reset(npc, view.sister); + return; + } + if (npc.i1 > 4) return; + if (!npc.entityRef.get()) + { + npc.i1 = 4; + return; + } + sisters_sweep_turn(npc, *static_cast(npc.entityRef.get()), direction); +} + +// The leap: Jumping, then the loop, gliding to its spot from the jump on until it lands there. +static void sisters_leap(Entity_NPC& npc) +{ + if (npc.i1 == 0) + { + npc.sprite.Play("Jumping"); + npc.i1++; + } + else if (npc.i1 == 1 && npc_anim_is_done(npc)) + { + npc.sprite.Play("JumpLoop"); + npc.i1++; + } + else if (npc.i1 == 2 && vector_length_squared(vector_sub(npc.targetPosition, npc.pos)) < SISTERS_LEAP_ARRIVE_SQUARED) + { + npc.i1 = 0; + npc.state = SISTERS_LAND; + npc.entityCollisionClass = ENTCOLL_ALL; + } + + if (npc.sprite.WasEventTriggered("Jump")) npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + if (npc.i1 < 2 && !npc.sprite.WasEventTriggered("Jump")) return; + + npc.v1.x = std::min(npc.v1.x + SISTERS_LEAP_STEP, 1.0f); + npc.pos = vector_add(vector_scale(npc.pos, 1 - npc.v1.x), vector_scale(npc.targetPosition, npc.v1.x)); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; +} + +// The landing, then the twin beam once both stand (or idle alone). +static void sisters_land(Entity_NPC& npc, Entity_NPC* sister) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + if (npc.i1 == 0) + { + npc.sprite.Play("Landing"); + npc.i1++; + return; + } + if (npc.i1 == 1) + { + if (npc.sprite.IsEventTriggered("Landed")) npc.PlaySound(SOUND_MEAT_IMPACTS, 1, 2, false, 1); + if (npc_anim_is_done(npc)) npc.i1++; + return; + } + if (!npc_anim_is_done(npc)) return; + + if (!sister) + { + npc.i1 = 0; + npc.state = NPC_STATE_IDLE; + } + else if (sister->i1 == 2) + { + npc.i1 = 0; + sister->i1 = 0; + npc.state = SISTERS_TWIN_BEAM; + sister->state = SISTERS_TWIN_BEAM; + } +} + +// Each sister ignores her Vis' hits, and rages red (hitting harder, rolling and shooting faster) when alone or far +// healthier than the other. +static SistersView sisters_view(Entity_NPC& npc) +{ + SistersView view; + view.sister = static_cast(npc.child.get()); + bool isSpawnedTwin = npc.spawnerType == npc.type; + view.isFirst = !isSpawnedTwin && view.sister; + view.isSecond = isSpawnedTwin && view.sister; + view.isImpaired = npc.HasEntityFlags(FLAG_DISTRACTED); + view.isSisterInactive = !view.sister || view.sister->HasEntityFlags(FLAG_DISTRACTED); + if (!view.sister) npc.i2++; + else if (npc.health - view.sister->health > SISTERS_RAGE_GAP) npc.i2 = SISTERS_RAGE_FRAMES; + + if (npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + if (event.source.type == ENTITY_VIS) event.damage = 0; + return view; +} + +// 00496fb0 The Sisters Vis (410): two sisters leaping to opposite walls and beaming at each other, rolling about in +// creep, summoning Vis and Begotten, and beaming, sweeping and spraying alone. +void boss_sisters_vis_update(Entity_NPC& npc) +{ + SistersView view = sisters_view(npc); + if (npc.state == NPC_STATE_INIT) return sisters_init(npc); + + npc.sprite.color = npc.i2 == 0 ? npc.color : SISTERS_RAGE_COLOR; + npc.collisionDamage = npc.i2 == 0 ? 1 : SISTERS_RAGE_DAMAGE; + switch (npc.state) + { + case NPC_STATE_IDLE: + sisters_idle(npc, view); + break; + case SISTERS_SUMMON_BEGOTTEN: + case SISTERS_SUMMON_VIS: + sisters_summon(npc); + break; + case SISTERS_ROLL: + sisters_roll(npc, view); + break; + case SISTERS_BEAM: + sisters_beam(npc, view); + break; + case SISTERS_LEAP: + sisters_leap(npc); + break; + case SISTERS_LAND: + sisters_land(npc, view.sister); + break; + case SISTERS_TWIN_BEAM: + sisters_twin_beam(npc, view); + break; + case SISTERS_SPRAY: + sisters_spray(npc, view); + break; + case SISTERS_SWEEP: + sisters_sweep(npc, view); + break; + } + + bool isBeaming = npc.state == SISTERS_BEAM || npc.state == SISTERS_TWIN_BEAM || npc.state == SISTERS_SWEEP || + npc.state == SISTERS_SPRAY; + if (!isBeaming) npc.sprite.isFlipX = npc.GetPlayerTarget()->pos.x - npc.pos.x < 0; + if (npc.sprite.animState.animData && npc.sprite.IsEventTriggered("ScareSFX")) + npc_sound_play(SOUND_SISTERS_VIS_SCARE, 1, 2, 1); + npc.friction *= SISTERS_FRICTION; + if (npc.i2 > 0) npc.i2--; +} diff --git a/src/boss_tuff_twins.cpp b/src/boss_tuff_twins.cpp new file mode 100644 index 0000000..8eb3f14 --- /dev/null +++ b/src/boss_tuff_twins.cpp @@ -0,0 +1,572 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_effect_combat.h" +#include "entity_familiar.h" +#include "path_finder.h" +#include +#include +#include + +// The Tuff Twins (Larry Jr. variant 2) and the Shell (variant 3): chains of stony segments. A segment starts encased +// (i2 0), its hits much reduced and only blasts and crushes hurting it, and breaks out once 15 health is gone. The +// Tuff Twins crawl about, their heads spitting suckers and their bodies lobbing shots. The Shell's encased head rolls +// at its target dragging the rest, an exposed one turns the chain around, and exposed segments spawn Fly Bombs or +// shoot. +constexpr int TUFF_TWINS = 2; +constexpr int TUFF_SHELL = 3; + +// Breaking out: the 15 health of the casing, blasts dealing 40% (30% exposed, and less the further they went off, +// down to a quarter at 128), crushes 60% to a casing, the rest nothing. +constexpr float CASING_HEALTH = 15; +constexpr float BLAST_REACH = 128; +constexpr float BLAST_FALLOFF = 0.75f; +constexpr float BLAST_SHARE_ENCASED = 0.4f; +constexpr float BLAST_SHARE_EXPOSED = 0.3f; +constexpr float CRUSH_SHARE = 0.6f; +constexpr int BREAK_PARTICLES_MIN = 6; +constexpr uint32_t BREAK_PARTICLES_RANGE = 3; +constexpr float BREAK_PARTICLE_SPEED = 5; +constexpr int BREAK_PARTICLE_SUBTYPE = 0x10001; +constexpr uint32_t SHELL_ATTACK_DELAY_RANGE = 30; +constexpr int SHELL_ATTACK_DELAY_MIN = 30; +constexpr float HEAD_DEATH_HEAL = 25; + +// Movement: the Shell crawls 2.5 a frame (1.9 once a part broke out), its head rolling at its target and swerving +// along the walls, a segment trailing 24 behind its parent. The Tuff Twins wander axis-aligned, 1.8 down to 1 as more +// of them break out. +constexpr float SHELL_SPEED = 2.5f; +constexpr float SHELL_SPEED_BROKEN = 1.9f; +constexpr float SHELL_FRICTION = 0.85f; +constexpr float SHELL_TURN_MIN = 10; +constexpr float SHELL_TURN_RANGE = 10; +constexpr float SHELL_DIAGONAL_STEP = 90; +constexpr float SHELL_DIAGONAL = 45; +constexpr float SHELL_STRETCH = 160; +constexpr float SHELL_STRETCH_PULL = 0.001f; +constexpr float SHELL_STRETCH_TURN = 5; +constexpr float SHELL_AIM_NEAR = 130; +constexpr float SHELL_AIM_FULL = 70; +constexpr float SHELL_AIM_SPAN = 60; +constexpr float SHELL_AIM_TURN_MIN = 2; +constexpr float SHELL_AIM_TURN_RANGE = 1.5f; +constexpr float SHELL_PATH_SPEED_MIN = 0.2f; +constexpr float SHELL_PATH_SPEED_RANGE = 0.8f; +constexpr int SHELL_PATH_MARKER = 900; +constexpr float SHELL_SLACK = 10; +constexpr float SHELL_SLACK_PULL = 0.05f; +constexpr float TUFF_SEGMENT_GAP = 24; +constexpr float SEGMENT_SPEED_SCALE = 5; +constexpr float TWINS_WEIGHT_ENCASED = 3.5f; +constexpr float TWINS_WEIGHT_EXPOSED = 1; +constexpr float TWINS_WEIGHT_FIRST = 2; +constexpr float TWINS_WEIGHT_SPAN = 18; +constexpr float TWINS_SPEED_MAX = 1.8f; +constexpr float TWINS_SPEED_SPAN = 0.79999995f; +constexpr float TUFF_ATTACK_FRICTION = 0.8f; +constexpr float TUFF_SEGMENT_FRICTION = 0.8f; + +// Joining: a new segment hooks onto a free tail within 42 of the same kind. +constexpr float JOIN_REACH = 42; + +// Attacks: a Tuff Twin's head every 10th frame 1 time in 24 with fewer than 4 flies and suckers about, an exposed body +// every 5th frame 1 time in 24. The Shell's exposed parts once rested: its butt a Fly Bomb (fewer than 4), its guts +// three shots, resting 90 to 149 (the head 20, the middle 60 to 89). +constexpr uint32_t TUFF_ATTACK_ODDS = 24; +constexpr int HEAD_ATTACK_FRAMES = 10; +constexpr int BODY_ATTACK_FRAMES = 5; +constexpr int SPAWNS_MAX = 4; +constexpr uint32_t BUTT_REST_RANGE = 60; +constexpr int BUTT_REST_MIN = 90; +constexpr int HEAD_REST = 20; +constexpr uint32_t GUTS_REST_RANGE = 30; +constexpr int GUTS_REST_MIN = 60; +constexpr int HEAD_RENDER_Z = 200; +constexpr float FLY_BOMB_SPEED = 3; +constexpr float GUTS_SHOT_SPEED = 8; +constexpr float GUTS_SHOT_DROP = -0.075f; +constexpr float SUCKER_SPEED = 30; +constexpr float SUCKER_SPREAD = 20; +constexpr float SUCKER_AHEAD = 2; +constexpr int SUCKER_ENCASED = 3; +constexpr int SUCKER_EXPOSED = 0; +constexpr float BODY_SHOT_REACH = 160; +constexpr uint32_t BODY_SHOTS_RANGE = 3; +constexpr int BODY_SHOTS_MIN = 2; +constexpr float BODY_SHOT_CURVE = 10; +constexpr float BODY_SHOT_POOF_RISE = -12; +constexpr uint32_t SPLAT_MASK = 7; +constexpr float TUFF_SPLAT_SIZE_MIN = 0.2f; +constexpr float TUFF_SPLAT_SIZE_RANGE = 0.5f; +constexpr int ROTATE_FRAMES = 8; +constexpr float ROTATE_STEP = 45; +constexpr int SHELL_BOUNCE_LAYER = 1; + +constexpr std::array WALK_HEAD_ANIMS = {"WalkHeadHori", "WalkHeadUp", "WalkHeadHori", "WalkHeadDown"}; +constexpr std::array ATTACK_HEAD_ANIMS = {"AttackHeadHori", "AttackHeadUp", "AttackHeadHori", + "AttackHeadDown"}; +constexpr std::array BUTT_ANIMS = {"ButtHori", "ButtUp", "ButtHori", "ButtDown"}; +constexpr std::array BODY_ANIMS = {"Body1Hori", "Body1Vert", "Body2Hori", + "Body2Vert", "Body3Hori", "Body3Vert"}; +constexpr std::array BODY_ATTACK_ANIMS = {"Body1AttackHori", "Body1AttackVert", "Body2AttackHori", + "Body2AttackVert", "Body3AttackHori", "Body3AttackVert"}; +constexpr size_t BODY_ATTACK_PREFIX = 11; + +// The way (0 left, 1 up, 2 right, 3 down) a vector leans along most, down on a tie. +static int direction_get(Vector v) +{ + if (std::abs(v.x) <= std::abs(v.y)) return v.y >= 0 ? 3 : 1; + return v.x < 0 ? 0 : 2; +} + +// Isaac::GetAxisAlignedUnitVectorFromDir: the unit step of a way. +static Vector direction_vector_get(int way) +{ + const std::array steps = {vector_make(-1, 0), vector_make(0, -1), vector_make(1, 0), vector_make(0, 1)}; + return steps[way & 3]; +} + +// 005999b0 Plays an animation, its exposed version ("B") once the segment broke out. +static void tuff_play(Entity_NPC& npc, std::string_view anim) +{ + npc.sprite.Play(npc.i2 != 0 ? std::string(anim) + "B" : std::string(anim)); +} + +// An angle wrapped into a frame of a turning animation's 8 ways. +static int rotate_frame_get(float degrees) +{ + return (int)((degrees + DEGREES_PER_TURN) / ROTATE_STEP + 0.5f) % ROTATE_FRAMES; +} + +// 00599b80 A head's walk: the Shell's rolling frame at its heading (a half frame up while bouncing) under its overlay, +// a Tuff Twin's by its way. +static void head_anim(Entity_NPC& npc) +{ + if (npc.variant != TUFF_SHELL) + { + tuff_play(npc, WALK_HEAD_ANIMS[npc.i1]); + npc.sprite.isFlipX = npc.i1 == 0; + return; + } + + int frame = rotate_frame_get(angle_wrap(npc.v1.y)) * 2; + const NullFrame* bounce = + npc.sprite.overlayAnimState.animData ? npc.sprite.overlayAnimState.GetNullFrame("Bounce") : nullptr; + if (bounce && bounce->color._tint[0] > 0) frame++; + if (npc.sprite.SetAnimation("HeadRotate")) + { + npc.sprite.SetFrame((float)frame); + npc.sprite.animState.isPlaying = false; + } + npc.sprite.PlayOverlay("WalkHeadOverlay"); +} + +// 00599d70 A body's walk: a Tuff Twin's by its way to its parent (one of three looks by its seed), the Shell's by its +// angle, its exposed parts idling. +static void body_anim(Entity_NPC& npc) +{ + if (npc.variant != TUFF_SHELL) + { + int way = direction_get(vector_sub(npc.parent->pos, npc.pos)); + tuff_play(npc, BODY_ANIMS[(way & 1) + (npc.initSeed % 3) * 2]); + npc.sprite.isFlipX = way == 0; + return; + } + if (npc.i2 != 0) + { + npc.sprite.Play(npc.child ? "GutsIdle" : "ButtIdle"); + npc.sprite.overlayAnimState.SetAnimationData(nullptr); + return; + } + if (npc.sprite.SetAnimation("BodyRotate")) + { + float angle = vector_angle(vector_sub(npc.parent->pos, npc.pos)); + npc.sprite.SetFrame((float)rotate_frame_get(angle)); + npc.sprite.animState.isPlaying = false; + } + npc.sprite.PlayOverlay("WalkBodyOverlay"); +} + +// 0059a200 A Tuff Twin's tail: its butt, by its way to its parent. +static void butt_anim(Entity_NPC& npc) +{ + int way = direction_get(vector_sub(npc.parent->pos, npc.pos)); + tuff_play(npc, BUTT_ANIMS[way]); + npc.sprite.isFlipX = way == 0; +} + +// 00599f80 A Tuff Twin body's attack, keeping its frame when it only turned. +static void body_attack_anim(Entity_NPC& npc) +{ + int way = direction_get(vector_sub(npc.parent->pos, npc.pos)); + std::string_view attack = BODY_ATTACK_ANIMS[(way & 1) + (npc.initSeed % 3) * 2]; + npc.sprite.isFlipX = way == 0; + const std::string& current = npc.sprite.GetAnimation(); + if (current == attack) return; + + bool isTurning = current.compare(0, BODY_ATTACK_PREFIX, attack.substr(0, BODY_ATTACK_PREFIX)) == 0; + int frame = npc.sprite.animState.animData ? (int)std::floor(npc.sprite.animState.animFrame) : -1; + tuff_play(npc, attack); + if (isTurning) npc.sprite.SetFrame((float)frame); +} + +// 00599950 How many of what its head spits are about: flies and suckers for the Tuff Twins, Fly Bombs for the Shell. +static int spawns_count(Entity_NPC& npc) +{ + int count = 0; + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (npc.variant == TUFF_TWINS && (entity->type == ENTITY_FLY || entity->type == ENTITY_SUCKER)) count++; + else if (npc.variant == TUFF_SHELL && entity->type == ENTITY_FLY_BOMB) count++; + } + return count; +} + +// A segment's casing breaking: a crumble, rubble, and its hits counting again. +static void casing_break(Entity_NPC& npc, Entity_NPC& sounder) +{ + npc.i2 = 1; + npc.health = npc.maxHitPoints - CASING_HEALTH; + if (npc.variant == TUFF_SHELL) npc.projectileCooldown = (int)(Random() % SHELL_ATTACK_DELAY_RANGE) + SHELL_ATTACK_DELAY_MIN; + if (&sounder == &npc) npc_sound_play(SOUND_ROCK_CRUMBLE, 1, 2, champion_pitch_get(npc)); + else sounder.PlaySound(SOUND_ROCK_CRUMBLE, 1, 2, false, 1); + game_particles_spawn({.position = npc.pos, + .speed = BREAK_PARTICLE_SPEED, + .count = (int)(Random() % BREAK_PARTICLES_RANGE) + BREAK_PARTICLES_MIN, + .subType = BREAK_PARTICLE_SUBTYPE, + .variant = EFFECT_ROCK_PARTICLE}); + npc.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.state = NPC_STATE_MOVE; +} + +// Before its update: its hits filtered by its casing, and the casing breaking once 15 health is gone. The Shell's +// encased head takes nothing. +static void tuff_pre_update(Entity_NPC& npc) +{ + if (npc.variant == TUFF_SHELL && !npc.parent && npc.i2 == 0) + { + npc.damageEvents.clear(); + npc.pendingDamage = 0; + } + else + for (auto event = npc.damageEvents.begin(); event != npc.damageEvents.end();) + { + npc.pendingDamage -= event->damage; + bool isBlast = event->damageFlags & DAMAGE_EXPLOSION; + bool isCrush = event->damageFlags & DAMAGE_CRUSH; + if (npc.i2 == 0 && !isBlast && !isCrush) + { + event = npc.damageEvents.erase(event); + continue; + } + if (isCrush && npc.i2 == 0) event->damage *= CRUSH_SHARE; + else if (isBlast) + { + if (!vector_is_zero(event->source.position)) + { + float distance = vector_length(vector_sub(event->source.position, npc.pos)); + event->damage *= 1 - std::clamp(distance / BLAST_REACH, 0.0f, 1.0f) * BLAST_FALLOFF; + } + event->damage *= npc.i2 == 0 ? BLAST_SHARE_ENCASED : BLAST_SHARE_EXPOSED; + } + npc.pendingDamage += event->damage; + ++event; + } + if (npc.i2 != 0 || npc.health - npc.pendingDamage > npc.maxHitPoints - CASING_HEALTH) return; + + npc.damageEvents.clear(); + npc.pendingDamage = 0; + casing_break(npc, npc); +} + +// Dying: a head's death heals its next segment by 25, and the Shell's next segment breaks out if it is the tail. +static void tuff_death(Entity_NPC& npc) +{ + Entity_NPC* next = npc.ChildNPC(); + if (!npc.parent && next && next->health > 0) next->health = std::min(next->health + HEAD_DEATH_HEAL, next->maxHitPoints); + if (npc.variant == TUFF_SHELL && next && next->i2 == 0 && !next->child) casing_break(*next, npc); +} + +// The Shell's chain turns around once its head broke out while its tail is still encased. +static void shell_chain_reverse(Entity_NPC& npc) +{ + Entity_NPC* tail = static_cast(npc.GetLastChild()); + if (npc.parent || npc.i2 == 0 || tail->i2 != 0) return; + + for (Entity_NPC* segment = &npc; segment;) + { + Entity_NPC* next = segment->ChildNPC(); + Entity* previous = segment->parent.get(); + segment->child = previous; + segment->parent = next; + if (!next) + { + if (segment->child) segment->v1.y = vector_angle(vector_sub(segment->pos, segment->child->pos)); + break; + } + segment = next; + } +} + +// The Shell's encased head rolls on at its heading: off walls to a diagonal, back toward a lagging exposed part, and +// toward its target when near. +static void shell_head_roll(Entity_NPC& npc) +{ + if (npc.isCollidesWithGrid) + { + npc.v1.y = vector_angle(npc.velocity); + float diagonal = angle_wrap(std::floor(npc.v1.y / SHELL_DIAGONAL_STEP) * SHELL_DIAGONAL_STEP + SHELL_DIAGONAL); + npc.v1.y = angle_approach(npc.v1.y, diagonal, random_unit() * SHELL_TURN_RANGE + SHELL_TURN_MIN); + } + Entity_NPC* previous = &npc; + for (Entity_NPC* segment = npc.ChildNPC(); segment; previous = segment, segment = segment->ChildNPC()) + { + Vector gap = vector_sub(segment->pos, previous->pos); + if (segment->i2 == 0 || vector_length(gap) <= SHELL_STRETCH) continue; + + Vector heading = vector_from_angle(npc.v1.y); + Vector pulled = vector_add(vector_scale(gap, SHELL_STRETCH_PULL), heading); + npc.v1.y = angle_approach(npc.v1.y, vector_angle(pulled), SHELL_STRETCH_TURN); + break; + } + Vector target = npc.CalcTargetPosition(0); + float distance = vector_length(vector_sub(npc.pos, target)); + if (distance < SHELL_AIM_NEAR) + { + float pull = 1 - std::clamp((distance - SHELL_AIM_FULL) / SHELL_AIM_SPAN, 0.0f, 1.0f); + float turn = (random_unit() * SHELL_AIM_TURN_RANGE + SHELL_AIM_TURN_MIN) * pull * npc.speedMultiplier; + npc.v1.y = angle_approach(npc.v1.y, vector_angle(vector_sub(target, npc.pos)), turn); + } + npc_push(npc, vector_scale(vector_from_angle(npc.v1.y), npc.v1.x)); +} + +// The Shell's crawl: its chain turned around if need be, encased parts trailing their head, exposed ones pathing (the +// head) or kept close to their parent. +static void shell_move(Entity_NPC& npc) +{ + shell_chain_reverse(npc); + Entity_NPC* parent = npc.ParentNPC(); + if (parent && npc.child) npc.v1.y = vector_angle(vector_sub(npc.pos, npc.child->pos)); + if (npc.i2 != 0 && npc.entityGridCollisionClass == GRIDCOLL_WALLS && room_grid_collision_at(npc.pos) == 0) + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + + npc.v1.x = SHELL_SPEED; + for (Entity* segment = npc.child; segment; segment = segment->child) + if (static_cast(segment)->i2 != 0) + { + npc.v1.x = SHELL_SPEED_BROKEN; + break; + } + + npc.friction *= SHELL_FRICTION; + bool isTrailing = npc.i2 == 0 && (!parent || parent->i2 == 0); + if (isTrailing && !parent) shell_head_roll(npc); + else if (!isTrailing && !parent && npc.child) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), random_unit() * SHELL_PATH_SPEED_RANGE + SHELL_PATH_SPEED_MIN, + SHELL_PATH_MARKER, DIRECT_PATH_FAR); + else if (!isTrailing && parent) + { + Vector away = vector_sub(npc.pos, parent->pos); + float distance = vector_length(away); + if (distance > SHELL_SLACK) + npc.velocity = vector_sub(npc.velocity, vector_scale(vector_normalized(away), + (distance - SHELL_SLACK) * SHELL_SLACK_PULL * npc.speedMultiplier)); + } + segment_follow(npc, isTrailing ? SEGMENT_FOLLOW : SEGMENT_RECORD, TUFF_SEGMENT_GAP, npc.v1.x * SEGMENT_SPEED_SCALE); +} + +// The Tuff Twins' wander: slower the more of them are encased, each segment trailing its parent. +static void twins_move(Entity_NPC& npc) +{ + float weight = 0; + for (Entity* segment = &npc; segment; segment = segment->child) + weight += static_cast(segment)->i2 == 0 ? TWINS_WEIGHT_ENCASED : TWINS_WEIGHT_EXPOSED; + npc.v1.x = TWINS_SPEED_MAX - std::clamp((weight - TWINS_WEIGHT_FIRST) / TWINS_WEIGHT_SPAN, 0.0f, 1.0f) * TWINS_SPEED_SPAN; + npc.pathfinder.MoveRandomlyAxisAligned(npc.v1.x, STATUS_OBEYED); + segment_follow(npc, SEGMENT_FOLLOW, TUFF_SEGMENT_GAP, npc.v1.x * SEGMENT_SPEED_SCALE); + npc.i1 = direction_get(npc.velocity); +} + +// Its first frame: hooked onto a nearby free tail of its kind, untargetable while encased, the head facing away from +// its body at a random heading, the chain grouped under the head. +static void tuff_init(Entity_NPC& npc) +{ + npc.i2 = 0; + npc.aiCallFlags |= AI_CALL_PRE_UPDATE; + npc.entityGridCollisionClass = npc.variant != TUFF_SHELL ? GRIDCOLL_GROUND : GRIDCOLL_WALLS; + if (npc.variant == TUFF_SHELL) npc.sprite.GetLayer(SHELL_BOUNCE_LAYER)->isVisible = false; + + std::vector kin = entity_query(npc.type, npc.variant); + for (auto other = kin.rbegin(); other != kin.rend(); ++other) + { + Entity* tail = *other; + if (tail == &npc || tail->parent.get() == &npc || tail->child || vector_length(vector_sub(npc.pos, tail->pos)) >= JOIN_REACH) + continue; + bool isLoop = false; + for (Entity* link = tail; link && !isLoop; link = link->parent.get()) + { + isLoop = link == &npc; + if (link->parent.get() == tail) break; + } + if (!isLoop) npc.parent = tail; + } + if (npc.parent) npc.parent->child = &npc; + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + + if (npc.parent) return body_anim(npc); + npc.i1 = npc.child ? direction_get(vector_sub(npc.pos, npc.child->pos)) : (int)(npc.initSeed & 3); + // The original stops on a zero seed. Here the heading stays 0. + RNG heading = {npc.initSeed, 2, 9, 15}; + npc.v1.y = npc.initSeed ? heading.RandomFloat() * DEGREES_PER_TURN : 0; + head_anim(npc); + for (Entity* segment = &npc; segment; segment = segment->child) + { + segment_follow(npc, SEGMENT_FOLLOW, TUFF_SEGMENT_GAP, 0); + static_cast(segment)->groupIdx = (int)npc.index; + } + if (npc.variant == TUFF_SHELL) return; + auto* tail = static_cast(npc.GetLastChild()); + if (tail->parent) butt_anim(*tail); +} + +// Walking: the head's or body's look, and the start of an attack. +static void tuff_walk(Entity_NPC& npc) +{ + npc.ClearEntityFlags(FLAG_NO_TARGET); + bool isHead = !npc.parent && (npc.variant != TUFF_SHELL || npc.i2 == 0); + if (isHead) head_anim(npc); + else if (npc.child || npc.variant == TUFF_SHELL) body_anim(npc); + else butt_anim(npc); + npc.renderZOffset = isHead ? HEAD_RENDER_Z : 0; + + if (npc.variant == TUFF_SHELL) + { + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + if (npc.i2 == 0 || npc.projectileCooldown > 0) return; + if (!npc.child && spawns_count(npc) >= SPAWNS_MAX) return; + + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play(npc.child ? "GutsAttack" : "ButtAttack"); + if (!npc.child) npc.projectileCooldown = (int)(Random() % BUTT_REST_RANGE) + BUTT_REST_MIN; + else if (!npc.parent) npc.projectileCooldown = HEAD_REST; + else npc.projectileCooldown = (int)(Random() % GUTS_REST_RANGE) + GUTS_REST_MIN; + npc.sprite.isFlipX = npc.GetPlayerTarget()->pos.x > npc.pos.x; + return; + } + if (!npc.parent && npc.IsFrame(HEAD_ATTACK_FRAMES, (int)npc.initSeed) && Random() % TUFF_ATTACK_ODDS == 0 && + spawns_count(npc) < SPAWNS_MAX) + npc.state = NPC_STATE_ATTACK; + if (npc.parent && npc.child && npc.i2 != 0 && npc.IsFrame(BODY_ATTACK_FRAMES, (int)npc.initSeed) && + Random() % TUFF_ATTACK_ODDS == 0) + npc.state = NPC_STATE_ATTACK; +} + +// The Shell's attack on Shoot: its butt a Fly Bomb away from its parent, its guts three shots at its target. +static void shell_attack(Entity_NPC& npc) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc.PlaySound(SOUND_WORM_SPIT, 1, 2, false, 1); + if (npc.child) + { + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + ProjectileParams params; + params.fallingAccelModifier = GUTS_SHOT_DROP; + return npc.FireProjectiles(npc.pos, vector_scale(aim, GUTS_SHOT_SPEED), PROJECTILES_THREE_WIDE, params); + } + Vector away = npc.parent ? vector_normalized(vector_sub(npc.pos, npc.parent->pos)) : random_direction(); + Entity* bomb = g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(away, FLY_BOMB_SPEED), + .spawner = &npc, + .type = ENTITY_FLY_BOMB, + .seed = Random()}); + bomb->ClearEntityFlags(FLAG_APPEAR); + bomb->Update(); +} + +// A Tuff Twin head's attack: a sucker spat 30 fast its way, a little off, encased ones of the ink kind. +static void twins_head_attack(Entity_NPC& npc) +{ + npc.friction *= TUFF_ATTACK_FRICTION; + tuff_play(npc, ATTACK_HEAD_ANIMS[npc.i1]); + npc.renderZOffset = HEAD_RENDER_Z; + npc.sprite.isFlipX = npc.i1 == 0; + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + Vector way = direction_vector_get(npc.i1); + npc.PlaySound(SOUND_WHEEZY_COUGH, 1, 2, false, 1); + uint32_t seed = Random(); + float angle = (random_unit() * SUCKER_SPREAD - SUCKER_SPREAD / 2) * DEGREES_TO_RADIANS; + Vector velocity = vector_make((std::cos(angle) * way.x - way.y * std::sin(angle)) * SUCKER_SPEED, + (std::sin(angle) * way.x + std::cos(angle) * way.y) * SUCKER_SPEED); + g_game->Spawn({.position = vector_add(npc.pos, vector_scale(way, SUCKER_AHEAD)), + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_SUCKER, + .variant = npc.i2 != 0 ? SUCKER_EXPOSED : SUCKER_ENCASED, + .seed = seed}); +} + +// A Tuff Twin body's attack: two to four shots lobbed at its target (or anywhere when it is far), with a poof. +static void twins_body_attack(Entity_NPC& npc) +{ + body_attack_anim(npc); + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + Vector target = npc.GetPlayerTarget()->pos; + if (vector_length(vector_sub(npc.pos, target)) > BODY_SHOT_REACH) target = {}; + npc.FireBossProjectiles((int)(Random() % BODY_SHOTS_RANGE) + BODY_SHOTS_MIN, target, BODY_SHOT_CURVE, + ProjectileParams()); + Entity* poof = + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BULLET_POOF, .seed = Random()}); + poof->sprite.offset = vector_make(0, BODY_SHOT_POOF_RISE); +} + +// The Shell's bounce: its layers follow the overlay's Bounce null, or rest. +static void shell_bounce(Entity_NPC& npc) +{ + const NullFrame* bounce = + npc.sprite.overlayAnimState.animData ? npc.sprite.overlayAnimState.GetNullFrame("Bounce") : nullptr; + for (int i = 0; i < (int)npc.sprite.layerStates.size(); i++) + { + LayerState* layer = npc.sprite.GetLayer(i); + layer->pos = bounce ? bounce->pos : Vector{}; + layer->size = bounce ? bounce->scale : vector_make(1, 1); + layer->rotation = bounce ? bounce->rotation : 0; + } +} + +// 0059a2d0 (NpcAI::ENTITY_TUFF_TWINS) The Tuff Twins and the Shell: casings filtered and broken before the update, +// then their deaths, their crawl, walk and attacks. A head left alone dies unless it is the Shell's broken-out head. +void boss_tuff_twins_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return tuff_pre_update(npc); + + npc.friction *= TUFF_SEGMENT_FRICTION; + if (npc.isDead) tuff_death(npc); + if (npc.state != NPC_STATE_INIT) npc.variant == TUFF_SHELL ? shell_move(npc) : twins_move(npc); + + if (npc.state == NPC_STATE_INIT) + { + tuff_init(npc); + npc.state = NPC_STATE_MOVE; + } + else if (npc.state == NPC_STATE_MOVE) tuff_walk(npc); + else if (npc.state == NPC_STATE_ATTACK) + { + if (npc.variant == TUFF_SHELL) shell_attack(npc); + else if (!npc.parent) twins_head_attack(npc); + else twins_body_attack(npc); + if (!npc.sprite.IsPlaying()) npc.state = NPC_STATE_MOVE; + } + + if (!npc.parent && !npc.child && (npc.variant != TUFF_SHELL || npc.i2 == 0)) npc.Kill(EntityRef()); + if (npc.i2 != 0 && (Random() & SPLAT_MASK) == 0) npc.MakeSplat(random_unit() * TUFF_SPLAT_SIZE_RANGE + TUFF_SPLAT_SIZE_MIN); + if (npc.variant == TUFF_SHELL) shell_bounce(npc); + + Entity_NPC* next = npc.ChildNPC(); + if (!npc.isDead || !next) return; + next->pathfinder.Reset(); + for (Entity* segment = next; segment; segment = segment->child) + static_cast(segment)->groupIdx = (int)next->index; +} diff --git a/src/entity.cpp b/src/entity.cpp index b5624a6..fb6504d 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -1,4 +1,5 @@ #include "entity.h" +#include "capsule.h" #include "entity_effect.h" #include "entity_familiar.h" #include "entity_list.h" @@ -1250,10 +1251,44 @@ void* Entity::GetDebugShape(bool) reconstruction_missing("Entity::GetDebugShape 006b5f10"); } -// 006b6c20 -void Entity::GetNullCapsule(Capsule&, std::string_view) +// 006b6c20 The capsule its sprite's null layer covers: placed and turned like GetNullOffset, four times the null's +// scale wide and tall, or a point at its position while the null is hidden or missing. +void Entity::GetNullCapsule(Capsule& outCapsule, std::string_view nullLayerName) { - reconstruction_missing("Entity::GetNullCapsule 006b6c20"); + constexpr float NULL_CAPSULE_SIZE = 4; + const NullFrame* frame = sprite.animState.animData ? sprite.animState.GetNullFrame(nullLayerName) : nullptr; + if (!frame || !frame->isVisible) + { + outCapsule = Capsule(pos, Vector{}, 0, 0); + return; + } + + Vector offset = vector_make(frame->pos.x / ROOM_SCREEN_SCALE * sprite.scale.x, frame->pos.y / ROOM_SCREEN_SCALE * sprite.scale.y); + Vector size = vector_make(frame->scale.x * NULL_CAPSULE_SIZE / ROOM_SCREEN_SCALE * sprite.scale.x, + frame->scale.y * NULL_CAPSULE_SIZE / ROOM_SCREEN_SCALE * sprite.scale.y); + float rotation = frame->rotation; + if (sprite.isFlipX) size.x = -size.x; + if (sprite.isFlipY) size.y = -size.y; + if (size.x < 0) + { + size.x = -size.x; + rotation = 180 - rotation; + offset.x = -offset.x; + } + if (size.y < 0) + { + size.y = -size.y; + offset.y = -offset.y; + rotation = -rotation; + } + if (sprite.rotation != 0) + { + float angle = sprite.rotation * DEGREES_TO_RADIANS; + rotation += sprite.rotation; + offset = vector_make(std::cos(angle) * offset.x - std::sin(angle) * offset.y, + std::cos(angle) * offset.y + std::sin(angle) * offset.x); + } + outCapsule = Capsule(vector_add(offset, pos), size, rotation, 1); } // 007079c0 @@ -1262,12 +1297,6 @@ void Entity::RemoveWithPoof(Entity*) reconstruction_missing("Entity::RemoveWithPoof 007079c0"); } -// 0070c000 -void Entity::DestroyRockGridAt(const Vector&, GridEntityDesc*, Entity*, int) -{ - reconstruction_missing("Entity::DestroyRockGridAt 0070c000"); -} - // 0085e680 int Entity::IsVulnerableEnemy_lua(lua_State*) { diff --git a/src/entity.h b/src/entity.h index e469a30..dbada0b 100644 --- a/src/entity.h +++ b/src/entity.h @@ -60,6 +60,7 @@ enum EntityType : int ENTITY_GREED = 50, ENTITY_ENVY = 51, ENTITY_PRIDE = 52, + ENTITY_DOPLE = 53, ENTITY_FLAMING_HOPPER = 54, ENTITY_LEECH = 55, ENTITY_LUMP = 56, @@ -70,6 +71,9 @@ enum EntityType : int ENTITY_SUCKER = 61, ENTITY_PIN = 62, ENTITY_FAMINE = 63, + ENTITY_PESTILENCE = 64, + ENTITY_WAR = 65, + ENTITY_DEATH = 66, ENTITY_FISTULA_BIG = 71, ENTITY_FISTULA_MEDIUM = 72, ENTITY_FISTULA_SMALL = 73, @@ -86,6 +90,7 @@ enum EntityType : int ENTITY_KEEPER = 86, ENTITY_BUTTLICKER = 89, ENTITY_HANGER = 90, + ENTITY_SWARMER = 91, ENTITY_HEART = 92, ENTITY_MASK = 93, ENTITY_BIG_SPIDER = 94, @@ -114,6 +119,8 @@ enum EntityType : int ENTITY_SKINNY = 226, ENTITY_BONY = 227, ENTITY_HOMUNCULUS = 228, + ENTITY_TUMOR = 229, + ENTITY_CAMILLO_JR = 230, ENTITY_NERVE_ENDING = 231, ENTITY_GAPING_MAW = 235, ENTITY_BROKEN_GAPING_MAW = 236, @@ -126,10 +133,16 @@ enum EntityType : int ENTITY_CONJOINED_SPITTY = 243, ENTITY_ROUND_WORM = 244, ENTITY_POOP = 245, + ENTITY_RAGLING = 246, ENTITY_FLESH_MOBILE_HOST = 247, + ENTITY_BEGOTTEN = 251, + ENTITY_PSY_TUMOR = 253, + ENTITY_FLOATING_KNIGHT = 254, ENTITY_NIGHT_CRAWLER = 255, ENTITY_DART_FLY = 256, ENTITY_IMP = 259, + ENTITY_THE_HAUNT = 260, + ENTITY_DINGLE = 261, ENTITY_GATE = 263, ENTITY_MEGA_FATTY = 264, ENTITY_CAGE = 265, @@ -139,11 +152,13 @@ enum EntityType : int ENTITY_GABRIEL = 272, ENTITY_THE_LAMB = 273, ENTITY_MEGA_SATAN = 274, + ENTITY_MEGA_SATAN_2 = 275, ENTITY_ROUNDY = 276, ENTITY_BLACK_BONY = 277, ENTITY_BLACK_GLOBIN = 278, ENTITY_BLACK_GLOBIN_HEAD = 279, ENTITY_BLACK_GLOBIN_BODY = 280, + ENTITY_BONE_KNIGHT = 283, ENTITY_RED_GHOST = 285, ENTITY_FLESH_DEATHS_HEAD = 286, ENTITY_MOMS_DEAD_HAND = 287, @@ -160,8 +175,10 @@ enum EntityType : int ENTITY_BLISTER = 303, ENTITY_THE_THING = 304, ENTITY_PORTAL = 306, + ENTITY_LEPER = 310, ENTITY_STAIN = 401, ENTITY_BROWNIE = 402, + ENTITY_FORSAKEN = 403, ENTITY_LITTLE_HORN = 404, ENTITY_RAG_MAN = 405, ENTITY_ULTRA_GREED = 406, @@ -188,10 +205,13 @@ enum EntityType : int ENTITY_BLASTER = 821, ENTITY_QUAKEY = 823, ENTITY_GYRO = 824, + ENTITY_FIRE_WORM = 825, ENTITY_HARDY = 826, + ENTITY_MOLE = 829, ENTITY_BIG_BONY = 830, ENTITY_GUTTED_FATTY = 831, ENTITY_PEEPER_FATTY = 835, + ENTITY_PON = 840, ENTITY_SMALL_MAGGOT = 853, ENTITY_PUSTULE = 861, ENTITY_CYST = 862, @@ -334,6 +354,7 @@ enum DamageFlag : uint64_t DAMAGE_SPAWN_FLY = 1ull << 14, DAMAGE_POISON_BURN = 1ull << 15, DAMAGE_CURSED_DOOR = 1ull << 16, + DAMAGE_IV_BAG = 1ull << 18, DAMAGE_PITFALL = 1ull << 19, DAMAGE_CHEST = 1ull << 20, DAMAGE_BOOGER = 1ull << 22, diff --git a/src/entity_bomb.cpp b/src/entity_bomb.cpp index 8289b66..9970a57 100644 --- a/src/entity_bomb.cpp +++ b/src/entity_bomb.cpp @@ -93,7 +93,6 @@ constexpr size_t EXTENSION_SIZE = 4; constexpr size_t ANM2_EXTENSION_SIZE = 5; // The items and entities a bomb asks about (Lua's names). -constexpr int COLLECTIBLE_REMOTE_DETONATOR = 137; constexpr int TRINKET_BLASTING_CAP = 73; constexpr int PICKUP_BOMB = 40; constexpr int PICKUP_BOMBCHEST = 51; diff --git a/src/entity_collision.cpp b/src/entity_collision.cpp index 666c8a7..4491352 100644 --- a/src/entity_collision.cpp +++ b/src/entity_collision.cpp @@ -15,7 +15,6 @@ #include // What crushes rocks on contact: The Nail, Leo (worn or rolled by Zodiac), Thunder Thighs, Stompy and Mega Mush. -constexpr int COLLECTIBLE_LEO = 302; constexpr int COLLECTIBLE_THUNDER_THIGHS = 314; // A transformation counts once the player holds this many of its items. constexpr int PLAYER_FORM_ITEMS = 3; @@ -51,7 +50,6 @@ constexpr float HALF_CELL = GRID_CELL_SIZE / 2; // The enemies that bounce harder off walls, with the sounds some make. constexpr float REBOUND_GURDY_JR = 1.4f; constexpr float REBOUND_BOUNCER = 1.2f; -constexpr int SOUND_STONE_IMPACT = 487; constexpr int SOUND_BALL_AND_CHAIN_HIT = 581; constexpr float BOUNCE_VOLUME_SCALE = 0.05f; constexpr float BOUNCE_VOLUME_BASE = 0.2f; diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index a7b9ef8..b9fe239 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -29,8 +29,6 @@ constexpr float HALF_F = 0.5f; // The entities the combat code tells apart (Lua's EntityType). constexpr int ENTITY_SINS_FIRST = 46; constexpr int ENTITY_SINS_LAST = 52; -constexpr int ENTITY_SELFLESS_KNIGHT = 254; -constexpr int ENTITY_FLOATING_KNIGHT = 283; constexpr int ENTITY_IGNORED_BY_TEARS = 291; constexpr int ENTITY_REFLECTING_ENEMY = 822; constexpr int ENTITY_SHIELDED_SPAWN = 832; @@ -85,7 +83,6 @@ constexpr float FROZEN_SHARD_SPEED = 5; // The sounds the combat code plays (Lua's SoundEffect). constexpr int SOUND_DEATH_BURST_BONE = 27; -constexpr int SOUND_ROCKET_BLAST_DEATH = 141; constexpr int SOUND_GOODEATH = 207; constexpr int SOUND_BONE_BREAK = 500; constexpr int SOUND_BISHOP_HIT = 501; @@ -130,6 +127,12 @@ constexpr float VIRUS_DAMAGE = 12; constexpr float VIRUS_DAMAGE_VERSUS = 1; constexpr float BABY_CONTACT_DAMAGE = 10; constexpr float HORN_DAMAGE = 3.5f; +constexpr float RAM_DAMAGE = 20; +constexpr float RAM_FINISH_HEALTH = 40; +constexpr int MIDAS_CONTACT_FREEZE = 90; +constexpr int MIDAS_CONTACT_FREEZE_VERSUS = 45; +constexpr float MIDAS_CONTACT_DAMAGE = 3.5f; +constexpr float MIDAS_COIN_DAMAGE = 0.2f; constexpr float ARIES_DAMAGE = 25; constexpr float ARIES_DAMAGE_VERSUS = 10; constexpr float ARIES_SPEED = 4; @@ -836,8 +839,7 @@ static bool tear_damage_deal(Entity_Tear& tear, Entity& collider, bool& isHit) isHit = true; collider.TakeDamage(damage, damageFlags, EntityRef(&tear), TEAR_HIT_COUNTDOWN); - if (tear.tearFlags[TEAR_FETUS_FLAG] && !isObstacle) - reconstruction_missing("Entity_Tear::HandleCollision 00673660: a fetus tear's bounce and bomber"); + if (tear.tearFlags[TEAR_FETUS_FLAG] && !isObstacle) tear.fetus_hit(collider); if (collider.IsEnemy()) tear.isCanTriggerStreakEnd = false; return collider.IsEnemy() && (tear.tearFlags[TEAR_BOOGER_FLAG] || tear.tearFlags[TEAR_STICKY] || tear.tearFlags[TEAR_SPORE_FLAG]); } @@ -943,8 +945,7 @@ bool Entity_Tear::HandleCollision(Entity* collider, bool isLow) if (EntityList::HitListContains(hitList, *collider) && isPassing) return true; hit_list_insert(hitList, *collider); bool isSticking = tearFlags[TEAR_STICKY] || tearFlags[TEAR_BOOGER_FLAG] || tearFlags[TEAR_SPORE_FLAG]; - if (collider->IsActiveEnemy(DEAD_EXCLUDED) && isSticking) - reconstruction_missing("Entity_Tear::HandleCollision 00673660: a sticky tear sticking to an enemy"); + if (collider->IsActiveEnemy(DEAD_EXCLUDED) && isSticking && stick(*collider)) return true; if (!isExplosive) { @@ -969,7 +970,7 @@ bool Entity_Tear::HandleCollision(Entity* collider, bool isLow) else { apply_death_flag_effects(collider); - if (tearFlags[TEAR_BELIAL_FLAG]) reconstruction_missing("Entity_Tear::HandleCollision 00673660: Belial's homing"); + if (tearFlags[TEAR_BELIAL_FLAG]) belial_turn(); if (g_game->deathmatchManager.is_active() && collider->type == ENTITY_FAMILIAR) reconstruction_missing("Entity_Tear::HandleCollision 00673660: a versus familiar's block"); if (tear_flies_on(*this, *collider)) return true; @@ -1002,7 +1003,7 @@ static bool is_charger_hit_from_behind(Entity_NPC& npc, Vector hitVelocity) bool Entity_NPC::CanBeDamagedFromVelocity(Vector hitVelocity) { int facing = DIRECTION_DOWN; - if (type == ENTITY_KNIGHT || type == ENTITY_SELFLESS_KNIGHT || type == ENTITY_FLOATING_KNIGHT) + if (type == ENTITY_KNIGHT || type == ENTITY_FLOATING_KNIGHT || type == ENTITY_BONE_KNIGHT) { const std::string& animation = sprite.animState.GetAnimation(); if (animation == "Up") facing = DIRECTION_UP; @@ -1037,8 +1038,8 @@ void Entity_NPC::on_player_damaged() } } -// Part of 0078e1f0: the damage a player's touch deals: Mom's Heels, The Virus and Serpent's Kiss, Isaac's Heart's -// melee, the crow baby, Little Horn, Breath of Life, Aries at speed (which makes the player heavy and briefly unhurt), +// Part of 0078e1f0: the damage a player's touch deals: the ramming items (more against the weak), Mom's Heels, The +// Virus and Serpent's Kiss, Isaac's Heart's melee, Midas' Touch's gold freeze, the crow baby, Little Horn, Breath of Life, Aries at speed (which makes the player heavy and briefly unhurt), // Tooth and Nail, all tripled when thrown. Whether Breath of Life adds to it goes back through isBreath. static float player_contact_damage(Entity_Player& player, Entity& collider, bool& isBreath) { @@ -1052,7 +1053,8 @@ static float player_contact_damage(Entity_Player& player, Entity& collider, bool bool isRamming = effects.HasCollectibleEffect(COLLECTIBLE_MY_LITTLE_UNICORN) || effects.HasCollectibleEffect(COLLECTIBLE_GAMEKID) || effects.HasCollectibleEffect(COLLECTIBLE_THE_NAIL) || (taurus && taurus->cooldown != 0); - if (isRamming) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: the ramming items' contact damage"); + if (isRamming && isVersus) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: the versus ramming cooldown"); + if (isRamming) damage += collider.health <= RAM_FINISH_HEALTH ? RAM_DAMAGE + RAM_DAMAGE : RAM_DAMAGE; if (player.HasCollectible(COLLECTIBLE_MOMS_HEELS)) damage += isVersus ? HEELS_DAMAGE_VERSUS : HEELS_DAMAGE; if (player.HasCollectible(COLLECTIBLE_VIRUS)) damage += isVersus ? VIRUS_DAMAGE_VERSUS : VIRUS_DAMAGE; if (player.HasCollectible(COLLECTIBLE_SERPENTS_KISS)) damage += isVersus ? VIRUS_DAMAGE_VERSUS : VIRUS_DAMAGE; @@ -1061,7 +1063,10 @@ static float player_contact_damage(Entity_Player& player, Entity& collider, bool Entity_Player& heartOwner = player.playerType == PLAYER_THESOUL_B && twin ? *twin : player; if (heartOwner.HasCollectible(COLLECTIBLE_ISAACS_HEART)) damage = player.meleeDamage + player.meleeDamage + damage; if (player.HasCollectible(COLLECTIBLE_MIDAS_TOUCH)) - reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Midas' Touch (Entity::AddMidasFreeze)"); + { + collider.AddMidasFreeze(EntityRef(&player), isVersus ? MIDAS_CONTACT_FREEZE_VERSUS : MIDAS_CONTACT_FREEZE, false); + damage = (float)player.numCoins * MIDAS_COIN_DAMAGE + MIDAS_CONTACT_DAMAGE + damage; + } if (player.variant == PLAYER_VARIANT_COOP_BABY && player.babySkin == BABY_CROW) damage += BABY_CONTACT_DAMAGE; if (player.HasCollectible(COLLECTIBLE_LITTLE_HORN)) damage += HORN_DAMAGE; isBreath = effects.HasCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE); @@ -1092,15 +1097,12 @@ static void player_contact_missing_check(Entity_Player& player, Entity& collider tainted_magdalene_hug(player, collider); if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Mega Mush's stomp"); - if (player.playerType == PLAYER_THESOUL_B && collider.type == ENTITY_PLAYER && - static_cast(collider).playerType == PLAYER_THEFORGOTTEN_B) - reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: Tainted Soul holding her body"); if (player.suplexState == 1) reconstruction_missing("Entity_Player::HandleCollision 0078e1f0: the suplex grab"); } // 0078e1f0 Touches another entity, after a mod's MC_PRE_PLAYER_COLLISION: mid-suplex it passes enemies and shots, // it hurts a vulnerable enemy by its items' contact damage, poisons with The Virus or Serpent's Kiss, and a thrown -// Tainted Forgotten slows on enemies. Whether the collision is ignored, which a pony's dash makes it. +// Tainted Forgotten slows on enemies. Tainted Forgotten's soul picks the body up. Whether the collision is ignored, which a pony's dash makes it. bool Entity_Player::HandleCollision(Entity* collider, bool isLow) { LuaResult lua = lua_engine_get().PrePlayerCollide(this, collider, isLow); @@ -1108,6 +1110,15 @@ bool Entity_Player::HandleCollision(Entity* collider, bool isLow) if (lua == LUA_RESULT_FALSE) return false; player_contact_missing_check(*this, *collider); + if (playerType == PLAYER_THESOUL_B && collider->type == ENTITY_PLAYER && + static_cast(collider)->playerType == PLAYER_THEFORGOTTEN_B) + { + Room& room = *g_game->room; + if (collider->HasEntityFlags(FLAG_HELD | FLAG_THROWN) || !room.isInitialized || + g_game->frameCount - room.enterFrame < 2) + return true; + TryHoldEntity(collider); + } if (suplexState >= SUPLEX_STATE_PASSING && (collider->IsEnemy() || collider->type == ENTITY_PROJECTILE)) return true; bool isIgnored = false; diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index 7294701..7914bb7 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -4,6 +4,7 @@ #include "entity_list.h" #include "entity_player.h" #include "entity_player_forgotten.h" +#include "entity_player_passives.h" #include "game.h" #include "kage_graphics.h" #include "log.h" @@ -29,8 +30,6 @@ constexpr std::array CRAWLSPACE_HIDDEN_EFFECTS = {7, 18, 22, 23, 24, 2 constexpr std::array WAVE_CHAIN_CREEPS = {53, 44, 46, 45, 32, 204}; constexpr int FAMILIAR_CREEP_WAVE = 125; -constexpr int EFFECT_HUSH_LASER = 96; -constexpr int EFFECT_HUSH_LASER_UP = 101; constexpr int EFFECT_BLACK_POWDER = 92; constexpr int EFFECT_BOOMERANG = 60; constexpr int EFFECT_TIMER = 119; @@ -101,7 +100,8 @@ static const EffectBehaviour* behaviour_find(int variant) for (auto group : {ambient_effect_behaviours(), hazard_effect_behaviours(), floor_effect_behaviours(), beam_effect_behaviours(), player_effect_behaviours(), mines_effect_behaviours(), trail_effect_behaviours(), spike_effect_behaviours(), boss_effect_behaviours(), - weapon_effect_behaviours(), std::span(TIMER_BEHAVIOURS)}) + weapon_effect_behaviours(), passive_effect_behaviours(), alt_effect_behaviours(), + std::span(TIMER_BEHAVIOURS)}) for (const EffectBehaviour& behaviour : group) table[behaviour.variant] = behaviour; return table; }(); diff --git a/src/entity_effect.h b/src/entity_effect.h index 87c7095..a60ad38 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -56,6 +56,12 @@ enum EffectVariant : int EFFECT_POOF02 = 16, EFFECT_BOMB_CRATER = 18, EFFECT_CRACK_THE_SKY = 19, + EFFECT_SCYTHE_BREAK = 20, + EFFECT_DIAMOND_PARTICLE = 85, + EFFECT_NAIL_PARTICLE = 86, + EFFECT_IMPACT = 97, + EFFECT_COIN_PARTICLE = 98, + EFFECT_URN_OF_SOULS = 178, EFFECT_TINY_BUG = 21, EFFECT_CREEP_RED = 22, EFFECT_CREEP_GREEN = 23, @@ -63,6 +69,7 @@ enum EffectVariant : int EFFECT_CREEP_WHITE = 25, EFFECT_CREEP_BLACK = 26, EFFECT_WOOD_PARTICLE = 27, + EFFECT_MOM_FOOT_STOMP = 29, EFFECT_TARGET = 30, EFFECT_ROCKET = 31, EFFECT_PLAYER_CREEP_LEMON_MISHAP = 32, @@ -77,6 +84,7 @@ enum EffectVariant : int EFFECT_PLAYER_CREEP_WHITE = 44, EFFECT_PLAYER_CREEP_BLACK = 45, EFFECT_PLAYER_CREEP_RED = 46, + EFFECT_TRINITY_SHIELD = 47, EFFECT_HEART = 49, EFFECT_LASER_IMPACT = 50, EFFECT_HOT_BOMB_FIRE = 51, @@ -109,10 +117,14 @@ enum EffectVariant : int EFFECT_FALLING_EMBER = 87, EFFECT_DARK_BALL_SMOKE_PARTICLE = 88, EFFECT_PLAYER_CREEP_PUDDLE_MILK = 90, + EFFECT_MOMS_HAND_CONTACT = 91, EFFECT_PLAYER_CREEP_BLACKPOWDER = 92, EFFECT_PENTAGRAM_BLACKPOWDER = 93, EFFECT_CREEP_SLIPPERY_BROWN = 94, + EFFECT_HUSH_LASER = 96, EFFECT_WATER_SPLASH = 99, + EFFECT_HUSH_LASER_UP = 101, + EFFECT_BULLET_POOF_HUSH = 102, EFFECT_FIREWORKS = 104, EFFECT_ENEMY_BRIMSTONE_SWIRL = 110, EFFECT_HAEMO_TRAIL = 111, @@ -136,6 +148,7 @@ enum EffectVariant : int EFFECT_RAIN_DROP = 135, EFFECT_GRID_ENTITY_PROJECTILE_HELPER = 136, EFFECT_MIST = 138, + EFFECT_WILLO_SPAWNER = 157, EFFECT_MINES_TRAPDOOR_COVER = 139, EFFECT_BACKDROP_DECORATION = 140, EFFECT_SMOKE_CLOUD = 141, @@ -159,10 +172,15 @@ enum EffectVariant : int EFFECT_RIFT = 180, EFFECT_PURGATORY = 189, EFFECT_ANIMA_CHAIN = 193, + EFFECT_CREEP_LIQUID_POOP = 195, EFFECT_GENERIC_TRACER = 198, EFFECT_PLAYER_CREEP_YELLOW = 204, EFFECT_MAMA_MEGA_EXPLOSION = 127, - EFFECT_CHAIN_GIB = 163 + EFFECT_CHAIN_GIB = 163, + EFFECT_BIG_ROCK_EXPLOSION = 149, + EFFECT_BIG_CRACKWAVE = 150, + EFFECT_BIG_ATTRACT = 151, + EFFECT_FIRE_WAVE = 148 }; // Construction and destruction (005cd9f0, 005cd960) are the defaults, the extra data shared with its other holders. @@ -232,6 +250,7 @@ std::span floor_effect_behaviours(); std::span beam_effect_behaviours(); std::span spike_effect_behaviours(); std::span boss_effect_behaviours(); +std::span alt_effect_behaviours(); // The frame the plain poofs share: the sprite turned by the effect's rotation (mirrored unless flipped), the effect // gone once its animation ends. diff --git a/src/entity_effect_alt.cpp b/src/entity_effect_alt.cpp new file mode 100644 index 0000000..4298c56 --- /dev/null +++ b/src/entity_effect_alt.cpp @@ -0,0 +1,358 @@ +#include "entity_effect.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect_combat.h" +#include "entity_factory.h" +#include "entity_familiar.h" +#include "game.h" +#include "grid_entity.h" +#include "manager.h" +#include "npc_alt.h" +#include "room.h" +#include "room_descriptor.h" +#include +#include + +// The alt path's effects: the mist drifting through Downpour and Min-Min's rooms, the Great Gideon's crackwave of +// rocks and pits and its explosions, the rings and trails its pull and the Beast's cries leave, and the pentagram a +// wave enemy rises from. Entity_Effect's Init and Update hand these variants here. + +// The mist fades out over 300 past either side of the room and is gone 600 past it. +constexpr float MIST_FADE_REACH = 300; +constexpr float MIST_GONE_REACH = 600; +constexpr int MIST_RENDER_Z = INT32_MIN; + +// 005cdb20 (Init's case 138) The mist draws under everything, blended additively. +static void mist_init(Entity_Effect& mist) +{ + mist.renderZOffset = MIST_RENDER_Z; + layer_additive_set(*mist.sprite.GetLayer(0)); +} + +// 005d668e (Update's case 138) The mist fades out past the room's sides and goes once far beyond the side it drifts to. +static void mist_update(Entity_Effect& mist) +{ + Room& room = *g_game->room; + float left = room.topLeftPos.x - MIST_FADE_REACH; + float right = room.bottomRightPos.x + MIST_FADE_REACH; + float& alpha = mist.sprite.color._tint[3]; + + if (mist.pos.x > right) alpha = std::max(1 - (mist.pos.x - right) / MIST_FADE_REACH, 0.0f); + else if (mist.pos.x >= left) alpha = 1; + else alpha = std::max(1 - (left - mist.pos.x) / MIST_FADE_REACH, 0.0f); + + bool isGoneLeft = mist.velocity.x < 0 && mist.pos.x < room.topLeftPos.x - MIST_GONE_REACH; + bool isGoneRight = mist.velocity.x > 0 && mist.pos.x > room.bottomRightPos.x + MIST_GONE_REACH; + if (isGoneLeft || isGoneRight) mist.Remove(); +} + +// A rock explosion's burst of rock particles. +constexpr int ROCK_BURST_COUNT = 4; +constexpr float ROCK_BURST_SPEED = 5; + +// 005d949a (Update's case 149) The big rock explosion bursts into rock particles once its animation ends. +static void big_rock_explosion_update(Entity_Effect& explosion) +{ + if (!explosion.sprite.IsFinished()) return; + + game_particles_spawn({.position = explosion.pos, + .speed = ROCK_BURST_SPEED, + .count = ROCK_BURST_COUNT, + .variant = EFFECT_ROCK_PARTICLE}); + explosion.Remove(); +} + +// The big crackwave steps 30 every 3rd frame along its rotation, swaying up to 30 degrees each way after its 6th +// frame. Two steps in three open a pit with rock particles about it, and each one blows up the ground, its shake +// easing from 13 to 4. +constexpr int CRACKWAVE_STEP_FRAMES = 3; +constexpr int CRACKWAVE_STRAIGHT_FRAMES = 6; +constexpr float CRACKWAVE_SWAY = 30; +constexpr float BIG_CRACKWAVE_STEP = 30; +constexpr int CRACKWAVE_PIT_ODDS = 3; +constexpr int CRACKWAVE_SHAKE_START = 13; +constexpr int CRACKWAVE_SHAKE_MIN = 4; +constexpr float CRACKWAVE_PARTICLE_SPREAD = 12; +constexpr float CRACKWAVE_PARTICLE_SPEED = 5; +constexpr float CRACKWAVE_DAMAGE = 10; +constexpr float CRACKWAVE_RADIUS = 30; +constexpr float CRACKWAVE_VOLUME = 0.4f; + +// Opens a pit where the crackwave stepped, fixing up the pits about it, with rock particles flying off. +static void crackwave_pit_open(Room& room, int gridIndex, const Vector& at) +{ + int column = gridIndex % room.gridWidth; + int row = gridIndex / room.gridWidth; + room.SpawnGridEntity(gridIndex, GRID_PIT, 0, Random(), 0); + for (int dx = -1; dx < 2; dx++) + for (int dy = -1; dy < 2; dy++) + { + int neighbour = room.GetGridIndexByTile(column + dx, row + dy); + GridEntity* grid = neighbour < 0 ? nullptr : room.GetGridEntity(neighbour); + if (grid && grid->type == GRID_PIT) grid->PostInit(); + } + + for (int i = 0; i < ROCK_BURST_COUNT; i++) + { + Vector direction = vector_from_angle(random_unit() * DEGREES_PER_TURN); + Vector from = vector_add(at, vector_scale(direction, random_unit() * CRACKWAVE_PARTICLE_SPREAD)); + g_game->Spawn({.position = from, + .velocity = vector_scale(direction, CRACKWAVE_PARTICLE_SPEED), + .type = ENTITY_EFFECT, + .variant = EFFECT_ROCK_PARTICLE, + .seed = Random()}) + ->Update(); + } +} + +// 005d952a (Update's case 150) Every 3rd frame the big crackwave steps on (from where it started), breaking what it +// lands on and opening a pit two times in three (on any free cell, or where it broke something), then blows up the +// ground there. Out of the room it is gone. +static void big_crackwave_update(Entity_Effect& wave) +{ + if (wave.FrameCount() % CRACKWAVE_STEP_FRAMES != 0) return; + + Room& room = *g_game->room; + if (vector_is_zero(wave.targetPosition)) wave.targetPosition = wave.pos; + float sway = wave.dropRNG.RandomFloat() * 2 * CRACKWAVE_SWAY - CRACKWAVE_SWAY; + if (wave.FrameCount() < CRACKWAVE_STRAIGHT_FRAMES) sway = 0; + bool isPitRolled = wave.dropRNG.RandomInt(CRACKWAVE_PIT_ODDS) != 0; + wave.targetPosition = + vector_add(wave.targetPosition, vector_scale(vector_from_angle(wave.rotation + sway), BIG_CRACKWAVE_STEP)); + + int gridIndex = room.GetGridIndex(wave.targetPosition); + GridEntity* grid = gridIndex < 0 ? nullptr : room.GetGridEntity(gridIndex); + int shake = std::max(CRACKWAVE_SHAKE_START - wave.FrameCount() / 2, CRACKWAVE_SHAKE_MIN); + if (!room.IsPositionInRoom(wave.targetPosition, 0)) wave.Remove(); + else + { + bool isSolid = grid && grid->collisionClass > COLLISION_NONE; + if (!grid || grid->Destroy(true, EntityRef(&wave))) + { + bool isPit = isPitRolled && (isSolid || room.CanSpawnObstacleAtPosition(gridIndex, false)); + if (isPit) crackwave_pit_open(room, gridIndex, wave.targetPosition); + } + + g_game->Spawn({.position = wave.targetPosition, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_ROCK_EXPLOSION, + .seed = Random()}); + explosion_damage({.position = wave.targetPosition, + .source = wave.spawnerEntity, + .damage = CRACKWAVE_DAMAGE, + .radius = CRACKWAVE_RADIUS, + .isLineCheck = false}); + game_shake_screen(shake); + } + npc_sound_play(SOUND_ROCK_CRUMBLE, CRACKWAVE_VOLUME, 2, 1); +} + +// The rings and trails: the pull's (subtype 0, 1) shrink away by 0.04 or 0.1 a frame, a ring drawn up to its target +// faster as it ages. The cries' (10, 11) swell over their lifespan from 0.01 and fade as they do. +constexpr int ATTRACT_RING = 0; +constexpr int SHOCKWAVE_RING = 10; +constexpr int SHOCKWAVE_TRAIL = 11; +constexpr float RING_SPIN_MIN = 5; +constexpr float RING_SPIN_RANGE = 30; +constexpr float RING_SIZE = 100; +constexpr float RING_SIZE_MIN = 1.2f; +constexpr float RING_SIZE_RANGE = 0.4f; +constexpr float TRAIL_SIZE = 20; +constexpr float BEAST_TRAIL_TILT_MIN = 140; +constexpr float BEAST_TRAIL_TILT_RANGE = 80; +constexpr float RING_DEPTH = 1000; +constexpr float RING_SHRINK = 0.04f; +constexpr float TRAIL_SHRINK = 0.1f; +constexpr float RING_PULL_RATE = 0.01f; +constexpr float RING_ALPHA = 0.15f; +constexpr float TRAIL_ALPHA = 0.4f; +constexpr float TRAIL_HEIGHT = 0.4f; +constexpr float SHOCKWAVE_START = 0.01f; +constexpr float SHOCKWAVE_TRAIL_LENGTH = 30; +constexpr float SHOCKWAVE_TRAIL_STRETCH = 2; +constexpr float SHOCKWAVE_TRAIL_BASE = 0.6f; +constexpr float SHOCKWAVE_TRAIL_THINNING = 1.6f; + +// 005cdb20 (Init's case 151) A ring or trail turns a random 5 to 35 degrees a frame, the pull's ring 1.2 to 1.6 big and +// its trail (the Beast's tilted down) 20, the cries' 100, the ring on the shockwave sheet. +static void attract_init(Entity_Effect& ring) +{ + ring.rotation = random_unit() * RING_SPIN_RANGE + RING_SPIN_MIN; + ring.scale = 1; + if (ring.subtype == SHOCKWAVE_TRAIL) + { + ring.sprite.rotation = random_unit() * DEGREES_PER_TURN; + ring.maxRadius = RING_SIZE; + } + else if (ring.subtype == SHOCKWAVE_RING) + { + ring.maxRadius = RING_SIZE; + ring.sprite.ReplaceSpritesheet(0, "gfx/effects/shockwave.png"); + } + else if (ring.subtype == ATTRACT_RING) ring.maxRadius = random_unit() * RING_SIZE_RANGE + RING_SIZE_MIN; + else + { + ring.sprite.rotation = random_unit() * DEGREES_PER_TURN; + ring.maxRadius = TRAIL_SIZE; + if (ring.spawnerType == ENTITY_BEAST) + ring.sprite.rotation = random_unit() * BEAST_TRAIL_TILT_RANGE + BEAST_TRAIL_TILT_MIN; + } +} + +// 005d9ba9 (Update's case 151) Drawn on top of the room, a ring or trail shrinks or swells, spinning and fading, until +// it is gone. +static EffectUpdateEnd attract_update(Entity_Effect& ring) +{ + ring.renderDepthOffset = RING_DEPTH; + float& alpha = ring.sprite.color._tint[3]; + if (ring.subtype < SHOCKWAVE_RING) + { + ring.scale -= ring.subtype == ATTRACT_RING ? RING_SHRINK : TRAIL_SHRINK; + if (ring.scale <= 0) + { + ring.Remove(); + return EFFECT_UPDATE_RETURN; + } + + float faded = std::clamp((1 - ring.scale) * (1 - ring.scale), 0.0f, 1.0f); + if (ring.subtype != ATTRACT_RING) + { + ring.sprite.scale = vector_make(std::sqrt(ring.scale) * ring.maxRadius, TRAIL_HEIGHT); + alpha = faded * TRAIL_ALPHA; + return EFFECT_UPDATE_FINISH; + } + + if (!vector_is_zero(ring.targetPosition)) + ring.velocity = vector_scale(vector_sub(ring.targetPosition, ring.pos), + std::min(ring.updateTime * RING_PULL_RATE, 1.0f)); + ring.sprite.rotation = angle_wrap(ring.sprite.rotation + ring.rotation); + ring.sprite.scale = vector_make(ring.scale * ring.maxRadius, ring.scale * ring.maxRadius); + alpha = faded * RING_ALPHA; + return EFFECT_UPDATE_FINISH; + } + + float progress = lerp_clamped(ring.updateTime, 0, (float)ring.lifespan, SHOCKWAVE_START, 1); + ring.scale = 1 - (progress - 1) * (progress - 1); + if (progress >= 1) + { + ring.Remove(); + return EFFECT_UPDATE_RETURN; + } + + if (ring.subtype == SHOCKWAVE_TRAIL) + { + ring.sprite.GetLayer(0)->pos.x = ring.maxRadius * ring.scale; + ring.sprite.scale = vector_make((ring.scale * SHOCKWAVE_TRAIL_STRETCH + SHOCKWAVE_TRAIL_BASE) * ring.maxRadius / + SHOCKWAVE_TRAIL_LENGTH, + SHOCKWAVE_TRAIL_STRETCH - ring.scale * SHOCKWAVE_TRAIL_THINNING); + } + else + { + ring.sprite.rotation = angle_wrap(ring.sprite.rotation + ring.rotation); + float size = ring.scale * ring.maxRadius / RING_SIZE; + ring.sprite.scale = vector_make(size, size); + } + alpha = (1 - ring.scale) * ring.color._tint[3]; + return EFFECT_UPDATE_FINISH; +} + +// What a spawn pentagram brings up: the spawn and the grid index the entity is given. +struct PentagramSpawn : Entity_Effect::ExtraData +{ + EntitySpawn spawn; + int gridIndex = -1; +}; + +// The pentagram is sized after what it brings up, a 16th of its collision radius, between 0.8 and 2. +constexpr float PENTAGRAM_SCALE_PER_RADIUS = 0.0625f; +constexpr float PENTAGRAM_SCALE_MIN = 0.8f; +constexpr float PENTAGRAM_SCALE_MAX = 2; + +// 006fec30 spawn_enemy_spawner_effect: a spawn pentagram where an entity is to rise, overwriting a pooled entity when +// full. +Entity_Effect* pentagram_spawn(const EntitySpawn& spawn, int gridIndex) +{ + auto* pentagram = static_cast(g_game->Spawn( + {.position = spawn.position, .type = ENTITY_EFFECT, .variant = EFFECT_SPAWN_PENTAGRAM, .seed = Random()})); + auto data = std::make_shared(); + data->spawn = spawn; + data->spawn.velocity = {}; + data->gridIndex = gridIndex; + pentagram->extraData = data; + return pentagram; +} + +// 005cdb20 (Init's case 203) The pentagram plays its summoning and holds the room's doors. +static void pentagram_init(Entity_Effect& pentagram) +{ + pentagram.sprite.Play("Summon"); + g_game->room->SetClear(false); +} + +// 005d4210 (Update's case 203) Sized to what it brings up, the pentagram spawns it (an enemy with the wave's sound, and +// with the ambush flag it carries) once its animation stops, and keeps the room uncleared. +static void pentagram_update(Entity_Effect& pentagram) +{ + auto* data = dynamic_cast(pentagram.extraData.get()); + if (!data) return pentagram.Remove(); + + const EntitySpawn& spawn = data->spawn; + if (EntityConfig_Entity* config = g_manager->entityConfig.GetEntity(spawn.type, spawn.variant, spawn.subType)) + { + float size = std::clamp(config->collisionRadius * PENTAGRAM_SCALE_PER_RADIUS, PENTAGRAM_SCALE_MIN, + PENTAGRAM_SCALE_MAX); + pentagram.sprite.scale = vector_make(size, size); + } + if (!pentagram.sprite.IsPlaying()) + { + Entity* entity = game_spawn(spawn, POOL_OVERWRITE); + entity->spawnGridIndex = data->gridIndex; + if (auto* npc = dynamic_cast(entity)) npc->isDeathSoundAlt = true; + if (pentagram.HasEntityFlags(FLAG_AMBUSH)) entity->AddEntityFlags(FLAG_AMBUSH); + pentagram.Remove(); + } + g_game->room->descriptor->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; +} + +// A woken spawner's Willo circles 80 out. +constexpr float WILLO_SPAWNER_RING = 80; + +// 005cdb20 (Init's case 157) The spawner appears. +static void willo_spawner_init(Entity_Effect& spawner) +{ + spawner.sprite.Play("Appear"); +} + +// 005daa46 (Update's case 157) Waiting it idles once it has appeared. Woken, it sends up an attacking Willo for its +// Min-Min and goes. +static void willo_spawner_update(Entity_Effect& spawner) +{ + if (spawner.state == SPAWNER_WAITING) + { + if (spawner.sprite.IsFinished()) spawner.sprite.Play("Idle"); + return; + } + spawner.sprite.Play("Spawn"); + if (spawner.sprite.IsEventTriggered("Spawn")) willo_spawn(spawner.pos, spawner.parent.get(), WILLO_SPAWNER_RING, 1); + if (spawner.sprite.IsFinished()) spawner.Remove(); +} + +// Invisible, the big crackwave is only its steps. +static void big_crackwave_init(Entity_Effect& wave) +{ + wave.isVisible = false; +} + +constexpr EffectBehaviour ALT_BEHAVIOURS[] = { + {EFFECT_MIST, mist_init, effect_finishing, nullptr}, + {EFFECT_BIG_ROCK_EXPLOSION, nullptr, effect_finishing, nullptr}, + {EFFECT_BIG_CRACKWAVE, big_crackwave_init, effect_finishing, nullptr}, + {EFFECT_BIG_ATTRACT, attract_init, attract_update, nullptr}, + {EFFECT_WILLO_SPAWNER, willo_spawner_init, effect_finishing, nullptr}, + {EFFECT_SPAWN_PENTAGRAM, pentagram_init, effect_finishing, nullptr}, +}; + +std::span alt_effect_behaviours() +{ + return ALT_BEHAVIOURS; +} diff --git a/src/entity_effect_boss.cpp b/src/entity_effect_boss.cpp index ce33b60..afadf01 100644 --- a/src/entity_effect_boss.cpp +++ b/src/entity_effect_boss.cpp @@ -1,6 +1,8 @@ #include "entity_effect.h" +#include "entity_player.h" #include "game.h" -#include "npc_ai.h" +#include "npc_caves.h" +#include "room.h" #include "room_grid.h" #include "sfx_manager.h" @@ -122,9 +124,125 @@ static void flame_update(Entity_Effect& flame) if (flame.isDead) flame.Remove(); } +// Hush's lasers: the one hunting his target (96) every 10 frames aims 40 to one side of where its target will be in 5, +// pushing on at the room's speed (plus 1.1 of a player target's speed) under friction 0.8. Every 2 frames it hurts +// players (or, fired by a charmed or friendly Hush, enemies) for 2, and every 5 it leaves blue creep. +constexpr int HUSH_LASER_RETARGET = 10; +constexpr float HUSH_LASER_LEAD = 5; +constexpr float HUSH_LASER_SIDE = 40; +constexpr float HUSH_LASER_PLAYER_PULL = 1.1f; +constexpr float HUSH_LASER_FRICTION = 0.8f; +constexpr int HUSH_LASER_HIT_SPACING = 2; +constexpr float HUSH_LASER_DAMAGE = 2; +constexpr int HUSH_LASER_HIT_COUNTDOWN = 30; +constexpr int HUSH_LASER_TRAIL_SPACING = 5; +constexpr int HUSH_LASER_TRAIL_PRIORITY = 255; +constexpr ColorMod HUSH_LASER_TRAIL_COLOR = {{0, 0, 0, 0.8f}, {0, 0, 0, 0}, {17 / 255.0f, 159 / 255.0f, 225 / 255.0f}}; + +// The life Hush's lasers share: they die with their parent, show "Start", then "Loop" until their timeout (counted +// here as well as by Update) runs out or they die, then "End" and are gone. +static void hush_laser_cycle(Entity_Effect& laser) +{ + if (laser.sprite.IsFinished("Start")) laser.sprite.Play("Loop"); + if (laser.timeout > 0) laser.timeout--; + if (laser.sprite.IsPlaying("Loop") && (laser.timeout == 0 || laser.isDead)) laser.sprite.Play("End"); + if (laser.sprite.IsFinished("End")) laser.Remove(); +} + +// Hurts the players, or the enemies for a laser fired by a charmed or friendly Hush, that touch it. +static void hush_laser_hit(Entity_Effect& laser) +{ + Entity* source = laser.parent ? laser.parent.get() : &laser; + bool isFriendly = laser.parent && laser.parent->HasEntityFlags(FLAG_CHARM | FLAG_FRIENDLY); + auto hit = [&](Entity& victim) { + float reach = victim.size + laser.size; + + if (vector_length_squared(vector_sub(victim.pos, laser.pos)) >= reach * reach) return; + if (victim.isDead || victim.entityCollisionClass == ENTCOLL_NONE) return; + victim.TakeDamage(HUSH_LASER_DAMAGE, 0, EntityRef(source), HUSH_LASER_HIT_COUNTDOWN); + }; + + if (isFriendly) + { + std::vector& entities = g_game->room->GetEntities()->updateEL; + + for (size_t i = 0; i < entities.size(); i++) + if (entities[i]->IsEnemy()) hit(*entities[i]); + return; + } + for (size_t i = 0; i < g_game->playerManager.playerList.size(); i++) hit(*g_game->GetPlayer((int)i)); +} + +// 005ea523 (Update's case 96) The laser hunting Hush's target. +static void hush_laser_update(Entity_Effect& laser) +{ + if (laser.parent && laser.parent->isDead) laser.Kill(EntityRef()); + if (!laser.target) + { + if (laser.parent && laser.parent->IsEnemy()) + laser.target = static_cast(laser.parent.get())->GetPlayerTarget(); + else laser.target = game_nearest_player(laser.pos); + } + + Entity& target = *laser.target; + + if (laser.state == 0) + { + laser.sprite.Play("Start"); + laser.targetPosition = target.pos; + laser.velocity = vector_normalized(vector_sub(laser.targetPosition, laser.pos)); + laser.state++; + } + hush_laser_cycle(laser); + + if (laser.IsFrame(HUSH_LASER_RETARGET, 0)) + { + Vector lead = vector_add(target.pos, vector_scale(target.velocity, HUSH_LASER_LEAD)); + Vector toward = vector_normalized(vector_sub(lead, laser.pos)); + Vector side = laser.index % 2 == 0 ? vector_make(toward.y, -toward.x) : vector_make(-toward.y, toward.x); + + laser.targetPosition = vector_add(lead, vector_scale(side, HUSH_LASER_SIDE)); + } + + Vector toward = vector_normalized(vector_sub(laser.targetPosition, laser.pos)); + + laser.velocity = vector_add(laser.velocity, vector_scale(toward, laser.speedMultiplier)); + if (target.is_player()) + { + auto& player = static_cast(target); + Vector pull = vector_scale(vector_scale(toward, HUSH_LASER_PLAYER_PULL), player.moveSpeed); + + laser.velocity = vector_add(laser.velocity, vector_scale(pull, player.speedMultiplier)); + } + laser.velocity = vector_scale(laser.velocity, npc_friction_scaled(HUSH_LASER_FRICTION, laser.speedMultiplier)); + if (laser.IsFrame(HUSH_LASER_HIT_SPACING, (int)laser.index)) hush_laser_hit(laser); + if (!laser.IsFrame(HUSH_LASER_TRAIL_SPACING, (int)laser.index)) return; + + Entity* trail = g_game->Spawn({.position = laser.pos, .spawner = laser.parent.get(), .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_SLIPPERY_BROWN, .seed = Random()}); + trail->Update(); + trail->SetColor(HUSH_LASER_TRAIL_COLOR, -1, HUSH_LASER_TRAIL_PRIORITY, false, true); +} + +// 005ea366 (Update's case 101) One of Hush's eye beams. +static void hush_beam_update(Entity_Effect& beam) +{ + if (beam.parent && beam.parent->isDead) beam.Kill(EntityRef()); + if (beam.state == 0) + { + beam.sprite.Play("Start"); + beam.state++; + } + hush_laser_cycle(beam); +} + +// Hush's lasers and the poof of his shots have no Init case of their own. constexpr auto BOSS_EFFECT_BEHAVIOURS = std::to_array({ {EFFECT_BLUE_FLAME, flame_init, effect_finishing, nullptr}, {EFFECT_CRACK_THE_SKY, crack_init, effect_finishing, nullptr}, + {EFFECT_HUSH_LASER, nullptr, effect_finishing, nullptr}, + {EFFECT_HUSH_LASER_UP, nullptr, effect_finishing, nullptr}, + {EFFECT_BULLET_POOF_HUSH, nullptr, effect_poof_update, nullptr}, }); std::span boss_effect_behaviours() diff --git a/src/entity_effect_hazard.cpp b/src/entity_effect_hazard.cpp index be70145..0bda7a3 100644 --- a/src/entity_effect_hazard.cpp +++ b/src/entity_effect_hazard.cpp @@ -1,5 +1,6 @@ #include "entity_bomb.h" #include "entity_effect.h" +#include "boss_ai.h" #include "entity_player.h" #include "entity_projectile.h" #include "game.h" @@ -59,6 +60,10 @@ constexpr int CRACKWAVE_BEAST = 10; constexpr int CRACKWAVE_FRAMES = 240; constexpr int CRACKWAVE_PERIOD = 2; constexpr int CRACKWAVE_BEAST_PERIOD = 4; +// The Beast's crackwave hurts 35 (players 1) within 38 of each step, both sides alike. +constexpr float CRACKWAVE_BEAST_DAMAGE = 35; +constexpr float CRACKWAVE_BEAST_STRONG = 50; +constexpr float CRACKWAVE_BEAST_RADIUS = 38; constexpr float CRACKWAVE_STEP = 30; constexpr float CRACKWAVE_BEAST_STEP = 60; constexpr float CRACKWAVE_WOBBLE_SPAN = 150; @@ -324,7 +329,12 @@ static void crackwave_step(Entity_Effect& wave, int frame) rock->sprite.scale = wave.sprite.scale; } if (isBeast) - reconstruction_missing("Entity_Effect::Update 005d4380: the Beast's crackwave damage (Game::DamageRadius)"); + damage_radius({.position = wave.targetPosition, + .source = wave.spawnerEntity, + .damage = CRACKWAVE_BEAST_DAMAGE, + .playerDamageThreshold = CRACKWAVE_BEAST_STRONG, + .radius = CRACKWAVE_BEAST_RADIUS, + .isHitAll = true}); if (wave.HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS) && random_below(CRACKWAVE_ROCK_ODDS) == 0) crackwave_rocks_throw(wave); diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index def6174..d2e0f38 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -35,9 +35,8 @@ constexpr std::pair ORBIT_LAYERS[] = { {121, 5}, {128, 5}, {84, 4}, {123, 4}, {204, 6}, {216, 6}, {217, 6}, {229, 10}, {237, 8}}; // The familiars whose setup, drawing and links wait for their takeovers. -constexpr int UNWRITTEN_INIT_VARIANTS[] = {48, 62, 121, 122, 128, 131, 206, 228, 231, - 233, 234, 236, 237, 238, 239, 240}; -constexpr int UNWRITTEN_RENDER_VARIANTS[] = {48, 68, 75, 78, 79, 231, 237, 240, 243}; +constexpr int UNWRITTEN_INIT_VARIANTS[] = {48, 62, 121, 122, 128, 131, 228, 231, 233, 234, 236, 238, 239, 240}; +constexpr int UNWRITTEN_RENDER_VARIANTS[] = {48, 68, 75, 78, 79, 231, 240, 243}; // The familiars that walk, Init's grid collision for them, and the ones whose hit list survives the reset. constexpr int GROUND_VARIANTS[] = {46, 47, 71, 72, 48, 56, 73}; @@ -372,7 +371,11 @@ void Entity_Familiar::Init(int initType, int initVariant, int initSubtype, uint3 { for (auto [orbitVariant, layer] : ORBIT_LAYERS) if (orbitVariant == initVariant) orbitLayer = layer; - if (initVariant == WISP) reconstruction_missing("Entity_Familiar::Init 0060de70 (a wisp's orbit layer)"); + if (initVariant == WISP) + { + int ring = ItemConfig::wisp_config_get(subtype)->layer; + orbitLayer = ring < 0 ? -1 : ring + WISP_RING_FIRST_LAYER; + } if (isSubtype55555) orbitLayer = -1; else if (orbitLayer >= 0 && isExists) { @@ -405,6 +408,8 @@ void Entity_Familiar::variant_init(int initSubtype) switch (variant) { case FORGOTTEN_BODY: forgotten_body_init(*this); break; + case WISP: + case ITEM_WISP: WispInit(); break; case BLUE_FLY: collisionDamage = player->meleeDamage + player->meleeDamage; if (initSubtype >= 1 && initSubtype <= 5) sprite.Play(LOCUST_ANIMS[initSubtype]); @@ -737,6 +742,9 @@ void Entity_Familiar::variant_update() return; case BLUE_FLY: return ai_blue_fly(); case FORGOTTEN_BODY: return forgotten_body_update(*this); + case WISP: + case ITEM_WISP: return ai_wisp(); + case KEY_FULL: return ai_key_full(); default: reconstruction_missing("Entity_Familiar::Update 0061da10 (this familiar's behaviour)"); } } @@ -825,7 +833,7 @@ void Entity_Familiar::Interpolate() } // 00624e10 Draws a familiar with its charge bar. The familiars drawn their own way (Isaac's body, Samson's chains, the -// locusts, item wisps, the co-op babies) and Tainted Lazarus's hologram stop the game. +// locusts, the co-op babies) and Tainted Lazarus's hologram stop the game. An item wisp shows its item's icon. void Entity_Familiar::Render(const Vector& offset) { if (IsLilithBirthrightIncubus()) @@ -840,6 +848,7 @@ void Entity_Familiar::Render(const Vector& offset) ColorMod saved = sprite.color; Entity::Render(offset); + if (variant == ITEM_WISP) item_wisp_icon_render(*this); lua_engine_get().PostFamiliarRender(this, offset); render_charge_indicator(renderPosition); sprite.color = saved; @@ -931,12 +940,17 @@ void Entity_Familiar::Remove() ResolveOrbitConflict(); } -// 006121d0 Drops its links and its weapon. The Forgotten's body, the wisps and Gello's cord stop the game. +// 006121d0 Drops its links and its weapon. A Fortune Cookie wisp takes its luck back. Gello's cord stops the game. void Entity_Familiar::ClearReferences() { 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)"); + if (variant == UMBILICAL_BABY) + reconstruction_missing("Entity_Familiar::ClearReferences 006121d0 (Gello's cord)"); + if ((variant == WISP || variant == ITEM_WISP) && subtype == COLLECTIBLE_FORTUNE_COOKIE) + { + player->cacheFlags |= CACHE_LUCK; + player->temporaryEffects.isEvaluateCachePending = true; + } linkedEntity = nullptr; Entity::ClearReferences(); hitList = {}; diff --git a/src/entity_familiar.h b/src/entity_familiar.h index 4f40916..88fe704 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -6,6 +6,7 @@ #include "sfx_manager.h" #include "weapon.h" #include +#include #include #include #include @@ -50,6 +51,13 @@ enum TargetFlag : uint32_t TARGET_NO_STICKINESS = 1 << 4 }; +// The Book of Virtues wisps' three rings (orbit layers 7 to 9) and how many each holds, Lemegeton's entry when Book of +// Virtues is held, and a priority below every wisp's. +constexpr int WISP_RING_FIRST_LAYER = 7; +constexpr std::array WISP_RING_CAPACITY = {6, 8, 12}; +constexpr int LEMEGETON_VIRTUES_WISP = 0x10012; +constexpr int WISP_PRIORITY_NONE = 9999; + // The formation slot of a familiar outside any. constexpr uint8_t FORMATION_NONE = 0xff; @@ -94,6 +102,9 @@ struct Entity_Familiar : Entity RELIC = 23, BUM_FRIEND = 24, HOLY_WATER = 25, + KEY_PIECE_1 = 26, + KEY_PIECE_2 = 27, + KEY_FULL = 28, FLY_ORBITAL = 33, SACRIFICIAL_DAGGER = 35, DEAD_CAT = 40, @@ -294,9 +305,10 @@ struct Entity_Familiar : Entity void update_tail(); void ai_umbilical_baby(bool isInterpolated); void WispInit(); - uint32_t wisp_kill(); + bool wisp_kill(); + void wisp_death(const EntityRef& source); Entity_Tear* fire_wisp_projectile(Vector velocity); - uint32_t wisp_take_damage(float*, uint32_t*, int*); + bool wisp_take_damage(const EntityRef& source, uint64_t damageFlags); void ai_wisp(); void ai_mr_me_wisp(); void ai_mega_blast_wisp(); @@ -450,6 +462,15 @@ bool familiar_unicorn_active(Entity_Player& owner); Entity* spawn_dip_at(int subType, const Vector* position, Entity* spawner, const Vector* targetPosition); float angle_wrap(float angle); Vector direction_unit(int direction); + +// The wisps' shared parts of the familiar's animations, hits, touches and death (familiar_wisp.cpp). +void wisp_anim_play(Entity_Familiar& wisp, std::string_view name); +int wisp_hit_countdown(int damageCountdown); +void wisp_countdown_share(Entity_Familiar& hurt); +bool wisp_touch(Entity_Familiar& wisp, Entity& enemy); +void wisp_morph(Entity_Familiar& wisp, int newSubtype); +void wisp_room_clear(Entity_Familiar& wisp); +void item_wisp_icon_render(Entity_Familiar& wisp); void familiar_check(Entity_Player& player, const FamiliarCount& familiars); void familiars_evaluate(Entity_Player& player); int familiar_lullaby_delay(Entity_Familiar& familiar, int fireDelay); diff --git a/src/entity_knife.cpp b/src/entity_knife.cpp index 6c463e1..480d9fb 100644 --- a/src/entity_knife.cpp +++ b/src/entity_knife.cpp @@ -123,7 +123,6 @@ constexpr float SWORD_BEAM_DAMAGE_BONUS = 2; constexpr float SWORD_SPIN_BEAM_DAMAGE = 4; constexpr float SWORD_BEAM_SCALE_MIN = 0.01f; // The flag a sword carries while a full-health beam waits for the end of its swing. -constexpr uint64_t FLAG_SWORD_BEAM = FLAG_SPAWN_STICKY_SPIDERS; // Technology's laser and Brimstone's ring on a thrown knife, and Mysterious Liquid's creep. constexpr float KNIFE_TECH_LIFT = -8; diff --git a/src/entity_knife.h b/src/entity_knife.h index 38b33c6..781aed1 100644 --- a/src/entity_knife.h +++ b/src/entity_knife.h @@ -6,6 +6,8 @@ // The distances a knife has no use for yet: where it splits off its parent and where it shows up. constexpr float KNIFE_DISTANCE_NONE = -1; +// A swung sword marked to throw its beam this swing. +constexpr uint64_t FLAG_SWORD_BEAM = FLAG_SPAWN_STICKY_SPIDERS; // The knives (Lua's KnifeVariant): Mom's Knife, the Forgotten's swung weapons, Bloody Babylon's and the swords. enum KnifeVariant : int diff --git a/src/entity_knife_hits.cpp b/src/entity_knife_hits.cpp index 8b5e462..7a087d6 100644 --- a/src/entity_knife_hits.cpp +++ b/src/entity_knife_hits.cpp @@ -146,9 +146,6 @@ constexpr float BURST_TRAIL_SCALE = 0.6f; constexpr int BURST_TRAIL_DEPTH = -400; constexpr float KNIFE_SPLIT_SCALE = 0.8f; constexpr float SPLIT_ANGLE = 90; -constexpr float RIFT_MARGIN = -10; -constexpr int RIFT_FRAMES = 60; -constexpr int RIFT_VERSUS_FRAMES = 30; constexpr float SHARD_CRAWLSPACE_OFFSET_Y = -18; constexpr float RANDOM_HALF_TURN_KNIFE = 3.14f; diff --git a/src/entity_laser.cpp b/src/entity_laser.cpp index 3e90fd4..47747b8 100644 --- a/src/entity_laser.cpp +++ b/src/entity_laser.cpp @@ -666,7 +666,7 @@ Vector Entity_Laser::CalculateEndPoint(const Vector& start, const Vector& direct Vector end = vector_add(start, vector_scale(direction, BEAM_REACH)); bool isPlayersParent = parent && (parent->type == ENTITY_PLAYER || parent->type == ENTITY_FAMILIAR); - if (g_game->challenge == CHALLENGE_PONG && !isPlayersParent) + if (g_game->challenge == CHALLENGE_GUARDIAN && !isPlayersParent) { float nearest = BEAM_REACH; for (Entity_Player* player : g_game->playerManager.playerList) @@ -1334,7 +1334,7 @@ void Entity_Laser::path_update(bool& isRedirected, bool& isCut) if (homingType == LASER_HOMING_PLAYER) homingLaser.truncate_samples_at_obstacle(posOffset); } bool isPlayersParent = parent && (parent->type == ENTITY_PLAYER || parent->type == ENTITY_FAMILIAR); - if (g_game->challenge == CHALLENGE_PONG && !isPlayersParent) homingLaser.truncate_samples_at_player(); + if (g_game->challenge == CHALLENGE_GUARDIAN && !isPlayersParent) homingLaser.truncate_samples_at_player(); bool isMirrored = false; path_redirects_update(isRedirected, isCut, isMirrored); diff --git a/src/entity_laser_hits.cpp b/src/entity_laser_hits.cpp index b7ee753..dfaaddc 100644 --- a/src/entity_laser_hits.cpp +++ b/src/entity_laser_hits.cpp @@ -67,7 +67,6 @@ 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}; constexpr int PULLED_EFFECTS[] = {EFFECT_TINY_BUG, EFFECT_TINY_FLY, EFFECT_WORM, EFFECT_BEETLE, EFFECT_LIL_GHOST}; @@ -119,7 +118,7 @@ void Entity_Laser::DoDamage(Entity* entity, float damage) } else if (entity->type == ENTITY_FAMILIAR && !isVersus && (entity->variant == Entity_Familiar::ISAACS_HEART || - (g_game->challenge == CHALLENGE_PONG_HITS && entity->variant == Entity_Familiar::PUNCHING_BAG))) + (g_game->challenge == CHALLENGE_GUARDIAN && entity->variant == Entity_Familiar::PUNCHING_BAG))) { Entity_Player* player = static_cast(entity)->player; player->TakeDamage(PLAYER_HIT_DAMAGE, DAMAGE_LASER | DAMAGE_ISAAC_HURT, EntityRef(source), LASER_HIT_COUNTDOWN); diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index ce5b8e1..b8d6c02 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -23,25 +23,26 @@ #include "room_grid.h" #include "sfx_manager.h" #include "mines.h" +#include "npc_alt.h" #include #include #include // The frames of a controlled NPC's charge bar, empty to full. constexpr int CHARGE_BAR_FRAMES = 100; +constexpr float POOP_THROW_HEIGHT = -20; +constexpr float POOP_THROW_LOUD_SPEED = 5; constexpr int ENTITY_FEAR_IMMUNE = 205; constexpr int ENTITY_NO_DECOY_TYPE = 213; -constexpr int ENTITY_MOMS_HEART_PLAYER_PICK = 53; +constexpr uint32_t DOPLE_PICK_SHIFT = 11; constexpr int ENTITY_UNREACHABLE_EXEMPT = 886; constexpr int ENTITY_FLICKER_TYPE = 252; constexpr int ENTITY_DEATH_SPARK_TYPE = 882; -constexpr int ENTITY_SHADOW_OVERLAY_TYPE = 886; constexpr int ENTITY_DAMAGE_NUMBERS_TYPE = 964; constexpr int ENTITY_ERASE_EXEMPT = 950; constexpr int APPEAR_OVERLAY_KEPT_TYPE = 266; -constexpr int APPEAR_SOUND_TYPE_A = 401; -constexpr int APPEAR_SOUND_TYPE_B = 403; +constexpr float BIG_HORN_APPEAR_VOLUME = 2; constexpr std::array APPEAR_EVENT_TYPES = {404, 912, 913, 917}; constexpr std::array FLUSH_TYPES = {217, 220, 223, 261, 402, 870, 871, 872, 914}; constexpr int FLUSH_PROP_TYPE = 237; @@ -75,7 +76,7 @@ constexpr int DEATH_NO_BURST_FIRST = 74; constexpr int DEATH_NO_BURST_LAST = 76; constexpr int MULLIGAN_VARIANT_FLEEING = 2; constexpr int CHALLENGE_KILL_CHARGE = 33; -constexpr std::string_view BIG_HORN_SPIT_EVENT = "Item"; +constexpr std::string_view BIG_HORN_SPLASH_EVENT = "Poof"; constexpr std::string_view DIRT_LAYER = "dirt"; constexpr std::string_view HOLE_LAYER = "Hole"; constexpr std::string_view HOLE2_LAYER = "Hole2"; @@ -157,6 +158,7 @@ constexpr int TRINKET_TICK_ID = 53; constexpr int TRINKET_SUPER_MAGNET_ID = 68; constexpr int TRINKET_LIGHTER_ID = 135; constexpr int TRINKET_ICE_CUBE_ID = 188; +constexpr int ROOM_TRINKET_STATUS_FRAMES = -90; constexpr int NULLITEM_DAMOCLES_WEAKNESS = 64; constexpr int CHALLENGE_BEANS = 30; @@ -223,6 +225,9 @@ constexpr float RIPPLE_SCALE = 0.05f; constexpr float RIPPLE_DEPTH = -10; constexpr float RIPPLE_SPEED = 0.5f; constexpr int RIPPLE_FRAMES = 7; +constexpr float POOF02_SCALE = 0.3f; +constexpr float POOF02_DEPTH = 10; +constexpr ColorMod POOF02_COLOR = {{1, 1, 1, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr float SLOW_FRICTION = 0.92f; constexpr int WEAKNESS_FRAMES = 2; constexpr int STATUS_REFRESH = -2; @@ -1469,8 +1474,13 @@ void Entity_NPC::appear_update() int sound = isDeathSoundAlt ? SOUND_SUMMON_WAVE : SOUND_SUMMON_POOF; g_manager->sfxManager.Stop(sound); PlaySound(sound, 1, 2, false, 1); - if (type == APPEAR_SOUND_TYPE_A || type == APPEAR_SOUND_TYPE_B || (type == ENTITY_BIG_HORN && variant == 0)) - reconstruction_missing("Entity_NPC::Update 006c4b30: a Repentance boss's appear sounds"); + if (type == ENTITY_STAIN) + { + npc_sound_play(SOUND_MAGGOT_BURST_OUT, 1, 2, 1); + PlaySound(SOUND_THE_STAIN_BURST, 1, 2, false, 1); + } + else if (type == ENTITY_FORSAKEN) PlaySound(SOUND_FORSAKEN_LAUGH, 1, 2, false, 1); + else if (type == ENTITY_BIG_HORN && variant == 0) PlaySound(SOUND_BOSS_LITE_ROAR, BIG_HORN_APPEAR_VOLUME, 2, false, 1); } else if (appearFrames == APPEAR_SHOW_FRAME) { @@ -1557,7 +1567,7 @@ static void death_events_update(Entity_NPC& npc) return npc.FireProjectiles(npc.pos, vector_make(PLUM_RING_SPEED, PLUM_RING_SHOTS), PROJECTILES_RING, params); } case ENTITY_GIDEON: - return NpcHelper::gideon_update_death(&npc); + return gideon_death_update(npc); case ENTITY_REAP_CREEP: if (npc.sprite.overlayAnimState.animData) npc.sprite.RemoveOverlay(); return; @@ -1567,9 +1577,7 @@ static void death_events_update(Entity_NPC& npc) .radiusMultiplier = SINGE_BLAST_REACH}); return; case ENTITY_MIN_MIN: - if (npc.sprite.IsEventTriggered("Shoot") && npc.sprite.GetNullFrame("BloodGuide")) - reconstruction_missing("Entity_NPC::Update 006c4b30: Min-Min's death bursts"); - return; + return min_min_death_update(npc); case ENTITY_MOTHER: if (npc.variant != MOTHER_SLAM_VARIANT || !npc.sprite.IsEventTriggered("Shoot")) return; game_shake_screen(MOTHER_SLAM_SHAKE); @@ -1625,8 +1633,7 @@ void Entity_NPC::death_animation_start() if (sprite.GetAnimationData("Death")) { - if (type == ENTITY_BIG_HORN) - return reconstruction_missing("Entity_NPC::Update 006c4b30: Big Horn's death animations"); + if (type == ENTITY_BIG_HORN) return big_horn_death_play(*this); if (type == ENTITY_RAG_MAN) death_head_layer_keep(sprite); sprite.Play("Death"); return; @@ -1834,18 +1841,44 @@ void Entity_NPC::toxic_shock_creep_spawn() creep->Update(); } -// Part of 006c4b30: the items whose aura works on enemies near a player (The Soul, Super Magnet, Salvation). +// Part of 006c4b30: the items whose aura works on enemies near a player: Super Magnet's nearest holder pulls the +// enemy in one frame in three. The Soul's push and Salvation's beam stop the game until reached. void Entity_NPC::player_aura_update() { + constexpr float SUPER_MAGNET_REACH_SQUARED = 1e9f; + constexpr float SUPER_MAGNET_PULL = 0.5f; + constexpr int SUPER_MAGNET_ODDS = 3; if (state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH || IsFriendly() || !IsVulnerableEnemy(nullptr)) return; + + Entity_Player* magnet = nullptr; + float magnetDistance = SUPER_MAGNET_REACH_SQUARED; for (Entity_Player* player : g_game->playerManager.playerList) { - bool isAura = player->HasCollectible(COLLECTIBLE_SOUL_ID) || player->HasTrinket(TRINKET_SUPER_MAGNET_ID) || - player->HasCollectible(COLLECTIBLE_SALVATION_ID); - if (isAura) - reconstruction_missing("Entity_NPC::Update 006c4b30: The Soul's, Super Magnet's and Salvation's pull"); + if (player->HasCollectible(COLLECTIBLE_SOUL_ID) || player->HasCollectible(COLLECTIBLE_SALVATION_ID)) + reconstruction_missing("Entity_NPC::Update 006c4b30: The Soul's push and Salvation's beam"); + if (!player->HasTrinket(TRINKET_SUPER_MAGNET_ID)) continue; + Vector away = vector_sub(player->pos, pos); + float distance = away.x * away.x + away.y * away.y; + if (distance >= magnetDistance) continue; + magnet = player; + magnetDistance = distance; } + if (magnet && random_below(SUPER_MAGNET_ODDS) == 0) velocity = vector_add(velocity, vector_resized(vector_sub(magnet->pos, pos), SUPER_MAGNET_PULL)); +} + +// Whether Lighter or Ice Cube catches an enemy entering the room: a fifth, a third or a half by strength, more with +// the owner's luck, rolled on the enemy's seed. +static bool is_room_trinket_struck(Entity_NPC& npc, Entity_Player& owner, int trinket) +{ + constexpr float CHANCES[] = {0.2f, 0.33f, 0.5f}; + constexpr float LUCK_CHANCE = 0.02f; + constexpr uint32_t STATUS_SHIFT_INDEX = 5; + int multiplier = owner.GetTrinketMultiplier(trinket); + float chance = CHANCES[multiplier == 2 ? 1 : multiplier == 3 ? 2 : 0]; + RNG rng; + rng.SetSeed(npc.initSeed, STATUS_SHIFT_INDEX); + return rng.RandomFloat() < owner.luck * LUCK_CHANCE + chance; } // Part of 006c4b30: what the players' items do to enemies each frame: Toxic Shock's poison, Lighter's burn and Ice @@ -1858,8 +1891,15 @@ void Entity_NPC::item_effects_update() { if (Entity_Player* owner = players.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_IGNORE)) AddPoison(EntityRef(owner), TOXIC_SHOCK_POISON, 0, false); - if (players.FirstTrinketOwner(TRINKET_LIGHTER_ID) || players.FirstTrinketOwner(TRINKET_ICE_CUBE_ID)) - reconstruction_missing("Entity_NPC::Update 006c4b30: Lighter's burn and Ice Cube's freeze"); + Entity_Player* toxicOwner = players.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_IGNORE); + if (Entity_Player* lighter = players.FirstTrinketOwner(TRINKET_LIGHTER_ID); lighter && is_room_trinket_struck(*this, *lighter, TRINKET_LIGHTER_ID)) + AddBurn(EntityRef(lighter), ROOM_TRINKET_STATUS_FRAMES, 0, false); + // The original freezes from the Toxic Shock owner's reference, usually none. + if (Entity_Player* ice = players.FirstTrinketOwner(TRINKET_ICE_CUBE_ID); ice && is_room_trinket_struck(*this, *ice, TRINKET_ICE_CUBE_ID)) + { + AddFreeze(EntityRef(toxicOwner), ROOM_TRINKET_STATUS_FRAMES, false); + AddIce(EntityRef(toxicOwner), ROOM_TRINKET_STATUS_FRAMES); + } } Entity_Player* targetPlayer = GetPlayerTarget()->ToPlayer(); @@ -1888,10 +1928,18 @@ static float timescale_factor(float factor, float timeScale) return timeScale == 1 ? factor : factor / ((factor + timeScale) - factor * timeScale); } -// Part of 006c4b30: a poof02 event puffs smoke from the null of that name. +// Part of 006c4b30: a poof02 event puffs half-faded smoke at the NPC, placed and sized (a third) by the null of that +// name. The original reads the null unchecked. Here a sprite without one puffs nothing. void Entity_NPC::poof02_spawn() { - reconstruction_missing("Entity_NPC::Update 006c4b30: the poof02 event's smoke"); + const NullFrame* null = sprite.GetNullFrame("poof02"); + if (!null) return; + + Entity* poof = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF02, .seed = Random()}); + poof->sprite.offset = null->pos; + poof->sprite.scale = vector_scale(null->scale, POOF02_SCALE); + poof->renderDepthOffset = POOF02_DEPTH; + poof->SetColor(POOF02_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); } // Part of 006c4b30: a grounded enemy walking through water leaves a ripple every 7 frames. @@ -2035,12 +2083,11 @@ void Entity_NPC::seed_effects_update() } // Part of 006c4b30: the few enemies with their own per-frame step: Hornfel, Gideon's camera, the Heart's partner and -// Big Horn's spit. +// Big Horn's splash. void Entity_NPC::type_update() { if (type == ENTITY_HORNFEL) Hornfel_UpdateFrame(); - if (type == ENTITY_GIDEON && state == NPC_STATE_APPEAR) - reconstruction_missing("Entity_NPC::Update 006c4b30: Gideon's camera"); + if (type == ENTITY_GIDEON && state == NPC_STATE_APPEAR) g_game->room->camera->SetFocusPosition(pos); if (type == ENTITY_HEART) { targetPosition = {}; @@ -2051,8 +2098,7 @@ void Entity_NPC::type_update() partner->targetPosition = vector_scale(targetPosition, -1); } } - if (type == ENTITY_BIG_HORN && sprite.IsEventTriggered(BIG_HORN_SPIT_EVENT)) - reconstruction_missing("Entity_NPC::Update 006c4b30: Big Horn's spit"); + if (type == ENTITY_BIG_HORN && sprite.IsEventTriggered(BIG_HORN_SPLASH_EVENT)) big_horn_splash(*this); } // Part of 006c4b30: a forced target runs out, and a boss then waits 150 frames before taking another. @@ -2140,9 +2186,14 @@ void Entity_NPC::Kill(const EntityRef& source) // 006b8f30 Lets go of everything it points at, Gideon's chain and Mother's sounds included. void Entity_NPC::ClearReferences() { - if (type == ENTITY_SIREN_HELPER || type == ENTITY_GIDEON || - (type == ENTITY_MOTHER && (variant == 0 || variant == 10))) - reconstruction_missing("Entity_NPC::ClearReferences 006b8f30: Siren's helper, Gideon's and Mother's links"); + auto* charmed = dynamic_cast(target.get()); + if (type == ENTITY_SIREN_HELPER && charmed && charmed->HasEntityFlags(FLAG_CHARM)) charmed->RemoveFromPlayer(); + if (type == ENTITY_GIDEON) gideon_chain_unlink(*this); + if (type == ENTITY_MOTHER && (variant == 0 || variant == 10)) + { + g_manager->sfxManager.Stop(SOUND_MOTHER_SUCTION); + g_manager->sfxManager.Stop(SOUND_ULTRA_GREED_SPINNING); + } pickupGhostsEntity = nullptr; unknownF54 = nullptr; salvationTarget = nullptr; @@ -2261,12 +2312,43 @@ int Entity_NPC::death_burst_get() } } +// Part of 006be840: a Dople keeps its player, else picks one by its seed among the players no other Dople copies (a +// controlled one, its controller's). With none left it dies, mimicking the first player. +static Entity* dople_player_pick(Entity_NPC& npc) +{ + if (npc.target) return npc.target.get(); + + std::vector doples = entity_query(ENTITY_DOPLE, -1); + std::vector candidates; + for (Entity_Player* player : g_game->playerManager.playerList) + { + bool isFree = npc.controllerID != -1 ? player->controllerIndex == npc.controllerID + : std::ranges::none_of(doples, [&](Entity* dople) { + return dople != &npc && static_cast(dople)->target.get() == player; + }); + if (isFree) candidates.push_back(player); + } + + Entity* picked = nullptr; + if (!candidates.empty()) + { + RNG pick = rng_make(npc.initSeed, DOPLE_PICK_SHIFT); + picked = candidates[pick.RandomInt((int)candidates.size())]; + } + else + { + npc.Kill(EntityRef()); + picked = g_game->GetPlayer(0); + } + npc.target = picked; + return npc.target.get(); +} + // 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() { - if (type == ENTITY_MOMS_HEART_PLAYER_PICK) - reconstruction_missing("Entity_NPC::GetPlayerTarget 006be840: the shared player choice of its kind"); + if (type == ENTITY_DOPLE) return dople_player_pick(*this); bool isRetargeting = IsFrame(TARGET_REFRESH_FRAMES, (int)index) || !target; if (HasEntityFlags(FLAG_CHARM) && !g_game->room->isPacifist && isRetargeting) @@ -2563,14 +2645,6 @@ void Entity_NPC::status_overlay_render(const Vector& offset) statusEffectSprite.Render(SpriteDraw{at, {}, {}}); } -// 006d4840 Draws its shadow layer (Entity::RenderShadowLayer), a few with their links' shadows first. -bool Entity_NPC::RenderShadowLayer(const Vector& offset) -{ - if (type == ENTITY_SHADOW_OVERLAY_TYPE || (type == ENTITY_LARRYJR && variant == 3)) - reconstruction_missing("Entity_NPC::RenderShadowLayer 006d4840: a linked enemy's shadow"); - return Entity::RenderShadowLayer(offset); -} - // 006d90e0 Moves the effect a controlled enemy aims with along the controller's input and keeps it in reach. void Entity_NPC::UpdateChildEffectPosition(bool) { @@ -2759,10 +2833,24 @@ void Entity_NPC::UpdateControllerMovement(bool) // The rest of Entity_NPC is not reconstructed yet. -// 006d9440 -bool Entity_NPC::TryThrow(const EntityRef&, const Vector&, float) +// 006d9440 Thrown: a poop pile flies at the throw's velocity from 20 pixels up at the throw's height, stops being kept +// across rooms, gets the thrown flag (colliding with everything when a player threw it) and splats when fast. Other +// NPCs are thrown only while held. +bool Entity_NPC::TryThrow(const EntityRef& source, const Vector& throwVelocity, float height) { - reconstruction_missing("Entity_NPC::TryThrow 006d9440"); + if (type != ENTITY_POOP) return HasEntityFlags(FLAG_HELD); + + v1 = vector_make(POOP_THROW_HEIGHT, -height); + velocity = throwVelocity; + flags = (flags & ~FLAG_PERSISTENT) | FLAG_THROWN; + if (source.type == ENTITY_PLAYER) entityCollisionClass = ENTCOLL_ALL; + if (vector_length_squared(throwVelocity) > POOP_THROW_LOUD_SPEED * POOP_THROW_LOUD_SPEED) + { + int sound = SOUND_POOPITEM_THROW; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); + } + return true; } // 004b92e0 @@ -2777,24 +2865,6 @@ void Entity_NPC::Hornfel_UpdateFrame() reconstruction_missing("Entity_NPC::Hornfel_UpdateFrame 004bb0e0"); } -// 004e8fa0 -void Entity_NPC::UpdateCordChain(bool) -{ - reconstruction_missing("Entity_NPC::UpdateCordChain 004e8fa0"); -} - -// 004e9b10 -void Entity_NPC::render_overlay(const Vector&, bool) -{ - reconstruction_missing("Entity_NPC::render_overlay 004e9b10"); -} - -// 0059bed0 -void Entity_NPC::RenderSegmentLink(const Vector&, bool) -{ - reconstruction_missing("Entity_NPC::RenderSegmentLink 0059bed0"); -} - // 0059e390 void Entity_NPC::CreateBling() { @@ -2871,10 +2941,13 @@ void* Entity_NPC::fireplace_get_loot(void*, bool) reconstruction_missing("Entity_NPC::fireplace_get_loot 006d1580"); } -// 006d4db0 +// 006d4db0 Whether a reroll may turn it into another enemy: not when its tags forbid it, for a Lil Haunt still tied +// to the Haunt, or for a boss. bool Entity_NPC::CanReroll() { - reconstruction_missing("Entity_NPC::CanReroll 006d4db0"); + if ((config->tags & ENTITY_TAG_NOREROLL) || (type == ENTITY_THE_HAUNT && variant == HAUNT_LIL_VARIANT && parent)) + return false; + return !IsBoss() && !config->isBoss; } // 006d88b0 diff --git a/src/entity_npc_render.cpp b/src/entity_npc_render.cpp index 5c6d81e..6171663 100644 --- a/src/entity_npc_render.cpp +++ b/src/entity_npc_render.cpp @@ -1,4 +1,5 @@ #include "entity_npc.h" +#include "beam_renderer.h" #include "entity_config.h" #include "entity_player.h" #include "game.h" @@ -6,6 +7,7 @@ #include "manager.h" #include "mines.h" #include "npc_ai.h" +#include "npc_depths.h" #include "room.h" #include #include @@ -251,25 +253,24 @@ static void npc_body_render(Entity_NPC& npc, const Vector& offset) { bool isChained = npc.type == ENTITY_BALL_AND_CHAIN && !vector_is_zero(npc.targetPosition); if (npc.type == ENTITY_BALL_AND_CHAIN && !isChained) return npc.Entity::Render(offset); - if (isChained && npc.pos.y > npc.targetPosition.y) - reconstruction_missing("NpcHelper::ball_and_chain_render_chain 004f5f20"); + if (isChained && npc.pos.y > npc.targetPosition.y) ball_and_chain_render(npc, offset); if (npc.type == ENTITY_POOP && npc.entityRef && npc.isVisible) poop_rider_render(npc, offset); switch (npc.type) { case ENTITY_PEEPER_FATTY: - return reconstruction_missing("Entity_NPC::Render 006d2e50: the Peeping Fatty's eyes (005579b0)"); + return peeping_fatty_render(npc, offset); case ENTITY_EVIS: - return reconstruction_missing("Entity_NPC::Render 006d2e50: Evis's cord (004e07a0)"); + return evis_render(npc, offset); case ENTITY_HORNFEL: - return reconstruction_missing("Entity_NPC::Render 006d2e50: Hornfel's drawing"); + return hornfel_render(npc, offset); case ENTITY_SCOURGE: if (npc.variant != SCOURGE_CHAIN) return npc.Entity::Render(offset); - return reconstruction_missing("Entity_NPC::Render 006d2e50: the Scourge's chain (00589de0)"); + return scourge_chain_render(npc, offset); case ENTITY_MOTHER: return reconstruction_missing("NpcHelper::mother_render 0056fcf0"); case ENTITY_HORNY_BOYS: - return reconstruction_missing("NpcHelper::horny_boys_render 004bcfd0"); + return horny_boys_render(npc, offset); case ENTITY_CLUTCH: return reconstruction_missing("NpcHelper::clutch_render 00575a10"); case ENTITY_BEAST: @@ -288,10 +289,10 @@ static void npc_front_render(Entity_NPC& npc, const Vector& offset) { if (npc.type == ENTITY_VIS_FATTY) npc.render_overlay(offset, false); if (npc.type == ENTITY_BALL_AND_CHAIN && !vector_is_zero(npc.targetPosition) && npc.pos.y <= npc.targetPosition.y) - reconstruction_missing("NpcHelper::ball_and_chain_render_chain 004f5f20"); + ball_and_chain_render(npc, offset); if (is_type(npc, ENTITY_LARRYJR, SHELL) && npc.child && npc.pos.y <= npc.child->pos.y) npc.RenderSegmentLink(offset, false); - if (npc.type == ENTITY_CHIMERA) reconstruction_missing("NpcHelper::chimera_render_child 004a1000"); + if (npc.type == ENTITY_CHIMERA) chimera_child_render(npc, offset); } // Whether a local player controls it. @@ -397,7 +398,7 @@ void Entity_NPC::Render(const Vector& offset) if (cart && isVisible) { cart->sprite.RenderLayer(1, SpriteDraw{cartPosition, {}, {}}); - if (type == ENTITY_HORNFEL) reconstruction_missing("NpcHelper::hornfel_render_minecart 004b7c30"); + if (type == ENTITY_HORNFEL) hornfel_minecart_render(*this, cart->sprite, cartPosition); } if (npc_is_locally_controlled(*this) && chargeBarSprite.isLoaded && chargeBarSprite.color._tint[3] > 0) { @@ -448,3 +449,160 @@ void Entity_NPC::render_v1_layer_frames() sprite.GetLayer(1)->color._tint[3] = fissure_alpha(nearHeight, isReflected); farLayer->color._tint[3] = fissure_alpha(farHeight, isReflected); } + +// A shadow pass draws links and cords flat black. +constexpr ColorMod SHADOW_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// 006d4840 Draws its shadow layer (Entity::RenderShadowLayer), the Vis Fatty's cord and the Shell's link first. +bool Entity_NPC::RenderShadowLayer(const Vector& offset) +{ + if (type == ENTITY_VIS_FATTY) render_overlay(offset, true); + else if (is_type(*this, ENTITY_LARRYJR, SHELL)) RenderSegmentLink(offset, true); + return Entity::RenderShadowLayer(offset); +} + +// A cord's look: the length it stretches to fully, the layer it takes, which trail points it draws, the head's shade +// and how its middle points smooth over their neighbours. +constexpr float OVERLAY_CORD_LENGTH = 192; +constexpr float DOGMA_CORD_LENGTH = 76; +constexpr int CORD_LAYER = 2; +constexpr size_t CORD_TRAIL_STRIDE = 3; +constexpr size_t CORD_TRAIL_LIFT = 2; +constexpr float CORD_HEAD_SHADE = 0.3f; +constexpr float CORD_SMOOTH_SIDE = 0.3f; +constexpr float CORD_SMOOTH_MIDDLE = 0.4f; +constexpr float CORD_BULGE_WIDTH = 2; +constexpr float EVIS_TAUT_WIDTH = 0.9f; + +// A cord point: where it draws and how far along the cord it lies. +struct CordPoint +{ + Vector pos{}; + float length = 0; +}; + +// The cord's points on screen: every third trail point (lifted by the height the third after it holds, unless a +// shadow), the middle ones smoothed over their neighbours, each with its length along the cord. +static std::vector cord_points_get(Entity_NPC& npc, const Vector& offset, bool isShadow) +{ + std::vector screen; + for (size_t i = 0; i < npc.vectorDeque2.size(); i += CORD_TRAIL_STRIDE) + { + Vector point = npc.vectorDeque2[i]; + if (!isShadow && i + CORD_TRAIL_LIFT < npc.vectorDeque2.size()) point.y += npc.vectorDeque2[i + CORD_TRAIL_LIFT].x; + screen.push_back(vector_add(render_position_get(point, RENDER_SNAPPED), offset)); + } + + std::vector cord = {{screen.front(), 0}}; + for (size_t i = 1; i + 1 < screen.size(); i++) + { + Vector smoothed = vector_add(vector_scale(screen[i], CORD_SMOOTH_MIDDLE), + vector_scale(vector_add(screen[i - 1], screen[i + 1]), CORD_SMOOTH_SIDE)); + cord.push_back({smoothed, cord.back().length + vector_length(vector_sub(cord.back().pos, smoothed))}); + } + cord.push_back({screen.back(), cord.back().length + vector_length(vector_sub(cord.back().pos, screen.back()))}); + return cord; +} + +// 004e9b10 Draws a cord along its trail (vectorDeque2): the Vis Fatty's with a bulge pumping down it, Dogma's +// tethers while its CordPos null shows, the Peeping Fatty's and Evis's, whose frame follows how far it stretches. +// The head point is shaded, and the cord's texture slides in as it stretches. +void Entity_NPC::render_overlay(const Vector& offset, bool isShadow) +{ + if (vectorDeque2.empty()) return; + + float cordLength = OVERLAY_CORD_LENGTH; + int layerId = CORD_LAYER; + BeamFrame beamFrame = BEAM_FRAME_OVERLAY; + if (type == ENTITY_DOGMA) + { + const NullFrame* cordNull = sprite.animState.animData ? sprite.GetNullFrame("CordPos") : nullptr; + if (!cordNull || !cordNull->isVisible) return; + cordLength = DOGMA_CORD_LENGTH; + } + else if (type == ENTITY_EVIS) + { + layerId = 0; + beamFrame = BEAM_FRAME_MAIN; + } + else if (type == ENTITY_PEEPER_FATTY) layerId = 1; + if (layerId >= (int)sprite.layerStates.size()) return; + + ColorMod cordColor = isShadow ? SHADOW_COLOR : COLOR_DEFAULT; + float headShade = isShadow ? 0 : CORD_HEAD_SHADE; + ColorMod headColor = {{headShade, headShade, headShade, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + std::vector cord = cord_points_get(*this, offset, isShadow); + float totalLength = cord.back().length; + + float width = 1; + int bulgePoint = -1; + if (type == ENTITY_VIS_FATTY && projectileDelay > 0) bulgePoint = projectileDelay / 2; + else if (type == ENTITY_EVIS && sprite.animState.animData) + { + const AnimationData* data = sprite.animState.animData; + const std::vector& frames = data->animLayers[0].frames; + auto stretched = std::ranges::find_if(frames, [&](const AnimationFrame& frame) { return totalLength <= frame.height; }); + if (stretched != frames.end()) sprite.animState.SetFrameFloat((float)(stretched - frames.begin())); + headColor = cordColor; + cordLength = totalLength; + if (target) width = EVIS_TAUT_WIDTH; + } + + float fill = std::min(totalLength / cordLength, 1.0f) * width; + g_beamRenderer.Begin(sprite, layerId, beamFrame, BEAM_COORDINATE_HEIGHTS); + for (size_t i = 0; i < cord.size(); i++) + g_beamRenderer.Add({.color = i == 0 ? headColor : cordColor, + .pos = cord[i].pos, + .coordinate = width - (1 - cord[i].length / totalLength) * fill, + .width = (int)i == bulgePoint ? CORD_BULGE_WIDTH : 1}); + g_beamRenderer.End(); +} + +// The Shell's link: it hangs from 6 above each end (18 higher on a segment still in its shell, i2 0), starts and ends +// 6 in, narrows to 40% at its middle as it stretches from 20 to 90 long, and draws once at least 6 long. +constexpr float LINK_INSET = 6; +constexpr float LINK_SHELL_RAISE = 18; +constexpr float LINK_STRETCH_START = 20; +constexpr float LINK_STRETCH_SPAN = 70; +constexpr float LINK_NARROWING = 0.6f; +constexpr float LINK_TAPER_SHARE = 0.15f; +constexpr float LINK_TAPER_MAX = 30; + +// 0059bed0 Draws the link between it and its child segment along its sprite's second layer, while either has come out +// of its shell. +void Entity_NPC::RenderSegmentLink(const Vector& offset, bool isShadow) +{ + Entity_NPC* next = ChildNPC(); + if (!next || (next->i2 == 0 && i2 == 0) || sprite.layerStates.size() < 2) return; + + Vector start = vector_add(render_position_get(pos, RENDER_SNAPPED), offset); + Vector end = vector_add(render_position_get(next->pos, RENDER_SNAPPED), offset); + start.y -= i2 == 0 ? LINK_INSET + LINK_SHELL_RAISE : LINK_INSET; + end.y -= next->i2 == 0 ? LINK_INSET + LINK_SHELL_RAISE : LINK_INSET; + + Vector span = vector_sub(end, start); + float distance = vector_length(span); + Vector direction = vector_normalized(span); + float length = distance - LINK_INSET; + if (length < LINK_INSET) return; + + float stretch = std::clamp((distance - LINK_STRETCH_START) / LINK_STRETCH_SPAN, 0.0f, 1.0f); + float taper = std::min((length - LINK_INSET) * LINK_TAPER_SHARE, LINK_TAPER_MAX); + float middleWidth = 1 - stretch * LINK_NARROWING; + float shoulderWidth = 1 - (1 - middleWidth) * (1 - middleWidth); + ColorMod color = isShadow ? SHADOW_COLOR : COLOR_DEFAULT; + std::array points = {{ + {.color = color, .pos = vector_add(start, vector_scale(direction, LINK_INSET)), .coordinate = 0, .width = 1}, + {.color = color, .pos = vector_add(start, vector_scale(direction, taper + LINK_INSET)), .coordinate = 0.33f, + .width = shoulderWidth}, + {.color = color, .pos = vector_add(start, vector_scale(direction, (length - LINK_INSET) / 2 + LINK_INSET)), + .coordinate = 0.5f, .width = middleWidth}, + {.color = color, .pos = vector_add(start, vector_scale(direction, length - taper)), .coordinate = 0.66f, + .width = shoulderWidth}, + {.color = color, .pos = vector_add(start, vector_scale(direction, length)), .coordinate = 1, .width = 1}, + }}; + + g_beamRenderer.Begin(sprite, 1, BEAM_FRAME_MAIN, BEAM_COORDINATE_HEIGHTS); + for (const BeamPoint& point : points) g_beamRenderer.Add(point); + g_beamRenderer.End(); +} diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index e06df17..8e7ec64 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -4,6 +4,7 @@ #include "entity_effect.h" #include "entity_familiar.h" #include "entity_player.h" +#include "entity_player_trinkets.h" #include "game.h" #include "grid_entity.h" #include "log.h" @@ -14,6 +15,7 @@ #include "room.h" #include "room_grid.h" #include +#include #include #include #include @@ -52,23 +54,13 @@ constexpr int COLLECTIBLE_THE_NEGATIVE = 328; constexpr float OPTIONS_POOF_DROP = 10; constexpr int OPTIONS_ITEM_TIMEOUT = 4; constexpr int TRINKET_BROKEN_MAGNET = 6; -constexpr int TRINKET_BLACK_LIPSTICK = 17; constexpr int TRINKET_BIBLE_TRACT = 18; constexpr int TRINKET_MOMS_PEARL = 38; -constexpr int TRINKET_BLOODY_PENNY = 49; -constexpr int TRINKET_FLAT_PENNY = 51; constexpr int TRINKET_SUPER_MAGNET = 68; -constexpr int TRINKET_BLESSED_PENNY = 131; constexpr float VERSUS_CHEST_VOLUME = 0.7f; constexpr int TRINKET_APPLE_OF_SODOM = 140; -constexpr int TRINKET_CHARGED_PENNY = 147; constexpr int TRINKET_NUH_UH = 165; -constexpr int TRINKET_CURSED_PENNY = 172; constexpr int COLLECTIBLE_MITRE = 173; -// The trinkets that turn a collected coin into something more, which are not reconstructed yet. -constexpr std::array PENNY_TRINKETS = {TRINKET_BLOODY_PENNY, TRINKET_BURNT_PENNY, TRINKET_FLAT_PENNY, - TRINKET_COUNTERFEIT_PENNY, TRINKET_BLESSED_PENNY, TRINKET_CHARGED_PENNY, - TRINKET_CURSED_PENNY, (int)TRINKET_BUTT_PENNY, TRINKET_ROTTEN_PENNY}; constexpr int SPECIAL_DAILY_NICKELS = 7; // Achievement 33 unlocks both the half soul heart and the micro battery. constexpr int ACHIEVEMENT_HALF_SOUL_HEART = 33; @@ -117,16 +109,13 @@ constexpr int SOUND_DIMEDROP = 198; constexpr int SOUND_DIMEPICKUP = 199; constexpr int SOUND_LUCKYPICKUP = 200; constexpr int SOUND_FETUS_FEET = 201; -constexpr int SOUND_GOLDENKEY = 204; constexpr int SOUND_NICKELDROP = 231; constexpr int SOUND_NICKELPICKUP = 232; constexpr int SOUND_PENNYDROP = 233; constexpr int SOUND_PENNYPICKUP = 234; -constexpr int SOUND_PING_PONG = 458; constexpr int SOUND_BONE_HEART = 461; constexpr int SOUND_SHOVEL_DROP = 463; constexpr int SOUND_GOLD_HEART = 465; -constexpr int SOUND_BONE_DROP = 467; constexpr int SOUND_UNHOLY = 468; constexpr int SOUND_GOLDENBOMB = 470; constexpr int SOUND_ROTTEN_HEART = 497; @@ -1265,23 +1254,132 @@ void Entity_Pickup::appear_update() if (variant == PICKUP_THROWABLEBOMB) entityGridCollisionClass = GRIDCOLL_GROUND; } -// 006ed690 Magneto, Super Magnet and Broken Magnet pull pickups to the players. Without them a pickup flying over the -// pits lands again. +// Whether a magnet pulls a free pickup to a player: coins, keys, bombs and hearts the player can take, batteries it +// needs, and with stronger Super Magnets bags, trinkets and chests. +static bool is_magnet_pulled(Entity_Pickup& pickup, Entity_Player& player) +{ + constexpr int CHEST_MAGNETS = 3; + constexpr int BAG_MAGNETS = 2; + int superMagnets = player.GetTrinketMultiplier(TRINKET_SUPER_MAGNET); + + switch (pickup.variant) + { + case PICKUP_COIN: + case PICKUP_KEY: + case PICKUP_BOMB: + return true; + case PICKUP_HEART: + switch (pickup.subtype) + { + case HEART_FULL: + case HEART_HALF: + case HEART_DOUBLEPACK: + case HEART_SCARED: + return player.CanPickRedHearts(); + case HEART_SOUL: + case HEART_HALF_SOUL: + return player.CanPickSoulHearts(); + case HEART_BLACK: + return player.CanPickBlackHearts(); + case HEART_GOLDEN: + return player.CanPickGoldenHearts(); + case HEART_BLENDED: + return player.CanPickRedHearts() || player.CanPickSoulHearts(); + case HEART_BONE: + return player.CanPickBoneHearts(); + case HEART_ROTTEN: + return player.CanPickRottenHearts(); + } + return true; + case PICKUP_LIL_BATTERY: + return player.NeedsCharge(ACTIVE_SLOT_PRIMARY); + case PICKUP_GRAB_BAG: + case PICKUP_TRINKET: + return superMagnets >= BAG_MAGNETS; + case PICKUP_CHEST: + case PICKUP_SPIKEDCHEST: + case PICKUP_ETERNALCHEST: + case PICKUP_MIMICCHEST: + case PICKUP_OLDCHEST: + case PICKUP_WOODENCHEST: + case PICKUP_MEGACHEST: + case PICKUP_HAUNTEDCHEST: + case PICKUP_LOCKEDCHEST: + return superMagnets >= CHEST_MAGNETS; + } + return false; +} + +// Magneto opens the chests a main player comes near: the plain, wooden, red, spiked and mimic ones, and with Paper Clip +// the locked, eternal and old ones. +static void magneto_chest_open(Entity_Pickup& pickup, Entity_Player& player) +{ + constexpr float OPEN_DISTANCE_SQUARED = 6400; + bool isFree = is_listed({PICKUP_CHEST, PICKUP_WOODENCHEST, PICKUP_REDCHEST, PICKUP_SPIKEDCHEST, PICKUP_MIMICCHEST}, + pickup.variant); + bool isKeyed = is_listed({PICKUP_LOCKEDCHEST, PICKUP_ETERNALCHEST, PICKUP_OLDCHEST}, pickup.variant) && + player.GetTrinketMultiplier(TRINKET_PAPER_CLIP) > 0; + if (!isFree && !isKeyed) return; + Vector away = vector_make(pickup.pos.x - player.pos.x, pickup.pos.y - player.pos.y); + if (away.y * away.y + away.x * away.x < OPEN_DISTANCE_SQUARED) pickup.TryOpenChest(&player); +} + +// 006ed690 Magneto, Super Magnet and Broken Magnet pull free pickups to the nearest player who wants them (Broken +// Magnet only coins until doubled), and Magneto opens the chests a player comes near. Without a magnet a pickup flying +// over the pits lands again. The original also pulls coins to a second player of one kind, which needs co-op. void Entity_Pickup::update_magnet_attraction() { + constexpr float MAX_DISTANCE_SQUARED = 1e9f; + constexpr float PULL = 0.5f; + constexpr float PULL_FRICTION = 0.8f; PlayerManager& players = g_game->playerManager; + if (variant == PICKUP_THROWABLEBOMB) return; bool isMagnet = anyone_has_collectible(COLLECTIBLE_MAGNETO) || players.AnyoneHasTrinket(TRINKET_SUPER_MAGNET) || players.AnyoneHasTrinket(TRINKET_BROKEN_MAGNET); + if (!isMagnet) + { + if (entityGridCollisionClass == GRIDCOLL_WALLS) entityGridCollisionClass = GRIDCOLL_GROUND; + return; + } - if (isMagnet) reconstruction_missing("Entity_Pickup::update_magnet_attraction 006ed690: the magnets"); - if (entityGridCollisionClass == GRIDCOLL_WALLS) entityGridCollisionClass = GRIDCOLL_GROUND; + bool isPriceless = price == 0 || is_listed({PICKUP_KEY, PICKUP_BOMB, PICKUP_COIN, PICKUP_HEART, PICKUP_LIL_BATTERY}, variant); + Entity_Player* closest = nullptr; + float closestDistance = MAX_DISTANCE_SQUARED; + for (Entity_Player* player : isPriceless ? players.playerList : std::vector{}) + { + if (player->variant != PLAYER_VARIANT_PLAYER) continue; + bool isMagneto = player->HasCollectible(COLLECTIBLE_MAGNETO); + bool isStrong = isMagneto || player->GetTrinketMultiplier(TRINKET_BROKEN_MAGNET) >= 2; + bool isCoinPulled = player->GetTrinketMultiplier(TRINKET_BROKEN_MAGNET) > 0 && variant == PICKUP_COIN; + bool isPulling = isStrong || player->GetTrinketMultiplier(TRINKET_SUPER_MAGNET) > 0 || isCoinPulled; + if (isPulling && price == 0 && is_magnet_pulled(*this, *player)) + { + float distance = (pos.x - player->pos.x) * (pos.x - player->pos.x) + (pos.y - player->pos.y) * (pos.y - player->pos.y); + if (distance < closestDistance) + { + closest = player; + closestDistance = distance; + } + } + else if (isMagneto && IsChest(variant) && subtype != 0) magneto_chest_open(*this, *player); + } + if (closest) + { + Vector toward = vector_make(closest->pos.x - pos.x, closest->pos.y - pos.y); + float length = std::sqrt(toward.x * toward.x + toward.y * toward.y); + if (length > 0) toward = vector_make(1 / length * toward.x, 1 / length * toward.y); + velocity = vector_make((toward.x * PULL + velocity.x) * PULL_FRICTION, (toward.y * PULL + velocity.y) * PULL_FRICTION); + entityGridCollisionClass = GRIDCOLL_WALLS; + } + if (price == 0 && variant == PICKUP_COIN && players.playerList.size() > 1) + reconstruction_missing("Entity_Pickup::update_magnet_attraction 006ed690: the coins pulled to a second player"); } // 006e8ae0 A player touching the pickup collects it (hearts, coins, keys and bombs into their counters), plays its // pickup sound and animation and marks it dead. Coop ghosts, babies and players who cannot pick up take only a few // kinds. Whether the collision is solid: a priced or collected pickup and players' bombs pass through. // A priced pickup is bought with the player's coins or health, and chests open (entity_pickup_chest.cpp). Sacks, -// trinkets, familiars that collect and the rarer items and trinkets that change what a pickup gives are not +// familiars that collect and the rarer items and trinkets that change what a pickup gives are not // reconstructed yet. bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) { @@ -1397,6 +1495,9 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) case PICKUP_PILL: isPickedUp = pocket_item_collect(*this, *player); break; + case PICKUP_TRINKET: + isPickedUp = trinket_collect(*this, *player); + break; case PICKUP_CHEST: case PICKUP_SPIKEDCHEST: case PICKUP_ETERNALCHEST: @@ -1419,7 +1520,7 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) ending_pickup_touch(*this, *player); break; default: - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: sacks and trinkets"); + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: sacks"); } Room& room = *g_game->room; @@ -1445,6 +1546,7 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) g_game->scoreSheet.add_pickup_points(variant, collectedSubtype, pos); if (variant != PICKUP_COLLECTIBLE) PlayPickupSound(); if (paidPrice != 0) purchase_finish(*player, paidPrice); + else if (variant == PICKUP_TRINKET) trinket_lift(*this, *player); else if (variant != PICKUP_COLLECTIBLE) collect_finish(player); if ((variant == PICKUP_COLLECTIBLE || paidPrice != 0) && !player->proceduralItems.empty()) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the procedural items' pickup trigger"); @@ -1611,17 +1713,14 @@ bool Entity_Pickup::heart_collect(Entity_Player& player) return isPickedUp; } -// A coin into the player's coins, and a lucky penny's luck with its name shown. -// The pennies trinkets turn into other pickups are not reconstructed yet. +// A coin into the player's coins, the penny trinkets' effects (entity_player_trinkets.cpp), and a lucky penny's luck +// with its name shown. void Entity_Pickup::coin_collect(Entity_Player& player) { if (g_game->challenge == CHALLENGE_APRILS_FOOL) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Bloody Mary's coins"); player.AddCoins(GetCoinValue()); - - for (int trinket : PENNY_TRINKETS) - if (player.HasTrinket(trinket)) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a penny trinket"); + coin_trinkets_collect(*this, player, GetCoinValue()); if (subtype != COIN_LUCKYPENNY) return; StringTable& strings = g_manager->stringTable; diff --git a/src/entity_player.cpp b/src/entity_player.cpp index 10c09ad..a11abec 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -1,4 +1,5 @@ #include "entity_player.h" +#include "entity_player_characters.h" #include "data.h" #include "entity_effect.h" #include "entity_familiar.h" @@ -34,10 +35,6 @@ constexpr float GREED_START_SPOT_Y = 280; constexpr float BACKASSWARDS_START_OFFSET_Y = 100; constexpr int BETHANY_START_CHARGE = 4; constexpr int MAGDALENE_B_START_RED_HEARTS = 4; -constexpr float EDEN_SPEED_SPREAD = 0.3f; -constexpr float EDEN_FIRE_DELAY_SPREAD = 1.5f; -constexpr float EDEN_RANGE_SPREAD = 120; -constexpr float EDEN_SHOT_SPEED_SPREAD = 0.5f; constexpr int DEATHMATCH_HEART_SCALE = 8; // The shift triples Init seeds the player's generators with: one stepping the init seed, one for each list of @@ -323,6 +320,9 @@ void Entity_Player::stats_reset() edenDamage = 0; jarHearts = 0; jarFlies = 0; + firstVisitRooms = 0; + techFiveDelay = 0; + trinityShieldAngle = 0; gnawedLeafTimer = 0; lastActionTriggers = 0; bloodLustCounter = 0; @@ -685,12 +685,7 @@ void Entity_Player::eden_stats_roll(RNG& rng) else numBombs = (int)rng.RandomInt(2) + 1; } - edenDamage = rng.RandomFloat() * 2 - 1; - edenSpeed = rng.RandomFloat() * EDEN_SPEED_SPREAD - EDEN_SPEED_SPREAD / 2; - edenFireDelay = rng.RandomFloat() * EDEN_FIRE_DELAY_SPREAD - EDEN_FIRE_DELAY_SPREAD / 2; - edenTearRange = rng.RandomFloat() * EDEN_RANGE_SPREAD - EDEN_RANGE_SPREAD / 2; - edenShotSpeed = rng.RandomFloat() * EDEN_SHOT_SPEED_SPREAD - EDEN_SHOT_SPEED_SPREAD / 2; - edenLuck = rng.RandomFloat() * 2 - 1; + eden_offsets_roll(*this, rng); } // The part of 007bc740 that rolls Eden's starting pickups and items: a trinket on a third of the rolls, else maybe a @@ -1439,6 +1434,7 @@ void Entity_Player::release_weapons_and_effects(bool isRemoveEntities) } link_release(azazelsRageLaser, isRemoveEntities); link_release(breathOfLifeEffect, isRemoveEntities); + link_release(trinityShield, isRemoveEntities); link_release(megaBlastLaser, isRemoveEntities); link_release(markedTarget, isRemoveEntities); link_release(forgottenBody, isRemoveEntities); diff --git a/src/entity_player.h b/src/entity_player.h index 869c6b1..8e48d73 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -31,6 +31,7 @@ constexpr int HUD_HEART_FLASH_FRAMES = 4; constexpr int INVENTORY_SIZE = 16; constexpr int POCKET_SLOT_COUNT = 4; constexpr int POOP_SPELL_QUEUE_SIZE = 6; +constexpr int POOP_SPELL_BAG_SIZE = 20; constexpr int TRINKET_SLOT_COUNT = 2; constexpr int WEAPON_SLOT_COUNT = 5; constexpr uint32_t QUEUED_TOUCHED = 0x1; @@ -124,6 +125,28 @@ enum HeartKind : int HEART_ROTTEN = 12 }; +// The weight of a player Gnawed Leaf turned to stone. +constexpr float STATUE_MASS = 1000; + +// What the player did this frame (Lua's GetLastActionTriggers): bombed, moved, shot, used a pocket item or an +// active, or dropped. +enum ActionTrigger : int +{ + ACTION_TRIGGER_BOMB = 1 << 0, + ACTION_TRIGGER_MOVE = 1 << 1, + ACTION_TRIGGER_SHOOT = 1 << 2, + ACTION_TRIGGER_POCKET = 1 << 3, + ACTION_TRIGGER_ITEM = 1 << 4, + ACTION_TRIGGER_DROP = 1 << 5 +}; + +// Which side of the player a held entity is drawn on. +enum HeldSide +{ + HELD_BEHIND, + HELD_FRONT +}; + // Whether a pocket slot holds a pill, a card or an active item. enum PocketItemType : int { @@ -199,11 +222,13 @@ enum PlayerItemId : int COLLECTIBLE_BONE_SPURS = 683, COLLECTIBLE_HUNGRY_SOUL = 684, COLLECTIBLE_DOLLAR = 18, + COLLECTIBLE_LUNCH = 22, COLLECTIBLE_ROTTEN_MEAT = 26, COLLECTIBLE_BLOOD_BAG = 119, COLLECTIBLE_IV_BAG = 135, COLLECTIBLE_CRYSTAL_BALL = 158, COLLECTIBLE_PORTABLE_SLOT = 177, + COLLECTIBLE_BOOK_OF_SIN = 97, COLLECTIBLE_BUDDY_IN_A_BOX = 518, COLLECTIBLE_BATTERY_PACK = 603, COLLECTIBLE_BOOK_OF_BELIAL = 34, @@ -232,6 +257,7 @@ enum PlayerItemId : int COLLECTIBLE_LOKIS_HORNS = 87, COLLECTIBLE_SPELUNKER_HAT = 91, COLLECTIBLE_RELIC = 98, + COLLECTIBLE_LITTLE_STEVEN = 100, COLLECTIBLE_D6 = 105, COLLECTIBLE_PINKING_SHEARS = 107, COLLECTIBLE_WAFER = 108, @@ -248,12 +274,16 @@ enum PlayerItemId : int COLLECTIBLE_PONY = 130, COLLECTIBLE_MOMS_PURSE = 139, COLLECTIBLE_BOBS_CURSE = 140, + COLLECTIBLE_SCAPULAR = 142, COLLECTIBLE_NOTCHED_AXE = 147, + COLLECTIBLE_INFESTATION = 148, COLLECTIBLE_IPECAC = 149, COLLECTIBLE_MULLIGAN = 151, COLLECTIBLE_MUTANT_SPIDER = 153, COLLECTIBLE_PEEPER = 155, + COLLECTIBLE_HABIT = 156, COLLECTIBLE_BLOODY_LUST = 157, + COLLECTIBLE_CELTIC_CROSS = 162, COLLECTIBLE_EPIC_FETUS = 168, COLLECTIBLE_HOLY_WATER = 178, COLLECTIBLE_WHITE_PONY = 181, @@ -266,10 +296,16 @@ enum PlayerItemId : int COLLECTIBLE_BALL_OF_BANDAGES = 207, COLLECTIBLE_GUPPYS_COLLAR = 212, COLLECTIBLE_POLYPHEMUS = 169, + COLLECTIBLE_BLACK_BEAN = 180, + COLLECTIBLE_FANNY_PACK = 204, + COLLECTIBLE_SPIDERBABY = 211, COLLECTIBLE_ANEMIC = 214, + COLLECTIBLE_PLACENTA = 218, + COLLECTIBLE_OLD_BANDAGE = 219, COLLECTIBLE_ANTI_GRAVITY = 222, COLLECTIBLE_PYROMANIAC = 223, COLLECTIBLE_CRICKETS_BODY = 224, + COLLECTIBLE_PIGGY_BANK = 227, COLLECTIBLE_MONSTROS_LUNG = 229, COLLECTIBLE_BALL_OF_TAR = 231, COLLECTIBLE_STOP_WATCH = 232, @@ -277,7 +313,10 @@ enum PlayerItemId : int COLLECTIBLE_E_COLI = 236, COLLECTIBLE_KEY_PIECE_1 = 238, COLLECTIBLE_KEY_PIECE_2 = 239, + COLLECTIBLE_EXPERIMENTAL_TREATMENT = 240, COLLECTIBLE_INFAMY = 242, + COLLECTIBLE_TRINITY_SHIELD = 243, + COLLECTIBLE_TECH_5 = 244, COLLECTIBLE_20_20 = 245, COLLECTIBLE_BLUE_MAP = 246, COLLECTIBLE_BFFS = 247, @@ -291,18 +330,26 @@ enum PlayerItemId : int COLLECTIBLE_BLACK_CANDLE = 260, COLLECTIBLE_MISSING_PAGE_2 = 262, COLLECTIBLE_LEECH = 270, + COLLECTIBLE_BEST_BUD = 274, COLLECTIBLE_LIL_BRIMSTONE = 275, COLLECTIBLE_ISAACS_HEART = 276, COLLECTIBLE_DARK_BUM = 278, + COLLECTIBLE_HOW_TO_JUMP = 282, + COLLECTIBLE_D4 = 284, COLLECTIBLE_THE_JAR = 290, COLLECTIBLE_FLUSH = 291, COLLECTIBLE_SATANIC_BIBLE = 292, COLLECTIBLE_BUTTER_BEAN = 294, COLLECTIBLE_TAURUS = 299, + COLLECTIBLE_CANCER = 301, + COLLECTIBLE_VIRGO = 303, + COLLECTIBLE_LIBRA = 304, COLLECTIBLE_SCORPIO = 305, + COLLECTIBLE_AQUARIUS = 308, COLLECTIBLE_HOLY_MANTLE = 313, COLLECTIBLE_STRANGE_ATTRACTOR = 315, COLLECTIBLE_CURSED_EYE = 316, + COLLECTIBLE_GEMINI = 318, COLLECTIBLE_UNDEFINED = 324, COLLECTIBLE_BREATH_OF_LIFE = 326, COLLECTIBLE_POLAROID = 327, @@ -320,8 +367,10 @@ enum PlayerItemId : int COLLECTIBLE_INCUBUS = 360, COLLECTIBLE_SWORN_PROTECTOR = 363, COLLECTIBLE_EPIPHORA = 368, + COLLECTIBLE_CURSE_OF_THE_TOWER = 371, COLLECTIBLE_DEAD_EYE = 373, COLLECTIBLE_HOST_HAT = 375, + COLLECTIBLE_NO_2 = 378, COLLECTIBLE_RESTOCK = 376, COLLECTIBLE_BURSTING_SACK = 377, COLLECTIBLE_PAY_TO_PLAY = 380, @@ -332,6 +381,7 @@ enum PlayerItemId : int COLLECTIBLE_MARKED = 394, COLLECTIBLE_TECH_X = 395, COLLECTIBLE_TRACTOR_BEAM = 397, + COLLECTIBLE_PURITY = 407, COLLECTIBLE_EVIL_EYE = 410, COLLECTIBLE_LUSTY_BLOOD = 411, COLLECTIBLE_CAMBION_CONCEPTION = 412, @@ -339,6 +389,7 @@ enum PlayerItemId : int COLLECTIBLE_MORE_OPTIONS = 414, COLLECTIBLE_CROWN_OF_LIGHT = 415, COLLECTIBLE_SUCCUBUS = 417, + COLLECTIBLE_TELEPORT_2 = 419, COLLECTIBLE_BLACK_POWDER = 420, COLLECTIBLE_GLOWING_HOUR_GLASS = 422, COLLECTIBLE_NIGHT_LIGHT = 425, @@ -360,24 +411,39 @@ enum PlayerItemId : int COLLECTIBLE_METRONOME = 488, COLLECTIBLE_D_INFINITY = 489, COLLECTIBLE_DEEP_POCKETS = 416, + COLLECTIBLE_SHARD_OF_GLASS = 448, + COLLECTIBLE_VARICOSE_VEINS = 452, + COLLECTIBLE_POLYDACTYLY = 454, COLLECTIBLE_PLAN_C = 475, + COLLECTIBLE_EDENS_SOUL = 490, COLLECTIBLE_DUALITY = 498, COLLECTIBLE_EUCHARIST = 499, COLLECTIBLE_GREEDS_GULLET = 501, + COLLECTIBLE_LARGE_ZIT = 502, COLLECTIBLE_LITTLE_HORN = 503, COLLECTIBLE_DELIRIOUS = 510, + COLLECTIBLE_BOZO = 513, COLLECTIBLE_BROKEN_MODEM = 514, + COLLECTIBLE_MYSTERY_GIFT = 515, COLLECTIBLE_JUMPER_CABLES = 520, COLLECTIBLE_COUPON = 521, COLLECTIBLE_MOVING_BOX = 523, + COLLECTIBLE_LEPROSY = 525, COLLECTIBLE_DEATHS_LIST = 530, COLLECTIBLE_HAEMOLACRIA = 531, COLLECTIBLE_SCHOOLBAG = 534, + COLLECTIBLE_BLANKET = 535, + COLLECTIBLE_DIVORCE_PAPERS = 547, COLLECTIBLE_BROKEN_SHOVEL = 550, COLLECTIBLE_BROKEN_SHOVEL_1 = 550, COLLECTIBLE_BRITTLE_BONES = 549, + COLLECTIBLE_BROKEN_SHOVEL_2 = 551, + COLLECTIBLE_MOMS_SHOVEL = 552, COLLECTIBLE_GOLDEN_RAZOR = 555, + COLLECTIBLE_FORTUNE_COOKIE = 557, + COLLECTIBLE_IT_HURTS = 560, COLLECTIBLE_ALMOND_MILK = 561, + COLLECTIBLE_ROCK_BOTTOM = 562, COLLECTIBLE_DREAM_CATCHER = 566, COLLECTIBLE_PLAYDOUGH_COOKIE = 570, COLLECTIBLE_SOCKS = 571, @@ -390,13 +456,16 @@ enum PlayerItemId : int COLLECTIBLE_ALABASTER_BOX = 585, COLLECTIBLE_SOL = 588, COLLECTIBLE_LUNA = 589, + COLLECTIBLE_SATURNUS = 595, COLLECTIBLE_URANUS = 596, COLLECTIBLE_ACT_OF_CONTRITION = 601, COLLECTIBLE_MOMS_BRACELET = 604, COLLECTIBLE_ETERNAL_D6 = 609, + COLLECTIBLE_BIRD_CAGE = 610, COLLECTIBLE_LARYNX = 611, COLLECTIBLE_BIRTHRIGHT = 619, COLLECTIBLE_GENESIS = 622, + COLLECTIBLE_BOOSTER_PACK = 624, COLLECTIBLE_DEATH_CERTIFICATE = 628, COLLECTIBLE_KNIFE_PIECE_1 = 626, COLLECTIBLE_KNIFE_PIECE_2 = 627, @@ -412,11 +481,13 @@ enum PlayerItemId : int COLLECTIBLE_DAMOCLES_PASSIVE = 656, COLLECTIBLE_PASSIVE_DAMOCLES = 656, COLLECTIBLE_VASCULITIS = 657, + COLLECTIBLE_GIANT_CELL = 658, COLLECTIBLE_BINGE_EATER = 664, COLLECTIBLE_STRAW_MAN = 667, COLLECTIBLE_DADS_NOTE = 668, COLLECTIBLE_SAUSAGE = 669, COLLECTIBLE_REDEMPTION = 673, + COLLECTIBLE_CRACKED_ORB = 675, COLLECTIBLE_EMPTY_HEART = 676, COLLECTIBLE_ASTRAL_PROJECTION = 677, COLLECTIBLE_C_SECTION = 678, @@ -428,6 +499,8 @@ enum PlayerItemId : int COLLECTIBLE_BLOODY_GUST = 695, COLLECTIBLE_SALVATION = 696, COLLECTIBLE_TWISTED_PAIR = 698, + COLLECTIBLE_VENGEFUL_SPIRIT = 702, + COLLECTIBLE_HYPERCOAGULATION = 724, COLLECTIBLE_MY_LITTLE_UNICORN = 77, COLLECTIBLE_GAMEKID = 93, @@ -450,10 +523,14 @@ enum PlayerItemId : int COLLECTIBLE_BAG_OF_CRAFTING = 710, COLLECTIBLE_FLIP = 711, COLLECTIBLE_RECALL = 714, + COLLECTIBLE_HOLD = 715, COLLECTIBLE_EVERYTHING_JAR = 720, COLLECTIBLE_TMTRAINER = 721, COLLECTIBLE_DECAP_ATTACK = 729, COLLECTIBLE_STYE = 731, + COLLECTIBLE_REMOTE_DETONATOR = 137, + COLLECTIBLE_EVES_MASCARA = 310, + COLLECTIBLE_SPIRIT_SWORD = 579, TRINKET_POOL_SHIFT = 2, TRINKET_PETRIFIED_POOP = 2, TRINKET_PURPLE_HEART = 5, @@ -539,15 +616,63 @@ enum PlayerItemId : int TRINKET_FOUND_SOUL = 180, TRINKET_BROKEN_GLASSES = 187, TRINKET_ID_MASK = 0x7fff, + TRINKET_SWALLOWED_PENNY = 1, + TRINKET_CARTRIDGE = 8, + TRINKET_WIGGLE_WORM = 10, + TRINKET_RING_WORM = 11, + TRINKET_MOMS_TOENAIL = 16, + TRINKET_BLACK_LIPSTICK = 17, + TRINKET_MYSTERIOUS_CANDY = 25, + TRINKET_HOOK_WORM = 26, + TRINKET_WHIP_WORM = 27, + TRINKET_LIBERTY_CAP = 32, + TRINKET_UMBILICAL_CORD = 33, + TRINKET_CURVED_HORN = 35, + TRINKET_GOAT_HOOF = 37, + TRINKET_CANCER = 39, + TRINKET_RED_PATCH = 40, + TRINKET_BLOODY_PENNY = 49, + TRINKET_FLAT_PENNY = 51, + TRINKET_SAMSONS_LOCK = 58, + TRINKET_TAPE_WORM = 65, + TRINKET_LAZY_WORM = 66, + TRINKET_CRACKED_DICE = 67, + TRINKET_LOUSE = 70, + TRINKET_BLACK_FEATHER = 80, + TRINKET_EQUALITY = 103, + TRINKET_WISH_BONE = 104, + TRINKET_BAG_LUNCH = 105, + TRINKET_BAT_WING = 118, + TRINKET_HAIRPIN = 120, + TRINKET_BLESSED_PENNY = 131, + TRINKET_BROKEN_SYRINGE = 132, + TRINKET_LIGHTER = 135, + TRINKET_DEVILS_CROWN = 146, + TRINKET_CHARGED_PENNY = 147, + TRINKET_MOMS_LOCK = 153, + TRINKET_DICE_BAG = 154, + TRINKET_TORN_POCKET = 158, + TRINKET_KIDS_DRAWING = 169, + TRINKET_CURSED_PENNY = 172, + TRINKET_LIL_CLOT = 176, + TRINKET_THE_TWINS = 183, + TRINKET_BROKEN_REMOTE = 4, + TRINKET_M = 138, + TRINKET_PANIC_BUTTON = 149, + TRINKET_EXPANSION_PACK = 181, + NULLITEM_EXPLOSIVE_DIARRHEA = 0, + NULLITEM_STATUE = 4, NULLITEM_BLINDFOLD = 14, NULLITEM_BLANKFACE = 15, NULLITEM_CHRISTMAS = 16, NULLITEM_PURITY_GLOW = 17, NULLITEM_EMPTY_VESSEL = 18, + NULLITEM_HOLY_CARD = 46, NULLITEM_LAZARUS_BOOST = 49, NULLITEM_SPIN_TO_WIN = 50, NULLITEM_INTRUDER = 55, + NULLITEM_IT_HURTS = 57, NULLITEM_TOOTH_AND_NAIL_STATUE = 59, NULLITEM_REVERSE_CHARIOT = 63, NULLITEM_JUPITER_BODY_ANGEL = 76, @@ -561,20 +686,124 @@ enum PlayerItemId : int NULLITEM_FORGOTTEN_BOMB = 106, NULLITEM_JACOBS_CURSE = 109, NULLITEM_BLOODY_BABYLON = 110, + NULLITEM_DARK_ARTS = 111, NULLITEM_LOST_CURSE = 112, NULLITEM_SOUL_FORGOTTEN = 120, NULLITEM_SOUL_JACOB = 121, NULLITEM_JUDAS_BIRTHRIGHT_STAGE = 129, + NULLITEM_REVERSE_MAGICIAN = 60, + NULLITEM_REVERSE_HIGH_PRIESTESS = 61, + NULLITEM_REVERSE_EMPRESS = 62, + NULLITEM_REVERSE_STRENGTH = 64, + NULLITEM_REVERSE_DEVIL = 67, + NULLITEM_REVERSE_TEMPERANCE = 69, + NULLITEM_ERA_WALK = 42, + NULLITEM_HUGE_GROWTH = 41, + NULLITEM_PUBERTY = 1, + NULLITEM_I_FOUND_PILLS = 2, + NULLITEM_WIZARD = 6, + NULLITEM_OVERDOSE = 29, + NULLITEM_RELAX = 28, + NULLITEM_EXTRA_BIG_FAN = 107, + NULLITEM_HORSE_PUBERTY = 119, + NULLITEM_I_FOUND_HORSE_PILLS = 118, PILLEFFECT_FULL_HEALTH = 5, PILLEFFECT_HEALTH_UP = 7, PILLEFFECT_TELEPILLS = 19, PILLEFFECT_LARGER = 32, PILLEFFECT_SMALLER = 33, + PILLEFFECT_BAD_GAS = 0, + PILLEFFECT_BAD_TRIP = 1, + PILLEFFECT_BALLS_OF_STEEL = 2, + PILLEFFECT_BOMBS_ARE_KEYS = 3, + PILLEFFECT_EXPLOSIVE_DIARRHEA = 4, + PILLEFFECT_HEALTH_DOWN = 6, + PILLEFFECT_I_FOUND_PILLS = 8, + PILLEFFECT_PUBERTY = 9, + PILLEFFECT_PRETTY_FLY = 10, + PILLEFFECT_RANGE_DOWN = 11, + PILLEFFECT_RANGE_UP = 12, + PILLEFFECT_SPEED_DOWN = 13, + PILLEFFECT_SPEED_UP = 14, + PILLEFFECT_TEARS_DOWN = 15, + PILLEFFECT_TEARS_UP = 16, + PILLEFFECT_LUCK_DOWN = 17, + PILLEFFECT_LUCK_UP = 18, + PILLEFFECT_48HOUR_ENERGY = 20, + PILLEFFECT_HEMATEMESIS = 21, + PILLEFFECT_PARALYSIS = 22, + PILLEFFECT_SEE_FOREVER = 23, + PILLEFFECT_PHEROMONES = 24, + PILLEFFECT_AMNESIA = 25, + PILLEFFECT_LEMON_PARTY = 26, + PILLEFFECT_WIZARD = 27, + PILLEFFECT_PERCS = 28, + PILLEFFECT_ADDICTED = 29, + PILLEFFECT_RELAX = 30, + PILLEFFECT_QUESTIONMARK = 31, + PILLEFFECT_INFESTED_EXCLAMATION = 34, + PILLEFFECT_INFESTED_QUESTION = 35, + PILLEFFECT_POWER = 36, + PILLEFFECT_RETRO_VISION = 37, + PILLEFFECT_FRIENDS_TILL_THE_END = 38, + PILLEFFECT_X_LAX = 39, + PILLEFFECT_SOMETHINGS_WRONG = 40, + PILLEFFECT_IM_DROWSY = 41, + PILLEFFECT_IM_EXCITED = 42, + PILLEFFECT_GULP = 43, + PILLEFFECT_HORF = 44, + PILLEFFECT_SUNSHINE = 45, + PILLEFFECT_VURP = 46, + PILLEFFECT_SHOT_SPEED_DOWN = 47, + PILLEFFECT_SHOT_SPEED_UP = 48, + PILLEFFECT_EXPERIMENTAL = 49, COLLECTIBLE_BROTHER_BOBBY = 8, COLLECTIBLE_ABYSS = 706, COLLECTIBLE_LEMEGETON = 712, - COLLECTIBLE_ANIMA_SOLA = 722 + COLLECTIBLE_ANIMA_SOLA = 722, + COLLECTIBLE_MAGIC_MUSHROOM = 12, + COLLECTIBLE_ANARCHIST_COOKBOOK = 65, + COLLECTIBLE_WE_NEED_TO_GO_DEEPER = 84, + COLLECTIBLE_D20 = 166, + COLLECTIBLE_DADS_KEY = 175, + COLLECTIBLE_TELEPATHY_BOOK = 192, + COLLECTIBLE_BLANK_CARD = 286, + COLLECTIBLE_BOOK_OF_THE_DEAD = 545, + COLLECTIBLE_LEO = 302, + COLLECTIBLE_D1 = 476, + COLLECTIBLE_BELT = 28, + COLLECTIBLE_BLUE_CAP = 342, + COLLECTIBLE_MR_BOOM = 37, + COLLECTIBLE_TAMMYS_HEAD = 38, + COLLECTIBLE_MOMS_BRA = 39, + COLLECTIBLE_KAMIKAZE = 40, + COLLECTIBLE_MOMS_PAD = 41, + COLLECTIBLE_BOBS_ROTTEN_HEAD = 42, + COLLECTIBLE_DECK_OF_CARDS = 85, + COLLECTIBLE_MOMS_BOTTLE_OF_PILLS = 102, + COLLECTIBLE_GUPPYS_HEAD = 145, + COLLECTIBLE_PRAYER_CARD = 146, + COLLECTIBLE_CRACK_THE_SKY = 160, + COLLECTIBLE_CANDLE = 164, + COLLECTIBLE_RED_CANDLE = 289, + COLLECTIBLE_DOCTORS_REMOTE = 47, + COLLECTIBLE_LEMON_MISHAP = 56, + COLLECTIBLE_9_VOLT = 116, + COLLECTIBLE_DEAD_SEA_SCROLLS = 124, + COLLECTIBLE_GUPPYS_PAW = 133, + COLLECTIBLE_SPIDER_BUTT = 171, + COLLECTIBLE_SHARP_PLUG = 205, + COLLECTIBLE_D100 = 283, + COLLECTIBLE_MAGIC_FINGERS = 295, + COLLECTIBLE_D12 = 386, + COLLECTIBLE_D8 = 406, + COLLECTIBLE_MINE_CRAFTER = 427, + COLLECTIBLE_POTATO_PEELER = 487, + COLLECTIBLE_MR_ME = 527, + COLLECTIBLE_HALLOWED_GROUND = 543, + COLLECTIBLE_SHARP_KEY = 623, + COLLECTIBLE_STITCHES = 635 }; // The unlocks the player's code checks or grants (Lua's Achievement). @@ -603,8 +832,8 @@ enum PlayerAchievement : int enum PlayerChallenge : int { CHALLENGE_HAVE_A_HEART = 25, + CHALLENGE_PRIDE_DAY = 28, CHALLENGE_GUARDIAN = 30, - CHALLENGE_PONG = 30, CHALLENGE_BACKASSWARDS = 31, CHALLENGE_APRILS_FOOL = 32, CHALLENGE_ULTRA_HARD = 34, @@ -930,6 +1159,7 @@ public: std::array curseMistTrinkets{}; std::array ghostTrinkets{}; std::array bagOfCraftingContent{}; + std::array poopSpellBag{}; std::array poopSpellQueue{}; QueueItemData queuedItem; int bagOfCraftingHoldFrames = 0; @@ -959,6 +1189,7 @@ public: float bodyAngle = 0; float heightVelocity = 0; float ibsChargeBar = 0; + float poopSpellCharge = 0; int64_t lastShootTime = 0; int actionHoldDrop = 0; int bombPlaceDelay = 0; @@ -968,6 +1199,7 @@ public: int fireBlockCooldown = 0; int glowingHourglassIndex = -1; int lastActionTriggers = 0; + int lastPillColor = 0; int playerIndex = -1; int shootHeldFrames = 0; int slipperyTimer = 0; @@ -1008,6 +1240,7 @@ public: EntityPtr salvationEffect; EntityPtr tetheredEffect; EntityPtr tractorBeam; + EntityPtr trinityShield; EntityPtr twinPlayer; Entity_Player* backupPlayer = nullptr; Entity_Player* replacedPlayer = nullptr; @@ -1064,7 +1297,11 @@ public: int epiphoraCharge = 0; int eveSumptoriumCharge = 0; int forgottenSwapFormCooldown = 0; + int firstVisitRooms = 0; + int techFiveDelay = 0; + float trinityShieldAngle = 0; int gnawedLeafTimer = 0; + int momsHandTimer = 0; int evilCharmHazardFrames = 0; int hallowedGroundCountdown = 0; int immaculateConceptionState = 0; @@ -1096,6 +1333,8 @@ public: int reverseSunBoneHearts = 0; int samsonBerserkCharge = 0; int strengthMaxHearts = 0; + int edenBirthrightFrame = -1; + int poopSpellBagCount = 0; int itemHeartsOverflow = 0; short bloodLustCounter = 0; short brittleBonesUpgrades = 0; @@ -1217,7 +1456,7 @@ public: bool TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown) override; bool TryThrow(const EntityRef& source, const Vector& velocity, float height) override; bool HandleCollision(Entity* collider, bool isLow) override; - void AddCollectible(int type, int charge, bool isFirstTime, int activeSlot, int varData); + void AddCollectible(int type, int charge, bool isFirstTime, int activeSlot, int varData, int poolType = 0); void SetQueuedItem(const QueueItemData& queued); int tagged_item_count(uint64_t tag); void collectible_unlocks_check(int collectibleId, ItemConfig_Item& item); @@ -1285,7 +1524,6 @@ private: void costume_map_reset(int priority); Vector walk_direction_update(Vector input); void walk_velocity_update(Vector walkInput); - bool walking_items_has(); void walk_animation_update(); void sprite_scale_update(); void shoot_input_read(ShootInput& input); @@ -1535,6 +1773,11 @@ public: Entity_Player* InitTwin(int playerType); bool TryHoldEntity(Entity* entity); Entity* ThrowHeldEntity(Vector Velocity); + void held_entity_follow(); + void height_update(); + void height_land(); + void held_entity_render(Vector renderOffset, HeldSide side); + void held_throw_update(Vector shootDirection, bool isShooting); void AddFriendlyDip(int subtype, Vector position); void ThrowFriendlyDip(int subtype, Vector position, Vector target); void AddSoulCharge(int count); diff --git a/src/entity_player_actives.cpp b/src/entity_player_actives.cpp index eae43af..4fbb67c 100644 --- a/src/entity_player_actives.cpp +++ b/src/entity_player_actives.cpp @@ -1,6 +1,7 @@ #include "entity_player.h" #include "entity_player_characters.h" #include "entity_player_crafting.h" +#include "entity_player_trinkets.h" #include "console.h" #include "entity_familiar.h" #include "npc_ai.h" @@ -29,83 +30,6 @@ #include #include -// The items and trinkets the active item code names (Lua's CollectibleType and TrinketType). -enum ActiveItemId : int -{ - COLLECTIBLE_MR_BOOM = 37, - COLLECTIBLE_TAMMYS_HEAD = 38, - COLLECTIBLE_MOMS_BRA = 39, - COLLECTIBLE_KAMIKAZE = 40, - COLLECTIBLE_MOMS_PAD = 41, - COLLECTIBLE_DOCTORS_REMOTE = 47, - COLLECTIBLE_LEMON_MISHAP = 56, - COLLECTIBLE_ANARCHIST_COOKBOOK = 65, - COLLECTIBLE_9_VOLT = 116, - COLLECTIBLE_DEAD_SEA_SCROLLS = 124, - COLLECTIBLE_GUPPYS_PAW = 133, - COLLECTIBLE_SPIDER_BUTT = 171, - COLLECTIBLE_SHARP_PLUG = 205, - COLLECTIBLE_D100 = 283, - COLLECTIBLE_D4 = 284, - COLLECTIBLE_MAGIC_FINGERS = 295, - COLLECTIBLE_D12 = 386, - COLLECTIBLE_D8 = 406, - COLLECTIBLE_MINE_CRAFTER = 427, - COLLECTIBLE_POTATO_PEELER = 487, - COLLECTIBLE_MR_ME = 527, - COLLECTIBLE_HALLOWED_GROUND = 543, - COLLECTIBLE_SHARP_KEY = 623, - COLLECTIBLE_STITCHES = 635, - - TRINKET_BROKEN_REMOTE = 4, - TRINKET_M = 138, - TRINKET_PANIC_BUTTON = 149, - TRINKET_EXPANSION_PACK = 181 -}; - -// The sounds the active items play (Lua's SoundEffect). -enum ActiveSound : int -{ - ACTIVE_SOUND_BOOK_PAGE_TURN = 8, - ACTIVE_SOUND_DEATH_CARD = 33, - ACTIVE_SOUND_DEVIL_CARD = 34, - ACTIVE_SOUND_FART = 37, - ACTIVE_SOUND_MR_BOOM = 40, - ACTIVE_SOUND_GASCAN_POUR = 51, - ACTIVE_SOUND_VAMP_GULP = 157, - ACTIVE_SOUND_BATTERY_CHARGE = 170, - ACTIVE_SOUND_BEEP = 171, - ACTIVE_SOUND_ITEM_RECHARGE = 218, - ACTIVE_SOUND_VAMP_DOUBLE = 614, - ACTIVE_SOUND_D6_ROLL = 910, - ACTIVE_SOUND_ITEM_RAISE = 1017, - ACTIVE_SOUND_MOMS_BRA = 1035, - ACTIVE_SOUND_BIBLE = 1038, - ACTIVE_SOUND_RAZOR_BLADE = 1058 -}; - -// The entities and effects the active items look for or spawn (Lua's EntityType and EffectVariant). -enum ActiveEntity : int -{ - ACTIVE_ENTITY_MOM = 45, - ACTIVE_ENTITY_MOMS_HEART = 78, - ACTIVE_ENTITY_SATAN = 84, - ACTIVE_EFFECT_POOF = 15, - ACTIVE_EFFECT_PLAYER_CREEP_LEMON_MISHAP = 32, - ACTIVE_EFFECT_BATTERY = 49, - ACTIVE_BOMB_BIG = 1 -}; - -// The kinds of battery (Lua's BatterySubType). -enum BatterySubType : int -{ - BATTERY_NORMAL = 1, - BATTERY_MICRO = 2, - BATTERY_MEGA = 3, - BATTERY_GOLDEN = 4 -}; - -// The kinds of poop The Poop drops (Lua's GridPoopVariant). constexpr int ACHIEVEMENT_HALO = 27; constexpr int ACTIVE_PICKUP_HOLD_FRAMES = 30; constexpr int BATTERY_CHARGE = 6; @@ -258,7 +182,7 @@ static bool is_item_target(Entity* entity, Entity_Player& player) // Spawns the battery spark over the player that an overcharge or a 9 Volt refill shows. static void battery_effect_spawn(Entity_Player& player) { - EntitySpawn spawn = {.position = player.pos, .subType = 1, .type = ENTITY_EFFECT, .variant = ACTIVE_EFFECT_BATTERY, + EntitySpawn spawn = {.position = player.pos, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_HEART, .seed = Random()}; Entity* effect = g_game->Spawn(spawn); @@ -577,7 +501,7 @@ int Entity_Player::AddActiveCharge(int charge, int slot, bool isFlashHud, bool i if (isFlash) { g_game->hud.FlashChargeBar(this, slot); - sound_play(ACTIVE_SOUND_BATTERY_CHARGE); + sound_play(SOUND_BATTERYCHARGE); battery_effect_spawn(*this); } } @@ -585,7 +509,7 @@ int Entity_Player::AddActiveCharge(int charge, int slot, bool isFlashHud, bool i else if (added > 0 && isFlash) { g_game->hud.FlashChargeBar(this, slot); - sound_play(active.charge < maxCharge ? ACTIVE_SOUND_BEEP : ACTIVE_SOUND_ITEM_RECHARGE); + sound_play(active.charge < maxCharge ? SOUND_BEEP : SOUND_ITEMRECHARGE); } } @@ -673,7 +597,7 @@ void Entity_Player::DischargeActiveItem(uint32_t slot, bool isRemoved) else if (chargeType == CHARGE_NORMAL) { newCharge++; - sound_play(ACTIVE_SOUND_BEEP); + sound_play(SOUND_BEEP); } } battery_effect_spawn(*this); @@ -709,13 +633,6 @@ void Entity_Player::active_used_post(int slot, bool isRemoved, int chargeBeforeU reconstruction_missing("Entity_Player::active_used_post 007abf80 (M!, Butter! and Expansion Pack)"); } -// 005ca470 Book of Virtues' wisps for an active used. -void Entity_Player::TriggerBookOfVirtues(int, int) -{ - if (!HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) return; - reconstruction_missing("Entity_Player::TriggerBookOfVirtues 005ca470 (the wisps)"); -} - // 005c9930 Judas' Birthright: the bonus an active gives when Book of Belial's passive is held. void Entity_Player::trigger_book_of_belial_passive(int, int) { @@ -765,17 +682,17 @@ static void bible_use(ItemUse& use) { Entity_Player& player = use.player; - sound_play(ACTIVE_SOUND_BOOK_PAGE_TURN); - sound_play(ACTIVE_SOUND_BIBLE); + sound_play(SOUND_BOOK_PAGE_TURN_12); + sound_play(SOUND_BIBLE); for (Entity* entity : room_entities()) { - if (entity->type == ACTIVE_ENTITY_MOM || entity->type == ACTIVE_ENTITY_MOMS_HEART) + if (entity->type == ENTITY_MOM || entity->type == ENTITY_MOMS_HEART) { entity->Kill(EntityRef(&player)); g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_HALO); break; } - if (entity->type == ACTIVE_ENTITY_SATAN) + if (entity->type == ENTITY_SATAN) { player.lastDamageSource = EntityRef(entity); player.Kill(EntityRef(&player)); @@ -788,7 +705,7 @@ static void bible_use(ItemUse& use) // Book of Belial: the devil card's sound and the item raised. The damage comes from the room effect. static void book_of_belial_use(ItemUse& use) { - sound_play(ACTIVE_SOUND_DEVIL_CARD); + sound_play(SOUND_DEVIL_CARD); use_animate(use); } @@ -823,7 +740,7 @@ static void poop_use(ItemUse& use) game_butter_bean_fart( {.position = player.pos, .source = &player, .radius = THE_POOP_FART_RADIUS, .isShowEffect = false}); } - sound_play(ACTIVE_SOUND_FART); + sound_play(SOUND_FART); player.ShootCandle(Vector{}); } @@ -857,7 +774,7 @@ static void moms_bra_use(ItemUse& use) Entity_Player& player = use.player; EntityList_EL& entities = room_entities(); - sound_play(ACTIVE_SOUND_MOMS_BRA); + sound_play(SOUND_MOMS_BRA); for (size_t i = 0; i < entities.size(); i++) { int duration = g_manager->itemConfig.GetCollectible(COLLECTIBLE_MOMS_BRA)->maxCooldown; @@ -881,7 +798,7 @@ static void kamikaze_use(ItemUse& use) static void mr_boom_use(ItemUse& use) { Entity_Player& player = use.player; - EntitySpawn spawn = {.position = player.pos, .spawner = &player, .type = ENTITY_BOMB, .variant = ACTIVE_BOMB_BIG, + EntitySpawn spawn = {.position = player.pos, .spawner = &player, .type = ENTITY_BOMB, .variant = BOMB_BIG, .seed = Random()}; if (Entity_Bomb* bomb = dynamic_cast(g_game->Spawn(spawn))) @@ -891,7 +808,7 @@ static void mr_boom_use(ItemUse& use) bomb->isLoadCostumes = true; bomb->explosionDamage += MR_BOOM_DAMAGE_BONUS; } - g_manager->sfxManager.Play(ACTIVE_SOUND_MR_BOOM, {.frameDelay = MR_BOOM_SOUND_DELAY}); + g_manager->sfxManager.Play(SOUND_FETUS_LAND, {.frameDelay = MR_BOOM_SOUND_DELAY}); } // Teleport!: off to a random room of the floor. @@ -909,7 +826,7 @@ static void yum_heart_use(ItemUse& use) Entity_Player& player = use.player; if (player.variant != PLAYER_VARIANT_PLAYER) return; - sound_play(player.playerType == PLAYER_MAGDALENE_B ? ACTIVE_SOUND_VAMP_DOUBLE : ACTIVE_SOUND_VAMP_GULP); + sound_play(player.playerType == PLAYER_MAGDALENE_B ? SOUND_VAMP_DOUBLE : SOUND_VAMP_GULP); for (Entity_Player* each : g_game->playerManager.playerList) each->AddHearts(each == &player ? YUM_HEART_OWN_HEARTS : YUM_HEART_OTHER_HEARTS, false, false); } @@ -919,9 +836,9 @@ static void lemon_mishap_use(ItemUse& use) { Entity_Player& player = use.player; EntitySpawn spawn = {.position = player.pos, .spawner = &player, .type = ENTITY_EFFECT, - .variant = ACTIVE_EFFECT_PLAYER_CREEP_LEMON_MISHAP, .seed = Random()}; + .variant = EFFECT_PLAYER_CREEP_LEMON_MISHAP, .seed = Random()}; - sound_play(ACTIVE_SOUND_GASCAN_POUR); + sound_play(SOUND_GASCAN_POUR); g_game->Spawn(spawn)->Update(); use_animate(use); } @@ -963,7 +880,7 @@ static void pedestal_reroll(ItemUse& use, Entity_Pickup& pickup) if (use.player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && use.isWispAllowed && use.id == COLLECTIBLE_D6) reconstruction_missing("Entity_Player::UseActiveItem 005b39d0 (the D6's wisps)"); } - g_game->Spawn({.position = pickup.pos, .type = ENTITY_EFFECT, .variant = ACTIVE_EFFECT_POOF, .seed = Random()}); + g_game->Spawn({.position = pickup.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); } // The D6 and the Eternal D6: every pedestal item of the room rerolled. @@ -990,7 +907,7 @@ static void d6_use(ItemUse& use) } if (!use.isShowAnimation) return; - sound_play_local(player, ACTIVE_SOUND_D6_ROLL); + sound_play_local(player, SOUND_D6_ROLL); use_animate(use); } @@ -1006,7 +923,7 @@ static void razor_blade_use(ItemUse& use) player.damageCooldown = 0; player.TakeDamage(damage * (isFirst ? RAZOR_BLADE_FIRST_SCALE : 1), RAZOR_BLADE_DAMAGE_FLAGS, EntityRef(), DAMAGE_COUNTDOWN_FRAMES); - sound_play(ACTIVE_SOUND_RAZOR_BLADE); + sound_play(SOUND_RAZOR_BLADE); } // Spider Butt: every enemy slowed for the item's cooldown, hurt, and set to leave a spider when it dies. @@ -1016,7 +933,7 @@ static void spider_butt_use(ItemUse& use) if (player.variant != PLAYER_VARIANT_PLAYER) return; EntityList_EL& entities = room_entities(); - sound_play(ACTIVE_SOUND_DEATH_CARD); + sound_play(SOUND_DEATH_CARD); for (size_t i = 0; i < entities.size(); i++) { Entity* entity = entities[i]; @@ -1234,7 +1151,7 @@ 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); + npc_sound_play(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) @@ -1250,6 +1167,183 @@ void Game::ShowHallucination(int frames, int backdrop) room->backdrop.load_details(); } +// Holds the item up once, so a mod's use does not raise it again. +static void use_raise(ItemUse& use) +{ + use_animate(use); + use.isLuaAnimationAllowed = false; +} + +// The books whose effect is all in their room effect: their sound, the item raised. +static void sound_raise_use(ItemUse& use, int sound) +{ + sound_play(sound); + use_raise(use); +} + +// The items held up until fired or let go (Bob's Rotten Head, Doctor's Remote, the candles): the item lifted. +static void lift_use(ItemUse& use) +{ + use.player.SetItemState(use.id); + use.player.AnimateCollectible(use.id, "LiftItem", "PlayerPickupSparkle"); + if (use.id == COLLECTIBLE_CANDLE || use.id == COLLECTIBLE_RED_CANDLE) sound_play(SOUND_RED_CANDLE); +} + +// The Nail: a black heart with its sound. Its stomp comes from the room effect. +static void nail_use(ItemUse& use) +{ + if (use.player.variant != PLAYER_VARIANT_PLAYER) return; + sound_play(SOUND_MONSTER_YELL_A); + use.player.AddBlackHearts(1); +} + +// A Pony and the White Pony: a dash the way the player moves, when it moves. +static void pony_use(ItemUse& use) +{ + constexpr float PONY_DASH_SPEED = 10; + constexpr int PONY_DASH_FRAMES = 60; + + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER || vector_length_squared(player.velocity) <= 1) return; + + player.velocity = vector_scale(vector_normalized(player.velocity), PONY_DASH_SPEED); + player.ponyCharge = PONY_DASH_FRAMES; + player.contactHitList.clear(); + sound_play(SOUND_MONSTER_YELL_A); +} + +// Guppy's Paw: a heart container traded for three soul hearts, red health kept within the containers left. Judas' +// Birthright adds its damage effect for the first slot. +static void guppys_paw_use(ItemUse& use) +{ + constexpr int NULL_BELIAL_BIRTHRIGHT_PAW = 130; + + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER || player.maxHearts <= 1) return; + + sound_play(SOUND_VAMP_GULP); + player.maxHearts -= 2; + player.redHearts = std::min(player.redHearts, player.GetEffectiveMaxHearts()); + player.AddSoulHearts(6, false); + player.UpdateHeartDependentEffects(); + use_animate(use); + if (use.request.slot == ACTIVE_SLOT_PRIMARY && player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + player.temporaryEffects.AddNullEffect(NULL_BELIAL_BIRTHRIGHT_PAW, true, 1); +} + +// Guppy's Head: two to four blue flies, or as many wisps with Book of Virtues. +static void guppys_head_use(ItemUse& use) +{ + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + int count = (int)player.GetCollectibleRNG(COLLECTIBLE_GUPPYS_HEAD).RandomInt(3) + 2; + if (!player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) || !use.isWispAllowed) + player.AddBlueFlies(count, player.pos, nullptr); + else + for (int i = 0; i < count; i++) player.AddWisp(COLLECTIBLE_GUPPYS_HEAD, player.pos, false, false); +} + +// Notched Axe: the axe drawn for the room, once, its charge kept. +static void notched_axe_use(ItemUse& use) +{ + if (!use.player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_NOTCHED_AXE)) + { + use.player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_NOTCHED_AXE, false, 1); + sound_play(SOUND_NOTCHED_AXE); + } + use.result.isDischarge = false; + use.isAddEffect = false; +} + +// Blood Rights: the player hurt for a full heart (half on later uses in the room, more in a versus match), the +// Necronomicon's damage, the screen shaken and blood from the walls. A versus match keeps one effect. +static void blood_rights_use(ItemUse& use) +{ + constexpr float BLOOD_RIGHTS_DAMAGE = 2; + constexpr float BLOOD_RIGHTS_VERSUS_DAMAGE = 15; + constexpr int BLOOD_RIGHTS_SHAKE = 8; + constexpr int BLOOD_WALL_FRAMES = 10; + constexpr int BLOOD_WALL_DROPS = 5; + + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + + sound_play(SOUND_DEATH_CARD); + player.damageCooldown = 0; + float damage = 1; + if (player.temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_BLOOD_RIGHTS) < 1) damage = BLOOD_RIGHTS_DAMAGE; + if (g_game->deathmatchManager.is_active()) damage = BLOOD_RIGHTS_VERSUS_DAMAGE; + player.TakeDamage(damage, DAMAGE_RED_HEARTS | DAMAGE_INVINCIBLE, EntityRef(), DAMAGE_COUNTDOWN_FRAMES); + player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM}); + game_shake_screen(BLOOD_RIGHTS_SHAKE); + g_game->room->bloodFromWallsDuration = BLOOD_WALL_FRAMES; + g_game->room->bloodFromWallsCount = BLOOD_WALL_DROPS; + if (g_game->deathmatchManager.is_active() && player.temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_BLOOD_RIGHTS) > 1) + player.RemoveCollectible(COLLECTIBLE_BLOOD_RIGHTS, true, use.request.slot, true); + player.cacheFlags |= CACHE_FIREDELAY; + player.EvaluateItems(); +} + +// Telepathy for Dummies: homing tears from the room effect, the achievement when the player already has homing. +static void telepathy_book_use(ItemUse& use) +{ + constexpr int ACHIEVEMENT_TELEPATHY_HOMING = 389; + + sound_play(SOUND_TELEPATHY_DUMMY); + if ((use.player.tearFlags & TearFlags().set(TEAR_HOMING)).any()) + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_TELEPATHY_HOMING); + use_raise(use); +} + +// The Smelter: the held trinkets smelted for good, with its sound. +static void smelter_use(ItemUse& use) +{ + trinkets_smelt(use.player); + use.isLuaAnimationAllowed = false; + if (!use.isShowAnimation) return; + sound_play_local(use.player, SOUND_SMELTER); + use_animate(use); +} + +// Mom's Pad: every vulnerable enemy feared for Mom's Bra's cooldown, and a blue fly. +static void moms_pad_use(ItemUse& use) +{ + Entity_Player& player = use.player; + + sound_play(SOUND_MOMS_BRA); + if (player.variant != PLAYER_VARIANT_PLAYER) return; + int duration = g_manager->itemConfig.GetCollectible(COLLECTIBLE_MOMS_BRA)->maxCooldown; + for (Entity* entity : room_entities()) + if (entity->IsVulnerableEnemy(nullptr) && entity != &player) entity->AddFear(EntityRef(&player), duration, false); + player.AddBlueFlies(1, player.pos, nullptr); +} + +// Deck of Cards and Mom's Bottle of Pills: a card or a pill in the pockets, held up. Little Baggy turns the deck's +// cards into pills and Starter Deck the bottle's pills into cards, unless the player has both. +static void pocket_item_use(ItemUse& use) +{ + Entity_Player& player = use.player; + if (player.variant != PLAYER_VARIANT_PLAYER) return; + if (use.id == COLLECTIBLE_MOMS_BOTTLE_OF_PILLS) sound_play(SOUND_MOM_BOTTLE); + + bool isBaggy = player.HasCollectible(COLLECTIBLE_LITTLE_BAGGY); + bool isDeck = player.HasCollectible(COLLECTIBLE_STARTER_DECK); + bool isCard = use.id == COLLECTIBLE_DECK_OF_CARDS ? !isBaggy || isDeck : isDeck && !isBaggy; + uint32_t seed = player.GetCollectibleRNG(use.id).Next(); + use.isLuaAnimationAllowed = use.isShowAnimation; + if (isCard) + { + int card = ItemPool::GetCard(seed, true, false, false); + player.AddCard(card); + if (use.isShowAnimation) player.AnimateCard(card, "UseItem"); + return; + } + int pill = ItemPool::GetPill(seed); + player.AddPill(pill); + if (use.isShowAnimation) player.AnimatePill(pill, "UseItem"); +} + // 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) @@ -1297,6 +1391,49 @@ static void item_effect_run(ItemUse& use) return lemegeton_use(use); case COLLECTIBLE_ANIMA_SOLA: return anima_sola_use(use); + case COLLECTIBLE_HOLD: + return hold_use(use); + case COLLECTIBLE_BOBS_ROTTEN_HEAD: + case COLLECTIBLE_DOCTORS_REMOTE: + case COLLECTIBLE_CANDLE: + case COLLECTIBLE_RED_CANDLE: + return lift_use(use); + case COLLECTIBLE_SHOOP_DA_WHOOP: + return use.player.SetItemState(COLLECTIBLE_SHOOP_DA_WHOOP); + case COLLECTIBLE_BOOK_OF_SHADOWS: + return sound_raise_use(use, SOUND_BOOK_SHADOWS_START); + case COLLECTIBLE_ANARCHIST_COOKBOOK: + return sound_raise_use(use, SOUND_BOOK_PAGE_TURN_12); + case COLLECTIBLE_THE_NAIL: + return nail_use(use); + case COLLECTIBLE_GAMEKID: + return; + case COLLECTIBLE_PONY: + case COLLECTIBLE_WHITE_PONY: + return pony_use(use); + case COLLECTIBLE_GUPPYS_PAW: + return guppys_paw_use(use); + case COLLECTIBLE_GUPPYS_HEAD: + return guppys_head_use(use); + case COLLECTIBLE_PRAYER_CARD: + if (use.player.variant == PLAYER_VARIANT_PLAYER) use.player.AddEternalHearts(1); + return; + case COLLECTIBLE_NOTCHED_AXE: + return notched_axe_use(use); + case COLLECTIBLE_CRACK_THE_SKY: + case COLLECTIBLE_BOOK_OF_VIRTUES: + return use_animate(use); + case COLLECTIBLE_BLOOD_RIGHTS: + return blood_rights_use(use); + case COLLECTIBLE_TELEPATHY_BOOK: + return telepathy_book_use(use); + case COLLECTIBLE_SMELTER: + return smelter_use(use); + case COLLECTIBLE_MOMS_PAD: + return moms_pad_use(use); + case COLLECTIBLE_DECK_OF_CARDS: + case COLLECTIBLE_MOMS_BOTTLE_OF_PILLS: + return pocket_item_use(use); case COLLECTIBLE_BAG_OF_CRAFTING: { const char* animation = bag_of_crafting_use(use.player, use.request.slot); @@ -1336,7 +1473,7 @@ UseResult Entity_Player::UseActiveItem(const ActiveUse& request) use.isWispAllowed = use.isShowAnimation || (request.flags & USE_ALLOWWISPSPAWN); if (use.id < 0) reconstruction_missing("Entity_Player::UseActiveItem 005b39d0: glitched_item_effects_run 009e01b0"); - if (use.isShowAnimation) sound_play(ACTIVE_SOUND_ITEM_RAISE); + if (use.isShowAnimation) sound_play(SOUND_ITEM_RAISE); if (!use.item) { // The original goes on to read the missing item's cache flags and crashes: here the use ends. @@ -1401,7 +1538,7 @@ static void timed_items_recharge(Entity_Player& player) if (active.charge >= maxCharge) { g_game->hud.FlashChargeBar(&player, slot); - sound_play(ACTIVE_SOUND_BEEP); + sound_play(SOUND_BEEP); } } if (player.HasCollectible(COLLECTIBLE_BATTERY) && active.batteryCharge < maxCharge && step > 0) @@ -1500,7 +1637,6 @@ static void active_slot_use(Entity_Player& player, int slot, int itemStateBefore // did not change is put away after. static void active_trigger(Entity_Player& player, int slot) { - constexpr int ACTION_TRIGGER_ITEM = 0x10; constexpr int SHOOP_DA_WHOOP = 49; constexpr int UNHIDDEN_STATES[] = {0, COLLECTIBLE_PONY, COLLECTIBLE_WHITE_PONY, COLLECTIBLE_BOOMERANG}; @@ -1596,7 +1732,9 @@ bool is_temporary_effect_plain(const TemporaryEffect& effect) COLLECTIBLE_ABYSS, COLLECTIBLE_FLIP, COLLECTIBLE_LEMEGETON, - COLLECTIBLE_ANIMA_SOLA}; + COLLECTIBLE_ANIMA_SOLA, + COLLECTIBLE_HOLD, + COLLECTIBLE_BOOK_OF_VIRTUES}; 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_bombs.cpp b/src/entity_player_bombs.cpp index 42521a2..a9d261f 100644 --- a/src/entity_player_bombs.cpp +++ b/src/entity_player_bombs.cpp @@ -1,4 +1,5 @@ #include "entity_player.h" +#include "entity_player_characters.h" #include "active_items.h" #include "entity_bomb.h" #include "entity_laser.h" @@ -197,8 +198,8 @@ void Entity_Player::update_bomb_input() { bool isCast = isControlsEnabled && controlsCooldown < 1 && !HasEntityFlags(FLAG_FEAR) && input_is_action_triggered(ACTION_BOMB, controllerIndex, this); - if (isCast) lastActionTriggers |= 1; - if (isCast && poopMana > 0) reconstruction_missing("Entity_Player::update_bomb_input 00780f40: poop spells"); + if (isCast) lastActionTriggers |= ACTION_TRIGGER_BOMB; + if (isCast && poopMana > 0) poop_spell_cast(*this); return; } if (bombPlaceDelay >= 1) @@ -209,7 +210,7 @@ void Entity_Player::update_bomb_input() if (!AreControlsEnabled() || HasEntityFlags(FLAG_FEAR) || !input_is_action_triggered(ACTION_BOMB, controllerIndex, this)) return; - lastActionTriggers |= 1; + lastActionTriggers |= ACTION_TRIGGER_BOMB; for (Entity* partner : {twinPlayer.get(), parent && parent->is_player() ? parent.get() : nullptr}) { Entity_Player* other = partner ? partner->ToPlayer() : nullptr; diff --git a/src/entity_player_cards.cpp b/src/entity_player_cards.cpp new file mode 100644 index 0000000..e37c9d2 --- /dev/null +++ b/src/entity_player_cards.cpp @@ -0,0 +1,984 @@ +#include "entity_player.h" +#include "active_items.h" +#include "entity_effect.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_slot.h" +#include "entity_tear.h" +#include "entity_familiar.h" +#include "game.h" +#include "hud.h" +#include "level_generator.h" +#include "item_overlay.h" +#include "manager.h" +#include "npc_ai.h" +#include "pocket_items.h" +#include "room.h" +#include "room_grid.h" +#include "room_special.h" +#include +#include +#include + +// The room transition's flags Tarot Cloth's Hermit and Stars set. +enum CardTransitionFlag : uint32_t +{ + CARD_TRANSITION_TREASURE_DISCOUNT = 1, + CARD_TRANSITION_SHOP_DISCOUNT = 2 +}; + +constexpr int ACHIEVEMENT_MAGICIAN_HOMING = 389; +constexpr int WHEEL_CRANE_GAME_ACHIEVEMENT = 607; +constexpr int JUDGEMENT_ROTTEN_BEGGAR_ACHIEVEMENT = 614; +constexpr int BERKANO_LOCUSTS = 3; +constexpr int BERKANO_LOCUST_SUBTYPE = 25; +constexpr int BOSS_MOM = 6; +constexpr int DAEMONS_TAIL_HEART_ODDS = 5; +constexpr int DAGAZ_EVIL_CHARM_FRAMES = 600; +constexpr int DEATH_EVENT_COUNTER = 7; +constexpr int EMERGENCY_HANDS = 2; +constexpr int EMERGENCY_HOLD_FRAMES = 150; +constexpr int ALGIZ_FRAMES = 600; +constexpr int JUDGEMENT_DEVIL_ROLL = 3; +constexpr int JUDGEMENT_RARE_ROLL = 50; +constexpr int PLAYING_CARD_EMPTY = 2; +constexpr int SHARD_SHADOW_FRAMES = 90; +constexpr int SHARD_EFFECTS = 8; +constexpr int SUICIDE_KING_PICKUPS = 10; +constexpr int SUN_DAMAGE_COUNTDOWN = 30; +constexpr int VERSUS_HEARTS = 16; +constexpr int WHEEL_ROLL = 100; +constexpr int WHEEL_FORTUNE_MAX = 25; +constexpr int ACE_RNG_SHIFT = 1; +constexpr int HIGH_PRIESTESS_DELAY = 15; +constexpr int PRIESTESS_FIRST_TARGET = 1; +constexpr int SHARD_MAP_RADIUS = 3; +constexpr uint32_t SHARD_MAP_FLAGS = 5; +constexpr int SHARD_REROLL_SHIFT = 11; +constexpr int QUESTIONMARK_ERROR_ROOM = -2; +constexpr int SHOPKEEPER_ERROR = 2; +constexpr float CHAOS_SPEED = 10; +constexpr float CHAOS_INHERIT = 0.5f; +constexpr float RECALL_STEP_DEGREES = -90; +constexpr float RECALL_SPEED = 2; +constexpr float SUN_DAMAGE = 100; +constexpr float WHEEL_VOLUME = 1.2f; +constexpr int REVERSE_DEVIL_SOUND = 266; +constexpr std::array ACE_VARIANTS = {PICKUP_BOMB, PICKUP_COIN, PICKUP_KEY, PICKUP_HEART}; +constexpr std::array SUICIDE_KING_PICKUP_VARIANTS = {10, 20, 30, 40, 50, 60, 70, 90, 100, 300, 350, 360}; + +// Plays a sound the seeds may swap for a fart, at a volume. +static void card_sound_play(int sound, float volume) +{ + int id = sound; + + seed_fart_sound_override(&id); + g_manager->sfxManager.Play(id, {.volume = volume}); +} + +// Adds an item's effect for its own duration (twice that when doubled), wearing its costume unless the use hides it. +static void item_effect_add(PocketUse& use, ItemConfig_Item* item, int cooldownScale) +{ + TemporaryEffect effect(item); + + effect.cooldown = item->maxCooldown * cooldownScale; + use.player.temporaryEffects.AddEffect(effect, use.isAddCostume, 1); +} + +// Builds a slot machine on a free spot near the player. +static void slot_spawn(PocketUse& use, int variant) +{ + uint32_t seed = use.rng.Next(); + Vector position = room_free_pickup_position_find({.position = use.player.pos, .step = 40}); + + g_game->Spawn({.position = position, .type = ENTITY_SLOT, .variant = variant, .seed = seed})->AddEntityFlags(FLAG_APPEAR); +} + +// Teleports the player to a room of the floor, its index from a query. +static void card_teleport(PocketUse& use, int roomIndex) +{ + g_game->leaveDoor = -1; + g_game->StartRoomTransition({.player = &use.player, .animation = TRANSITION_TELEPORT, .roomIndex = roomIndex}); +} + +// Teleports to the first room of a type, when the floor has one. +static PocketUseEnd room_type_teleport(PocketUse& use, int roomType, bool isIgnoreGroup) +{ + int roomIndex = g_game->QueryRoomTypeIndex(roomType, false, use.rng, isIgnoreGroup); + if (roomIndex < 0) return POCKET_END_ANIMATE; + card_teleport(use, roomIndex); + return POCKET_END_SKIP_ANIMATION; +} + +// The Fool: back to the floor's first room. +static PocketUseEnd fool_use(PocketUse& use) +{ + g_game->leaveDoor = -1; + g_game->StartRoomTransition({.player = &use.player, .animation = TRANSITION_TELEPORT, .dimension = 0, + .roomIndex = g_game->startingRoomIdx}); + return POCKET_END_SKIP_ANIMATION; +} + +// The Magician: homing tears for the room, Book of Belial's damage too when doubled. +static PocketUseEnd magician_use(PocketUse& use) +{ + ItemConfig& config = g_manager->itemConfig; + + if ((use.player.tearFlags & TearFlags().set(TEAR_HOMING)).any()) + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_MAGICIAN_HOMING); + item_effect_add(use, config.GetCollectible(COLLECTIBLE_TELEPATHY_BOOK), 1); + if (use.isDoubled) item_effect_add(use, config.GetCollectible(COLLECTIBLE_BOOK_OF_BELIAL), 1); + return POCKET_END_ANIMATE; +} + +// The High Priestess's second foot, a little later at the runner-up. +static void priestess_foot_spawn(Entity_Effect* timer) +{ + uint32_t seed = Random(); + Entity* foot = g_game->Spawn({.position = timer->pos, .type = ENTITY_EFFECT, .variant = EFFECT_MOM_FOOT_STOMP, .seed = seed}); + + foot->target = timer->target.get(); + foot->Update(); +} + +// The High Priestess: Mom's foot stomps the toughest enemy (any enemy but a fireplace when none is vulnerable), and +// when doubled a second one stomps the runner-up. Never in Mom's fight. The room's first entity is never picked. +static PocketUseEnd high_priestess_use(PocketUse& use) +{ + Entity_Player& player = use.player; + Room& room = *g_game->room; + EntityList_EL& entities = room.GetEntities()->updateEL; + + Entity* best = &player; + Entity* runnerUp = &player; + if (!entities.empty() && room.bossId != BOSS_MOM) + { + float bestHealth = 0; + bool isVulnerableFound = false; + for (size_t i = PRIESTESS_FIRST_TARGET; i < entities.size(); i++) + { + Entity* entity = entities[i]; + if (!player.IsValidTarget(entity)) continue; + bool isEnemy = (g_game->deathmatchManager.is_active() && entity->type == ENTITY_PLAYER) || + (entity->type >= ENTITY_FIRST_ENEMY && entity->type < ENTITY_EFFECT && entity->type != ENTITY_FIREPLACE); + if (!entity->IsVulnerableEnemy(nullptr) && (!isEnemy || isVulnerableFound)) continue; + if (entity->isDead || entity->health < bestHealth) continue; + + runnerUp = best; + best = entity; + bestHealth = entity->health; + isVulnerableFound |= entity->IsVulnerableEnemy(nullptr); + } + } + if (!runnerUp || runnerUp == &player) runnerUp = best; + if (best) + { + Entity* foot = g_game->Spawn({.position = best->pos, .type = ENTITY_EFFECT, .variant = EFFECT_MOM_FOOT_STOMP, .seed = Random()}); + foot->target = best; + foot->Update(); + } + if (use.isDoubled && runnerUp) + { + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&priestess_foot_spawn), HIGH_PRIESTESS_DELAY, 0, false); + timer->pos = runnerUp->pos; + timer->target = runnerUp; + } + return POCKET_END_ANIMATE; +} + +// The Empress: Whore of Babylon's boost for the room (twice when doubled), its giant book the first time. +static PocketUseEnd empress_use(PocketUse& use) +{ + ItemConfig_Item* whore = g_manager->itemConfig.GetCollectible(COLLECTIBLE_WHORE_OF_BABYLON); + + if (!use.player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON)) + g_game->itemOverlay.Show(GIANTBOOK_EMPRESS, 3, nullptr); + item_effect_add(use, whore, 1); + if (use.isDoubled) item_effect_add(use, whore, 1); + return POCKET_END_ANIMATE; +} + +// The Emperor: off to the floor's boss room, with a soul heart when doubled and the room is new. +static PocketUseEnd emperor_use(PocketUse& use) +{ + int roomIndex = g_game->QueryRoomTypeIndex(ROOM_BOSS, false, use.rng, false); + if (roomIndex >= 0) + { + card_teleport(use, roomIndex); + use.isPlayAnimation = false; + } + if (use.isDoubled && g_game->GetRoomByIdx(roomIndex)->visitedCount == 0) use.player.AddSoulHearts(2, false); + return POCKET_END_ANIMATE; +} + +// The Hierophant and the Lovers: two soul or red hearts, three when doubled. +static PocketUseEnd hearts_card_use(PocketUse& use, int heartSubType) +{ + for (int i = 0; i < (use.isDoubled ? 3 : 2); i++) pocket_pickup_spawn(use, PICKUP_HEART, heartSubType); + return POCKET_END_ANIMATE; +} + +// The Chariot: My Little Unicorn's invincibility, for twice as long when doubled. +static PocketUseEnd chariot_use(PocketUse& use) +{ + item_effect_add(use, g_manager->itemConfig.GetCollectible(COLLECTIBLE_MY_LITTLE_UNICORN), use.isDoubled ? 2 : 1); + return POCKET_END_ANIMATE; +} + +// Justice: a heart (Daemon's Tail lets one in five through), a bomb, a key and a coin, twice when doubled. +static PocketUseEnd justice_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + for (int i = 0; i < (use.isDoubled ? 2 : 1); i++) + { + if (!player.HasTrinket(TRINKET_DAEMONS_TAIL) || player.GetTrinketRNG(TRINKET_DAEMONS_TAIL).RandomInt(DAEMONS_TAIL_HEART_ODDS) == 0) + pocket_pickup_spawn(use, PICKUP_HEART, 0); + pocket_pickup_spawn(use, PICKUP_BOMB, 0); + pocket_pickup_spawn(use, PICKUP_KEY, 0); + pocket_pickup_spawn(use, PICKUP_COIN, 0); + } + return POCKET_END_ANIMATE; +} + +// The Hermit and the Stars: off to the shop, or the planetarium (else the treasure room). Doubled, the room's wares +// come cheaper. +static PocketUseEnd shop_card_use(PocketUse& use, bool isStars) +{ + int roomIndex = -1; + if (isStars) + { + roomIndex = g_game->QueryRoomTypeIndex(ROOM_PLANETARIUM, false, use.rng, false); + if (roomIndex < 0 || g_game->GetRoomByIdx(roomIndex)->data->type != ROOM_PLANETARIUM) + roomIndex = g_game->QueryRoomTypeIndex(ROOM_TREASURE, false, use.rng, false); + } + else roomIndex = g_game->QueryRoomTypeIndex(ROOM_SHOP, false, use.rng, false); + if (roomIndex < 0) return POCKET_END_ANIMATE; + + card_teleport(use, roomIndex); + if (use.isDoubled) g_game->roomTransition.flags |= isStars ? CARD_TRANSITION_TREASURE_DISCOUNT : CARD_TRANSITION_SHOP_DISCOUNT; + return POCKET_END_SKIP_ANIMATION; +} + +// Wheel of Fortune: a slot machine, a fortune telling machine a quarter of the time, or a crane game (once unlocked) +// one time in a hundred and one. +static PocketUseEnd wheel_of_fortune_use(PocketUse& use) +{ + card_sound_play(SOUND_SUMMONSOUND, WHEEL_VOLUME); + int roll = (int)(Random() % (WHEEL_ROLL + 1)); + int variant = SLOT_MACHINE; + if (roll == 0 && g_manager->persistentGameData.Unlocked(WHEEL_CRANE_GAME_ACHIEVEMENT)) variant = SLOT_CRANE_GAME; + else if (roll <= WHEEL_FORTUNE_MAX) variant = SLOT_FORTUNE_TELLING_MACHINE; + slot_spawn(use, variant); + return POCKET_END_ANIMATE; +} + +// Strength: the Magic Mushroom's boost for the room, a heart container while under the limit, and a red heart. +static PocketUseEnd strength_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_MAGIC_MUSHROOM, use.isAddCostume, 1); + if (player.GetEffectiveMaxHearts() < player.GetHeartLimit(false)) + { + player.strengthMaxHearts++; + player.AddMaxHearts(2, false); + } + player.AddHearts(2, false, false); + return POCKET_END_ANIMATE; +} + +// Death: the Necronomicon's damage, its giant book and the death card's sound. +static PocketUseEnd death_use(PocketUse& use) +{ + g_game->itemOverlay.Show(GIANTBOOK_NECRONOMICON, 0, nullptr); + card_sound_play(SOUND_DEATH_CARD, 1); + use.player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM}); + g_manager->persistentGameData.IncreaseEventCounter(DEATH_EVENT_COUNTER, 1); + return POCKET_END_ANIMATE; +} + +// The Hanged Man, the Devil and the Tower: an item's effect for the room (the Devil with its giant book). +static PocketUseEnd room_item_card_use(PocketUse& use, int item) +{ + if (item == COLLECTIBLE_BOOK_OF_BELIAL) + { + card_sound_play(SOUND_DEVIL_CARD, 1); + g_game->itemOverlay.Show(GIANTBOOK_DEVIL, 3, nullptr); + } + use.player.temporaryEffects.AddEffect(TemporaryEffect(g_manager->itemConfig.GetCollectible(item)), use.isAddCostume, 1); + return POCKET_END_ANIMATE; +} + +// Temperance and Judgement: a blood donation machine, or a beggar of a random kind. +static PocketUseEnd temperance_use(PocketUse& use) +{ + card_sound_play(SOUND_SUMMONSOUND, WHEEL_VOLUME); + slot_spawn(use, SLOT_BLOOD_DONATION_MACHINE); + return POCKET_END_ANIMATE; +} + +// Judgement: a devil beggar a third of the time, else now and then a battery bum, a rotten beggar (once unlocked), a key +// master or a bomb bum, and a beggar otherwise. +static PocketUseEnd judgement_use(PocketUse& use) +{ + RNG& rng = use.rng; + int variant = SLOT_BEGGAR; + + if (rng.RandomInt(JUDGEMENT_DEVIL_ROLL) == 0) variant = SLOT_DEVIL_BEGGAR; + else if (rng.RandomInt(JUDGEMENT_RARE_ROLL) == 0) variant = SLOT_BATTERY_BUM; + else if (rng.RandomInt(JUDGEMENT_RARE_ROLL) == 0 && g_manager->persistentGameData.Unlocked(JUDGEMENT_ROTTEN_BEGGAR_ACHIEVEMENT)) + variant = SLOT_ROTTEN_BEGGAR; + else if (rng.RandomInt(JUDGEMENT_RARE_ROLL) == 0) variant = SLOT_KEY_MASTER; + else if (rng.RandomInt(JUDGEMENT_RARE_ROLL) == 0) variant = SLOT_BOMB_BUM; + slot_spawn(use, variant); + return POCKET_END_ANIMATE; +} + +// The Sun: every vulnerable enemy hurt (twice as hard when doubled), every live player healed, the map shown, the rain +// stopped and the curse of darkness lifted, with its giant book. +static PocketUseEnd sun_use(PocketUse& use) +{ + float damage = (use.isDoubled ? 2 : 1) * SUN_DAMAGE; + + for (Entity* entity : g_game->room->GetEntities()->updateEL) + if (entity->IsVulnerableEnemy(nullptr)) entity->TakeDamage(damage, 0, EntityRef(&use.player), SUN_DAMAGE_COUNTDOWN); + for (Entity_Player* player : g_game->playerManager.playerList) + if (!player->isDead) player->SetFullHearts(); + g_game->ShowMap(); + g_game->room->isRainStopped = true; + g_game->RemoveCurses(CURSE_OF_DARKNESS); + g_game->itemOverlay.Show(GIANTBOOK_SUN, 0, nullptr); + return POCKET_END_ANIMATE; +} + +// The 2 of Clubs, Diamonds, Spades and Hearts: double the bombs, coins, keys or red hearts, or two when there are +// none. Tainted Bethany's hearts are her blood charges, and a versus match counts hearts by eight. +static PocketUseEnd playing_card_use(PocketUse& use, int card) +{ + Entity_Player& player = use.player; + auto doubled = [](int count) { return count == 0 ? PLAYING_CARD_EMPTY : count; }; + + if (card == CARD_CLUBS_2) player.AddBombs(doubled(player.numBombs)); + else if (card == CARD_DIAMONDS_2) player.AddCoins(doubled(player.numCoins)); + else if (card == CARD_SPADES_2) player.AddKeys(doubled(player.numKeys)); + else if (player.playerType == PLAYER_BETHANY_B) player.AddBloodCharge(doubled(player.effectiveBloodCharge)); + else if (g_game->deathmatchManager.is_active()) + { + int hearts = player.redHearts == 0 ? VERSUS_HEARTS : player.redHearts; + player.redHearts += hearts & 7; + player.AddHearts(hearts >> 3, false, false); + } + else player.AddHearts(doubled(player.redHearts), false, false); + return POCKET_END_ANIMATE; +} + +// The aces: every rerollable free pickup but items, and every active enemy that can be rerolled, turned into a bomb, +// coin, key or heart, an enemy with a poof. Each new pickup keeps the old one's options group. +static PocketUseEnd ace_use(PocketUse& use, int card) +{ + Room& room = *g_game->room; + bool isVersus = g_game->deathmatchManager.is_active(); + std::vector targets; + + for (Entity* entity : room.GetEntities()->updateEL) + { + if (entity->isDead) continue; + if (entity->type == ENTITY_PICKUP) + { + auto* pickup = static_cast(entity); + if (pickup->CanReroll() && pickup->price == 0 && pickup->variant != PICKUP_COLLECTIBLE) targets.push_back(entity); + } + else if ((!isVersus || entity->type != ENTITY_PLAYER) && entity->type >= ENTITY_FIRST_ENEMY && + entity->type < ENTITY_EFFECT && entity->IsActiveEnemy(DEAD_EXCLUDED) && + static_cast(entity)->CanReroll()) + targets.push_back(entity); + } + + int variant = ACE_VARIANTS[card - CARD_ACE_OF_CLUBS]; + for (Entity* target : targets) + { + if ((isVersus && target->type == ENTITY_PLAYER) || (target->type >= ENTITY_FIRST_ENEMY && target->type < ENTITY_EFFECT)) + g_game->Spawn({.position = target->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + int options = target->type == ENTITY_PICKUP ? static_cast(target)->optionsPickupIndex : 0; + target->Remove(); + + Vector position = target->pos; + if (room.GetGridCollision(room.GetGridIndex(position)) != 0) + position = room_free_pickup_position_find({.position = position}); + RNG rng = rng_make(target->initSeed, ACE_RNG_SHIFT); + Entity* pickup = g_game->Spawn({.position = position, .spawner = &use.player, .type = ENTITY_PICKUP, .variant = variant, + .seed = rng.Next()}); + static_cast(pickup)->optionsPickupIndex = options; + } + return POCKET_END_ANIMATE; +} + +// The Joker: off to the devil room. +static PocketUseEnd joker_use(PocketUse& use) +{ + g_game->leaveDoor = -1; + int roomIndex = g_game->QueryRoomTypeIndex(ROOM_DEVIL, false, use.rng, false); + g_game->StartRoomTransition({.player = &use.player, .animation = TRANSITION_TELEPORT, .dimension = 0, .roomIndex = roomIndex}); + return POCKET_END_SKIP_ANIMATION; +} + +// Jera: every pickup of the room that may be duplicated, copied with its own seed, with its giant book. +static PocketUseEnd jera_use(PocketUse& use) +{ + std::vector pickups; + + for (Entity* entity : g_game->room->GetEntities()->updateEL) + if (entity->type == ENTITY_PICKUP) pickups.push_back(entity); + for (Entity* entity : pickups) + { + if (!static_cast(entity)->CanJeraDuplicate()) continue; + Vector position = room_free_pickup_position_find({.position = entity->pos, .step = 40}); + g_game->Spawn({.position = position, .spawner = &use.player, .subType = entity->subtype, .type = ENTITY_PICKUP, + .variant = entity->variant, .seed = entity->initSeed}); + } + g_game->itemOverlay.Show(GIANTBOOK_JERA, 4, nullptr); + return POCKET_END_ANIMATE; +} + +// The runes that use an item and show their giant book: Ehwaz (We Need To Go Deeper!) and Perthro (the D6). +static PocketUseEnd item_rune_use(PocketUse& use, int item, int overlay) +{ + use.player.UseActiveItem({.item = item, .flags = USE_NOANIM}); + g_game->itemOverlay.Show(overlay, 4, nullptr); + return POCKET_END_ANIMATE; +} + +// Dagaz: every curse lifted and a soul heart. In a versus match it charms for a while as Evil Charm does. +static PocketUseEnd dagaz_use(PocketUse& use) +{ + g_game->RemoveCurses(UINT32_MAX); + use.player.AddSoulHearts(2, false); + g_game->itemOverlay.Show(GIANTBOOK_DAGAZ, 4, nullptr); + if (g_game->deathmatchManager.is_active()) + { + TemporaryEffect effect(g_manager->itemConfig.GetCollectible(COLLECTIBLE_EVIL_CHARM)); + effect.cooldown = DAGAZ_EVIL_CHARM_FRAMES; + use.player.temporaryEffects.AddEffect(effect, true, 1); + } + return POCKET_END_ANIMATE; +} + +// Ansuz: the map and its secret rooms shown. +static PocketUseEnd ansuz_use(PocketUse&) +{ + g_game->ShowMap(); + g_game->ApplyBlueMapEffect(); + g_game->itemOverlay.Show(GIANTBOOK_ANSUZ, 4, nullptr); + return POCKET_END_ANIMATE; +} + +// Throws an Abyss locust of Berkano's kind from the player. +static void berkano_locust_spawn(Entity_Player& player) +{ + Entity* locust = g_game->Spawn({.position = player.pos, .spawner = &player, .subType = BERKANO_LOCUST_SUBTYPE, + .type = ENTITY_FAMILIAR, .variant = Entity_Familiar::ABYSS_LOCUST, .seed = Random()}); + static_cast(locust)->isNotCountedAsFollower = true; +} + +// Berkano: three locusts. +static PocketUseEnd berkano_use(PocketUse& use) +{ + for (int i = 0; i < BERKANO_LOCUSTS; i++) berkano_locust_spawn(use.player); + g_game->itemOverlay.Show(GIANTBOOK_BERKANO, 4, nullptr); + return POCKET_END_ANIMATE; +} + +// Algiz: ten seconds of Book of Shadows' shield. +static PocketUseEnd algiz_use(PocketUse& use) +{ + TemporaryEffect effect(g_manager->itemConfig.GetCollectible(COLLECTIBLE_BOOK_OF_SHADOWS)); + + effect.cooldown = ALGIZ_FRAMES; + use.player.temporaryEffects.AddEffect(effect, use.isAddCostume, 1); + g_game->itemOverlay.Show(GIANTBOOK_ALGIZ, 4, nullptr); + return POCKET_END_ANIMATE; +} + +// Chaos Card: the card thrown the way the player last moved (or aims), a little faster for its own speed. +static PocketUseEnd chaos_use(PocketUse& use) +{ + Entity_Player& player = use.player; + Vector direction = vector_normalized(player.lastVelocity); + + if (vector_is_zero(direction)) direction = player.movementVector; + if (vector_is_zero(direction)) direction = vector_make(0, 1); + uint32_t seed = Random(); + Vector velocity = vector_add(vector_scale(direction, CHAOS_SPEED), vector_scale(player.lastVelocity, CHAOS_INHERIT * 2)); + g_game->Spawn({.position = player.pos, .velocity = velocity, .spawner = &player, .type = ENTITY_TEAR, + .variant = TEAR_CHAOS_CARD, .seed = seed}); + return POCKET_END_SKIP_ANIMATION; +} + +// Credit Card: the room's price tags redrawn, which the card's effect then makes free. +static PocketUseEnd credit_use(PocketUse&) +{ + for (Entity* entity : g_game->room->GetEntities()->updateEL) + if (entity->type == ENTITY_PICKUP && static_cast(entity)->price != 0) + static_cast(entity)->update_price_sprite(0); + return POCKET_END_ANIMATE; +} + +// Rules Card: a random rule of the game shown, a seed hint one time in twenty. +static PocketUseEnd rules_use(PocketUse& use) +{ + constexpr float SEED_HINT_CHANCE = 0.05f; + + fortune_show(use.rng.RandomFloat() < SEED_HINT_CHANCE ? "Fortune_Seeds" : "Fortune_Rules"); + return POCKET_END_ANIMATE; +} + +// A Card Against Humanity: the room fills with poop on its next update. +static PocketUseEnd humanity_use(PocketUse&) +{ + card_sound_play(SOUND_FART, 1); + g_game->room->isCardAgainstHumanity = true; + return POCKET_END_ANIMATE; +} + +// Suicide King: the player dies, with no cause kept, and ten random pickups and items spill out. +static PocketUseEnd suicide_king_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + player.Kill(EntityRef()); + player.lastDamageFlags = 0; + player.lastDamageSource.type = 0; + player.lastDamageSource.variant = 0; + for (int i = 0; i < SUICIDE_KING_PICKUPS; i++) + { + uint32_t seed = use.rng.Next(); + Vector position = room_free_pickup_position_find({.position = player.pos, .step = 40}); + int variant = SUICIDE_KING_PICKUP_VARIANTS[use.rng.RandomInt(SUICIDE_KING_PICKUP_VARIANTS.size())]; + Entity* pickup = + g_game->Spawn({.position = position, .spawner = &player, .type = ENTITY_PICKUP, .variant = variant, .seed = seed}); + static_cast(pickup)->dropDelay = i; + } + return POCKET_END_SKIP_ANIMATION; +} + +// ? Card: the first slot's active used for free (the Glowing Hour Glass's saved rewinds kept straight), with Book of +// Virtues' wisp. With Blank Card it opens the I AM ERROR room instead, or drops a trapdoor, and the Blank Card goes. +static PocketUseEnd questionmark_use(PocketUse& use) +{ + Entity_Player& player = use.player; + int item = player.activeItems[ACTIVE_SLOT_PRIMARY].item; + + if (item == 0) return POCKET_END_ANIMATE; + if (item == COLLECTIBLE_BLANK_CARD) + { + if (g_game->IsNextStageAvailable()) + { + g_game->leaveDoor = -1; + g_game->StartRoomTransition({.player = &player, .animation = TRANSITION_TELEPORT, .roomIndex = QUESTIONMARK_ERROR_ROOM}); + } + else + { + Vector position = room_free_pickup_position_find({.position = player.pos}); + g_game->Spawn({.position = position, .spawner = &player, .type = ENTITY_SHOPKEEPER, .variant = SHOPKEEPER_ERROR, .seed = Random()}); + } + player.RemoveCollectible(item, false, ACTIVE_SLOT_PRIMARY, true); + return POCKET_END_ANIMATE; + } + if (item == COLLECTIBLE_GLOWING_HOUR_GLASS) + reconstruction_missing("Entity_Player::UseCard 007b2230 (? Card's Glowing Hour Glass rewinds)"); + player.UseActiveItem({.item = item, .flags = USE_OWNED, .slot = ACTIVE_SLOT_PRIMARY}); + player.TriggerBookOfVirtues(item, 0); + return POCKET_END_SKIP_ANIMATION; +} + +// Dice Shard: the D6 and the D20 together. +static PocketUseEnd dice_shard_use(PocketUse& use) +{ + use.player.UseActiveItem({.item = COLLECTIBLE_D6, .flags = USE_NOANIM}); + use.player.UseActiveItem({.item = COLLECTIBLE_D20, .flags = USE_NOANIM}); + return POCKET_END_ANIMATE; +} + +// Emergency Contact: two of Mom's hands each hold a vulnerable enemy down, the first one found and the nearest to it. +static PocketUseEnd emergency_contact_use(PocketUse&) +{ + std::array targets{}; + + for (Entity* entity : g_game->room->GetEntities()->updateEL) + { + if (!entity->IsVulnerableEnemy(nullptr)) continue; + if (!targets[0]) targets[0] = entity; + else if (!targets[1] || vector_length_squared(vector_sub(entity->pos, targets[0]->pos)) < + vector_length_squared(vector_sub(targets[1]->pos, targets[0]->pos))) + targets[1] = entity; + } + for (Entity* target : targets) + { + if (!target) continue; + auto* hand = static_cast( + g_game->Spawn({.position = target->pos, .type = ENTITY_EFFECT, .variant = EFFECT_MOMS_HAND_CONTACT, .seed = Random()})); + hand->target = target; + hand->SetTimeout(EMERGENCY_HOLD_FRAMES); + hand->Update(); + static_cast(target)->hold_set(EMERGENCY_HOLD_FRAMES, target->pos); + } + return POCKET_END_ANIMATE; +} + +// Holy Card: a Holy Mantle shield, unless one from the card is up. +static PocketUseEnd holy_use(PocketUse& use) +{ + TemporaryEffects& effects = use.player.temporaryEffects; + + if (effects.HasNullEffect(NULLITEM_HOLY_CARD)) return POCKET_END_ANIMATE; + effects.AddNullEffect(NULLITEM_HOLY_CARD, use.isAddCostume, 1); + effects.AddCollectibleEffect(COLLECTIBLE_HOLY_MANTLE, use.isAddCostume, 1); + return POCKET_END_ANIMATE; +} + +// Huge Growth: the screen shakes and the player grows for the room with Leo's stomp, once. +static PocketUseEnd huge_growth_use(PocketUse& use) +{ + ItemConfig_Item* growth = g_manager->itemConfig.GetNullItem(NULLITEM_HUGE_GROWTH); + + game_shake_screen(30); + if (use.player.temporaryEffects.has_item_effect(growth)) return POCKET_END_ANIMATE; + use.player.temporaryEffects.AddEffect(TemporaryEffect(growth), use.isAddCostume, 1); + use.player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_LEO, false, 1); + return POCKET_END_ANIMATE; +} + +// Ancient Recall: three random cards thrown out a quarter turn apart. +static PocketUseEnd ancient_recall_use(PocketUse& use) +{ + Entity_Player& player = use.player; + Vector position = room_free_pickup_position_find({.position = player.pos}); + + for (int i = 0; i < 3; i++) + { + uint32_t seed = use.rng.Next(); + int card = ItemPool::GetCard(player.GetCardRNG(CARD_ANCIENT_RECALL).Next(), true, false, false); + Vector velocity = vector_scale(vector_from_angle((float)i * RECALL_STEP_DEGREES), RECALL_SPEED); + g_game->Spawn({.position = position, .velocity = velocity, .spawner = &player, .subType = card, + .type = ENTITY_PICKUP, .variant = PICKUP_TAROTCARD, .seed = seed}); + } + return POCKET_END_ANIMATE; +} + +// Era Walk: slower enemies and a faster player for the room, as the Stop Watch does. +static PocketUseEnd era_walk_use(PocketUse& use) +{ + use.player.temporaryEffects.AddEffect(TemporaryEffect(g_manager->itemConfig.GetNullItem(NULLITEM_ERA_WALK)), true, 1); + g_game->room->temporaryEffects.AddCollectibleEffect(COLLECTIBLE_STOP_WATCH, true, 1); + return POCKET_END_ANIMATE; +} + +// Marks the rooms within a few steps of the current one on the map, as Rune Shard's first roll does. +static void shard_map_reveal() +{ + int current = g_game->currentRoomIdx; + if (current < 0 || current >= LEVEL_GRID_CELLS) return; + + int column = current % LEVEL_GRID_WIDTH; + int row = current / LEVEL_GRID_WIDTH; + for (int dx = -SHARD_MAP_RADIUS; dx <= SHARD_MAP_RADIUS; dx++) + { + for (int dy = -SHARD_MAP_RADIUS; dy <= SHARD_MAP_RADIUS; dy++) + { + int x = column + dx; + int y = row + dy; + if (x < 0 || x >= LEVEL_GRID_WIDTH || y < 0 || y >= LEVEL_GRID_WIDTH) continue; + if (std::abs(dx) + std::abs(dy) >= SHARD_MAP_RADIUS + 1) continue; + RoomDescriptor* room = g_game->GetRoomByIdx(y * LEVEL_GRID_WIDTH + x); + if (room->data) room->displayFlags |= SHARD_MAP_FLAGS; + } + } + g_game->minimap.Refresh(); +} + +// Rerolls one random pedestal of the room into an item, or empties it half the time, as Rune Shard's second roll. +static void shard_pedestal_reroll(RNG& cardRng) +{ + g_game->itemPool.ResetRoomBlacklist(); + Entity_Pickup* chosen = nullptr; + std::vector pedestals; + for (Entity* entity : g_game->room->GetEntities()->updateEL) + if (entity->type == ENTITY_PICKUP && entity->variant == PICKUP_COLLECTIBLE) pedestals.push_back(entity); + if (pedestals.empty()) return; + + RNG rng = rng_make(cardRng._seed, SHARD_REROLL_SHIFT); + int subType = rng.RandomInt(2) != 0 ? 0 : 36; + for (Entity* entity : pedestals) + { + auto* pickup = static_cast(entity); + if (pickup->isDead || pickup->subtype == 0 || !pickup->CanReroll()) continue; + if (pickup->optionsPickupIndex != 0 && pickup->timeout >= 0) continue; + if (rng.Next() != 0 || !chosen) chosen = pickup; + } + if (!chosen) return; + chosen->Morph(chosen->type, chosen->variant, subType, true, false, false); + chosen->isTouched = false; +} + +// Rune Shard: one of eight small rune effects. Greed mode rerolls the map and the Hagalaz rolls. +static PocketUseEnd rune_shard_use(PocketUse& use) +{ + Entity_Player& player = use.player; + int roll = (int)use.rng.RandomInt(SHARD_EFFECTS); + + while (g_game->IsGreedMode() && (roll == 0 || roll == 6)) roll = (int)use.rng.RandomInt(SHARD_EFFECTS); + switch (roll) + { + case 0: + shard_map_reveal(); + break; + case 1: + shard_pedestal_reroll(use.rng); + break; + case 2: + berkano_locust_spawn(player); + break; + case 3: + { + TemporaryEffect effect(g_manager->itemConfig.GetCollectible(COLLECTIBLE_BOOK_OF_SHADOWS)); + effect.cooldown = SHARD_SHADOW_FRAMES; + player.temporaryEffects.AddEffect(effect, use.isAddCostume, 1); + break; + } + case 4: + player.use_card_hagalaz(&use.rng); + break; + case 5: + player.UseActiveItem({.item = COLLECTIBLE_D1, .flags = USE_NOANIM}); + break; + case 6: + player.UseActiveItem({.item = COLLECTIBLE_WE_NEED_TO_GO_DEEPER, .flags = USE_NOANIM}); + break; + case 7: + player.AddSoulHearts(1, false); + break; + } + return POCKET_END_ANIMATE; +} + +// A null effect the reversed cards renew: the old one taken off first. +static PocketUseEnd null_effect_renew(PocketUse& use, int nullItem) +{ + use.player.temporaryEffects.RemoveNullEffect(nullItem, 1); + use.player.temporaryEffects.AddNullEffect(nullItem, use.isAddCostume, 1); + return POCKET_END_ANIMATE; +} + +// III - The Empress?: the effect renewed and two heart containers for the room (three when doubled), filled, within +// the heart limit. The containers it gave before are kept counted. +static PocketUseEnd reverse_empress_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + if (!player.temporaryEffects.HasNullEffect(NULLITEM_REVERSE_EMPRESS)) + g_game->itemOverlay.Show(GIANTBOOK_REVERSE_EMPRESS, 3, nullptr); + int given = player.reverseEmpressMaxHearts; + player.reverseEmpressMaxHearts = 0; + null_effect_renew(use, NULLITEM_REVERSE_EMPRESS); + player.reverseEmpressMaxHearts = given; + for (int i = (use.isDoubled ? 1 : 0) - given + 2; i > 0; i--) + { + if (player.GetEffectiveMaxHearts() < player.GetHeartLimit(false)) + { + player.reverseEmpressMaxHearts++; + player.AddMaxHearts(2, false); + } + player.AddHearts(2, false, false); + } + return POCKET_END_ANIMATE; +} + +// IV - The Emperor?: off to an extra boss room made for the floor, or a random room when none can be made. +static PocketUseEnd reverse_emperor_use(PocketUse& use) +{ + g_game->TryInitializeExtraBossRoom(use.player.GetCardRNG(CARD_REVERSE_EMPEROR).Next()); + if (!g_game->GetRoomByIdx(ROOM_EXTRA_BOSS_IDX)->data) + game_random_room_move(*g_game, false, use.player.GetCardRNG(CARD_REVERSE_EMPEROR).Next(), &use.player); + else + { + g_game->leaveDoor = -1; + g_game->StartRoomTransition({.player = &use.player, .animation = TRANSITION_TELEPORT, .dimension = 0, + .roomIndex = ROOM_EXTRA_BOSS_IDX}); + } + return POCKET_END_SKIP_ANIMATION; +} + +// XIV - Temperance?: five pill effects of the card's kind (ten when doubled). +static PocketUseEnd reverse_temperance_use(PocketUse& use) +{ + if (use.isCarBattery) return POCKET_END_RETURN; + for (int i = 0; i < (use.isDoubled ? 10 : 5); i++) + use.player.temporaryEffects.AddNullEffect(NULLITEM_REVERSE_TEMPERANCE, true, 1); + return POCKET_END_SKIP_ANIMATION; +} + +// XV - The Devil?: the angel's effect renewed with its giant book the first time, and the Bible used. +static PocketUseEnd reverse_devil_use(PocketUse& use) +{ + if (!use.player.temporaryEffects.HasNullEffect(NULLITEM_REVERSE_DEVIL)) + { + card_sound_play(REVERSE_DEVIL_SOUND, 1); + g_game->itemOverlay.Show(GIANTBOOK_REVERSE_DEVIL, 3, nullptr); + } + use.player.temporaryEffects.RemoveNullEffect(NULLITEM_REVERSE_DEVIL, 1); + use.player.temporaryEffects.AddNullEffect(NULLITEM_REVERSE_DEVIL, true, 1); + use.player.UseActiveItem({.item = COLLECTIBLE_BIBLE, .flags = USE_NOANIM | USE_NOCOSTUME}); + return POCKET_END_ANIMATE; +} + +// Runs a card's own effect. The ones a car battery's second use skips return at once for it. The cards not written +// yet stop the game. +PocketUseEnd card_effect_run(PocketUse& use, int card) +{ + bool isSingleUse = card <= CARD_HERMIT || (card >= CARD_CLUBS_2 && card <= CARD_ACE_OF_HEARTS); + if (isSingleUse && use.isCarBattery) return POCKET_END_RETURN; + + switch (card) + { + case CARD_FOOL: + return fool_use(use); + case CARD_MAGICIAN: + return magician_use(use); + case CARD_HIGH_PRIESTESS: + return high_priestess_use(use); + case CARD_EMPRESS: + return empress_use(use); + case CARD_EMPEROR: + return emperor_use(use); + case CARD_HIEROPHANT: + return hearts_card_use(use, HEART_SOUL); + case CARD_LOVERS: + return hearts_card_use(use, HEART_RED); + case CARD_CHARIOT: + return chariot_use(use); + case CARD_JUSTICE: + return justice_use(use); + case CARD_HERMIT: + return shop_card_use(use, false); + case CARD_WHEEL_OF_FORTUNE: + return wheel_of_fortune_use(use); + case CARD_STRENGTH: + return strength_use(use); + case CARD_HANGED_MAN: + return room_item_card_use(use, COLLECTIBLE_TRANSCENDENCE); + case CARD_DEATH: + return death_use(use); + case CARD_TEMPERANCE: + return temperance_use(use); + case CARD_DEVIL: + return room_item_card_use(use, COLLECTIBLE_BOOK_OF_BELIAL); + case CARD_TOWER: + return room_item_card_use(use, COLLECTIBLE_ANARCHIST_COOKBOOK); + case CARD_STARS: + return shop_card_use(use, true); + case CARD_MOON: + return room_type_teleport(use, ROOM_SECRET, false); + case CARD_SUN: + return sun_use(use); + case CARD_JUDGEMENT: + return judgement_use(use); + case CARD_WORLD: + g_game->ShowMap(); + return POCKET_END_ANIMATE; + case CARD_CLUBS_2: + case CARD_DIAMONDS_2: + case CARD_SPADES_2: + case CARD_HEARTS_2: + return playing_card_use(use, card); + case CARD_ACE_OF_CLUBS: + case CARD_ACE_OF_DIAMONDS: + case CARD_ACE_OF_SPADES: + case CARD_ACE_OF_HEARTS: + return ace_use(use, card); + case CARD_JOKER: + return joker_use(use); + case RUNE_HAGALAZ: + use.player.use_card_hagalaz(nullptr); + return POCKET_END_ANIMATE; + case RUNE_JERA: + return jera_use(use); + case RUNE_EHWAZ: + return item_rune_use(use, COLLECTIBLE_WE_NEED_TO_GO_DEEPER, GIANTBOOK_EHWAZ); + case RUNE_DAGAZ: + return dagaz_use(use); + case RUNE_ANSUZ: + return ansuz_use(use); + case RUNE_PERTHRO: + return item_rune_use(use, COLLECTIBLE_D6, GIANTBOOK_PERTHRO); + case RUNE_BERKANO: + return berkano_use(use); + case RUNE_ALGIZ: + return algiz_use(use); + case CARD_CHAOS: + return chaos_use(use); + case CARD_CREDIT: + return credit_use(use); + case CARD_RULES: + return rules_use(use); + case CARD_HUMANITY: + return humanity_use(use); + case CARD_SUICIDE_KING: + return suicide_king_use(use); + case CARD_GET_OUT_OF_JAIL: + use.player.UseActiveItem({.item = COLLECTIBLE_DADS_KEY, .flags = USE_NOANIM}); + return POCKET_END_ANIMATE; + case CARD_QUESTIONMARK: + return questionmark_use(use); + case CARD_DICE_SHARD: + return dice_shard_use(use); + case CARD_EMERGENCY_CONTACT: + return emergency_contact_use(use); + case CARD_HOLY: + return holy_use(use); + case CARD_HUGE_GROWTH: + return huge_growth_use(use); + case CARD_ANCIENT_RECALL: + return ancient_recall_use(use); + case CARD_ERA_WALK: + return era_walk_use(use); + case RUNE_SHARD: + return rune_shard_use(use); + case CARD_REVERSE_MAGICIAN: + return null_effect_renew(use, NULLITEM_REVERSE_MAGICIAN); + case CARD_REVERSE_HIGH_PRIESTESS: + return null_effect_renew(use, NULLITEM_REVERSE_HIGH_PRIESTESS); + case CARD_REVERSE_EMPRESS: + return reverse_empress_use(use); + case CARD_REVERSE_EMPEROR: + return reverse_emperor_use(use); + case CARD_REVERSE_STRENGTH: + g_game->room->temporaryEffects.AddNullEffect(NULLITEM_REVERSE_STRENGTH, true, 1); + return POCKET_END_ANIMATE; + case CARD_REVERSE_HANGED_MAN: + use.player.temporaryEffects.AddNullEffect(NULLITEM_REVERSE_HANGED_MAN, true, 1); + return POCKET_END_ANIMATE; + case CARD_REVERSE_DEATH: + use.player.UseActiveItem({.item = COLLECTIBLE_BOOK_OF_THE_DEAD, .flags = USE_NOANIM | USE_NOCOSTUME}); + return POCKET_END_ANIMATE; + case CARD_REVERSE_TEMPERANCE: + return reverse_temperance_use(use); + case CARD_REVERSE_DEVIL: + return reverse_devil_use(use); + case CARD_REVERSE_MOON: + return room_type_teleport(use, ROOM_ULTRASECRET, true); + case CARD_REVERSE_JUDGEMENT: + card_sound_play(SOUND_SUMMONSOUND, WHEEL_VOLUME); + slot_spawn(use, SLOT_SHOP_RESTOCK_MACHINE); + return POCKET_END_ANIMATE; + case CARD_CRACKED_KEY: + use.player.UseActiveItem({.item = COLLECTIBLE_RED_KEY, .flags = USE_NOANIM}); + return POCKET_END_ANIMATE; + case CARD_QUEEN_OF_HEARTS: + for (int i = (int)use.rng.RandomInt(20) + 1; i > 0; i--) pocket_pickup_spawn(use, PICKUP_HEART, HEART_RED); + return POCKET_END_ANIMATE; + } + if (card >= (int)g_manager->itemConfig.cards.size()) log_printf(LOG_WARN, "Warning: Card %d don't exist\n", card); + else reconstruction_missing(("Entity_Player::UseCard 007b2230 (card " + std::to_string(card) + ")").c_str()); + return POCKET_END_ANIMATE; +} diff --git a/src/entity_player_characters.cpp b/src/entity_player_characters.cpp index 8af5943..4ec851f 100644 --- a/src/entity_player_characters.cpp +++ b/src/entity_player_characters.cpp @@ -121,6 +121,10 @@ bool is_character_reconstructed(Entity_Player& player) case PLAYER_JACOB2_B: case PLAYER_ISAAC_B: case PLAYER_MAGDALENE_B: + case PLAYER_BLUEBABY_B: + case PLAYER_THEFORGOTTEN_B: + case PLAYER_THESOUL_B: + case PLAYER_LILITH_B: case PLAYER_CAIN_B: case PLAYER_SAMSON_B: case PLAYER_EVE_B: @@ -1083,12 +1087,14 @@ static void maggy_health_drain(Entity_Player& player) player.maggyHealthDrainCooldown = MAGGY_DRAIN_FRAMES; } -// Tainted Magdalene's part of 00794e50: while her health drains, one frame in five drops a small spot of red creep. -static void maggy_blood_drip(Entity_Player& player) +// The bleeding part of 00794e50: with Anemic's effect, bleeding out from her own wound, or while Tainted Magdalene's +// health drains, one frame in five drops a small spot of red creep. +static void blood_drip_update(Entity_Player& player) { - if (player.playerType != PLAYER_MAGDALENE_B || player.maggyHealthDrainCooldown <= 0 || - random_below(MAGGY_DRIP_ODDS) != 0) - return; + bool isBleeding = player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_ANEMIC) || + (player.HasEntityFlags(FLAG_BLEED_OUT) && player.bleedSource.entity == &player) || + (player.playerType == PLAYER_MAGDALENE_B && player.maggyHealthDrainCooldown > 0); + if (!isBleeding || random_below(MAGGY_DRIP_ODDS) != 0) return; uint32_t seed = Random(); Entity* drip = g_game->Spawn({.position = player.pos, .spawner = &player, .type = ENTITY_EFFECT, .variant = EFFECT_PLAYER_CREEP_RED, .seed = seed}); @@ -1152,8 +1158,9 @@ static void berserk_charge_update(Entity_Player& player) void character_frame_update(Entity_Player& player) { maggy_health_drain(player); - maggy_blood_drip(player); + blood_drip_update(player); berserk_charge_update(player); + blue_baby_poop_update(player); } // Tainted Magdalene's hug, part of 0078e1f0: touching a vulnerable enemy that is not a friend, with the last swing diff --git a/src/entity_player_characters.h b/src/entity_player_characters.h index b6ae8cc..27b9b21 100644 --- a/src/entity_player_characters.h +++ b/src/entity_player_characters.h @@ -5,6 +5,26 @@ constexpr int GIANTBOOK_WHORE_OF_BABYLON = 3; +// Tainted ???'s poop spells, as the queue and the HUD's frames hold them (REPENTOGON's PoopSpellType). +enum PoopSpell : char +{ + POOP_SPELL_NONE, + POOP_SPELL_POOP, + POOP_SPELL_CORNY, + POOP_SPELL_BURNING, + POOP_SPELL_STONE, + POOP_SPELL_STINKY, + POOP_SPELL_BLACK, + POOP_SPELL_HOLY, + POOP_SPELL_LIQUID, + POOP_SPELL_FART, + POOP_SPELL_BOMB, + POOP_SPELL_DIARRHEA, + POOP_SPELL_COUNT +}; + +struct ItemUse; + // The buttons Jacob and Esau share: the item button and the pocket button. enum TwinButton { @@ -50,5 +70,16 @@ bool is_maggy_draining(Entity_Player& player); void character_frame_update(Entity_Player& player); void tainted_magdalene_hug(Entity_Player& player, Entity& collider); +// Eden's rolled stat offsets, and Tainted Eden's glitch on a penalised hit (part of 007729d0). +void eden_offsets_roll(Entity_Player& player, RNG& rng); +void tainted_eden_glitch(Entity_Player& player); + +// Tainted ???'s spells cast with the bomb action, his poop charged by damage dealt, Hold's use and the poop piles the +// spells lift (entity_player_poop_spells.cpp, npc_poop.cpp). +void poop_spell_cast(Entity_Player& player); +void blue_baby_poop_update(Entity_Player& player); +void hold_use(ItemUse& use); +void npc_poop_update(Entity_NPC& npc); + // What a point of damage dealt adds to a damage charge (007d3560). float damage_charge_scale(); diff --git a/src/entity_player_collectibles.cpp b/src/entity_player_collectibles.cpp index 91a6ee0..c807dc1 100644 --- a/src/entity_player_collectibles.cpp +++ b/src/entity_player_collectibles.cpp @@ -1,4 +1,5 @@ #include "entity_player.h" +#include "entity_player_passives.h" #include "active_items.h" #include "entity_config.h" #include "entity_pickup.h" @@ -6,6 +7,9 @@ #include "hud.h" #include "log.h" #include "manager.h" +#include "music_manager.h" +#include "room.h" +#include "room_grid.h" #include #include @@ -34,13 +38,11 @@ enum RemovalItem : int NULLITEM_DOUBLED_B = 126 }; -// The collectibles whose loss does more than the counts: pockets and trinkets dropped for want of room, Mom's Box, -// The Jar, Purity, Greed's Gullet, Rock Bottom and Red Key. -constexpr int REMOVAL_EFFECT_ITEMS[] = {139, 251, 252, 290, 407, 416, 439, 454, 458, 501, 562, 580}; - -// The collectibles whose effect ends with more than its costume: Hourglass, My Little Unicorn, Gamekid, Dead Bird, -// How to Jump, Unicorn Stump, Taurus, Purity, Camo Undies, Wavy Cap, Mega Mush, Berserk, Dark Arts and the rest. -constexpr int EFFECT_END_ITEMS[] = {66, 77, 93, 117, 282, 298, 299, 409, 497, 582, 610, 625, 704, 705}; +// The collectibles whose effect ends with more than its costume that are not written yet: Camo Undies, Wavy Cap, +// Mega Mush, Berserk and Dark Arts. +constexpr int EFFECT_END_ITEMS[] = {497, 582, 625, 704, 705}; +constexpr int PURITY_STATE_COUNT = 4; +constexpr float REMOVED_DROP_STEP = 40; constexpr int DEAD_CAT_LIVES_PER_COPY = 9; constexpr int HEARTBREAK_BROKEN_HEARTS = 3; @@ -93,9 +95,87 @@ void Entity_Player::SwapActiveItems() g_game->hud.InvalidateActiveItem(this, -1); } +// The pocket items past the pockets left after losing Starter Deck, Little Baggy, Deep Pockets or Polydactyly drop from +// the last slots, the slots after each one moving up. +static void pocket_excess_drop(Entity_Player& player) +{ + int held = (int)std::ranges::count_if(player.pocketItems, [](const PocketItem& pocket) { return pocket.id != 0; }); + int excess = held - (int)player.GetMaxPocketItems(); + + for (int slot = POCKET_SLOT_COUNT - 1; slot >= 0 && excess > 0; slot--) + { + PocketItem& pocket = player.pocketItems[slot]; + if (pocket.id == 0 || pocket.type == POCKET_ACTIVE) continue; + + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({.position = player.pos, .step = REMOVED_DROP_STEP}); + g_game->Spawn({.position = spot, .spawner = &player, .subType = pocket.id, .type = ENTITY_PICKUP, + .variant = pocket.type == POCKET_CARD ? PICKUP_TAROTCARD : PICKUP_PILL, .seed = seed}); + std::move(player.pocketItems.begin() + slot + 1, player.pocketItems.end(), player.pocketItems.begin() + slot); + player.pocketItems.back() = {}; + excess--; + } +} + +// The second trinket drops after losing Mom's Purse or Belly Button. +static void second_trinket_drop(Entity_Player& player) +{ + uint32_t trinket = player.trinkets[1]; + if (trinket == 0) return; + + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({.position = player.pos, .step = REMOVED_DROP_STEP}); + g_game->Spawn({.position = spot, .spawner = &player, .subType = (int)trinket, .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, .seed = seed}); + player.trinkets[1] = 0; +} + +// What losing the last copy of a collectible does for itself: the pockets and trinkets it made room for drop, the +// Necromancer count drops, the Jar spills, Mom's Box takes Wooden Cross's mantles, Purity rolls its next stat, and +// Greed's Gullet and Red Key update. +static void collectible_last_removed(Entity_Player& player, int collectibleId) +{ + switch (collectibleId) + { + case COLLECTIBLE_STARTER_DECK: + case COLLECTIBLE_LITTLE_BAGGY: + case COLLECTIBLE_DEEP_POCKETS: + case COLLECTIBLE_POLYDACTYLY: + pocket_excess_drop(player); + return; + case COLLECTIBLE_MOMS_PURSE: + case COLLECTIBLE_BELLY_BUTTON: + second_trinket_drop(player); + return; + case REMOVAL_NECRONOMICON: + case REMOVAL_MISSING_PAGE_2: + player.IncrementPlayerFormCounter(PLAYER_FORM_NECROMANCER, -1); + return; + case COLLECTIBLE_THE_JAR: + player.UseActiveItem({.item = COLLECTIBLE_THE_JAR, .flags = USE_NOANIM}); + return; + case COLLECTIBLE_MOMS_BOX: + if (player.HasTrinket(TRINKET_WOODEN_CROSS)) player.remove_wooden_cross_mantles(); + return; + case COLLECTIBLE_PURITY: + player.temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_PURITY, 1); + player.purityState = (int)player.GetCollectibleRNG(COLLECTIBLE_PURITY).RandomInt(PURITY_STATE_COUNT); + player.RemoveCostume(g_manager->itemConfig.GetNullItem(NULLITEM_PURITY_GLOW)); + return; + case COLLECTIBLE_GREEDS_GULLET: + player.update_greeds_gullet(); + return; + case COLLECTIBLE_ROCK_BOTTOM: + reconstruction_missing("Entity_Player::TriggerCollectibleRemoved 0078ff90 (Rock Bottom, FUN_007d3e00)"); + case COLLECTIBLE_RED_KEY: + g_game->room->UpdateRedKey(); + return; + } +} + // 0078ff90 What losing a collectible undoes: Leo's and Magic Mushroom's count towards their form, Dead Cat's lives, and -// Heartbreak's broken hearts. With the last copy gone, the Missing Pages count drops, and an effect that clears on -// removal ends. Netplay's stats are offline. +// Heartbreak's broken hearts. With the last copy gone, the item's own loss runs (see collectible_last_removed), and an +// effect that clears on removal ends. Netplay's stats are offline. void Entity_Player::TriggerCollectibleRemoved(int collectibleId) { if (collectibleId == REMOVAL_MAGIC_MUSHROOM || collectibleId == REMOVAL_LEO) @@ -104,13 +184,8 @@ void Entity_Player::TriggerCollectibleRemoved(int collectibleId) deadCatLives = (short)std::min(deadCatLives, GetCollectibleNum(REMOVAL_DEAD_CAT) * DEAD_CAT_LIVES_PER_COPY); else if (collectibleId == REMOVAL_HEARTBREAK) AddBrokenHearts(-HEARTBREAK_BROKEN_HEARTS); - if (GetCollectibleNum(collectibleId) <= 0) - { - if (collectibleId == REMOVAL_NECRONOMICON || collectibleId == REMOVAL_MISSING_PAGE_2) - IncrementPlayerFormCounter(PLAYER_FORM_NECROMANCER, -1); - if (std::ranges::find(REMOVAL_EFFECT_ITEMS, collectibleId) != std::end(REMOVAL_EFFECT_ITEMS)) - reconstruction_missing("Entity_Player::TriggerCollectibleRemoved 0078ff90 (an item that made room)"); - } + if (GetCollectibleNum(collectibleId) > 0) return; + collectible_last_removed(*this, collectibleId); ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); if (temporaryEffects.HasCollectibleEffect(collectibleId) && item && item->isClearEffectsOnRemove) @@ -134,20 +209,64 @@ static void doubled_costume_remove(Entity_Player& player, int collectibleId) player.RemoveCostume(g_manager->itemConfig.GetNullItem(doubled.nullItem)); } +// What the end of a collectible's effect does after its costume comes off: the invincible items give the music its +// pitch back (Unicorn Stump its volume too), Taurus's colour fades, Dead Bird keeps its costume, and How to Jump and +// Empty Vessel land the player. +static void collectible_effect_end(Entity_Player& player, int collectibleId) +{ + MusicManager& music = g_manager->musicManager; + + switch (collectibleId) + { + case COLLECTIBLE_HOURGLASS: + case COLLECTIBLE_MY_LITTLE_UNICORN: + case COLLECTIBLE_GAMEKID: + case COLLECTIBLE_UNICORN_STUMP: + case COLLECTIBLE_TAURUS: + music.targetPitch = g_game->room->time_scale_update(); + if (collectibleId == COLLECTIBLE_UNICORN_STUMP) + music.VolumeSlide(1, STUMP_VOLUME_RATE); + if (collectibleId != COLLECTIBLE_TAURUS) return; + player.stop_costume_item_anims(); + player.cacheFlags |= CACHE_COLOR; + player.EvaluateItems(); + return; + case COLLECTIBLE_DEAD_BIRD: + case COLLECTIBLE_BIRD_CAGE: + player.AddCostume(g_manager->itemConfig.GetCollectible(collectibleId), false); + return; + case COLLECTIBLE_HOW_TO_JUMP: + case COLLECTIBLE_EMPTY_VESSEL: + if (player.variant != PLAYER_VARIANT_PLAYER) return; + if (collectibleId == COLLECTIBLE_HOW_TO_JUMP) player.entityCollisionClass = ENTCOLL_ALL; + player.cacheFlags |= CACHE_FLYING; + player.EvaluateItems(); + return; + } +} + // 00793970 An item's temporary effect ran out or was taken: a collectible's costume comes off unless the item keeps -// it, the doubled ones with it, and a null effect's costume comes off. The items whose end does more, and trinket -// effects and the null effects whose end does more, are not written yet. +// it, the doubled ones with it, then the collectible's own end runs (see collectible_effect_end), and a null effect's +// costume comes off. A trinket's effect takes its costume off (Faded Polaroid's fading colour too). The null effects +// and the items whose end does more are not written yet. void Entity_Player::trigger_collectible_effect_removed(ItemConfig_Item* item, int) { constexpr int NULL_EFFECTS_WITH_ENDS[] = {50, 62, 63, 66, 67, 70, 71, 101}; if (item->type == ITEM_NULL && std::ranges::find(NULL_EFFECTS_WITH_ENDS, item->id) == std::end(NULL_EFFECTS_WITH_ENDS)) return RemoveCostume(g_manager->itemConfig.GetNullItem(item->id)); + if (item->type == ITEM_TRINKET) + { + TryRemoveTrinketCostume(item->id); + if (item->id == TRINKET_FADED_POLAROID) ResetColor(); + return; + } if (!item->IsCollectible()) - reconstruction_missing("Entity_Player::trigger_collectible_effect_removed 00793970 (a trinket or null effect)"); + reconstruction_missing("Entity_Player::trigger_collectible_effect_removed 00793970 (a null effect)"); doubled_costume_remove(*this, item->id); if (std::ranges::find(EFFECT_END_ITEMS, item->id) != std::end(EFFECT_END_ITEMS)) reconstruction_missing("Entity_Player::trigger_collectible_effect_removed 00793970 (an item's own end)"); TryRemoveCollectibleCostume(item->id, true); + collectible_effect_end(*this, item->id); } // 0078f840 Takes a collectible from the player: a voided active leaves the Void, a helper's item goes from its diff --git a/src/entity_player_costumes.cpp b/src/entity_player_costumes.cpp index 0853d48..586182e 100644 --- a/src/entity_player_costumes.cpp +++ b/src/entity_player_costumes.cpp @@ -3,6 +3,7 @@ #include "log.h" #include "manager.h" #include "room_render.h" +#include "weapon_umbilical_whip.h" #include #include #include @@ -10,10 +11,18 @@ constexpr float BLEED_OUT_TINT_HEALTH = 150; constexpr int REVERSE_CHARIOT_FLASH_FRAMES = 90; -constexpr float STATUE_MASS = 1000; constexpr float HEAD_LIFT_PER_HEAD_SCALE = 2.5f; constexpr float HEAD_LIFT_PER_SQUASH = 8; constexpr std::string_view SUB_ANIM_PREFIX = "SubAnim"; +constexpr float GELLO_FRAME_HEIGHT = 96; + +// Tainted Lilith's whip as her costume shows it (Weapon_UmbilicalWhip::whipLook): 0 without one, 1 hidden, 2 out. +static int gello_look_get(Entity_Player& player) +{ + Weapon* weapon = player.weapons[0] ? player.weapons[0].get() : player.weapons[1].get(); + bool isWhip = weapon && weapon->weaponType == WEAPON_UMBILICAL_WHIP; + return isWhip ? static_cast(weapon)->whipLook : 0; +} // Tainted Magdalene's squash and stretch over a hug's last frames (the exe's table at 00b6bc98), and how far it lifts // her head. @@ -93,10 +102,9 @@ static void layer_look_read(Entity_Player& player, LayerLook& look) if (const NullFrame* transform = player.costumeSpriteDescs[body.index].sprite.GetNullFrame("HeadTransform"); transform && transform->isVisible) { - if (player.playerType == PLAYER_LILITH_B) - reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Lilith's head over Gello)"); look.headOffset = transform->pos; look.headSize = transform->scale; + if (player.playerType == PLAYER_LILITH_B) look.headOffset.y -= (float)(gello_look_get(player) * 2); } if (player.playerType == PLAYER_THEFORGOTTEN_B) look.headOffset.y += player.forgottenBHeight; @@ -189,7 +197,8 @@ void Entity_Player::costume_layers_update() } worn.insert(map.index); if (map.isBodyLayer && is_null_costume(costume, NULLITEM_LILITH_B)) - reconstruction_missing("Entity_Player::Update 00782af0 (Tainted Lilith's Gello costume frame)"); + if (LayerState* gello = costume.sprite.GetLayer(map.layerId)) + gello->cropOffset.y = IsHoldingItem() ? 0 : (float)gello_look_get(*this) * GELLO_FRAME_HEIGHT; } if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; @@ -259,3 +268,30 @@ void Entity_Player::body_costumes_speed_set(float speed) for (PlayerCostumeMap& map : playerCostumeMap) if (map.index >= 0 && map.isBodyLayer) costumeSpriteDescs[map.index].sprite.playbackSpeed = speed; } + +// 007ad5a0 The costumes of a collectible stop playing its own animation (not for a co-op ghost). +void Entity_Player::ClearCollectibleAnim(int collectible) +{ + if (isCoopGhost) return; + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectible); + for (PlayerCostumeMap& map : playerCostumeMap) + if (map.index >= 0 && costumeSpriteDescs[map.index].item == item) costumeSpriteDescs[map.index].isItemAnimPlay = false; +} + +// 007ad680 Whether a collectible's own animation ended on its costumes: true at the first one done with a non looping +// animation, or when none plays it. +bool Entity_Player::IsCollectibleAnimFinished(int collectible, std::string_view animName) +{ + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectible); + bool isFinished = true; + for (PlayerCostumeMap& map : playerCostumeMap) + { + if (map.index < 0) continue; + CostumeSpriteDesc& costume = costumeSpriteDescs[map.index]; + if (!costume.isItemAnimPlay || costume.item != item) continue; + const AnimationData* animation = costume.sprite.animState.animData; + if (costume.sprite.IsFinished(animName) && (!animation || !animation->isLooping)) return true; + isFinished = false; + } + return isFinished; +} diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index e437f29..403fc18 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -3,6 +3,8 @@ #include "entity_npc.h" #include "entity_player.h" #include "entity_player_characters.h" +#include "entity_player_passives.h" +#include "entity_player_trinkets.h" #include "entity_tear.h" #include "game.h" #include "level.h" @@ -17,11 +19,9 @@ constexpr int COLLECTIBLE_BINKY = 438; constexpr int COLLECTIBLE_CONE_HEAD = 457; constexpr int COLLECTIBLE_DULL_RAZOR = 486; -constexpr int COLLECTIBLE_HYPERCOAGULATION = 724; constexpr int COLLECTIBLE_JELLY_BELLY = 690; constexpr int COLLECTIBLE_MARBLES = 538; constexpr int COLLECTIBLE_METAL_PLATE = 449; -constexpr int COLLECTIBLE_SCAPULAR = 142; constexpr int COLLECTIBLE_SPIRIT_SHACKLES = 674; constexpr int TRINKET_BLIND_RAGE = 81; constexpr int TRINKET_CROW_HEART = 107; @@ -34,12 +34,8 @@ constexpr int NULLITEM_SHACKLES_GHOST = 101; constexpr int SAMSON_B_HIT_CHARGE = 10000; constexpr int BLEED_OUT_HEALTH = 600; -// The items and trinkets a landed hit sets off, by id, from Infestation's flies to Tonsil and Pinking Shears. -constexpr int HIT_COLLECTIBLES[] = {148, 525, 658, 696, 162, 610, 274, 156, 180, 214, 204, 219, 225, 227, 211, 262, - 301, 303, 392, 371, 407, 412, 448, 452, 560, 675, 702, 502, 513}; -constexpr int HIT_TRINKETS[] = {40, 48, 29, 1, 8, 67, 158, 97, 105, 33, 104, 122}; -constexpr int CROWN_OF_LIGHT = 415; -constexpr int HYPERCOAGULATION_IGNORED = 0x10040000; +// Zodiac's sign a landed hit may set off, until the zodiac's hits are written. +constexpr int ZODIAC = 392; constexpr int ENTITY_SEGMENTED_WORM = 903; constexpr int ENTITY_DAMAGE_RELAY = 966; @@ -227,6 +223,19 @@ static int damage_cooldown_scale(int frames) return frames > COOLDOWN_SCALE_MIN - 1 ? frames >> COOLDOWN_SCALE_SHIFT : 1; } +// Blind Rage's and Finger Bone's part of 007729d0: Blind Rage stretches the invincibility frames, and Finger Bone +// gives a bone heart one hit in 25 (12, 8 with stronger copies). +static void blind_rage_finger_bone_hit(Entity_Player& player) +{ + constexpr int FINGER_BONE_ODDS[] = {25, 12, 8}; + if (player.HasTrinket(TRINKET_BLIND_RAGE)) + player.damageCooldown = damage_cooldown_scale(player.GetTrinketMultiplier(TRINKET_BLIND_RAGE) * 2) * player.damageCooldown; + if (!player.HasTrinket(TRINKET_FINGER_BONE)) return; + int multiplier = player.GetTrinketMultiplier(TRINKET_FINGER_BONE); + int odds = FINGER_BONE_ODDS[multiplier == 2 ? 1 : multiplier == 3 ? 2 : 0]; + if (player.GetTrinketRNG(TRINKET_FINGER_BONE).RandomInt((uint32_t)odds) == 0) player.AddBoneHearts(1); +} + // The bestiary count an enemy adds to, unless the save is frozen or the enemy has no page. static void bestiary_count_add(std::map& counts, int type, int variant) { @@ -415,17 +424,65 @@ static int hearts_remove(Entity_Player& player, int amount, uint64_t damageFlags 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 -// Samson's rage. Bleeding out restarts its timer. -static void hit_items_check(Entity_Player& player, uint64_t damageFlags, bool isPenalized) +// 007db2d0 Spends one of the Holy Mantles Wooden Cross lends (one per copy, two at most, beyond those spent), moving +// one from the lent half of the stacks to the spent half. Whether there was one. +static bool wooden_cross_mantle_spend(Entity_Player& player) { - bool isItemHit = std::ranges::any_of(HIT_COLLECTIBLES, [&](int item) { return player.HasCollectible(item); }) || - std::ranges::any_of(HIT_TRINKETS, [&](int trinket) { return player.HasTrinket(trinket); }) || - (isPenalized && player.HasTrinket(TRINKET_PERFECTION)) || player.HasPlayerForm(PLAYER_FORM_STOMPY) || - (player.HasCollectible(CROWN_OF_LIGHT) && !g_game->deathmatchManager.is_active()) || - (player.HasCollectible(COLLECTIBLE_HYPERCOAGULATION) && !(damageFlags & HYPERCOAGULATION_IGNORED)) || - std::ranges::any_of(player.activeItems, [](const ActiveItemDesc& active) { return active.item == COLLECTIBLE_LARYNX; }); - if (isItemHit) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the items and trinkets a hit sets off)"); + constexpr int CROSS_MANTLES_MAX = 2; + constexpr int STACK_LOW_MASK = 0xf; + constexpr int STACK_HIGH_SHIFT = 4; + int crosses = std::min(player.GetTrinketMultiplier(TRINKET_WOODEN_CROSS), CROSS_MANTLES_MAX); + uint8_t stacks = player.holyMantleStacks; + + if (crosses - (stacks & STACK_LOW_MASK) <= 0) return false; + player.holyMantleStacks = (uint8_t)((((stacks >> STACK_HIGH_SHIFT) - 1) << STACK_HIGH_SHIFT) | ((stacks + 1) & STACK_LOW_MASK)); + return true; +} + +// Holy Mantle's shield takes the hit: it shatters with a burst that follows the player, a Wooden Cross mantle, the +// Blanket's, the room's own mantle or a Holy Card's is spent, and the player is invincible for a second (longer with +// Blind Rage). The hit does not hurt. +static bool holy_mantle_block(Entity_Player& player) +{ + constexpr int MANTLE_BREAK_SUBTYPE = 11; + constexpr float MANTLE_BREAK_DEPTH = 16; + constexpr int MANTLE_COOLDOWN = 60; + TemporaryEffects& effects = player.temporaryEffects; + + voice_play(SOUND_HOLY_MANTLE, 1, SOUND_FRAME_DELAY, 1); + uint32_t seed = Random(); + auto* burst = static_cast(g_game->Spawn({.position = player.pos, .spawner = &player, + .subType = MANTLE_BREAK_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, .seed = seed})); + burst->FollowParent(&player); + burst->posOffset = player.posOffset; + burst->sprite.scale = player.sprite.scale; + burst->renderDepthOffset = MANTLE_BREAK_DEPTH; + burst->Update(); + effects.RemoveCollectibleEffect(COLLECTIBLE_HOLY_MANTLE, 1); + if (!wooden_cross_mantle_spend(player)) + { + if (effects.HasCollectibleEffect(COLLECTIBLE_BLANKET)) effects.RemoveCollectibleEffect(COLLECTIBLE_BLANKET, 1); + else if (player.HasCollectible(COLLECTIBLE_HOLY_MANTLE) && player.holyMantleState == 0) player.holyMantleState = 1; + else if (effects.HasNullEffect(NULLITEM_HOLY_CARD)) effects.RemoveNullEffect(NULLITEM_HOLY_CARD, 1); + } + if (effects.GetCollectibleEffectNum(COLLECTIBLE_HOLY_MANTLE) < 1) + player.RemoveCostume(g_manager->itemConfig.GetCollectible(COLLECTIBLE_HOLY_MANTLE)); + player.damageCooldown = damage_cooldown_scale(MANTLE_COOLDOWN); + if (player.HasTrinket(TRINKET_BLIND_RAGE)) + player.damageCooldown *= damage_cooldown_scale(player.GetTrinketMultiplier(TRINKET_BLIND_RAGE) * 2); + player.ClearEntityFlags(FLAG_NO_DAMAGE_BLINK); + return false; +} + +// The items a landed hit sets off: collectibles 1 to 366, then the trinkets and later collectibles +// (entity_player_hits.cpp), Eve's Dead Bird and Samson's Bloody Lust, then Tainted Samson's rage. Bleeding out +// restarts its timer. The amount is the hit's hearts, not yet taken. Whether the hurt animation still plays. +static bool hit_items_check(Entity_Player& player, int amount, const ItemsHit& hit) +{ + passives_hit_trigger(player, amount); + if (player.HasCollectible(ZODIAC)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Zodiac's sign)"); + bool isHurtShown = late_items_hit_trigger(player, hit); character_items_hit(player); if (player.playerType == PLAYER_SAMSON_B && (player.redHearts > 0 || player.soulHearts > 0 || player.boneHearts > 0)) player.add_samson_berserk_charge(SAMSON_B_HIT_CHARGE); @@ -434,6 +491,7 @@ static void hit_items_check(Entity_Player& player, uint64_t damageFlags, bool is player.bleedOutHealth = BLEED_OUT_HEALTH; if (!player.proceduralItems.empty()) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (glitched items, trigger_set_dispatch)"); + return isHurtShown; } // 007729d0 The player takes a hit: the hit is ignored or turned by many items, then costs its hearts, plays the hurt @@ -444,7 +502,10 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR Entity_Player* twin = twin_get(); if (playerType == PLAYER_THESOUL_B && twin && !twin->HasCollectible(COLLECTIBLE_ISAACS_HEART)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the Forgotten's soul passing the hit on)"); + { + if (twin->itemState == COLLECTIBLE_GLASS_CANNON) twin->bodySprite.Reset(); + return twin->TakeDamage(damage, damageFlags, source, damageCountdown); + } if (source.entity && (source.type == ENTITY_DAMAGE_RELAY || source.type == ENTITY_FAMILIAR)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a familiar or relay source)"); if (is_wisp_shield_present(*this)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (wisp shields)"); @@ -491,7 +552,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR if (isBlocked && !isFake) return false; if (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HOLY_MANTLE) && !(damageFlags & DAMAGE_RED_HEARTS)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Holy Mantle's shield)"); + return holy_mantle_block(*this); if (hallowedGroundCountdown > 0 && !(damageFlags & DAMAGE_NO_MODIFIERS)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Hallowed Ground)"); if (!lua_engine_get().EntityTakeDamage(this, (float)amount, damageFlags, source, damageCountdown)) return false; @@ -543,7 +604,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR 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); + bool isHurt = hit_items_check(*this, amount, {source, damageFlags, damage, isPenalized}); for (size_t i = 0; i < game.room->entityList.updateEL.size(); i++) { Entity* entity = game.room->entityList.updateEL[i]; @@ -567,7 +628,6 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR !temporaryEffects.HasCollectibleEffect(COLLECTIBLE_ASTRAL_PROJECTION) && !astralProjectionBody; bool isInstantDeath = HasInstantDeathCurse() && amount > 0; bool isDeathSkipped = isAstral || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BERSERK); - bool isHurt = true; if ((redHearts < 1 && soulHearts < 1 && boneHearts < 1) || isInstantDeath) { @@ -600,26 +660,22 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR } } } - if (!isDead && HasCollectible(COLLECTIBLE_CURSED_EYE) && !HasCollectible(COLLECTIBLE_BLACK_CANDLE) && weapons[1]) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Cursed Eye's teleport)"); + bool isTeleported = !isDead && cursed_eye_teleport(*this); - bool isHitAnimated = pitfallState == 0 && isHurt; - if (HasTrinket(TRINKET_CURSED_SKULL) && !isDead) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Cursed Skull)"); + bool isHitAnimated = pitfallState == 0 && isHurt && !isTeleported; + if (HasTrinket(TRINKET_CURSED_SKULL) && !isDead) cursed_skull_teleport(*this); if (redHearts <= scale_for_hard_difficulty(1)) { - if (HasCollectible(COLLECTIBLE_POLAROID) || HasCollectible(COLLECTIBLE_NEGATIVE)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the Polaroid and the Negative)"); + last_heart_items_trigger(*this, damageFlags); bool isLastHeart = soulHearts < 1 || (redHearts < 1 && soulHearts == scale_for_hard_difficulty(1)); - if (isLastHeart && (HasCollectible(COLLECTIBLE_SCAPULAR) || (HasTrinket(TRINKET_MONKEY_PAW) && variant == PLAYER_VARIANT_PLAYER))) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Scapular and Monkey Paw)"); + if (isLastHeart && HasTrinket(TRINKET_MONKEY_PAW) && variant == PLAYER_VARIANT_PLAYER) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Monkey Paw)"); } damageCooldown = damage_cooldown_scale(std::min(hurtFrames, HURT_HEARTS_MAX) * HURT_FRAMES_PER_HEART); flags &= ~FLAG_NO_DAMAGE_BLINK; if (isAstral) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Astral Projection)"); - if (HasTrinket(TRINKET_BLIND_RAGE) || HasTrinket(TRINKET_FINGER_BONE)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Blind Rage and Finger Bone)"); + blind_rage_finger_bone_hit(*this); if (isPenalized && HasCollectible(COLLECTIBLE_GLASS_CANNON)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Glass Cannon)"); if (isHitAnimated) @@ -639,7 +695,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Swallowed M80)"); bool isGlitching = isPlayingExtraAnimation && sprite.IsPlaying("Glitch"); if (!isDead && playerType == PLAYER_EDEN_B && isPenalized && !isGlitching) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Tainted Eden's reroll)"); + tainted_eden_glitch(*this); return true; } diff --git a/src/entity_player_death.cpp b/src/entity_player_death.cpp index 271a106..01b086b 100644 --- a/src/entity_player_death.cpp +++ b/src/entity_player_death.cpp @@ -17,11 +17,9 @@ constexpr int COLLECTIBLE_ANKH = 161; constexpr int COLLECTIBLE_JUDAS_SHADOW = 311; -constexpr int COLLECTIBLE_POLYDACTYLY = 454; constexpr int TRINKET_BROKEN_ANKH = 28; constexpr int TRINKET_LOCUST_OF_WRATH = 113; constexpr int TRINKET_LOCUST_OF_CONQUEST = 117; -constexpr int TRINKET_BAT_WING = 118; constexpr int NULLITEM_BATWING_WINGS = 40; constexpr int NULLITEM_LAZARUS_SOUL_REVIVE = 113; constexpr int CARD_SOUL_LAZARUS = 89; @@ -30,7 +28,6 @@ constexpr int BABY_FOUND_SOUL = 59; constexpr int CLOT_SUBTYPE_UNCOUNTED = 7; constexpr int SPECIAL_DAILY_SHUFFLED_ITEMS = 7; -constexpr int SOUND_ITEMRECHARGE = 218; constexpr float DEATH_FRICTION = 0.6f; constexpr int DEATH_FRAME_TWIN_FALLS = 7; diff --git a/src/entity_player_evaluate.cpp b/src/entity_player_evaluate.cpp index 3cfb2a2..f7b505b 100644 --- a/src/entity_player_evaluate.cpp +++ b/src/entity_player_evaluate.cpp @@ -2,6 +2,7 @@ #include "active_items.h" #include "entity_familiar.h" #include "entity_player_characters.h" +#include "entity_player_passives.h" #include "entity_tear.h" #include "game.h" #include "lua_engine.h" @@ -52,18 +53,16 @@ constexpr int PILL_SHOT_SPEED_DOWN = 47; constexpr int PILL_SHOT_SPEED_UP = 48; constexpr int TRINKET_CRACKED_CROWN = 92; constexpr int FAMILIAR_ITEM_WISP = 206; -constexpr int COLLECTIBLE_FORTUNE_COOKIE = 557; constexpr int COOP_BUFF_DAMAGE = 0; constexpr int COOP_BUFF_TEARS = 1; constexpr int COOP_BUFF_SPEED = 2; constexpr int COOP_BUFF_RANGE = 3; constexpr int COOP_BUFF_LUCK = 4; -// The run states the evaluation is reconstructed for: the stat changes of other characters, effects, trinkets, -// seeds, challenges, procedural items, wisps and the items below stop the game until reached. -// Candy Heart, Soul Locket, Experimental Treatment, Libra, Rock Bottom, Adrenaline, the pill 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 run states the evaluation is reconstructed for: the stat changes of other characters, effects, seeds, +// challenges, procedural items, wisps and the items below stop the game until reached. +// Candy Heart, Soul Locket, Rock Bottom, the pill items, Mega Mush, Berserk!, Jupiter and Dogma. +constexpr std::array EVALUATION_UNHANDLED_ITEMS = {671, 686, 562, 654, 625, 704, 594, 633, 556}; // The constants of the other sections: the collectibles, trinkets, null items and characters they ask about. constexpr int PILL_TEARS_UP = 16; @@ -76,9 +75,6 @@ constexpr int BABY_SKIN_BONE = 57; constexpr int BABY_SKIN_GHOST_A = 58; constexpr int BABY_SKIN_GHOST_B = 59; constexpr int NULLITEM_SPIRIT_SHACKLES_SOUL = 101; -constexpr int NULLITEM_REVERSE_DEVIL = 67; -constexpr int NULLITEM_HUGE_GROWTH = 41; -constexpr int COLLECTIBLE_SPIRIT_SWORD = 579; constexpr int COLLECTIBLE_2SPOOKY = 554; constexpr int SPRITE_SCALE_UNLOCK = 3; constexpr int ACHIEVEMENT_HUGE = 361; @@ -96,6 +92,12 @@ constexpr float HOLOGRAM_ALPHA = 0.2f; constexpr float COLOR_OFFSET_UNIT = 0.003921569f; constexpr float HELD_THROW_SCALE = 0.1f; constexpr float TAINTED_BETHANY_STAT_SCALE = 0.75f; +constexpr float SAMSONS_LOCK_CAP = 5; +constexpr float ADRENALINE_POWER = 1.6f; +constexpr int PURITY_DAMAGE = 0; +constexpr int PURITY_TEARS = 1; +constexpr int PURITY_SPEED = 2; +constexpr int PURITY_RANGE = 3; // Whether the player owns any of the listed collectibles. static bool is_owning_any(Entity_Player& player, std::span collectibles) @@ -109,18 +111,54 @@ static float pill_uses(Entity_Player& player, int pillEffect) return pillEffect < (int)player.pillEffectUses.size() ? (float)player.pillEffectUses[pillEffect] : 0; } +// The trinket and late collectible effects the evaluation and the frame know: Red Patch, Samson's Lock, Eve's Bird +// Foot, Equality, Bat Wing, Purity and the crowns. +static bool is_trinket_effect_plain(const TemporaryEffect& effect) +{ + constexpr int PLAIN_TRINKET_EFFECTS[] = {TRINKET_RED_PATCH, TRINKET_SAMSONS_LOCK, TRINKET_EVES_BIRD_FOOT, + TRINKET_EQUALITY, TRINKET_BAT_WING}; + constexpr int PLAIN_LATE_EFFECTS[] = {COLLECTIBLE_PURITY, COLLECTIBLE_CROWN_OF_LIGHT, COLLECTIBLE_DARK_PRINCES_CROWN}; + std::span plain = effect.item->type == ITEM_TRINKET ? std::span(PLAIN_TRINKET_EFFECTS) + : std::span(PLAIN_LATE_EFFECTS); + return effect.item->type != ITEM_NULL && std::ranges::find(plain, effect.item->id) != plain.end(); +} + +// Whether Purity's aura is on in a colour (0 damage, 1 tears, 2 speed, 3 range). +static bool is_purity(Entity_Player& p, int state) +{ + return p.HasCollectible(COLLECTIBLE_PURITY) && p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_PURITY) && + p.purityState == state; +} + +// A trinket's multiplier as a float. +static float trinket_num(Entity_Player& p, int trinket) +{ + return (float)p.GetTrinketMultiplier(trinket); +} + +// The bulbs' part of a stat in 00763570: Dim Bulb adds while the main active is empty and Vibrant Bulb while it is +// fully charged, each its multiplier times its scale. +static void bulbs_apply(Entity_Player& p, float& stat, float dimScale, float vibrantScale) +{ + int maxCharge = p.GetActiveMaxCharge(ACTIVE_SLOT_PRIMARY); + bool isFull = maxCharge >= 1 && maxCharge <= p.GetTotalActiveCharge(ACTIVE_SLOT_PRIMARY); + bool isEmpty = maxCharge >= 1 && p.activeItems[ACTIVE_SLOT_PRIMARY].charge == 0; + + if (p.HasTrinket(TRINKET_DIM_BULB) && isEmpty) stat = trinket_num(p, TRINKET_DIM_BULB) * dimScale + stat; + if (p.HasTrinket(TRINKET_VIBRANT_BULB) && isFull) stat = trinket_num(p, TRINKET_VIBRANT_BULB) * vibrantScale + stat; +} + // Whether the character and run are ones the evaluation is reconstructed for (see EVALUATION_UNHANDLED_ITEMS), with -// only the temporary effects of the actives written for them. +// only the temporary effects of the actives and trinkets written for them. bool Entity_Player::is_character_plain() { Game& game = *g_game; - bool isSmelted = std::ranges::any_of(smeltedTrinkets, [](SmeltedTrinket& t) { return t.count || t.goldenCount; }); return is_character_reconstructed(*this) && variant == PLAYER_VARIANT_PLAYER && !isCoopGhost && !hasCurseMistEffect && game.challenge == 0 && game.dailyChallenge._id == 0 && game.seedEffects.CountSeedEffects() == 0 && !game.deathmatchManager.is_active() && - std::ranges::all_of(temporaryEffects.effects, is_temporary_effect_plain) && - trinkets == std::array{} && !isSmelted && proceduralItems.empty() && - itemWispsList.empty(); + std::ranges::all_of(temporaryEffects.effects, + [](const TemporaryEffect& e) { return is_temporary_effect_plain(e) || is_passive_effect_plain(e) || is_trinket_effect_plain(e); }) && + proceduralItems.empty(); } // The bonuses Binge Eater's foods give: damage, tears, range, shot speed, speed and luck, each food also slowing. @@ -134,12 +172,25 @@ struct StatBonuses float luck = 0; }; -// The part of 00763570 before the sections: Binge Eater's foods add to the stats it lowers speed for. +// The part of 00763570 before the sections: Experimental Treatment's effect deals three stats up and three down in +// an order the room's spawn seed shuffles, then Binge Eater's foods add to the stats it lowers speed for. static StatBonuses stat_bonuses_get(Entity_Player& player) { constexpr float FOOD_SLOW = 0.15f; + constexpr uint32_t SHUFFLE_SHIFT_INDEX = 19; StatBonuses bonus; + if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_EXPERIMENTAL_TREATMENT)) + { + std::array stats = {&bonus.damage, &bonus.tears, &bonus.range, &bonus.shotSpeed, &bonus.speed, &bonus.luck}; + std::array values = {1, 1, 1, -1, -1, -1}; + RoomDescriptor* descriptor = g_game->room->descriptor; + RNG rng; + + rng.SetSeed(descriptor ? descriptor->spawnSeed : 0, SHUFFLE_SHIFT_INDEX); + for (uint32_t i = 0; i < values.size() - 1; i++) std::swap(values[i], values[i + rng.RandomInt(values.size() - i)]); + for (size_t i = 0; i < values.size(); i++) *stats[i] = values[i]; + } if (!player.HasCollectible(COLLECTIBLE_BINGE_EATER)) return bonus; auto food = [&](int id, std::initializer_list stats) { @@ -170,12 +221,16 @@ static void fire_delay_evaluate(Entity_Player& p, const StatBonuses& bonus, floa tears = (n(598) + tears) * 0.7f; tears = n(6) * 1.5f + tears; tears = (n(669) + n(564) + n(255) + n(115) + n(72)) * 0.5f + tears; - tears = (float)(p.GetCollectibleNum(196) - p.GetCollectibleNum(182)) * 0.4f + tears; + int worms = p.GetTrinketMultiplier(TRINKET_WIGGLE_WORM) + (p.GetCollectibleNum(196) - p.GetCollectibleNum(182)) + + p.GetTrinketMultiplier(TRINKET_OUROBOROS_WORM) + p.GetTrinketMultiplier(TRINKET_HOOK_WORM) + + p.GetTrinketMultiplier(TRINKET_RING_WORM); + tears = (float)worms * 0.4f + tears; tears = (float)(p.GetCollectibleNum(189) + p.GetCollectibleNum(101) + p.GetCollectibleNum(90)) * 0.2f + tears; tears = tears - (float)(p.GetCollectibleNum(331) + p.GetCollectibleNum(237)) * 0.3f; tears = n(438) * 0.75f + tears; tears = n(443) * 0.3f + tears; tears = n(465) * 0.35f + tears; + bulbs_apply(p, tears, 0.5f, 0.2f); tears = tears + character_tears_get(p); float bonusTears = is_eden(p) ? bonus.tears * 0.5f + p.edenFireDelay : bonus.tears * 0.5f; if (bonusTears < 0) bonusTears *= NEGATIVE_TEARS_SCALE; @@ -196,10 +251,14 @@ static void fire_delay_evaluate(Entity_Player& p, const StatBonuses& bonus, floa float pairs = (float)(p.GetCollectibleNum(307) + p.GetCollectibleNum(228) + p.GetCollectibleNum(224) + p.GetCollectibleNum(206)) + zodiacA; pairs = (n(309) + pairs + zodiacB + (float)p.fireDelayModifier) * 0.5f; - float flat = (float)p.brittleBonesUpgrades * 0.4f + pairs; + float purityTears = is_purity(p, PURITY_TEARS) ? 2.0f : 0.0f; + float crown = p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN) ? 2.0f : 0.0f; + float flat = (float)p.brittleBonesUpgrades * 0.4f + trinket_num(p, TRINKET_CANCER) + purityTears + pairs + crown; flat = n(397) + flat; rate = flat + rate; if (has(120)) rate = n(120) * 0.7f + 1 + rate; + // The original also counts Equality when a trinket slot only the constructor writes holds it, always empty. + if (p.temporaryEffects.HasTrinketEffect(TRINKET_EQUALITY)) rate = trinket_num(p, TRINKET_EQUALITY) * 2 + rate; rate = n(554) * 0.5f + rate; if (!p.HasWeaponType(WEAPON_BRIMSTONE)) rate = n(222) + rate; rate = (float)p.g_fuel_count() * 0.5f + rate; @@ -269,6 +328,7 @@ static void damage_evaluate(Entity_Player& p, const StatBonuses& bonus, float cr if (p.redStewBonusDuration > 0 && !p.temporaryEffects.isDisabled) damage = (float)(p.redStewBonusDuration / 10) * 0.04f + damage; if (has(716)) damage = (float)((p.keepersSackBonus / 3 + 2) / 3) * 0.5f + damage; + bulbs_apply(p, damage, 1.5f, 0.5f); for (TemporaryEffect* babylon : {p.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON), p.temporaryEffects.GetNullEffect(NULLITEM_BLOODY_BABYLON)}) if (babylon) damage = (float)(babylon->count * babylon->count) * 1.5f + damage; @@ -287,8 +347,19 @@ static void damage_evaluate(Entity_Player& p, const StatBonuses& bonus, float cr if (has(694)) damage = (float)p.brokenHearts * 0.25f + damage; if (has(120)) damage = damage * 0.9f - 0.4f; if (p.coopBabyBuffTimers[COOP_BUFF_DAMAGE] > 0) damage = damage + 2; + if (TemporaryEffect* lock = p.temporaryEffects.GetTrinketEffect(TRINKET_SAMSONS_LOCK)) + damage = std::min(SAMSONS_LOCK_CAP, (float)lock->count * 0.5f) + damage; if (TemporaryEffect* boost = p.temporaryEffects.GetNullEffect(NULLITEM_LAZARUS_BOOST)) damage = (float)boost->count * 0.5f + damage; + if (TemporaryEffect* patch = p.temporaryEffects.GetTrinketEffect(TRINKET_RED_PATCH)) + damage = (float)patch->count * 1.8f + damage; + if (p.HasTrinket(TRINKET_BLACK_FEATHER)) + { + int evil = n(654) + n(344) + n(339) + n(262) + n(260) + n(230) + n(216) + n(215) + n(80) + n(79); + float feathers = ((float)evil + trinket_num(p, TRINKET_BLACK_LIPSTICK) + trinket_num(p, TRINKET_DAEMONS_TAIL)) * 0.5f; + damage = trinket_num(p, TRINKET_BLACK_FEATHER) * feathers + damage; + } + if (is_purity(p, PURITY_DAMAGE)) damage = damage + 4; damage = std::sqrt(std::max(damage * DAMAGE_CURVE_SCALE + 1, 0.0f)) * DAMAGE_BASE; if (has(169)) @@ -300,11 +371,22 @@ static void damage_evaluate(Entity_Player& p, const StatBonuses& bonus, float cr damage = (damage + 2) * 3; damage = (float)(p.potatoPeelerBandageCounter + p.potatoPeelerCounter) * 0.2f + damage; damage = std::max((float)p.damageModifier + bonus.damage + damage, DAMAGE_MIN); + float horns = trinket_num(p, TRINKET_CURVED_HORN); + damage = horns + horns + damage; if (has(513)) damage = damage + 0.1f; if (p.HasWeaponType(WEAPON_BONE) && has(114)) damage = damage + 4; + if (has(COLLECTIBLE_CROWN_OF_LIGHT) && p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT)) + damage = damage + damage; if (has(182)) damage = damage * 2.3f + 1; if (has(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) && has(COLLECTIBLE_PASSIVE_DAMOCLES)) damage = damage * 1.4f + 1; if (has(573) || p.hallowedGroundCountdown > 0) damage = damage * 1.2f; + if (has(COLLECTIBLE_ADRENALINE) || p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_ADRENALINE)) + { + uint32_t empty = (uint32_t)((p.boneHearts * 2 - p.redHearts + p.maxHearts) / 2); + if (g_game->deathmatchManager.is_active()) empty >>= 3; + float hearts = (float)(int)empty; + damage = std::pow(hearts + hearts, ADRENALINE_POWER) * 0.1f + damage; + } if (has(157) && !p.temporaryEffects.isDisabled) { float cap = has(COLLECTIBLE_BIRTHRIGHT) && p.playerType == PLAYER_SAMSON ? 10.0f : 6.0f; @@ -378,6 +460,7 @@ static void damage_evaluate(Entity_Player& p, const StatBonuses& bonus, float cr p.meleeDamage = melee; static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_DAMAGE); + p.damage = trinket_num(p, TRINKET_LAZY_WORM) * 0.5f + p.damage; if (g_game->debugFlags & DEBUG_HIGH_DAMAGE) { p.damage = p.damage + DEBUG_DAMAGE_BONUS; @@ -404,12 +487,17 @@ static void shot_speed_evaluate(Entity_Player& p, const StatBonuses& bonus, floa speed = speed - (float)mascara * 0.5f; speed = speed - (float)n(336) * 0.4f; speed = speed - (float)n(331) * 0.3f; - speed = speed + character_shot_speed_get(p); + speed = speed - (float)p.temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_CROWN_OF_LIGHT) * 0.3f; speed = ((float)p.shotSpeedModifier + bonus.shotSpeed) * 0.2f + (float)n(329) * 0.2f + speed; + bulbs_apply(p, speed, 0.3f, 0.1f); + speed = speed + character_shot_speed_get(p); if (p.coopBabyBuffTimers[COOP_BUFF_RANGE] > 0) speed = speed + 0.5f; + if (p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN)) speed = speed + 0.2f; + speed = trinket_num(p, TRINKET_WHIP_WORM) * 0.5f + speed; speed = (float)n(554) * 0.2f + speed; if (has(5)) speed = speed * 1.6f; if (has(149)) speed = speed * 0.8f; + speed = speed - trinket_num(p, TRINKET_LAZY_WORM) * 0.5f; if (crownScale != 1 && speed - 1 > 0) speed = (crownScale - 1) * (speed - 1) + speed; p.shotSpeed = speed; @@ -451,6 +539,9 @@ static void range_evaluate(Entity_Player& p, const StatBonuses& bonus, float cro if (has(598)) p.tearHeight = p.tearHeight * 0.4f; if (has(716)) p.tearRange = (float)((p.keepersSackBonus / 3 + 1) / 3) * 10 + p.tearRange; if (p.coopBabyBuffTimers[COOP_BUFF_RANGE] > 0) p.tearRange = p.tearRange + 80; + bulbs_apply(p, p.tearRange, 60, 30); + if (p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN)) p.tearRange = p.tearRange + 60; + if (is_purity(p, PURITY_RANGE)) p.tearRange = p.tearRange + 120; if (has(149) || has(531)) { if (!has(229)) @@ -466,7 +557,17 @@ static void range_evaluate(Entity_Player& p, const StatBonuses& bonus, float cro p.tearFallingAcceleration = p.tearFallingAcceleration * 0.01f; } if (has(307) || p.GetZodiacEffect() == 307) p.tearRange = p.tearRange + 30; - if (has(214)) p.tearRange = p.tearRange + 60; + if (has(COLLECTIBLE_ANEMIC) || p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_ANEMIC)) p.tearRange = p.tearRange + 60; + if (p.HasTrinket(TRINKET_HOOK_WORM) && p.HasWeaponType(WEAPON_TEARS)) + p.tearRange = trinket_num(p, TRINKET_HOOK_WORM) * 60 + p.tearRange; + if (p.HasTrinket(TRINKET_OUROBOROS_WORM)) p.tearRange = trinket_num(p, TRINKET_OUROBOROS_WORM) * 60 + p.tearRange; + if (p.HasTrinket(TRINKET_TAPE_WORM)) + { + float tape = trinket_num(p, TRINKET_TAPE_WORM); + p.tearHeight = (tape + tape) * p.tearHeight; + p.tearFallingSpeed = tape * 0.5f * p.tearFallingSpeed; + p.tearRange = tape * 120 + p.tearRange; + } if (has(6)) { p.tearHeight = p.tearHeight + 18; @@ -516,16 +617,23 @@ static void speed_evaluate(Entity_Player& p, const StatBonuses& bonus, float cro p.moveSpeed = lust * 0.02f * lust + lust * 0.05f + p.moveSpeed; } if (has(716)) p.moveSpeed = (float)(p.keepersSackBonus / 9) * 0.03f + p.moveSpeed; + bulbs_apply(p, p.moveSpeed, 0.5f, 0.25f); + if (p.HasTrinket(TRINKET_GOAT_HOOF)) p.moveSpeed = trinket_num(p, TRINKET_GOAT_HOOF) * 0.15f + p.moveSpeed; if (p.coopBabyBuffTimers[COOP_BUFF_SPEED] > 0) p.moveSpeed = p.moveSpeed + 0.15f; if (has(230)) p.moveSpeed = p.moveSpeed + 0.2f; if (p.HasPlayerForm(PLAYER_FORM_SPUN)) p.moveSpeed = p.moveSpeed + 0.15f; if (p.HasPlayerForm(PLAYER_FORM_FLIGHT)) p.moveSpeed = p.moveSpeed + 0.2f; if (has(130) || has(181)) p.moveSpeed = std::max(p.moveSpeed, 1.5f); - if (has(COLLECTIBLE_TAURUS) || p.GetZodiacEffect() == COLLECTIBLE_TAURUS) p.moveSpeed = p.moveSpeed - 0.3f; + if (has(COLLECTIBLE_TAURUS) || p.GetZodiacEffect() == COLLECTIBLE_TAURUS) + { + p.moveSpeed = p.moveSpeed - 0.3f; + if (p.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_TAURUS)) p.moveSpeed = p.taurusSpeedBonus + p.moveSpeed; + } if (has(300) || p.GetZodiacEffect() == 300) p.moveSpeed = p.moveSpeed + 0.25f; if (has(306) || p.GetZodiacEffect() == 306) p.moveSpeed = p.moveSpeed + 0.2f; if (has(307) || p.GetZodiacEffect() == 307) p.moveSpeed = p.moveSpeed + 0.1f; if (has(314)) p.moveSpeed = p.moveSpeed - 0.4f; + if (is_purity(p, PURITY_SPEED)) p.moveSpeed = p.moveSpeed + 0.5f; p.moveSpeed = p.d8SpeedModifier * p.moveSpeed; if (crownScale != 1 && p.moveSpeed > 1) p.moveSpeed = (p.moveSpeed - 1) * (crownScale - 1) + p.moveSpeed; @@ -544,6 +652,8 @@ static void luck_evaluate(Entity_Player& p, const StatBonuses& bonus) luck = n(669) + luck; luck = (float)(p.GetCollectibleNum(632) * 2) + luck; p.luck = n(730) + luck; + if (p.HasTrinket(TRINKET_LUCKY_TOE)) p.luck = trinket_num(p, TRINKET_LUCKY_TOE) + p.luck; + if (p.HasTrinket(TRINKET_PERFECTION)) p.luck = trinket_num(p, TRINKET_PERFECTION) * 10 + p.luck; p.luck = p.luck + character_luck_get(p); int wisps = 0; @@ -553,7 +663,9 @@ static void luck_evaluate(Entity_Player& p, const StatBonuses& bonus) wisps++; p.luck = (float)wisps * 0.2f + p.luck; if (p.coopBabyBuffTimers[COOP_BUFF_LUCK] > 0) p.luck = p.luck + 2; + bulbs_apply(p, p.luck, 2, 0); if (p.HasCollectible(492)) p.luck = p.luck + 1; + bulbs_apply(p, p.luck, 0, 1); if (g_game->debugFlags & DEBUG_HIGH_LUCK) p.luck = p.luck + DEBUG_LUCK_BONUS; static_cast(g_luaEngine)->EvaluateItems(&p, CACHE_LUCK); @@ -997,21 +1109,67 @@ static void weapons_evaluate(Entity_Player& p) p.cacheFlags |= CACHE_DAMAGE; } +// Libra's balance (009bfc00 to 009bfd20): damage per second, speed and range each mapped onto one scale, damage +// counting twice, and their average mapped back onto fire delay, damage, speed and range. +constexpr uint32_t LIBRA_CACHE = CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_RANGE | CACHE_SPEED; +constexpr float LIBRA_OFFSET = 2; +constexpr float LIBRA_DPS_POWER = 0.65f; +constexpr float LIBRA_DPS_SCALE = 2.161616086959839f; +constexpr float LIBRA_SPEED_SCALE = 4.5f; +constexpr float LIBRA_RANGE_BASE = 230; +constexpr float LIBRA_RANGE_SCALE = 60; +constexpr float LIBRA_TEARS_SCALE = 0.4716111421585083f; +constexpr float LIBRA_TEARS_POWER = 1.3333333730697632f; +constexpr float LIBRA_DAMAGE_SCALE = 0.4481935203075409f; +constexpr float LIBRA_DAMAGE_POWER = 1.7857142686843872f; +constexpr float LIBRA_SLOWEST_FIRE_DELAY = 10000; + +// Whether the player has Libra, or Zodiac lends it. +static bool is_libra(Entity_Player& p) +{ + return p.HasCollectible(COLLECTIBLE_LIBRA) || p.GetZodiacEffect() == COLLECTIBLE_LIBRA; +} + +// A float power taken in double precision, as the original's wrapper does. +static float power_double(float base, float exponent) +{ + return (float)std::pow((double)base, (double)exponent); +} + +// The Libra part of 00763570: the four stats meet at their average. +static void libra_balance(Entity_Player& p) +{ + float dps = p.damage * FIRE_RATE_FRAMES / (p.maxFireDelay + 1); + float dpsStat = power_double((float)std::sqrt((double)dps), LIBRA_DPS_POWER) * LIBRA_DPS_SCALE - LIBRA_OFFSET; + float speedStat = p.moveSpeed * LIBRA_SPEED_SCALE - LIBRA_OFFSET; + float rangeStat = (p.tearRange - LIBRA_RANGE_BASE) / LIBRA_RANGE_SCALE + LIBRA_OFFSET; + float average = (rangeStat + speedStat + (dpsStat + dpsStat)) * 0.25f; + bool isPositive = average > -LIBRA_OFFSET; + + p.moveSpeed = (average + LIBRA_OFFSET) / LIBRA_SPEED_SCALE; + p.maxFireDelay = isPositive ? FIRE_RATE_FRAMES / power_double((average + LIBRA_OFFSET) * LIBRA_TEARS_SCALE, LIBRA_TEARS_POWER) - 1 + : LIBRA_SLOWEST_FIRE_DELAY; + p.damage = isPositive ? power_double((average + LIBRA_OFFSET) * LIBRA_DAMAGE_SCALE, LIBRA_DAMAGE_POWER) : 0; + p.tearRange = (average - LIBRA_OFFSET) * LIBRA_RANGE_SCALE + LIBRA_RANGE_BASE; + p.cacheFlags |= LIBRA_CACHE; +} + // 00763570 Recomputes what the cache flags ask for: the weapons, then fire delay, damage, shot speed, range, speed and // luck from the items, pills, modifiers and Binge Eater's foods, then the tear flags and colours, flight, size and // colour, each section handed to the mods. Then it clamps the stats and works out how fast tears fall. A shot speed -// change redoes the range. Familiars, other characters, effects, trinkets and run modifiers stop the game when they -// have work to do. +// change redoes the range. Familiars, other characters, effects and run modifiers stop the game when they have work +// to do. void Entity_Player::EvaluateItems() { if (!is_character_plain() || is_owning_any(*this, EVALUATION_UNHANDLED_ITEMS)) - reconstruction_missing("Entity_Player::EvaluateItems 00763570 (characters, effects, trinkets or special items)"); + reconstruction_missing("Entity_Player::EvaluateItems 00763570 (characters, effects or special items)"); StatBonuses bonus = stat_bonuses_get(*this); float crownScale = (float)GetTrinketMultiplier(TRINKET_CRACKED_CROWN) * 0.2f + 1; if (playerType == PLAYER_BETHANY_B) crownScale *= TAINTED_BETHANY_STAT_SCALE; if (cacheFlags & CACHE_WEAPON) weapons_evaluate(*this); if (cacheFlags & CACHE_SHOTSPEED) cacheFlags |= CACHE_RANGE; + if (is_libra(*this) && (cacheFlags & LIBRA_CACHE)) cacheFlags |= LIBRA_CACHE; if (cacheFlags & CACHE_FIREDELAY) fire_delay_evaluate(*this, bonus, crownScale); if (cacheFlags & CACHE_DAMAGE) damage_evaluate(*this, bonus, crownScale); if (cacheFlags & CACHE_SHOTSPEED) shot_speed_evaluate(*this, bonus, crownScale); @@ -1024,6 +1182,7 @@ void Entity_Player::EvaluateItems() if (cacheFlags & CACHE_LUCK) luck_evaluate(*this, bonus); if ((cacheFlags & CACHE_SIZE) && variant == PLAYER_VARIANT_PLAYER) size_evaluate(*this); if (cacheFlags & CACHE_COLOR) color_evaluate(*this); + if (is_libra(*this) && (cacheFlags & LIBRA_CACHE)) libra_balance(*this); twins_speed_share(*this); if ((cacheFlags & CACHE_SPEED) && std::ranges::any_of(g_game->playerManager.playerList, @@ -1043,12 +1202,17 @@ void Entity_Player::EvaluateItems() cacheFlags = 0; } -// 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, 465, 493, 497, 534, 575, 593, 619, 632, 641, 59, 202, 210, 399}; +// The collectibles the frame (00782af0) looks at itself, which its plain path does not cover yet: Judas's kept Book of +// Belial among them. The weapon items are not: the frame and its items' part (update_effects 00794e50) never ask for +// them, their weapons do. Midas' Touch only tints a Gnawed Leaf statue or a frozen player. +constexpr std::array FRAME_ITEMS = {465, 493, 497, 575, 593, 619, 632, 641, 59, 399}; + +// The trinkets the items' frame (00794e50) looks at that it does not run yet: Faded Polaroid and Extension Cord. +constexpr std::array FRAME_TRINKETS = {69, 125}; // Whether the player's frame runs its plain path: a plain character holding none of the items the frame handles. bool Entity_Player::is_frame_plain() { - return is_character_plain() && !is_owning_any(*this, FRAME_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) && + std::ranges::none_of(FRAME_TRINKETS, [this](int trinket) { return HasTrinket(trinket); }); } diff --git a/src/entity_player_forgotten.cpp b/src/entity_player_forgotten.cpp index e24960b..103abc9 100644 --- a/src/entity_player_forgotten.cpp +++ b/src/entity_player_forgotten.cpp @@ -23,12 +23,10 @@ constexpr int D_INFINITY_FACE_SHIFT = 16; constexpr int D_INFINITY_FACE_MASK = 0xffff; 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; diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index ca5808d..548dfa3 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -1,6 +1,8 @@ #include "entity_player.h" +#include "entity_player_trinkets.h" #include "entity_player_characters.h" #include "entity_player_crafting.h" +#include "entity_player_passives.h" #include "tainted_characters.h" #include "entity_effect.h" #include "game.h" @@ -10,12 +12,14 @@ #include "manager.h" #include "menu_manager.h" #include "npc_ai.h" +#include "npc_depths.h" #include "platform.h" #include "room.h" #include "weapon_lasers.h" #include #include +constexpr int DUCT_TAPE_MODES = 4; constexpr float BODY_TURN_RATE = 0.3f; constexpr float DEGREES_PER_RADIAN = 57.295776f; constexpr float FLYING_OFFSET_Y = -4; @@ -40,8 +44,9 @@ constexpr float SHOOT_INPUT_MIN = 0.001f; constexpr int64_t NANOSECONDS_PER_MILLISECOND = 1000000; constexpr int BLINK_CLOSED_FRAME = 2; constexpr int BLINK_CLOSED_FROM = 9; -constexpr int HELD_ITEM_STATE_FRIEND_BALL = 604; constexpr int HELD_ITEM_STATE_SUPLEX = 709; +constexpr float HELD_DROP_SPEED = 0.1f; +constexpr float BODY_THROWN_DRAG = 0.97f; constexpr int ITEM_STATE_DOCTORS_REMOTE = 47; constexpr int ITEM_STATE_SHOOP_DA_WHOOP = 49; constexpr int POINTY_RIB_BLINK = 7; @@ -59,15 +64,14 @@ constexpr uint32_t DEAD_EYE_CHARGE_LIMIT = 8; constexpr uint32_t DEAD_EYE_RESET_CHANCES[] = {50, 20, 33}; constexpr uint32_t DEAD_EYE_RESET_CERTAIN = 100; -constexpr int COLLECTIBLE_HOW_TO_JUMP = 282; constexpr int COLLECTIBLE_POINTY_RIB = 544; constexpr int TRINKET_TEARDROP_CHARM = 139; // The effects that stop the player shooting while on: Gamekid, My Little Unicorn and Unicorn Stump. constexpr int NO_SHOOT_EFFECTS[] = {93, 77, 298}; // The items whose shooting update_shooting does not write yet: No. 2, Maw of the Void, Revelation, Montezuma's -// Revenge, Trinity Shield, the double tap items (GB Bug, Divine Intervention, Hemoptysis, Lil Portal), Spear of -// Destiny, Bone Spurs and Tech.5. -constexpr int SHOOTING_ITEMS[] = {378, 399, 643, 680, 243, 405, 568, 726, 681, 400, 683, 244}; +// Revenge, the double tap items (GB Bug, Divine Intervention, Hemoptysis, Lil Portal), Spear of +// Destiny and Bone Spurs. +constexpr int SHOOTING_ITEMS[] = {378, 399, 643, 680, 405, 568, 726, 681, 400, 683}; // The room render passes the player draws its overlays in: the room itself and the water's surface. static bool is_overlay_pass() @@ -263,7 +267,8 @@ bool Entity_Player::IsFullSpriteRendering() } // 00779b40 Moves the player by its input: speed and friction from its speed stat, a slippery floor's drift and the -// facing it walks in. The items that change walking stop the game until reached. +// facing it walks in. A doubled Duct Tape's drop button turns the familiars' formation. The items that change walking +// stop the game until reached. void Entity_Player::update_body_animations() { if (heightVelocity < 0 || posOffset.y < 0) return; @@ -282,9 +287,9 @@ void Entity_Player::update_body_animations() float length = std::sqrt(input.x * input.x + input.y * input.y); if (length > 1) input = vector_make(input.x / length, input.y / length); } - if ((playerType == PLAYER_THEFORGOTTEN_B && !isCoopGhost) || suplexState != 0 || isDarkArtsBlastPending) - reconstruction_missing( - "Entity_Player::update_body_animations 00779b40 (Tainted Forgotten, suplexes and Dark Arts)"); + if (playerType == PLAYER_THEFORGOTTEN_B && !isCoopGhost) input = {}; + if (suplexState != 0 || isDarkArtsBlastPending) + reconstruction_missing("Entity_Player::update_body_animations 00779b40 (suplexes and Dark Arts)"); bool isPair = playerType == PLAYER_JACOB || playerType == PLAYER_ESAU || playerType == PLAYER_LAZARUS_B || playerType == PLAYER_LAZARUS2_B; if ((isPair && twin_get()) || playerType == PLAYER_EVE_B) @@ -302,17 +307,16 @@ void Entity_Player::update_body_animations() walk_velocity_update(walkInput); if (temporaryEffects.HasNullEffect(NULLITEM_SPIN_TO_WIN)) reconstruction_missing("Entity_Player::update_body_animations 00779b40 (Spin to Win)"); - if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && walking_items_has()) - reconstruction_missing("Entity_Player::update_body_animations 00779b40 (the items that change walking)"); + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) walking_items_animate(*this); if (HasCollectible(COLLECTIBLE_JUPITER)) reconstruction_missing("Entity_Player::update_body_animations 00779b40 (Jupiter)"); jupiterCharge = 0; if (HasCollectible(COLLECTIBLE_MARS) && isControlsEnabled) reconstruction_missing("Entity_Player::update_body_animations 00779b40 (Mars)"); marsTapFrames = std::min(marsTapFrames + 1, MARS_TAP_FRAMES_MAX); - if (HasTrinket(TRINKET_DUCT_TAPE) && GetTrinketMultiplier(TRINKET_DUCT_TAPE) >= 2) - reconstruction_missing("Entity_Player::update_body_animations 00779b40 (golden Duct Tape)"); - ductTapeMode = 0; + if (!HasTrinket(TRINKET_DUCT_TAPE) || GetTrinketMultiplier(TRINKET_DUCT_TAPE) < 2) ductTapeMode = 0; + else if (isControlsEnabled && input_is_action_triggered(ACTION_DROP, controllerIndex, this)) + ductTapeMode = std::max((ductTapeMode + 1) % DUCT_TAPE_MODES, 1); } // The direction the player walks in and the body angle turning towards it, and the input scaled by the speed stat. @@ -336,14 +340,25 @@ Vector Entity_Player::walk_direction_update(Vector input) // Turns the walk input into velocity: the part across the input fades, the input accelerates up to the speed stat, // a slippery floor keeps the momentum, and gravity pulls in side-scrolling rooms. A thrown player keeps its speed. +// Tainted Forgotten's body only slides to a stop, slowly while thrown. void Entity_Player::walk_velocity_update(Vector walkInput) { Vector before = velocity; float slippery = (float)slipperyTimer / SLIPPERY_FRAMES; float drag = 0; + bool isGrounded = !HasEntityFlags(FLAG_APPLY_GRAVITY) || canFly; + + if (playerType == PLAYER_THEFORGOTTEN_B && !isCoopGhost) + { + if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) drag = 1; + else drag = HasEntityFlags(FLAG_THROWN) ? BODY_THROWN_DRAG : slippery * 0.51f + 0.45f; + velocity.x *= drag; + if (isGrounded) velocity.y *= drag; + else velocity.y += GRAVITY_PULL; + return; + } if (HasEntityFlags(FLAG_SLOW)) slippery = 0; - bool isGrounded = !HasEntityFlags(FLAG_APPLY_GRAVITY) || canFly; if ((walkInput.x != 0 || walkInput.y != 0) && isGrounded) { float along = before.y * walkInput.y + before.x * walkInput.x; @@ -380,16 +395,6 @@ void Entity_Player::walk_velocity_update(Vector walkInput) else velocity.y += GRAVITY_PULL; } -// Whether one of the effects whose costume animates with the walk is on: Gamekid, My Little Unicorn, Unicorn Stump, -// Taurus, Book of Shadows and Holy Mantle. -bool Entity_Player::walking_items_has() -{ - for (int collectible : {COLLECTIBLE_GAMEKID, COLLECTIBLE_MY_LITTLE_UNICORN, COLLECTIBLE_UNICORN_STUMP, - COLLECTIBLE_TAURUS, COLLECTIBLE_BOOK_OF_SHADOWS, COLLECTIBLE_HOLY_MANTLE}) - if (temporaryEffects.HasCollectibleEffect(collectible)) return true; - return false; -} - // Holds the lifted item where the body's held null is, shown while that null shows. Whether the item is lifted. static bool held_item_pose_update(Entity_Player& player) { @@ -598,6 +603,16 @@ void Entity_Player::ClearDeadEyeCharge() EvaluateItems(); } +// The weapon that replaces the player's own for a while (part of 0077b020): Doctor's Remote's rocket, Notched Axe, +// the Urn of Souls, and Tainted Lilith's umbilical whip, else none. +static WeaponType weapon_override_get(Entity_Player& player) +{ + if (player.itemState == ITEM_STATE_DOCTORS_REMOTE) return WEAPON_ROCKETS; + if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_NOTCHED_AXE)) return WEAPON_NOTCHED_AXE; + if (player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_URN_OF_SOULS)) return WEAPON_URN_OF_SOULS; + return player.playerType == PLAYER_LILITH_B ? WEAPON_UMBILICAL_WHIP : WEAPON_NULL; +} + // 0077b020 Shooting, each frame: reads the shoot input, turns the head to the shot (or to the walk when idle), counts // the weapons' delays down and fires them, blinks the eyes while shooting and keeps the recent shot directions. The // items, item states and characters that change shooting stop the game until reached. @@ -626,9 +641,9 @@ void Entity_Player::update_shooting() if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_YBAB) reconstruction_missing("Entity_Player::update_shooting 0077b020 (the mirrored baby's aim)"); if (peeBurstCooldown > 0) reconstruction_missing("Entity_Player::update_shooting 0077b020 (Kidney Stone's burst)"); - if ((isPlayingExtraAnimation || isPlayingItemAnimation) && heldEntity && itemState != HELD_ITEM_STATE_FRIEND_BALL && + if ((isPlayingExtraAnimation || isPlayingItemAnimation) && heldEntity && itemState != COLLECTIBLE_MOMS_BRACELET && itemState != HELD_ITEM_STATE_SUPLEX) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (dropping the held entity)"); + ThrowHeldEntity(vector_scale(velocity, HELD_DROP_SPEED)); Vector markedAim = input.direction; TemporaryEffect* taurus = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_TAURUS); @@ -706,14 +721,24 @@ void Entity_Player::update_shooting() reconstruction_missing("Entity_Player::update_shooting 0077b020 (Tainted Eve's clots)"); uint32_t modifiers = (uint32_t)GetWeaponModifiers(); - if (itemState == ITEM_STATE_DOCTORS_REMOTE || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_NOTCHED_AXE) || - temporaryEffects.HasCollectibleEffect(COLLECTIBLE_URN_OF_SOULS) || playerType == PLAYER_LILITH_B) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (overriding weapons)"); - weapons[0].reset(); + WeaponType overriding = weapon_override_get(*this); + if (overriding == WEAPON_NULL) weapons[0].reset(); + else + { + if (!weapons[0] || weapons[0]->weaponType != overriding) weapons[0] = weapon_create(overriding, this); + if (!weapons[0]) reconstruction_missing("Entity_Player::update_shooting 0077b020 (this overriding weapon)"); + if (overriding != WEAPON_ROCKETS) canFire = true; + } for (int slot = 1; slot < WEAPON_SLOT_COUNT; slot++) if (weapons[slot]) weapons[slot]->modifiers = modifiers; - for (int slot = 1; slot < WEAPON_SLOT_COUNT; slot++) - if (weapons[slot]) weapons[slot]->Update(isInterpolation); + if (weapons[0]) + { + weapons[0]->modifiers = modifiers | WEAPON_MOD_OVERRIDE; + weapons[0]->Update(isInterpolation); + } + else + for (int slot = 1; slot < WEAPON_SLOT_COUNT; slot++) + if (weapons[slot]) weapons[slot]->Update(isInterpolation); if (itemState == ITEM_STATE_SHOOP_DA_WHOOP && isAiming) blinkTime = SHOOP_BLINK; int blinkFrame = blinkTime >= BLINK_CLOSED_FROM ? BLINK_CLOSED_FRAME : 0; @@ -731,16 +756,27 @@ void Entity_Player::update_shooting() if (HasCollectible(COLLECTIBLE_POINTY_RIB) || (playerType == PLAYER_LILITH && HasCollectible(COLLECTIBLE_BIRTHRIGHT))) blinkTime = std::max(blinkTime, POINTY_RIB_BLINK); + PassiveShot shot{shootDirection, isAiming, isShootHeld}; + trinity_shield_update(*this, shot); doubleTapFrames++; if (!isInterpolation && IsFrame(2, 0) && (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_SCISSORS) || HasEntityFlags(FLAG_BLEED_OUT))) reconstruction_missing("Entity_Player::update_shooting 0077b020 (the headless blood spray)"); + float savedLuck = luck; if (HasTrinket(TRINKET_TEARDROP_CHARM)) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (the luck trinket)"); + { + float charms = (float)GetTrinketMultiplier(TRINKET_TEARDROP_CHARM); + luck = charms + charms + 2 + luck; + } + float shotLuck = luck; if (itemState == COLLECTIBLE_BAG_OF_CRAFTING) bag_of_crafting_swing(*this, shootDirection, !isInterpolation && isShootHeld); + else if (itemState == COLLECTIBLE_MOMS_BRACELET) held_throw_update(shootDirection, isShootHeld); else if (itemState != 0) reconstruction_missing("Entity_Player::update_shooting 0077b020 (item states)"); + bool isTechFiveReady = itemState == 0 && (canFire || playerType == PLAYER_LILITH || playerType == PLAYER_LILITH_B); + if (isTechFiveReady) tech_five_update(*this, shot); if (canFire && isFireReady) trigger_fire_item_effects(shootDirection, isShootHeld); + if (luck == shotLuck) luck = savedLuck; if (!isShootHeld && blinkTime < 0 && headDirectionTime < 0 && game.roomTransition.mode == TRANSITION_NONE) { @@ -793,6 +829,8 @@ static void temporary_effects_update(Entity_Player& player) tainted_frame_update(player); effects.Update(); character_frame_update(player); + passives_frame_update(player); + trinkets_frame_update(player); lua_engine_get().PostPEffectUpdate(&player); } @@ -801,6 +839,7 @@ static void temporary_effects_update(Entity_Player& player) // animates. Items and effects the plain frame does not know and the held entity stop the game until reached. void Entity_Player::Update() { + equality_update(*this); if (isPlayingExtraAnimation && sprite.IsFinished()) isPlayingExtraAnimation = false; if (isPlayingItemAnimation && bodySprite.IsFinished() && !bodySprite.IsFinished("LiftItem")) { @@ -809,15 +848,21 @@ void Entity_Player::Update() heldSprite.Reset(); } update_pitfall(); + trinket_teleports_update(*this); + if (activeItems[ACTIVE_SLOT_SECONDARY].item != 0 && !HasCollectible(COLLECTIBLE_SCHOOLBAG) && !isCoopGhost) + reconstruction_missing("Entity_Player::Update 00782af0 (the second active dropped without the Schoolbag)"); if (isHurtPending && !isPlayingExtraAnimation) { isHurtPending = false; if (HasCollectible(COLLECTIBLE_INTRUDER) && !temporaryEffects.HasNullEffect(NULLITEM_INTRUDER)) reconstruction_missing("Entity_Player::Update 00782af0 (the spiders a hurt sets loose)"); } + book_of_belial_passive_update(*this); if (isDead) return death_update(); - if (!is_frame_plain() || heldEntity) + if (!is_frame_plain()) reconstruction_missing("Entity_Player::Update 00782af0 (items, effects and item animations)"); + held_entity_follow(); + height_update(); Entity::Update(); if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) @@ -827,6 +872,7 @@ void Entity_Player::Update() } sprite_scale_update(); costume_layers_update(); + lastActionTriggers = 0; update_body_animations(); update_bomb_input(); ControlActiveItem(ACTIVE_SLOT_PRIMARY); @@ -834,13 +880,18 @@ void Entity_Player::Update() update_shooting(); tractor_beam_update(*this); pockets_rotate(); + gnawed_leaf_update(*this); temporary_effects_update(*this); walk_animation_update(); if (damageCooldown > 0) damageCooldown--; if (controlsCooldown > 0) controlsCooldown--; if (fireBlockCooldown > 0) fireBlockCooldown--; if (itemHoldCooldown > 0) itemHoldCooldown--; + if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && HasCollectible(COLLECTIBLE_HOST_HAT) && + IsCollectibleAnimFinished(COLLECTIBLE_HOST_HAT, "")) + ClearCollectibleAnim(COLLECTIBLE_HOST_HAT); update_footprints(); + moms_hand_player_release_update(*this); lua_engine_get().PostPlayerUpdate(this); } @@ -869,9 +920,9 @@ void Entity_Player::Render(const Vector& offset) if (damageCooldown > 0 && damageCooldown % DAMAGE_BLINK_PERIOD < DAMAGE_BLINK_HIDDEN && IsExtraAnimationFinished() && g_game->challenge != CHALLENGE_GUARDIAN && !HasEntityFlags(FLAG_NO_DAMAGE_BLINK)) return; - if (heldEntity) reconstruction_missing("Entity_Player::Render 0078ca00 (the held entity)"); - + held_entity_render(renderOffset, HELD_BEHIND); render_pass(renderOffset, RENDER_PASS_MAIN); + held_entity_render(renderOffset, HELD_FRONT); lua_engine_get().PostPlayerRender(this, offset); if (!is_overlay_pass()) return; diff --git a/src/entity_player_health.cpp b/src/entity_player_health.cpp index 317fa6f..f7e28f2 100644 --- a/src/entity_player_health.cpp +++ b/src/entity_player_health.cpp @@ -1,4 +1,5 @@ #include "entity_player.h" +#include "entity_player_trinkets.h" #include "game.h" #include "entity_effect.h" #include "entity_pickup.h" @@ -611,8 +612,7 @@ void Entity_Player::UpdateHeartDependentEffects() temporaryEffects.AddCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON, true, 1); } - if (HasCollectible(COLLECTIBLE_CROWN_OF_LIGHT) || HasCollectible(COLLECTIBLE_DARK_PRINCES_CROWN)) - reconstruction_missing("Entity_Player::UpdateHeartDependentEffects 007c9ea0 (the crowns)"); + crowns_update(*this); if (HasCollectible(COLLECTIBLE_VASCULITIS) || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_VASCULITIS)) { cacheFlags |= CACHE_DAMAGE; @@ -667,7 +667,40 @@ void Entity_Player::update_greeds_gullet() int target = GetGreedsGulletHearts(); int current = greedsGulletHearts; if (target != current || greedsGulletOverflow > 0) - reconstruction_missing("Entity_Player::update_greeds_gullet 007ce420 (Greed's Gullet hearts changing)"); + { + if (game.deathmatchManager.is_active() && target > current && target > greedsGulletRedHearts) + { + redHearts += scale_for_hard_difficulty((target - current) * 2); + greedsGulletRedHearts = (short)target; + } + int delta = greedsGulletOverflow - current + target; + int unfit = 0; + switch (owner.GetHealthType()) + { + case HEALTH_DEFAULT: + case HEALTH_COIN: + unfit = scale_for_hard_difficulty(delta) + (owner.maxHearts >> 1); + owner.AddMaxHearts(delta * 2, false); + unfit -= owner.maxHearts >> 1; + break; + case HEALTH_SOUL: + unfit = ((owner.soulHearts + 1) >> 1) + scale_for_hard_difficulty(delta); + owner.AddSoulHearts(delta * 2, false); + unfit -= (owner.soulHearts + 1) >> 1; + break; + case HEALTH_BONE: + unfit = scale_for_hard_difficulty(delta) + owner.boneHearts; + owner.AddBoneHearts(delta); + unfit -= owner.boneHearts; + break; + default: + owner.isUpdatingGreedsGullet = false; + isUpdatingGreedsGullet = false; + return; + } + greedsGulletHearts = (short)target; + greedsGulletOverflow = (short)std::max(unfit, 0); + } owner.isUpdatingGreedsGullet = false; isUpdatingGreedsGullet = false; } @@ -1138,3 +1171,12 @@ bool Entity_Player::CanPickRottenHearts() if (owner.GetHealthType() == HEALTH_COIN) return false; return !owner.HasFullHearts() || owner.rottenHearts * 2 < owner.GetEffectiveMaxHearts(); } + +// 00758850 Heart containers taken away come first out of those the reversed Empress lent, then out of Strength's. +void Entity_Player::trigger_max_hearts_removed(int removed) +{ + int hearts = removed / 2; + int empress = std::min(hearts, reverseEmpressMaxHearts); + reverseEmpressMaxHearts -= empress; + strengthMaxHearts -= std::min(strengthMaxHearts, hearts - empress); +} diff --git a/src/entity_player_hits.cpp b/src/entity_player_hits.cpp new file mode 100644 index 0000000..cedc241 --- /dev/null +++ b/src/entity_player_hits.cpp @@ -0,0 +1,498 @@ +#include "entity_player_trinkets.h" +#include "active_items.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "grid_entity.h" +#include "grid_entity_poop.h" +#include "item_overlay.h" +#include "log.h" +#include "loot_list.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_grid.h" +#include "room_special.h" +#include "sfx_manager.h" +#include + +// The odds and amounts of the trinkets and collectibles (367 on) a hit sets off: Red Patch's chance and luck, Missing +// Page's Necronomicon, Salvation's count, the stomp, the pennies, Cartridge, the dice, Purity's colours, the shards, +// It Hurts' tears, Tonsil's familiars and the chance trinkets' one in so many. +constexpr int RED_PATCH_CHANCES[] = {20, 33, 50}; +constexpr int RED_PATCH_CHANCES_VERSUS[] = {10, 20, 30}; +constexpr float RED_PATCH_LUCK = 5; +constexpr float RED_PATCH_LUCK_VERSUS = 2.5f; +constexpr int MISSING_PAGE_ODDS = 20; +constexpr float MISSING_PAGE_LUCK = 0.3f; +constexpr int MISSING_PAGE_ODDS_MIN = 2; +constexpr int OVERLAY_MISSING_PAGE = 30; +constexpr int FISH_HEAD_VERSUS_ODDS = 5; +constexpr int GIANT_CELL_MAX = 16; +constexpr int SALVATION_HITS_MAX = 10; +constexpr float PERFECTION_SPEED_MIN = 4; +constexpr float PERFECTION_SPEED_RANDOM = 6; +constexpr float PERFECTION_FRICTION = 0.8f; +constexpr int PERFECTION_SHARD_SUBTYPE = 100; +constexpr int STOMPY_ODDS = 5; +constexpr float STOMPY_RADIUS_MAX = 90; +constexpr int STOMPY_TIMEOUT = 10; +constexpr float PENNY_SPEED_MIN = 2; +constexpr float PENNY_SPEED_RANDOM = 5; +constexpr int CARTRIDGE_ODDS = 20; +constexpr float CARTRIDGE_LUCK = 0.5f; +constexpr int CRACKED_DICE_CHANCES[] = {50, 75, 100}; +constexpr int CRACKED_DICE_ITEMS[] = {105, 166, 386, 406, 285}; +constexpr int BLEED_OUT_FRAMES = 600; +constexpr int SHARD_HEART_ODDS = 4; +constexpr int VARICOSE_ANEMIC_ODDS = 5; +constexpr int VARICOSE_ANEMIC_FRAMES = 60; +constexpr int IT_HURTS_TEARS = 10; +constexpr float IT_HURTS_SPEED = 10; +constexpr float IT_HURTS_SCALE = 1.33f; +constexpr float IT_HURTS_DAMAGE = 10; +constexpr int VENGEFUL_WISPS_MAX = 5; +constexpr int TONSIL_EXTRA = 1; +constexpr int TONSIL_HITS_MIN = 6; +constexpr int TONSIL_HITS_RANDOM = 7; +constexpr int LUNCH_ODDS[] = {20, 10, 7}; +constexpr float UMBILICAL_CHANCE = 0.3f; +constexpr float UMBILICAL_CHANCE_VERSUS = 0.1f; +constexpr float UMBILICAL_LUCK = 0.02f; +constexpr int BOZO_ODDS = 20; +constexpr int BOZO_ODDS_VERSUS = 33; +constexpr float BOZO_POOP_BEHIND = 15; +constexpr int BUTTER_ODDS[] = {50, 25, 16}; +constexpr int PICKUP_FREE_STEP = 40; + +// What a chance trinket rolls against: its plain value, or the stronger copies' (two, three or more). +static int trinket_strength(Entity_Player& player, int trinket, const int (&values)[3]) +{ + int multiplier = player.GetTrinketMultiplier(trinket); + return multiplier == 2 ? values[1] : multiplier > 2 ? values[2] : values[0]; +} + +// The player's familiars of a variant in the room. +static std::vector player_familiars(Entity_Player& player, int variant) +{ + std::vector familiars; + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->type == ENTITY_FAMILIAR && entity->variant == variant && + static_cast(entity)->player == &player) + familiars.push_back(static_cast(entity)); + return familiars; +} + +// A pickup dropped on a free spot near the player, its seed drawn first. +static void hit_pickup_drop(Entity_Player& player, int variant, int subType, uint32_t seed) +{ + Vector position = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_FREE_STEP}); + g_game->Spawn({.position = position, .spawner = &player, .subType = subType, .type = ENTITY_PICKUP, + .variant = variant, .seed = seed}); +} + +// Red Patch's part of 007729d0: a luck-raised chance (more for stronger copies) of its damage up for the room. +static void red_patch_hit(Entity_Player& player) +{ + bool isVersus = g_game->deathmatchManager.is_active(); + int chance = trinket_strength(player, TRINKET_RED_PATCH, isVersus ? RED_PATCH_CHANCES_VERSUS : RED_PATCH_CHANCES); + float luck = isVersus ? RED_PATCH_LUCK_VERSUS : RED_PATCH_LUCK; + + // An unlucky enough player turns the sum negative, which the original compares unsigned: always a hit. + if ((uint32_t)random_below(100) < (uint32_t)(chance + (int)(luck * player.luck))) + player.temporaryEffects.AddEffect(TemporaryEffect(g_manager->itemConfig.GetTrinket(TRINKET_RED_PATCH)), true, 1); +} + +// Missing Page's part of 007729d0: a luck-raised one in twenty that the Necronomicon goes off, with its overlay. +static void missing_page_hit(Entity_Player& player) +{ + int odds = std::max(MISSING_PAGE_ODDS_MIN, MISSING_PAGE_ODDS - (int)(player.luck * MISSING_PAGE_LUCK)); + if (random_below(odds) != 0) return; + npc_sound_play(SOUND_DEATH_CARD, 1, 2, 1); + g_game->itemOverlay.Show(OVERLAY_MISSING_PAGE, 0, nullptr); + player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM}); +} + +// Giant Cell's part of 007729d0: the player's Minisaacs heal, and one more joins them up to sixteen. +static void giant_cell_hit(Entity_Player& player) +{ + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Giant Cell in versus)"); + std::vector minisaacs = player_familiars(player, Entity_Familiar::MINISAAC); + for (Entity_Familiar* minisaac : minisaacs) minisaac->health = minisaac->maxHitPoints; + if (minisaacs.size() < GIANT_CELL_MAX) player.AddMinisaac(player.pos, true); +} + +// Perfection breaking on a penalized hit: its luck goes, and its shards fly off the player with a thumbs down. +static void perfection_break(Entity_Player& player) +{ + ItemConfig_Item* perfection = g_manager->itemConfig.GetTrinket(TRINKET_PERFECTION); + if (!perfection) return; + player.cacheFlags |= perfection->cacheFlags; + player.temporaryEffects.isEvaluateCachePending = true; + npc_sound_play(SOUND_THUMBS_DOWN, 1, 2, 1); + + uint32_t seed = Random(); + Vector direction = random_direction(); + Vector velocity = vector_scale(direction, random_unit() * PERFECTION_SPEED_RANDOM + PERFECTION_SPEED_MIN); + Entity* shards = g_game->Spawn({.position = player.pos, .velocity = velocity, .subType = PERFECTION_SHARD_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + EntityConfig_Entity* look = g_manager->entityConfig.GetEntity(ENTITY_PICKUP, PICKUP_TRINKET, 0); + shards->sprite.Load(look->anm2Path, GRAPHICS_DEFER); + shards->sprite.ReplaceSpritesheet(0, perfection->gfxFilename); + shards->sprite.LoadGraphics(); + shards->sprite.Play("Appear"); + shards->friction = PERFECTION_FRICTION; + shards->entityGridCollisionClass = GRIDCOLL_GROUND; + shards->Update(); +} + +// Swallowed Penny's part of 007729d0: a penny per copy bursts out, one or none for a coin-health player. +static void swallowed_penny_hit(Entity_Player& player) +{ + RNG& rng = player.GetTrinketRNG(TRINKET_SWALLOWED_PENNY); + int pennies = player.GetTrinketMultiplier(TRINKET_SWALLOWED_PENNY); + if (player.GetHealthType() == HEALTH_COIN) pennies = (int)rng.RandomInt(2); + else rng.Next(); + + for (; pennies > 0; pennies--) + { + uint32_t seed = Random(); + Vector direction = random_direction(); + Vector velocity = vector_scale(direction, random_unit() * PENNY_SPEED_RANDOM + PENNY_SPEED_MIN); + g_game->Spawn({.position = player.pos, .velocity = velocity, .spawner = &player, .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, .seed = seed}); + } +} + +// Purity's part of 007729d0: a hit ends its aura and rolls the next room's colour. +static void purity_hit(Entity_Player& player) +{ + if (g_game->deathmatchManager.is_active()) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Purity in versus)"); + player.temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_PURITY, 1); + player.purityState = (int)player.GetCollectibleRNG(COLLECTIBLE_PURITY).RandomInt(PURITY_STATES); + player.RemoveCostume(g_manager->itemConfig.GetNullItem(NULLITEM_PURITY_GLOW)); +} + +// Varicose Veins' part of 007729d0: the hit fires Tammy's Head's ring of tears, and one hit in five bleeds Anemic's +// trail for two seconds. +static void varicose_veins_hit(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Varicose Veins in versus)"); + + effects.AddCollectibleEffect(COLLECTIBLE_VARICOSE_VEINS, true, 1); + player.UseActiveItem({.item = COLLECTIBLE_TAMMYS_HEAD, .flags = USE_NOANIM}); + effects.RemoveCollectibleEffect(COLLECTIBLE_VARICOSE_VEINS, 1); + if (effects.HasCollectibleEffect(COLLECTIBLE_ANEMIC) || + player.GetCollectibleRNG(COLLECTIBLE_VARICOSE_VEINS).RandomInt(VARICOSE_ANEMIC_ODDS) != 0) + return; + TemporaryEffect anemic(g_manager->itemConfig.GetCollectible(COLLECTIBLE_ANEMIC)); + anemic.cooldown = VARICOSE_ANEMIC_FRAMES; + effects.AddEffect(anemic, true, 1); +} + +// It Hurts' part of 007729d0: ten blood tears burst out in a ring, and the tears go up for the room. +static void it_hurts_hit(Entity_Player& player) +{ + if (g_game->deathmatchManager.is_active()) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (It Hurts in versus)"); + for (int i = 0; i < IT_HURTS_TEARS; i++) + { + Vector velocity = vector_scale(vector_from_angle((float)i * DEGREES_PER_TURN / IT_HURTS_TEARS), IT_HURTS_SPEED); + uint32_t seed = Random(); + auto* tear = static_cast(g_game->Spawn({.position = player.pos, .velocity = velocity, + .spawner = &player, .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, .seed = seed})); + tear->SetScale(IT_HURTS_SCALE); + tear->SetCollisionDamage(IT_HURTS_DAMAGE); + tear->tearFlags.set(TEAR_BLOOD_CREEP); + } + player.temporaryEffects.AddNullEffect(NULLITEM_IT_HURTS, true, 1); + player.EvaluateItems(); +} + +// Torn Pocket's part of 007729d0: once per copy and once more, a coin, key or bomb (Bethany's soul charge as a half +// soul heart, Tainted Bethany's blood charge as a half heart, each one time in ten any heart), picked by how many the +// player holds, falls out of the pocket. +static void torn_pocket_hit(Entity_Player& player) +{ + enum PocketLoss + { + POCKET_COIN, + POCKET_KEY, + POCKET_BOMB, + POCKET_SOUL_CHARGE, + POCKET_BLOOD_CHARGE + }; + constexpr uint32_t POCKET_SHIFT_INDEX = 35; + constexpr int ANY_HEART_ODDS = 10; + RNG& pocketRng = player.GetTrinketRNG(TRINKET_TORN_POCKET); + + for (int i = player.GetTrinketMultiplier(TRINKET_TORN_POCKET) + 1; i > 0; i--) + { + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(POCKET_COIN, player.numCoins); + picker.AddOutcomeWeight(POCKET_KEY, player.numKeys); + picker.AddOutcomeWeight(POCKET_BOMB, player.numBombs); + if (player.playerType == PLAYER_BETHANY) picker.AddOutcomeWeight(POCKET_SOUL_CHARGE, player.effectiveSoulCharge); + else if (player.playerType == PLAYER_BETHANY_B) picker.AddOutcomeWeight(POCKET_BLOOD_CHARGE, player.effectiveBloodCharge); + RNG rng; + rng.SetSeed(pocketRng.Next(), POCKET_SHIFT_INDEX); + + int variant = PICKUP_HEART; + int subType = 0; + switch (picker.PickOutcome(rng)) + { + case POCKET_COIN: + player.AddCoins(-1); + variant = PICKUP_COIN; + break; + case POCKET_KEY: + player.AddKeys(-1); + variant = PICKUP_KEY; + break; + case POCKET_BOMB: + player.AddBombs(-1); + variant = PICKUP_BOMB; + break; + case POCKET_SOUL_CHARGE: + player.AddSoulCharge(-1); + break; + case POCKET_BLOOD_CHARGE: + player.AddBloodCharge(-1); + break; + default: + continue; + } + uint32_t seed = pocketRng.Next(); + if (variant == PICKUP_HEART && pocketRng.RandomInt(ANY_HEART_ODDS) != 0) + subType = player.playerType == PLAYER_BETHANY ? HEART_HALF_SOUL : HEART_HALF; + hit_pickup_drop(player, variant, subType, seed); + } +} + +// Hypercoagulation's part of 007729d0: the hit's blood flies out the way the player aims as a short lived half heart +// (a whole one for a big hit, black with Daemon's Tail, which lets only one in five through) with a burst of blood. +static void hypercoagulation_hit(Entity_Player& player, float damage) +{ + constexpr float AIM_REACH = 10; + constexpr float SCATTER = 2; + constexpr float BLOOD_SPEED = 18; + constexpr float SPAWN_LEAD = 0.4f; + constexpr int HEART_TIMEOUT = 45; + constexpr ColorMod DARK_BLOOD = {{0.3f, 0.3f, 0.3f, 1}, {1, 1, 1, 1}, {0, 0, 0}}; + bool isBlack = player.HasTrinket(TRINKET_DAEMONS_TAIL); + if (isBlack && player.GetTrinketRNG(TRINKET_DAEMONS_TAIL).RandomInt(DAEMONS_TAIL_ODDS) != 0) return; + + Vector aim = vector_scale(player.aimDirection, AIM_REACH); + Vector velocity = vector_resized(vector_add(aim, vector_scale(random_direction(), SCATTER)), BLOOD_SPEED); + int heart = isBlack ? (int)HEART_BLACK : damage > 1 ? (int)HEART_FULL : (int)HEART_HALF; + uint32_t seed = Random(); + auto* pickup = static_cast(g_game->Spawn({.position = vector_add(player.pos, vector_scale(velocity, SPAWN_LEAD)), + .velocity = velocity, .spawner = &player, .subType = heart, + .type = ENTITY_PICKUP, .variant = PICKUP_HEART, .seed = seed})); + pickup->timeout = HEART_TIMEOUT; + pickup->Update(); + Entity* blood = g_game->Spawn({.position = player.pos, .velocity = vector_scale(velocity, SPAWN_LEAD), .spawner = &player, + .subType = 2, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + if (isBlack) blood->SetColor(DARK_BLOOD, -1, 255, false, true); + blood->Update(); +} + +// Tonsil's part of 007729d0: every six to twelve hits a tonsil grows, one more than the trinket's copies at most, and +// then the trinket is spent. +static void tonsil_hit(Entity_Player& player) +{ + int multiplier = player.GetTrinketMultiplier(TRINKET_TONSIL); + if (--player.tonsilCounter < 1) + { + if (player.tonsilCount < multiplier + TONSIL_EXTRA) + { + player.cacheFlags |= CACHE_FAMILIARS; + player.tonsilCount++; + player.EvaluateItems(); + } + player.tonsilCounter = (short)(player.GetTrinketRNG(TRINKET_TONSIL).Next() % TONSIL_HITS_RANDOM + TONSIL_HITS_MIN); + } + if (multiplier + TONSIL_EXTRA <= player.tonsilCount) player.TryRemoveTrinket(TRINKET_TONSIL); +} + +// A trinket that drops its collectible once and is spent: Bag Lunch's Lunch from the boss pool, Wish Bone's from the +// room's. Pica Run's drops ignore the pickup modifiers. +static void trinket_item_drop(Entity_Player& player, int trinket, int collectible, uint32_t seed) +{ + bool isPica = g_game->challenge == CHALLENGE_PICA_RUN; + if (isPica) g_pickupIgnoreModifiers++; + hit_pickup_drop(player, PICKUP_COLLECTIBLE, collectible, seed); + if (isPica) g_pickupIgnoreModifiers--; + player.TryRemoveTrinket((uint32_t)trinket); +} + +// Bozo's part of 007729d0: one hit in twenty leaves a rainbow poop just behind the player, with a fart. +static void bozo_hit(Entity_Player& player) +{ + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_BOZO); + if (rng.RandomInt(g_game->deathmatchManager.is_active() ? BOZO_ODDS_VERSUS : BOZO_ODDS) != 0) return; + + Room& room = *g_game->room; + int cell = room.GetGridIndex(vector_sub(player.pos, vector_scale(vector_normalized(player.velocity), BOZO_POOP_BEHIND))); + GridEntity* grid = room.GetGridEntity(cell); + bool isFree = room.roomType != ROOM_DUNGEON && room.GetGridCollision(cell) == 0 && + !(grid && is_grid_floor_special(grid->type)); + if (isFree) room.SpawnGridEntity(cell, GRID_POOP, POOP_RAINBOW, rng.Next(), 0); + npc_sound_play(SOUND_FART, 1, 2, 1); +} + +// Butter's part of 007729d0: one hit in fifty (fewer with stronger copies) drops a passive the player owns. +static void butter_hit(Entity_Player& player) +{ + RNG& rng = player.GetTrinketRNG(TRINKET_BUTTER); + if (rng.RandomInt((uint32_t)trinket_strength(player, TRINKET_BUTTER, BUTTER_ODDS)) != 0) return; + + std::vector owned; + for (int id = 1; id < (int)player.collectibleCounts.size(); id++) + if (player.collectibleCounts[id] > 0 && player.CanRerollCollectible(id, false) && player.GetActiveItemSlot(id) < 0) + owned.push_back(id); + if (owned.empty()) return; + player.DropCollectible(owned[rng.RandomInt((uint32_t)owned.size())], nullptr, true); + sound_play(SOUND_BUTTER_DROP); +} + +// The hit part of 007729d0 for the trinkets and collectibles 367 on, in their order there (the collectibles 1 to 366 +// run first, in passives_hit_trigger): Red Patch, Missing Page, Fish Head, Leprosy, Giant Cell, Salvation, Perfection, +// Stompy, the Bird Cage, Larynx, Swallowed Penny, Cartridge, Curse of the Tower, Cracked Dice, Purity, the Crown of +// Light, the Shard of Glass, Varicose Veins, It Hurts, the Cracked Orb, the Vengeful Spirit, Torn Pocket, +// Hypercoagulation, Large Zit, Tonsil, Bag Lunch, Umbilical Cord, Wish Bone, Bozo and Butter. Whether the hurt +// animation still plays (Cartridge's Gamekid stops it). Cambion Conception stops the game until reached. +bool late_items_hit_trigger(Entity_Player& player, const ItemsHit& hit) +{ + Game& game = *g_game; + TemporaryEffects& effects = player.temporaryEffects; + bool isVersus = game.deathmatchManager.is_active(); + bool isHurtShown = true; + + if (player.HasTrinket(TRINKET_RED_PATCH)) red_patch_hit(player); + if (player.HasTrinket(TRINKET_MISSING_PAGE)) missing_page_hit(player); + if (player.HasTrinket(TRINKET_FISH_HEAD) && (!isVersus || random_below(FISH_HEAD_VERSUS_ODDS) == 0)) + { + int multiplier = player.GetTrinketMultiplier(TRINKET_FISH_HEAD); + player.AddBlueFlies(multiplier * (random_below(2) + 1), player.pos, nullptr); + } + if (player.HasCollectible(COLLECTIBLE_LEPROSY)) + { + if (isVersus) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Leprosy in versus)"); + player.AddLeprosy(); + } + if (player.HasCollectible(COLLECTIBLE_GIANT_CELL)) giant_cell_hit(player); + if (player.HasCollectible(COLLECTIBLE_SALVATION) && effects.GetCollectibleEffectNum(COLLECTIBLE_SALVATION) < SALVATION_HITS_MAX) + effects.AddCollectibleEffect(COLLECTIBLE_SALVATION, true, 1); + if (hit.isPenalized && player.HasTrinket(TRINKET_PERFECTION) && player.TryRemoveTrinket(TRINKET_PERFECTION)) + perfection_break(player); + if (player.HasPlayerForm(PLAYER_FORM_STOMPY) && random_below(STOMPY_ODDS) == 0) + { + uint32_t seed = Random(); + auto* wave = static_cast(game.Spawn({.position = player.pos, .spawner = &player, + .type = ENTITY_EFFECT, .variant = EFFECT_SHOCKWAVE, + .seed = seed})); + wave->parent = &player; + wave->SetRadii(player.size, STOMPY_RADIUS_MAX); + wave->SetTimeout(STOMPY_TIMEOUT); + } + + if (player.HasCollectible(COLLECTIBLE_BIRD_CAGE)) + { + effects.AddCollectibleEffect(COLLECTIBLE_BIRD_CAGE, true, 1); + player.RemoveCostume(g_manager->itemConfig.GetCollectible(COLLECTIBLE_BIRD_CAGE)); + } + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + if (player.activeItems[slot].item == COLLECTIBLE_LARYNX) player.AddActiveCharge(1, slot, false, false, false); + if (player.HasTrinket(TRINKET_SWALLOWED_PENNY)) swallowed_penny_hit(player); + if (player.HasTrinket(TRINKET_CARTRIDGE)) + { + int odds = std::max(1, CARTRIDGE_ODDS - (int)(player.luck * CARTRIDGE_LUCK)); + int roll = (int)player.GetTrinketRNG(TRINKET_CARTRIDGE).RandomInt((uint32_t)odds); + if (roll < player.GetTrinketMultiplier(TRINKET_CARTRIDGE) && !effects.HasCollectibleEffect(COLLECTIBLE_GAMEKID)) + { + player.UseActiveItem({.item = COLLECTIBLE_GAMEKID, .flags = USE_NOANIM}); + isHurtShown = false; + } + } + if (player.HasCollectible(COLLECTIBLE_CURSE_OF_THE_TOWER) && hit.source.type != ENTITY_BOMB && hit.source.type != ENTITY_SLOT) + effects.AddEffect(TemporaryEffect(g_manager->itemConfig.GetCollectible(COLLECTIBLE_ANARCHIST_COOKBOOK)), true, 1); + if (player.HasTrinket(TRINKET_CRACKED_DICE)) + { + RNG& rng = player.GetTrinketRNG(TRINKET_CRACKED_DICE); + if (rng.RandomInt(100) < (uint32_t)trinket_strength(player, TRINKET_CRACKED_DICE, CRACKED_DICE_CHANCES)) + player.UseActiveItem({.item = CRACKED_DICE_ITEMS[rng.RandomInt((uint32_t)std::size(CRACKED_DICE_ITEMS))], + .flags = USE_NOANIM}); + } + if (player.HasCollectible(COLLECTIBLE_PURITY) && effects.HasCollectibleEffect(COLLECTIBLE_PURITY)) purity_hit(player); + if (!isVersus && player.HasCollectible(COLLECTIBLE_CROWN_OF_LIGHT) && effects.HasCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT)) + { + effects.RemoveCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT, 1); + player.crownOfLightSprite.Play("FloatNoGlow"); + } + if (player.HasCollectible(COLLECTIBLE_CAMBION_CONCEPTION)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Cambion Conception)"); + + if (player.HasCollectible(COLLECTIBLE_SHARD_OF_GLASS)) + { + player.AddEntityFlags(FLAG_BLEED_OUT); + player.bleedSource = EntityRef(&player); + if (player.bleedOutHealth < 1) player.bleedOutHealth = BLEED_OUT_FRAMES; + if (player.GetCollectibleRNG(COLLECTIBLE_SHARD_OF_GLASS).RandomInt(SHARD_HEART_ODDS) == 0) + hit_pickup_drop(player, PICKUP_HEART, HEART_FULL, Random()); + } + if (player.HasCollectible(COLLECTIBLE_VARICOSE_VEINS) && !effects.HasCollectibleEffect(COLLECTIBLE_VARICOSE_VEINS)) + varicose_veins_hit(player); + if (player.HasCollectible(COLLECTIBLE_IT_HURTS)) it_hurts_hit(player); + if (player.HasCollectible(COLLECTIBLE_CRACKED_ORB)) player.trigger_cracked_orb({}); + if (player.HasCollectible(COLLECTIBLE_VENGEFUL_SPIRIT)) + { + int wisps = (int)std::ranges::count_if(player_familiars(player, Entity_Familiar::WISP), [](Entity_Familiar* wisp) + { return wisp->subtype == COLLECTIBLE_VENGEFUL_SPIRIT; }); + if (wisps <= VENGEFUL_WISPS_MAX) player.AddWisp(COLLECTIBLE_VENGEFUL_SPIRIT, player.pos, false, false); + } + if (player.HasTrinket(TRINKET_TORN_POCKET)) torn_pocket_hit(player); + if (player.HasCollectible(COLLECTIBLE_HYPERCOAGULATION) && !(hit.damageFlags & (DAMAGE_IV_BAG | DAMAGE_NO_PENALTIES))) + hypercoagulation_hit(player, hit.damage); + if (player.HasCollectible(COLLECTIBLE_LARGE_ZIT)) player.DoZitEffect(vector_from_angle(random_unit() * DEGREES_PER_TURN)); + if (player.HasTrinket(TRINKET_TONSIL)) tonsil_hit(player); + if (player.HasTrinket(TRINKET_BAG_LUNCH) && + player.GetTrinketRNG(TRINKET_BAG_LUNCH).RandomInt((uint32_t)trinket_strength(player, TRINKET_BAG_LUNCH, LUNCH_ODDS)) == 0) + { + game.itemPool.lastPool = POOL_BOSS; + trinket_item_drop(player, TRINKET_BAG_LUNCH, COLLECTIBLE_LUNCH, Random()); + } + + float cordChance = (isVersus ? UMBILICAL_CHANCE_VERSUS : UMBILICAL_CHANCE) + player.luck * UMBILICAL_LUCK; + if (player.HasTrinket(TRINKET_UMBILICAL_CORD) && player.GetTrinketRNG(TRINKET_UMBILICAL_CORD).RandomFloat() <= cordChance) + effects.AddCollectibleEffect(COLLECTIBLE_GEMINI, true, 1); + if (player.HasTrinket(TRINKET_WISH_BONE)) + { + RNG& rng = player.GetTrinketRNG(TRINKET_WISH_BONE); + if (rng.RandomInt((uint32_t)trinket_strength(player, TRINKET_WISH_BONE, LUNCH_ODDS)) == 0) + trinket_item_drop(player, TRINKET_WISH_BONE, 0, rng.Next()); + } + if (player.HasCollectible(COLLECTIBLE_BOZO)) bozo_hit(player); + if (player.HasTrinket(TRINKET_BUTTER)) butter_hit(player); + return isHurtShown; +} + +// Cursed Skull's part of 007729d0: a hit leaving the player at its last red heart (two with three copies) and no soul +// hearts to spare sends it to a random room. Stronger copies pick among the special rooms. +void cursed_skull_teleport(Entity_Player& player) +{ + constexpr int SKULL_STRONG = 3; + int multiplier = player.GetTrinketMultiplier(TRINKET_CURSED_SKULL); + int hearts = scale_for_hard_difficulty(multiplier >= SKULL_STRONG ? 2 : 1); + bool isLow = player.redHearts <= hearts && (player.soulHearts < 1 || (player.redHearts < 1 && player.soulHearts <= hearts)); + if (!isLow) return; + if (multiplier != 1) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (golden Cursed Skull's special rooms)"); + game_random_room_move(*g_game, false, player.GetTrinketRNG(TRINKET_CURSED_SKULL).Next(), &player); +} diff --git a/src/entity_player_hold.cpp b/src/entity_player_hold.cpp index 33c12d1..e095b31 100644 --- a/src/entity_player_hold.cpp +++ b/src/entity_player_hold.cpp @@ -1,6 +1,8 @@ #include "entity_bomb.h" #include "entity_effect.h" +#include "entity_familiar.h" #include "entity_player.h" +#include "game.h" #include "log.h" #include "manager.h" #include "npc_ai.h" @@ -11,6 +13,21 @@ constexpr float THROWN_BOMB_OFFSET_Y = -24; constexpr float THROWN_ROCKET_OFFSET_Y = -14; constexpr float THROWN_BOMB_FALL_SPEED = -4; constexpr float THROWN_ROCKET_SPEED = 15; +constexpr float LIFTED_ROCK_HEIGHT = -10; +constexpr float THROWN_PLAYER_SLOWDOWN = 0.3f; +constexpr float HELD_RENDER_SCALE = 0.65f; +constexpr float HELD_THROW_SPEED = 10; +constexpr float HELD_THROW_BOOST = 1.2f; +constexpr int HELD_HIDE_COOLDOWN = 5; +constexpr int SUPLEX_GRAB = 1; +constexpr float PLAYER_FALL_GRAVITY = 1.1f; +constexpr float THROWN_GRAVITY = 0.6f; +constexpr float THROWN_HIGH = -26; +constexpr float BODY_BOUNCE_PULL = 0.2f; +constexpr float BODY_BOUNCE_GRAVITY = 0.6f; +constexpr float BODY_BOUNCE_MIN = 2; +constexpr float BODY_BOUNCE_KEEP = -0.45f; +constexpr int BODY_LANDING_SHAKE = 4; // A held bomb leaving the hands: a rocket aimed along the throw at shoulder height, any other bomb falling from over // the head. Both fly at the throw's velocity and stop being held and kept across rooms. @@ -64,3 +81,229 @@ Entity* Entity_Player::ThrowHeldEntity(Vector throwVelocity) heldEntity = nullptr; return held; } + +// 007d2170 Takes an entity in both hands: a bomb that still collides (a rocket straightened), Mom's Bracelet's lifted +// rock, a suplexed enemy, a Dip or Cube Baby, a poop pile, or Tainted Forgotten's body not yet held or thrown. The +// entity hides and stops colliding while held, and the player lifts it. False when the hands are full or it is none of +// those. +bool Entity_Player::TryHoldEntity(Entity* entity) +{ + if (heldEntity || !entity) return false; + + isHeldEntityVisible = entity->isVisible; + heldEntityGridCollisionClass = entity->entityGridCollisionClass; + heldEntityCollisionClass = entity->entityCollisionClass; + bool isBodyFree = entity->type == ENTITY_PLAYER && entity != this && + static_cast(entity)->playerType == PLAYER_THEFORGOTTEN_B && + !entity->HasEntityFlags(FLAG_HELD | FLAG_THROWN); + bool isHeldFamiliar = entity->type == ENTITY_FAMILIAR && + (entity->variant == Entity_Familiar::DIP || entity->variant == Entity_Familiar::CUBE_BABY); + + if (entity->type == ENTITY_BOMB) + { + if (entity->entityCollisionClass == ENTCOLL_NONE || entity->isDead) return false; + entity->flags |= FLAG_PERSISTENT | FLAG_HELD; + entity->spawnerType = type; + entity->posOffset = {}; + if (static_cast(entity)->IsRocket()) + { + entity->sprite.Play("Idle"); + entity->sprite.rotation = 0; + } + } + else if (entity->type == ENTITY_EFFECT && entity->variant == EFFECT_GRID_ENTITY_PROJECTILE_HELPER) + { + entity->flags |= FLAG_PERSISTENT; + entity->spawnerType = type; + entity->posOffset = vector_make(0, LIFTED_ROCK_HEIGHT); + } + else if (isBodyFree) + { + auto* body = static_cast(entity); + body->velocity = {}; + body->flags |= FLAG_HELD; + if (body->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_RECALL)) npc_sound_play(SOUND_RECALL_FINISH, 1, 2, 1); + body->temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_RECALL, -1); + } + else if (isHeldFamiliar || (entity->IsEnemy() && suplexState == SUPLEX_GRAB)) entity->flags |= FLAG_HELD; + else if (entity->type == ENTITY_POOP) entity->flags |= FLAG_PERSISTENT | FLAG_HELD; + else return false; + + entity->isVisible = false; + entity->entityCollisionClass = ENTCOLL_NONE; + heldEntity = entity; + PlayExtraAnimation("LiftItem", false); + heldSprite.Reset(); + FlushQueueItem(); + itemState = COLLECTIBLE_MOMS_BRACELET; + itemStateCooldown = 0; + return true; +} + +// 007d2930 Thrown: the player rises at the throw's height and adds the throw to its motion, a grounded walker first +// losing most of its own when a player threw it. +bool Entity_Player::TryThrow(const EntityRef& source, const Vector& throwVelocity, float height) +{ + bool isGrounded = !canFly && entityGridCollisionClass == GRIDCOLL_GROUND && posOffset.y >= 0; + if (source.type != ENTITY_PLAYER && !isGrounded) return false; + + if (source.type == ENTITY_PLAYER) velocity = vector_scale(velocity, THROWN_PLAYER_SLOWDOWN); + heightVelocity = -height; + posOffset.y = 0; + velocity = vector_add(velocity, throwVelocity); + return true; +} + +// The held entity's part of 00782af0: it moves with the player. A held player sits at the height of the body's held +// null. +void Entity_Player::held_entity_follow() +{ + if (!heldEntity) return; + + heldEntity->pos = pos; + heldEntity->velocity = velocity; + if (!heldEntity->is_player()) return; + + if (suplexState > SUPLEX_GRAB && !bodySprite.GetNullFrameById(0)) + reconstruction_missing("Entity_Player::Update 00782af0 (a suplexed player's height)"); + if (const NullFrame* held = bodySprite.GetNullFrameById(0)) + heldEntity->posOffset.y = held->pos.y / HELD_RENDER_SCALE * playerSpriteScale.y; +} + +// Part of 0078ca00: draws the held entity on its side of the player, at the body's held null while lifting, shown for +// the draw only. One with a negative depth goes behind. +void Entity_Player::held_entity_render(Vector renderOffset, HeldSide side) +{ + if (!heldEntity || heldEntity->isVisible || (heldEntity->renderZOffset < 0) != (side == HELD_BEHIND)) return; + + Vector lift{}; + if (itemState == COLLECTIBLE_MOMS_BRACELET || suplexState > SUPLEX_GRAB) + { + if (suplexState > SUPLEX_GRAB) reconstruction_missing("Entity_Player::Render 0078ca00 (a suplexed entity)"); + const NullFrame* held = bodySprite.animState.animData ? bodySprite.GetNullFrameById(0) : nullptr; + if (!held) return; + lift = held->pos; + } + + Entity& entity = *heldEntity; + entity.isVisible = true; + entity.Render(vector_add(vector_add(vector_scale(vector_sub(pos, entity.pos), HELD_RENDER_SCALE), renderOffset), lift)); + entity.isVisible = false; +} + +// Whether Tainted Forgotten's soul holds its body while the body's weapon takes the throw over or its urethra is +// blocked, and so keeps it. +static bool is_body_busy(Entity_Player& player) +{ + Entity_Player* body = player.playerType == PLAYER_THESOUL_B ? player.twin_get() : nullptr; + if (!body || player.heldEntity != body) return false; + + Weapon* weapon = body->weapons[0] ? body->weapons[0].get() : body->weapons[1].get(); + if (!weapon || body->peeBurstCooldown > 0) return false; + return (weapon->CanOverrideForgottenThrow() || body->isUrethraBlocked) && player.canShoot; +} + +// The held entity's item state in 0077b020: the lift is held unless a teleport is under way, a press throws the +// entity along the aim (with the walk's push, a little faster) and hides the hands, using up Mom's Bracelet. With the +// hands emptied the state ends. +void Entity_Player::held_throw_update(Vector shootDirection, bool isShooting) +{ + RoomTransition& transition = g_game->roomTransition; + bool isTeleporting = transition.is_active() && transition.is_teleport(); + if (!isTeleporting && !isPlayingItemAnimation && !isPlayingExtraAnimation && heldEntity) + { + PlayExtraAnimation("LiftItem", false); + bodySprite.SetLastFrame(); + heldSprite.Reset(); + } + if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + + if (isShooting && heldEntity && !is_body_busy(*this)) + { + Vector aim = vector_add(vector_scale(shootDirection, HELD_THROW_SPEED), + GetTearMovementInheritance(shootDirection, INHERIT_CHECKED)); + Vector throwVelocity = vector_scale(aim, HELD_THROW_BOOST); + ThrowHeldEntity(throwVelocity); + heldSprite.Reset(); + blinkTime = 1; + itemStateCooldown = HELD_HIDE_COOLDOWN; + PlayExtraAnimation("HideItem", false); + if (activeItems[ACTIVE_SLOT_PRIMARY].item == COLLECTIBLE_MOMS_BRACELET) DischargeActiveItem(ACTIVE_SLOT_PRIMARY, false); + return; + } + if (heldEntity || itemStateCooldown != 0) return; + + heldSprite.Reset(); + itemStateCooldown = HELD_HIDE_COOLDOWN; + blinkTime = 1; + PlayExtraAnimation("HideItem", false); +} + +// 007dac80 Tainted Forgotten's body, held by its soul, is thrown along a direction when it attacks, unless Kidney +// Stone's burst holds it. True when thrown. +bool Entity_Player::TryForgottenThrow(Vector direction) +{ + Entity_Player* soul = playerType == PLAYER_THEFORGOTTEN_B ? twin_get() : nullptr; + if (!soul || soul->heldEntity != this || peeBurstCooldown >= 1) return false; + + Vector aim = vector_normalized(direction); + Vector throwVelocity = vector_add(vector_scale(aim, HELD_THROW_SPEED), soul->GetTearMovementInheritance(aim, INHERIT_CHECKED)); + soul->ThrowHeldEntity(vector_scale(throwVelocity, HELD_THROW_BOOST)); + soul->heldSprite.Reset(); + soul->blinkTime = 1; + soul->itemStateCooldown = HELD_HIDE_COOLDOWN; + soul->PlayExtraAnimation("HideItem", false); + return true; +} + +// Part of 00782af0: a player off the ground falls back (a thrown one slower, flying over obstacles while high) and +// lands, a thrown one regaining control outside transitions, Tainted Forgotten's body with a thud and a shake. The +// body's head bobs on its own spring, pushed by the fall. +void Entity_Player::height_update() +{ + if (HasEntityFlags(FLAG_HELD)) heightVelocity = 0; + else if (posOffset.y < 0 || heightVelocity < 0) + { + bool isThrown = HasEntityFlags(FLAG_THROWN); + if ((canFly || entityGridCollisionClass != GRIDCOLL_GROUND) && !isThrown) + { + posOffset.y = 0; + heightVelocity = 0; + } + else + { + forgottenBHeight -= heightVelocity; + if (forgottenBHeight > 0) forgottenBHeightVelocity -= forgottenBHeight * BODY_BOUNCE_PULL; + posOffset.y += heightVelocity; + heightVelocity += isThrown ? THROWN_GRAVITY : PLAYER_FALL_GRAVITY; + bool isHigh = heightVelocity < 0 || posOffset.y < THROWN_HIGH; + if (isThrown) entityGridCollisionClass = isHigh || canFly ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; + if (posOffset.y > 0) height_land(); + } + } + if (playerType != PLAYER_THEFORGOTTEN_B) return; + + float bounce = forgottenBHeightVelocity; + forgottenBHeight += bounce; + if (forgottenBHeight < 0 || bounce <= 0) bounce += BODY_BOUNCE_GRAVITY; + else bounce = bounce >= BODY_BOUNCE_MIN ? bounce * BODY_BOUNCE_KEEP : 0; + if (forgottenBHeight >= 0) forgottenBHeight = 0; + forgottenBHeightVelocity = bounce; +} + +// A player reaching the ground: a thrown one lands and, outside transitions, takes control again, Tainted +// Forgotten's body with a thud and a shake. +void Entity_Player::height_land() +{ + posOffset.y = 0; + heightVelocity = 0; + if (!HasEntityFlags(FLAG_THROWN)) return; + + ClearEntityFlags(FLAG_THROWN); + if (g_game->roomTransition.is_active() || g_game->stageTransition.state != STAGE_TRANSITION_NONE) return; + isControlsEnabled = true; + if (playerType != PLAYER_THEFORGOTTEN_B) return; + g_game->screenShakeTimer = BODY_LANDING_SHAKE; + sound_play(SOUND_BONE_BOUNCE); + sound_play(SOUND_BONE_DROP); +} diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index 25d7187..e67f9ad 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -1,9 +1,12 @@ #include "entity_player.h" +#include "entity_player_trinkets.h" #include "active_items.h" #include "entity_familiar.h" #include "entity_pickup.h" #include "stage_transition.h" +#include "entity_player_passives.h" #include "game.h" +#include "item_pool.h" #include "lua_engine.h" #include "room.h" #include "room_grid.h" @@ -16,7 +19,6 @@ constexpr int ROOM_TRINKET_ROLL_SHIFT = 13; constexpr float PICKUP_SPAWN_STEP = 40; -constexpr int RAINBOW_WORM_FRAMES = 90; constexpr uint32_t DAILY_RAINBOW_TRINKETS = 28; constexpr int ERROR_TRINKET_RANGE = 189; constexpr uint32_t GRANTED_FIRE_MIND = 0x8; @@ -493,39 +495,32 @@ int Entity_Player::GetZodiacEffect() return ZODIAC_SIGNS[((seed >> ROLL_SHIFTS[2]) ^ seed) % ZODIAC_SIGNS.size()]; } -// 007a8350 The effects a new room gives back: Holy Mantle's shield (and the Blanket's in a boss room), Whore of -// Babylon at one red heart (Eve's at two, or always with her Birthright), the shields Holy Mantle stacks and Holy Card -// keep, Camo Undies, and the effects of the items that last the floor. A shield broken in the last room is taken away -// first. The other items and trinkets with room effects stop the game until reached. +// 007a8350 The effects a new room gives back: Holy Mantle's shield (and the Blanket's in a boss room), Taurus's charge +// in a room seen for the first time, Whore of Babylon at one red heart (Eve's at two, or always with her Birthright), +// Scapular, the shields Holy Mantle stacks and Holy Card keep, Camo Undies, and the effects of the items that last the +// floor, with the trinkets' room effects (entity_player_trinkets.cpp) in their places. A shield broken in the last room +// is taken away first. The other items with room effects stop the game until reached. void Entity_Player::TriggerNewRoom_TemporaryEffects() { - // Redemption, Taurus, Empty Vessel, Scapular, Purity, the crowns and Sol. - constexpr int ROOM_ITEMS[] = {673, 299, 409, 142, 407, 415, 442, 588}; - // Liberty Cap, Broken Syringe, Mom's Lock, Modeling Clay, Umbilical Cord and Dice Bag. - constexpr int ROOM_TRINKETS[] = {32, 132, 153, 166, 33, 154}; - constexpr int BLANKET = 535; + // Empty Vessel and Sol. + constexpr int ROOM_ITEMS[] = {409, 588}; constexpr int CAMO_UNDIES = 497; - constexpr int NULLITEM_HOLY_CARD = 46; ItemConfig& items = g_manager->itemConfig; ItemConfig_Item* mantle = items.GetCollectible(COLLECTIBLE_HOLY_MANTLE); for (int item : ROOM_ITEMS) if (HasCollectible(item)) reconstruction_missing("Entity_Player::TriggerNewRoom_TemporaryEffects 007a8350 (room items)"); - for (int trinket : ROOM_TRINKETS) - if (HasTrinket((uint32_t)trinket)) - reconstruction_missing("Entity_Player::TriggerNewRoom_TemporaryEffects 007a8350 (room trinkets)"); - if (modelingClayEffect != 0 || GetZodiacEffect() == COLLECTIBLE_TAURUS) - reconstruction_missing("Entity_Player::TriggerNewRoom_TemporaryEffects 007a8350 (Modeling Clay and Taurus)"); + trinkets_room_enter(*this); if (holyMantleState == 0) { if (HasCollectible(COLLECTIBLE_HOLY_MANTLE) && !temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HOLY_MANTLE)) temporaryEffects.AddCollectibleEffect(COLLECTIBLE_HOLY_MANTLE, true, 1); - if (HasCollectible(BLANKET) && g_game->room->roomType == ROOM_BOSS) + if (HasCollectible(COLLECTIBLE_BLANKET) && g_game->room->roomType == ROOM_BOSS) { temporaryEffects.AddCollectibleEffect(COLLECTIBLE_HOLY_MANTLE, true, 1); - temporaryEffects.AddCollectibleEffect(BLANKET, true, 1); + temporaryEffects.AddCollectibleEffect(COLLECTIBLE_BLANKET, true, 1); } } else @@ -535,12 +530,23 @@ void Entity_Player::TriggerNewRoom_TemporaryEffects() temporaryEffects.isDisabled ? nullptr : temporaryEffects.GetCollectibleEffect(COLLECTIBLE_HOLY_MANTLE); if (!shield || shield->count < 1) RemoveCostume(mantle); } + if (HasCollectible(COLLECTIBLE_TAURUS) || GetZodiacEffect() == COLLECTIBLE_TAURUS) + { + taurusSpeedBonus = 0; + SetColor(COLOR_DEFAULT, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (ItemConfig_Item* taurus = items.GetCollectible(COLLECTIBLE_TAURUS); taurus && g_game->room->isFirstVisit) + temporaryEffects.AddEffect(TemporaryEffect(taurus), true, 1); + } if (HasCollectible(COLLECTIBLE_WHORE_OF_BABYLON) && !temporaryEffects.HasCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON)) { TryRemoveCollectibleCostume(COLLECTIBLE_WHORE_OF_BABYLON, false); bool isEveAwake = playerType == PLAYER_EVE && (redHearts < 3 || HasCollectible(COLLECTIBLE_BIRTHRIGHT)); if (redHearts < 2 || isEveAwake) temporaryEffects.AddCollectibleEffect(COLLECTIBLE_WHORE_OF_BABYLON, true, 1); } + umbilical_cord_room_enter(*this); + if (ItemConfig_Item* scapular = items.GetCollectible(COLLECTIBLE_SCAPULAR); scapular && HasCollectible(COLLECTIBLE_SCAPULAR)) + temporaryEffects.AddEffect(TemporaryEffect(scapular), true, 1); + crowns_room_enter(*this); for (int i = 0; mantle && i < holyMantleStacks >> 4; i++) temporaryEffects.AddEffect(TemporaryEffect(mantle), true, 1); @@ -553,6 +559,7 @@ void Entity_Player::TriggerNewRoom_TemporaryEffects() for (int id : levelEffectItems) if (ItemConfig_Item* item = items.GetCollectible(id)) temporaryEffects.AddEffect(TemporaryEffect(item), true, 1); + dice_bag_room_enter(*this); holyMantleState = holyMantleState > 1; } @@ -566,7 +573,6 @@ constexpr int EVENT_RUBBER_CEMENT = 201; constexpr int PILL_TEARS_UP = 16; constexpr int BINGE_EATER_STEW_FRAMES = 900; constexpr int T_BETHANY_HEART_CAP = 12; -constexpr int HISTORY_POOL_NONE = -1; // An unlock earned by holding more than a number of items of a tag (Dead, Syringe, Mom, Tech, Battery, Stars). struct TagUnlock @@ -913,6 +919,160 @@ static void experimental_treatment_gain(Entity_Player& p, RNG& rng) } } +// The pennies Pageant Boy may leave a trinket of, in its order, and the coins it drops with it. +constexpr std::array PAGEANT_PENNIES = {TRINKET_BUTT_PENNY, TRINKET_BLOODY_PENNY, TRINKET_BURNT_PENNY, + TRINKET_FLAT_PENNY, TRINKET_COUNTERFEIT_PENNY, TRINKET_ROTTEN_PENNY, + TRINKET_BLESSED_PENNY, TRINKET_CHARGED_PENNY, TRINKET_CURSED_PENNY}; +constexpr int PAGEANT_COINS = 7; +constexpr int CARD_ITEM_SPECIAL_CHANCE = 25; +constexpr int CARD_ITEM_SUIT_CHANCE = 10; +constexpr uint32_t CARD_ITEM_SHIFT_INDEX = 35; +constexpr int CHALLENGE_STARTER_DECK_CARDS = 3; +constexpr int CHALLENGE_STARTER_DECK_CARD = 1; +constexpr int ABADDON_BLACK_HEARTS = 4; +constexpr int ABADDON_VERSUS_SHIFT = 4; +constexpr int TOXIC_SHOCK_POISON_FRAMES = 90; +constexpr uint64_t TOXIC_SHOCK_IMMUNE = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_FRIENDLY; +constexpr int PILL_COLOR_LAST = 14; + +// Pageant Boy's first pickup: seven random coins, eight when one of them is a penny trinket still available. +static void pageant_boy_gain(Entity_Player& p, RNG& rng) +{ + std::vector pennies; + for (int id : PAGEANT_PENNIES) + if (ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(id); trinket && trinket->IsAvailableEx(AVAILABLE_ALL)) + pennies.push_back(id); + int penny = pennies.empty() ? 0 : pennies[rng.RandomInt(pennies.size())]; + int drops = PAGEANT_COINS + (penny != 0); + int pennyDrop = penny ? (int)rng.RandomInt(drops) : -1; + + for (int i = 0; i < drops; i++) + { + Vector position = pickup_spawn_position(p.pos); + bool isPenny = i == pennyDrop; + pickup_drop(position, {isPenny ? PICKUP_TRINKET : PICKUP_COIN, isPenny ? penny : 0, rng.Next(), &p}, i); + } +} + +// A card an item hands out: drawn with more special cards and no runes, then offered to the mods' card callback. +static int item_card_roll(uint32_t seed) +{ + int card = ItemPool::GetCardEx((int)seed, CARD_ITEM_SPECIAL_CHANCE, 0, CARD_ITEM_SUIT_CHANCE, true); + RNG rng = rng_make(seed, CARD_ITEM_SHIFT_INDEX); + return lua_engine_get().GetCard({.rng = &rng, .card = card, .isPlaying = true}); +} + +// Magic 8 Ball's first pickup: a card. +static void magic_8_ball_gain(Entity_Player& p, RNG& rng) +{ + Vector position = pickup_spawn_position(p.pos); + uint32_t seed = rng.Next(); + pickup_drop(position, {PICKUP_TAROTCARD, item_card_roll(rng.Next()), seed, &p}); +} + +// Abaddon's first pickup: the heart containers (and the Forgotten's soul's) go, and black hearts for them and four +// more take their place. A versus match keeps half the containers for a sixteenth of the hearts. +static void abaddon_gain(Entity_Player& p) +{ + Entity_Player* soul = p.subPlayer; + int blackHearts = (soul ? soul->maxHearts : 0) + ABADDON_BLACK_HEARTS + p.maxHearts; + + if (g_game->deathmatchManager.is_active()) + { + blackHearts = (int)((uint32_t)blackHearts >> ABADDON_VERSUS_SHIFT); + p.maxHearts = p.maxHearts / 2; + } + else + { + p.redHearts = 0; + p.maxHearts = 0; + } + if (soul) + { + soul->redHearts = 0; + soul->maxHearts = 0; + } + p.UpdateHeartDependentEffects(); + p.AddBlackHearts(blackHearts); + p.TryPreventDeath(); +} + +// Starter Deck's first pickup: a card (three Fools in its challenge), and the pills in the pockets turn into cards. +static void starter_deck_gain(Entity_Player& p, RNG& rng) +{ + if (g_game->challenge == CHALLENGE_CANTRIPPED) + { + for (int i = 0; i < CHALLENGE_STARTER_DECK_CARDS; i++) + { + uint32_t seed = rng.Next(); + pickup_drop(pickup_spawn_position(p.pos), {PICKUP_TAROTCARD, CHALLENGE_STARTER_DECK_CARD, seed, &p}); + } + return; + } + uint32_t seed = rng.Next(); + pickup_drop(pickup_spawn_position(p.pos), {PICKUP_TAROTCARD, 0, seed, &p}); + for (PocketItem& pocket : p.pocketItems) + { + if (pocket.id == 0 || pocket.type != POCKET_PILL) continue; + pocket.type = POCKET_CARD; + pocket.id = item_card_roll(rng.Next()); + } +} + +// Little Baggy's first pickup: a pill, and the cards in the pockets turn into pills. +static void little_baggy_gain(Entity_Player& p, RNG& rng) +{ + uint32_t seed = rng.Next(); + pickup_drop(pickup_spawn_position(p.pos), {PICKUP_PILL, 0, seed, &p}); + for (PocketItem& pocket : p.pocketItems) + { + if (pocket.id == 0 || pocket.type != POCKET_CARD) continue; + pocket.type = POCKET_PILL; + pocket.id = ItemPool::GetPill(rng.Next()); + } +} + +// PHD and False PHD's first pickup: a pill, and every pill colour identified. +static void phd_gain(Entity_Player& p, RNG& rng) +{ + Vector position = pickup_spawn_position(p.pos); + pickup_drop(position, {PICKUP_PILL, 0, rng.Next(), &p}); + for (int color = 1; color <= PILL_COLOR_LAST; color++) g_game->itemPool.IdentifyPill(color); +} + +// Toxic Shock: every enemy that takes status effects (and in a versus match every player) is poisoned for three +// seconds, under green clouds when any was. +static void toxic_shock_gain(Entity_Player& p) +{ + Room& room = *g_game->room; + bool isVersus = g_game->deathmatchManager.is_active(); + bool isPoisoned = false; + + for (size_t i = 0; i < room.entityList.updateEL.size(); i++) + { + Entity* entity = room.entityList.updateEL[i]; + bool isTarget = (isVersus && entity->type == ENTITY_PLAYER) || (entity->type >= ENTITY_FIRST_ENEMY && entity->type < ENTITY_EFFECT); + if (!isTarget || (entity->flags & TOXIC_SHOCK_IMMUNE)) continue; + entity->AddPoison(EntityRef(&p), TOXIC_SHOCK_POISON_FRAMES, 0, false); + isPoisoned = true; + } + if (isPoisoned) room.fxLayers.AddPoopFx(TOXIC_SHOCK_COLOR); +} + +// Missing No.'s first pickup: the main player's items reroll with a glitch, and each stat moves a step at random. +static void missing_no_gain(Entity_Player& p, RNG& rng) +{ + if (p.variant == PLAYER_VARIANT_PLAYER && !p.isCoopGhost) + { + p.UseActiveItem({.item = COLLECTIBLE_D4, .flags = USE_NOANIM}); + if (p.variant == PLAYER_VARIANT_PLAYER && !p.isCoopGhost) p.queuedExtraAnimation = "Glitch"; + } + for (int* modifier : {&p.speedModifier, &p.fireDelayModifier, &p.damageModifier, &p.tearRangeModifier, + &p.shotSpeedModifier, &p.luckModifier}) + *modifier += (int)rng.RandomInt(3) - 1; + p.cacheFlags = CACHE_ALL; +} + // Heartbreak's broken hearts: one for the Keeper's coins, else up to three while the heart limit allows. static void heartbreak_gain(Entity_Player& p) { @@ -1177,29 +1337,45 @@ static void collectible_effect_apply(Entity_Player& p, const CollectibleGain& ga heartbreak_gain(p); return; case 75: + case 654: + if (isFirst) phd_gain(p, rng); + return; case 141: + if (isFirst) pageant_boy_gain(p, rng); + return; case 194: + if (isFirst) magic_8_ball_gain(p, rng); + return; case 230: + if (isFirst) abaddon_gain(p); + return; case 251: + if (isFirst) starter_deck_gain(p, rng); + return; case 252: - case 263: + if (isFirst) little_baggy_gain(p, rng); + return; case 350: + toxic_shock_gain(p); + return; + case 263: case 439: case 451: case 497: case 547: case 549: case 551: - case 588: case 589: - case 593: case 595: - case 619: case 624: - case 644: - case 654: case 668: case 721: + late_collectible_gain(p, gain.type, isFirst); + return; + case 588: + case 593: + case 619: + case 644: case 732: reconstruction_missing( (std::string("Entity_Player::AddCollectible 0075f0e0 (the pickup effect of ") + @@ -1242,19 +1418,20 @@ static void collectible_late_effect_apply(Entity_Player& p, const CollectibleGai p.darkPrincesCrownSprite.Play("FloatNoGlow"); return; case 258: + if (gain.isFirstTime) missing_no_gain(p, rng); + return; case 407: - reconstruction_missing( - (std::string("Entity_Player::AddCollectible 0075f0e0 (the pickup effect of ") + - std::to_string(gain.type) + ")").c_str()); + purity_gain(p); + return; } } // 0075f0e0 Gives the player a collectible: Tainted Jacob's ghost passes it to Jacob, it joins the collection, the // counts and the history, its first pickup gives its pickups and hearts, the unlocks for many items are checked, its // own pickup effect runs, its cache flags are evaluated, transformations count it, and its costume goes on. An active -// takes its slot, and Book of Virtues an empty first one. Procedural items and the pickup effects not written yet stop -// the game. -void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int activeSlot, int varData) +// takes its slot, and Book of Virtues an empty first one. The history keeps the pool the item came from. Procedural +// items and the pickup effects not written yet stop the game. +void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int activeSlot, int varData, int poolType) { Game& game = *g_game; ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(type); @@ -1266,7 +1443,7 @@ void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int a reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (during a stage transition)"); Entity_Player* twin = twin_get(); if (playerType == PLAYER_JACOB2_B && twin && item->type != ITEM_ACTIVE) - return twin->AddCollectible(type, charge, isFirstTime, slot, varData); + return twin->AddCollectible(type, charge, isFirstTime, slot, varData, poolType); log_printf(LOG_INFO, "Adding collectible %d (%s) to player %d (%s) from pool %s\n", type, item->GetLocalizedName(LANGUAGE_CURRENT).c_str(), playerIndex, name.c_str(), ""); @@ -1285,8 +1462,7 @@ void Entity_Player::AddCollectible(int type, int charge, bool isFirstTime, int a { collectible_unlocks_check(type, *item); int time = isPostLevelInitFinished ? game.frameCount : 0; - history.AddHistoryItem({time, false, type, (int)game.stage, (int)game.stageType, game.room->roomType, - HISTORY_POOL_NONE}); + history.AddHistoryItem({time, false, type, (int)game.stage, (int)game.stageType, game.room->roomType, poolType}); stop_costume_item_anims(); if (isFirstTime) collectible_pickups_add(*item); } @@ -1595,11 +1771,13 @@ void Entity_Player::UpdateCostumes() isUpdating = false; } -// The head costume part of 0077b020: each head costume shows the head's animation at the blink frame (or plays a -// looping one, its layer stepped down a frame per blink), with its overlay animation. Costumes playing an item's own -// animation keep it. An idle head animation stops the game until reached. +// The head costume part of 0077b020: each head costume shows the head's animation at the blink frame (or plays its +// _Idle animation while the eyes are open, or a looping one with its layer stepped down a frame per blink), with its +// overlay animation. Costumes playing an item's own animation keep it. void Entity_Player::costume_heads_update(int blinkFrame) { + constexpr int HEAD_IDLE_BLINK_LIMIT = 9; + for (PlayerCostumeMap& map : playerCostumeMap) { if (map.index < 0 || map.isBodyLayer) continue; @@ -1609,9 +1787,9 @@ void Entity_Player::costume_heads_update(int blinkFrame) if (!head->isLooping) { - if (costume.sprite.GetAnimationData(headAnim + "_Idle")) - reconstruction_missing("Entity_Player::update_shooting 0077b020 (an idle head costume)"); - costume.sprite.SetFrame(headAnim, blinkFrame); + std::string idle = headAnim + "_Idle"; + if (blinkTime < HEAD_IDLE_BLINK_LIMIT && costume.sprite.GetAnimationData(idle)) costume.sprite.Play(idle); + else costume.sprite.SetFrame(headAnim, blinkFrame); } else { diff --git a/src/entity_player_kills.cpp b/src/entity_player_kills.cpp index cd2a458..18bab1d 100644 --- a/src/entity_player_kills.cpp +++ b/src/entity_player_kills.cpp @@ -12,7 +12,6 @@ constexpr int COLLECTIBLE_CHARM_OF_THE_VAMPIRE = 62; constexpr int COLLECTIBLE_BERSERK_KILLS = 704; -constexpr int TRINKET_SAMSONS_LOCK = 58; constexpr int TRINKET_BAT_WING_KILLS = 118; constexpr int TRINKET_SIGIL_OF_BAPHOMET = 189; constexpr int NULLITEM_BAT_WING = 40; diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index d75bca5..a422f92 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -1,22 +1,10 @@ #include "entity_player.h" #include "log.h" -bool Entity_Player::TryThrow(const EntityRef&, const Vector&, float) -{ - reconstruction_missing("Entity_Player::TryThrow 007d2930"); -} -Entity_Familiar* Entity_Player::AddWisp(int, Vector, bool, bool) -{ - reconstruction_missing("Entity_Player::AddWisp 005c93b0"); -} void Entity_Player::StopExtraAnimation() { reconstruction_missing("Entity_Player::StopExtraAnimation 0058e230"); } void Entity_Player::moms_bracelet_grab() { reconstruction_missing("Entity_Player::moms_bracelet_grab 005b1a20"); } void Entity_Player::UseRedKey() { reconstruction_missing("Entity_Player::UseRedKey 005b2360"); } void Entity_Player::use_card_hagalaz(RNG*) { reconstruction_missing("Entity_Player::use_card_hagalaz 005b23f0"); } -int Entity_Player::reroll_collectibles_on_damage(RNG*, bool) -{ - reconstruction_missing("Entity_Player::reroll_collectibles_on_damage 005c88a0"); -} void Entity_Player::ResetDamageCooldown() { reconstruction_missing("Entity_Player::ResetDamageCooldown 0060d090"); } Vector Entity_Player::SpriteScale() { reconstruction_missing("Entity_Player::SpriteScale 0060d0a0"); } void Entity_Player::set_last_damage(uint64_t, const EntityRef&) @@ -28,10 +16,6 @@ void Entity_Player::QueueExtraAnimation(std::string_view) reconstruction_missing("Entity_Player::QueueExtraAnimation 007539c0"); } void Entity_Player::cycle_spectate_target() { reconstruction_missing("Entity_Player::cycle_spectate_target 007585b0"); } -void Entity_Player::trigger_max_hearts_removed(int) -{ - reconstruction_missing("Entity_Player::trigger_max_hearts_removed 00758850"); -} void Entity_Player::AddGoldenKey() { reconstruction_missing("Entity_Player::AddGoldenKey 00759620"); } void Entity_Player::RemoveGoldenKey() { reconstruction_missing("Entity_Player::RemoveGoldenKey 00759660"); } void Entity_Player::RemoveBlueFly() { reconstruction_missing("Entity_Player::RemoveBlueFly 00759b80"); } @@ -45,18 +29,6 @@ void Entity_Player::AddNullCostume(int) { reconstruction_missing("Entity_Player: 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"); } -Entity_Pickup* Entity_Player::DropTrinket(Vector, bool) -{ - reconstruction_missing("Entity_Player::DropTrinket 00771800"); -} -void Entity_Player::AddTrinket(int, bool) { reconstruction_missing("Entity_Player::AddTrinket 00771d30"); } -bool Entity_Player::TryRemoveTrinket(uint32_t) { reconstruction_missing("Entity_Player::TryRemoveTrinket 00771f60"); } -bool Entity_Player::TryRemoveSmeltedTrinket(uint32_t) -{ - reconstruction_missing("Entity_Player::TryRemoveSmeltedTrinket 00772260"); -} bool Entity_Player::replace_trinket() { reconstruction_missing("Entity_Player::replace_trinket 00772530"); } void Entity_Player::RemoveCollectibleByHistoryIndex(int, bool) { @@ -75,30 +47,10 @@ void Entity_Player::AnimateTrapdoor() { reconstruction_missing("Entity_Player::A void Entity_Player::AnimateLightTravel() { PlayExtraAnimation("LightTravel"); } void Entity_Player::AnimateAppear() { reconstruction_missing("Entity_Player::AnimateAppear 007abcb0"); } void Entity_Player::AddPrettyFly() { reconstruction_missing("Entity_Player::AddPrettyFly 007abdf0"); } -void Entity_Player::TryRemoveTrinketCostume(int) -{ - reconstruction_missing("Entity_Player::TryRemoveTrinketCostume 007ad3a0"); -} void Entity_Player::TryRemoveNullCostume(int) { reconstruction_missing("Entity_Player::TryRemoveNullCostume 007ad400"); } -void Entity_Player::ClearCollectibleAnim(int) -{ - reconstruction_missing("Entity_Player::ClearCollectibleAnim 007ad5a0"); -} -bool Entity_Player::IsCollectibleAnimFinished(int, std::string_view) -{ - reconstruction_missing("Entity_Player::IsCollectibleAnimFinished 007ad680"); -} -void Entity_Player::TriggerTrinketAdded(uint32_t, bool) -{ - reconstruction_missing("Entity_Player::TriggerTrinketAdded 007ad860"); -} -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::TryDecreaseGlowingHourglassUses(int, bool) { @@ -123,7 +75,6 @@ uint32_t Entity_Player::GetGlitchBabySubType() } void Entity_Player::SetShootingCooldown(int) { reconstruction_missing("Entity_Player::SetShootingCooldown 007c37f0"); } void Entity_Player::add_random_stat_up(RNG*) { reconstruction_missing("Entity_Player::add_random_stat_up 007c3980"); } -bool Entity_Player::CanUsePill(int) { reconstruction_missing("Entity_Player::CanUsePill 007c40e0"); } void Entity_Player::trigger_immaculate_conception(bool) { reconstruction_missing("Entity_Player::trigger_immaculate_conception 007c7d70"); @@ -132,7 +83,6 @@ void Entity_Player::dash_impact() { reconstruction_missing("Entity_Player::dash_ Entity_Laser* Entity_Player::SpawnMawOfVoid(int) { reconstruction_missing("Entity_Player::SpawnMawOfVoid 007c8dc0"); } void Entity_Player::AddGoldenBomb() { reconstruction_missing("Entity_Player::AddGoldenBomb 007c8f80"); } void Entity_Player::RemoveGoldenBomb() { reconstruction_missing("Entity_Player::RemoveGoldenBomb 007c8fc0"); } -void Entity_Player::AddDollarBillEffect() { reconstruction_missing("Entity_Player::AddDollarBillEffect 007c9000"); } int Entity_Player::GetCambionPregnancyLevel() { reconstruction_missing("Entity_Player::GetCambionPregnancyLevel 007c90b0"); @@ -161,10 +111,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::CanRerollCollectible(int, bool) -{ - reconstruction_missing("Entity_Player::CanRerollCollectible 007ce2a0"); -} void Entity_Player::GetGlyphOfBalanceDrop(int*, int*) { reconstruction_missing("Entity_Player::GetGlyphOfBalanceDrop 007d12c0"); @@ -173,7 +119,6 @@ Entity_Familiar* Entity_Player::AddMinisaac(Vector, bool) { reconstruction_missing("Entity_Player::AddMinisaac 007d1860"); } -bool Entity_Player::TryHoldEntity(Entity*) { reconstruction_missing("Entity_Player::TryHoldEntity 007d2170"); } void Entity_Player::AddFriendlyDip(int, Vector) { reconstruction_missing("Entity_Player::AddFriendlyDip 007d2a00"); } void Entity_Player::ThrowFriendlyDip(int, Vector, Vector) { @@ -184,42 +129,18 @@ void Entity_Player::AddGigaBombs(int) { reconstruction_missing("Entity_Player::A void Entity_Player::fire_saturnus_tears() { reconstruction_missing("Entity_Player::fire_saturnus_tears 007d3e40"); } void Entity_Player::get_salvation_scale() { reconstruction_missing("Entity_Player::get_salvation_scale 007d4340"); } void Entity_Player::update_suplex() { reconstruction_missing("Entity_Player::update_suplex 007d4390"); } -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*) -{ - reconstruction_missing("Entity_Player::RecomputeWispCollectibles 007d7740"); -} void Entity_Player::trigger_cracked_orb(Vector) { reconstruction_missing("Entity_Player::trigger_cracked_orb 007d7c30"); } uint32_t Entity_Player::AddItemCard(uint32_t) { reconstruction_missing("Entity_Player::AddItemCard 007d8240"); } -void Entity_Player::spawn_lil_clot_familiars() -{ - reconstruction_missing("Entity_Player::spawn_lil_clot_familiars 007d83f0"); -} void Entity_Player::creep_contact_add(int, int) { reconstruction_missing("Entity_Player::creep_contact_add 007d8740"); } void Entity_Player::AttachMinecart(Entity_NPC*) { reconstruction_missing("Entity_Player::AttachMinecart 007d9180"); } void Entity_Player::RevivePlayerGhost() { reconstruction_missing("Entity_Player::RevivePlayerGhost 007d93b0"); } void Entity_Player::MorphToCoopGhost() { reconstruction_missing("Entity_Player::MorphToCoopGhost 007d96f0"); } void Entity_Player::reset_body_sprite() { reconstruction_missing("Entity_Player::reset_body_sprite 007d9b70"); } void Entity_Player::SpawnClot(Vector, bool) { reconstruction_missing("Entity_Player::SpawnClot 007da810"); } -bool Entity_Player::TryForgottenThrow(Vector) { reconstruction_missing("Entity_Player::TryForgottenThrow 007dac80"); } void Entity_Player::ResetPlayer() { reconstruction_missing("Entity_Player::ResetPlayer 007daed0"); } -void Entity_Player::remove_wooden_cross_mantles() -{ - reconstruction_missing("Entity_Player::remove_wooden_cross_mantles 007db160"); -} -void Entity_Player::add_random_drug_item_effect() -{ - reconstruction_missing("Entity_Player::add_random_drug_item_effect 007dbba0"); -} -void Entity_Player::AddRandomMomItemEffect() -{ - reconstruction_missing("Entity_Player::AddRandomMomItemEffect 007dbc80"); -} -void Entity_Player::ModelingClay_roll(RNG*) { reconstruction_missing("Entity_Player::ModelingClay_roll 007dbd70"); } void Entity_Player::twins_duplicate_familiars(int) { reconstruction_missing("Entity_Player::twins_duplicate_familiars 007dbeb0"); @@ -236,8 +157,4 @@ void Entity_Player::CheckPoopSpellQueue(Vector) { reconstruction_missing("Entity_Player::CheckPoopSpellQueue 0095ffb0"); } -void Entity_Player::PlayCollectibleAnim(int, bool, std::string_view, int) -{ - reconstruction_missing("Entity_Player::PlayCollectibleAnim 00759f50"); -} void History::merge(History&) { reconstruction_missing("History::merge 00721c80"); } diff --git a/src/entity_player_passives.cpp b/src/entity_player_passives.cpp new file mode 100644 index 0000000..cf1ab58 --- /dev/null +++ b/src/entity_player_passives.cpp @@ -0,0 +1,711 @@ +#include "entity_player_passives.h" +#include "active_items.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_laser.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "item_overlay.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "room.h" +#include "room_grid.h" +#include "room_special.h" +#include "temporary_effects.h" +#include "weapon.h" +#include + +// The frame pieces' timings, odds and sizes: the Black Bean's farts, the invincible items' flashing and music, +// 3 Dollar Bill's change, Placenta's heal and the creep of Ball of Tar and Aquarius. +constexpr int BLACK_BEAN_FART_PERIOD = 5; +constexpr float BLACK_BEAN_FART_RADIUS = 100; +constexpr float BLACK_BEAN_PUSH_RADIUS = 120; +constexpr int BLACK_BEAN_CLOUD_FRAMES = 90; +constexpr float INVINCIBLE_PITCH = 3; +constexpr int INVINCIBLE_FLICKER_FRAMES = 30; +constexpr int INVINCIBLE_FLASH_PERIOD = 4; +constexpr int INVINCIBLE_FLASH_FRAMES = 4; +constexpr int INVINCIBLE_FLICKER_DURATION = 2; +constexpr int STUMP_MUSIC_PERIOD = 24; +constexpr float STUMP_PITCH_RANGE = 1.5f; +constexpr float STUMP_PITCH_MIN = 0.5f; +constexpr int DOLLAR_BILL_PERIOD = 180; +constexpr int PLACENTA_PERIOD = 1800; +constexpr int PLACENTA_VERSUS_PERIOD = 900; +constexpr float HEART_RISE_OFFSET = -24; +constexpr int CREEP_PERIOD = 2; +constexpr float PLAYER_CREEP_SCALE_RANGE = 0.5f; +constexpr float PLAYER_CREEP_SCALE_MIN = 0.2f; +constexpr int TAR_ODDS = 5; +constexpr int AQUARIUS_ODDS = 5; +constexpr float AQUARIUS_DAMAGE_SCALE = 0.666f; +constexpr float TAURUS_SPEED_STEP = 0.0022222223f; +constexpr float TAURUS_SPEED_FULL = 2; +constexpr int TAURUS_RAGE_FRAMES = 180; +constexpr float COLOR_UNIT = 0.003921569f; + +// The tear effects 3 Dollar Bill lends, rolled every 180 frames. +constexpr int DOLLAR_BILL_ITEMS[] = {1, 2, 3, 5, 6, 46, 53, 110, 115, 143, 150, 153, 104, + 201, 261, 257, 259, 317, 237, 245, 228, 213, 200, 221, 224, 358, + 359, 369, 373, 374, 379, 401, 443, 459, 461, 462, 496, 503}; + +// The hit pieces' odds and counts: Celtic Cross and Virgo's shields, the pickups of Fanny Pack, Old Bandage, Gimpy +// and Piggy Bank, Infestation's flies and Spiderbaby's spiders. +constexpr int CELTIC_CROSS_ODDS = 5; +constexpr float CELTIC_CROSS_LUCK = 0.15f; +constexpr int VIRGO_ODDS = 4; +constexpr float VIRGO_LUCK = 0.3f; +constexpr float OLD_BANDAGE_CHANCE = 0.2f; +constexpr float OLD_BANDAGE_LUCK = 0.01f; +constexpr float GIMPY_CHANCE = 0.08f; +constexpr float GIMPY_LUCK = 0.02f; +constexpr float PICKUP_SPOT_STEP = 40; +constexpr float PIGGY_BANK_SPEED = 2; +constexpr int INFESTATION_FLIES_MIN = 2; +constexpr int INFESTATION_FLIES_RANGE = 5; +constexpr int SPIDERBABY_SPIDERS_MIN = 2; +constexpr int SPIDERBABY_SPIDERS_RANGE = 4; +constexpr int MISSING_PAGE_HEARTS = 2; +constexpr int POLAROID_SHIELD_FRAMES = 150; +constexpr int HEART_EFFECT_SCAPULAR = 4; +constexpr std::array FANNY_PACK_PICKUPS = {PICKUP_HEART, PICKUP_COIN, PICKUP_KEY, PICKUP_BOMB}; + +// The collectible effects these items leave whose frame, stats and hits are written: Book of Shadows (Celtic Cross, +// Virgo, the Polaroid), the Wafer (Cancer), Scapular, the Black Bean, Anemic, Experimental Treatment, Best Bud, Taurus +// and Holy Mantle's shield. +bool is_passive_effect_plain(const TemporaryEffect& effect) +{ + constexpr int PLAIN_PASSIVE_EFFECTS[] = { + COLLECTIBLE_BOOK_OF_SHADOWS, COLLECTIBLE_WAFER, COLLECTIBLE_SCAPULAR, + COLLECTIBLE_BLACK_BEAN, COLLECTIBLE_ANEMIC, COLLECTIBLE_EXPERIMENTAL_TREATMENT, + COLLECTIBLE_BEST_BUD, COLLECTIBLE_TAURUS, COLLECTIBLE_HOLY_MANTLE}; + return effect.item->IsCollectible() && + std::ranges::find(PLAIN_PASSIVE_EFFECTS, effect.item->id) != std::end(PLAIN_PASSIVE_EFFECTS); +} + +// 007c9000 Rolls the tear effect 3 Dollar Bill lends, asking for the stats of the old and the new one. +void Entity_Player::AddDollarBillEffect() +{ + ItemConfig& items = g_manager->itemConfig; + int id = DOLLAR_BILL_ITEMS[Random() % std::size(DOLLAR_BILL_ITEMS)]; + ItemConfig_Item* old = items.GetCollectible(threeDollarBillItem); + ItemConfig_Item* next = items.GetCollectible(id); + + threeDollarBillItem = id; + if (old) cacheFlags |= old->cacheFlags; + if (next) cacheFlags |= next->cacheFlags; + EvaluateItems(); +} + +// The Black Bean's effect farts every fifth frame it has left, pushing enemies away under a smoke cloud. +static void black_bean_update(Entity_Player& player) +{ + TemporaryEffect* bean = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_BLACK_BEAN); + if (!bean || bean->cooldown % BLACK_BEAN_FART_PERIOD != 0) return; + + game_fart({.position = player.pos, .source = &player, .radius = BLACK_BEAN_FART_RADIUS}); + game_butter_bean_fart({.position = player.pos, .source = &player, .radius = BLACK_BEAN_PUSH_RADIUS, + .isShowEffect = false, .isSuperKnockback = true}); + uint32_t seed = Random(); + auto* cloud = static_cast(g_game->Spawn({.position = player.pos, .spawner = &player, + .type = ENTITY_EFFECT, .variant = EFFECT_SMOKE_CLOUD, + .seed = seed})); + cloud->SetTimeout(BLACK_BEAN_CLOUD_FRAMES); + cloud->Update(); +} + +// A random bright flash: red, green or blue lightly brightened, or yellow, cyan or magenta more. +static ColorMod invincible_flash_color() +{ + constexpr int LIGHT_OFFSET = 50; + constexpr int STRONG_OFFSET = 70; + constexpr float FULL = 1; + float red = 0; + float green = 0; + float blue = 0; + int offset = LIGHT_OFFSET; + + if (random_below(6) == 0) red = FULL; + else if (random_below(5) == 0) green = FULL; + else if (random_below(4) == 0) blue = FULL; + else + { + offset = STRONG_OFFSET; + if (random_below(3) == 0) red = green = FULL; + else if (random_below(2) == 0) green = blue = FULL; + else red = blue = FULL; + } + float shade = (float)offset * COLOR_UNIT; + return {{red, green, blue, FULL}, {0, 0, 0, 0}, {shade, shade, shade}}; +} + +// The invincible effects (My Little Unicorn, a charging Taurus, the Gamekid, Unicorn Stump): the first one on races +// the music (Unicorn Stump warbles it now and then), and the player flashes colours every fourth frame, then +// flickers out over its last 30. +static void invincible_effects_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + MusicManager& music = g_manager->musicManager; + TemporaryEffect* taurus = effects.GetCollectibleEffect(COLLECTIBLE_TAURUS); + TemporaryEffect* effect = effects.GetCollectibleEffect(COLLECTIBLE_MY_LITTLE_UNICORN); + + if (!effect && taurus && taurus->cooldown != 0) effect = taurus; + if (!effect) effect = effects.GetCollectibleEffect(COLLECTIBLE_GAMEKID); + if (effect) music.PitchSlide(INVINCIBLE_PITCH); + else + { + effect = effects.GetCollectibleEffect(COLLECTIBLE_UNICORN_STUMP); + if (!effect) return; + if (player.IsFrame(STUMP_MUSIC_PERIOD, 0) && random_below(2) != 0) + { + music.PitchSlide(random_unit() * STUMP_PITCH_RANGE + STUMP_PITCH_MIN); + music.VolumeSlide(random_below(3) != 0 ? 1.0f : 0.0f, STUMP_VOLUME_RATE); + } + } + + if (effect->cooldown > INVINCIBLE_FLICKER_FRAMES) + { + if (effect->cooldown % INVINCIBLE_FLASH_PERIOD == 0) + player.SetColor(invincible_flash_color(), INVINCIBLE_FLASH_FRAMES, 0, false, true); + return; + } + constexpr ColorMod HIDDEN = {{1, 1, 1, 0}, {0, 0, 0, 0}, {0, 0, 0}}; + player.SetColor(effect->cooldown & 1 ? player.color : HIDDEN, INVINCIBLE_FLICKER_DURATION, 1, false, true); +} + +// A rising heart over the player, as a heal shows. +static void heart_rise_spawn(Entity_Player& player, int subType) +{ + Entity* heart = g_game->Spawn({.position = player.pos, .subType = subType, .type = ENTITY_EFFECT, + .variant = EFFECT_HEART, .seed = Random()}); + heart->sprite.offset = vector_make(0, HEART_RISE_OFFSET); + heart->renderDepthOffset = 1; +} + +// Placenta: a player missing health heals half a heart, one 1800th frame in two (every 900th in a versus match), +// with a gulp and a rising heart. +static void placenta_update(Entity_Player& player) +{ + if (!player.HasCollectible(COLLECTIBLE_PLACENTA) || player.HasFullHearts()) return; + bool isHeal = g_game->deathmatchManager.is_active() ? player.IsFrame(PLACENTA_VERSUS_PERIOD, 0) + : player.IsFrame(PLACENTA_PERIOD, 0) && random_below(2) != 0; + if (!isHeal) return; + + player.AddHearts(1, false, false); + npc_sound_play(player.playerType == PLAYER_MAGDALENE_B ? SOUND_VAMP_DOUBLE : SOUND_VAMP_GULP, 1, 2, 1); + heart_rise_spawn(player, 0); +} + +// A spot of creep under the player, randomly sized, before its first update. +static Entity* creep_drop(Entity_Player& player, int variant) +{ + uint32_t seed = Random(); + Entity* creep = g_game->Spawn({.position = player.pos, .spawner = &player, .type = ENTITY_EFFECT, + .variant = variant, .seed = seed}); + float scale = random_unit() * PLAYER_CREEP_SCALE_RANGE + PLAYER_CREEP_SCALE_MIN; + creep->sprite.scale = vector_make(scale, scale); + return creep; +} + +// Taurus's charge: in a room with enemies (or past full speed) the speed builds every frame, and at full speed the +// charge turns into 180 frames of invincible rage. Without the effect the built speed is dropped. +static void taurus_update(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + TemporaryEffect* taurus = effects.GetCollectibleEffect(COLLECTIBLE_TAURUS); + + if (!taurus) + { + bool isTaurus = player.HasCollectible(COLLECTIBLE_TAURUS) || player.GetZodiacEffect() == COLLECTIBLE_TAURUS; + if (!isTaurus || player.taurusSpeedBonus == 0) return; + player.taurusSpeedBonus = 0; + player.cacheFlags |= CACHE_SPEED; + player.EvaluateItems(); + return; + } + if (g_game->room->GetAliveEnemiesCount() == 0 && player.moveSpeed < TAURUS_SPEED_FULL) + { + effects.RemoveCollectibleEffect(COLLECTIBLE_TAURUS, 1); + return; + } + if (player.moveSpeed < TAURUS_SPEED_FULL || taurus->cooldown != 0) + { + player.taurusSpeedBonus += TAURUS_SPEED_STEP; + player.cacheFlags |= CACHE_SPEED | CACHE_COLOR; + player.EvaluateItems(); + return; + } + effects.RemoveCollectibleEffect(COLLECTIBLE_TAURUS, 1); + TemporaryEffect rage(g_manager->itemConfig.GetCollectible(COLLECTIBLE_TAURUS)); + rage.cooldown = TAURUS_RAGE_FRAMES; + effects.AddEffect(rage, true, 1); +} + +// Aquarius: four frames in five of every second frame leave holy water creep carrying the player's tear effects at +// two thirds of its melee damage. +static void aquarius_update(Entity_Player& player) +{ + bool isAquarius = player.HasCollectible(COLLECTIBLE_AQUARIUS) || player.GetZodiacEffect() == COLLECTIBLE_AQUARIUS; + if (!isAquarius || !player.IsFrame(CREEP_PERIOD, 0) || random_below(AQUARIUS_ODDS) == 0) return; + + int displacement = random_below(2) != 0 ? 1 : -1; + float damageScale = player.meleeDamage * AQUARIUS_DAMAGE_SCALE / player.damage; + TearParams params = player.GetTearHitParams(WEAPON_TEARS, damageScale, displacement, nullptr); + auto* creep = static_cast(creep_drop(player, EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL)); + creep->SetCollisionDamage(params.tearDamage); + creep->varData = {}; + for (size_t bit = 0; bit < params.tearFlags.size(); bit++) + if (params.tearFlags[bit]) creep->varData[bit / 32] |= 1u << (bit % 32); + creep->SetColor(params.tearColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + creep->Update(); +} + +// The pieces of the items' frame (update_effects 00794e50) for collectibles 1 to 366, in their order there: the Black +// Bean, the invincible effects, 3 Dollar Bill, Placenta, Ball of Tar, Taurus and Aquarius. +void passives_frame_update(Entity_Player& player) +{ + black_bean_update(player); + invincible_effects_update(player); + if (player.HasCollectible(COLLECTIBLE_3_DOLLAR_BILL) && g_game->room->GetFrameCount() % DOLLAR_BILL_PERIOD == 0) + player.AddDollarBillEffect(); + placenta_update(player); + if (player.HasCollectible(COLLECTIBLE_BALL_OF_TAR) && player.IsFrame(CREEP_PERIOD, 0) && random_below(TAR_ODDS) > 1) + creep_drop(player, EFFECT_PLAYER_CREEP_BLACK)->Update(); + taurus_update(player); + aquarius_update(player); +} + +// 00759f50 Plays an animation on the costumes of an item that cover the body (or head) layers, marking them as +// playing the item's own animation: unforced, or held on a frame. Costumes with an overlay play its _Overlay alike. +void Entity_Player::PlayCollectibleAnim(int collectible, bool isCheckBodyLayers, std::string_view animation, int frame) +{ + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectible); + std::string overlay = std::string(animation) + "_Overlay"; + + for (PlayerCostumeMap& map : playerCostumeMap) + { + if (map.index < 0 || map.isBodyLayer != isCheckBodyLayers) continue; + CostumeSpriteDesc& costume = costumeSpriteDescs[map.index]; + if (costume.item != item) continue; + + ANM2& sprite = costume.sprite; + costume.isItemAnimPlay = true; + if (frame < 0) sprite.Play(animation); + else sprite.SetFrame(animation, frame); + if (!costume.isHasOverlay) continue; + if (frame < 0) sprite.PlayOverlay(overlay); + else sprite.SetOverlayFrame(overlay, frame); + } +} + +// The animation a walking item's costume turns to with the walk, from its names for left, up, right and down. +static std::string_view walk_animation(Direction direction, const std::array& names) +{ + switch (direction) + { + case DIRECTION_LEFT: return names[0]; + case DIRECTION_UP: return names[1]; + case DIRECTION_RIGHT: return names[2]; + default: return names[3]; + } +} + +// The walking items' part of update_body_animations (00779b40): the Gamekid's head faces left or right, the first of +// My Little Unicorn, Unicorn Stump, a charging Taurus (held on its first frame) and the Book of Shadows' shield +// (blinking over its last 90 frames) turns with the walk, and Holy Mantle's shield shimmers. +void walking_items_animate(Entity_Player& player) +{ + constexpr int SHADOWS_BLINK_FRAMES = 89; + constexpr std::array HEADS = {"HeadLeft", "HeadUp", "HeadRight", "HeadDown"}; + constexpr std::array WALKS = {"WalkLeft", "WalkUp", "WalkRight", "WalkDown"}; + TemporaryEffects& effects = player.temporaryEffects; + TemporaryEffect* taurus = effects.GetCollectibleEffect(COLLECTIBLE_TAURUS); + TemporaryEffect* shadows = effects.GetCollectibleEffect(COLLECTIBLE_BOOK_OF_SHADOWS); + std::string_view head = walk_animation(player.moveDirection, HEADS); + + if (effects.HasCollectibleEffect(COLLECTIBLE_GAMEKID)) + { + bool isLeft = player.moveDirection == DIRECTION_LEFT || player.moveDirection == DIRECTION_UP; + player.PlayCollectibleAnim(COLLECTIBLE_GAMEKID, false, isLeft ? "HeadLeft" : "HeadRight", -1); + } + if (effects.HasCollectibleEffect(COLLECTIBLE_MY_LITTLE_UNICORN)) + player.PlayCollectibleAnim(COLLECTIBLE_MY_LITTLE_UNICORN, false, head, -1); + else if (effects.HasCollectibleEffect(COLLECTIBLE_UNICORN_STUMP)) + player.PlayCollectibleAnim(COLLECTIBLE_UNICORN_STUMP, false, head, -1); + else if (taurus && taurus->cooldown >= 1) player.PlayCollectibleAnim(COLLECTIBLE_TAURUS, false, head, 0); + else if (shadows) + { + bool isBlinking = shadows->cooldown <= SHADOWS_BLINK_FRAMES; + player.PlayCollectibleAnim(COLLECTIBLE_BOOK_OF_SHADOWS, true, + isBlinking ? "Blink" : walk_animation(player.moveDirection, WALKS), -1); + } + if (effects.HasCollectibleEffect(COLLECTIBLE_HOLY_MANTLE)) + player.PlayCollectibleAnim(COLLECTIBLE_HOLY_MANTLE, true, "Shimmer", -1); +} + +// A collectible's own effect, lasting the cooldown of another item. +static void effect_lend(Entity_Player& player, int effectItem, int cooldownItem) +{ + ItemConfig& items = g_manager->itemConfig; + TemporaryEffect effect(items.GetCollectible(effectItem)); + + effect.cooldown = items.GetCollectible(cooldownItem)->maxCooldown; + player.temporaryEffects.AddEffect(effect, true, 1); +} + +// Whether a pickup a hit drops survives Daemon's Tail, which lets one in five through. +static bool is_daemons_tail_passed(Entity_Player& player, RNG& rng) +{ + return !player.HasTrinket(TRINKET_DAEMONS_TAIL) || rng.RandomInt(DAEMONS_TAIL_ODDS) == 0; +} + +// A pickup dropped at a free spot near the player. +static void pickup_drop(Entity_Player& player, PickupVariant variant, int subType, uint32_t seed) +{ + Vector spot = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}); + g_game->Spawn({.position = spot, .spawner = &player, .subType = subType, .type = ENTITY_PICKUP, .variant = variant, + .seed = seed}); +} + +// Fanny Pack: one hit in two drops a heart, coin, key or bomb. Daemon's Tail turns four hearts in five into the others. +static void fanny_pack_hit(Entity_Player& player) +{ + if (random_below(2) == 0) return; + + int pick = random_below((int)FANNY_PACK_PICKUPS.size()); + if (pick == 0 && player.HasTrinket(TRINKET_DAEMONS_TAIL) && random_below(DAEMONS_TAIL_ODDS) != 0) + pick = random_below((int)FANNY_PACK_PICKUPS.size() - 1) + 1; + pickup_drop(player, FANNY_PACK_PICKUPS[pick], 0, Random()); +} + +// Old Bandage and Gimpy: a luck scaled chance of a red or a soul heart. +static void heart_items_hit(Entity_Player& player) +{ + RNG& bandageRng = player.GetCollectibleRNG(COLLECTIBLE_OLD_BANDAGE); + RNG& tailRng = player.GetTrinketRNG(TRINKET_DAEMONS_TAIL); + float bandageChance = OLD_BANDAGE_CHANCE + player.luck * OLD_BANDAGE_LUCK; + + if (player.HasCollectible(COLLECTIBLE_OLD_BANDAGE) && bandageRng.RandomFloat() <= bandageChance && + is_daemons_tail_passed(player, tailRng)) + pickup_drop(player, PICKUP_HEART, HEART_FULL, Random()); + RNG& gimpyRng = player.GetCollectibleRNG(COLLECTIBLE_GIMPY); + if (player.HasCollectible(COLLECTIBLE_GIMPY) && gimpyRng.RandomFloat() <= player.luck * GIMPY_LUCK + GIMPY_CHANCE && + is_daemons_tail_passed(player, tailRng)) + pickup_drop(player, PICKUP_HEART, HEART_SOUL, Random()); +} + +// Piggy Bank: one or two pennies spill out (none or one for coin health). +static void piggy_bank_hit(Entity_Player& player) +{ + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_PIGGY_BANK); + int coins = (int)rng.RandomInt(2) + (player.GetHealthType() == HEALTH_COIN ? 0 : 1); + + for (int i = 0; i < coins; i++) + { + uint32_t seed = rng.Next(); + g_game->Spawn({.position = player.pos, .velocity = vector_scale(random_direction(), PIGGY_BANK_SPEED), + .spawner = &player, .subType = COIN_PENNY, .type = ENTITY_PICKUP, .variant = PICKUP_COIN, + .seed = seed}); + } +} + +// Missing Page 2: a hit that brings the player to two hearts or fewer reads the Necronomicon. +static void missing_page_hit(Entity_Player& player, int amount) +{ + int limit = scale_for_hard_difficulty(MISSING_PAGE_HEARTS); + int hearts = player.redHearts + player.boneHearts + player.soulHearts; + if (hearts - amount > limit || hearts <= limit) return; + + npc_sound_play(SOUND_DEATH_CARD, 1, 2, 1); + g_game->itemOverlay.Show(GIANTBOOK_MISSING_PAGE_2, 0, nullptr); + player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM}); +} + +// The collectibles 1 to 366 a landed hit sets off (part of 007729d0), in their order there: Infestation's flies, +// Celtic Cross's shield, Best Bud, Habit's charge, the Black Bean, Anemic, the pickups of Fanny Pack, Old Bandage, +// Gimpy and Piggy Bank, Spiderbaby's spiders, Missing Page 2, Cancer's and Virgo's protection. The amount is the hit's +// hearts, not yet taken. +void passives_hit_trigger(Entity_Player& player, int amount) +{ + bool isVersus = g_game->deathmatchManager.is_active(); + auto has = [&](int id) { return player.HasCollectible(id); }; + auto zodiac = [&](int id) { return has(id) || player.GetZodiacEffect() == id; }; + + if (isVersus && (has(COLLECTIBLE_INFESTATION) || has(COLLECTIBLE_HABIT) || has(COLLECTIBLE_BLACK_BEAN) || + has(COLLECTIBLE_ANEMIC) || has(COLLECTIBLE_PIGGY_BANK) || has(COLLECTIBLE_SPIDERBABY) || + has(COLLECTIBLE_MISSING_PAGE_2) || zodiac(COLLECTIBLE_VIRGO) || has(COLLECTIBLE_OLD_BANDAGE))) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the versus timings of the hit items)"); + + if (has(COLLECTIBLE_INFESTATION)) + player.AddBlueFlies(random_below(INFESTATION_FLIES_RANGE) + INFESTATION_FLIES_MIN, player.pos, nullptr); + if (has(COLLECTIBLE_CELTIC_CROSS) && + random_below(std::max(1, CELTIC_CROSS_ODDS - (int)(player.luck * CELTIC_CROSS_LUCK))) == 0) + effect_lend(player, COLLECTIBLE_BOOK_OF_SHADOWS, COLLECTIBLE_CELTIC_CROSS); + if (has(COLLECTIBLE_BEST_BUD)) player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_BEST_BUD, true, 1); + if (has(COLLECTIBLE_HABIT)) player.AddActiveCharge(1, ACTIVE_SLOT_NONE, false, false, false); + if (has(COLLECTIBLE_BLACK_BEAN)) player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_BLACK_BEAN, true, 1); + if (has(COLLECTIBLE_ANEMIC)) effect_lend(player, COLLECTIBLE_ANEMIC, COLLECTIBLE_ANEMIC); + if (has(COLLECTIBLE_FANNY_PACK)) fanny_pack_hit(player); + heart_items_hit(player); + if (has(COLLECTIBLE_PIGGY_BANK)) piggy_bank_hit(player); + if (has(COLLECTIBLE_SPIDERBABY)) + { + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_SPIDERBABY); + int spiders = (int)rng.RandomInt(SPIDERBABY_SPIDERS_RANGE) + SPIDERBABY_SPIDERS_MIN; + Vector spot = room_free_pickup_position_find({.position = player.pos, .isAvoidActiveEntities = true}); + for (int i = 0; i < spiders; i++) player.ThrowBlueSpider(spot, Vector{}); + } + if (has(COLLECTIBLE_MISSING_PAGE_2)) missing_page_hit(player, amount); + if (zodiac(COLLECTIBLE_CANCER)) player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_WAFER, true, 1); + if (zodiac(COLLECTIBLE_VIRGO)) + { + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_VIRGO); + if (rng.RandomInt(std::max(1, VIRGO_ODDS - (int)(player.luck * VIRGO_LUCK))) == 0) + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_BOOK_OF_SHADOWS, true, 1); + } +} + +// Cursed Eye, without the Black Candle: a hit while the weapon charges teleports the player to a random room. Whether +// it did, which keeps the hit from animating. +bool cursed_eye_teleport(Entity_Player& player) +{ + Weapon* weapon = player.weapons[1].get(); + bool isCursed = player.HasCollectible(COLLECTIBLE_CURSED_EYE) && !player.HasCollectible(COLLECTIBLE_BLACK_CANDLE); + if (!isCursed || !weapon || !weapon->CanTriggerCursedEyeTeleport()) return false; + + game_random_room_move(*g_game, false, player.GetCollectibleRNG(COLLECTIBLE_CURSED_EYE).Next(), &player); + return true; +} + +// The collectibles a hit down to the last red heart sets off (part of 007729d0): the Polaroid's five second shield, +// the Negative's Necronomicon, and with no soul heart left to lose, Scapular's spent effect gives a soul heart back. +void last_heart_items_trigger(Entity_Player& player, uint64_t damageFlags) +{ + TemporaryEffects& effects = player.temporaryEffects; + + if (player.HasCollectible(COLLECTIBLE_POLAROID)) + { + TemporaryEffect shield(g_manager->itemConfig.GetCollectible(COLLECTIBLE_BOOK_OF_SHADOWS)); + shield.cooldown = POLAROID_SHIELD_FRAMES; + effects.AddEffect(shield, true, 1); + } + if (player.HasCollectible(COLLECTIBLE_NEGATIVE)) + player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM}); + + bool isLastHeart = + player.soulHearts < 1 || (player.redHearts < 1 && player.soulHearts == scale_for_hard_difficulty(1)); + bool isSaved = isLastHeart && player.HasCollectible(COLLECTIBLE_SCAPULAR) && + effects.HasCollectibleEffect(COLLECTIBLE_SCAPULAR) && !player.isDead && + !(damageFlags & (DAMAGE_RED_HEARTS | DAMAGE_IV_BAG)); + if (!isSaved) return; + + player.AddSoulHearts(2, false); + effects.RemoveCollectibleEffect(COLLECTIBLE_SCAPULAR, 1); + player.TryRemoveCollectibleCostume(COLLECTIBLE_SCAPULAR, false); + npc_sound_play(SOUND_HOLY, 1, 2, 1); + heart_rise_spawn(player, HEART_EFFECT_SCAPULAR); +} + +// The part of 00782af0 for the Book of Belial Judas's Birthright lends: unless Judas (or Dark Judas) keeps it with his +// Birthright, the passive copy goes and the slots holding it get the active Book of Belial back. +void book_of_belial_passive_update(Entity_Player& player) +{ + bool isJudas = player.playerType == PLAYER_JUDAS || player.playerType == PLAYER_BLACKJUDAS; + bool isKept = isJudas && player.HasCollectible(COLLECTIBLE_BIRTHRIGHT); + if (!player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) || isKept) return; + + player.collectibleCounts[COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE] = 0; + for (int slot = ACTIVE_SLOT_SECONDARY; slot >= ACTIVE_SLOT_PRIMARY; slot--) + { + if (player.activeItems[slot].item != COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) continue; + player.activeItems[slot].item = COLLECTIBLE_BOOK_OF_BELIAL; + player.collectibleCounts[COLLECTIBLE_BOOK_OF_BELIAL]++; + } + player.UpdateBookOfVirtues(false); +} + +// The part of 00782af0 after the inputs: moving and shooting count as actions, and with Gnawed Leaf a player who did +// nothing for over 60 frames turns to stone, a statue costume and a puff of dust, too heavy to push (a helper also +// turns white). Any action breaks it. The weight goes back to the player's own otherwise. +void gnawed_leaf_update(Entity_Player& player) +{ + constexpr int STATUE_FRAMES = 60; + constexpr int STATUE_DUST_SUBTYPE = 2; + constexpr float STATUE_DUST_RISE = -10; + constexpr ColorMod STATUE_WHITE = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; + ItemConfig_Item* statue = g_manager->itemConfig.GetNullItem(NULLITEM_STATUE); + + if (player.moveDirection != DIRECTION_NONE) player.lastActionTriggers |= ACTION_TRIGGER_MOVE; + if (player.fireDirection != DIRECTION_NONE) player.lastActionTriggers |= ACTION_TRIGGER_SHOOT; + if (!player.HasCollectible(COLLECTIBLE_GNAWED_LEAF) || player.lastActionTriggers != 0) + { + if (player.mass == STATUE_MASS) + { + player.RemoveCostume(statue); + player.mass = player.config->mass; + } + player.gnawedLeafTimer = 0; + } + else if (player.gnawedLeafTimer++ > STATUE_FRAMES) + { + if (player.mass != STATUE_MASS) + { + npc_sound_play(SOUND_GNAWED_LEAF_STONE, 1, 2, 1); + player.AddCostume(statue, false); + player.mass = STATUE_MASS; + uint32_t seed = Random(); + Entity* dust = g_game->Spawn({.position = player.pos, .spawner = &player, .subType = STATUE_DUST_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + dust->posOffset = vector_make(player.posOffset.x, player.posOffset.y + STATUE_DUST_RISE); + dust->renderDepthOffset = player.posOffset.y + 1; + dust->Update(); + } + if (player.variant == PLAYER_VARIANT_COOP_BABY || player.isCoopGhost) + player.SetColor(STATUE_WHITE, 2, 0, false, true); + } + if (player.mass != STATUE_MASS) player.mass = player.config->mass; +} + +// The part of 0077b020 for Trinity Shield: a shield floats 30 units out on the side the player shoots to (or faces), +// turning there by half the way each frame while shooting and slowing down after, in the colour of the tears. The +// eyes stay half closed. Without the item the shield goes. +void trinity_shield_update(Entity_Player& player, const PassiveShot& shot) +{ + constexpr float SHIELD_DISTANCE = 30; + constexpr float SHIELD_TURN_SHOOTING = 0.5f; + constexpr float SHIELD_TURN_IDLE = 0.8f; + constexpr float SHIELD_SIDE = 90; + constexpr int SHIELD_BLINK = 7; + constexpr std::array FACED_X = {-1, 0, 1, 0}; + constexpr std::array FACED_Y = {0, -1, 0, 1}; + Entity* held = player.trinityShield.get(); + + if (!player.HasCollectible(COLLECTIBLE_TRINITY_SHIELD)) + { + if (held) + { + held->Remove(); + player.trinityShield = nullptr; + } + return; + } + auto place = [&](Entity_Effect& shield, float angle) + { + shield.sprite.rotation = angle; + shield.pos = vector_add(player.pos, vector_scale(vector_from_angle(angle + SHIELD_SIDE), SHIELD_DISTANCE)); + shield.SetColor(player.tearColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + }; + if (!held) + { + uint32_t seed = Random(); + auto* shield = static_cast(g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, + .variant = EFFECT_TRINITY_SHIELD, .seed = seed})); + player.trinityShield = shield; + shield->parent = &player; + shield->rotation = player.trinityShieldAngle; + place(*shield, player.trinityShieldAngle); + shield->Update(); + return; + } + + auto& shield = static_cast(*held); + float turn = SHIELD_TURN_IDLE; + if (shot.isShootHeld) + { + bool isFacing = shot.direction.x == 0 && shot.direction.y == 0; + Vector aim = isFacing && player.headDirection >= DIRECTION_LEFT && player.headDirection <= DIRECTION_DOWN + ? vector_make(FACED_X[player.headDirection], FACED_Y[player.headDirection]) + : shot.direction; + shield.rotation = angle_wrap(vector_angle(aim) - SHIELD_SIDE); + player.trinityShieldAngle = shield.rotation; + turn = SHIELD_TURN_SHOOTING; + } + place(shield, angle_lerp(shield.sprite.rotation, shield.rotation, turn)); + player.blinkTime = std::max(player.blinkTime, SHIELD_BLINK); +} + +// The part of 0077b020 for Tech.5: every 16th frame of shooting (or Lilith's), two times in three, a thin laser fires +// on the shot's axis (or straight along it with the Analog Stick or a Marked target). +void tech_five_update(Entity_Player& player, const PassiveShot& shot) +{ + constexpr int TECH_FIVE_DELAY = 15; + constexpr int TECH_FIVE_ODDS = 3; + constexpr float TECH_FIVE_SCALE = 0.8f; + constexpr int TECH_FIVE_BLINK = 5; + + if (!player.HasCollectible(COLLECTIBLE_TECH_5)) return; + if (player.techFiveDelay >= 1) + { + player.techFiveDelay--; + return; + } + player.techFiveDelay = TECH_FIVE_DELAY; + if ((!shot.isAiming && !player.markedTarget) || random_below(TECH_FIVE_ODDS) == 0) return; + + bool isStraight = player.HasCollectible(COLLECTIBLE_ANALOG_STICK) || player.markedTarget; + Vector direction = isStraight ? shot.direction : vector_cardinal(shot.direction); + Entity_Laser* laser = player.FireTechLaser( + {.direction = direction, .position = player.pos, .offsetId = LASER_OFFSET_TECH5, .isOneHit = true}); + laser->set_scale(TECH_FIVE_SCALE); + laser->Update(); + player.blinkTime = TECH_FIVE_BLINK; +} + +// Trinity Shield's part of 005d4380 (Effect Update): the shield shows the frame of its side, drawn behind the player +// unless it faces down, and every enemy shot it touches dies. +static void trinity_shield_effect_update(Entity_Effect& shield) +{ + constexpr float SHIELD_RISE = -10; + constexpr float SHIELD_FRONT_DEPTH = 30; + constexpr float SIDE_FROM = 80; + constexpr float BACK_FROM = 100; + constexpr int SHIELD_FRAME_DOWN = 0; + constexpr int SHIELD_FRAME_LEFT = 2; + constexpr int SHIELD_FRAME_UP = 4; + constexpr int SHIELD_FRAME_RIGHT = 6; + float angle = shield.rotation; + bool isBack = std::fabs(angle) >= BACK_FROM; + + shield.posOffset = vector_make(0, SHIELD_RISE); + shield.sprite.isFlipX = isBack; + shield.sprite.isFlipY = isBack; + if (isBack) + { + shield.renderDepthOffset = 0; + shield.sprite.SetFrame("Rotation", SHIELD_FRAME_UP); + shield.posOffset.y = shield.posOffset.y - SHIELD_RISE; + } + else if (angle >= SIDE_FROM) + { + shield.renderDepthOffset = 0; + shield.sprite.SetFrame("Rotation", SHIELD_FRAME_RIGHT); + } + else if (angle <= -SIDE_FROM) + { + shield.renderDepthOffset = 0; + shield.sprite.SetFrame("Rotation", SHIELD_FRAME_LEFT); + } + else + { + shield.renderDepthOffset = SHIELD_FRONT_DEPTH; + shield.sprite.SetFrame("Rotation", SHIELD_FRAME_DOWN); + } + shield.targetPosition = {}; + EntityList_EL shots = entity_query_radius(shield.pos, shield.size, QUERY_PROJECTILES); + for (size_t i = 0; i < shots.size(); i++) + if (shots[i]->type == ENTITY_PROJECTILE) shots[i]->isDead = true; +} + +constexpr auto PASSIVE_EFFECT_BEHAVIOURS = std::to_array({ + {EFFECT_TRINITY_SHIELD, nullptr, effect_finishing, nullptr}, +}); + +// The effect variants the passives own: Trinity Shield's shield. +std::span passive_effect_behaviours() +{ + return PASSIVE_EFFECT_BEHAVIOURS; +} diff --git a/src/entity_player_passives.h b/src/entity_player_passives.h new file mode 100644 index 0000000..008604c --- /dev/null +++ b/src/entity_player_passives.h @@ -0,0 +1,36 @@ +#pragma once + +#include "classes.h" +#include + +struct EffectBehaviour; +struct Entity_Player; +struct TemporaryEffect; + +// Toxic Shock's green poop clouds, and how fast Unicorn Stump's music changes volume. +constexpr ColorMod TOXIC_SHOCK_COLOR = {{1, 1, 1, 1}, {0, 1, 0, 1}, {0, 0, 0}}; +constexpr float STUMP_VOLUME_RATE = 0.08f; + +// The passive collectibles' (1 to 366) pieces other files call: the effects the frame and stats are written for, the +// items' frame, the walking items' costumes and the hit, Cursed Eye's teleport and the last heart's saves. +bool is_passive_effect_plain(const TemporaryEffect& effect); +void passives_frame_update(Entity_Player& player); +void walking_items_animate(Entity_Player& player); +void book_of_belial_passive_update(Entity_Player& player); +void gnawed_leaf_update(Entity_Player& player); + +// What the shooting pieces of 0077b020 the passives own read: where the player shoots, whether it aims or holds the +// shoot input. +struct PassiveShot +{ + Vector direction{}; + bool isAiming = false; + bool isShootHeld = false; +}; + +void trinity_shield_update(Entity_Player& player, const PassiveShot& shot); +void tech_five_update(Entity_Player& player, const PassiveShot& shot); +std::span passive_effect_behaviours(); +void passives_hit_trigger(Entity_Player& player, int amount); +bool cursed_eye_teleport(Entity_Player& player); +void last_heart_items_trigger(Entity_Player& player, uint64_t damageFlags); diff --git a/src/entity_player_pills.cpp b/src/entity_player_pills.cpp new file mode 100644 index 0000000..73eb453 --- /dev/null +++ b/src/entity_player_pills.cpp @@ -0,0 +1,952 @@ +#include "entity_player.h" +#include "active_items.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_tear.h" +#include "game.h" +#include "grid_entity.h" +#include "hud.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "pocket_items.h" +#include "room.h" +#include "room_grid.h" +#include "room_special.h" +#include +#include +#include +#include +#include + +constexpr int BAD_GAS_POISON_FRAMES = 90; +constexpr int BAD_TRIP_COUNTDOWN = 30; +constexpr int DIARRHEA_PILL_FRAMES = 60; +constexpr int DIARRHEA_HORSE_PILL_FRAMES = 30; +constexpr int ENERGY_BATTERIES = 1; +constexpr int ENERGY_HORSE_BATTERIES = 3; +constexpr int ENERGY_BATTERY_ROLL = 2; +constexpr int EXCITED_FRAMES = 900; +constexpr int EXCITED_ROLL = 2; +constexpr int EXCITED_MIN_STEPS = 2; +constexpr int FRIENDS_FLIES = 3; +constexpr int FRIENDS_HORSE_FLIES = 12; +constexpr int HEMATEMESIS_HEARTS = 2; +constexpr int HEMATEMESIS_ROLL = 4; +constexpr int HEMATEMESIS_HORSE_MIN = 4; +constexpr int HORF_HORSE_TEARS = 6; +constexpr int INFESTED_QUESTION_ROLL = 3; +constexpr int INFESTED_ROLL = 2; +constexpr int IDENTIFIED_PILL_COLORS = 14; +constexpr int PARALYSIS_FRAMES = 120; +constexpr int PARALYSIS_HORSE_FRAMES = 240; +constexpr int PERCS_HORSE_HEARTS = 20; +constexpr int PHEROMONES_CHARM_FRAMES = 150; +constexpr int PHEROMONES_BOSS_CHARM_FRAMES = 300; +constexpr int PHEROMONES_SHAKE = 3; +constexpr int PHEROMONES_ECHO_DELAY = 20; +constexpr int POWER_SHAKE = 30; +constexpr int RELAX_FRAMES = 30; +constexpr int RELAX_HORSE_FRAMES = 300; +constexpr int RETRO_FRAMES = 900; +constexpr int RETRO_HORSE_FRAMES = 2700; +constexpr int STAT_COLOR_FRAMES = 15; +constexpr int STAT_COLOR_PRIORITY = 255; +constexpr int TELEPILLS_STAGE = 6; +constexpr int WIZARD_FRAMES = 900; +constexpr int WIZARD_HORSE_FRAMES = 1800; +constexpr int CREEP_COUNT = 3; +constexpr int CREEP_HORSE_COUNT = 9; +constexpr int CREEP_HORSE_TIMEOUT = 900; +constexpr int BOMBS_ARE_KEYS_CHANGED = 0x1e; +constexpr int PERMANENT = -1; +constexpr float BAD_GAS_RADIUS = 85; +constexpr float BAD_GAS_HORSE_RADIUS = 170; +constexpr float BAD_GAS_BEAN_RADIUS = 120; +constexpr float BAD_GAS_HORSE_BEAN_RADIUS = 200; +constexpr float BAD_GAS_HORSE_SCALE = 2; +constexpr float BAD_TRIP_DAMAGE = 2; +constexpr float BAD_TRIP_HORSE_DAMAGE = 4; +constexpr float BAD_TRIP_DEATHMATCH_SCALE = 8; +constexpr float CREEP_RADIUS = 40; +constexpr float CREEP_HORSE_RADIUS = 80; +constexpr float CREEP_MIN_RADIUS = 35; +constexpr float PILL_CREEP_SCALE = 5; +constexpr float HORF_DAMAGE = 200; +constexpr float HORF_FALL_ACCEL = 0.6f; +constexpr float HORF_FALL_SPEED = -13; +constexpr float HORF_HORSE_FALL_SPEED = -9; +constexpr float HORF_HORSE_FALL_ROLL = 5; +constexpr float HORF_HORSE_MIN_SCALE = 0.8f; +constexpr float HORF_HORSE_SPEED = 8; +constexpr float HORF_MIN_SCALE = 0.01f; +constexpr float HORF_SPEED = 10; +constexpr float LEMON_PARTY_HORSE_SCALE = 2; +constexpr float PICKUP_STEP = 40; +constexpr float PHEROMONES_ECHO_PITCH = 0.5f; +constexpr float PHEROMONES_ECHO_VOLUME = 1.2f; +constexpr float SPIDER_GRID_ORIGIN_X = 40; +constexpr float SPIDER_GRID_ORIGIN_Y = 120; +constexpr float SPIDER_GRID_STEP = 40; +constexpr float STAT_COLOR_TINT = 0.3f; +constexpr ColorMod BAD_GAS_CLOUDS = {{1, 1, 1, 1}, {0, 1, 0, 1}, {0, 0, 0}}; +constexpr ColorMod HORF_COLOR = {{0.5f, 0.9f, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod PARALYSIS_COLOR = {{0.6f, 0.6f, 0.6f, 1}, {0, 0, 0, 0}, {0.4f, 0.4f, 0.4f}}; +constexpr ColorMod PHEROMONES_CLOUDS = {{1, 1, 1, 1}, {2, 0, 1, 1}, {0, 0, 0}}; +constexpr ColorMod PHEROMONES_FART = {{2, 0, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr std::array TELEPILLS_HORSE_ROOMS = {4, 2, 7, 8, 18, 20, 21, 12, 11, 24, 9, 13}; +constexpr std::array QUESTIONMARK_HORSE_CURSES = {CURSE_OF_DARKNESS, CURSE_OF_THE_LOST, + CURSE_OF_THE_UNKNOWN, CURSE_OF_BLIND}; + +// An up pill's color left over the player (a colorize) and the offsets of the flash it starts with. +struct StatPillColor +{ + std::array colorize{}; + std::array flashOffset{}; +}; + +constexpr StatPillColor HEALTH_UP_COLOR = {{1, 0.5f, 0, 0.33f}, {0.5f, 0.25f, 0.25f}}; +constexpr StatPillColor RANGE_UP_COLOR = {{0.5f, 1, 1, 0.33f}, {0.25f, 0.5f, 0.5f}}; +constexpr StatPillColor SPEED_UP_COLOR = {{1, 1, 0, 0.33f}, {0.5f, 0.5f, 0.25f}}; +constexpr StatPillColor TEARS_UP_COLOR = {{0.5f, 0.5f, 1, 0.33f}, {0.4f, 0.4f, 0.5f}}; +constexpr StatPillColor LUCK_UP_COLOR = {{0, 1, 0, 0.33f}, {0.25f, 0.5f, 0.25f}}; +constexpr StatPillColor SHOT_SPEED_UP_COLOR = {{1.3f, 1.3f, 1.3f, 0.5f}, {0.5f, 0.5f, 0.5f}}; + +// One of Experimental Treatment's six stats: its up and down pills, the stats it rereads and its HUD text key. +struct ExperimentalStat +{ + int upPill = 0; + int downPill = 0; + uint32_t cacheFlags = 0; + const char* textFormat = nullptr; +}; + +constexpr std::array EXPERIMENTAL_PILL_STATS = {{ + {PILLEFFECT_HEALTH_UP, PILLEFFECT_HEALTH_DOWN, 0, "#STAT_%s_HP_%d"}, + {PILLEFFECT_TEARS_UP, PILLEFFECT_TEARS_DOWN, CACHE_FIREDELAY, "#STAT_%s_TEARS_%d"}, + {PILLEFFECT_RANGE_UP, PILLEFFECT_RANGE_DOWN, CACHE_RANGE, "#STAT_%s_RANGE_%d"}, + {PILLEFFECT_SPEED_UP, PILLEFFECT_SPEED_DOWN, CACHE_SPEED, "#STAT_%s_SPEED_%d"}, + {PILLEFFECT_LUCK_UP, PILLEFFECT_LUCK_DOWN, CACHE_LUCK, "#STAT_%s_LUCK_%d"}, + {PILLEFFECT_SHOT_SPEED_UP, PILLEFFECT_SHOT_SPEED_DOWN, CACHE_SHOTSPEED, "#STAT_%s_SHOT_SPEED_%d"}, +}}; + +// Whether PHD, Virgo, Lucky Foot or Virgo's zodiac sign turn the bad pills away. +static bool is_pill_protected(Entity_Player& player) +{ + return player.HasCollectible(COLLECTIBLE_PHD) || player.HasCollectible(COLLECTIBLE_VIRGO) || + player.HasCollectible(COLLECTIBLE_LUCKY_FOOT) || player.GetZodiacEffect() == COLLECTIBLE_VIRGO; +} + +// Spawns a pickup on a free spot near the player, held back a few frames by its place in a batch. +static void pickup_batch_spawn(Entity_Player& player, int variant, int subType, int index) +{ + uint32_t seed = Random(); + Vector position = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_STEP}); + Entity* pickup = g_game->Spawn( + {.position = position, .spawner = &player, .subType = subType, .type = ENTITY_PICKUP, .variant = variant, .seed = seed}); + + static_cast(pickup)->dropDelay = index; +} + +// Adds a null item's effect for a number of frames. +static void timed_null_effect_add(Entity_Player& player, int nullItem, int frames) +{ + TemporaryEffect effect(g_manager->itemConfig.GetNullItem(nullItem)); + + effect.cooldown = frames; + player.temporaryEffects.AddEffect(effect, true, 1); +} + +// Throws blue spiders from a position, two for a horse pill. +static void pill_spiders_spawn(PocketUse& use, Vector position, int count) +{ + Entity_Player& player = use.player; + + for (int i = 0; i < count * (use.isHorse ? 2 : 1); i++) + { + player.numBlueSpiders++; + spawn_blue_spider(position, &player, Vector{}); + } +} + +// Holds the pill up. +static void pill_animate(PocketUse& use) +{ + use.player.AnimatePill(use.pillColor, "UseItem"); +} + +// A stat pill: its stats asked for, the thumbs down for a down pill, the thumbs up with a flash of the stat's color for +// an up pill, the color staying over the player. +static void stat_pill_use(PocketUse& use, uint32_t cacheFlags, const StatPillColor* color) +{ + Entity_Player& player = use.player; + + player.cacheFlags |= cacheFlags; + if (!color) return player.AnimateSad(); + player.cacheFlags |= CACHE_COLOR; + player.AnimateHappy(); + sound_fart_play(use.sound); + player.colorOverride = COLOR_DEFAULT; + std::ranges::copy(color->colorize, player.colorOverride._colorize); + ColorMod flash = {{STAT_COLOR_TINT, STAT_COLOR_TINT, STAT_COLOR_TINT, 1}, {}, {}}; + std::ranges::copy(color->flashOffset, flash._offset); + player.SetColor(flash, STAT_COLOR_FRAMES, STAT_COLOR_PRIORITY, true, true); +} + +// Bad Gas: a fart that poisons every enemy in the room, bigger with a Butter Bean push for a horse pill, which also +// clouds the screen green when it poisoned something. +static void bad_gas_use(PocketUse& use) +{ + Entity_Player& player = use.player; + Room& room = *g_game->room; + + if (!use.isHorse) + { + game_fart({.position = player.pos, .source = &player, .radius = BAD_GAS_RADIUS}); + game_butter_bean_fart({.position = player.pos, .source = &player, .radius = BAD_GAS_BEAN_RADIUS, .isShowEffect = false}); + return pill_animate(use); + } + game_fart({.position = player.pos, .source = &player, .radius = BAD_GAS_HORSE_RADIUS, .scale = BAD_GAS_HORSE_SCALE}); + game_butter_bean_fart( + {.position = player.pos, .source = &player, .radius = BAD_GAS_HORSE_BEAN_RADIUS, .isShowEffect = false}); + + bool isPoisoned = false; + if (room.GetAliveEnemiesCount() > 0) + { + for (Entity* entity : room.GetEntities()->updateEL) + { + bool isTarget = (g_game->deathmatchManager.is_active() && entity->type == ENTITY_PLAYER) || + (entity->type >= ENTITY_FIRST_ENEMY && entity->type < ENTITY_EFFECT); + if (!isTarget || entity->HasEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_FRIENDLY)) continue; + entity->AddPoison(EntityRef(&player), BAD_GAS_POISON_FRAMES, 0, false); + isPoisoned = true; + } + } + if (isPoisoned) room.fxLayers.AddPoopFx(BAD_GAS_CLOUDS); + pill_animate(use); +} + +// Bad Trip: a full heart of damage that cannot kill, two for a horse pill. +static void bad_trip_use(PocketUse& use) +{ + Entity_Player& player = use.player; + float damage = use.isHorse ? BAD_TRIP_HORSE_DAMAGE : BAD_TRIP_DAMAGE; + + if (g_game->deathmatchManager.is_active()) damage *= BAD_TRIP_DEATHMATCH_SCALE; + player.TakeDamage(damage, DAMAGE_NOKILL | DAMAGE_INVINCIBLE | DAMAGE_NO_PENALTIES, EntityRef(&player), + BAD_TRIP_COUNTDOWN); + player.AnimateSad(); +} + +// Balls of Steel: two soul hearts, four for a horse pill. +static void balls_of_steel_use(PocketUse& use) +{ + use.player.AddSoulHearts(use.isHorse ? 8 : 4, false); + use.player.AnimateHappy(); + sound_fart_play(use.sound); +} + +// Bombs Are Key: bombs and keys swap, golden ones too, and a horse pill adds half of each again. Tainted ???'s poop +// takes the bombs' place. +static void bombs_are_keys_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + if (player.playerType == PLAYER_BLUEBABY_B) + { + std::swap(player.numKeys, player.poopMana); + player.AddPoopMana(0); + if (use.isHorse) + { + player.AddPoopMana((player.poopMana + 1) / 2); + player.AddKeys((player.numKeys + 1) / 2); + } + } + else + { + std::swap(player.numKeys, player.numBombs); + std::swap(player.hasGoldenKey, player.hasGoldenBomb); + if (use.isHorse) + { + player.AddBombs((player.numBombs + 1) / 2); + player.AddKeys((player.numKeys + 1) / 2); + } + } + player.ConsumableCountChanged(BOMBS_ARE_KEYS_CHANGED); + player.AnimateHappy(); + g_game->hud.refresh_request(HUD_REFRESH_PLAYER); +} + +// Explosive Diarrhea: a minute of explosive farts, another half minute for a horse pill. +static void explosive_diarrhea_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + sound_fart_play(SOUND_FART); + player.temporaryEffects.RemoveNullEffect(NULLITEM_EXPLOSIVE_DIARRHEA, -1); + timed_null_effect_add(player, NULLITEM_EXPLOSIVE_DIARRHEA, DIARRHEA_PILL_FRAMES); + if (use.isHorse) timed_null_effect_add(player, NULLITEM_EXPLOSIVE_DIARRHEA, DIARRHEA_HORSE_PILL_FRAMES); + player.AnimateSad(); + player.ShootCandle(Vector{}); +} + +// Full Health: every heart filled, and three soul hearts for a horse pill. +static void full_health_use(PocketUse& use) +{ + if (use.isHorse) use.player.AddSoulHearts(6, false); + use.player.SetFullHearts(); + use.player.AnimateHappy(); + sound_fart_play(use.sound); +} + +// Health Down: a heart container less, two for a horse pill, and the death it may cause prevented when it can. +static void health_down_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + player.AddMaxHearts(use.isHorse ? -4 : -2, false); + player.TryPreventDeath(); + player.sprite.overlayAnimState.SetAnimationData(nullptr); + player.AnimateSad(); +} + +// Health Up: an empty heart container, two for a horse pill, with the stat pills' red flash. +static void health_up_use(PocketUse& use) +{ + use.player.AddMaxHearts(use.isHorse ? 4 : 2, false); + stat_pill_use(use, 0, &HEALTH_UP_COLOR); +} + +// I Found Pills and Puberty: a costume, its bigger one for a horse pill. +static void costume_pill_use(PocketUse& use, int nullItem, int horseNullItem) +{ + Entity_Player& player = use.player; + ItemConfig& config = g_manager->itemConfig; + + if (use.isHorse) player.RemoveCostume(config.GetNullItem(nullItem)); + player.AddCostume(config.GetNullItem(use.isHorse ? horseNullItem : nullItem), false); + if (nullItem == NULLITEM_PUBERTY) + { + player.AnimateSad(); + player.IncrementPlayerFormCounter(PLAYER_FORM_ADULT, 1); + return; + } + sound_fart_play(SOUND_DERP); + pill_animate(use); +} + +// Pretty Fly: a fly that orbits the player, and its effect for a horse pill. +static void pretty_fly_use(PocketUse& use) +{ + if (use.isHorse) use.player.temporaryEffects.AddNullEffect(NULLITEM_EXTRA_BIG_FAN, true, 1); + use.player.cacheFlags |= CACHE_FAMILIARS; + use.player.AnimateHappy(); +} + +// Telepills: a random room of the floor, the I AM ERROR room among them unless the floor's Broken Shovel or photo door +// needs the player here. A horse pill picks among the special rooms, unvisited first. +static void telepills_use(PocketUse& use) +{ + Entity_Player& player = use.player; + Game& game = *g_game; + + if (use.isHorse) + { + teleport_random_room_of_types(player, TELEPILLS_HORSE_ROOMS, true); + return; + } + int stage = game.stage; + if ((game.GetCurses() & CURSE_OF_LABYRINTH) && !game.IsGreedMode()) stage++; + bool isShovelFloor = game.playerManager.AnyoneHasCollectible(COLLECTIBLE_BROKEN_SHOVEL) && !game.IsGreedMode() && + stage == TELEPILLS_STAGE; + bool isPhotoRoom = game.HasPhotoDoor() && game.room->descriptor->listIndex == game.lastBossRoomListIdx; + game_random_room_move(game, !isShovelFloor && !isPhotoRoom, player.GetPillRNG(PILLEFFECT_TELEPILLS).Next(), &player); +} + +// 48 Hour Energy: every active slot charged (doubled for a horse pill, the first one skipped by Placebo's copy) and a +// battery or more, a few lil batteries for a horse pill. +static void energy_use(PocketUse& use) +{ + Entity_Player& player = use.player; + bool isMimic = use.flags & USE_MIMIC; + + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + { + if (isMimic && slot == 0) continue; + if (use.isHorse) player.AddActiveCharge(player.GetActiveMaxCharge(slot) * 2, slot, true, false, false); + else if (player.FullCharge(slot, false, false)) break; + } + int count = (int)use.rng.RandomInt(ENERGY_BATTERY_ROLL) + (use.isHorse ? ENERGY_HORSE_BATTERIES : ENERGY_BATTERIES); + for (int i = 0; i < count; i++) + pickup_batch_spawn(player, PICKUP_LIL_BATTERY, isMimic && i > 0 ? BATTERY_MICRO : BATTERY_NORMAL, i); + player.AnimateHappy(); +} + +// Hematemesis: red health down to one heart (a Keeper keeps one coin heart) and a few hearts or coins dropped around. +static void hematemesis_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + player.redHearts = scale_for_hard_difficulty(std::min(player.GetEffectiveMaxHearts(), HEMATEMESIS_HEARTS)); + if (Entity_Player* sub = player.subPlayer) sub->redHearts = std::min(sub->GetEffectiveMaxHearts(), HEMATEMESIS_HEARTS); + player.UpdateHeartDependentEffects(); + + int variant = player.GetHealthType() == HEALTH_COIN ? PICKUP_COIN : PICKUP_HEART; + int count = (int)use.rng.RandomInt(HEMATEMESIS_ROLL) + (use.isHorse ? HEMATEMESIS_HORSE_MIN : 1); + for (int i = 0; i < count; i++) pickup_batch_spawn(player, variant, 1, i); + pill_animate(use); +} + +// Paralysis: the controls off for two seconds, four for a horse pill, the player greyed meanwhile. +static void paralysis_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + player.controlsCooldown = use.isHorse ? PARALYSIS_HORSE_FRAMES : PARALYSIS_FRAMES; + player.SetColor(PARALYSIS_COLOR, player.controlsCooldown, -1, true, true); + pill_animate(use); +} + +// I Can See Forever!: the secret rooms shown, the whole map for a horse pill. +static void see_forever_use(PocketUse& use) +{ + Game& game = *g_game; + + game.isCanSeeEverything = true; + if (use.isHorse) + { + game.ApplyMapEffect(); + game.ApplyBlueMapEffect(); + game.ApplyCompassEffect(true); + } + game.UpdateVisibility(); + use.player.AnimateHappy(); +} + +// Pheromones: a pink fart that charms every enemy for a while. A horse pill farts louder and bigger, makes the enemies +// friends for good (bosses and friends for longer) and clouds the screen pink. +static void pheromones_use(PocketUse& use) +{ + Entity_Player& player = use.player; + Entity* fart = g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_FART, .seed = Random()}); + + fart->SetColor(PHEROMONES_FART, -1, STAT_COLOR_PRIORITY, false, true); + if (use.isHorse) + { + g_manager->sfxManager.Stop(SOUND_FART); + g_manager->sfxManager.Play(SOUND_FART, {.frameDelay = 0}); + g_manager->sfxManager.Play( + SOUND_FART, {.volume = PHEROMONES_ECHO_VOLUME, .frameDelay = PHEROMONES_ECHO_DELAY, .pitch = PHEROMONES_ECHO_PITCH}); + game_shake_screen(PHEROMONES_SHAKE); + fart->sprite.scale = vector_scale(fart->sprite.scale, 2); + } + fart->Update(); + player.ShootCandle(Vector{}); + + for (Entity* entity : g_game->room->GetEntities()->updateEL) + { + if (entity == &player || !entity->IsVulnerableEnemy(nullptr)) continue; + if (!use.isHorse) entity->AddCharmed(EntityRef(&player), PHEROMONES_CHARM_FRAMES, false, false); + else if (entity->IsBoss() || entity->HasEntityFlags(FLAG_FRIENDLY)) + entity->AddCharmed(EntityRef(&player), PHEROMONES_BOSS_CHARM_FRAMES, false, false); + else + { + entity->AddCharmed(EntityRef(&player), PERMANENT, false, true); + if (entity->type == ENTITY_THE_HAUNT) entity->parent = nullptr; + } + } + if (use.isHorse) g_game->room->fxLayers.AddPoopFx(PHEROMONES_CLOUDS); + pill_animate(use); +} + +// Amnesia: the curse of the lost. A horse pill also forgets every identified pill, unless PHD's kind protects. +static void amnesia_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + g_game->AddCurse(CURSE_OF_THE_LOST, false); + if (use.isHorse && !player.HasCollectible(COLLECTIBLE_FALSE_PHD) && !is_pill_protected(player)) + std::fill_n(g_game->itemPool.identifiedPillEffects.begin(), IDENTIFIED_PILL_COLORS, false); + player.AnimateSad(); +} + +// Lemon Party: a pool of lemon creep, twice as big for a horse pill. +static void lemon_party_use(PocketUse& use) +{ + Entity_Player& player = use.player; + Entity* creep = g_game->Spawn({.position = player.pos, .spawner = &player, .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_LEMON_PARTY, .seed = Random()}); + + if (use.isHorse) static_cast(creep)->scale = LEMON_PARTY_HORSE_SCALE; + creep->Update(); + pill_animate(use); +} + +// R U a Wizard?: tears that fly diagonally for a while, longer for a horse pill. +static void wizard_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + player.AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_WIZARD), false); + player.AnimateHappy(); + player.rUaWizardTimer += use.isHorse ? WIZARD_HORSE_FRAMES : WIZARD_FRAMES; +} + +// Percs!: the Wafer's halved damage for the room, and ten red hearts for a horse pill. +static void percs_use(PocketUse& use) +{ + use.player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_WAFER, true, 1); + if (use.isHorse) use.player.AddHearts(PERCS_HORSE_HEARTS, false, false); + use.player.AnimateHappy(); +} + +// Addicted!: hits cost a whole heart for the room, and a broken heart for a horse pill. +static void addicted_use(PocketUse& use) +{ + use.player.temporaryEffects.AddNullEffect(NULLITEM_OVERDOSE, true, 1); + if (use.isHorse) use.player.AddBrokenHearts(1); + use.player.AnimateSad(); +} + +// Re-Lax: poop where the player stands still, for longer with a horse pill. +static void relax_use(PocketUse& use) +{ + sound_fart_play(SOUND_FART); + timed_null_effect_add(use.player, NULLITEM_RELAX, use.isHorse ? RELAX_HORSE_FRAMES : RELAX_FRAMES); + use.player.AnimateSad(); + use.player.ShootCandle(Vector{}); +} + +// ???: the curse of the maze with Blue Cap's look, and another random curse the floor lacks for a horse pill. +static void questionmark_use(PocketUse& use) +{ + Game& game = *g_game; + + game.AddCurse(CURSE_OF_MAZE, false); + use.player.AddCostume(g_manager->itemConfig.GetCollectible(COLLECTIBLE_BLUE_CAP), false); + if (use.isHorse) + { + std::vector curses; + for (uint32_t curse : QUESTIONMARK_HORSE_CURSES) + if (game.filter_curses(curse) == 0) curses.push_back(curse); + if (!curses.empty()) game.AddCurse(curses[game.generationRNG.RandomInt(curses.size())], false); + } + use.player.AnimateSad(); +} + +// One Makes You Larger and One Makes You Small: the size reread, a larger one counting toward Stompy. +static void size_pill_use(PocketUse& use, bool isLarger) +{ + pill_animate(use); + use.player.cacheFlags |= CACHE_SIZE; + if (isLarger) use.player.IncrementPlayerFormCounter(PLAYER_FORM_STOMPY, use.isHorse ? 2 : 1); +} + +// Infested!: every poop of the room bursts into a blue spider, or one or two from the player when there is none. +static void infested_use(PocketUse& use) +{ + Entity_Player& player = use.player; + Room& room = *g_game->room; + + bool isBurst = false; + for (int x = 1; x < room.gridWidth - 1; x++) + { + for (int y = 1; y < room.gridHeight - 1; y++) + { + GridEntity* grid = room.GetGridEntity(y * room.gridWidth + x); + if (!grid || grid->type != GRID_POOP) continue; + + Vector position = vector_make((float)(grid->gridIndex % room.gridWidth) * SPIDER_GRID_STEP + SPIDER_GRID_ORIGIN_X, + (float)(grid->gridIndex / room.gridWidth) * SPIDER_GRID_STEP + SPIDER_GRID_ORIGIN_Y); + pill_spiders_spawn(use, position, 1); + grid->Destroy(false, EntityRef(&player)); + isBurst = true; + } + } + if (!isBurst) pill_spiders_spawn(use, player.pos, (int)use.rng.RandomInt(INFESTED_ROLL) + 1); + pill_animate(use); +} + +// Infested?: a blue spider for each enemy alive, or one to three when there is none. +static void infested_question_use(PocketUse& use) +{ + int count = g_game->room->GetAliveEnemiesCount(); + + if (count == 0) count = (int)use.rng.RandomInt(INFESTED_QUESTION_ROLL) + 1; + pill_spiders_spawn(use, use.player.pos, count); + pill_animate(use); +} + +// Power Pill!: the Gamekid's invincibility. A horse pill shakes the screen and adds Leo's stomp once. +static void power_use(PocketUse& use) +{ + Entity_Player& player = use.player; + ItemConfig_Item* horseEffect = g_manager->itemConfig.GetNullItem(NULLITEM_HUGE_GROWTH); + + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_GAMEKID, true, 1); + if (!use.isHorse) return; + game_shake_screen(POWER_SHAKE); + if (player.temporaryEffects.has_item_effect(horseEffect)) return; + player.temporaryEffects.AddEffect(TemporaryEffect(horseEffect), true, 1); + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_LEO, false, 1); +} + +// Retro Vision: the screen pixelated for a while, longer for a horse pill. In a versus match only the local player +// would see it, which is not written. +static void retro_vision_use(PocketUse& use) +{ + Game& game = *g_game; + + if (game.deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::UsePill 007c4180 (Retro Vision's local player in a versus match)"); + game.pixelationTimer = std::max(use.isHorse ? RETRO_HORSE_FRAMES : RETRO_FRAMES, game.pixelationTimer); + game.pixelationDuration = game.pixelationTimer; + pill_animate(use); +} + +// Friends Till The End!: three blue flies, twelve for a horse pill. +static void friends_use(PocketUse& use) +{ + use.player.AddBlueFlies(use.isHorse ? FRIENDS_HORSE_FLIES : FRIENDS_FLIES, use.player.pos, nullptr); + pill_animate(use); +} + +// X-Lax and Something's Wrong...: three big pools of slippery or black creep around the player, nine farther and +// lasting longer for a horse pill. +static void creep_pill_use(PocketUse& use, int variant) +{ + Entity_Player& player = use.player; + int count = use.isHorse ? CREEP_HORSE_COUNT : CREEP_COUNT; + + for (int i = 0; i < count; i++) + { + uint32_t seed = Random(); + Vector direction = vector_from_angle((float)i * FULL_TURN_DEGREES / CREEP_COUNT); + float distance = random_unit() * (use.isHorse ? CREEP_HORSE_RADIUS : CREEP_RADIUS) + CREEP_MIN_RADIUS; + Entity* creep = g_game->Spawn({.position = vector_add(player.pos, vector_scale(direction, distance)), + .spawner = &player, .type = ENTITY_EFFECT, .variant = variant, .seed = seed}); + creep->AddEntityFlags(FLAG_FRIENDLY); + creep->sprite.scale = vector_make(PILL_CREEP_SCALE, PILL_CREEP_SCALE); + if (use.isHorse) + { + static_cast(creep)->timeout = CREEP_HORSE_TIMEOUT; + static_cast(creep)->lifespan = CREEP_HORSE_TIMEOUT; + } + creep->Update(); + } + pill_animate(use); +} + +// I'm Drowsy... and I'm Excited!!!: the room slowed or sped up as by the Broken Watch, the horse pill's for the floor. +// Excitement wears off after a while. +static void watch_pill_use(PocketUse& use, bool isExcited) +{ + Room& room = *g_game->room; + + if (use.isHorse) g_game->SetStateFlag(isExcited ? LEVEL_STATE_BROKEN_WATCH_FAST : LEVEL_STATE_BROKEN_WATCH_SLOW, true); + if (!isExcited) + { + room.SetBrokenWatchState(BROKEN_WATCH_SLOW); + room.SetSlowDown(INT_MAX); + } + else + { + room.SetBrokenWatchState(BROKEN_WATCH_FAST); + use.player.imExcitedSpeedupCountdown = ((int)use.rng.RandomInt(EXCITED_ROLL) + EXCITED_MIN_STEPS) * EXCITED_FRAMES; + use.player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_BELT, false, 1); + } + pill_animate(use); +} + +// Gulp!: the held trinkets smelted, made golden first by a horse pill. +static void gulp_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + if (use.isHorse) + { + for (uint32_t& trinket : player.trinkets) + if (trinket != 0) trinket |= TRINKET_GOLDEN_FLAG; + player.cacheFlags |= CACHE_ALL; + player.EvaluateItems(); + } + player.UseActiveItem({.item = COLLECTIBLE_SMELTER, .flags = USE_NOANIM}); + pill_animate(use); +} + +// One Horf: an explosive poison tear thrown up the way the player looks. A horse pill sprays six of random sizes. +static void horf_use(PocketUse& use) +{ + Entity_Player& player = use.player; + + for (int i = 0; i < (use.isHorse ? HORF_HORSE_TEARS : 1); i++) + { + uint32_t seed = use.isHorse ? 0 : Random(); + Vector direction = direction_unit(player.headDirection); + Vector velocity = vector_scale(direction, HORF_SPEED * player.shotSpeed); + float scale = 1; + if (use.isHorse) + { + Vector spread = random_direction(); + float spreadScale = random_unit(); + velocity = vector_add(vector_scale(spread, 2 * spreadScale), vector_scale(direction, HORF_HORSE_SPEED * player.shotSpeed)); + scale = random_unit() + HORF_HORSE_MIN_SCALE; + seed = Random(); + } + Entity_Tear* tear = static_cast(g_game->Spawn( + {.position = player.pos, .velocity = velocity, .spawner = &player, .type = ENTITY_TEAR, .seed = seed})); + tear->SetCollisionDamage(HORF_DAMAGE * scale); + tear->SetTearFlags(TearFlags().set(TEAR_EXPLOSIVE).set(TEAR_POISON)); + tear->fallingAccel = HORF_FALL_ACCEL; + if (use.isHorse) + { + tear->fallingSpeed = HORF_HORSE_FALL_SPEED - random_unit() * HORF_HORSE_FALL_ROLL; + tear->baseScale = std::max(scale, HORF_MIN_SCALE); + tear->fScale = tear->baseScale; + tear->ResetSpriteScale(); + } + else tear->fallingSpeed = HORF_FALL_SPEED; + tear->SetColor(HORF_COLOR, -1, STAT_COLOR_PRIORITY, false, true); + tear->Update(); + } +} + +// Feels Like I'm Walking On Sunshine!: Unicorn Stump's invincibility, the Gamekid's for a horse pill. +static void sunshine_use(PocketUse& use) +{ + if (use.isHorse) use.player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_GAMEKID, true, 1); + else use.player.UseActiveItem({.item = COLLECTIBLE_UNICORN_STUMP, .flags = USE_NOANIM}); + pill_animate(use); +} + +// Vurp!: the last pill used (this one for the first) dropped again, as a horse pill when this one was. +static void vurp_use(PocketUse& use) +{ + Entity_Player& player = use.player; + int color = player.lastPillColor != 0 ? player.lastPillColor : use.pillColor; + uint32_t seed = Random(); + Vector position = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_STEP}); + + if (use.isHorse) color |= PILL_HORSE_FLAG; + g_game->Spawn({.position = position, .spawner = &player, .subType = color, .type = ENTITY_PICKUP, .variant = PICKUP_PILL, + .seed = seed}) + ->Update(); + pill_animate(use); +} + +// One stat's HUD text for Experimental Treatment, "#STAT_UP_TEARS_1" translated. +static std::string experimental_text(int stat, std::string_view direction, int variant) +{ + char key[64]; + + snprintf(key, sizeof key, EXPERIMENTAL_PILL_STATS[stat].textFormat, std::string(direction).c_str(), variant); + return std::string(string_table_translate(g_manager->stringTable, key)); +} + +// Experimental Treatment: one random stat up and another down, health down only when the player can lose a container. +// PHD's kind keeps the down away and False PHD the up. The HUD names both under the pill's name. +static void experimental_use(PocketUse& use, std::string_view name) +{ + Entity_Player& player = use.player; + bool isSkipUp = player.HasCollectible(COLLECTIBLE_FALSE_PHD); + bool isSkipDown = is_pill_protected(player) && !isSkipUp; + std::array stats = {0, 1, 2, 3, 4, 5}; + int uses = use.isHorse ? 2 : 1; + + RNG::Shuffle(&player.GetPillRNG(PILLEFFECT_EXPERIMENTAL), stats.data(), stats.data() + stats.size()); + if (stats[0] == 0 && !player.CanUsePill(PILLEFFECT_HEALTH_DOWN)) std::swap(stats[0], stats.back()); + int down = stats[0]; + int up = stats[1]; + if (!isSkipUp) + { + player.pillEffectUses[EXPERIMENTAL_PILL_STATS[up].upPill] += uses; + player.cacheFlags |= EXPERIMENTAL_PILL_STATS[up].cacheFlags; + if (up == 0) player.AddMaxHearts(use.isHorse ? 4 : 2, false); + } + if (!isSkipDown) + { + player.pillEffectUses[EXPERIMENTAL_PILL_STATS[down].downPill] += uses; + player.cacheFlags |= EXPERIMENTAL_PILL_STATS[down].cacheFlags; + if (down == 0) + { + player.AddMaxHearts(use.isHorse ? -4 : -2, false); + player.TryPreventDeath(); + } + } + + if (!(use.flags & USE_NOHUD)) + { + std::string text; + if (isSkipDown) text = experimental_text(up, "UP", 1); + else if (isSkipUp) text = experimental_text(down, "DOWN", 1); + else text = experimental_text(up, "UP", 1) + ", " + experimental_text(down, "DOWN", 2); + if (!text.empty()) text[0] = (char)toupper(text[0]); + g_game->hud.show_pill_name(&player, std::string(name).c_str(), text.c_str()); + } + if (isSkipDown) + { + player.AnimateHappy(); + sound_fart_play(use.sound); + } + else if (isSkipUp) player.AnimateSad(); + else player.AnimateHappy(); +} + +// Runs a pill's own effect. Experimental Treatment shows its own text under the pill's name. +void pill_effect_run(PocketUse& use, int pillEffect, std::string_view name) +{ + switch (pillEffect) + { + case PILLEFFECT_BAD_GAS: + return bad_gas_use(use); + case PILLEFFECT_BAD_TRIP: + return bad_trip_use(use); + case PILLEFFECT_BALLS_OF_STEEL: + return balls_of_steel_use(use); + case PILLEFFECT_BOMBS_ARE_KEYS: + return bombs_are_keys_use(use); + case PILLEFFECT_EXPLOSIVE_DIARRHEA: + return explosive_diarrhea_use(use); + case PILLEFFECT_FULL_HEALTH: + return full_health_use(use); + case PILLEFFECT_HEALTH_DOWN: + return health_down_use(use); + case PILLEFFECT_HEALTH_UP: + return health_up_use(use); + case PILLEFFECT_I_FOUND_PILLS: + return costume_pill_use(use, NULLITEM_I_FOUND_PILLS, NULLITEM_I_FOUND_HORSE_PILLS); + case PILLEFFECT_PUBERTY: + return costume_pill_use(use, NULLITEM_PUBERTY, NULLITEM_HORSE_PUBERTY); + case PILLEFFECT_PRETTY_FLY: + return pretty_fly_use(use); + case PILLEFFECT_RANGE_DOWN: + return stat_pill_use(use, CACHE_RANGE, nullptr); + case PILLEFFECT_RANGE_UP: + return stat_pill_use(use, CACHE_RANGE, &RANGE_UP_COLOR); + case PILLEFFECT_SPEED_DOWN: + return stat_pill_use(use, CACHE_SPEED, nullptr); + case PILLEFFECT_SPEED_UP: + return stat_pill_use(use, CACHE_SPEED, &SPEED_UP_COLOR); + case PILLEFFECT_TEARS_DOWN: + return stat_pill_use(use, CACHE_FIREDELAY, nullptr); + case PILLEFFECT_TEARS_UP: + return stat_pill_use(use, CACHE_FIREDELAY, &TEARS_UP_COLOR); + case PILLEFFECT_LUCK_DOWN: + return stat_pill_use(use, CACHE_LUCK, nullptr); + case PILLEFFECT_LUCK_UP: + return stat_pill_use(use, CACHE_LUCK, &LUCK_UP_COLOR); + case PILLEFFECT_TELEPILLS: + return telepills_use(use); + case PILLEFFECT_48HOUR_ENERGY: + return energy_use(use); + case PILLEFFECT_HEMATEMESIS: + return hematemesis_use(use); + case PILLEFFECT_PARALYSIS: + return paralysis_use(use); + case PILLEFFECT_SEE_FOREVER: + return see_forever_use(use); + case PILLEFFECT_PHEROMONES: + return pheromones_use(use); + case PILLEFFECT_AMNESIA: + return amnesia_use(use); + case PILLEFFECT_LEMON_PARTY: + return lemon_party_use(use); + case PILLEFFECT_WIZARD: + return wizard_use(use); + case PILLEFFECT_PERCS: + return percs_use(use); + case PILLEFFECT_ADDICTED: + return addicted_use(use); + case PILLEFFECT_RELAX: + return relax_use(use); + case PILLEFFECT_QUESTIONMARK: + return questionmark_use(use); + case PILLEFFECT_LARGER: + case PILLEFFECT_SMALLER: + return size_pill_use(use, pillEffect == PILLEFFECT_LARGER); + case PILLEFFECT_INFESTED_EXCLAMATION: + return infested_use(use); + case PILLEFFECT_INFESTED_QUESTION: + return infested_question_use(use); + case PILLEFFECT_POWER: + return power_use(use); + case PILLEFFECT_RETRO_VISION: + return retro_vision_use(use); + case PILLEFFECT_FRIENDS_TILL_THE_END: + return friends_use(use); + case PILLEFFECT_X_LAX: + return creep_pill_use(use, EFFECT_CREEP_SLIPPERY_BROWN); + case PILLEFFECT_SOMETHINGS_WRONG: + return creep_pill_use(use, EFFECT_PLAYER_CREEP_BLACK); + case PILLEFFECT_IM_DROWSY: + case PILLEFFECT_IM_EXCITED: + return watch_pill_use(use, pillEffect == PILLEFFECT_IM_EXCITED); + case PILLEFFECT_GULP: + return gulp_use(use); + case PILLEFFECT_HORF: + return horf_use(use); + case PILLEFFECT_SUNSHINE: + return sunshine_use(use); + case PILLEFFECT_VURP: + return vurp_use(use); + case PILLEFFECT_SHOT_SPEED_DOWN: + return stat_pill_use(use, CACHE_SHOTSPEED, nullptr); + case PILLEFFECT_SHOT_SPEED_UP: + return stat_pill_use(use, CACHE_SHOTSPEED, &SHOT_SPEED_UP_COLOR); + case PILLEFFECT_EXPERIMENTAL: + return experimental_use(use, name); + } + if (pillEffect >= (int)g_manager->itemConfig.pillEffects.size()) + log_printf(LOG_WARN, "Pill %d Effect Not Implemented!\n", pillEffect); +} + +// 007c40e0 Whether a pill effect is safe to use: Bad Trip and Health Down only with more health than they take (more +// in a versus match), never under the instant death curse or for a coin-hearted Health Down. +bool Entity_Player::CanUsePill(int pillEffect) +{ + constexpr int SAFE_HEALTH = 2; + constexpr int VERSUS_SAFE_HEALTH = 16; + + if (pillEffect != PILLEFFECT_BAD_TRIP && pillEffect != PILLEFFECT_HEALTH_DOWN) return true; + if (HasInstantDeathCurse()) return false; + + int health = boneHearts - rottenHearts + soulHearts + redHearts; + if (pillEffect == PILLEFFECT_HEALTH_DOWN) + { + HealthType healthType = GetHealthType(); + if (healthType == HEALTH_COIN) return false; + health = healthType == HEALTH_SOUL ? soulHearts : healthType == HEALTH_BONE ? boneHearts * 2 : maxHearts; + } + return health > (g_game->deathmatchManager.is_active() ? VERSUS_SAFE_HEALTH : SAFE_HEALTH); +} + +// 007cdf30 Teleports the player to a random room of the floor's dimension whose type is listed, an unvisited one when +// asked and there is one. Telepills' generator picks. A room at grid index 0 is never chosen. +bool teleport_random_room_of_types(Entity_Player& player, std::span roomTypes, bool isPreferUnvisited) +{ + Game& game = *g_game; + std::set seen; + std::vector unvisited; + std::vector others; + + for (int i = 0; i < game.nbRooms; i++) + { + RoomDescriptor& room = game.roomList[i]; + if (!room.data || room.dimension != game.currentDimensionIdx) continue; + if (std::ranges::find(roomTypes, room.data->type) == roomTypes.end()) continue; + if (!seen.insert(room.gridIndex).second) continue; + (room.visitedCount == 0 && isPreferUnvisited ? unvisited : others).push_back(room.gridIndex); + } + + std::vector& rooms = unvisited.empty() ? others : unvisited; + if (rooms.empty()) return false; + int roomIndex = rooms[player.GetPillRNG(PILLEFFECT_TELEPILLS).Next() % rooms.size()]; + if (roomIndex == 0) return false; + + game.leaveDoor = -1; + game.StartRoomTransition({.player = &player, .animation = TRANSITION_TELEPORT, .roomIndex = roomIndex}); + return true; +} diff --git a/src/entity_player_pockets.cpp b/src/entity_player_pockets.cpp index 4eaf5d3..baf91f1 100644 --- a/src/entity_player_pockets.cpp +++ b/src/entity_player_pockets.cpp @@ -13,67 +13,20 @@ #include "menu_manager.h" #include "manager.h" #include "room.h" +#include "pocket_items.h" +#include "menu_special_seeds.h" +#include "player_stats.h" #include "room_grid.h" #include #include #include -// The cards the first floor's rooms, chests and rocks drop most (Lua's Card). -enum CardId : int -{ - CARD_ID_FOOL = 1, - CARD_ID_EMPEROR = 5, - CARD_ID_HIEROPHANT = 6, - CARD_ID_LOVERS = 7, - CARD_ID_JUSTICE = 9, - CARD_ID_HERMIT = 10, - CARD_ID_CLUBS_2 = 23, - CARD_ID_DIAMONDS_2 = 24, - CARD_ID_SPADES_2 = 25, - CARD_ID_HEARTS_2 = 26, - CARD_ID_VANILLA_LAST = 97 -}; +constexpr int CARD_ID_VANILLA_LAST = 97; -// The pill effects the first floor's pills most often have (Lua's PillEffect). -enum PillEffectId : int -{ - PILL_ID_BALLS_OF_STEEL = 2, - PILL_ID_BOMBS_ARE_KEYS = 3, - PILL_ID_HEALTH_DOWN = 6, - PILL_ID_HEALTH_UP = 7, - PILL_ID_RANGE_DOWN = 11, - PILL_ID_RANGE_UP = 12, - PILL_ID_SPEED_DOWN = 13, - PILL_ID_SPEED_UP = 14, - PILL_ID_TEARS_DOWN = 15, - PILL_ID_TEARS_UP = 16, - PILL_ID_LUCK_DOWN = 17, - PILL_ID_LUCK_UP = 18, - PILL_ID_GULP = 43, - PILL_ID_EXPERIMENTAL = 49, - PILL_ID_COUNT = 50 -}; - -// What a card's or pill's use goes on with after its effect: the item held up, nothing more, or nothing at all. -enum PocketUseEnd -{ - POCKET_END_ANIMATE, - POCKET_END_SKIP_ANIMATION, - POCKET_END_RETURN -}; - -// The sounds the pockets play (Lua's SoundEffect). -enum PocketSound : int -{ - POCKET_SOUND_POWERUP_SPEWER = 132, - POCKET_SOUND_THUMBS_DOWN = 267, - POCKET_SOUND_THUMBSUP = 268, - POCKET_SOUND_THUMBSUP_AMPLIFIED = 602, - POCKET_SOUND_THUMBS_DOWN_AMPLIFIED = 603, - POCKET_SOUND_POWERUP_SPEWER_AMPLIFIED = 604 -}; - -constexpr uint32_t STAT_PILL_COLOR_FLAGS = CACHE_COLOR; +constexpr int PILL_ID_TEARS_UP = 16; +constexpr int PILL_ID_GULP = 43; +constexpr int PILL_ID_EXPERIMENTAL = 49; +constexpr int PILL_ID_COUNT = 50; constexpr int ACHIEVEMENT_GULP = 386; constexpr int ANNOUNCER_FRAMES_RANDOM = 900; constexpr int ANNOUNCER_FRAMES = 2; @@ -81,47 +34,13 @@ constexpr int CHALLENGE_RANDOM_POCKETS = 32; constexpr int COLLECTIBLE_ECHO_CHAMBER = 700; constexpr int DELAYED_SFX_FRAMES = 2; constexpr int GULP_UNLOCK_USES = 4; -constexpr int PLAYING_CARD_EMPTY = 2; -constexpr int CARD_HEART_COUNT = 2; -constexpr int BOMBS_ARE_KEYS_CHANGED = 0x1e; -constexpr int STAT_COLOR_FRAMES = 15; -constexpr int STAT_COLOR_PRIORITY = 255; -constexpr int TAROT_ROOM_TYPE_BOSS = 5; -constexpr int TAROT_ROOM_TYPE_SHOP = 2; -constexpr int DAEMONS_TAIL_HEART_ODDS = 5; -constexpr int USE_ITEM_ACTION_TRIGGER = 8; constexpr uint8_t WILD_CARD_PILL = 0; constexpr uint8_t WILD_CARD_CARD = 1; constexpr float CARD_HELD_RISE = -12; constexpr float POCKET_DROP_STEP = 40; -constexpr float STAT_COLOR_TINT = 0.3f; - -// An up pill's color left over the player (a colorize) and the offsets of the flash it starts with. -struct StatPillColor -{ - std::array colorize{}; - std::array flashOffset{}; -}; - -constexpr StatPillColor HEALTH_UP_COLOR = {{1, 0.5f, 0, 0.33f}, {0.5f, 0.25f, 0.25f}}; -constexpr StatPillColor RANGE_UP_COLOR = {{0.5f, 1, 1, 0.33f}, {0.25f, 0.5f, 0.5f}}; -constexpr StatPillColor SPEED_UP_COLOR = {{1, 1, 0, 0.33f}, {0.5f, 0.5f, 0.25f}}; -constexpr StatPillColor TEARS_UP_COLOR = {{0.5f, 0.5f, 1, 0.33f}, {0.4f, 0.4f, 0.5f}}; -constexpr StatPillColor LUCK_UP_COLOR = {{0, 1, 0, 0.33f}, {0.25f, 0.5f, 0.25f}}; - -// A card's or pill's use as its effect runs: the player, its generator, and the sound an up pill plays. -struct PocketUse -{ - Entity_Player& player; - RNG& rng; - int sound = POCKET_SOUND_POWERUP_SPEWER; - bool isCarBattery = false; - bool isHorse = false; - bool isPlayAnimation = true; -}; // Plays a sound the seeds may swap for a fart, at full volume. -static void sound_fart_play(int sound) +void sound_fart_play(int sound) { int id = sound; @@ -169,7 +88,7 @@ static bool is_ascent_stage() } // Spawns a pickup on a free spot near the player, seeded from the use's generator. -static void pocket_pickup_spawn(PocketUse& use, int variant, int subType) +void pocket_pickup_spawn(PocketUse& use, int variant, int subType) { Entity_Player& player = use.player; uint32_t seed = use.rng.Next(); @@ -279,14 +198,14 @@ void Entity_Player::TriggerEchoChamber(uint32_t, int) // 007abd30 Plays the thumbs up with its sound. void Entity_Player::AnimateHappy() { - sound_fart_play(POCKET_SOUND_THUMBSUP); + sound_fart_play(SOUND_THUMBSUP); PlayExtraAnimation("Happy"); } // 007abd90 Plays the thumbs down with its sound. void Entity_Player::AnimateSad() { - sound_fart_play(POCKET_SOUND_THUMBS_DOWN); + sound_fart_play(SOUND_THUMBS_DOWN); PlayExtraAnimation("Sad"); } @@ -371,114 +290,25 @@ bool pocket_item_collect(Entity_Pickup& pocket, Entity_Player& player) return true; } -// The Fool: back to the floor's first room. -static PocketUseEnd fool_use(PocketUse& use) -{ - if (use.isCarBattery) return POCKET_END_RETURN; - - g_game->leaveDoor = -1; - g_game->StartRoomTransition({.player = &use.player, .animation = TRANSITION_TELEPORT, .dimension = 0, - .roomIndex = g_game->startingRoomIdx}); - return POCKET_END_SKIP_ANIMATION; -} - -// The Emperor and the Hermit: off to the floor's boss room or shop, when it has one. -static PocketUseEnd room_card_use(PocketUse& use, int roomType) -{ - if (use.isCarBattery) return POCKET_END_RETURN; - - int roomIndex = g_game->QueryRoomTypeIndex(roomType, false, use.rng, false); - if (roomIndex < 0) return POCKET_END_ANIMATE; - g_game->leaveDoor = -1; - g_game->StartRoomTransition({.player = &use.player, .animation = TRANSITION_TELEPORT, .roomIndex = roomIndex}); - if (roomType == TAROT_ROOM_TYPE_SHOP) return POCKET_END_SKIP_ANIMATION; - use.isPlayAnimation = false; - return POCKET_END_ANIMATE; -} - -// The Hierophant and the Lovers: two soul or red hearts. -static PocketUseEnd hearts_card_use(PocketUse& use, int heartSubType) -{ - if (use.isCarBattery) return POCKET_END_RETURN; - - for (int i = 0; i < CARD_HEART_COUNT; i++) pocket_pickup_spawn(use, PICKUP_HEART, heartSubType); - return POCKET_END_ANIMATE; -} - -// Justice: a heart (Daemon's Tail lets one in five through), a bomb, a key and a coin. -static PocketUseEnd justice_use(PocketUse& use) -{ - Entity_Player& player = use.player; - if (use.isCarBattery) return POCKET_END_RETURN; - - bool isTailed = player.HasTrinket(TRINKET_DAEMONS_TAIL); - if (!isTailed || player.GetTrinketRNG(TRINKET_DAEMONS_TAIL).RandomInt(DAEMONS_TAIL_HEART_ODDS) == 0) - pocket_pickup_spawn(use, PICKUP_HEART, 0); - pocket_pickup_spawn(use, PICKUP_BOMB, 0); - pocket_pickup_spawn(use, PICKUP_KEY, 0); - pocket_pickup_spawn(use, PICKUP_COIN, 0); - return POCKET_END_ANIMATE; -} - -// The 2 of Clubs, Diamonds, Spades and Hearts: double the bombs, coins, keys or red hearts, or two when there are -// none. Tainted Bethany's hearts are her blood charges. -static PocketUseEnd playing_card_use(PocketUse& use, int card) -{ - Entity_Player& player = use.player; - auto doubled = [](int count) { return count == 0 ? PLAYING_CARD_EMPTY : count; }; - if (use.isCarBattery) return POCKET_END_RETURN; - - if (card == CARD_ID_CLUBS_2) player.AddBombs(doubled(player.numBombs)); - else if (card == CARD_ID_DIAMONDS_2) player.AddCoins(doubled(player.numCoins)); - else if (card == CARD_ID_SPADES_2) player.AddKeys(doubled(player.numKeys)); - else if (player.playerType == PLAYER_BETHANY_B) player.AddBloodCharge(doubled(player.effectiveBloodCharge)); - else if (g_game->deathmatchManager.is_active()) - reconstruction_missing("Entity_Player::UseCard 007b2230 (the 2 of Hearts in a deathmatch)"); - else player.AddHearts(doubled(player.redHearts), false, false); - return POCKET_END_ANIMATE; -} - -// Runs a card's own effect. The cards not written yet stop the game. -static PocketUseEnd card_effect_run(PocketUse& use, int card) -{ - switch (card) - { - case CARD_ID_FOOL: - return fool_use(use); - case CARD_ID_EMPEROR: - return room_card_use(use, TAROT_ROOM_TYPE_BOSS); - case CARD_ID_HIEROPHANT: - return hearts_card_use(use, HEART_SOUL); - case CARD_ID_LOVERS: - return hearts_card_use(use, HEART_RED); - case CARD_ID_JUSTICE: - return justice_use(use); - case CARD_ID_HERMIT: - return room_card_use(use, TAROT_ROOM_TYPE_SHOP); - case CARD_ID_CLUBS_2: - case CARD_ID_DIAMONDS_2: - case CARD_ID_SPADES_2: - case CARD_ID_HEARTS_2: - return playing_card_use(use, card); - } - reconstruction_missing(("Entity_Player::UseCard 007b2230 (card " + std::to_string(card) + ")").c_str()); -} - // 007b2230 Uses a card: its effect, the card held up unless hidden, the announcer naming it now and then, and the mods' -// MC_USE_CARD. The random cards challenge and Tarot Cloth's doubled tarot cards are not written yet. +// MC_USE_CARD. The random cards challenge swaps it for a random card. Tarot Cloth doubles a tarot card: the ones with +// a doubled effect run it, the others run once more as a car battery's second use. void Entity_Player::UseCard(int cardType, uint32_t useFlag) { + constexpr int ONLINE_STAT_CARDS = 5; + ItemConfig_Card* card = cardType >= 0 ? g_manager->itemConfig.GetCard(cardType) : nullptr; if (!card) return; + Player_stats_add(g_game->onlinePlayerStats, ONLINE_STAT_CARDS, this, 1); int frames = announcer_frames(); - if (g_game->challenge == CHALLENGE_RANDOM_POCKETS) - reconstruction_missing("Entity_Player::UseCard 007b2230 (the random cards challenge)"); - if (HasCollectible(COLLECTIBLE_TAROT_CLOTH) && (card->cardType == CARD_TAROT || card->cardType == CARD_TAROT_REVERSE)) - reconstruction_missing("Entity_Player::UseCard 007b2230 (Tarot Cloth)"); + if (g_game->challenge == CHALLENGE_RANDOM_POCKETS) cardType = (int)(GetCardRNG(cardType).Next() % CARD_ID_VANILLA_LAST) + 1; - PocketUse use = {.player = *this, .rng = GetCardRNG(cardType)}; + PocketUse use = {.player = *this, .rng = GetCardRNG(cardType), .flags = useFlag}; use.isCarBattery = useFlag & USE_CARBATTERY; + use.isAddCostume = !(useFlag & USE_NOCOSTUME); + use.isDoubled = HasCollectible(COLLECTIBLE_TAROT_CLOTH) && (card->cardType == CARD_TAROT || card->cardType == CARD_TAROT_REVERSE); + if (use.isDoubled && (useFlag & USE_OWNED) && !use.isCarBattery) UseCard(cardType, USE_CARBATTERY); use.isPlayAnimation = !(useFlag & USE_NOANIM); bool isAnnounced = is_announcer_rolled(useFlag) && (!is_ascent_stage() || !g_game->GetStateFlag(GAME_STATE_BACKWARDS_PATH)) && g_game->stage != STAGE_HOME; @@ -499,102 +329,6 @@ void tears_up_unlock_check(Entity_Player& player) if (tearsUps >= TEARS_UP_UNLOCK_COUNT) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_TEARS_UP_ITEMS); } -// A stat pill: its stats asked for, the thumbs down for a down pill, the thumbs up with a flash of the stat's color for -// an up pill, the color staying over the player. -static void stat_pill_use(PocketUse& use, uint32_t cacheFlags, const StatPillColor* color) -{ - Entity_Player& player = use.player; - - player.cacheFlags |= cacheFlags; - if (!color) return player.AnimateSad(); - player.cacheFlags |= STAT_PILL_COLOR_FLAGS; - player.AnimateHappy(); - sound_fart_play(use.sound); - player.colorOverride = COLOR_DEFAULT; - std::ranges::copy(color->colorize, player.colorOverride._colorize); - ColorMod flash = {{STAT_COLOR_TINT, STAT_COLOR_TINT, STAT_COLOR_TINT, 1}, {}, {}}; - std::ranges::copy(color->flashOffset, flash._offset); - player.SetColor(flash, STAT_COLOR_FRAMES, STAT_COLOR_PRIORITY, true, true); -} - -// Balls of Steel: two soul hearts, four for a horse pill. -static void balls_of_steel_use(PocketUse& use) -{ - use.player.AddSoulHearts(use.isHorse ? 8 : 4, false); - use.player.AnimateHappy(); - sound_fart_play(use.sound); -} - -// Bombs Are Key: bombs and keys swap, golden ones too, and a horse pill adds half of each again. -static void bombs_are_keys_use(PocketUse& use) -{ - Entity_Player& player = use.player; - if (player.playerType == PLAYER_BLUEBABY_B) - reconstruction_missing("Entity_Player::UsePill 007c4180 (Bombs Are Key with poop)"); - - std::swap(player.numKeys, player.numBombs); - std::swap(player.hasGoldenKey, player.hasGoldenBomb); - if (use.isHorse) - { - player.AddBombs((player.numBombs + 1) / 2); - player.AddKeys((player.numKeys + 1) / 2); - } - player.ConsumableCountChanged(BOMBS_ARE_KEYS_CHANGED); - player.AnimateHappy(); - g_game->hud.refresh_request(HUD_REFRESH_PLAYER); -} - -// Health Down: a heart container less, two for a horse pill, and the death it may cause prevented when it can. -static void health_down_use(PocketUse& use) -{ - Entity_Player& player = use.player; - - player.AddMaxHearts(use.isHorse ? -4 : -2, false); - player.TryPreventDeath(); - player.sprite.overlayAnimState.SetAnimationData(nullptr); - player.AnimateSad(); -} - -// Health Up: an empty heart container, two for a horse pill, with the stat pills' red flash. -static void health_up_use(PocketUse& use) -{ - use.player.AddMaxHearts(use.isHorse ? 4 : 2, false); - stat_pill_use(use, 0, &HEALTH_UP_COLOR); -} - -// Runs a pill's own effect. The effects not written yet stop the game. -static void pill_effect_run(PocketUse& use, int pillEffect) -{ - switch (pillEffect) - { - case PILL_ID_BALLS_OF_STEEL: - return balls_of_steel_use(use); - case PILL_ID_BOMBS_ARE_KEYS: - return bombs_are_keys_use(use); - case PILL_ID_HEALTH_DOWN: - return health_down_use(use); - case PILL_ID_HEALTH_UP: - return health_up_use(use); - case PILL_ID_RANGE_DOWN: - return stat_pill_use(use, CACHE_RANGE, nullptr); - case PILL_ID_RANGE_UP: - return stat_pill_use(use, CACHE_RANGE, &RANGE_UP_COLOR); - case PILL_ID_SPEED_DOWN: - return stat_pill_use(use, CACHE_SPEED, nullptr); - case PILL_ID_SPEED_UP: - return stat_pill_use(use, CACHE_SPEED, &SPEED_UP_COLOR); - case PILL_ID_TEARS_DOWN: - return stat_pill_use(use, CACHE_FIREDELAY, nullptr); - case PILL_ID_TEARS_UP: - return stat_pill_use(use, CACHE_FIREDELAY, &TEARS_UP_COLOR); - case PILL_ID_LUCK_DOWN: - return stat_pill_use(use, CACHE_LUCK, nullptr); - case PILL_ID_LUCK_UP: - return stat_pill_use(use, CACHE_LUCK, &LUCK_UP_COLOR); - } - reconstruction_missing(("Entity_Player::UsePill 007c4180 (pill effect " + std::to_string(pillEffect) + ")").c_str()); -} - // The pill's name and description as the HUD shows them, its #keys looked up in the "PocketItems" string table. static std::string pocket_text(std::string_view text) { @@ -606,32 +340,50 @@ static std::string pocket_text(std::string_view text) return std::string(isMissing ? text : localized); } -// 007c4180 Uses a pill effect: the screen blooms, the pill color is identified, its name shows and its use counts, -// its effect runs, the announcer names it now and then and the mods see it. A horse pill doubles the count and swaps -// the thumbs' sounds for louder ones. The golden pill, the random pills challenge, the seeds that hide or scramble -// pill names, False PHD and the versus mode's remote players are not written yet. The original keeps the last pill -// color for the save, which the curated player has no field for. +// 007c4180 Uses a pill effect: the screen blooms, the pill color is identified (a golden pill changes the pools +// instead), its name shows and its use counts, its effect runs, the announcer names it now and then and the mods see +// it. A horse pill doubles the count and swaps the thumbs' sounds for louder ones. False PHD turns a bad pill into a +// black heart and some damage. The random pills challenge shows a random pill's name, and the seeds hide or scramble +// it. Netplay's remote players, whose pills the original keeps off the HUD, are offline. void Entity_Player::UsePill(int pillEffect, int pillColor, uint32_t useFlags) { + constexpr int ONLINE_STAT_PILLS = 6; + constexpr int FALSE_PHD = 654; + constexpr int FALSE_PHD_SHIFT = 72; + constexpr int FALSE_PHD_PILLS[] = {25, 1, 27, 22, 29, 31, 37, 42}; + constexpr float FALSE_PHD_STEP = 40; + Game& game = *g_game; game.bloomDuration = 30; game.bloomTimer = 30; game.bloomStrength = 1; - if (game.deathmatchManager.is_active()) - reconstruction_missing("Entity_Player::UsePill 007c4180 (a versus mode's remote player)"); + Player_stats_add(game.onlinePlayerStats, ONLINE_STAT_PILLS, this, 1); bool isHorse = pillColor & PILL_HORSE_FLAG; int color = (int)(pillColor & PILL_COLOR_MASK); - if (color == PILL_COLOR_GOLD) reconstruction_missing("Entity_Player::UsePill 007c4180 (the golden pill)"); - game.itemPool.identifiedPillEffects[std::min(color, PILL_COLOR_GOLD)] = true; + if (color == PILL_COLOR_GOLD) + { + RNG& rng = GetCollectibleRNG(COLLECTIBLE_PHD); + game.itemPool.on_pill_used(pillColor, rng.Next(), rng._seed); + } + else game.itemPool.identifiedPillEffects[std::min(color, PILL_COLOR_GOLD)] = true; - ItemConfig_Pill* pill = pillEffect >= 0 ? g_manager->itemConfig.GetPillEffect(pillEffect) : nullptr; - if (game.challenge == CHALLENGE_RANDOM_POCKETS) - reconstruction_missing("Entity_Player::UsePill 007c4180 (the random pills challenge)"); - if (game.seedEffects.HasSeedEffect(SEED_PILLS_NEVER_IDENTIFY) || game.seedEffects.HasSeedEffect(SEED_DYSLEXIA)) - reconstruction_missing("Entity_Player::UsePill 007c4180 (a pill's hidden or scrambled name)"); + ItemConfig& config = g_manager->itemConfig; + ItemConfig_Pill* pill = pillEffect >= 0 ? config.GetPillEffect(pillEffect) : nullptr; + if (game.challenge == CHALLENGE_RANDOM_POCKETS && pillEffect >= 0 && pillEffect < PILL_ID_COUNT) + pill = config.GetPillEffect((int)(GetPillRNG(pillEffect).Next() % PILL_ID_COUNT)); std::string name = pill ? pocket_text(pill->name) : std::string(); std::string description = pill ? pocket_text(pill->desc) : std::string(); + if (game.seedEffects.HasSeedEffect(SEED_PILLS_NEVER_IDENTIFY)) + { + name = pocket_text("#QUESTION_MARKS_NAME"); + description.clear(); + } + if (game.seedEffects.HasSeedEffect(SEED_DYSLEXIA)) + { + name = string_scramble_seeded(name); + description = string_scramble_seeded(description); + } if (!(useFlags & USE_NOHUD) && pillEffect != PILL_ID_EXPERIMENTAL) game.hud.show_pill_name(this, name.c_str(), description.c_str()); if (pillEffect >= 0 && pillEffect < (int)pillEffectUses.size()) pillEffectUses[pillEffect] += isHorse ? 2 : 1; @@ -640,27 +392,38 @@ void Entity_Player::UsePill(int pillEffect, int pillColor, uint32_t useFlags) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_GULP); int frames = announcer_frames(); - PocketUse use = {.player = *this, .rng = GetPillRNG(pillEffect)}; + PocketUse use = {.player = *this, .rng = GetPillRNG(pillEffect), .pillColor = pillColor, .flags = useFlags}; use.isHorse = isHorse; - use.sound = isHorse ? POCKET_SOUND_POWERUP_SPEWER_AMPLIFIED : POCKET_SOUND_POWERUP_SPEWER; + use.sound = isHorse ? SOUND_POWERUP_SPEWER_AMPLIFIED : SOUND_POWERUP_SPEWER; bool isAnnounced = is_announcer_rolled(useFlags) && ((!is_ascent_stage() && game.stage != STAGE_HOME) || !game.GetStateFlag(GAME_STATE_BACKWARDS_PATH)); - pill_effect_run(use, pillEffect); + pill_effect_run(use, pillEffect, name); if (isAnnounced && pill && pill->announcerVoice != 0) announcer_queue(*this, isHorse ? pill->announcerVoiceSuper : pill->announcerVoice, pill->announcerDelay, frames); lua_engine_get().UsePill(pillEffect, this, useFlags); if (isHorse && sprite.IsPlaying("Happy")) { - g_manager->sfxManager.Stop(POCKET_SOUND_THUMBSUP); - g_manager->sfxManager.Play(POCKET_SOUND_THUMBSUP_AMPLIFIED, {}); + g_manager->sfxManager.Stop(SOUND_THUMBSUP); + g_manager->sfxManager.Play(SOUND_THUMBSUP_AMPLIFIED, {}); } else if (isHorse && sprite.IsPlaying("Sad")) { - g_manager->sfxManager.Stop(POCKET_SOUND_THUMBS_DOWN); - g_manager->sfxManager.Play(POCKET_SOUND_THUMBS_DOWN_AMPLIFIED, {}); + g_manager->sfxManager.Stop(SOUND_THUMBS_DOWN); + g_manager->sfxManager.Play(SOUND_THUMBSDOWN_AMPLIFIED, {}); } - if (HasCollectible(COLLECTIBLE_FALSE_PHD)) reconstruction_missing("Entity_Player::UsePill 007c4180 (False PHD)"); + if (HasCollectible(FALSE_PHD)) + { + cacheFlags |= CACHE_DAMAGE; + if (std::ranges::find(FALSE_PHD_PILLS, pillEffect) != std::end(FALSE_PHD_PILLS)) + { + RNG heartRng = rng_make(use.rng._seed, FALSE_PHD_SHIFT); + uint32_t seed = heartRng.Next(); + Vector position = room_free_pickup_position_find({.position = pos, .step = FALSE_PHD_STEP}); + game.Spawn({.position = position, .subType = HEART_BLACK, .type = ENTITY_PICKUP, .variant = PICKUP_HEART, .seed = seed}); + } + } + if (pillColor != 0 && color != PILL_COLOR_GOLD) lastPillColor = pillColor; } // The first pocket item is used up: the others move up and the last slot empties. @@ -682,9 +445,6 @@ void Entity_Player::pocket_use_input() constexpr int EVENT_CARDS_USED = 196; constexpr int COLLECTION_PILL = 43; constexpr int COLLECTION_CARD = 61; - constexpr int CARD_ID_RED_KEY_CRACKED = 78; - constexpr int CARD_ID_WILD = 80; - constexpr int CARD_ID_EXCEPTION = 48; constexpr int TRINKET_ENDLESS_NAMELESS = 79; constexpr int GOLDEN_PILL_KEEP_CHANCE = 5; constexpr int PERCENT = 100; @@ -704,17 +464,17 @@ void Entity_Player::pocket_use_input() PocketItem used = pocketItems[0]; if (used.id == 0) return; - lastActionTriggers |= USE_ITEM_ACTION_TRIGGER; + lastActionTriggers |= ACTION_TRIGGER_POCKET; PersistentGameData& save = g_manager->persistentGameData; if (used.type == POCKET_CARD) { - if (used.id == CARD_ID_RED_KEY_CRACKED && !is_active_usable(*this, COLLECTIBLE_RED_KEY, -1)) return; + if (used.id == CARD_CRACKED_KEY && !is_active_usable(*this, COLLECTIBLE_RED_KEY, -1)) return; save.AddToCollection(COLLECTION_CARD); save.IncreaseEventCounter(EVENT_CARDS_USED, 1); pockets_shift(*this); TriggerEchoChamber(POCKET_CARD, used.id); UseCard(used.id, USE_OWNED); - if (used.id != CARD_ID_WILD && used.id != CARD_ID_EXCEPTION) + if (used.id != CARD_WILD && used.id != CARD_QUESTIONMARK) { wildCardItemType = WILD_CARD_CARD; wildCardItem = used.id; diff --git a/src/entity_player_poop_spells.cpp b/src/entity_player_poop_spells.cpp new file mode 100644 index 0000000..17ea7cd --- /dev/null +++ b/src/entity_player_poop_spells.cpp @@ -0,0 +1,266 @@ +#include "entity_player_characters.h" +#include "active_items.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_pickup.h" +#include "game.h" +#include "hud.h" +#include "loot_list.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "player_hud.h" +#include +#include + +constexpr int POOP_SPELL_PICK_SHIFT = 35; +constexpr int POOP_SPELL_RARE_END = 4; +constexpr int POOP_SPELL_MIDDLE_END = 15; +constexpr float POOP_CHARGE_PER_DAMAGE = 1.5f; +constexpr int POOP_FART_SUBTYPE = 10; +constexpr float POOP_FART_SCALE = 0.5f; +constexpr float POOP_FART_VOLUME = 0.8f; +constexpr float POOP_FART_PITCH = 1.8f; +constexpr float POOP_FART_PITCH_SPREAD = 0.2f; +constexpr ColorMod POOP_FART_COLOR = {{1.8f, 0.7f, 1.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float LIQUID_GURGLE_PITCH = 1.5f; +constexpr int LIQUID_CREEP_SUBTYPE = 1; +constexpr int LIQUID_CREEP_FRAMES = 36; +constexpr float SPELL_FART_RADIUS = 85; +constexpr float SPELL_BEAN_RADIUS = 120; +constexpr int SPELL_CLOUD_SUBTYPE = 1; +constexpr float SPELL_BOMB_PUSH = 0.1f; +constexpr int DIARRHEA_FRAMES = 60; +constexpr float SPELL_SLOT_STEP = 12; +constexpr float SPELL_SLOT_INSET = 8; +constexpr float SPELL_SLOT_FAINT = 0.1f; + +// The poop pile each poop spell lifts (the exe's table at 00b6ba00), none for the other spells. +constexpr std::array POOP_SPELL_PILES = {0, 10, 12, 13, 11, 14, 15, 16, 0, 0, 0, 0}; + +// A spell with its weight in one stretch of the bag. +struct SpellWeight +{ + PoopSpell spell; + int weight; +}; + +// The bag's stretches: three fixed spells (bomb, fart, liquid), one rare draw, eleven from the middle and the last +// five from the common pool. +constexpr PoopSpell POOP_SPELL_BAG_START[] = {POOP_SPELL_BOMB, POOP_SPELL_FART, POOP_SPELL_LIQUID}; +constexpr SpellWeight POOP_SPELLS_COMMON[] = {{POOP_SPELL_POOP, 5}, {POOP_SPELL_FART, 5}, {POOP_SPELL_LIQUID, 3}, + {POOP_SPELL_CORNY, 1}, {POOP_SPELL_BURNING, 1}, {POOP_SPELL_STONE, 1}, + {POOP_SPELL_STINKY, 1}, {POOP_SPELL_BOMB, 1}}; +constexpr SpellWeight POOP_SPELLS_MIDDLE[] = {{POOP_SPELL_CORNY, 1}, {POOP_SPELL_BURNING, 1}, {POOP_SPELL_STONE, 1}, + {POOP_SPELL_STINKY, 1}, {POOP_SPELL_BOMB, 1}}; +constexpr SpellWeight POOP_SPELLS_RARE[] = {{POOP_SPELL_BLACK, 1}, {POOP_SPELL_HOLY, 1}, {POOP_SPELL_DIARRHEA, 1}}; + +// A picker over one stretch's weights. +template static WeightedOutcomePicker spell_picker_make(const SpellWeight (&weights)[N]) +{ + WeightedOutcomePicker picker; + for (const SpellWeight& entry : weights) picker.AddOutcomeWeight(entry.spell, entry.weight); + return picker; +} + +// Fills a new bag of twenty spells and shuffles it. +static void poop_spell_bag_fill(Entity_Player& player, RNG& rng) +{ + WeightedOutcomePicker common = spell_picker_make(POOP_SPELLS_COMMON); + WeightedOutcomePicker middle = spell_picker_make(POOP_SPELLS_MIDDLE); + WeightedOutcomePicker rare = spell_picker_make(POOP_SPELLS_RARE); + auto& bag = player.poopSpellBag; + int& count = player.poopSpellBagCount; + + for (PoopSpell spell : POOP_SPELL_BAG_START) bag[count++] = spell; + while (count < POOP_SPELL_BAG_SIZE) + { + WeightedOutcomePicker& picker = count < POOP_SPELL_RARE_END ? rare + : count < POOP_SPELL_MIDDLE_END ? middle + : common; + bag[count++] = (char)picker.PickOutcome(rng_make(rng.Next(), POOP_SPELL_PICK_SHIFT)); + } + for (int i = 0; i < POOP_SPELL_BAG_SIZE - 1; i++) + std::swap(bag[i], bag[i + (int)(rng.Next() % (uint32_t)(POOP_SPELL_BAG_SIZE - i))]); +} + +// 007d6670 Fills Tainted ???'s empty queue slots from the bag, filling a new bag when it runs out. +void Entity_Player::poop_spell_roll() +{ + RNG& rng = GetCollectibleRNG(COLLECTIBLE_NO_2); + for (char& slot : poopSpellQueue) + { + if (slot != POOP_SPELL_NONE) continue; + if (poopSpellBagCount == 0) poop_spell_bag_fill(*this, rng); + slot = poopSpellBag[--poopSpellBagCount]; + } +} + +// Takes the next spell off the queue, moving the rest up and refilling the end. +static int poop_spell_take(Entity_Player& player) +{ + auto& queue = player.poopSpellQueue; + int spell = queue[0]; + std::shift_left(queue.begin(), queue.end(), 1); + queue.back() = POOP_SPELL_NONE; + player.poop_spell_roll(); + return spell; +} + +// Part of 00780f40: the bomb action casts Tainted ???'s next spell while he has poop to spend. +void poop_spell_cast(Entity_Player& player) +{ + player.UsePoopSpell(poop_spell_take(player)); + player.AddPoopMana(-1); +} + +// The lifted pile or bomb's sound, under the fart override. +static void poop_hold_sound_play() +{ + int sound = SOUND_POOPITEM_HOLD; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); +} + +// 007d7290 Casts a poop spell: a poop pile lifted overhead (from No. 2's generator), liquid poop creep, a fart cloud +// that pushes enemies away, a butt bomb lifted overhead with the player's bomb effects, or explosive diarrhea. +void Entity_Player::UsePoopSpell(uint32_t spell) +{ + if (spell < POOP_SPELL_COUNT && POOP_SPELL_PILES[spell] > 0) + { + uint32_t seed = GetCollectibleRNG(COLLECTIBLE_NO_2).Next(); + Entity* pile = g_game->Spawn({pos, {}, this, 0, ENTITY_POOP, POOP_SPELL_PILES[spell], seed}); + pile->Update(); + if (const AnimationData* data = pile->sprite.animState.animData) pile->sprite.animState.AdvancePosition(data->length - 1); + TryHoldEntity(pile); + return poop_hold_sound_play(); + } + + switch (spell) + { + case POOP_SPELL_LIQUID: + { + npc_sound_play(SOUND_FART, 1, 2, 1); + npc_sound_play(SOUND_SINK_DRAIN_GURGLE, 1, 2, LIQUID_GURGLE_PITCH); + auto* creep = static_cast(g_game->Spawn( + {pos, {}, this, LIQUID_CREEP_SUBTYPE, ENTITY_EFFECT, EFFECT_CREEP_LIQUID_POOP, Random()})); + creep->timeout = LIQUID_CREEP_FRAMES; + creep->lifespan = LIQUID_CREEP_FRAMES; + creep->parent = this; + return creep->Update(); + } + case POOP_SPELL_FART: + { + game_fart({.position = pos, .source = this, .radius = SPELL_FART_RADIUS}); + game_butter_bean_fart({.position = pos, .source = this, .radius = SPELL_BEAN_RADIUS, .isShowEffect = false}); + auto* cloud = static_cast( + g_game->Spawn({pos, {}, this, SPELL_CLOUD_SUBTYPE, ENTITY_EFFECT, EFFECT_SMOKE_CLOUD, Random()})); + cloud->timeout = -1; + cloud->lifespan = -1; + return cloud->Update(); + } + case POOP_SPELL_BOMB: + { + TearFlags bombFlags = GetBombFlags(false); + auto* bomb = static_cast(g_game->Spawn( + {pos, vector_scale(velocity, SPELL_BOMB_PUSH), this, 0, ENTITY_BOMB, BOMB_BUTT, Random()})); + bomb->tearFlags = bombFlags; + bomb->isLoadCostumes = true; + TryHoldEntity(bomb); + return poop_hold_sound_play(); + } + case POOP_SPELL_DIARRHEA: + npc_sound_play(SOUND_FART, 1, 2, 1); + { + temporaryEffects.RemoveNullEffect(NULLITEM_EXPLOSIVE_DIARRHEA, -1); + TemporaryEffect diarrhea(g_manager->itemConfig.GetNullItem(NULLITEM_EXPLOSIVE_DIARRHEA)); + diarrhea.cooldown = DIARRHEA_FRAMES; + temporaryEffects.AddEffect(diarrhea, true, 1); + AnimateSad(); + return ShootCandle({}); + } + default: return; + } +} + +// Hold (part of 005b39d0): a stored spell is cast, else Tainted ??? spends a poop to store his next spell in the slot. +// A use with its own data casts that spell. +void hold_use(ItemUse& use) +{ + Entity_Player& player = use.player; + int slot = use.request.slot; + auto animate = [&] { if (use.isShowAnimation) player.AnimateCollectible(use.id, "UseItem", "PlayerPickupSparkle"); }; + + if (use.request.flags & USE_CUSTOMVARDATA) + { + if (use.request.varData <= 0) return; + animate(); + return player.UsePoopSpell(use.request.varData); + } + if (!(use.request.flags & USE_OWNED) || slot < 0) return; + + int stored = player.activeItems[slot].varData; + if (stored > 0) + { + animate(); + player.UsePoopSpell(stored); + return player.SetActiveVarData(0, slot); + } + if (player.playerType != PLAYER_BLUEBABY_B || player.poopMana <= 0) return; + + player.AddPoopMana(-1); + animate(); + player.SetActiveVarData(poop_spell_take(player), slot); + int sound = SOUND_POOPITEM_STORE; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); +} + +// Tainted ???'s part of 00794e50: out of a versus match, the damage enemies took this frame charges poop pickups, one +// for each whole point, with a purple fart. +void blue_baby_poop_update(Entity_Player& player) +{ + if (player.playerType != PLAYER_BLUEBABY_B) return; + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::update_effects 00794e50 (the versus damage dealt)"); + float dealt = g_game->room->entityList.enemyDamageInflicted; + if (dealt <= 0) return; + + player.poopSpellCharge += damage_charge_scale() * dealt * POOP_CHARGE_PER_DAMAGE; + if (player.poopSpellCharge < 1) return; + + int poops = (int)player.poopSpellCharge; + player.poopSpellCharge -= (float)poops; + for (int i = 0; i < poops; i++) + { + uint32_t seed = Random(); + Vector velocity = Entity_Pickup::GetRandomPickupVelocity(player.pos, nullptr, 0); + g_game->Spawn({player.pos, velocity, nullptr, 0, ENTITY_PICKUP, PICKUP_POOP, seed})->Update(); + } + Entity* fart = g_game->Spawn( + {.position = player.pos, .subType = POOP_FART_SUBTYPE, .type = ENTITY_EFFECT, .variant = EFFECT_FART, .seed = Random()}); + fart->SetColor(POOP_FART_COLOR, -1, 255, false, true); + fart->sprite.scale = vector_make(POOP_FART_SCALE, POOP_FART_SCALE); + npc_sound_play(SOUND_FART, POOP_FART_VOLUME, 2, random_unit() * POOP_FART_PITCH_SPREAD + POOP_FART_PITCH); +} + +// 0084a3e0 Draws Tainted ???'s spell queue from the last slot: the next spell big in the first box, the five after it +// small, each lit while the poop covers it and faint otherwise. +void PlayerHUD::RenderSpellQueue(Vector at, float queueScale) +{ + ANM2& spells = hud->poopSpellsSprite; + float inset = queueScale * SPELL_SLOT_INSET; + spells.scale = vector_make(queueScale, queueScale); + + for (int slot = POOP_SPELL_QUEUE_SIZE - 1; slot >= 0; slot--) + { + spells.color._tint[3] = slot < player->poopMana ? 1 : SPELL_SLOT_FAINT; + if (spells.SetAnimation(slot == 0 ? "Idle" : "IdleSmall", SWITCH_RESET) && spells.animState.animData) + { + spells.animState.SetFrameFloat((float)(unsigned char)player->poopSpellQueue[slot]); + spells.animState.isPlaying = false; + } + spells.Render({vector_make((float)slot * SPELL_SLOT_STEP * queueScale + at.x + inset, at.y + inset)}); + } +} diff --git a/src/entity_player_reroll.cpp b/src/entity_player_reroll.cpp new file mode 100644 index 0000000..66e3acc --- /dev/null +++ b/src/entity_player_reroll.cpp @@ -0,0 +1,286 @@ +#include "entity_player_characters.h" +#include "challenge_params.h" +#include "game.h" +#include "hud.h" +#include "item_pool.h" +#include "manager.h" +#include "player_manager.h" +#include +#include +#include + +constexpr int REROLL_TRIES = 10; +constexpr int REROLL_FALLBACK = 25; +constexpr int REROLL_SLOTS_KEPT = 2; +constexpr int FORM_COSTUME_COUNT = 3; +constexpr uint32_t REROLL_ACTIVE_FLAGS = 0xc; +constexpr uint32_t REROLL_PASSIVE_FLAGS = 6; +constexpr uint32_t CACHE_EVERYTHING = 0xffff; +constexpr int EDEN_SEED_SHIFT = 0x3e; +constexpr float EDEN_DAMAGE_SPREAD = 2; +constexpr float EDEN_SPEED_SPREAD = 0.3f; +constexpr float EDEN_FIRE_DELAY_SPREAD = 1.5f; +constexpr float EDEN_RANGE_SPREAD = 120; +constexpr float EDEN_SHOT_SPEED_SPREAD = 0.5f; +constexpr float EDEN_LUCK_SPREAD = 2; + +// An item a character starts with, which a reroll keeps. +struct StartingItem +{ + int playerType; + int collectible; +}; + +// 007ce2a0's switch. +constexpr StartingItem REROLL_KEPT_STARTS[] = { + {PLAYER_CAIN, COLLECTIBLE_LUCKY_FOOT}, {PLAYER_EVE, COLLECTIBLE_DEAD_BIRD}, + {PLAYER_EVE, COLLECTIBLE_WHORE_OF_BABYLON}, {PLAYER_SAMSON, COLLECTIBLE_BLOODY_LUST}, + {PLAYER_LAZARUS, COLLECTIBLE_ANEMIC}, {PLAYER_THELOST, COLLECTIBLE_HOLY_MANTLE}, + {PLAYER_LILITH, COLLECTIBLE_INCUBUS}, {PLAYER_LILITH, COLLECTIBLE_CAMBION_CONCEPTION}, + {PLAYER_BETHANY, COLLECTIBLE_BOOK_OF_VIRTUES}}; + +// What the first half of a reroll took: the items whose last copy went, the active entry to redraw, the charge share +// it held, the maximum hearts lost and how many items went. +struct RerollTaken +{ + std::vector emptied; + HistoryItem* activeEntry = nullptr; + float activeChargeRatio = 0; + int maxHeartsDelta = 0; + int count = 0; +}; + +// 007ce2a0 Whether a reroll may take a collectible: never Missing No., the passive Damocles, quest items or the +// challenge's own, nor (unless asked about blindly) the item the character starts with. +bool Entity_Player::CanRerollCollectible(int id, bool isUnknown) +{ + if (id == COLLECTIBLE_MISSING_NO || id == COLLECTIBLE_PASSIVE_DAMOCLES || ItemConfig::IsQuestItem(id)) return false; + if (g_game->challenge != 0) + { + std::vector& kept = g_manager->GetChallengeParams(g_game->challenge).collectibleList; + if (std::ranges::find(kept, id) != kept.end()) return false; + } + if (isUnknown) return true; + + for (const StartingItem& start : REROLL_KEPT_STARTS) + if (start.playerType == playerType && start.collectible == id) return false; + return true; +} + +// Whether a collectible counts towards a transformation. +static bool is_form_item(int form, ItemConfig_Item& item) +{ + auto& forms = g_manager->itemConfig.playerForms; + ItemConfig_PlayerForm* config = form < (int)forms.size() ? forms[form].get() : nullptr; + return config && config->tags != 0 && item.HasTags(config->tags); +} + +// The slot an active collectible sits in, or -1. +static int active_slot_find(Entity_Player& player, int id) +{ + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + if (player.activeItems[slot].item == id) return slot; + return -1; +} + +// The first half of a reroll: each rerollable collectible of the history (an active only from the first two slots, +// and only when asked) is removed and marked for a new draw with its maximum hearts and transformation counts. A kept +// item dresses its costume again. +static RerollTaken reroll_take(Entity_Player& player, bool isIncludeActives) +{ + RerollTaken taken; + + for (HistoryItem& entry : player.history.historyItems) + { + if (entry.isTrinket || player.collectibleCounts[entry.id] <= 0) continue; + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(entry.id); + int slot = item->type == ITEM_ACTIVE ? active_slot_find(player, item->id) : -1; + bool isKept = (slot >= 0 && (!isIncludeActives || slot >= REROLL_SLOTS_KEPT)) || + !player.CanRerollCollectible(entry.id, false) || entry.time < 0 || + (entry.id == COLLECTIBLE_BOOK_OF_VIRTUES && !isIncludeActives) || + (player.playerType == PLAYER_EDEN_B && entry.time <= player.edenBirthrightFrame); + if (isKept) + { + if (item->isAddCostumeOnPickup) player.AddCostume(item, false); + continue; + } + + if (slot >= 0) + { + taken.activeChargeRatio = + item->maxCharges < 1 ? 1 : (float)player.activeItems[slot].charge / (float)item->maxCharges; + player.activeItems[slot].item = 0; + } + player.collectibleCounts[entry.id]--; + taken.maxHeartsDelta -= item->addMaxHearts; + player.TriggerCollectibleRemoved(entry.id); + if (player.collectibleCounts[entry.id] < 1) + { + player.collectibleCounts[entry.id] = 0; + for (int form = 0; form < PLAYER_FORM_SLOTS; form++) + if (is_form_item(form, *item)) player.IncrementPlayerFormCounter(form, -1); + taken.emptied.push_back(entry.id); + } + taken.count++; + entry.id = 0; + if (item->type == ITEM_ACTIVE) taken.activeEntry = &entry; + } + return taken; +} + +// The maximum hearts a reroll settles: lost ones come off the items' unrealised hearts first, then off each player of +// the pair. One left without red hearts keeps a heart (a coin heart or Bethany's red one, the others a soul heart). +static void reroll_hearts_settle(Entity_Player& player, int delta) +{ + if (delta > 0) return player.AddMaxHearts(delta, false); + + for (Entity_Player* part = &player; part && delta < 0; part = part->subPlayer) + { + int used = std::min(-delta, std::max(part->itemHeartsOverflow, 0)); + delta += used; + part->itemHeartsOverflow -= used; + } + for (Entity_Player* part = &player; part && delta < 0; part = part->subPlayer) + { + if (part->maxHearts <= 0) continue; + + int lost = std::min(-delta, part->maxHearts); + part->AddMaxHearts(-lost, false); + delta += lost; + if (part->redHearts >= 1) continue; + if (part->GetHealthType() == HEALTH_COIN || part->playerType == PLAYER_BETHANY) + { + part->AddMaxHearts(2, false); + part->AddHearts(2, true, false); + } + else if (part->soulHearts < 1) part->AddSoulHearts(2, false); + } +} + +// 005c88a0 Rerolls the player's collectibles (the D4's and Tainted Eden's hit): the temporary effects, costumes and +// stat modifiers go, every rerollable item is replaced by a draw from the pool it came from (an active keeping its +// charge's share), Missing No. nudges the modifiers, and the maximum hearts and transformations follow. Returns how +// many items went. The original copies Holy Mantle's effect aside first but never puts it back. +int Entity_Player::reroll_collectibles_on_damage(RNG*, bool isIncludeActives) +{ + temporaryEffects.ClearEffects(false); + ClearCostumes(); + update_player_skin(); + for (int* modifier : + {&speedModifier, &fireDelayModifier, &damageModifier, &tearRangeModifier, &shotSpeedModifier, &luckModifier}) + *modifier = 0; + ResetItemState(); + + RerollTaken taken = reroll_take(*this, isIncludeActives); + if (HasCollectible(COLLECTIBLE_MISSING_NO)) + for (int* modifier : + {&speedModifier, &fireDelayModifier, &damageModifier, &tearRangeModifier, &shotSpeedModifier, &luckModifier}) + *modifier += (int)(Random() % 3) - 1; + + ItemConfig& items = g_manager->itemConfig; + for (int form = 0; form < PLAYER_FORM_SLOTS; form++) + { + ItemConfig_PlayerForm* config = form < (int)items.playerForms.size() ? items.playerForms[form].get() : nullptr; + if (!hasCurseMistEffect && !isCoopGhost && playerForms[form] >= FORM_COSTUME_COUNT && config && + config->costume != -1) + AddCostume(items.GetNullItem(config->costume), false); + } + for (int id : taken.emptied) g_game->itemPool.ResetCollectible(id); + + RNG& d4 = GetCollectibleRNG(COLLECTIBLE_D4); + std::vector formCounts(items.playerForms.size()); + history.isLocked = true; + for (HistoryItem& entry : history.historyItems) + { + if (entry.isTrinket || entry.id != 0) continue; + + for (int i = 0; i < REROLL_TRIES && entry.id == 0; i++) + { + bool isActive = &entry == taken.activeEntry; + entry.id = g_game->itemPool.GetCollectible((ItemPoolType)entry.itemPoolType, d4.Next(), + isActive ? REROLL_ACTIVE_FLAGS : REROLL_PASSIVE_FLAGS, 0, 0); + if (isActive) taken.activeEntry = nullptr; + if (playerType == PLAYER_EDEN_B && entry.id == COLLECTIBLE_BIRTHRIGHT) entry.id = 0; + } + if (entry.id == 0) entry.id = REROLL_FALLBACK; + + ItemConfig_Item* item = items.GetCollectible(entry.id); + int charge = item->type == ITEM_ACTIVE ? (int)std::ceil((float)item->maxCharges * taken.activeChargeRatio) : 0; + AddCollectible(entry.id, charge, false, ACTIVE_SLOT_PRIMARY, 0); + for (int form = 0; form < (int)formCounts.size(); form++) + if (is_form_item(form, *item)) formCounts[form]++; + taken.maxHeartsDelta += item->addMaxHearts; + } + history.isLocked = false; + + reroll_hearts_settle(*this, taken.maxHeartsDelta); + for (int form = 0; form < (int)formCounts.size(); form++) + if (formCounts[form] > 0) IncrementPlayerFormCounter(form, formCounts[form]); + cacheFlags |= CACHE_EVERYTHING; + EvaluateItems(); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + return taken.count; +} + +// Eden's and Tainted Eden's stat offsets, rolled in order: damage, speed, fire delay, range, shot speed and luck +// (part of 007bc740 and 007729d0). +void eden_offsets_roll(Entity_Player& player, RNG& rng) +{ + player.edenDamage = rng.RandomFloat() * EDEN_DAMAGE_SPREAD - EDEN_DAMAGE_SPREAD / 2; + player.edenSpeed = rng.RandomFloat() * EDEN_SPEED_SPREAD - EDEN_SPEED_SPREAD / 2; + player.edenFireDelay = rng.RandomFloat() * EDEN_FIRE_DELAY_SPREAD - EDEN_FIRE_DELAY_SPREAD / 2; + player.edenTearRange = rng.RandomFloat() * EDEN_RANGE_SPREAD - EDEN_RANGE_SPREAD / 2; + player.edenShotSpeed = rng.RandomFloat() * EDEN_SHOT_SPEED_SPREAD - EDEN_SHOT_SPEED_SPREAD / 2; + player.edenLuck = rng.RandomFloat() * EDEN_LUCK_SPREAD - EDEN_LUCK_SPREAD / 2; +} + +// Part of 007729d0: a penalised hit glitches Tainted Eden. New stat offsets from Missing No.'s generator, a new seed, +// every collectible rerolled, every trinket swapped for a fresh one and every card or pill for a new card or pill +// (Starter Deck and Little Baggy deciding which, both or neither giving even odds). +void tainted_eden_glitch(Entity_Player& player) +{ + sound_play(SOUND_EDEN_GLITCH); + RNG& rng = player.GetCollectibleRNG(COLLECTIBLE_MISSING_NO); + eden_offsets_roll(player, rng); + player.initSeed = rng_make(player.initSeed, EDEN_SEED_SHIFT).Next(); + player.reroll_collectibles_on_damage(&rng, true); + + int trinketsTaken = 0; + for (int slot = player.GetMaxTrinkets() - 1; slot >= 0; slot--) + { + int trinket = (int)player.trinkets[slot]; + if (trinket == 0) continue; + + player.TriggerTrinketRemoved(trinket); + player.trinkets[slot] = 0; + player.TryRemoveTrinketCostume(trinket); + trinketsTaken++; + } + for (int i = 0; i < trinketsTaken; i++) player.AddTrinket((int)g_game->itemPool.GetTrinket(TRINKET_DRAW_TAKE), false); + + int pocketsTaken = 0; + for (int slot = (int)player.GetMaxPocketItems() - 1; slot >= 0; slot--) + { + PocketItem& pocket = player.pocketItems[slot]; + if (pocket.id == 0 || pocket.type == POCKET_ACTIVE) continue; + + player.RemovePocketItem(slot); + pocketsTaken++; + } + + PlayerManager& players = g_game->playerManager; + bool isCardsOnly = players.AnyoneHasCollectible(COLLECTIBLE_STARTER_DECK); + bool isPillsOnly = players.AnyoneHasCollectible(COLLECTIBLE_LITTLE_BAGGY); + if (isCardsOnly && isPillsOnly) + { + isCardsOnly = false; + isPillsOnly = false; + } + for (int i = 0; i < pocketsTaken; i++) + { + if (!isCardsOnly && (isPillsOnly || rng.RandomInt(2) != 0)) player.AddPill(ItemPool::GetPill(rng.Next())); + else player.AddCard(ItemPool::GetCard(rng.Next(), true, true, false)); + } + player.PlayExtraAnimation("Glitch"); +} diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp index fe4c8f5..6e84073 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -1,4 +1,5 @@ #include "entity_player.h" +#include "entity_player_passives.h" #include "boss_ai.h" #include "entity_familiar.h" #include "room_grid.h" @@ -10,15 +11,12 @@ #include constexpr int TRINKET_DOOR_STOP = 124; -constexpr int TRINKET_LIL_CLOT = 176; -constexpr int TRINKET_THE_TWINS = 183; constexpr int COLLECTIBLE_BROKEN_WATCH = 337; constexpr int COLLECTIBLE_DOG_TOOTH = 445; constexpr int COLLECTIBLE_BELIAL_PARTNER = 474; constexpr int COLLECTIBLE_BELIAL_EFFECT = 214; constexpr int COLLECTIBLE_POKE_GO = 505; constexpr int COLLECTIBLE_MERCURIUS = 590; -constexpr int COLLECTIBLE_SATURNUS = 595; constexpr int NULL_ITEM_BELIAL = 123; constexpr int NULL_ITEM_FORGOTTEN_CHALLENGE = 106; constexpr int BELIAL_NULL_COUNT = 4; @@ -45,7 +43,6 @@ constexpr float DOOR_STOP_REACH_SQUARED = 10000; constexpr float DOOR_ENTER_OFFSET = 40; constexpr uint32_t DOOR_SIDES = 4; constexpr int ROCK_STATE_BROKEN = 2; -constexpr ColorMod TOXIC_SHOCK_COLOR = {{1, 1, 1, 1}, {0, 1, 0, 1}, {0, 0, 0}}; // The grid entities Dog Tooth howls at when the floor's crawlspace rock hides there. constexpr GridEntityType DOG_TOOTH_ROCKS[] = {GRID_ROCK, GRID_ROCKT, GRID_ROCK_BOMB, @@ -171,6 +168,10 @@ static void dog_tooth_apply(Entity_Player& player) delayed_sound_queue(player, SOUND_DOG_TOOTH_ROCK, DOG_TOOTH_ROCK_DELAY); } +// Broken Watch acts on every fourth new room: it slows the room, one time in ten it speeds it up. +constexpr int BROKEN_WATCH_PERIOD = 4; +constexpr uint32_t BROKEN_WATCH_FAST_ODDS = 10; + // What the player's items do on entering a room after it is placed: Toxic Shock's clouds, Poke Go's charmed enemy, // Dog Tooth's sounds, the locusts, a co-op baby's shield, the Broken Watch, the weapons' new room reset and the // poop under the player. @@ -195,8 +196,15 @@ static void room_items_apply(Entity_Player& player) if (player.babySkin == BABY_SKIN_WITH_FOLLOWER) reconstruction_missing("Entity_Player::room_enter 007a6c50: the co-op baby's follower effect 1000.114"); } - else if (player.variant == PLAYER_VARIANT_PLAYER && room.isFirstVisit && player.HasCollectible(COLLECTIBLE_BROKEN_WATCH)) - reconstruction_missing("Entity_Player::room_enter 007a6c50: the Broken Watch's rooms counter (Entity_Player +0x1820)"); + else if (player.variant == PLAYER_VARIANT_PLAYER && room.isFirstVisit) + { + player.firstVisitRooms++; + if (player.HasCollectible(COLLECTIBLE_BROKEN_WATCH) && player.firstVisitRooms % BROKEN_WATCH_PERIOD == 0) + { + room.brokenWatchState = Random() % BROKEN_WATCH_FAST_ODDS != 0 ? BROKEN_WATCH_SLOW : BROKEN_WATCH_FAST; + g_manager->musicManager.targetPitch = room.time_scale_update(); + } + } Entity* parent = player.parent.get(); if (player.variant == PLAYER_VARIANT_COOP_BABY && parent && diff --git a/src/entity_player_tears.cpp b/src/entity_player_tears.cpp index a2187b9..e59b1f0 100644 --- a/src/entity_player_tears.cpp +++ b/src/entity_player_tears.cpp @@ -138,7 +138,6 @@ constexpr int COLLECTIBLE_GODS_FLESH = 398; constexpr int COLLECTIBLE_MAW_OF_THE_VOID = 399; constexpr int COLLECTIBLE_EXPLOSIVO = 401; constexpr int COLLECTIBLE_FRUIT_CAKE = 418; -constexpr int COLLECTIBLE_VARICOSE_VEINS = 452; constexpr int COLLECTIBLE_COMPOUND_FRACTURE = 453; constexpr int COLLECTIBLE_SINUS_INFECTION = 459; constexpr int COLLECTIBLE_PARASITOID = 461; @@ -157,7 +156,6 @@ constexpr int COLLECTIBLE_KNOCKOUT_DROPS = 637; constexpr int COLLECTIBLE_TROPICAMIDE = 659; constexpr int TRINKET_PINKY_EYE = 30; constexpr int TRINKET_PUSH_PIN = 31; -constexpr int TRINKET_RED_PATCH = 40; constexpr int TRINKET_BLISTER = 77; constexpr int TRINKET_BLACK_TOOTH = 95; constexpr int TRINKET_NOSE_GOBLIN = 98; @@ -166,7 +164,6 @@ constexpr int TRINKET_JAW_BREAKER = 129; constexpr int TRINKET_CHEWED_PEN = 130; constexpr int TRINKET_BRAIN_WORM = 144; constexpr int NULLITEM_BLOOD_OATH = 54; -constexpr int NULLITEM_IT_HURTS = 57; constexpr int NULLITEM_JUDAS_BIRTHRIGHT = 123; constexpr int NULLITEM_JUDAS_BIRTHRIGHT_TIMED = 124; constexpr int NULLITEM_JUDAS_BIRTHRIGHT_PERMANENT = 130; diff --git a/src/entity_player_trinkets.cpp b/src/entity_player_trinkets.cpp new file mode 100644 index 0000000..d98f7bd --- /dev/null +++ b/src/entity_player_trinkets.cpp @@ -0,0 +1,1043 @@ +#include "entity_player_trinkets.h" +#include "active_items.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity.h" +#include "grid_entity_poop.h" +#include "hud.h" +#include "item_config.h" +#include "item_pickup.h" +#include "item_pool.h" +#include "level.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "room.h" +#include "room_config.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include + +// The trinkets' constants: Rosary Bead's Bible chance, the battery trinkets' achievement, Wooden Cross's mantles +// counted in the high half of the mantle stacks, Mother's Kiss's hearts and Lil Clot's clots. +constexpr int ROSARY_BIBLE_CHANCE = 5; +constexpr int BATTERY_ITEMS_FOR_UNLOCK = 2; +constexpr int ACHIEVEMENT_BATTERY_PACK = 367; +constexpr int WOODEN_CROSS_MANTLES_MAX = 2; +constexpr int MANTLE_STACK_LOW = 0xf; +constexpr int MANTLE_STACK_HIGH_SHIFT = 4; +constexpr int MOTHERS_KISS_HEARTS = 2; +constexpr int MOMS_TOENAIL_STOMPS_MAX = 3; +constexpr int CLOT_SUBTYPE = 7; +constexpr float CLOT_LAUNCH_SPEED = 2; +constexpr float CLOT_POOF_RISE = -6; +constexpr float CLOT_POOF_DEPTH = 10; +constexpr int PICKUP_COLLISION_COOLDOWN = 4; +constexpr int ROOM_TRINKET_ODDS = 4; +constexpr float GAIN_PICKUP_STEP = 40; +constexpr int BRITTLE_BONES_HEARTS = 6; +constexpr int BOOSTER_PACK_CARDS = 5; +constexpr int BOOSTER_SPECIAL_FIRST = 15; +constexpr int BOOSTER_SPECIAL = 25; +constexpr int BOOSTER_SUIT_FIRST = 1; +constexpr int BOOSTER_SUIT = 5; + +// Whether a trinket stays in its slot when a new one is picked up: the Tick, and Rainbow Worm in Pride Day. +static bool is_trinket_stuck(uint32_t trinket) +{ + return trinket == TRINKET_TICK || (trinket == TRINKET_RAINBOW_WORM && g_game->challenge == CHALLENGE_PRIDE_DAY); +} + +// 007716c0 Whether a trinket burns the Tick away when picked up: Match Stick and Lighter. +static bool is_tick_burner(int trinketId) +{ + int id = trinketId & TRINKET_ID_MASK; + return id == TRINKET_MATCH_STICK || id == TRINKET_LIGHTER; +} + +// The Holy Mantles Wooden Cross lends a player: one per copy up to two, less those the player's own mantles cover. +static int wooden_cross_mantles_kept(Entity_Player& player) +{ + int crosses = std::min(player.GetTrinketMultiplier(TRINKET_WOODEN_CROSS), WOODEN_CROSS_MANTLES_MAX); + return std::max(crosses - (player.holyMantleStacks & MANTLE_STACK_LOW), 0); +} + +// 007db0a0 Wooden Cross lends a Holy Mantle effect, counted in the high half of the mantle stacks. +void wooden_cross_mantle_add(Entity_Player& player) +{ + if (wooden_cross_mantles_kept(player) == 0) return; + + if (ItemConfig_Item* mantle = g_manager->itemConfig.GetCollectible(COLLECTIBLE_HOLY_MANTLE)) + player.temporaryEffects.AddEffect(TemporaryEffect(mantle), true, 1); + uint8_t stacks = player.holyMantleStacks; + player.holyMantleStacks = (uint8_t)(((stacks & ~MANTLE_STACK_LOW) + (1 << MANTLE_STACK_HIGH_SHIFT)) | + (stacks & MANTLE_STACK_LOW)); +} + +// 007db160 Takes back the Holy Mantle effects Wooden Cross lent beyond what the trinkets left still lend. The costume +// goes with each one unless a mantle effect is still on. +void Entity_Player::remove_wooden_cross_mantles() +{ + ItemConfig_Item* mantle = g_manager->itemConfig.GetCollectible(COLLECTIBLE_HOLY_MANTLE); + int kept = wooden_cross_mantles_kept(*this); + int lent = holyMantleStacks >> MANTLE_STACK_HIGH_SHIFT; + + for (; lent > kept; lent--) + { + if (mantle) temporaryEffects.RemoveEffect(mantle, 1); + if (!temporaryEffects.isDisabled && temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_HOLY_MANTLE) > 0) + continue; + RemoveCostume(mantle); + } + holyMantleStacks = (uint8_t)((holyMantleStacks & MANTLE_STACK_LOW) | (lent << MANTLE_STACK_HIGH_SHIFT)); +} + +// 00771620 Whether the player holds the trinket golden, in a slot or smelted. +// The original also reads a trinket slot only the constructor writes, always empty. +bool Entity_Player::HasGoldenTrinket(uint32_t trinketId) +{ + for (int i = 0; i < GetMaxTrinkets(); i++) + if ((trinkets[i] & TRINKET_ID_MASK) == trinketId && (trinkets[i] & TRINKET_GOLDEN_FLAG)) return true; + return trinketId < smeltedTrinkets.size() && smeltedTrinkets[trinketId].goldenCount > 0; +} + +// 007716f0 Whether the player can take a trinket: a free slot, or one holding a trinket that may be swapped out. The +// Tick (and Rainbow Worm in Pride Day) stay unless the new trinket burns the Tick. +bool Entity_Player::TryHoldTrinket(int trinketId) +{ + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::TryHoldTrinket 007716f0 (the versus mode)"); + + for (int i = 0; i < GetMaxTrinkets(); i++) + { + uint32_t held = trinkets[i]; + bool isBurningTick = (held & TRINKET_ID_MASK) == TRINKET_TICK && is_tick_burner(trinketId); + if (held == 0 || !is_trinket_stuck(held) || isBurningTick) return true; + } + return false; +} + +// 00771800 Drops the first trinket that may go (the Tick only to a trinket that burns it, with a sizzle), the next +// slot moving up: it lands as a pickup at the position for a main player, its pickup effect undone and its costume +// off unless its effect wears it. Butter plays its sound. The stats are evaluated. The dropped pickup, if any. +Entity_Pickup* Entity_Player::DropTrinket(Vector position, bool isReplaceTick) +{ + FlushQueueItem(); + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::DropTrinket 00771800 (the versus mode)"); + + int slot = -1; + for (int i = 0; i < TRINKET_SLOT_COUNT && trinkets[i] != 0; i++) + { + bool isKept = is_trinket_stuck(trinkets[i]) && !((trinkets[i] & TRINKET_ID_MASK) == TRINKET_TICK && isReplaceTick); + if (!isKept) + { + slot = i; + break; + } + } + auto tick = std::ranges::find(trinkets, (uint32_t)TRINKET_TICK); + if (isReplaceTick && tick != trinkets.end()) + { + sound_play(SOUND_TICK_BURN); + slot = (int)(tick - trinkets.begin()); + } + if (slot < 0) + { + if (cacheFlags) EvaluateItems(); + return nullptr; + } + + uint32_t dropped = trinkets[slot]; + uint32_t id = dropped & TRINKET_ID_MASK; + int stomps = id == TRINKET_MOMS_TOENAIL ? std::min(GetTrinketMultiplier(TRINKET_MOMS_TOENAIL), MOMS_TOENAIL_STOMPS_MAX) : 0; + if (slot == 0) trinkets[0] = trinkets[1]; + trinkets[TRINKET_SLOT_COUNT - 1] = 0; + ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(id); + if (trinket) cacheFlags |= trinket->cacheFlags; + + Entity_Pickup* pickup = nullptr; + if (variant == PLAYER_VARIANT_PLAYER) + { + pickup = static_cast(g_game->Spawn({.position = position, .spawner = this, + .subType = (int)dropped, .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, .seed = Random()})); + pickup->collisionCooldown = PICKUP_COLLISION_COOLDOWN; + pickup->isTouched = true; + } + TriggerTrinketRemoved(dropped); + if (trinket) + { + bool isEffectWorn = !trinket->isAddCostumeOnPickup && !temporaryEffects.isDisabled && + std::ranges::any_of(temporaryEffects.effects, [&](const TemporaryEffect& effect) + { return effect.item->type == ITEM_TRINKET && (uint32_t)effect.item->id == dropped; }); + if (!isEffectWorn) RemoveCostume(trinket); + } + if (id == TRINKET_BUTTER) sound_play(SOUND_BUTTER_DROP); + else if (id == TRINKET_MOMS_TOENAIL && !(g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR) && stomps > 0) + reconstruction_missing("Entity_Player::DropTrinket 00771800 (Mom's Toenail's stomps)"); + if (cacheFlags) EvaluateItems(); + return pickup; +} + +// 00771d30 Puts a trinket in the first free slot (two with Mom's Purse or Belly Button), wearing its costume, then +// sets off its pickup effect. Three battery items held unlock an achievement. A helper player drops it at once. +void Entity_Player::AddTrinket(int type, bool isFirstTime) +{ + ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(type & TRINKET_ID_MASK); + if (!trinket) return; + + if (trinket->isAddCostumeOnPickup) AddCostume(trinket, false); + for (int i = 0; i < GetMaxTrinkets(); i++) + { + if (trinkets[i] != 0) continue; + cacheFlags |= trinket->cacheFlags; + trinkets[i] = (uint32_t)type; + break; + } + log_printf(LOG_INFO, "Adding trinket %d (%s) to player %d (%s)\n", type, + trinket->GetLocalizedName(LANGUAGE_CURRENT).c_str(), playerIndex, name.c_str()); + TriggerTrinketAdded((uint32_t)type, isFirstTime); + + if (variant == PLAYER_VARIANT_PLAYER && !isCoopGhost) + { + if (ItemConfig::is_trinket_tagged((uint32_t)type, TAG_BATTERY) && tagged_item_count(TAG_BATTERY) > BATTERY_ITEMS_FOR_UNLOCK) + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_BATTERY_PACK); + InvalidateCoPlayerItems(); + } + HUD& hud = g_game->hud; + if (hud.hudRefreshType != HUD_REFRESH_FULL) + { + hud.hudRefreshType = HUD_REFRESH_PLAYER; + hud.hudRefreshCountdown = 2; + } + if (parent) DropTrinket(pos, true); +} + +// The end of 007ad860 and 007adb30: the stats the trinket touches are evaluated with the next frame. +static void trinket_cache_add(Entity_Player& player, uint32_t id) +{ + ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(id); + if (!trinket || trinket->cacheFlags == 0) return; + player.cacheFlags |= trinket->cacheFlags; + player.temporaryEffects.isEvaluateCachePending = true; +} + +// 007ad860 What picking a trinket up changes at once: the Bible's chance, the transformations it counts for, Duct +// Tape's mode, Wooden Cross's mantles, Mother's Kiss's hearts, Gilded Key's key, Lil Clot's clots and the versus +// trinkets. The trinket's stats are evaluated with the next frame. +void Entity_Player::TriggerTrinketAdded(uint32_t trinketId, bool isFirstTime) +{ + Game& game = *g_game; + if (variant != PLAYER_VARIANT_PLAYER) return; + bool isGolden = trinketId & TRINKET_GOLDEN_FLAG; + uint32_t id = trinketId & TRINKET_ID_MASK; + bool isVersus = game.deathmatchManager.is_active(); + + switch (id) + { + case TRINKET_ROSARY_BEAD: + game.itemPool.pools[POOL_LIBRARY].bibleUpgrade += ROSARY_BIBLE_CHANCE; + game.itemPool.pools[POOL_SHOP].bibleUpgrade += ROSARY_BIBLE_CHANCE; + break; + case TRINKET_MISSING_PAGE: IncrementPlayerFormCounter(PLAYER_FORM_NECROMANCER, 1); break; + case TRINKET_BOBS_BLADDER: IncrementPlayerFormCounter(PLAYER_FORM_BOB, 1); break; + case TRINKET_DUCT_TAPE: + if (GetTrinketMultiplier(TRINKET_DUCT_TAPE) > 1 && ductTapeMode == 0) ductTapeMode = 1; + break; + case TRINKET_WOODEN_CROSS: + wooden_cross_mantle_add(*this); + if (isGolden || HasCollectible(COLLECTIBLE_MOMS_BOX)) wooden_cross_mantle_add(*this); + break; + case TRINKET_BROKEN_SYRINGE: + if (isVersus) add_random_drug_item_effect(); + break; + case TRINKET_DEVILS_CROWN: Level::update_treasure_room_doors_for_trinket(); break; + case TRINKET_MOMS_LOCK: + if (isVersus) AddRandomMomItemEffect(); + break; + case TRINKET_MOTHERS_KISS: + update_greeds_gullet(); + if (isFirstTime) AddHearts(isGolden ? MOTHERS_KISS_HEARTS * 2 : MOTHERS_KISS_HEARTS, false, false); + break; + case TRINKET_MODELING_CLAY: + if (isVersus) ModelingClay_roll(&trinketRNGs[TRINKET_MODELING_CLAY]); + break; + case TRINKET_KIDS_DRAWING: IncrementPlayerFormCounter(PLAYER_FORM_GUPPY, isGolden ? 2 : 1); break; + case TRINKET_LIL_CLOT: spawn_lil_clot_familiars(); break; + case TRINKET_THE_TWINS: + if (isVersus) twins_duplicate_familiars(1); + break; + } + if (isFirstTime && trinketId == TRINKET_GILDED_KEY) AddKeys(1); + trinket_cache_add(*this, id); +} + +// 007adb30 What losing a trinket changes at once, undoing its pickup: the Bible's chance, the transformations, Wooden +// Cross's mantles, Modeling Clay's copied item and the versus trinkets' effects. The stats are evaluated with the next +// frame. +void Entity_Player::TriggerTrinketRemoved(uint32_t trinketId) +{ + Game& game = *g_game; + if (variant != PLAYER_VARIANT_PLAYER) return; + uint32_t id = trinketId & TRINKET_ID_MASK; + bool isVersusLost = game.deathmatchManager.is_active() && !HasTrinket(trinketId); + + switch (id) + { + case TRINKET_ROSARY_BEAD: + game.itemPool.pools[POOL_LIBRARY].bibleUpgrade -= ROSARY_BIBLE_CHANCE; + game.itemPool.pools[POOL_SHOP].bibleUpgrade -= ROSARY_BIBLE_CHANCE; + break; + case TRINKET_MISSING_PAGE: IncrementPlayerFormCounter(PLAYER_FORM_NECROMANCER, -1); break; + case TRINKET_BOBS_BLADDER: IncrementPlayerFormCounter(PLAYER_FORM_BOB, -1); break; + case TRINKET_WOODEN_CROSS: + if (HasTrinket(TRINKET_WOODEN_CROSS)) break; + remove_wooden_cross_mantles(); + if (HasCollectible(COLLECTIBLE_MOMS_BOX)) remove_wooden_cross_mantles(); + break; + case TRINKET_BROKEN_SYRINGE: + case TRINKET_MOMS_LOCK: + case TRINKET_THE_TWINS: + if (isVersusLost) reconstruction_missing("Entity_Player::TriggerTrinketRemoved 007adb30 (the versus trinkets)"); + break; + case TRINKET_DEVILS_CROWN: Level::update_treasure_room_doors_for_trinket(); break; + case TRINKET_MOTHERS_KISS: update_greeds_gullet(); break; + case TRINKET_MODELING_CLAY: + { + if (HasTrinket(trinketId)) break; + int copied = modelingClayEffect; + modelingClayEffect = 0; + if (copied == 0) break; + if (ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(copied)) + { + cacheFlags |= item->cacheFlags; + temporaryEffects.isEvaluateCachePending = true; + } + TryRemoveCollectibleCostume(copied, false); + break; + } + case TRINKET_KIDS_DRAWING: + IncrementPlayerFormCounter(PLAYER_FORM_GUPPY, trinketId & TRINKET_GOLDEN_FLAG ? -2 : -1); + break; + } + trinket_cache_add(*this, id); +} + +// 007ad3a0 Takes a trinket's costume off, unless the trinket wears it only while its effect lasts and that is on. +void Entity_Player::TryRemoveTrinketCostume(int trinketId) +{ + ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(trinketId & TRINKET_ID_MASK); + if (!trinket) return; + if (!trinket->isAddCostumeOnPickup && temporaryEffects.HasTrinketEffect(trinketId)) return; + RemoveCostume(trinket); +} + +// 00772260 Takes back one smelted copy of a trinket, a plain one first unless the id asks for a golden one, with its +// history entry, and its costume once none is left. +bool Entity_Player::TryRemoveSmeltedTrinket(uint32_t trinketId) +{ + if (variant == PLAYER_VARIANT_PLAYER && !isCoopGhost) InvalidateCoPlayerItems(); + uint32_t id = trinketId & TRINKET_ID_MASK; + ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(id); + if (!trinket) + { + log_printf(LOG_WARN, "Tried to remove smelted trinket with invalid trinket type (%d) \n", trinketId); + return false; + } + SmeltedTrinket& smelted = smeltedTrinkets[id]; + + bool isPlain = !(trinketId & TRINKET_GOLDEN_FLAG) && smelted.count > 0; + if (!isPlain && smelted.goldenCount < 1) return false; + uint32_t removed = isPlain ? id : id | TRINKET_GOLDEN_FLAG; + log_printf(LOG_INFO, "Removing smelted trinket %d (%s) from player %d (%s)\n", removed, + trinket->GetLocalizedName(LANGUAGE_CURRENT).c_str(), playerIndex, name.c_str()); + if (isPlain) smelted.count--; + else smelted.goldenCount--; + TriggerTrinketRemoved(removed); + history_item_remove(history, {.time = g_game->frameCount, .isTrinket = true, .id = (int)removed}); + if (smelted.count < 1 && smelted.goldenCount < 1) TryRemoveTrinketCostume((int)id); + return true; +} + +// 00771f60 Takes a trinket away: the queued one, else from its slot (the next slot moving up) with its costume unless +// its effect still wears it, else a smelted copy. A helper player gives back the glitched item standing for it. +bool Entity_Player::TryRemoveTrinket(uint32_t trinketId) +{ + uint32_t id = trinketId & TRINKET_ID_MASK; + ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(id); + if (!trinket) return false; + bool isMain = variant == PLAYER_VARIANT_PLAYER && !isCoopGhost; + if (isMain) InvalidateCoPlayerItems(); + if (queuedItem.item && queuedItem.item == trinket) + { + ClearQueueItem(); + return true; + } + + int slots = GetMaxTrinkets(); + for (int i = 0; i < slots; i++) + { + if (trinkets[i] != trinketId && (trinkets[i] & TRINKET_ID_MASK) != trinketId) continue; + std::shift_left(trinkets.begin() + i, trinkets.begin() + slots, 1); + trinkets[slots - 1] = 0; + log_printf(LOG_INFO, "Removing trinket %d (%s) from player %d (%s)\n", trinketId, + trinket->GetLocalizedName(LANGUAGE_CURRENT).c_str(), playerIndex, name.c_str()); + TriggerTrinketRemoved(trinketId); + bool isEffectWorn = !trinket->isAddCostumeOnPickup && !temporaryEffects.isDisabled && + std::ranges::any_of(temporaryEffects.effects, [&](const TemporaryEffect& effect) + { return effect.item->type == ITEM_TRINKET && (uint32_t)effect.item->id == trinketId; }); + if (!isEffectWorn) RemoveCostume(trinket); + return true; + } + if (isMain) return TryRemoveSmeltedTrinket(trinketId); + if (!proceduralItems.empty()) reconstruction_missing("Entity_Player::TryRemoveTrinket 00771f60 (a glitched item)"); + return false; +} + +// 007d83f0 Lil Clot's clots: one per copy of the trinket, less those already following, each launched in a random +// direction from a poof of blood with a squish. +void Entity_Player::spawn_lil_clot_familiars() +{ + int multiplier = GetTrinketMultiplier(TRINKET_LIL_CLOT); + if (multiplier == 0) return; + + int clots = (int)std::ranges::count_if(g_game->room->entityList.updateEL, [this](Entity* entity) + { + return entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::BLOOD_BABY && + entity->subtype == CLOT_SUBTYPE && static_cast(entity)->player == this; + }); + for (int i = clots; i < multiplier; i++) + { + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector velocity = vector_make(std::cos(angle) * CLOT_LAUNCH_SPEED, std::sin(angle) * CLOT_LAUNCH_SPEED); + Entity* clot = g_game->Spawn({.position = pos, .velocity = velocity, .spawner = this, .subType = CLOT_SUBTYPE, + .type = ENTITY_FAMILIAR, .variant = Entity_Familiar::BLOOD_BABY, .seed = seed}); + clot->ClearEntityFlags(FLAG_APPEAR); + clot->Update(); + sound_play(SOUND_MEAT_JUMPS); + + Entity* poof = g_game->Spawn({.position = pos, .subType = 2, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + poof->SetColor(clot->splatColor, -1, 0xff, false, true); + poof->sprite.offset = vector_make(0, CLOT_POOF_RISE); + poof->renderDepthOffset = CLOT_POOF_DEPTH; + poof->Update(); + } +} + +// The trinket part of 006e8ae0: a player not holding an item up who can take the trinket sees its name, drops the +// trinket it swaps out (or the Tick a Match Stick or Lighter burns), and holds the new one up, golden or not, until it +// is added. Whether it was taken. +bool trinket_collect(Entity_Pickup& pickup, Entity_Player& player) +{ + int id = pickup.subtype; + if (player.IsHoldingItem() || player.parent || !player.TryHoldTrinket(id)) return false; + + ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(id); + if (trinket) item_text_show(g_game->hud, &player, trinket); + int slots = player.GetMaxTrinkets(); + bool isTickHeld = std::ranges::any_of(player.trinkets.begin(), player.trinkets.begin() + slots, + [](uint32_t held) { return (held & TRINKET_ID_MASK) == TRINKET_TICK; }); + bool isTickBurnt = isTickHeld && is_tick_burner(id); + bool isFull = player.trinkets[0] != 0 && (slots < 2 || player.trinkets[1] != 0); + if (isFull || isTickBurnt) player.DropTrinket(player.pos, isTickBurnt); + + uint32_t flags = pickup.isTouched ? QUEUED_TOUCHED : 0; + if (id & TRINKET_GOLDEN_FLAG) flags |= QUEUED_GOLDEN; + player.SetQueuedItem({.item = g_manager->itemConfig.GetTrinket(id), .flags = flags}); + return true; +} + +// The free trinket's end of 006e8ae0: it sparkles over the player's head as they lift it, and the pickup goes. +void trinket_lift(Entity_Pickup& pickup, Entity_Player& player) +{ + pickup.sprite.Play("PlayerPickupSparkle"); + player.AnimatePickup(&pickup.sprite, false, "Pickup"); + pickup.Remove(); + pickup.UpdateLootPreview(); +} + +// Equality's part of 00782af0: a main player keeps the trinket's effect while bombs, coins and keys are equal, the +// tears evaluated whenever it is checked. +void equality_update(Entity_Player& player) +{ + if (player.variant != PLAYER_VARIANT_PLAYER || player.isDead) return; + TemporaryEffects& effects = player.temporaryEffects; + bool isEqual = player.HasTrinket(TRINKET_EQUALITY) && player.numBombs == player.numCoins && + player.numCoins == player.numKeys; + + if (isEqual == effects.HasTrinketEffect(TRINKET_EQUALITY)) return; + if (isEqual) effects.AddTrinketEffect(TRINKET_EQUALITY, true, 1); + else effects.RemoveTrinketEffect(TRINKET_EQUALITY, 1); + player.cacheFlags |= CACHE_FIREDELAY; + player.EvaluateItems(); +} + +// Broken Remote's part of 00782af0: after an active used from the main slot the player teleports (Teleport 2.0's pick +// with more than one copy). Cursed Penny's teleports stop the game. +void trinket_teleports_update(Entity_Player& player) +{ + Game& game = *g_game; + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || game.roomTransition.is_active() || + game.stageTransition.state != STAGE_TRANSITION_NONE) + return; + + if (player.isBrokenRemotePending) + { + int item = player.GetTrinketMultiplier(TRINKET_BROKEN_REMOTE) <= 1 ? COLLECTIBLE_TELEPORT : COLLECTIBLE_TELEPORT_2; + player.UseActiveItem({.item = item, .flags = USE_NOANIM}); + } + else if (player.cursedPennyPending != 0) + reconstruction_missing("Entity_Player::Update 00782af0 (Cursed Penny's teleport)"); + player.isBrokenRemotePending = false; + player.cursedPennyPending = 0; +} + +// The odds a room trinket rolls with: one in four over its multiplier, sure once that rounds to none. +static bool is_room_trinket_rolled(Entity_Player& player, int trinket) +{ + int odds = ROOM_TRINKET_ODDS / player.GetTrinketMultiplier(trinket); + return odds == 0 || Random() % (uint32_t)odds == 0; +} + +// 007dbba0 Broken Syringe lends one of eight drug collectibles' effects for the room. The versus mode remembers which. +void Entity_Player::add_random_drug_item_effect() +{ + constexpr int DRUG_ITEMS[] = {13, 14, 240, 70, 143, 345, 493, 496}; + int id = DRUG_ITEMS[GetTrinketRNG(TRINKET_BROKEN_SYRINGE).Next() & 7]; + + temporaryEffects.AddEffect(TemporaryEffect(g_manager->itemConfig.GetCollectible(id)), true, 1); + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::add_random_drug_item_effect 007dbba0 (the versus mode)"); +} + +// 007dbc80 Mom's Lock lends one of Mom's thirteen collectibles' effects for the room. The versus mode remembers which. +void Entity_Player::AddRandomMomItemEffect() +{ + constexpr int MOM_ITEMS[] = {29, 30, 31, 55, 110, 114, 199, 200, 217, 228, 355, 508, 732}; + int id = MOM_ITEMS[GetTrinketRNG(TRINKET_MOMS_LOCK).Next() % std::size(MOM_ITEMS)]; + + temporaryEffects.AddEffect(TemporaryEffect(g_manager->itemConfig.GetCollectible(id)), true, 1); + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::AddRandomMomItemEffect 007dbc80 (the versus mode)"); +} + +// 007dbe70 Modeling Clay copies only summonable collectibles. +static bool is_clay_copyable(ItemConfig_Item& item) +{ + bool isCollectible = item.type == ITEM_PASSIVE || item.type == ITEM_ACTIVE || item.type == ITEM_FAMILIAR; + return !isCollectible || item.HasTags(TAG_SUMMONABLE); +} + +// 007dbd70 Modeling Clay copies a summonable collectible the room's pool draws for the room, wearing its costume. +void Entity_Player::ModelingClay_roll(RNG* rng) +{ + ItemConfig& items = g_manager->itemConfig; + items.availabilityFilters.push_back(is_clay_copyable); + modelingClayEffect = g_game->itemPool.GetSeededCollectible(rng->Next(), 1, *g_game->room->descriptor); + items.availabilityFilters.pop_back(); + + ItemConfig_Item* copied = items.GetCollectible(modelingClayEffect); + if (!copied) return; + cacheFlags |= copied->cacheFlags; + temporaryEffects.isEvaluateCachePending = true; + if (copied->isAddCostumeOnPickup) AddCostume(copied, false); + g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); +} + +// The first trinket part of 007a8350: Liberty Cap lends a mushroom's effect, Broken Syringe a drug's and Mom's Lock one +// of Mom's items, each one time in four over its multiplier. Redemption watches a devil room's first visit. Modeling +// Clay's copy ends, and it copies anew one time in two over its multiplier on the room's seed. +void trinkets_room_enter(Entity_Player& player) +{ + constexpr int MUSHROOMS[] = {12, 71, 121, 120, 342, 398}; + constexpr RNG CLAY_SHIFTS = {0, 7, 17, 21}; + ItemConfig& items = g_manager->itemConfig; + + if (player.HasTrinket(TRINKET_LIBERTY_CAP) && is_room_trinket_rolled(player, TRINKET_LIBERTY_CAP)) + { + int id = MUSHROOMS[player.GetTrinketRNG(TRINKET_LIBERTY_CAP).Next() % std::size(MUSHROOMS)]; + player.temporaryEffects.AddEffect(TemporaryEffect(items.GetCollectible(id)), true, 1); + } + if (player.HasTrinket(TRINKET_BROKEN_SYRINGE) && is_room_trinket_rolled(player, TRINKET_BROKEN_SYRINGE)) + player.add_random_drug_item_effect(); + if (player.HasTrinket(TRINKET_MOMS_LOCK) && is_room_trinket_rolled(player, TRINKET_MOMS_LOCK)) + player.AddRandomMomItemEffect(); + RoomDescriptor* descriptor = g_game->room->descriptor; + bool isDevilRoom = g_game->room->roomType == ROOM_DEVIL || (descriptor && (descriptor->flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE)); + if (player.HasCollectible(COLLECTIBLE_REDEMPTION) && descriptor && descriptor->visitedCount == 1 && isDevilRoom && + !player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_REDEMPTION)) + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_REDEMPTION, true, 1); + + int copied = player.modelingClayEffect; + player.modelingClayEffect = 0; + if (copied != 0) + { + if (ItemConfig_Item* item = items.GetCollectible(copied)) + { + player.cacheFlags |= item->cacheFlags; + player.temporaryEffects.isEvaluateCachePending = true; + } + player.TryRemoveCollectibleCostume(copied, false); + } + RoomDescriptor* room = g_game->GetRoomByIdx(g_game->currentRoomIdx, -1); + if (player.HasTrinket(TRINKET_MODELING_CLAY) && room->spawnSeed != 0) + { + RNG rng = CLAY_SHIFTS; + rng._seed = room->spawnSeed; + if (rng.RandomInt((uint32_t)(2 / player.GetTrinketMultiplier(TRINKET_MODELING_CLAY))) == 0) + player.ModelingClay_roll(&rng); + } +} + +// Umbilical Cord's part of 007a8350: at one red heart or less (two or three with more copies) the player gets Little +// Steven's effect for the room. +void umbilical_cord_room_enter(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + if (!player.HasTrinket(TRINKET_UMBILICAL_CORD) || effects.HasCollectibleEffect(COLLECTIBLE_LITTLE_STEVEN)) return; + + int hearts = std::min(std::max(player.GetTrinketMultiplier(TRINKET_UMBILICAL_CORD), 1), 3); + if (player.redHearts <= hearts) effects.AddCollectibleEffect(COLLECTIBLE_LITTLE_STEVEN, true, 1); +} + +// Dice Bag's part of 007a8350: on a first visit, one time in two per copy, a single use die lands in the pocket. +void dice_bag_room_enter(Entity_Player& player) +{ + constexpr int DICE[] = {476, 284, 105, 609, 437, 406, 285, 386, 166, 283}; + if (!player.HasTrinket(TRINKET_DICE_BAG) || g_game->room->descriptor->visitedCount != 1) return; + + if ((int)(player.GetTrinketRNG(TRINKET_DICE_BAG).Next() & 1) >= player.GetTrinketMultiplier(TRINKET_DICE_BAG)) return; + // The original draws the die from The Twins' RNG. + int die = DICE[player.GetTrinketRNG(TRINKET_THE_TWINS).Next() % std::size(DICE)]; + player.SetPocketActiveItem(die, ACTIVE_SLOT_POCKET2, true); + player.AnimateCollectible(die, "UseItem", "PlayerPickupSparkle"); + sound_play(SOUND_SHELLGAME); +} + +// A pickup a collectible's first pickup drops on a free spot near the player. +static void gain_pickup_drop(Entity_Player& player, const EntitySpawn& spawn) +{ + EntitySpawn drop = spawn; + drop.position = room_free_pickup_position_find({.position = player.pos, .step = GAIN_PICKUP_STEP}); + drop.type = ENTITY_PICKUP; + g_game->Spawn(drop); +} + +// Divorce Papers' first pickup: a bone heart, and Mysterious Paper from the trinket pool once it is unlocked (or in a +// daily or debug run). +static void divorce_papers_gain(Entity_Player& player, RNG& rng) +{ + constexpr int ACHIEVEMENT_MYSTERIOUS_PAPER = 123; + player.AddBoneHearts(1); + Game& game = *g_game; + bool isAllowed = g_manager->persistentGameData.achievements[ACHIEVEMENT_MYSTERIOUS_PAPER] || + (g_manager->state == MANAGER_STATE_GAME && (game.dailyChallenge._id != 0 || game.isDebug)); + if (!isAllowed || !game.itemPool.RemoveTrinket(TRINKET_MYSTERIOUS_PAPER)) return; + Vector position = room_free_pickup_position_find({.position = player.pos, .step = GAIN_PICKUP_STEP}); + game.Spawn({.position = position, .subType = TRINKET_MYSTERIOUS_PAPER, .type = ENTITY_PICKUP, + .variant = PICKUP_TRINKET, .seed = rng.Next()}); +} + +// Brittle Bones' first pickup: six bone hearts for the red hearts (and the Soul's) it takes, or a tears up for +// a coin or soul health player. +static void brittle_bones_gain(Entity_Player& player) +{ + HealthType health = player.GetHealthType(); + if (health == HEALTH_COIN || health == HEALTH_SOUL) + { + player.brittleBonesUpgrades++; + player.cacheFlags |= CACHE_FIREDELAY; + } + else + { + player.redHearts = 0; + player.maxHearts = 0; + if (Entity_Player* sub = player.subPlayer) + { + sub->redHearts = 0; + sub->maxHearts = 0; + } + } + player.AddBoneHearts(BRITTLE_BONES_HEARTS); +} + +// The second Broken Shovel piece joins the first into Mom's Shovel, keeping the first piece's charge. +static void broken_shovel_gain(Entity_Player& player) +{ + int charge = 0; + for (ActiveItemDesc& active : player.activeItems) + if (active.item == COLLECTIBLE_BROKEN_SHOVEL_1) charge = active.batteryCharge + active.charge; + if (!player.HasCollectible(COLLECTIBLE_BROKEN_SHOVEL_1)) return; + + player.RemoveCollectible(COLLECTIBLE_BROKEN_SHOVEL_1, false, 0, true); + player.RemoveCollectible(COLLECTIBLE_BROKEN_SHOVEL_2, false, 0, true); + player.AddCollectible(COLLECTIBLE_MOMS_SHOVEL, 0, false, 0, 0); + int slot = player.GetActiveItemSlot(COLLECTIBLE_MOMS_SHOVEL); + if (slot >= 0) player.SetActiveCharge(charge, slot); +} + +// Booster Pack's first pickup: five cards, the first with a special card's chance, the others a suit's. +static void booster_pack_gain(Entity_Player& player, RNG& rng) +{ + for (int i = 0; i < BOOSTER_PACK_CARDS; i++) + { + bool isFirst = i == 0; + int card = ItemPool::GetCardEx((int)rng.Next(), isFirst ? BOOSTER_SPECIAL_FIRST : BOOSTER_SPECIAL, 0, + isFirst ? BOOSTER_SUIT_FIRST : BOOSTER_SUIT, false); + Vector position = room_free_pickup_position_find({.position = player.pos, .step = GAIN_PICKUP_STEP}); + auto* pickup = static_cast(g_game->Spawn({.position = position, .subType = card, + .type = ENTITY_PICKUP, .variant = PICKUP_TAROTCARD, + .seed = rng.Next()})); + pickup->dropDelay = i; + } +} + +// False PHD's first pickup: a pill, and every pill colour identified. +static void false_phd_gain(Entity_Player& player, RNG& rng) +{ + gain_pickup_drop(player, {.spawner = &player, .variant = PICKUP_PILL, .seed = rng.Next()}); + for (uint32_t color = 1; color < PILL_COLOR_SLOTS; color++) g_game->itemPool.IdentifyPill(color); +} + +// TMTRAINER's first pickup: the music fades and every enemy (and versus player) still alive burns and freezes for a +// hundred seconds. +static void tmtrainer_gain(Entity_Player& player) +{ + constexpr int TMTRAINER_FRAMES = 6000; + constexpr float MUSIC_FADE = 0.01f; + g_manager->musicManager.Fadeout(MUSIC_FADE); + std::vector entities = g_game->room->entityList.updateEL; + bool isVersus = g_game->deathmatchManager.is_active(); + for (Entity* entity : entities) + { + bool isTarget = (isVersus && entity->type == ENTITY_PLAYER) || entity->IsEnemy(); + if (!isTarget || entity->isDead || entity->type == ENTITY_FIREPLACE || entity->type == ENTITY_PITFALL) + continue; + entity->bossStatusEffectCooldown = 0; + entity->CopyStatusEffects(); + entity->AddBurn(EntityRef(&player), TMTRAINER_FRAMES, 0, false); + entity->AddFreeze(EntityRef(&player), TMTRAINER_FRAMES, false); + } +} + +// Room::is_pre_ascent_mom_room: Mom's boss room on the floor before the Ascent. +static bool is_pre_ascent_mom_room() +{ + constexpr int BOSS_SUBTYPE_MOM = 89; + Room& room = *g_game->room; + return room.roomType == ROOM_BOSS && room.descriptor->data->subtype == BOSS_SUBTYPE_MOM && g_game->IsPreAscent(); +} + +// The pickup effects of 0075f0e0 for the collectibles 367 on that do more than drop pickups: Mom's Box's Wooden +// Cross and Duct Tape, Tarot Cloth's card, Divorce Papers, Brittle Bones, the Broken Shovel, Luna's secret room, +// Saturnus' tears, the Booster Pack, False PHD, Dad's Note's ascent and TMTRAINER. Camo Undies only acts in versus. +void late_collectible_gain(Entity_Player& player, int type, bool isFirstTime) +{ + RNG& rng = player.GetCollectibleRNG(type); + switch (type) + { + case COLLECTIBLE_MOMS_BOX: + if (player.HasTrinket(TRINKET_WOODEN_CROSS) && !player.HasGoldenTrinket(TRINKET_WOODEN_CROSS)) + wooden_cross_mantle_add(player); + if (player.GetTrinketMultiplier(TRINKET_DUCT_TAPE) > 1 && player.ductTapeMode == 0) player.ductTapeMode = 1; + return; + case COLLECTIBLE_TAROT_CLOTH: + if (!isFirstTime) return; + { + Vector position = room_free_pickup_position_find({.position = player.pos, .step = GAIN_PICKUP_STEP}); + int card = ItemPool::GetCardEx((int)rng.Next(), 0, 0, 0, false); + g_game->Spawn({.position = position, .subType = card, .type = ENTITY_PICKUP, .variant = PICKUP_TAROTCARD, + .seed = rng.Next()}); + } + return; + case COLLECTIBLE_CAMO_UNDIES: + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::AddCollectible 0075f0e0 (Camo Undies in versus)"); + return; + case COLLECTIBLE_DIVORCE_PAPERS: + if (isFirstTime) divorce_papers_gain(player, rng); + return; + case COLLECTIBLE_BRITTLE_BONES: + if (isFirstTime) brittle_bones_gain(player); + return; + case COLLECTIBLE_BROKEN_SHOVEL_2: + broken_shovel_gain(player); + return; + case COLLECTIBLE_LUNA: + g_game->reveal_secret_room(); + return; + case COLLECTIBLE_SATURNUS: + if (isFirstTime) player.fire_saturnus_tears(); + return; + case COLLECTIBLE_BOOSTER_PACK: + if (isFirstTime) booster_pack_gain(player, rng); + return; + case COLLECTIBLE_FALSE_PHD: + if (isFirstTime) false_phd_gain(player, rng); + return; + case COLLECTIBLE_DADS_NOTE: + if (is_pre_ascent_mom_room() && !g_game->IsAscent() && g_game->ascentTimer < 1) g_game->ascentTimer = 1; + return; + case COLLECTIBLE_TMTRAINER: + if (isFirstTime) tmtrainer_gain(player); + return; + } + reconstruction_missing((std::string("Entity_Player::AddCollectible 0075f0e0 (the pickup effect of ") + + std::to_string(type) + ")").c_str()); +} + +// Purity's pickup in 0075f0e0: a colour is rolled, its aura and glow come on. +void purity_gain(Entity_Player& player) +{ + player.purityState = (int)player.GetCollectibleRNG(COLLECTIBLE_PURITY).RandomInt(PURITY_STATES); + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_PURITY, true, 1); + player.AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_PURITY_GLOW), false); + player.update_purity_glow(); +} + +// A crown's glow following its condition: the effect and the glowing float come on together, or go together. +static void crown_glow_set(Entity_Player& player, int crown, ANM2& sprite, bool isLit) +{ + TemporaryEffects& effects = player.temporaryEffects; + if (isLit == effects.HasCollectibleEffect(crown)) return; + if (isLit) effects.AddCollectibleEffect(crown, true, 1); + else effects.RemoveCollectibleEffect(crown, 1); + sprite.Play(isLit ? "FloatGlow" : "FloatNoGlow"); +} + +// 007db360 Whether Dark Prince's Crown glows: at exactly one red heart, or in versus with a tenth to three tenths of +// the red hearts. +bool is_dark_prince_lit(Entity_Player& player) +{ + constexpr float VERSUS_SHARE_MIN = 0.1f; + constexpr float VERSUS_SHARE_MAX = 0.3f; + constexpr int PRINCE_HEARTS = 2; + if (!g_game->deathmatchManager.is_active()) return player.redHearts == PRINCE_HEARTS; + float share = (float)player.redHearts / (float)player.maxHearts; + return share >= VERSUS_SHARE_MIN && share <= VERSUS_SHARE_MAX; +} + +// The crowns' part of 007c9ea0: Crown of Light glows while the player is at full red health and unhurt this room (in +// versus at eight tenths of the red hearts), Dark Prince's Crown at one red heart. +void crowns_update(Entity_Player& player) +{ + constexpr float VERSUS_LIGHT_SHARE = 0.8f; + if (player.HasCollectible(COLLECTIBLE_CROWN_OF_LIGHT)) + { + bool isLit = g_game->deathmatchManager.is_active() ? (float)player.redHearts / (float)player.maxHearts >= VERSUS_LIGHT_SHARE + : !player.isHurtThisRoom && player.HasFullHearts(); + crown_glow_set(player, COLLECTIBLE_CROWN_OF_LIGHT, player.crownOfLightSprite, isLit); + } + if (player.HasCollectible(COLLECTIBLE_DARK_PRINCES_CROWN)) + crown_glow_set(player, COLLECTIBLE_DARK_PRINCES_CROWN, player.darkPrincesCrownSprite, is_dark_prince_lit(player)); +} + +// The crowns' and Purity's part of 007a8350: Purity's aura comes back with its glow, and a crown not glowing is +// lit again when its condition holds, its float showing which. +void crowns_room_enter(Entity_Player& player) +{ + TemporaryEffects& effects = player.temporaryEffects; + if (player.HasCollectible(COLLECTIBLE_PURITY) && !effects.HasCollectibleEffect(COLLECTIBLE_PURITY)) + { + effects.AddEffect(TemporaryEffect(g_manager->itemConfig.GetCollectible(COLLECTIBLE_PURITY)), true, 1); + player.AddCostume(g_manager->itemConfig.GetNullItem(NULLITEM_PURITY_GLOW), false); + player.update_purity_glow(); + } + if (player.HasCollectible(COLLECTIBLE_CROWN_OF_LIGHT) && !effects.HasCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT)) + { + bool isLit = player.HasFullHearts(); + if (isLit) effects.AddCollectibleEffect(COLLECTIBLE_CROWN_OF_LIGHT, true, 1); + player.crownOfLightSprite.Play(isLit ? "FloatGlow" : "FloatNoGlow"); + } + if (player.HasCollectible(COLLECTIBLE_DARK_PRINCES_CROWN) && !effects.HasCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN)) + { + bool isLit = is_dark_prince_lit(player); + if (isLit) effects.AddCollectibleEffect(COLLECTIBLE_DARK_PRINCES_CROWN, true, 1); + player.darkPrincesCrownSprite.Play(isLit ? "FloatGlow" : "FloatNoGlow"); + } +} + +// The Smelter's use in 005b39d0 (and Gulp!'s): a main player's held trinkets, the one held up first, are smelted into +// it for good, each joining the history, plain or golden. +void trinkets_smelt(Entity_Player& player) +{ + if (player.variant != PLAYER_VARIANT_PLAYER) return; + Game& game = *g_game; + + player.FlushQueueItem(); + for (uint32_t& held : player.trinkets) + { + if (held == 0) continue; + uint32_t id = held & TRINKET_ID_MASK; + ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(id); + log_printf(LOG_INFO, "Adding smelted trinket %d (%s) to player %d (%s)\n", held, + trinket ? trinket->GetLocalizedName(LANGUAGE_CURRENT).c_str() : "", player.playerIndex, player.name.c_str()); + player.history.AddHistoryItem({game.frameCount, true, (int)held, (int)game.stage, (int)game.stageType, + game.room->roomType, HISTORY_POOL_NONE}); + SmeltedTrinket& smelted = player.smeltedTrinkets[id]; + if (held & TRINKET_GOLDEN_FLAG) smelted.goldenCount++; + else smelted.count++; + held = 0; + } + player.InvalidateCoPlayerItems(); + game.hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); +} + +// Hairpin's part of 00794e50: the frame after entering a boss room for the first time, the first active that takes a +// charge is filled (overcharged when golden or with Mom's Box), with the battery sound and icon. +static void hairpin_update(Entity_Player& player) +{ + constexpr int BATTERY_ICON = 1; + constexpr float BATTERY_ICON_RISE = -24; + Room& room = *g_game->room; + if (!room.isInitialized || g_game->frameCount - room.enterFrame != 1 || room.roomType != ROOM_BOSS || !room.isFirstVisit) + return; + + bool isOvercharge = player.HasGoldenTrinket(TRINKET_HAIRPIN) || player.HasCollectible(COLLECTIBLE_MOMS_BOX); + for (int slot = 0; slot < ACTIVE_SLOT_COUNT && !player.FullCharge(slot, false, isOvercharge); slot++) {} + sound_play(SOUND_BATTERYCHARGE); + Entity* icon = g_game->Spawn({.position = player.pos, .subType = BATTERY_ICON, .type = ENTITY_EFFECT, + .variant = EFFECT_HEART, .seed = Random()}); + icon->sprite.offset = vector_make(0, BATTERY_ICON_RISE); + icon->renderDepthOffset = 1; +} + +// Mysterious Candy's part of 00794e50: every 900 frames, one time in two, a poop (golden with a golden candy, black on +// Meconium's roll) drops under a main player standing on an empty or decorated cell outside crawl spaces. Otherwise +// every 1800 frames, one time in two, the player farts. +static void mysterious_candy_update(Entity_Player& player) +{ + constexpr int CANDY_POOP_FRAMES = 900; + constexpr int CANDY_FART_FRAMES = 1800; + constexpr float CANDY_FART_RADIUS = 120; + constexpr int MECONIUM_CHANCES[] = {33, 66, 100}; + Room& room = *g_game->room; + int cell = room.GetGridIndex(player.pos); + GridEntity* grid = room.GetGridEntity(cell); + int frame = g_game->frameCount; + + bool isFree = !grid || grid->type == GRID_DECORATION || grid->type == GRID_SPIDERWEB; + if (frame % CANDY_POOP_FRAMES == 0 && random_below(2) == 0 && isFree && room.roomType != ROOM_DUNGEON) + { + int variant = player.HasGoldenTrinket(TRINKET_MYSTERIOUS_CANDY) ? POOP_GOLDEN : POOP_NORMAL; + if (player.HasTrinket(TRINKET_MECONIUM)) + { + int multiplier = player.GetTrinketMultiplier(TRINKET_MECONIUM); + uint32_t chance = (uint32_t)MECONIUM_CHANCES[multiplier == 2 ? 1 : multiplier == 3 ? 2 : 0]; + if (player.GetTrinketRNG(TRINKET_MECONIUM).RandomInt(100) < chance) variant = POOP_BLACK; + } + room.SpawnGridEntity(cell, GRID_POOP, variant, player.GetTrinketRNG(TRINKET_MYSTERIOUS_CANDY).Next(), 0); + } + else if (frame % CANDY_FART_FRAMES == 0 && random_below(2) == 0) + game_butter_bean_fart({.position = player.pos, .source = &player, .radius = CANDY_FART_RADIUS}); +} + +// Louse's part of 00794e50: in an uncleared room, every 900 frames one time in two (and surely every 1800), both +// timed from the room's seed, the player throws a blue spider per copy. +static void louse_update(Entity_Player& player) +{ + constexpr int LOUSE_FRAMES = 900; + constexpr int LOUSE_FRAMES_SURE = 1800; + constexpr float LOUSE_VOLUME = 0.7f; + int offset = (int)(g_game->room->GetSpawnSeed() % LOUSE_FRAMES_SURE); + if (g_game->room->IsClear()) return; + + bool isTime = (player.IsFrame(LOUSE_FRAMES, offset) && random_below(2) == 0) || player.IsFrame(LOUSE_FRAMES_SURE, offset); + if (!isTime) return; + npc_sound_play(SOUND_BOIL_HATCH, LOUSE_VOLUME, 2, 1); + for (int i = player.GetTrinketMultiplier(TRINKET_LOUSE); i > 0; i--) player.ThrowBlueSpider(player.pos, {}); +} + +// The trinkets' part of the items' frame (00794e50), in their order there: Hairpin, Mysterious Candy, Louse and +// Rainbow Worm, whose tear effect changes every 90 frames. +void trinkets_frame_update(Entity_Player& player) +{ + if (player.HasTrinket(TRINKET_HAIRPIN)) hairpin_update(player); + if (player.HasTrinket(TRINKET_MYSTERIOUS_CANDY) && player.variant == PLAYER_VARIANT_PLAYER) mysterious_candy_update(player); + if (player.HasTrinket(TRINKET_LOUSE)) louse_update(player); + if (player.HasTrinket(TRINKET_RAINBOW_WORM) && g_game->frameCount % RAINBOW_WORM_FRAMES == 0) + { + player.cacheFlags |= CACHE_FIREDELAY | CACHE_SHOTSPEED | CACHE_RANGE | CACHE_TEARFLAG; + player.EvaluateItems(); + } +} + +// The pennies' drop: once a penny trinket rolls at least its threshold, a pickup lands on a free spot near the player. +static void penny_drop(Entity_Player& player, int variant, int subType) +{ + uint32_t seed = Random(); + Vector position = room_free_pickup_position_find({.position = player.pos, .step = GAIN_PICKUP_STEP}); + g_game->Spawn({.position = position, .subType = subType, .type = ENTITY_PICKUP, .variant = variant, .seed = seed}); +} + +// Whether a penny trinket's roll passes: a pickup worth more coins (and stronger copies, a quarter each) makes it likelier. +static bool is_penny_rolled(Entity_Player& player, int trinket, float threshold) +{ + float chance = threshold - (float)(player.GetTrinketMultiplier(trinket) - 1) * 0.25f; + return chance <= player.GetTrinketRNG(trinket).RandomFloat(); +} + +// Blessed Penny's chance of a half soul heart, by its strength and the coin's worth. +static float blessed_penny_chance(int multiplier, int value) +{ + constexpr float CHANCES[3][4] = {{0.17f, 0.3f, 0.6f, 0.83f}, {0.25f, 0.4f, 0.7f, 0.9f}, {0.3f, 0.5f, 0.75f, 1.0f}}; + const float* chances = CHANCES[multiplier == 2 ? 1 : multiplier == 3 ? 2 : 0]; + return value == 2 ? chances[1] : value == 5 ? chances[2] : value == 10 ? chances[3] : chances[0]; +} + +// The penny trinkets' part of 006e8ae0 for a coin worth value: Burnt, Flat and Bloody Penny drop a bomb, key or half +// heart (Bloody Penny one time in five with Daemon's Tail), Counterfeit Penny adds coins, Blessed Penny drops a half +// soul heart, Charged Penny charges the first active that takes it, Cursed Penny teleports, Butt Penny farts (a dip with +// Dirty Mind) and Rotten Penny brings blue flies. +void coin_trinkets_collect(Entity_Pickup& pickup, Entity_Player& player, int value) +{ + constexpr float BUTT_FART_RADIUS = 85; + constexpr float BUTT_BEAN_RADIUS = 120; + constexpr int BURNT_PENNY_BOMB = 1; + float threshold = std::pow(0.75f, (float)value); + float doubling = std::pow(0.5f, (float)value); + + if (player.HasTrinket(TRINKET_BURNT_PENNY) && is_penny_rolled(player, TRINKET_BURNT_PENNY, threshold)) + penny_drop(player, PICKUP_BOMB, BURNT_PENNY_BOMB); + if (player.HasTrinket(TRINKET_FLAT_PENNY) && is_penny_rolled(player, TRINKET_FLAT_PENNY, threshold)) + penny_drop(player, PICKUP_KEY, KEY_NORMAL); + if (player.HasTrinket(TRINKET_BLOODY_PENNY) && is_penny_rolled(player, TRINKET_BLOODY_PENNY, threshold) && + (!player.HasTrinket(TRINKET_DAEMONS_TAIL) || player.GetTrinketRNG(TRINKET_DAEMONS_TAIL).RandomInt(DAEMONS_TAIL_ODDS) == 0)) + penny_drop(player, PICKUP_HEART, HEART_HALF); + if (player.HasTrinket(TRINKET_COUNTERFEIT_PENNY) && doubling <= player.GetTrinketRNG(TRINKET_COUNTERFEIT_PENNY).RandomFloat()) + player.AddCoins(player.GetTrinketMultiplier(TRINKET_COUNTERFEIT_PENNY)); + if (player.HasTrinket(TRINKET_BLESSED_PENNY)) + { + float chance = blessed_penny_chance(player.GetTrinketMultiplier(TRINKET_BLESSED_PENNY), value); + if (player.GetTrinketRNG(TRINKET_BLESSED_PENNY).RandomFloat() <= chance) penny_drop(player, PICKUP_HEART, HEART_HALF_SOUL); + } + if (player.HasTrinket(TRINKET_CHARGED_PENNY) && threshold <= player.GetTrinketRNG(TRINKET_CHARGED_PENNY).RandomFloat()) + { + int charge = std::min(std::max(player.GetTrinketMultiplier(TRINKET_CHARGED_PENNY), 1), 3); + for (int slot = 0; slot < ACTIVE_SLOT_COUNT && player.AddActiveCharge(charge, slot, false, false, false) == 0; slot++) {} + } + if (player.HasTrinket(TRINKET_CURSED_PENNY) && !player.HasCollectible(COLLECTIBLE_BLACK_CANDLE)) + player.cursedPennyPending = pickup.subtype; + if (player.HasTrinket(TRINKET_BUTT_PENNY)) + { + game_fart({.position = pickup.pos, .source = &player, .radius = BUTT_FART_RADIUS}); + game_butter_bean_fart({.position = player.pos, .source = &player, .radius = BUTT_BEAN_RADIUS, .isShowEffect = false}); + if (player.GetTrinketRNG(TRINKET_BUTT_PENNY).RandomInt(2) == 0 && player.HasCollectible(COLLECTIBLE_DIRTY_MIND)) + { + Vector target = room_free_pickup_position_find({.position = player.pos, .step = GAIN_PICKUP_STEP}); + player.ThrowFriendlyDip(0, player.pos, target); + } + } + if (player.HasTrinket(TRINKET_ROTTEN_PENNY)) + player.AddBlueFlies(std::min(std::max(player.GetTrinketMultiplier(TRINKET_ROTTEN_PENNY), 1), 3), player.pos, nullptr); +} diff --git a/src/entity_player_trinkets.h b/src/entity_player_trinkets.h new file mode 100644 index 0000000..c3b476a --- /dev/null +++ b/src/entity_player_trinkets.h @@ -0,0 +1,48 @@ +#pragma once + +#include "classes.h" +#include "entity.h" + +struct Entity_Pickup; +struct Entity_Player; + +// Purity's colours, how often Rainbow Worm changes its worm, and the history's pool for an item from none. +constexpr int PURITY_STATES = 4; +constexpr int RAINBOW_WORM_FRAMES = 90; +constexpr int HISTORY_POOL_NONE = -1; + +// What a landed hit tells the items it sets off. +struct ItemsHit +{ + EntityRef source; + uint64_t damageFlags = 0; + float damage = 0; + bool isPenalized = false; +}; + +// The trinkets' and late collectibles' (367 on) pieces other files call (entity_player_trinkets.cpp and +// entity_player_hits.cpp). Pickups: a trinket taken and lifted, a coin's penny trinkets, the Smelter's smelting. +bool trinket_collect(Entity_Pickup& pickup, Entity_Player& player); +void trinket_lift(Entity_Pickup& pickup, Entity_Player& player); +void coin_trinkets_collect(Entity_Pickup& pickup, Entity_Player& player, int value); +void trinkets_smelt(Entity_Player& player); + +// The player's frame and the items' frame. +void equality_update(Entity_Player& player); +void trinket_teleports_update(Entity_Player& player); +void trinkets_frame_update(Entity_Player& player); + +// A new room, the hearts changing, a hit. +void trinkets_room_enter(Entity_Player& player); +void umbilical_cord_room_enter(Entity_Player& player); +void crowns_room_enter(Entity_Player& player); +void dice_bag_room_enter(Entity_Player& player); +void crowns_update(Entity_Player& player); +bool is_dark_prince_lit(Entity_Player& player); +bool late_items_hit_trigger(Entity_Player& player, const ItemsHit& hit); +void cursed_skull_teleport(Entity_Player& player); + +// A collectible taken. +void wooden_cross_mantle_add(Entity_Player& player); +void late_collectible_gain(Entity_Player& player, int type, bool isFirstTime); +void purity_gain(Entity_Player& player); diff --git a/src/entity_player_weapons.cpp b/src/entity_player_weapons.cpp index 180112f..1b021be 100644 --- a/src/entity_player_weapons.cpp +++ b/src/entity_player_weapons.cpp @@ -22,7 +22,6 @@ constexpr int PLAYER_HEAD_LAYER = 4; constexpr const char* NULL_OFFSET_NAMES[] = {"LeftEye", "RightEye", "Forehead", "Mouth", "Mouth", "MomsEye", "Tractor"}; constexpr float CROSS_EYED_ANGLE = 0.7853982f; -constexpr float DEAD_EYE_STEP = 0.125f; constexpr float DEGREES_TO_RADIANS = 0.017453292f; constexpr float DEGREES_PER_RADIAN = 57.295776f; constexpr float DUNGEON_TEAR_HEIGHT_MAX = -5.1f; @@ -33,8 +32,6 @@ constexpr float LANE_SPREAD_X = 1.15f; constexpr float LANE_SPREAD_Y = 0.8f; constexpr float RANDOM_UNIT = 2.3283064e-10f; constexpr float SPREAD_CLAMP = 90; -constexpr float TEAR_FALL_SPREAD = 0.2f; -constexpr float TEAR_SCALE_MIN = 0.01f; constexpr float WIZ_EYE_ANGLE = 45; // How much each extra tear widens a volley's tears and lasers, by what adds it, and how the other weapons follow. constexpr float SPREAD_ITEM_LASER = 2.333f; @@ -60,9 +57,6 @@ constexpr int EYE_SORE_ROLL_MASK = 3; constexpr int BOOKWORM_ROLL_MASK = 3; constexpr int CONJOINED_EXTRA_TEARS = 2; constexpr float WIZ_EYE_ANGLE_MAX = 55; -constexpr int DEAD_EYE_STEPS = 8; -constexpr int DARK_ARTS_STEPS = 16; -constexpr float DARK_ARTS_STEP = 0.0625f; constexpr int MAX_TEARS = 16; constexpr int MAX_EYES = 8; constexpr int BABY_TECHNOLOGY = 16; @@ -70,7 +64,6 @@ constexpr int BABY_TWENTY_TWENTY = 65; 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; @@ -79,9 +72,7 @@ constexpr int COLLECTIBLE_CURSED_EYE_WEAPON = 316; constexpr int COLLECTIBLE_DEAD_TOOTH = 446; constexpr int COLLECTIBLE_EYE_SORE = 558; constexpr int COLLECTIBLE_INNER_EYE = 2; -constexpr int COLLECTIBLE_LARGE_ZIT = 502; constexpr int COLLECTIBLE_NEPTUNUS = 597; -constexpr int NULLITEM_DARK_ARTS = 111; // The items GetWeaponModifiers turns into modifier bits, in the order it asks. constexpr std::pair MODIFIER_ITEMS[] = { @@ -404,10 +395,7 @@ Entity_Tear* Entity_Player::FireTear(const PosVel& shot, uint32_t fireFlags, Ent tear->parent = this; if (fireFlags & TEAR_FIRE_NO_STREAK_END) tear->isCanTriggerStreakEnd = false; - float deadEye = deadEyeCharges > 0 ? (float)std::min((int)deadEyeCharges, DEAD_EYE_STEPS) * DEAD_EYE_STEP : 0; - float intensity = deadEye; - if (int darkArts = temporaryEffects.GetNullEffectNum(NULLITEM_DARK_ARTS); darkArts > 0) - intensity = std::max((float)std::min(darkArts, DARK_ARTS_STEPS) * DARK_ARTS_STEP, deadEye); + float intensity = dead_eye_glow_get(*this); if (HasCollectible(COLLECTIBLE_STYE)) reconstruction_missing("Entity_Player::FireTear 00790af0 (Stye)"); if (intensity > 0) tear->SetDeadEyeIntensity(intensity); tear->mass *= params.massMultiplier; diff --git a/src/entity_projectile.cpp b/src/entity_projectile.cpp index bbfe06e..32b7ebb 100644 --- a/src/entity_projectile.cpp +++ b/src/entity_projectile.cpp @@ -275,7 +275,6 @@ constexpr int COLOR_PRIORITY = 255; constexpr int COLOR_PRIORITY_NONE = -1; constexpr int ENTITY_MR_FRED = 270; -constexpr int ENTITY_MEGA_SATAN_2 = 275; constexpr int ENTITY_TARBOY = 307; constexpr int ENTITY_NECRO = 828; constexpr int ENTITY_SHADY = 888; @@ -287,8 +286,6 @@ constexpr int EFFECT_BONE_PARTICLE = 35; constexpr int EFFECT_CORN_POOF = 43; constexpr int EFFECT_CORN_PARTICLE = 58; constexpr int EFFECT_COIN_POOF = 97; -constexpr int EFFECT_COIN_PARTICLE = 98; -constexpr int EFFECT_HUSH_POOF = 102; constexpr int EFFECT_GODHEAD_AURA = 123; constexpr int EFFECT_DOGMA_POOF = 200; constexpr int GODHEAD_AURA_SUBTYPE = 4; @@ -877,7 +874,7 @@ void Entity_Projectile::death_poof_spawn() .variant = EFFECT_CORN_PARTICLE}); effect = EFFECT_CORN_POOF; } - else if (variant == PROJECTILE_HUSH) effect = EFFECT_HUSH_POOF; + else if (variant == PROJECTILE_HUSH) effect = EFFECT_BULLET_POOF_HUSH; else if (sprite.bitflags & ANIM_RENDER_STATIC) effect = EFFECT_DOGMA_POOF; poof = effect_spawn(effect, pos, nullptr); diff --git a/src/entity_rock_drop.cpp b/src/entity_rock_drop.cpp new file mode 100644 index 0000000..09da71f --- /dev/null +++ b/src/entity_rock_drop.cpp @@ -0,0 +1,101 @@ +#include "entity_bomb.h" +#include "entity_effect.h" +#include "game.h" +#include "grid_entity_poop.h" +#include "grid_entity_rock.h" +#include "grid_entity_tnt.h" +#include "npc_ai.h" +#include + +// What a thrown grid entity leaves when it lands: a bomb rock's or barrel's blast of 60, a rock's four bits of rubble +// (in the thrower's look unless it was a rock-like shot, variant 9000), or a poop's rewards, gibs and drops. +constexpr float LANDED_BLAST_DAMAGE = 60; +constexpr int ROCKLIKE_VARIANT = 9000; +constexpr int RUBBLE_PIECES = 4; +constexpr float RUBBLE_SCATTER = 12; +constexpr float RUBBLE_SPEED = 5; +constexpr int RUBBLE_PLAIN = 1; +constexpr int RUBBLE_ALT = 2; +constexpr int RUBBLE_ROCKLIKE = 0x10001; +constexpr int RUBBLE_LANDED = 1; +constexpr int POOP_LANDED_DAMAGE = 1000; +constexpr int POOP_LANDED_GIBS = 4; + +// Whether a grid type is one of the rocks a landing breaks into rubble. +static bool is_landed_rock(int type) +{ + return type == GRID_ROCK || type == GRID_ROCKT || type == GRID_ROCK_ALT || type == GRID_ROCK_SS || + type == GRID_ROCK_ALT2 || type == GRID_ROCK_GOLD; +} + +// A rock's rubble: four bits scattered about the spot, in the thrower's look and still on a random frame. +static void rubble_spawn(const Vector& position, int type, int subType, Entity* source, bool isNormal) +{ + for (int i = 0; i < RUBBLE_PIECES; i++) + { + float angle = random_unit() * 360 * DEGREES_TO_RADIANS; + Vector direction = vector_make(std::cos(angle), std::sin(angle)); + Vector at = vector_add(position, vector_scale(direction, random_unit() * RUBBLE_SCATTER)); + auto* rubble = static_cast(g_game->Spawn({.position = at, + .velocity = vector_scale(direction, RUBBLE_SPEED), + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_ROCK_PARTICLE, + .seed = Random()})); + if (!isNormal) continue; + + if (source) rubble->sprite = source->sprite; + std::string_view anim = type == GRID_ROCK_ALT || type == GRID_ROCK_ALT2 ? "rubble_alt" : "rubble"; + if (const AnimationData* data = rubble->sprite.GetAnimationData(anim)) + { + int frame = data->length == 0 ? 0 : (int)(Random() % (uint32_t)data->length); + rubble->sprite.SetFrame(anim, frame); + } + rubble->state = RUBBLE_LANDED; + } +} + +// 0070c000 Breaks a thrown grid entity where it landed, as if it were broken in place there. +void Entity::DestroyRockGridAt(const Vector& position, GridEntityDesc* desc, Entity* source, int backdropType) +{ + int type = desc->_type; + int variant = desc->_variant; + if (type == GRID_ROCK_BOMB || type == GRID_TNT) + { + explosion_effects({.position = position, .source = source, .damage = LANDED_BLAST_DAMAGE}); + if (type == GRID_ROCK_BOMB) return; + wood_particles_spawn(position); + return trinket_drop_try(desc->_spawnSeed); + } + + if (is_landed_rock(type)) + { + GridEntity_Rock::PlayBreakSound((GridEntityType)type, backdropType); + bool isNormal = variant != ROCKLIKE_VARIANT; + int subType = RUBBLE_ROCKLIKE; + if (isNormal) + { + subType = type == GRID_ROCK_ALT || type == GRID_ROCK_ALT2 ? RUBBLE_ALT : RUBBLE_PLAIN; + GridEntity_Rock::RegisterRockDestroyed((GridEntityType)type); + } + rubble_spawn(position, type, subType, source, isNormal); + if (isNormal) + GridEntity_Rock::SpawnDrops(position, (GridEntityType)type, variant, desc->_spawnSeed, backdropType, source); + return; + } + if (type != GRID_POOP) return; + + GridEntity_Poop::spawn_rewards({.source = EntityRef(source), + .position = position, + .seed = desc->_spawnSeed, + .damage = POOP_LANDED_DAMAGE, + .previousState = desc->_state, + .variant = variant}); + GridEntity_Poop::destroy_effects(position, variant); + GridEntity_Poop::spawn_hit_gibs(position, variant, POOP_LANDED_GIBS); + GridEntity_Poop::spawn_drops({.position = position, + .seed = desc->_spawnSeed, + .variant = variant, + .isLowDropChance = desc->_varData == 1, + .isNoWisp = true}); +} diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index e4ad161..0786b3a 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -1,7 +1,12 @@ #include "entity_tear.h" +#include "boss_ai.h" +#include "entity_config.h" #include "entity_effect.h" #include "entity_familiar.h" +#include "entity_knife.h" #include "entity_laser.h" +#include "entity_pickup.h" +#include "entity_npc.h" #include "entity_player.h" #include "game.h" #include "grid_entity.h" @@ -19,14 +24,14 @@ constexpr float TEAR_HEIGHT_START = -23; constexpr float TEAR_DAMAGE_DEFAULT = 3.5f; -constexpr float TEAR_FALL_SPREAD = 0.2f; constexpr float TEAR_HOMING_FRICTION = 0.85f; constexpr float DEFLECT_REBOUND = 0.85f; constexpr float TEAR_KNOCKBACK_MULTIPLIER = 1.7f; constexpr float TEAR_RANGE_DEFAULT = 260; -constexpr float TEAR_SCALE_MIN = 0.01f; -constexpr float TEAR_FLOOR_HEIGHT = -5; constexpr float TEAR_GRID_HIT_HEIGHT = -60; +// A Chaos Card on the floor lies upside down, and a water tear bounces off the floor a little faster than it fell. +constexpr float CHAOS_CARD_FLOOR_ANGLE = 180; +constexpr float HYDROBOUNCE_REBOUND = -1.6f; constexpr float CRAWLSPACE_OFFSET_Y = -18; constexpr float CRAWLSPACE_RANGE_SHARE = 0.6f; constexpr float CRAWLSPACE_ROOM_MARGIN = -256; @@ -35,11 +40,13 @@ constexpr float CRAWLSPACE_LEVEL_SLOPE = 0.05f; constexpr float GRAVITY_MIN_ACCEL = 0.001f; constexpr float GRAVITY_PULL = 0.1f; constexpr float GRAVITY_FALL_DRAG = 0.9f; +constexpr float FETUS_HOVER_SHARE = 0.25f; +constexpr float FETUS_FALL_ACCEL = 0.2f; constexpr float HOVER_HEIGHT_BOB = 0.5f; constexpr int HOVER_BOB_FRAMES = 15; constexpr float ROOM_SLOWDOWN_SCALE = 0.75f; -constexpr float RIGHT_ANGLE = 90; -constexpr float FULL_TURN = 360; +constexpr float REMOTE_OPACITY_STEP = 0.09f; +constexpr float REMOTE_OPACITY_MIN = 0.1f; // The height offset a tear flying without gravity draws at: a fixed lift, and a curve near the floor. constexpr float HOVER_OFFSET_SCALE = 0.4f; @@ -51,6 +58,11 @@ constexpr float GFUEL_NAIL_OFFSET = -12; constexpr std::array TEAR_ANIMATION_SCALES = {0.25f, 0.5f, 0.625f, 0.75f, 0.875f, 1.0f, 1.125f, 1.375f, 1.625f, 1.875f, 2.125f, 2.5f, 2.75f}; constexpr float TEAR_ANIMATION_MARGIN = 0.05f; +// The scales of the scythe's and rock's Rotate%d (and a sixth past them), and of the fetus' five, which plays one +// a quarter larger than its scale. +constexpr std::array SPINNING_ANIMATION_SCALES = {0.556f, 1, 1.333f, 1.667f, 2.5f}; +constexpr std::array FETUS_ANIMATION_SCALES = {0.75f, 1.125f, 1.375f, 1.75f, 2.25f}; +constexpr float FETUS_ANIMATION_GROWTH = 0.25f; constexpr int TEAR_ANIMATION_BASE = 100; constexpr int TEAR_ANIMATION_NAME_SIZE = 32; constexpr float TEAR_EFFECT_SCALE = 0.45f; @@ -59,28 +71,14 @@ constexpr unsigned int TEAR_EFFECT_BEHIND = 1 << 13; constexpr float GFUEL_SIZE_DIVISOR = 3; constexpr float GFUEL_NAIL_WIDTH = 3; -// The splash a dying tear leaves: the poof sizes by its scale, the sounds, and the stains blood tears leave. -constexpr float POOF_SCALE_SMALL = 0.4f; -constexpr float POOF_SCALE_LARGE = 0.8f; -constexpr float SWORD_BEAM_VOLUME = 0.3f; -constexpr float SWORD_BEAM_PITCH = 2; -constexpr float SWORD_BEAM_PITCH_SPREAD = 0.5f; -constexpr int SWORD_BEAM_POOF_SUBTYPE = 22; -constexpr int STAIN_COUNT_MAX = 5; -constexpr float STAIN_SPREAD = 24; -constexpr float STAIN_SCALE = 0.3f; -constexpr float STAIN_ALPHA = 0.08f; -constexpr float MASCARA_ALPHA = 0.2f; -constexpr float MASCARA_ALPHA_SPREAD = 0.3f; -constexpr ColorMod STAIN_COLOR = {{0, 0, 0, STAIN_ALPHA}, {0, 0, 0, 0}, {0, 0, 0}}; -constexpr ColorMod NUMBER_ONE_STAIN_COLOR = {{0, 0, 0, 0.5f}, {0, 0, 0, 0}, {150 / 255.0f, 150 / 255.0f, 0}}; // The tint a room's slowdown (the Broken Watch's) lays over a tear for two frames. constexpr ColorMod SLOWDOWN_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.0f, 40 / 255.0f, 40 / 255.0f}}; constexpr int SLOWDOWN_COLOR_FRAMES = 2; -constexpr int COLOR_PRIORITY_TOP = 255; // What the tear's grid hit does to rocks: one hit, two for a strong tear. constexpr float STRONG_TEAR_DAMAGE = 10; +// A rock tear breaks a rock by a tenth of its damage's chance. +constexpr float ROCK_BREAK_CHANCE = 0.1f; // The grid path below which a wall the players pass stops tears. constexpr int GRID_PATH_TEAR_WALL = 3000; // A tear spawned with FLAG_NO_SPIKE_DAMAGE starts with more friction, easing off over its first updates. @@ -90,10 +88,6 @@ constexpr float LAUNCH_DRAG_FRICTION = 0.55f; // How the flags move a tear: Anti-Gravity's wait, homing's search and pull, Hook Worm's turns, Lump of Coal's growth, // Proptosis' shrinking, My Reflection's pull, Pulse Worm's beat and Flat Worm's stretch. constexpr int WAIT_FRAMES = 90; -constexpr int HOMING_SEARCH_FRAMES = 4; -constexpr float HOMING_LOOK_AHEAD = 5; -constexpr float HOMING_RADIUS = 128; -constexpr float HOMING_SCORE_NONE = 1e9f; constexpr float HOMING_PULL = 2; constexpr int SQUARE_START_FRAME = 3; constexpr int SQUARE_LOOP_START = 5; @@ -107,6 +101,8 @@ constexpr float GROW_SCALE = 0.01f; constexpr float SHRINK_START = 4; constexpr float SHRINK_FAST = 0.08f; constexpr float SHRINK_SLOW = 0.03f; +constexpr float SHRINK_FETUS_FAST = 0.022f; +constexpr float SHRINK_FETUS_SLOW = 0.006f; constexpr float SHRINK_FAST_SHARE = 3; constexpr float SHRINK_DAMAGE_MIN = 0.1f; constexpr int SPECTRAL_GRID_CHANCE = 8; @@ -118,6 +114,12 @@ constexpr float PULSE_STRENGTH = 0.3f; constexpr float PULSE_RATE = 0.7f; constexpr float PULSE_BASE = 0.6f; constexpr float PULSE_OFFSET = 0.7f; +constexpr float PULSE_LUDOVICO_RATE = 0.2f; +constexpr float PULSE_LUDOVICO_OFFSET = 0.2f; +constexpr float PULSE_LUDOVICO_BASE = 1.1f; +// A sticking tear grows while it holds on, and a booger hits its enemy again every 30 frames. +constexpr float STICK_GROWTH_FRAMES = 60; +constexpr int BOOGER_HIT_FRAMES = 30; // Technology Zero: the reach it links another tear within, its electric beam's lift, life and share of the damage. constexpr float TECH_ZERO_REACH = 350; @@ -137,9 +139,6 @@ constexpr float OCCULT_HOMING_FRICTION = 0.9f; // Ludovico's tears: the circling and Monstro's Lung's ones (and their own bit), the fast one, their drag, the reach // of their hits' refresh without a player, a fast tear's speed bonus and Spectral, the familiar's smaller tear, the // circling tears' ring and spin, the cloud's sway, a familiar tear's push off another, and the fast tear's leash. -constexpr int LUDOVICO_LUNG_BIT = 1; -constexpr int LUDOVICO_FAST = 2; -constexpr int LUDOVICO_CHILD = 4; constexpr float LUDOVICO_FRICTION = 0.7f; constexpr float LUDOVICO_FAST_FRICTION = 0.98f; constexpr float LUDOVICO_INTERVAL_DEFAULT = 10; @@ -182,7 +181,6 @@ constexpr float BOOMERANG_REACH_SHARE = 0.5f; constexpr float FLAT_STRETCH = 0.5f; constexpr float PUPULA_SPIN = 45; constexpr float TURN_AWAY = -0.1f; -constexpr int BOUNCE_SOUND = 905; // The wiggles: Wiggle Worm's sideways sway, Ring Worm's spiral and Ouroboros Worm's wide one. constexpr float WIGGLE_RATE = 0.7f; @@ -196,27 +194,10 @@ constexpr float BIG_SPIRAL_RADIUS = 15; constexpr float QUARTER_TURN = 1.5707964f; constexpr float HALF_FRAME = 0.5f; -// The pieces a dying tear breaks into: Parasite's two halves, Compound Fracture's shards and Cricket's Body's four. -constexpr float SPLIT_DAMAGE_MIN = 1; -constexpr float SPLIT_HEIGHT_SHARE = 1.5f; -constexpr float SPLIT_DAMAGE = 0.5f; -constexpr float SPLIT_RISING_DAMAGE = 0.25f; -constexpr float SPLIT_RISING_ACCEL = 2; -constexpr float SPLIT_SCALE = 0.5f; -constexpr float BONE_DAMAGE = 0.5f; -constexpr int BONE_SHARDS = 2; -constexpr const char* BROKEN_BONE_SHEET = "gfx/tears_brokenbone.png"; -constexpr int QUADSPLIT_PIECES = 4; -constexpr float QUADSPLIT_SLOW_SQUARED = 0.1f; -constexpr float QUADSPLIT_SLOW_SPEED = 10; -constexpr float QUADSPLIT_DAMAGE = 0.5f; -constexpr float QUADSPLIT_SCALE = 0.6f; -constexpr float QUADSPLIT_HEIGHT_SHARE = 0.5f; -constexpr float QUADSPLIT_FALL_SHARE = 0.3f; -constexpr float PLAYER_TEAR_HEIGHT = -23.75f; // The creep Mysterious Liquid's and It Hurts' tears leave where they die. constexpr float CREEP_MARGIN = 15; constexpr float CREEP_SCALE = 0.4f; +constexpr int CREEP_LUDOVICO_FRAMES = 5; // What a hit's flags do: the slowing and its tint (Ball of Tar's dark), and the durations of the status effects. constexpr int SLOW_DURATION = 60; @@ -243,15 +224,44 @@ constexpr int ICE_DURATION = 10; constexpr int SHRINK_DURATION = -150; constexpr int GREED_COIN_CHANCE = 20; constexpr int HP_DROP_CHANCE = 3; +constexpr int HIT_DROP_COUNTDOWN = 30; +// Parasitoid's hatching: its sound, and the flies' spread, speed and delay before they chase. +constexpr float EGG_VOLUME = 0.5f; +constexpr float EGG_PITCH_SPREAD = 0.2f; +constexpr float EGG_FLY_SPREAD = 48; +constexpr float EGG_FLY_SPEED = 10; +constexpr float EGG_FLY_SPEED_SPREAD = 4; +constexpr int EGG_FLY_DELAY = 20; +constexpr uint32_t EGG_FLY_DELAY_SPREAD = 10; +constexpr float HOLY_LIGHT_HIT_SCALE = 3; +constexpr float HOLY_LIGHT_REACH = 100; +constexpr int ENTITY_TYPE_NPC_FIRST = 10; constexpr float HIT_DIRECTION_MIN_SPEED = 0.02f; +// A knocked out coin flies back off the hit, turned 160 to 200 degrees, at 2 to 6, or drops within 40 of it. +constexpr float KNOCKED_COIN_TURN_MIN = 160; +constexpr float KNOCKED_COIN_TURN_SPREAD = 40; +constexpr float KNOCKED_COIN_SPEED_MIN = 2; +constexpr float KNOCKED_COIN_SPEED_SPREAD = 4; +constexpr float KNOCKED_COIN_FREE_STEP = 40; +// Euthanasia's needles: ten around at 10, a third larger, paler, and a water needle thrown up. +constexpr int NEEDLE_COUNT = 10; +constexpr float NEEDLE_SPEED = 10; +constexpr float NEEDLE_SCALE = 1.355f; +constexpr float NEEDLE_HYDRO_ACCEL = 3; +constexpr float NEEDLE_HYDRO_FALL = -15; +constexpr ColorMod NEEDLE_COLOR = {{0.85f, 0.85f, 0.85f, 1}, {1, 1, 1, 1}, {-0.2f, -0.2f, -0.2f}}; +// Backstabber: the extra hit's cooldown, the bleeding, its sound, and the blood sprayed out of the back. +constexpr int BACKSTAB_COUNTDOWN = 30; +constexpr int BACKSTAB_BLEED = -150; +constexpr float BACKSTAB_VOLUME = 0.7f; +constexpr int BACKSTAB_SOUND_DELAY = 8; +constexpr float BACKSTAB_SPRAY_SPEED = -4; +constexpr float BACKSTAB_SPRAY_LIFT = -15; constexpr int SOUND_TEAR_FIRE = 153; constexpr int SOUND_FETUS_FIRE = 237; constexpr float FETUS_FIRE_PITCH = 1.2f; constexpr int SOUND_LITTLE_HORN = 868; -constexpr int SOUND_SWORD_BEAM_IMPACT = 49; -constexpr int SOUND_TECH_SWORD_BEAM_IMPACT = 134; -constexpr int SOUND_DELAY = 2; // How Tiny Planet's and My Reflection's tears are thrown when fired. constexpr float ORBIT_FALL_SCALE = 3; @@ -261,13 +271,9 @@ constexpr float BOOMERANG_FALL_SCALE = 0.5f; constexpr float BOOMERANG_ACCEL_OFFSET = 0.08f; constexpr float BOOMERANG_ACCEL_SCALE = 0.25f; -constexpr int COLLECTIBLE_EVES_MASCARA = 310; constexpr uint32_t CHALLENGE_ONANS_STREAK = 29; constexpr int TRINKET_PULSE_WORM = 9; -constexpr int TRINKET_WIGGLE_WORM = 10; -constexpr int TRINKET_RING_WORM = 11; constexpr int TRINKET_FLAT_WORM = 12; -constexpr int TRINKET_HOOK_WORM = 26; // Onan's Streak punishes a tear that misses with a hit to its player. constexpr float STREAK_DAMAGE = 1; @@ -275,25 +281,18 @@ constexpr int STREAK_DAMAGE_COUNTDOWN = 30; constexpr const char* GFUEL_NAIL_ANM2 = "gfx/promo/gfuel/bullet tear.anm2"; constexpr const char* GFUEL_NAIL_BLOOD_ANM2 = "gfx/promo/gfuel/missile.anm2"; +constexpr const char* DEAD_EYE_ANM2 = "gfx/DeadEyeTearEffect.anm2"; +// Dead Eye's glow per charge and Dark Arts' per kill, each to a full glow. +constexpr float DEAD_EYE_STEP = 0.125f; +constexpr int DEAD_EYE_STEPS = 8; +constexpr float DARK_ARTS_STEP = 0.0625f; +constexpr int DARK_ARTS_STEPS = 16; -// The variants whose splash and flight are reconstructed: plain tears and the ones that only change the sprite. -constexpr std::array TEAR_PLAIN_VARIANTS = { - TEAR_BLUE, TEAR_BLOOD, TEAR_METALLIC, TEAR_FIRE_MIND, TEAR_DARK_MATTER, - TEAR_MYSTERIOUS, TEAR_LOST_CONTACT, TEAR_CUPID_BLUE, TEAR_CUPID_BLOOD, TEAR_PUPULA, - TEAR_PUPULA_BLOOD, TEAR_GODS_FLESH, TEAR_GODS_FLESH_BLOOD, TEAR_MULTIDIMENSIONAL, TEAR_GLAUCOMA, - TEAR_GLAUCOMA_BLOOD, TEAR_NEEDLE, TEAR_BELIAL, TEAR_HUNGRY, TEAR_FIST, - TEAR_ICE, TEAR_SWORD_BEAM, TEAR_TECH_SWORD_BEAM}; -// The variants whose splash is a bullet poof rather than a tear poof. -constexpr std::array TEAR_BULLET_POOF_VARIANTS = {TEAR_BLOOD, TEAR_CUPID_BLOOD, TEAR_PUPULA_BLOOD, - TEAR_GODS_FLESH_BLOOD, TEAR_GLAUCOMA_BLOOD, TEAR_BELIAL, - TEAR_FIST}; // The variants that point along their flight. constexpr std::array TEAR_ROTATED_VARIANTS = { TEAR_CUPID_BLUE, TEAR_CUPID_BLOOD, TEAR_NAIL, TEAR_PUPULA, TEAR_PUPULA_BLOOD, TEAR_NAIL_BLOOD, TEAR_NEEDLE, TEAR_EYE, TEAR_EYE_BLOOD, TEAR_COIN, TEAR_FIST, TEAR_ICE, TEAR_KEY, TEAR_KEY_BLOOD, TEAR_ERASER, TEAR_SWORD_BEAM, TEAR_TECH_SWORD_BEAM}; -// The variants that stain the floor where they splash. -constexpr std::array TEAR_STAINING_VARIANTS = {TEAR_BLUE, TEAR_GLAUCOMA, TEAR_GODS_FLESH, TEAR_HUNGRY}; // The variants that play BloodTear%d, Tooth%dMove, Rotate%d or Stone%dMove rather than RegularTear%d. constexpr std::array BLOOD_ANIMATION_VARIANTS = {TEAR_BLOOD, TEAR_CUPID_BLOOD, TEAR_PUPULA_BLOOD, TEAR_GODS_FLESH_BLOOD, TEAR_EYE_BLOOD, TEAR_GLAUCOMA_BLOOD}; @@ -331,53 +330,27 @@ struct UnhandledFlag const char* name = nullptr; }; -constexpr std::array UPDATE_UNHANDLED_FLAGS = {{ - {TEAR_DETONATE, "Entity_Tear::Update 006670f0: a detonating tear"}, - {TEAR_LASERSHOT, "Entity_Tear::Update 006670f0: a laser shot tear"}, - {TEAR_HYDROBOUNCE, "Entity_Tear::Update 006670f0: a bouncing water tear"}, - {TEAR_EXPLOSIVE, "Entity_Tear::Update 006670f0: an explosive tear"}, - {TEAR_BURSTSPLIT, "Entity_Tear::Update 006670f0: Haemolacria's burst"}, - {TEAR_ORBIT, "Entity_Tear::Update 006670f0: an orbiting tear"}, - {TEAR_ORBIT_ADVANCED, "Entity_Tear::Update 006670f0: an orbiting tear"}, - {TEAR_FETUS_FLAG, "Entity_Tear::Update 006670f0: a fetus tear"}, - {TEAR_ATTRACTOR, "Entity_Tear::Update 006670f0: Strange Attractor's pull"}, - {TEAR_STICKY, "Entity_Tear::Update 006670f0: a sticking tear"}, - {TEAR_SPORE_FLAG, "Entity_Tear::Update 006670f0: a sticking tear"}, - {TEAR_BOOGER_FLAG, "Entity_Tear::Update 006670f0: a sticking tear"}, - {TEAR_GLOW, "Entity_Tear::Update 006670f0: Godhead's aura"}, - {TEAR_DECELERATE, "Entity_Tear::Update 006670f0: a slowing tear"}, - {TEAR_ACCELERATE, "Entity_Tear::Update 006670f0: a speeding tear"}, - {TEAR_ABSORB, "Entity_Tear::Update 006670f0: Lachryphagy's absorbing"}, - {TEAR_CHAIN, "Entity_Tear::Update 006670f0: a chained tear"}, - {TEAR_POP, "Entity_Tear::Update 006670f0: Pop!'s bouncing"}, - {TEAR_REROLL_ROCK_WISP, "Entity_Tear::Update 006670f0: a rock rerolling tear"}, - {TEAR_CONTINUUM, "Entity_Tear::Update 006670f0: Continuum's wrapping"}, - {TEAR_BOUNCE_WALLSONLY, "Entity_Tear::Update 006670f0: a wall bouncing tear"}, - {TEAR_INTERVAL_FLAGS, "Entity_Tear::Update 006670f0: flags swapped on an interval"}, - {TEAR_INTERVAL_SPEED, "Entity_Tear::Update 006670f0: a speed reset on an interval"}, - {TEAR_PARENT_STEER, "Entity_Tear::Update 006670f0: a tear steering to its parent"}, -}}; - -constexpr std::array HIT_UNHANDLED_FLAGS = {{ - {TEAR_COIN_DROP_DEATH, "Entity_Tear::ApplyTearFlagEffects 0067af60: a drop on death"}, - {TEAR_CARD_DROP_DEATH, "Entity_Tear::ApplyTearFlagEffects 0067af60: a drop on death"}, - {TEAR_RUNE_DROP_DEATH, "Entity_Tear::ApplyTearFlagEffects 0067af60: a drop on death"}, - {TEAR_ECOLI, "Entity_Tear::ApplyTearFlagEffects 0067af60: E. Coli's poop"}, +constexpr std::array HIT_UNHANDLED_FLAGS = {{ {TEAR_ENEMY_TO_WISP, "Entity_Tear::ApplyTearFlagEffects 0067af60: an enemy turned to a wisp"}, {TEAR_REROLL_ENEMY, "Entity_Tear::ApplyTearFlagEffects 0067af60: an enemy rerolled"}, {TEAR_MOM_STOMP_WISP, "Entity_Tear::ApplyTearFlagEffects 0067af60: Mom's stomp"}, }}; -// The splash a dying tear leaves: its poof and its sound. -struct TearSplash +// The drops a hit's flags mark its enemy to leave: a red heart one time in three, and the coin, card and rune drops +// on death, each through a harmless hit carrying the drop. +struct HitDrop { - float pitch = 1; - float volume = 1; - int effect = 0; - int sound = 0; - int subType = 0; + uint64_t damageFlag = 0; + int flag = 0; }; +constexpr std::array HIT_DROPS = {{ + {DAMAGE_SPAWN_RED_HEART, TEAR_HP_DROP}, + {DAMAGE_SPAWN_COIN, TEAR_COIN_DROP_DEATH}, + {DAMAGE_SPAWN_CARD, TEAR_CARD_DROP_DEATH}, + {DAMAGE_SPAWN_RUNE, TEAR_RUNE_DROP_DEATH}, +}}; + template static bool is_listed(const std::array& list, int value) { @@ -399,7 +372,7 @@ static float timescale_factor(float factor, float timeScale) } // Whether the current room is a crawlspace, where tears drop under gravity. -static bool is_crawlspace() +bool tear_room_is_crawlspace() { return g_game->room->roomType == ROOM_DUNGEON; } @@ -438,7 +411,7 @@ static void streak_end(Entity_Player& player) } // Vector::Rotated: a vector turned by an angle in degrees. -static Vector vector_rotate(Vector v, float degrees) +Vector tear_vector_rotate(Vector v, float degrees) { float angle = degrees * DEGREES_TO_RADIANS; return vector_make(v.x * std::cos(angle) - v.y * std::sin(angle), v.x * std::sin(angle) + v.y * std::cos(angle)); @@ -477,7 +450,7 @@ void Entity_Tear::Init(int entityType, int entityVariant, int entitySubType, uin height = TEAR_HEIGHT_START; fallingSpeed = (fallSpread - 0.5f) * TEAR_FALL_SPREAD; posOffset.y = get_height_offset_y(TEAR_HEIGHT_START); - if (is_crawlspace()) posOffset.y = CRAWLSPACE_OFFSET_Y; + if (tear_room_is_crawlspace()) posOffset.y = CRAWLSPACE_OFFSET_Y; homingFriction = TEAR_HOMING_FRICTION; fScale = 1; @@ -529,8 +502,9 @@ void Entity_Tear::Init(int entityType, int entityVariant, int entitySubType, uin lua_engine_get().PostTearInit(this); } -// 006670f0 Flies the tear for a frame, or splashes and removes it once it has died. While held it bobs at its -// parent, while waiting it hovers until its player stops firing, and its flags steer, grow, shrink and split it. +// 006670f0 Flies the tear for a frame, or splashes and removes it once it has died (a Chaos Card stuck in a wall +// stays). While held it bobs at its parent, while waiting it hovers until its player stops firing, and its flags +// steer, grow, shrink, split, link and stick it. void Entity_Tear::Update() { if (isFireSoundPending) @@ -539,38 +513,31 @@ void Entity_Tear::Update() isFireSoundPending = false; } if (tearFlags[TEAR_LUDOVICO] && (subtype & LUDOVICO_CHILD) && !parent) return Remove(); - if (!is_listed(TEAR_PLAIN_VARIANTS, variant)) - reconstruction_missing("Entity_Tear::Update 006670f0: this tear variant's flight and splash"); - Room& room = *g_game->room; + Entity_Player* player = GetRootPlayer(); speedMultiplier = g_game->room->GetTimeScale(this); - if (room.HasSlowDown()) speedMultiplier *= ROOM_SLOWDOWN_SCALE; + if (g_game->room->HasSlowDown()) speedMultiplier *= ROOM_SLOWDOWN_SCALE; if (hold_update()) return; - if (is_crawlspace() && height >= CRAWLSPACE_HEIGHT_MAX && updateTime > tearRange * CRAWLSPACE_RANGE_SHARE && + detonate_update(player); + if (tear_room_is_crawlspace() && height >= CRAWLSPACE_HEIGHT_MAX && updateTime > tearRange * CRAWLSPACE_RANGE_SHARE && !tearFlags[TEAR_LUDOVICO]) { isDead = true; deathFlags = TEAR_DEATH_FORCED; } if (is_gfuel_nail(variant)) tearFlags.reset(TEAR_LASERSHOT); - unhandled_check(tearFlags, UPDATE_UNHANDLED_FLAGS); wait_update(); death_creep_spawn(); tech_zero_update(); - if (laserShotLaser) + lasershot_update(); + float verticalMotion = ludovico_hydrobounce_update(); + if (isDead && variant != TEAR_CHAOS_CARD) { - isVisible = true; - entityCollisionClass = ENTCOLL_ALL; - laserShotLaser->Remove(); - laserShotLaser = nullptr; + death_update(); + if (isDead) return; } - if (isDead) return death_update(); - - flight_update(); - if (is_crawlspace() && !room.IsPositionInRoom(pos, CRAWLSPACE_ROOM_MARGIN)) Remove(); - if (room.HasSlowDown()) SetColor(SLOWDOWN_COLOR, SLOWDOWN_COLOR_FRAMES, COLOR_PRIORITY_TOP, false, true); - lua_engine_get().PostTearUpdate(this); + flight_update(verticalMotion); } // Counts down a held tear, pinning it bobbing at its parent and updating it there. Whether it is still held. @@ -619,17 +586,20 @@ void Entity_Tear::wait_update() SetHeight(height + ((waitFrames / HOVER_BOB_FRAMES & 1) == 0 ? HOVER_HEIGHT_BOB : -HOVER_HEIGHT_BOB)); } -// Leaves the creep a dying tear's flags call for: Mysterious Liquid's green and It Hurts' red, sized by the tear. -// An explosive tear or Bob's head leaves none. +// Leaves the creep a dying tear's flags call for: Mysterious Liquid's green (a Ludovico tear's every fifth frame +// too) and It Hurts' red, sized by the tear. An explosive tear or Bob's head leaves none where it dies. void Entity_Tear::death_creep_spawn() { - if (!isDead || tearFlags[TEAR_EXPLOSIVE] || variant == TEAR_BOBS_HEAD) return; + bool isBlast = isDead && (tearFlags[TEAR_EXPLOSIVE] || variant == TEAR_BOBS_HEAD); + bool isGreen = tearFlags[TEAR_MYSTERIOUS_LIQUID_CREEP] && + (isDead || (tearFlags[TEAR_LUDOVICO] && IsFrame(CREEP_LUDOVICO_FRAMES, (int)index))); + bool isRed = tearFlags[TEAR_BLOOD_CREEP] && isDead; + if (isBlast) return; - for (int flag : {TEAR_MYSTERIOUS_LIQUID_CREEP, TEAR_BLOOD_CREEP}) + for (int creepVariant : {EFFECT_PLAYER_CREEP_GREEN, EFFECT_PLAYER_CREEP_RED}) { - if (!tearFlags[flag]) continue; + if (!(creepVariant == EFFECT_PLAYER_CREEP_GREEN ? isGreen : isRed)) continue; Vector position = g_game->room->GetClampedPosition(pos, CREEP_MARGIN); - int creepVariant = flag == TEAR_BLOOD_CREEP ? EFFECT_PLAYER_CREEP_RED : EFFECT_PLAYER_CREEP_GREEN; Entity* creep = g_game->Spawn({.position = position, .spawner = spawnerEntity, .type = ENTITY_EFFECT, .variant = creepVariant, .seed = Random()}); creep->sprite.scale = vector_make(CREEP_SCALE * fScale, CREEP_SCALE * fScale); @@ -637,145 +607,25 @@ void Entity_Tear::death_creep_spawn() } } -// The splash of a dying tear by its variant: a bullet poof for the blood-like ones, a tear poof sized by its scale -// (the larger one above the floor) for the rest, and the sword beams' own. -static TearSplash splash_get(Entity_Tear& tear) +// FUN_00665a90: takes an entity off a hit list so the tear can hit it again. +static void hit_list_remove(std::vector& hitList, Entity& entity) { - TearSplash splash; - - if (tear.variant == TEAR_SWORD_BEAM || tear.variant == TEAR_TECH_SWORD_BEAM) - { - splash.sound = tear.variant == TEAR_SWORD_BEAM ? SOUND_SWORD_BEAM_IMPACT : SOUND_TECH_SWORD_BEAM_IMPACT; - splash.pitch = random_unit() * SWORD_BEAM_PITCH_SPREAD + SWORD_BEAM_PITCH; - splash.effect = EFFECT_TEAR_POOF_A; - splash.subType = SWORD_BEAM_POOF_SUBTYPE; - splash.volume = SWORD_BEAM_VOLUME; - } - else if (is_listed(TEAR_BULLET_POOF_VARIANTS, tear.variant)) - { - splash.effect = EFFECT_BULLET_POOF; - splash.sound = SOUND_TEAR_IMPACTS; - } - else if (tear.fScale < POOF_SCALE_SMALL) - { - splash.volume = POOF_VOLUME_TINY; - splash.sound = SOUND_SPLATTER; - splash.effect = EFFECT_TEAR_POOF_VERYSMALL; - } - else if (tear.fScale < POOF_SCALE_LARGE) - { - splash.volume = POOF_VOLUME_SMALL; - splash.sound = SOUND_SPLATTER; - splash.effect = EFFECT_TEAR_POOF_SMALL; - } - else - { - bool isHigh = tear.height <= TEAR_FLOOR_HEIGHT; - splash.sound = isHigh ? SOUND_TEAR_IMPACTS : SOUND_SPLATTER; - splash.effect = isHigh ? EFFECT_TEAR_POOF_A : EFFECT_TEAR_POOF_B; - } - return splash; + uint32_t key = entity.GetHitListIndex(); + auto found = std::lower_bound(hitList.begin(), hitList.end(), key); + if (found != hitList.end() && *found == key) hitList.erase(found); } -// Splashes the dead tear: its sound, Cricket's Body's four pieces, its poof in its color at its height, the stains -// some leave, then removes it. Game::Spawn returning nothing crashes the original. This skips the poof. -void Entity_Tear::death_update() -{ - TearSplash splash = splash_get(*this); - if (splash.sound) npc_sound_play(splash.sound, splash.volume, SOUND_DELAY, splash.pitch); - if (tearFlags[TEAR_QUADSPLIT]) quadsplit_fire(); - - uint32_t seed = Random(); - Entity* poof = g_game->Spawn({.position = pos, .spawner = this, .subType = splash.subType, .type = ENTITY_EFFECT, - .variant = splash.effect, .seed = seed}); - if (poof) - { - poof->posOffset = posOffset; - if (splash.effect != EFFECT_TEAR_POOF_SMALL && splash.effect != EFFECT_TEAR_POOF_VERYSMALL) - { - bool isPupula = variant == TEAR_PUPULA || variant == TEAR_PUPULA_BLOOD; - float scale = fScale * (isPupula ? POOF_SCALE_SMALL : POOF_SCALE_LARGE); - poof->sprite.scale = vector_make(scale, scale); - poof->sprite.rotation = (float)random_below(4) * RIGHT_ANGLE; - } - poof->SetColor(sprite.color, -1, COLOR_PRIORITY_TOP, false, true); - if (is_remote_player(spawnerEntity ? spawnerEntity->ToPlayer() : nullptr)) - reconstruction_missing("Entity_Tear::Update 006670f0: a remote player's faded splash"); - } - if (is_listed(TEAR_STAINING_VARIANTS, variant)) blood_stains_spawn(); - Remove(); -} - -// Cricket's Body: four pieces at a random angle and its right angles, at the dying tear's speed (10 when it barely -// moved), from where it was a frame ago. They fly a little lower and slower, smaller and with half the damage. -void Entity_Tear::quadsplit_fire() -{ - float speedSquared = vector_length_squared(velocity); - Vector direction = vector_scale(random_direction(), speedSquared < QUADSPLIT_SLOW_SQUARED ? QUADSPLIT_SLOW_SPEED - : vector_length(velocity)); - TearFlags flags = tearFlags; - for (int dropped : {TEAR_QUADSPLIT, TEAR_SPLIT, TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_ABSORB, TEAR_HYDROBOUNCE, - TEAR_FETUS_FLAG}) - flags.reset(dropped); - - for (int i = 0; i < QUADSPLIT_PIECES; i++) - { - Vector pieceVelocity = i < 2 ? direction : vector_make(direction.y, -direction.x); - if (i & 1) pieceVelocity = vector_scale(pieceVelocity, -1); - Entity_Player* player = GetRootPlayer(); - int pieceVariant = variant == TEAR_FETUS ? TEAR_BLOOD : variant; - Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = pieceVelocity, - .spawner = spawnerEntity, .type = type, .variant = pieceVariant, - .seed = Random()}); - Entity_Tear& piece = *spawned->ToTear(); - - piece.SetHeight((player ? player->tearHeight : PLAYER_TEAR_HEIGHT) * QUADSPLIT_HEIGHT_SHARE); - piece.fallingAccel = fallingAccel; - float playerFall = g_game->GetPlayer(0)->tearFallingSpeed; - if (playerFall > 0) playerFall *= QUADSPLIT_FALL_SHARE; - piece.fallingSpeed = random_unit() * TEAR_FALL_SPREAD - playerFall; - piece.SetCollisionDamage(collisionDamage * QUADSPLIT_DAMAGE); - piece.SetTearFlags(flags); - piece.SetScale(fScale * QUADSPLIT_SCALE); - piece.SetColor(sprite.color, -1, COLOR_PRIORITY_TOP, false, true); - piece.parent = parent; - piece.Update(); - } -} - -// Leaves up to four faint stains around the splash, Eve's Mascara's darker and Number One's yellow. -void Entity_Tear::blood_stains_spawn() -{ - int count = random_below(STAIN_COUNT_MAX); - Entity_Player* player = GetRootPlayer(); - - for (int i = 0; i < count; i++) - { - uint32_t seed = Random(); - Vector direction = random_direction(); - float distance = random_unit() * STAIN_SPREAD; - Vector position = vector_add(pos, vector_scale(direction, distance)); - Entity* stain = g_game->Spawn( - {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = seed}); - if (!stain) continue; - - ColorMod color = STAIN_COLOR; - stain->sprite.scale = vector_make(STAIN_SCALE, STAIN_SCALE); - if (player && player->HasCollectible(COLLECTIBLE_EVES_MASCARA)) - color._tint[3] = random_unit() * MASCARA_ALPHA_SPREAD + MASCARA_ALPHA; - else if (player && player->HasCollectible(COLLECTIBLE_NUMBER_ONE)) color = NUMBER_ONE_STAIN_COLOR; - stain->SetColor(color, -1, COLOR_PRIORITY_TOP, false, true); - stain->Update(); - } -} - -// Flies the living tear: its flags steer and resize it, it points along its flight, dies on the floor or a wall (or -// bounces), sizes its sprite, moves, turns toward its target, and falls by its speed and acceleration. -void Entity_Tear::flight_update() +// Flies the living tear in the original's order: its flags steer, orbit, home, resize and wiggle it, pull things in, +// burn and eat around it, link and bounce it, it points along its flight, dies on the floor or a wall (or bounces, +// sticks or opens what it hits), sizes its sprite, moves, follows what steers it or what it stuck in, swaps its +// interval flags, falls, wraps and tints. +void Entity_Tear::flight_update(float verticalMotion) { Entity_Player* player = GetRootPlayer(); square_turn(); - homing_update(); + orbit_update(); + if (tearFlags[TEAR_FETUS_FLAG]) fetus_update(); + else homing_update(); occult_steer(); float scaleFactor = size_flags_update(); spectral_update(); @@ -783,39 +633,74 @@ void Entity_Tear::flight_update() if (tearFlags[TEAR_WIGGLE]) wiggle_apply(worm_multiplier_get(player, TEAR_WIGGLE)); if (tearFlags[TEAR_SPIRAL]) spiral_apply(worm_multiplier_get(player, TEAR_SPIRAL)); if (tearFlags[TEAR_BIG_SPIRAL]) big_spiral_apply(worm_multiplier_get(player, TEAR_BIG_SPIRAL)); + attractor_pull(); if (tearFlags[TEAR_PULSE]) { float strength = worm_multiplier_get(player, TEAR_PULSE) * PULSE_STRENGTH; - scaleFactor *= (std::sin((float)FrameCount() * PULSE_RATE) + PULSE_OFFSET) * strength + PULSE_BASE; + if (!tearFlags[TEAR_LUDOVICO]) + scaleFactor *= (std::sin((float)FrameCount() * PULSE_RATE) + PULSE_OFFSET) * strength + PULSE_BASE; + else if (parent && parent->is_player()) + scaleFactor *= (std::sin((float)FrameCount() * PULSE_LUDOVICO_RATE) + PULSE_LUDOVICO_OFFSET) * strength + + PULSE_LUDOVICO_BASE; } - rotation_update(player); - + float unstuckScale = scaleFactor; + if ((tearFlags[TEAR_STICKY] || tearFlags[TEAR_SPORE_FLAG]) && stickTarget && stickTimer > 0) + { + float growth = 1 - (float)stickTimer / STICK_GROWTH_FRAMES; + scaleFactor += growth + growth; + } + rotation_update(player, verticalMotion); + trail_spawn(); + glow_burn(); + speed_flags_update(); + absorb_update(); + chain_update(); + tractor_beam_follow(); if (HasEntityFlags(FLAG_NO_SPIKE_DAMAGE)) { if (updateTime >= LAUNCH_DRAG_TIME) ClearEntityFlags(FLAG_NO_SPIKE_DAMAGE); - else friction *= updateTime / LAUNCH_DRAG_TIME * (1 - LAUNCH_DRAG_FRICTION) + LAUNCH_DRAG_FRICTION; + else friction *= lerp_clamped(updateTime, 0, LAUNCH_DRAG_TIME, LAUNCH_DRAG_FRICTION, 1); } - tractor_beam_follow(); + pop_update(); + bool isLudovico = tearFlags[TEAR_LUDOVICO]; - bool isBouncing = tearFlags[TEAR_BOUNCE] || variant == TEAR_FIRE; - if (height > TEAR_FLOOR_HEIGHT && !isLudovico) floor_hit(); + bool isOnFloor = height > TEAR_FLOOR_HEIGHT || (tearFlags[TEAR_HYDROBOUNCE] && fallingSpeed + height > TEAR_FLOOR_HEIGHT); + bool isBouncing = tearFlags[TEAR_BOUNCE] || tearFlags[TEAR_BOUNCE_WALLSONLY] || variant == TEAR_FIRE; + if (isOnFloor && !isLudovico) floor_hit(); else if ((isBouncing && !g_game->room->IsBeastDungeon()) || (isLudovico && (subtype & LUDOVICO_FAST))) bounce_hit(); + else if (tearFlags[TEAR_REROLL_ROCK_WISP]) + reconstruction_missing("Entity_Tear::Update 006670f0: a rock rerolling tear"); else grid_hit(); + if (variant == TEAR_CHAOS_CARD) chaos_card_stick(); + key_open(); if (isLudovico) scaleFactor *= ludovico_update(); if (g_game->deathmatchManager.is_active()) reconstruction_missing("Entity_Tear::Update 006670f0: the versus mode's tear reflections"); fScale = std::max(scaleFactor * baseScale, TEAR_SCALE_MIN); ResetSpriteScale(); - if (g_game->seedEffects.HasSeedEffect(SEED_BLACK_ISAAC)) - reconstruction_missing("Entity_Tear::Update 006670f0: Black Isaac's tear color"); + fire_update(); + black_seed_paint(); Vector previous = pos; Entity::Update(); - turn_horizontal_update(previous); - if (isLudovico && is_not_familiar_spawned() && !tearFlags[TEAR_CONTINUUM]) pos = g_game->room->GetClampedPosition(pos, 0); - posDisplacement = vector_sub(pos, previous); - if (!isLudovico) fall_update(); + if (!steer_update()) + { + turn_horizontal_update(previous); + sticky_update(unstuckScale); + if (tearFlags[TEAR_BOOGER_FLAG] && IsFrame(BOOGER_HIT_FRAMES, (int)index) && stickTarget && + stickTarget->IsVulnerableEnemy(nullptr)) + hit_list_remove(hitList, *stickTarget); + if (isLudovico && is_not_familiar_spawned() && !tearFlags[TEAR_CONTINUUM]) + pos = g_game->room->GetClampedPosition(pos, 0); + interval_update(); + posDisplacement = vector_sub(pos, previous); + fall_update(); + if (tear_room_is_crawlspace() && !g_game->room->IsPositionInRoom(pos, CRAWLSPACE_ROOM_MARGIN)) Remove(); + continuum_update(); + if (g_game->room->HasSlowDown()) SetColor(SLOWDOWN_COLOR, SLOWDOWN_COLOR_FRAMES, TEAR_COLOR_PRIORITY, false, true); + } + lua_engine_get().PostTearUpdate(this); } // Technology Zero: a tear links to the nearest other tear (one not linked back to it) with an electric beam its player @@ -983,7 +868,7 @@ void Entity_Tear::ludovico_refresh(Entity_Player* player, float speed, int ticks params.tearFlags.set(TEAR_SPECTRAL); } collisionDamage = params.tearDamage; - SetColor(params.tearColor, -1, COLOR_PRIORITY_TOP, false, true); + SetColor(params.tearColor, -1, TEAR_COLOR_PRIORITY, false, true); TearFlags flags = params.tearFlags; flags.reset(TEAR_BOUNCE); flags.set(TEAR_LUDOVICO); @@ -1014,7 +899,7 @@ void Entity_Tear::ludovico_child_update() float sway = std::sin(((float)FrameCount() + (float)index * LUDOVICO_SWAY_INDEX) * LUDOVICO_SWAY_RATE); pos = vector_add(main->pos, vector_resized(parentOffset, vector_length(parentOffset) * (sway * LUDOVICO_SWAY + 1))); float drift = ((float)(index % LUDOVICO_DRIFT_SPREAD) + 0) * LUDOVICO_DRIFT_STEP + LUDOVICO_DRIFT_BASE; - parentOffset = vector_rotate(parentOffset, drift); + parentOffset = tear_vector_rotate(parentOffset, drift); } if (!parent) Remove(); } @@ -1030,19 +915,19 @@ void Entity_Tear::ludovico_ring_update() { Entity_Tear& orbiter = *ring[i]; orbiter.velocity = velocity; - float angle = (float)i * FULL_TURN / (float)ring.size() + (float)FrameCount() * LUDOVICO_ORBIT_SPIN; + float angle = (float)i * TEAR_FULL_TURN / (float)ring.size() + (float)FrameCount() * LUDOVICO_ORBIT_SPIN; float radius = size + size; if (orbiter.FrameCount() < LUDOVICO_RING_GROW_FRAMES) radius *= (float)orbiter.FrameCount() / LUDOVICO_RING_GROW_FRAMES; Vector spot = vector_add(pos, vector_scale(vector_from_angle(angle), radius)); orbiter.AddVelocity_divided(vector_sub(spot, orbiter.pos), false); orbiter.SetScale(fScale * LUDOVICO_CHILD_SCALE); - orbiter.SetColor(sprite.color, -1, COLOR_PRIORITY_TOP, false, true); + orbiter.SetColor(sprite.color, -1, TEAR_COLOR_PRIORITY, false, true); TearFlags flags = tearFlags; flags.reset(TEAR_EXPLOSIVE); orbiter.SetTearFlags(flags); orbiter.entityGridCollisionClass = GRIDCOLL_NONE; orbiter.SetCollisionDamage(collisionDamage); - orbiter.rotation = angle_wrap(angle + RIGHT_ANGLE); + orbiter.rotation = angle_wrap(angle + TEAR_RIGHT_ANGLE); } if (parent && parent->IsFamiliar()) @@ -1127,45 +1012,13 @@ void Entity_Tear::square_turn() } } -// The enemy a homing tear picks every fourth frame: a vulnerable one ahead of it that it has not hit, each skipped -// half the time, scored by its distance plus a random part. A tear that collides with the grid needs a clear line. -static Entity* homing_target_find(Entity_Tear& tear) -{ - Entity* best = nullptr; - float bestScore = HOMING_SCORE_NONE; - Vector ahead = vector_add(tear.pos, vector_scale(tear.velocity, HOMING_LOOK_AHEAD)); - - for (Entity* enemy : entity_query_radius(ahead, HOMING_RADIUS, QUERY_ENEMIES)) - { - if (!enemy->IsVulnerableEnemy(nullptr)) continue; - if (tear.spawnerEntity && tear.spawnerEntity->IsDescendantOf(enemy)) continue; - if (enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) continue; - if (EntityList::HitListContains(tear.hitList, *enemy)) continue; - if (enemy->type == ENTITY_PLAYER && static_cast(enemy)->IsInvisible()) continue; - if (random_below(2) == 0) continue; - if (tear.entityGridCollisionClass == GRIDCOLL_BULLET && - !room_check_line(tear.pos, enemy->pos, LINE_MODE_PROJECTILE, 0)) - continue; - - float score = vector_length(vector_sub(ahead, enemy->pos)) + random_unit() * HOMING_RADIUS; - if (score < bestScore) - { - best = enemy; - bestScore = score; - } - } - if (g_game->deathmatchManager.is_active()) - reconstruction_missing("Entity_Tear::Update 006670f0: homing on the versus mode's familiars"); - return best; -} - // Spoon Bender and Brain Worm: drops a target already hit, searches a new one every fourth frame, and a homing tear // pulls toward it, its speed eased by its homing friction. void Entity_Tear::homing_update() { if (!tearFlags[TEAR_HOMING] && !tearFlags[TEAR_TURN_HORIZONTAL]) return; if (target && EntityList::HitListContains(hitList, *target)) target = nullptr; - if (!target && IsFrame(HOMING_SEARCH_FRAMES, (int)index)) target = homing_target_find(*this); + if (!target && IsFrame(TEAR_SEARCH_FRAMES, (int)index)) target = homing_target_find(*this, false); if (!target || !tearFlags[TEAR_HOMING]) return; Vector away = vector_normalized(vector_sub(pos, target->pos)); @@ -1174,38 +1027,54 @@ void Entity_Tear::homing_update() } // Lump of Coal's growth with the distance flown and Proptosis' shrinking damage, which kills the tear once it has -// none left. The factor its scale draws at. +// none left (a fetus shrinks slower). Ludovico's main tear instead grows or shrinks with its distance from its +// parent. The factor its scale draws at. float Entity_Tear::size_flags_update() { float scaleFactor = 1; - bool isLudovico = tearFlags[TEAR_LUDOVICO]; - if (tearFlags[TEAR_GROW] && waitFrames < 1 && !isLudovico) + bool isLudovicoMain = tearFlags[TEAR_LUDOVICO] && is_not_familiar_spawned() && parent; + float parentDistance = isLudovicoMain ? vector_length(vector_sub(parent->pos, pos)) : 0; + if (tearFlags[TEAR_GROW] && !tearFlags[TEAR_LUDOVICO] && waitFrames < 1) { collisionDamage += vector_length(posDisplacement) * GROW_DAMAGE; baseScale += GROW_SCALE; } - if (tearFlags[TEAR_SHRINK] && waitFrames < 1 && updateTime > SHRINK_START && !isLudovico) + else if (tearFlags[TEAR_GROW] && isLudovicoMain) { - float rate = baseDamage / SHRINK_FAST_SHARE < collisionDamage ? SHRINK_FAST : SHRINK_SLOW; - collisionDamage = std::max(collisionDamage - rate * baseDamage, SHRINK_DAMAGE_MIN); - scaleFactor = std::sqrt(collisionDamage / baseDamage); - if (collisionDamage <= SHRINK_DAMAGE_MIN) - { - isDead = true; - deathFlags |= TEAR_DEATH_SHRUNK; - } + scaleFactor = std::clamp(parentDistance, 1.0f, LUDOVICO_GROW_REACH) / LUDOVICO_GROW_REACH + 1; + collisionDamage = scaleFactor * baseDamage; + } + if (!tearFlags[TEAR_SHRINK]) return scaleFactor; + + if (isLudovicoMain) + { + float factor = 1 - std::clamp(parentDistance, 0.0f, LUDOVICO_SHRINK_SPAN) / LUDOVICO_SHRINK_SPAN; + scaleFactor *= factor; + collisionDamage = factor * baseDamage; + } + if (tearFlags[TEAR_LUDOVICO] || waitFrames >= 1 || updateTime <= SHRINK_START) return scaleFactor; + bool isFast = baseDamage / SHRINK_FAST_SHARE < collisionDamage; + float rate = tearFlags[TEAR_FETUS_FLAG] ? (isFast ? SHRINK_FETUS_FAST : SHRINK_FETUS_SLOW) + : (isFast ? SHRINK_FAST : SHRINK_SLOW); + collisionDamage = std::max(collisionDamage - rate * baseDamage, SHRINK_DAMAGE_MIN); + scaleFactor = std::sqrt(collisionDamage / baseDamage); + if (collisionDamage <= SHRINK_DAMAGE_MIN) + { + isDead = true; + deathFlags |= TEAR_DEATH_SHRUNK; } return scaleFactor; } // A spectral tear flies over the grid (Bob's head and the Chaos Card only stop at walls), hurting the poop and fires -// it passes: everything under it the first time it touches any, then now and then. +// it passes (but Ludovico's): everything under it the first time it touches any, then now and then. void Entity_Tear::spectral_update() { if (!tearFlags[TEAR_SPECTRAL]) return; bool isGridBound = variant == TEAR_BOBS_HEAD || variant == TEAR_CHAOS_CARD; entityGridCollisionClass = isGridBound ? GRIDCOLL_WALLS : GRIDCOLL_NONE; + if (tearFlags[TEAR_LUDOVICO]) return; if (!isGridTouched) { if (try_make_bridges(pos)) @@ -1218,10 +1087,11 @@ void Entity_Tear::spectral_update() } // My Reflection: pulls the tear back toward its parent (or the target position), harder at a higher shot speed and a -// shorter range. +// shorter range. Ludovico's and the orbiting tears keep their path. void Entity_Tear::boomerang_pull() { if (!tearFlags[TEAR_BOOMERANG] || !parent) return; + if (tearFlags[TEAR_LUDOVICO] || tearFlags[TEAR_ORBIT] || tearFlags[TEAR_ORBIT_ADVANCED]) return; Vector lift = vector_make(0, BOOMERANG_ANCHOR_LIFT); Vector anchor = vector_is_zero(targetPosition) ? vector_add(parent->pos, lift) : vector_sub(targetPosition, lift); @@ -1233,8 +1103,9 @@ void Entity_Tear::boomerang_pull() } // Points the tear along its flight: Flat Worm stretches it, the rotated variants and the turning layers of its tear -// effect follow the direction it moves and falls, and a boomerang Pupula Duplex tear spins. -void Entity_Tear::rotation_update(Entity_Player* player) +// effect follow the direction it moves and falls (a Ludovico water tear its bob), a boomerang Pupula Duplex tear +// spins, the fetus spins its frames and the G-Fuel missiles trail dust. +void Entity_Tear::rotation_update(Entity_Player* player, float verticalMotion) { sprite.rotation = 0; bool isRotated = false; @@ -1254,21 +1125,38 @@ void Entity_Tear::rotation_update(Entity_Player* player) isRotated = false; } else if (is_listed(TEAR_ROTATED_VARIANTS, variant)) isRotated = true; + if (variant == TEAR_FETUS) fetus_spin(); if (!isRotated && !isEffectRotated) return; Vector direction = velocity; if (waitFrames >= 1) direction = continueVelocity; - else if (fallingAccel > GRAVITY_MIN_ACCEL) direction.y += fallingSpeed; + else if (fallingAccel > GRAVITY_MIN_ACCEL || (tearFlags[TEAR_LUDOVICO] && tearFlags[TEAR_HYDROBOUNCE])) + direction.y += verticalMotion; float angle = vector_angle(direction); if (isRotated) sprite.rotation = angle; - if (!isEffectRotated) return; - for (LayerState& layer : tearEffectANM2.layerStates) - if (layer.bitflags & TEAR_EFFECT_LAYERED) layer.rotation = angle; + if (isEffectRotated) + for (LayerState& layer : tearEffectANM2.layerStates) + if (layer.bitflags & TEAR_EFFECT_LAYERED) layer.rotation = angle; + gfuel_trail_spawn(angle); } -// The tear reached the floor: it dies there, ending its player's streak. +// The tear reached the floor: it dies there, ending its player's streak. A Chaos Card lies there stuck, and a water +// tear bounces back up at a little more than its fall. void Entity_Tear::floor_hit() { + if (variant == TEAR_CHAOS_CARD && !isDead) + { + velocity = {}; + entityGridCollisionClass = GRIDCOLL_NONE; + entityCollisionClass = ENTCOLL_NONE; + sprite.rotation = CHAOS_CARD_FLOOR_ANGLE; + sprite.Play("Stuck"); + } + if (tearFlags[TEAR_HYDROBOUNCE]) + { + fallingSpeed *= HYDROBOUNCE_REBOUND; + SetHeight(TEAR_FLOOR_HEIGHT); + } isDead = true; deathFlags |= TEAR_DEATH_FLOOR; apply_death_flag_effects(nullptr); @@ -1281,8 +1169,9 @@ void Entity_Tear::floor_hit() } } -// The tear hit the grid, or stands on a wall: it dies, hurting the rocks and poop it touches, unless it is spectral. -// Missing anything but poop or TNT ends its player's streak. +// The tear hit the grid, or stands on a wall: it dies, hurting the rocks and poop it touches, unless it is spectral +// or stuck in an enemy (a Chaos Card sticks in the wall instead). Missing anything but poop or TNT ends its player's +// streak. void Entity_Tear::grid_hit() { Room& room = *g_game->room; @@ -1293,9 +1182,12 @@ void Entity_Tear::grid_hit() bool isPlayerWall = collision == COLLISION_WALL_EXCEPT_PLAYER && gridPath < GRID_PATH_TEAR_WALL; if (!isCollidesWithGrid) return; - bool isBlockedOnly = height <= TEAR_GRID_HIT_HEIGHT || tearFlags[TEAR_LUDOVICO]; + bool isBlockedOnly = height <= TEAR_GRID_HIT_HEIGHT || tearFlags[TEAR_LUDOVICO] || variant == TEAR_CHAOS_CARD; if (isBlockedOnly && !isWall && !isPlayerWall) return; + if (variant == TEAR_CHAOS_CARD) return; if (tearFlags[TEAR_SPECTRAL] && variant != TEAR_BOBS_HEAD) return; + bool isSticking = tearFlags[TEAR_STICKY] || tearFlags[TEAR_BOOGER_FLAG] || tearFlags[TEAR_SPORE_FLAG]; + if (isSticking && stickTarget) return; isDead = true; deathFlags |= TEAR_DEATH_GRID; @@ -1323,8 +1215,8 @@ void Entity_Tear::bounce_hit() tearFlags.reset(TEAR_TRACTOR_BEAM); hitList.clear(); Entity_Player* shooter = spawnerEntity ? spawnerEntity->ToPlayer() : nullptr; - npc_sound_play(BOUNCE_SOUND, shooter ? shooter->local_volume_get() : 1, SOUND_DELAY, 1); - if (is_crawlspace()) tearFlags.reset(TEAR_BOUNCE); + npc_sound_play(SOUND_TEAR_BOUNCE, shooter ? shooter->local_volume_get() : 1, TEAR_SOUND_DELAY, 1); + if (tear_room_is_crawlspace()) tearFlags.reset(TEAR_BOUNCE); } // Brain Worm: once the target passes beside the tear it turns a right angle toward it, once. A tear moving away from @@ -1342,24 +1234,32 @@ void Entity_Tear::turn_horizontal_update(Vector previous) if (after < TURN_AWAY && before < TURN_AWAY && !tearFlags[TEAR_HOMING]) target = nullptr; return; } - Vector turned = vector_rotate(direction, RIGHT_ANGLE); + Vector turned = tear_vector_rotate(direction, TEAR_RIGHT_ANGLE); if (vector_dot(turned, toTarget) < 0) turned = vector_scale(turned, -1); velocity = vector_scale(turned, vector_length(velocity)); tearFlags.reset(TEAR_TURN_HORIZONTAL); } -// Lets the flying tear fall by its speed and acceleration, a crawlspace's tears dropping under gravity. +// Lets the flying tear fall by its speed and acceleration, a crawlspace's tears dropping under gravity. A fetus +// hovers over the first quarter of its range, then drops faster. Waiting, Ludovico's, dead, stuck, chained and +// bouncing Pop! tears stay at their height. void Entity_Tear::fall_update() { - if (waitFrames >= 1 || isDead || stickTarget) return; + if (waitFrames >= 1 || tearFlags[TEAR_LUDOVICO] || isDead || stickTarget || tearFlags[TEAR_CHAIN] || is_popping()) + return; - fallingSpeed = speedMultiplier * GRAVITY_PULL + timescale_factor(GRAVITY_FALL_DRAG, speedMultiplier) * fallingSpeed + - speedMultiplier * fallingAccel; + if (!tearFlags[TEAR_FETUS_FLAG]) + fallingSpeed = speedMultiplier * GRAVITY_PULL + timescale_factor(GRAVITY_FALL_DRAG, speedMultiplier) * fallingSpeed + + speedMultiplier * fallingAccel; + else if (updateTime <= tearRange * FETUS_HOVER_SHARE) fallingSpeed = 0; + else + fallingSpeed = timescale_factor(GRAVITY_FALL_DRAG, speedMultiplier) * fallingSpeed + + speedMultiplier * std::max(fallingAccel + FETUS_FALL_ACCEL, 0.0f); SetHeight(speedMultiplier * fallingSpeed + height); - if (!is_crawlspace()) return; + if (!tear_room_is_crawlspace()) return; - if (fallingAccel >= GRAVITY_MIN_ACCEL) velocity.y += fallingAccel; - else if (height > CRAWLSPACE_SINK_HEIGHT) velocity.y += CRAWLSPACE_SINK_SPEED; + if (!tearFlags[TEAR_FETUS_FLAG] && fallingAccel >= GRAVITY_MIN_ACCEL) velocity.y += fallingAccel; + else if (!tearFlags[TEAR_FETUS_FLAG] && height > CRAWLSPACE_SINK_HEIGHT) velocity.y += CRAWLSPACE_SINK_SPEED; if (g_game->room->IsBeastDungeon()) reconstruction_missing("Entity_Tear::Update 006670f0: the Beast's lava"); } @@ -1368,7 +1268,6 @@ void Entity_Tear::fall_update() void Entity_Tear::Interpolate() { if (holdTimer > 0 && parent) pos = vector_add(parent->pos, holdOffset); - if (tearFlags[TEAR_HYDROBOUNCE]) reconstruction_missing("Entity_Tear::Interpolate 00679400: the tear flags' motion"); tractor_beam_follow(); if (tearFlags[TEAR_LASER] && techZeroLaser && techZeroTarget) tech_zero_aim(); if (tearFlags[TEAR_LUDOVICO]) return ludovico_interpolate(); @@ -1379,12 +1278,12 @@ void Entity_Tear::Interpolate() if (tearFlags[TEAR_BIG_SPIRAL]) big_spiral_apply(worm_multiplier_get(player, TEAR_BIG_SPIRAL)); Entity::Interpolate(); if (waitFrames >= 1 || isDead) return; - posOffset.y = is_crawlspace() ? CRAWLSPACE_OFFSET_Y + posOffset.y = tear_room_is_crawlspace() ? CRAWLSPACE_OFFSET_Y : get_height_offset_y(fallingSpeed * speedMultiplier * 0.5f + height); } // The Ludovico part of 00679400: a fast tear may skip a step, the tear moves half its step, the main tear stays in -// the room (unless it wraps) and a cloud tear sways around the main one. Its height stays. +// the room (unless it wraps) and a cloud tear sways around the main one. Its height stays, a water tear bobbing. void Entity_Tear::ludovico_interpolate() { if ((subtype & LUDOVICO_FAST) && HasEntityFlags(FLAG_NO_INTERPOLATE)) @@ -1404,11 +1303,14 @@ void Entity_Tear::ludovico_interpolate() else if (subtype & LUDOVICO_LUNG_BIT) { float drift = (float)(index % LUDOVICO_DRIFT_SPREAD) * LUDOVICO_DRIFT_STEP * LUDOVICO_DRIFT_HALF + LUDOVICO_DRIFT_HALF_BASE; - Vector offset = vector_rotate(parentOffset, drift); + Vector offset = tear_vector_rotate(parentOffset, drift); float frame = (float)(g_game->frameCount - spawnFrame) + HALF_FRAME + (float)index * LUDOVICO_SWAY_INDEX; float sway = std::sin(frame * LUDOVICO_SWAY_RATE); pos = vector_add(main->pos, vector_resized(offset, vector_length(offset) * (sway * LUDOVICO_SWAY + 1))); } + if (!tearFlags[TEAR_HYDROBOUNCE]) return; + float bob = std::sin(((float)(g_game->frameCount - spawnFrame) + HALF_FRAME) * (PI_F / fallingSpeed)); + posOffset.y = std::fabs(bob) * height; } // 006668c0 Wiggle Worm: sways the tear sideways on a wave, odd tears the other way, by half its speed (at most 5). @@ -1520,8 +1422,8 @@ void Entity_Tear::play_fire_sound() bool isSilent = variant == TEAR_CHAOS_CARD || variant == TEAR_FIRE || variant == TEAR_GRIDENT || isFireSoundMuted; bool isFetus = variant == TEAR_FETUS; if (!isSilent && !is_gfuel_nail(variant)) - npc_sound_play(isFetus ? SOUND_FETUS_FIRE : SOUND_TEAR_FIRE, 1, SOUND_DELAY, isFetus ? FETUS_FIRE_PITCH : 1); - if (tearFlags[TEAR_HORN]) npc_sound_play(SOUND_LITTLE_HORN, 1, SOUND_DELAY, 1); + npc_sound_play(isFetus ? SOUND_FETUS_FIRE : SOUND_TEAR_FIRE, 1, TEAR_SOUND_DELAY, isFetus ? FETUS_FIRE_PITCH : 1); + if (tearFlags[TEAR_HORN]) npc_sound_play(SOUND_LITTLE_HORN, 1, TEAR_SOUND_DELAY, 1); if (tearFlags[TEAR_ORBIT]) { if (fallingSpeed < 0) fallingSpeed *= ORBIT_FALL_SCALE; @@ -1538,7 +1440,7 @@ void Entity_Tear::play_fire_sound() fallingSpeed *= BOOMERANG_FALL_SCALE; fallingAccel = (fallingAccel + BOOMERANG_ACCEL_OFFSET) * BOOMERANG_ACCEL_SCALE - BOOMERANG_ACCEL_OFFSET; } - if (!is_crawlspace()) return; + if (!tear_room_is_crawlspace()) return; pos.y -= CRAWLSPACE_FIRE_RAISE; if (fallingAccel > 0 && velocity.y < std::fabs(velocity.x)) velocity.y = fallingSpeed * 0.5f + velocity.y; @@ -1570,7 +1472,7 @@ void Entity_Tear::SetHeight(float tearHeight) { height = tearHeight; posOffset.y = get_height_offset_y(tearHeight); - if (!is_crawlspace()) return; + if (!tear_room_is_crawlspace()) return; posOffset.y = CRAWLSPACE_OFFSET_Y; if (tearHeight > CRAWLSPACE_HEIGHT_MAX) height = CRAWLSPACE_HEIGHT_MAX; @@ -1626,12 +1528,18 @@ void Entity_Tear::SetTearFlags(TearFlags flags) tearFlags = flags; } +// The opacity the options fade a remote online player's shots to. +float tear_remote_opacity_get() +{ + return (float)g_manager->optionsConfig.onlinePlayerOpacity * REMOTE_OPACITY_STEP + REMOTE_OPACITY_MIN; +} + // The opacity a remote player's shots fade to, or one for local shots and in versus. -static float shot_alpha_get(Entity_Tear& tear) +float tear_shot_alpha_get(Entity_Tear& tear) { if (!is_remote_player(tear.spawnerEntity ? tear.spawnerEntity->ToPlayer() : nullptr)) return 1; if (g_game->deathmatchManager.is_active()) return 1; - return (float)g_manager->optionsConfig.onlinePlayerOpacity * 0.09f + 0.1f; + return tear_remote_opacity_get(); } // 0067a080 Turns it back the way it came for a new owner, as a fart or a familiar knocks it: no flags or interval flags, @@ -1647,91 +1555,6 @@ void Entity_Tear::Deflect(Entity* newSpawner, const Vector& newVelocity) if (fallingAccel > 0 && fallingSpeed > 0) fallingSpeed = -fallingSpeed * DEFLECT_REBOUND; } -// 00676be0 Applies what its flags do when it dies above the floor: Parasite splits it in two and Compound Fracture -// into two shards. A tear bouncing back up off water splits too, without explosions. -void Entity_Tear::apply_death_flag_effects(Entity*) -{ - bool isRising = isDead && tearFlags[TEAR_HYDROBOUNCE] && fallingSpeed < 0; - bool isAbove = height < TEAR_FLOOR_HEIGHT; - if (tearFlags[TEAR_SPLIT] && collisionDamage > SPLIT_DAMAGE_MIN && (isAbove || isRising)) split_fire(isRising); - if (tearFlags[TEAR_BONE_FLAG] && isAbove) bone_shards_fire(isRising); - if (tearFlags[TEAR_JACOBS] && isAbove) - reconstruction_missing("Entity_Tear::apply_death_flag_effects 00676be0: Jacob's Ladder's lightning"); - if (tearFlags[TEAR_RIFT]) - reconstruction_missing("Entity_Tear::apply_death_flag_effects 00676be0: Ocular Rift's rift"); -} - -// What every piece a dying tear breaks into shares: its color (faded for a remote player), its flags, its parent, -// and a first update. -void Entity_Tear::child_setup(Entity_Tear& child, TearFlags flags, float alpha) -{ - ColorMod color = sprite.color; - color._tint[3] *= alpha; - child.SetColor(color, -1, COLOR_PRIORITY_TOP, false, true); - child.SetTearFlags(flags); - child.parent = parent; - child.Update(); -} - -// Parasite: two plain tears out to the sides from where the tear was a frame ago, lower and with half its damage -// and size. Rising off water they start at the floor with a quarter. -void Entity_Tear::split_fire(bool isRising) -{ - TearFlags flags = tearFlags; - for (int dropped : {TEAR_LUDOVICO, TEAR_ABSORB, TEAR_HYDROBOUNCE, TEAR_FETUS_FLAG}) flags.reset(dropped); - if (isRising) flags.reset(TEAR_EXPLOSIVE); - float alpha = shot_alpha_get(*this); - - for (int i = 0; i < 2; i++) - { - Vector side = i == 0 ? vector_make(velocity.y, -velocity.x) : vector_make(-velocity.y, velocity.x); - Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = side, - .spawner = spawnerEntity, .type = ENTITY_TEAR, .variant = TEAR_BLUE, - .seed = Random()}); - Entity_Tear& piece = *spawned->ToTear(); - piece.SetHeight(isRising ? CRAWLSPACE_HEIGHT_MAX : height / SPLIT_HEIGHT_SHARE); - piece.fallingSpeed = fallingSpeed; - if (isRising) piece.fallingAccel = SPLIT_RISING_ACCEL; - piece.SetCollisionDamage(collisionDamage * (isRising ? SPLIT_RISING_DAMAGE : SPLIT_DAMAGE)); - piece.baseScale = std::max(fScale * SPLIT_SCALE, TEAR_SCALE_MIN); - piece.fScale = piece.baseScale; - piece.ResetSpriteScale(); - child_setup(piece, flags, alpha); - } -} - -// Compound Fracture: two shards (bone tears, broken looking ones from a bone tear) flying off at random at the -// tear's speed with half its damage. -void Entity_Tear::bone_shards_fire(bool isRising) -{ - TearFlags flags = tearFlags; - for (int dropped : {TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_FETUS_FLAG}) flags.reset(dropped); - if (isRising) flags.reset(TEAR_EXPLOSIVE); - float alpha = shot_alpha_get(*this); - int shardVariant = variant == TEAR_FETUS ? TEAR_BONE : variant; - - for (int i = 0; i < BONE_SHARDS; i++) - { - float angle = random_unit() * RANDOM_HALF_TURN; - angle += angle; - float speed = vector_length(velocity); - Vector shardVelocity = vector_make(std::cos(angle) * speed, std::sin(angle) * speed); - Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = shardVelocity, - .spawner = spawnerEntity, .type = ENTITY_TEAR, .variant = shardVariant, - .seed = Random()}); - Entity_Tear& shard = *spawned->ToTear(); - if (shardVariant == TEAR_BONE) - { - shard.sprite.ReplaceSpritesheet(0, BROKEN_BONE_SHEET); - shard.sprite.LoadGraphics(); - } - shard.SetHeight(height); - shard.fallingSpeed = fallingSpeed; - shard.SetCollisionDamage(collisionDamage * BONE_DAMAGE); - child_setup(shard, flags, alpha); - } -} - // Whether a variant plays an animation sized to its scale. static bool is_sized_variant(int variant) { @@ -1753,6 +1576,52 @@ static std::string sized_animation_name(int variant, int number) return name; } +// The scythe's and Mom's Bracelet rock's Rotate%d by their size (the first of five at least their scale, else the +// sixth), carried on at the same frame or started at a random one. The scythe doubles its scale for its reach. +// The scale its layers draw at: its own. +float Entity_Tear::spinning_animation_update() +{ + auto found = std::find_if(SPINNING_ANIMATION_SCALES.begin(), SPINNING_ANIMATION_SCALES.end(), + [this](float scale) { return fScale <= scale; }); + std::string name = "Rotate" + std::to_string(found - SPINNING_ANIMATION_SCALES.begin() + 1); + float layerScale = fScale; + if (sprite.animState.animData && sprite.animState.isPlaying) sprite.SetAnimation(name, SWITCH_KEEP_FRAME); + else + { + sprite.Play(name); + int startFrame = random_below(sprite.animState.animData ? sprite.animState.animData->length : 0); + if (sprite.animState.animData) sprite.animState.SetFrameFloat((float)startFrame); + } + if (variant == TEAR_SCHYTHE) fScale += fScale; + return layerScale; +} + +// The fetus' Rotate%d by its size grown by a quarter (the first of five at least it), kept at its frame when only its +// size changed, else at a random one, and held still for the spin to turn. The scale its layers draw at, its scale +// over the animation's. +float Entity_Tear::fetus_animation_update() +{ + fScale += FETUS_ANIMATION_GROWTH; + auto found = std::find_if(FETUS_ANIMATION_SCALES.begin(), FETUS_ANIMATION_SCALES.end() - 1, + [this](float scale) { return fScale <= scale; }); + int number = (int)(found - FETUS_ANIMATION_SCALES.begin()); + int previous = scaleAnimNum; + int animationBase = variant * TEAR_ANIMATION_BASE; + if (previous != animationBase + number) + { + scaleAnimNum = animationBase + number; + int frame = previous / TEAR_ANIMATION_BASE == scaleAnimNum / TEAR_ANIMATION_BASE ? sprite.GetFrame() : -1; + sprite.Play("Rotate" + std::to_string(number + 1)); + if (frame < 0) frame = random_below(sprite.animState.animData ? sprite.animState.animData->length : 0); + if (sprite.animState.animData) + { + sprite.animState.SetFrameFloat((float)frame); + sprite.animState.isPlaying = false; + } + } + return fScale / *found; +} + // Plays the animation of its variant and size when that changed: the first sized one at least its scale, or a // fixed one. The scale its layers draw at, its scale over the animation's where no animation matches it. float Entity_Tear::animation_update() @@ -1790,8 +1659,9 @@ float Entity_Tear::animation_update() } case TEAR_SCHYTHE: case TEAR_ROCK: + return spinning_animation_update(); case TEAR_FETUS: - reconstruction_missing("Entity_Tear::ResetSpriteScale 00677780: this tear variant's animation"); + return fetus_animation_update(); case TEAR_CHAOS_CARD: if (isDead) return 1; if (scaleAnimNum != animationBase) @@ -1858,7 +1728,8 @@ bool Entity_Tear::is_not_familiar_spawned() } // 0067d560 Hurts the rocks, poop and other solid grid entities its collision points touch at a position, once each, -// unless the tear does no grid damage. Whether it touched any. +// unless the tear does no grid damage. An acid tear (or a rock tear, by its damage's chance) breaks the first rock +// that tear effects may break instead, bridging the pit beyond it along its flight. Whether it touched any. bool Entity_Tear::try_make_bridges(const Vector& position) { if (tearFlags[TEAR_NO_GRID_DAMAGE]) return false; @@ -1866,6 +1737,7 @@ bool Entity_Tear::try_make_bridges(const Vector& position) std::vector cells; int damage = collisionDamage > STRONG_TEAR_DAMAGE ? 2 : 1; bool isHitSolid = false; + bool isRockBroken = false; for (Vector point : collisionPoints) { @@ -1881,26 +1753,139 @@ bool Entity_Tear::try_make_bridges(const Vector& position) if (!grid || grid->collisionClass == COLLISION_NONE || grid->collisionClass == COLLISION_PIT) continue; isHitSolid = true; - if (tearFlags[TEAR_ACID] || tearFlags[TEAR_ROCK_FLAG]) - reconstruction_missing("Entity_Tear::try_make_bridges 0067d560: the acid and rock tears breaking rocks"); - grid->Hurt(damage, EntityRef(this)); + if (isRockBroken) continue; + bool isBreaking = tearFlags[TEAR_ACID] || (tearFlags[TEAR_ROCK_FLAG] && random_unit() < collisionDamage * ROCK_BREAK_CHANCE); + if (grid->CanTakeDamageFromTearEffects() && isBreaking && grid->Destroy(false, EntityRef(this))) + { + isRockBroken = true; + bridge_beyond(*grid); + } + if (!isRockBroken) grid->Hurt(damage, EntityRef(this)); } return isHitSolid; } -// The hit's direction draws a random one for a tear too slow to have its own. Only Backstabber, Knockout Drops and -// the coins use the direction, none of which is written yet, but the draw still advances the generator. -static void hit_direction_draw(Entity* source) +// Bridges the pit one cell beyond a broken rock along the tear's flight (snapped to the four directions). +void Entity_Tear::bridge_beyond(GridEntity& rock) { - if (source && source->type == ENTITY_TEAR && vector_length(source->velocity) < HIT_DIRECTION_MIN_SPEED) - random_direction(); + Room& room = *g_game->room; + Vector along = vector_cardinal(velocity); + int column = rock.gridIndex % room.gridWidth + (int)along.x; + int row = rock.gridIndex / room.gridWidth + (int)along.y; + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return; + + int cell = row * room.gridWidth + column; + room_bridge_make(cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr, &rock); +} + +// The direction a hit pushes in: a tear's flight (a random one for a tear too slow to have its own), away from a +// knife's player (or the hit point), along a laser (a ring's motion), away from any other source or the hit point. +static Vector hit_direction_get(Entity& entity, const Vector& position, Entity* source) +{ + if (!source) return vector_normalized(vector_sub(entity.pos, position)); + if (source->type == ENTITY_KNIFE) + { + Entity_Player* player = static_cast(source)->GetPlayer(); + return vector_normalized(vector_sub(entity.pos, player ? player->pos : position)); + } + if (source->type == ENTITY_TEAR) + return vector_length(source->velocity) < HIT_DIRECTION_MIN_SPEED ? random_direction() + : vector_normalized(source->velocity); + if (source->type == ENTITY_LASER) + { + auto* laser = static_cast(source); + return laser->IsCircleLaser() ? vector_normalized(source->velocity) : vector_from_angle(laser->angleDegrees); + } + return vector_normalized(vector_sub(entity.pos, source->pos)); +} + +// Euthanasia: the needle kills the enemy outright and bursts it into ten needles all around, its player's tears +// without the needle, a little larger and paler. +static void needle_burst(Entity& entity, Entity* source) +{ + entity.Kill(EntityRef(source)); + Entity* spawner = source ? source->GetLastSpawner() : nullptr; + Entity_Player* player = spawner && spawner->type == ENTITY_PLAYER ? spawner->ToPlayer() : nullptr; + Entity* needleSpawner = source && source->spawnerEntity ? source->spawnerEntity.get() : source; + float start = random_unit(); + for (int i = 0; i < NEEDLE_COUNT; i++) + { + TearParams params; + if (player) params = player->GetTearHitParams(WEAPON_TEARS, 1, (int)(Random() & 1) * 2 - 1, needleSpawner); + uint32_t seed = Random(); + Vector velocity = vector_scale(vector_from_angle(((float)i / NEEDLE_COUNT + start) * TEAR_FULL_TURN), NEEDLE_SPEED); + Entity_Tear& needle = *g_game->Spawn({.position = entity.pos, .velocity = velocity, .spawner = needleSpawner, + .type = ENTITY_TEAR, .variant = TEAR_BLOOD, .seed = seed})->ToTear(); + needle.SetScale(params.tearScale * NEEDLE_SCALE); + TearFlags flags = params.tearFlags; + flags.reset(TEAR_NEEDLE_FLAG); + needle.SetTearFlags(flags); + needle.SetCollisionDamage(params.tearDamage); + needle.SetColor(NEEDLE_COLOR, -1, TEAR_COLOR_PRIORITY, false, true); + if (!needle.tearFlags[TEAR_HYDROBOUNCE]) continue; + needle.fallingAccel = NEEDLE_HYDRO_ACCEL; + needle.fallingSpeed = NEEDLE_HYDRO_FALL - needle.fallingSpeed; + } +} + +// Head of the Keeper's and Midas' coin knocked out of the enemy: thrown back off the hit (or dropped on a free spot +// when the hit is over the grid). +static void coin_knock_out(const Vector& position, Vector direction) +{ + uint32_t seed = Random(); + Vector spot = position; + Vector coinVelocity{}; + if (room_grid_collision_at(position) == COLLISION_NONE) + { + float turn = random_unit() * KNOCKED_COIN_TURN_SPREAD + KNOCKED_COIN_TURN_MIN; + coinVelocity = vector_scale(tear_vector_rotate(direction, turn), random_unit() * KNOCKED_COIN_SPEED_SPREAD + KNOCKED_COIN_SPEED_MIN); + } + else spot = room_free_pickup_position_find({.position = position, .step = KNOCKED_COIN_FREE_STEP}); + g_game->Spawn({.position = spot, .velocity = coinVelocity, .subType = COIN_PENNY, .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, .seed = seed}); +} + +// Where a hit lands, the way it moves, what dealt it and its damage. +struct TearHit +{ + Vector position{}; + Vector direction{}; + Entity* source = nullptr; + float damage = 0; +}; + +// Backstabber: a hit from behind (along the way the enemy faces) hurts again by the hit's damage (through the hurt +// cooldown in versus), makes it bleed for five seconds and sprays its blood out of its back. +static void backstab(Entity& entity, const TearHit& hit) +{ + Vector forward = entity.GetForwardVector(); + if (vector_is_zero(forward) || vector_dot(hit.direction, forward) <= 0) return; + + uint64_t damageFlags = g_game->deathmatchManager.state >= DEATHMATCH_INTRO ? DAMAGE_THROUGH_COOLDOWN : 0; + entity.TakeDamage(hit.damage, damageFlags, EntityRef(hit.source), BACKSTAB_COUNTDOWN); + entity.AddBleeding(EntityRef(hit.source), BACKSTAB_BLEED); + npc_sound_play(SOUND_MEATY_DEATHS, BACKSTAB_VOLUME, BACKSTAB_SOUND_DELAY, 1); + + uint32_t seed = Random(); + Vector velocity = vector_add(vector_scale(hit.direction, BACKSTAB_SPRAY_SPEED), random_direction()); + Vector at = vector_sub(entity.pos, vector_scale(hit.direction, entity.size * 0.5f)); + Entity_Effect& blood = *static_cast(g_game->Spawn({.position = at, .velocity = velocity, .subType = 2, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, .seed = seed})); + blood.SetColor(entity.splatColor, -1, TEAR_COLOR_PRIORITY, false, true); + blood.posOffset = vector_make(0, BACKSTAB_SPRAY_LIFT); + blood.rotation = random_unit() * TEAR_FULL_TURN; + blood.Update(); } // The status effects of a hit on a vulnerable enemy: Spider Bite's slowing (Ball of Tar's darker), poison, freezing, // charm, confusion (Glaucoma's lasting), fear, burning, Midas' gold, magnetism, bait, ice, black hearts and God's // Flesh's shrinking. -static void status_effects_apply(Entity& entity, const TearFlags& flags, Entity* source) +static void status_effects_apply(Entity& entity, const TearFlags& flags, const TearHit& hit) { + Entity* source = hit.source; + const Vector& position = hit.position; + Vector direction = hit.direction; EntityRef ref(source); bool isVersus = g_game->deathmatchManager.is_active(); @@ -1923,8 +1908,7 @@ static void status_effects_apply(Entity& entity, const TearFlags& flags, Entity* entity.AddBurn(ref, isFireJet ? BURN_DURATION_LONG : BURN_DURATION, 0, false); } if (flags[TEAR_MIDAS]) entity.AddMidasFreeze(ref, MIDAS_DURATION, false); - if (flags[TEAR_BACKSTAB]) - reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Backstabber's bleeding"); + if (flags[TEAR_BACKSTAB]) backstab(entity, hit); if (flags[TEAR_MAGNETIZE]) entity.AddMagnetized(ref, MAGNETIZE_DURATION); if (flags[TEAR_BAIT]) entity.AddBaited(ref, BAIT_DURATION); if (flags[TEAR_ICE_FLAG]) entity.AddIce(ref, ICE_DURATION); @@ -1932,28 +1916,99 @@ static void status_effects_apply(Entity& entity, const TearFlags& flags, Entity* if (flags[TEAR_BLACK_HP_DROP]) entity.AddEntityFlags(FLAG_SPAWN_BLACK_HP); if (flags[TEAR_GODS_FLESH_FLAG]) entity.AddShrink(ref, SHRINK_DURATION, false); if (flags[TEAR_COIN_DROP] || (flags[TEAR_GREED_COIN] && Random() % GREED_COIN_CHANCE == 0)) - reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: a coin knocked out"); + coin_knock_out(position, direction); +} + +// E. Coli turns a vulnerable enemy that may be rerolled into poop (keeping its minecart). The wisps' flags are not +// written yet. +static void rerollable_flags_apply(Entity& entity, const TearFlags& flags, Entity* source) +{ + bool isRerollable = entity.type >= ENTITY_TYPE_NPC_FIRST && static_cast(entity).CanReroll() && + entity.type != ENTITY_POOP && entity.type != ENTITY_CHUB && entity.type != ENTITY_MOMS_HAND; + if (!isRerollable) return; + if (flags[TEAR_ECOLI] && entity.IsVulnerableEnemy(nullptr) && entity.type != ENTITY_PLAYER) + { + entity.Remove(); + Entity* poop = g_game->Spawn({.position = entity.pos, .type = ENTITY_POOP, .seed = Random()}); + if (entity.minecart) static_cast(entity.minecart.get())->MinecartUpdateChild(poop); + } + unhandled_check(flags, HIT_UNHANDLED_FLAGS); + (void)source; +} + +// Holy Light's beam strikes the enemy for three times the hit's damage, its spawner's player (or the first player) +// its parent, with a wide reach. +static void holy_light_strike(Entity& entity, Entity* source, float damage) +{ + Entity* spawner = source ? source->GetLastSpawner() : nullptr; + Entity* player = spawner && spawner->type == ENTITY_PLAYER ? spawner : g_game->GetPlayer(0); + Entity* beam = g_game->Spawn({.position = entity.pos, .spawner = source, .type = ENTITY_EFFECT, + .variant = EFFECT_CRACK_THE_SKY, .seed = Random()}); + beam->parent = player; + beam->SetCollisionDamage(damage * HOLY_LIGHT_HIT_SCALE); + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Holy Light in versus"); + EntityConfig_Entity* beamConfig = g_manager->entityConfig.GetEntity(ENTITY_EFFECT, EFFECT_CRACK_THE_SKY, 0); + beam->SetSize(HOLY_LIGHT_REACH, vector_make(1, 1), beamConfig->gridCollisionPoints); + beam->subtype = 1; +} + +// Parasitoid: the hit leaves white creep, and on an enemy it hatches into one or two blue flies flying back off it +// toward its player (or the source's player, or the first) or one or two blue spiders. +static void parasitoid_egg_hatch(Entity& entity, Vector position, Entity* source) +{ + if (source && source->type == ENTITY_LASER) position = entity.pos; + Entity* creep = g_game->Spawn({.position = position, .spawner = source, .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_WHITE, .seed = Random()}); + creep->Update(); + Entity_Player* player = source && source->parent ? source->parent->ToPlayer() : nullptr; + if (!player) player = g_game->GetPlayer(0); + if (!entity.IsVulnerableEnemy(nullptr) && !entity.CanShutDoors()) return; + + npc_sound_play(SOUND_BOIL_HATCH, EGG_VOLUME, TEAR_SOUND_DELAY, random_unit() * EGG_PITCH_SPREAD + 1); + Vector from = source ? vector_sub(position, source->velocity) : position; + bool isFlies = (Random() & 1) == 0; + int count = (int)(Random() & 1) + 1; + for (int i = 0; i < count; i++) + { + if (!isFlies) + { + Vector spot = room_free_pickup_position_find({.position = player->pos}); + player->numBlueSpiders++; + spawn_blue_spider(from, player, spot); + continue; + } + auto* fly = static_cast(player->AddBlueFlies(1, from, &entity)); + Vector away = vector_normalized(vector_sub(player->pos, position)); + float turn = random_unit() * EGG_FLY_SPREAD - EGG_FLY_SPREAD / 2; + fly->velocity = vector_scale(tear_vector_rotate(away, turn), random_unit() * EGG_FLY_SPEED_SPREAD + EGG_FLY_SPEED); + fly->state = (int)(Random() % EGG_FLY_DELAY_SPREAD) + EGG_FLY_DELAY; + } } // 0067af60 What a hit's tear flags do to what it hits: the status effects on vulnerable enemies, the knockback a // tear's mass and push give, and the gore. An explosive tear leaves the effects to its explosion, and a friendly // target is spared. The original reads a missing target's position. This does nothing for one. -void Entity_Tear::ApplyTearFlagEffects(Entity* entity, const Vector&, const TearFlags& flags, Entity* source, float) +void Entity_Tear::ApplyTearFlagEffects(Entity* entity, const Vector& position, const TearFlags& flags, Entity* source, + float damage) { if (!entity || (source && entity->IsDamageSourceFriendly(EntityRef(source)))) return; - hit_direction_draw(source); + Vector direction = hit_direction_get(*entity, position, source); bool isActiveEnemy = entity->IsActiveEnemy(DEAD_EXCLUDED); - if (!source || source->type != ENTITY_TEAR || !flags[TEAR_EXPLOSIVE]) + bool isExplosiveTear = source && source->type == ENTITY_TEAR && flags[TEAR_EXPLOSIVE]; + if (!isExplosiveTear) { - if (entity->IsVulnerableEnemy(nullptr)) status_effects_apply(*entity, flags, source); - if (flags[TEAR_NEEDLE_FLAG] && isActiveEnemy && !entity->IsBoss() && entity->type != ENTITY_PLAYER) - reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Euthanasia's needle"); + if (entity->IsVulnerableEnemy(nullptr)) + status_effects_apply(*entity, flags, {.position = position, .direction = direction, .source = source, .damage = damage}); + if (flags[TEAR_NEEDLE_FLAG] && isActiveEnemy && !entity->IsBoss() && !entity->config->isBoss && + entity->type != ENTITY_PLAYER) + needle_burst(*entity, source); if (flags[TEAR_HORN] && isActiveEnemy && !entity->HasEntityFlags(FLAG_NO_TARGET)) reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Little Horn's hand"); - if (flags[TEAR_HP_DROP] && Random() % HP_DROP_CHANCE == 0) - reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: a heart knocked out"); - unhandled_check(flags, HIT_UNHANDLED_FLAGS); + for (const HitDrop& drop : HIT_DROPS) + if (flags[drop.flag] && (drop.flag != TEAR_HP_DROP || Random() % HP_DROP_CHANCE == 0)) + entity->TakeDamage(0, drop.damageFlag, EntityRef(source), HIT_DROP_COUNTDOWN); if (flags[TEAR_KNOCKBACK] && !entity->HasEntityFlags(FLAG_NO_KNOCKBACK) && source) { if (source->type != ENTITY_TEAR) @@ -1964,9 +2019,9 @@ void Entity_Tear::ApplyTearFlagEffects(Entity* entity, const Vector&, const Tear entity->AddVelocity_divided(vector_scale(push, multiplier), false); } } - if (flags[TEAR_LIGHT_FROM_HEAVEN] && isActiveEnemy) - reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Holy Light's beam"); - if (flags[TEAR_EGG_FLAG]) reconstruction_missing("Entity_Tear::ApplyTearFlagEffects 0067af60: Parasitoid's egg"); + if (!isExplosiveTear) rerollable_flags_apply(*entity, flags, source); + if (flags[TEAR_LIGHT_FROM_HEAVEN] && isActiveEnemy) holy_light_strike(*entity, source, damage); + if (flags[TEAR_EGG_FLAG]) parasitoid_egg_hatch(*entity, position, source); bool isGoreTarget = (g_game->deathmatchManager.is_active() && entity->type == ENTITY_PLAYER) || Entity::is_enemy_type(entity->type); @@ -1976,46 +2031,83 @@ void Entity_Tear::ApplyTearFlagEffects(Entity* entity, const Vector&, const Tear // The rest of Entity_Tear is not reconstructed yet: the split projectiles, Dead Eye, the multidimensional copies, // the variant change, the links and the rerolls. -// 00678080 -void Entity_Tear::fire_split_projectiles(bool) +// The glow a player's tears fire with: an eighth per Dead Eye charge (up to eight), or a sixteenth per Dark Arts +// kill (up to sixteen) when that is more. +float dead_eye_glow_get(Entity_Player& player) { - reconstruction_missing("Entity_Tear::fire_split_projectiles 00678080"); + float deadEye = player.deadEyeCharges > 0 ? (float)std::min((int)player.deadEyeCharges, DEAD_EYE_STEPS) * DEAD_EYE_STEP : 0; + int darkArts = player.temporaryEffects.GetNullEffectNum(NULLITEM_DARK_ARTS); + return darkArts > 0 ? std::max((float)std::min(darkArts, DARK_ARTS_STEPS) * DARK_ARTS_STEP, deadEye) : deadEye; } -// 00679e80 -void Entity_Tear::SetDeadEyeIntensity(float) +// 00679e80 Sets Dead Eye's glow, loading its additive sprite (playing, as faint as the glow) the first time. +void Entity_Tear::SetDeadEyeIntensity(float intensity) { - reconstruction_missing("Entity_Tear::SetDeadEyeIntensity 00679e80"); + deadEyeIntensity = intensity; + if (intensity == 0 || deadEyeANM2.isLoaded) return; + + deadEyeANM2.Load(DEAD_EYE_ANM2, GRAPHICS_LOAD); + layer_additive_set(deadEyeANM2, 0); + deadEyeANM2.Play("Idle"); + deadEyeANM2.color = {{1, 1, 1, intensity}, {0, 0, 0, 0}, {0, 0, 0}}; } -// 0067a190 -Entity_Tear* Entity_Tear::MakeMultidimensionalCopy(Entity*) +// 0067a190 A Multidimensional Baby copy of the tear for a spawner: a multidimensional tear (a balloon stays one) +// flying the same way at the same height, size, damage and range, with its flags but Ludovico's, its Dead Eye glow, +// wait, index and parent. +Entity_Tear* Entity_Tear::MakeMultidimensionalCopy(Entity* spawner) { - reconstruction_missing("Entity_Tear::MakeMultidimensionalCopy 0067a190"); + bool isBalloon = variant == TEAR_BALLOON || variant == TEAR_BALLOON_BRIMSTONE || variant == TEAR_BALLOON_BOMB; + Entity* spawned = g_game->Spawn({.position = pos, .velocity = velocity, .spawner = spawner, .subType = subtype, + .type = ENTITY_TEAR, .variant = isBalloon ? variant : TEAR_MULTIDIMENSIONAL, + .seed = dropRNG._seed}); + Entity_Tear& copy = *spawned->ToTear(); + copy.SetHeight(height); + copy.fallingSpeed = fallingSpeed; + copy.fallingAccel = fallingAccel; + copy.homingFriction = homingFriction; + copy.tearRange = tearRange; + copy.SetScale(fScale); + TearFlags flags = tearFlags; + flags.reset(TEAR_LUDOVICO); + copy.SetTearFlags(flags); + copy.waitFrames = waitFrames; + copy.tearIdx = tearIdx; + copy.SetCollisionDamage(collisionDamage); + copy.rotation = rotation; + copy.knockbackMultiplier = knockbackMultiplier; + copy.SetDeadEyeIntensity(deadEyeIntensity); + copy.isMultidimensionalTouched = isMultidimensionalTouched; + copy.continueVelocity = continueVelocity; + copy.parent = parent; + copy.spawnerEntity = spawner; + return © } -// 0067a400 -void Entity_Tear::ChangeVariant(int) +// 0067a400 Turns the tear into another variant: its config and sprite reload (the G-Fuel nails' bullets and +// missiles additive), keeping its size, damage and grid collision. +void Entity_Tear::ChangeVariant(int newVariant) { - reconstruction_missing("Entity_Tear::ChangeVariant 0067a400"); -} - -// 0067a770 -int Entity_Tear::find_nearest_linkable_tear() -{ - reconstruction_missing("Entity_Tear::find_nearest_linkable_tear 0067a770"); -} - -// 0067a8f0 -Entity_Tear* Entity_Tear::find_link_partner() -{ - reconstruction_missing("Entity_Tear::find_link_partner 0067a8f0"); -} - -// 0067aaf0 -void Entity_Tear::apply_link_spring_forces() -{ - reconstruction_missing("Entity_Tear::apply_link_spring_forces 0067aaf0"); + int gridCollision = entityGridCollisionClass; + float damage = collisionDamage; + float scale = fScale; + variant = newVariant; + LoadEntityConfig(); + if (config) + { + sprite.Load(config->anm2Path, GRAPHICS_LOAD); + if (is_gfuel_nail(variant)) + { + int layerId = variant == TEAR_NAIL ? 0 : 1; + sprite.Load(variant == TEAR_NAIL ? GFUEL_NAIL_ANM2 : GFUEL_NAIL_BLOOD_ANM2, GRAPHICS_LOAD); + layer_additive_set(sprite, layerId); + if (variant == TEAR_NAIL_BLOOD) sprite.GetLayer(layerId)->bitflags |= 1; + } + } + fScale = scale; + ResetSpriteScale(); + collisionDamage = damage; + entityGridCollisionClass = gridCollision; } // 006b5320 diff --git a/src/entity_tear.h b/src/entity_tear.h index b9e10a1..b3fcf4f 100644 --- a/src/entity_tear.h +++ b/src/entity_tear.h @@ -200,13 +200,46 @@ constexpr float HOVER_OFFSET_LIFT = -15; constexpr float POOF_VOLUME_SMALL = 0.85f; constexpr float POOF_VOLUME_TINY = 0.7f; +// What the tear files share: the smallest scale, the fire's random fall, the floor's height, a player's tear height, +// the delay of the tears' sounds, the priority of their tints, and the angles they turn by. +constexpr float TEAR_SCALE_MIN = 0.01f; +constexpr float TEAR_FALL_SPREAD = 0.2f; +constexpr float TEAR_FLOOR_HEIGHT = -5; +constexpr float PLAYER_TEAR_HEIGHT = -23.75f; +constexpr int TEAR_SOUND_DELAY = 2; +constexpr int TEAR_COLOR_PRIORITY = 255; +constexpr float TEAR_RIGHT_ANGLE = 90; +constexpr float TEAR_HALF_TURN = 180; +constexpr float TEAR_FULL_TURN = 360; +// Ocular Rift's rifts open inside the room, for a second (half that in versus). +constexpr float RIFT_MARGIN = -10; +constexpr int RIFT_FRAMES = 60; +constexpr int RIFT_VERSUS_FRAMES = 30; +// The homing and fetus tears look for a target every fourth frame. +constexpr int TEAR_SEARCH_FRAMES = 4; + +// The subtype bits of Ludovico's tears: Monstro's Lung's cloud, the fast tear, and a tear circling the main one. +constexpr int LUDOVICO_LUNG_BIT = 1; +constexpr int LUDOVICO_FAST = 2; +constexpr int LUDOVICO_CHILD = 4; + +// The splash a dying tear leaves: its poof and its sound. +struct TearSplash +{ + float pitch = 1; + float volume = 1; + int effect = 0; + int sound = 0; + int subType = 0; +}; + // Construction and destruction (00665ea0, 00665cf0) are the defaults. // Field accessors (004177c0, 00431750, 00435e50, 00456440, 004aade0, 00557cd0, 0060ccb0, 0060ccc0, 0060ccd0, // 0060cd00, 0085dd60, 0085dd70, 0085dd90) are the public fields. // A player's tear (Lua's EntityTear): its height and fall, scale and damage, the tear flags that change how it flies // and hits, the entity it sticks to, and the tears and lasers it links to. -// The flags of the common items fly and hit. The rest of the flags and the special variants stop the game in Update, -// Interpolate and ApplyTearFlagEffects until reconstructed. +// Every variant flies and splashes. A fetus' weapons, the rock rerolling wisp tears, Jacob's Ladder, Ocular Rift, +// Little Horn, Knockout Drops, Backstabber, the wisps' hits and the versus mode's parts stop the game until written. struct Entity_Tear : Entity { ANM2 deadEyeANM2; @@ -216,6 +249,7 @@ struct Entity_Tear : Entity TearFlags intervalFlags; TearFlags tearFlags; EntityPtr attachedEffect; + EntityPtr fetusLaser; EntityPtr laserShotLaser; EntityPtr linkNext; EntityPtr linkPrev; @@ -237,18 +271,23 @@ struct Entity_Tear : Entity float fallingSpeed = 0; float height = 0; float homingFriction = 0; + float intervalSpeed = 0; float knockbackMultiplier = 0; float orbitAngle = 0; float orbitRadius = 0; float rotation = 0; + float steerAngle = 0; float tearRange = 0; + int fetusTechCooldown = 0; int hitCount = 0; int holdTimer = 0; + int interval = 0; int scaleAnimNum = 0; int stickTimer = 0; int tearIdx = 0; int waitFrames = 0; uint32_t deathFlags = 0; + short hydroBounceCount = 0; short popBounceCount = 0; bool isCanTriggerStreakEnd = false; bool isFireSoundMuted = false; @@ -279,38 +318,80 @@ struct Entity_Tear : Entity void apply_death_flag_effects(Entity* target); void ResetSpriteScale(); bool is_not_familiar_spawned(); + bool stick(Entity& enemy); + void ludovico_stick_copy(Entity& enemy); + void fetus_hit(Entity& enemy); + void belial_turn(); + void rift_open(); void fire_split_projectiles(bool isHalved); void SetDeadEyeIntensity(float intensity); Entity_Tear* MakeMultidimensionalCopy(Entity* spawner); void ChangeVariant(int newVariant); - int find_nearest_linkable_tear(); + Entity_Tear* find_nearest_linkable_tear(); Entity_Tear* find_link_partner(); void apply_link_spring_forces(); bool try_make_bridges(const Vector& position); + void bridge_beyond(GridEntity& rock); void reroll_hit_entity(int unused); static void ApplyTearFlagEffects(Entity* entity, const Vector& position, const TearFlags& flags, Entity* source, float damage); private: float animation_update(); + float spinning_animation_update(); + float fetus_animation_update(); bool hold_update(); + void detonate_update(Entity_Player* player); void wait_update(); void death_creep_spawn(); + void lasershot_update(); + float ludovico_hydrobounce_update(); void death_update(); - void quadsplit_fire(); + bool grident_break(); + bool hydrobounce_revive(); + TearSplash splash_make(); + float explode(bool isRising); + void poof_spawn(const TearSplash& splash, float explosionScale); + void quadsplit_fire(bool isRising); void blood_stains_spawn(); - void flight_update(); + void flight_update(float verticalMotion); void square_turn(); + void orbit_update(); + void orbit_plain_update(Entity* center); + void orbit_steady_update(Entity* center); + void fetus_update(); + void fetus_spin(); void homing_update(); float size_flags_update(); void spectral_update(); void boomerang_pull(); - void rotation_update(Entity_Player* player); + void attractor_pull(); + void rotation_update(Entity_Player* player, float verticalMotion); + void trail_spawn(); + void gfuel_trail_spawn(float angle); + void glow_burn(); + void speed_flags_update(); + void absorb_update(); + bool absorb_burst(float shotSpeed); + void link_before(Entity_Tear& next); + int chain_length(); + void chain_update(); + void pop_update(); + bool is_popping(); void floor_hit(); void grid_hit(); void bounce_hit(); + void chaos_card_stick(); + void key_open(); + void fire_update(); + void black_seed_paint(); + bool steer_update(); void turn_horizontal_update(Vector previous); + void sticky_update(float scaleFactor); + void spores_burst(); + void interval_update(); void fall_update(); + void continuum_update(); void split_fire(bool isRising); void bone_shards_fire(bool isRising); void tech_zero_update(); @@ -327,3 +408,20 @@ private: }; float worm_multiplier_get(Entity_Player* player, int flag); +bool tear_room_is_crawlspace(); +float tear_remote_opacity_get(); +float tear_shot_alpha_get(Entity_Tear& tear); +Vector tear_vector_rotate(Vector v, float degrees); +Entity* homing_target_find(Entity_Tear& tear, bool isFetus); +float dead_eye_glow_get(Entity_Player& player); + +// Game::AttractEntities' arguments: where everything is pulled to, how hard and how far, and the one entity spared. +struct Attraction +{ + Vector position{}; + Entity* spared = nullptr; + float radius = 0; + float strength = 0; +}; + +void entities_attract(const Attraction& attraction); diff --git a/src/entity_tear_death.cpp b/src/entity_tear_death.cpp new file mode 100644 index 0000000..06a1b6d --- /dev/null +++ b/src/entity_tear_death.cpp @@ -0,0 +1,715 @@ +#include "entity_tear.h" +#include "entity_bomb.h" +#include "entity_effect_combat.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_player.h" +#include "game.h" +#include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "room.h" +#include "room_descriptor.h" +#include "sfx_manager.h" +#include +#include + +// The splash a dying tear leaves: the poof sizes by its scale, the volumes and pitches of the sounds, the particles +// the hard tears break into, Bob's head's and Ipecac's explosion, and the stains the plain tears leave. +constexpr float RIFT_SOUND_VOLUME = 0.5f; +constexpr float POOF_SCALE_SMALL = 0.4f; +constexpr float POOF_SCALE_LARGE = 0.8f; +constexpr float RIPPLE_SIZE_OFFSET = 8; +constexpr float RIPPLE_SIZE_SPAN = 28; +constexpr float SPLASH_QUIET = 0.3f; +constexpr float SPLASH_HALF = 0.5f; +constexpr float SPLASH_PITCH_HIGH = 2; +constexpr float SPLASH_PITCH_SPREAD = 0.5f; +constexpr float TOOTH_PITCH_SPREAD = 0.2f; +constexpr float SCYTHE_PITCH = 0.95f; +constexpr float SCYTHE_PITCH_SPREAD = 0.1f; +constexpr float RICOCHET_PITCH = 0.8f; +constexpr float RICOCHET_PITCH_SPREAD = 0.6f; +constexpr float BONE_PITCH = 3; +constexpr float FETUS_PITCH = 1.5f; +constexpr float FETUS_VOLUME = 0.6f; +constexpr int SWORD_BEAM_POOF_SUBTYPE = 22; +constexpr int KEY_POOF_SUBTYPE = 20; +constexpr int FETUS_POOF_SUBTYPE = 2; +constexpr int RICOCHET_CHANCE = 5; +constexpr int TOOTH_PARTICLES = 8; +constexpr int BONE_SPLASH_PARTICLES = 4; +constexpr float PARTICLE_SPEED = 2; +constexpr float PARTICLE_SPEED_SPREAD = 3; +constexpr ColorMod BLACK_TOOTH_COLOR = {{0.3f, 0.3f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Mom's Bracelet's rock: its dust's volume and pitch by its size, and the shards it breaks into, at most 16. +constexpr float ROCK_VOLUME_SCALE = 1.4f; +constexpr float ROCK_PITCH_MIN = 0.95f; +constexpr float ROCK_PITCH_MAX = 1.8f; +constexpr float ROCK_ROOM_MARGIN = -20; +constexpr float ROCK_SHARDS_PER_SCALE = 4; +constexpr int ROCK_SHARDS_MAX = 16; +constexpr float ROCK_SHARD_SPEED = 2; +constexpr int ROCK_SHARD_SUBTYPE = 1; +constexpr ColorMod ROCK_SHARD_COLOR = {{140 / 255.0f, 123 / 255.0f, 123 / 255.0f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int ROCK_WISPS_MAX = 3; + +// The tints the poofs of the tinted variants multiply the tear's color with. +struct PoofTint +{ + ColorMod color = COLOR_DEFAULT; + int variant = 0; +}; + +constexpr std::array POOF_TINTS = {{ + {{{0.3f, 0.3f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_METALLIC}, + {{{0.3f, 0.3f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_EXPLOSIVO}, + {{{0.02f, 0.5f, 0.02f, 1}, {0, 0, 0, 0}, {0, 85 / 255.0f, 0}}, TEAR_BOBS_HEAD}, + {{{1.5f, 0.7f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_FIRE_MIND}, + {{{0.1f, 0.1f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_DARK_MATTER}, + {{{0.5f, 1, 0.4f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_MYSTERIOUS}, + {{{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 70 / 255.0f, 1}}, TEAR_DIAMOND}, + {{{1, 1, 1, 1}, {0, 0, 0, 0}, {230 / 255.0f, 230 / 255.0f, 0}}, TEAR_COIN}, + {{{0.2f, 1, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_BOOGER}, + {{{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0.5f, 0.5f, 0.5f}}, TEAR_EGG}, + {{{0.1f, 0.1f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_NEEDLE}, + {{{0.3f, 0.3f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_BALLOON_BOMB}, + {{{1, 1, 1, 1}, {1, 0.6f, 0.78f, 1}, {0, 0, 0}}, TEAR_ERASER}, +}}; +constexpr PoofTint SPORE_TINT = {{{0.3f, 0.3f, 0.7f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, TEAR_SPORE}; + +// Ipecac's and Bob's head's explosion: its reach by the tear's size, the damage in versus, the hydro bounce's halving, +// and the poison's green splat and cloud. +constexpr float EXPLOSION_FLAG_RADIUS = 60; +constexpr float EXPLOSION_SIZE_FULL = 8.75f; +constexpr float IPECAC_RADIUS = 60; +constexpr float IPECAC_RADIUS_MIN = 30; +constexpr float EXPLOSION_SIZE_REACH = 30; +constexpr float EXPLOSION_VERSUS_DAMAGE = 35; +constexpr float CLOUD_HEIGHT_SHARE = 0.4f; +constexpr float CLOUD_DEPTH_OFFSET = -5; +constexpr int IPECAC_CLOUD_SUBTYPE = 4; +constexpr ColorMod IPECAC_SPLAT_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0, 85 / 255.0f, 0}}; +constexpr ColorMod IPECAC_CLOUD_COLOR = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {10 / 255.0f, 100 / 255.0f, 0}}; + +// A water bounce: the speed it leaves the floor at (harder for an explosive or splitting tear), and the splash it +// hurts what is around with. +constexpr float HYDROBOUNCE_SPEED = -10; +constexpr float HYDROBOUNCE_SPEED_HEAVY = -20; +constexpr float HYDROBOUNCE_REACH = 20; +constexpr float HYDROBOUNCE_DAMAGE = 0.25f; + +// The stains: how many and how far, their size and faintness, and the eye tears' red. +constexpr int STAIN_COUNT_MAX = 5; +constexpr int STAIN_COUNT_EGG = 3; +constexpr float STAIN_SPREAD = 24; +constexpr float STAIN_SCALE = 0.3f; +constexpr float STAIN_ALPHA = 0.08f; +constexpr float MASCARA_ALPHA = 0.2f; +constexpr float MASCARA_ALPHA_SPREAD = 0.3f; +constexpr ColorMod STAIN_COLOR = {{0, 0, 0, STAIN_ALPHA}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod EGG_STAIN_COLOR = {{0, 0, 0, 0.5f}, {0, 0, 0, 0}, {1, 1, 1}}; +constexpr ColorMod NUMBER_ONE_STAIN_COLOR = {{0, 0, 0, 0.5f}, {0, 0, 0, 0}, {150 / 255.0f, 150 / 255.0f, 0}}; +constexpr ColorMod EYE_STAIN_COLOR = {{0, 0, 0, 0.1f}, {0, 0, 0, 0}, {150 / 255.0f, 0, 0}}; +constexpr std::array TEAR_STAINING_VARIANTS = {TEAR_BLUE, TEAR_GLAUCOMA, TEAR_GODS_FLESH, TEAR_EGG, + TEAR_EYE, TEAR_EYE_BLOOD, TEAR_BALLOON, TEAR_HUNGRY, + TEAR_BALLOON_BRIMSTONE, TEAR_BALLOON_BOMB}; + +// The pieces a dying tear breaks into: Cricket's Body's four, Parasite's two halves, Compound Fracture's shards and +// Haemolacria's burst. +constexpr int QUADSPLIT_PIECES = 4; +constexpr float QUADSPLIT_SLOW_SQUARED = 0.1f; +constexpr float QUADSPLIT_SLOW_SPEED = 10; +constexpr float QUADSPLIT_DAMAGE = 0.5f; +constexpr float QUADSPLIT_SCALE = 0.6f; +constexpr float QUADSPLIT_HEIGHT_SHARE = 0.5f; +constexpr float QUADSPLIT_FALL_SHARE = 0.3f; +constexpr float SPLIT_DAMAGE_MIN = 1; +constexpr float PARASITE_HEIGHT_SHARE = 1.5f; +constexpr float SPLIT_DAMAGE = 0.5f; +constexpr float SPLIT_RISING_DAMAGE = 0.25f; +constexpr float SPLIT_RISING_ACCEL = 2; +constexpr float SPLIT_SCALE = 0.5f; +constexpr float SPLIT_RISING_HEIGHT = -5.1f; +constexpr float BONE_DAMAGE = 0.5f; +constexpr int BONE_SHARDS = 2; +constexpr const char* BROKEN_BONE_SHEET = "gfx/tears_brokenbone.png"; +constexpr int HAEMO_BURST_COUNT = 6; +constexpr int HAEMO_BURST_COUNT_WEAPON = 3; +constexpr int HAEMO_BURST_COUNT_BRIMSTONE = 4; +constexpr float HAEMO_BURST_SPEED = 10; +constexpr float HAEMO_BURST_DAMAGE_SHARE = 1.5f; +constexpr float HAEMO_BURST_DAMAGE_MIN = 0.75f; +constexpr float HAEMO_BURST_DAMAGE_SPREAD = 0.5f; +constexpr float HAEMO_BURST_SCALE = 0.55f; +constexpr float HAEMO_BURST_HEIGHT = -6; +constexpr float HAEMO_BURST_FALL_ACCEL = 1.3f; +constexpr float HAEMO_BURST_FALL_MIN = 0.5f; +constexpr float HAEMO_BURST_FALL_SPREAD = 0.75f; +constexpr float BURST_CRAWLSPACE_OFFSET = -18; + +// The flags Haemolacria's burst keeps of its tear. +constexpr std::array HAEMO_BURST_KEPT_FLAGS = { + TEAR_SPORE_FLAG, TEAR_OCCULT, TEAR_BAIT, TEAR_MAGNETIZE, TEAR_ICE_FLAG, TEAR_PUNCH, + TEAR_CREEP_TRAIL, TEAR_HYDROBOUNCE, TEAR_LASERSHOT, TEAR_LASER, TEAR_HORN, TEAR_JACOBS, + TEAR_NEEDLE_FLAG, TEAR_MIDAS, TEAR_BELIAL_FLAG, TEAR_ACID, TEAR_EGG_FLAG, TEAR_BOOGER_FLAG, + TEAR_PERMANENT_CONFUSION, TEAR_BIG_SPIRAL, TEAR_GREED_COIN, TEAR_GODS_FLESH_FLAG, TEAR_BLACK_HP_DROP, + TEAR_COIN_DROP, TEAR_LIGHT_FROM_HEAVEN, TEAR_CONTINUUM, TEAR_STICKY, TEAR_MYSTERIOUS_LIQUID_CREEP, + TEAR_GISH, TEAR_GLOW, TEAR_SQUARE, TEAR_FLAT, TEAR_SPIRAL, TEAR_PULSE, + TEAR_KNOCKBACK, TEAR_ATTRACTOR, TEAR_BURN, TEAR_SHRINK, TEAR_FEAR, TEAR_BOUNCE, + TEAR_HP_DROP, TEAR_CONFUSION, TEAR_CHARM, TEAR_MULLIGAN, TEAR_WIGGLE, TEAR_PERSISTENT, + TEAR_GROW, TEAR_FREEZE, TEAR_POISON, TEAR_SLOW, TEAR_HOMING, TEAR_SPECTRAL, + TEAR_PIERCING}; + +// 006684e5's Grident: Mom's Bracelet's rock breaks into the rock it was where it lands, and Book of Virtues adds one +// to three of the bracelet's wisps there. Whether the tear is gone. +bool Entity_Tear::grident_break() +{ + if (variant != TEAR_GRIDENT) return false; + + GridEntityDesc desc = GRID_SAVE_EMPTY; + desc._type = (uint32_t)subtype >> 16; + desc._variant = subtype & 0xffff; + desc._spawnSeed = initSeed; + desc._varData = HasEntityFlags(FLAG_NO_DEATH_TRIGGER); + desc._state = (int)health; + Entity::DestroyRockGridAt(pos, &desc, this, tearIdx); + + Entity_Player* player = spawnerEntity && spawnerEntity->is_player() ? spawnerEntity->ToPlayer() : nullptr; + if (player && player->HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) + for (int i = random_below(ROCK_WISPS_MAX) + 1; i > 0; i--) + if (Entity_Familiar* wisp = player->AddWisp(COLLECTIBLE_MOMS_BRACELET, pos, false, true)) + { + wisp->targetPosition = pos; + wisp->Update(); + } + Remove(); + return true; +} + +// A water tear that hit the floor bounces back up off it (its first bounce at a set speed), hurting what is around +// it with a quarter of its damage. One falling too fast, or a Ludovico tear, splashes for good. Whether it bounced. +bool Entity_Tear::hydrobounce_revive() +{ + if (!tearFlags[TEAR_HYDROBOUNCE] || deathFlags != TEAR_DEATH_FLOOR) return false; + + if (!tearFlags[TEAR_LUDOVICO]) + { + bool isHeavy = tearFlags[TEAR_EXPLOSIVE] || tearFlags[TEAR_QUADSPLIT] || tearFlags[TEAR_BURSTSPLIT]; + float bounceSpeed = isHeavy ? HYDROBOUNCE_SPEED_HEAVY : HYDROBOUNCE_SPEED; + if (bounceSpeed < fallingSpeed && hydroBounceCount == 0) fallingSpeed = bounceSpeed; + if (bounceSpeed < fallingSpeed) return false; + } + hydroBounceCount++; + isDead = false; + tear_flags_area_apply(pos, this, size + HYDROBOUNCE_REACH, collisionDamage * HYDROBOUNCE_DAMAGE, tearFlags); + return true; +} + +// Throws a few particles of a variant, tinted, from the tear's height at a random speed. The count draws after the +// speed. +static void particles_throw(Entity_Tear& tear, int particleVariant, int count, int countSpread, const ColorMod& color) +{ + float speed = random_unit() * PARTICLE_SPEED_SPREAD + PARTICLE_SPEED; + if (countSpread > 0) count += random_below(countSpread); + game_particles_spawn({.color = color, .position = tear.pos, .height = tear.height, .speed = speed, + .count = count, .subType = 1, .variant = particleVariant}); +} + +// A tear poof's size by the tear's scale, the larger one above the floor. +static TearSplash poof_splash_get(Entity_Tear& tear) +{ + if (tear.fScale < POOF_SCALE_SMALL) + return {.volume = POOF_VOLUME_TINY, .effect = EFFECT_TEAR_POOF_VERYSMALL, .sound = SOUND_SPLATTER}; + if (tear.fScale < POOF_SCALE_LARGE) + return {.volume = POOF_VOLUME_SMALL, .effect = EFFECT_TEAR_POOF_SMALL, .sound = SOUND_SPLATTER}; + if (tear.height <= TEAR_FLOOR_HEIGHT) return {.effect = EFFECT_TEAR_POOF_A, .sound = SOUND_TEAR_IMPACTS}; + return {.effect = EFFECT_TEAR_POOF_B, .sound = SOUND_SPLATTER}; +} + +// The broken shards of Mom's Bracelet's rock: up to 16 tooth particles by its size, scattered over it and tinted +// stone grey, where it lands in the room. +static void rock_shards_throw(Entity_Tear& tear) +{ + if (!g_game->room->IsPositionInRoom(tear.pos, ROCK_ROOM_MARGIN)) return; + + ColorMod color = ROCK_SHARD_COLOR; + color_multiply(color, tear.sprite.color); + int count = (int)(tear.fScale * ROCK_SHARDS_PER_SCALE * (random_unit() * SPLASH_HALF + 1)); + count = std::min(std::max(count, 1), ROCK_SHARDS_MAX); + for (int i = 0; i < count; i++) + { + Vector direction = vector_from_angle(random_unit() * TEAR_FULL_TURN); + float speed = random_unit() * ROCK_SHARD_SPEED + 1; + float distance = random_unit(); + Vector position = vector_add(tear.pos, vector_scale(direction, distance * tear.size)); + Entity* shard = g_game->Spawn({.position = position, .velocity = vector_scale(direction, speed), + .subType = ROCK_SHARD_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_TOOTH_PARTICLE, .seed = Random()}); + shard->posOffset = tear.posOffset; + shard->SetColor(color, -1, TEAR_COLOR_PRIORITY, false, true); + shard->Update(); + } +} + +// The splash of a dying tear by its variant, throwing the particles the hard ones break into: a tear poof for the +// plain ones, a bullet poof for the blood-like ones, an impact for the teeth, nails, coins, diamonds and bones, the +// scythe's break, the rock's dust, the keys' and sword beams' own poofs and the fetus' blood. The G-Fuel nails +// ricochet one time in five off the grid, and are silent otherwise. +TearSplash Entity_Tear::splash_make() +{ + switch (variant) + { + case TEAR_BLUE: case TEAR_METALLIC: case TEAR_FIRE_MIND: case TEAR_DARK_MATTER: case TEAR_MYSTERIOUS: + case TEAR_LOST_CONTACT: case TEAR_CUPID_BLUE: case TEAR_PUPULA: case TEAR_GODS_FLESH: case TEAR_EXPLOSIVO: + case TEAR_MULTIDIMENSIONAL: case TEAR_GLAUCOMA: case TEAR_BOOGER: case TEAR_EGG: case TEAR_NEEDLE: + case TEAR_HUNGRY: case TEAR_ICE: case TEAR_ERASER: case TEAR_SPORE: + return poof_splash_get(*this); + case TEAR_BLOOD: case TEAR_CUPID_BLOOD: case TEAR_PUPULA_BLOOD: case TEAR_GODS_FLESH_BLOOD: + case TEAR_GLAUCOMA_BLOOD: case TEAR_BELIAL: case TEAR_EYE: case TEAR_EYE_BLOOD: case TEAR_BALLOON: + case TEAR_BALLOON_BRIMSTONE: case TEAR_BALLOON_BOMB: case TEAR_FIST: + return {.effect = EFFECT_BULLET_POOF, .sound = SOUND_TEAR_IMPACTS}; + case TEAR_TOOTH: + case TEAR_BLACK_TOOTH: + { + ColorMod color = sprite.color; + if (variant == TEAR_BLACK_TOOTH) + { + ColorMod dark = BLACK_TOOTH_COLOR; + color_multiply(dark, color); + color = dark; + } + particles_throw(*this, EFFECT_TOOTH_PARTICLE, TOOTH_PARTICLES, 0, color); + float pitch = random_unit() * TOOTH_PITCH_SPREAD + 1; + return {.pitch = pitch, .volume = SPLASH_HALF, .effect = EFFECT_IMPACT, .sound = SOUND_BOIL_HATCH}; + } + case TEAR_SCHYTHE: + return {.pitch = random_unit() * SCYTHE_PITCH_SPREAD + SCYTHE_PITCH, .volume = SPLASH_QUIET, + .effect = EFFECT_SCYTHE_BREAK, .sound = SOUND_SCYTHE_BREAK}; + case TEAR_NAIL: + case TEAR_NAIL_BLOOD: + case TEAR_RAZOR: + { + float volume = SPLASH_QUIET; + if (variant != TEAR_RAZOR && g_game->seedEffects.HasSeedEffect(SEED_G_FUEL)) + { + if (random_below(RICOCHET_CHANCE) == 0 && (deathFlags & TEAR_DEATH_GRID)) + return {.pitch = random_unit() * RICOCHET_PITCH_SPREAD + RICOCHET_PITCH, .effect = EFFECT_IMPACT, + .sound = SOUND_GFUEL_RICOCHET}; + volume = 0; + } + else particles_throw(*this, EFFECT_NAIL_PARTICLE, 2, 2, sprite.color); + float pitch = random_unit() * SPLASH_PITCH_SPREAD + SPLASH_PITCH_HIGH; + return {.pitch = pitch, .volume = volume, .effect = EFFECT_IMPACT, .sound = SOUND_POT_BREAK}; + } + case TEAR_DIAMOND: + case TEAR_COIN: + { + bool isDiamond = variant == TEAR_DIAMOND; + particles_throw(*this, isDiamond ? EFFECT_DIAMOND_PARTICLE : EFFECT_COIN_PARTICLE, isDiamond ? 2 : 4, 2, + sprite.color); + float pitch = random_unit() * SPLASH_PITCH_SPREAD + SPLASH_PITCH_HIGH; + return {.pitch = pitch, .volume = SPLASH_QUIET, .effect = EFFECT_IMPACT, .sound = SOUND_POT_BREAK}; + } + case TEAR_BONE: + { + particles_throw(*this, EFFECT_TOOTH_PARTICLE, BONE_SPLASH_PARTICLES, 0, sprite.color); + float pitch = random_unit() * SPLASH_PITCH_SPREAD + BONE_PITCH; + return {.pitch = pitch, .volume = SPLASH_QUIET, .effect = EFFECT_IMPACT, .sound = SOUND_POT_BREAK}; + } + case TEAR_ROCK: + { + TearSplash splash = {.pitch = std::clamp(1 / fScale, ROCK_PITCH_MIN, ROCK_PITCH_MAX), + .volume = std::clamp(fScale * ROCK_VOLUME_SCALE, SPLASH_HALF, 1.0f), + .effect = EFFECT_ROCK_POOF, .sound = SOUND_STONE_IMPACT}; + rock_shards_throw(*this); + return splash; + } + case TEAR_KEY: + case TEAR_KEY_BLOOD: + { + particles_throw(*this, EFFECT_NAIL_PARTICLE, 2, 2, sprite.color); + float pitch = random_unit() * SPLASH_PITCH_SPREAD + SPLASH_PITCH_HIGH; + return {.pitch = pitch, .volume = SPLASH_QUIET, .effect = EFFECT_TEAR_POOF_A, .sound = SOUND_POT_BREAK, + .subType = KEY_POOF_SUBTYPE + (variant == TEAR_KEY_BLOOD)}; + } + case TEAR_SWORD_BEAM: + case TEAR_TECH_SWORD_BEAM: + { + int sound = variant == TEAR_SWORD_BEAM ? SOUND_SCYTHE_BREAK : SOUND_REDLIGHTNING_ZAP_WEAK; + return {.pitch = random_unit() * SPLASH_PITCH_SPREAD + SPLASH_PITCH_HIGH, .volume = SPLASH_QUIET, + .effect = EFFECT_TEAR_POOF_A, .sound = sound, .subType = SWORD_BEAM_POOF_SUBTYPE}; + } + case TEAR_FETUS: + return {.pitch = random_unit() * SPLASH_PITCH_SPREAD + FETUS_PITCH, .volume = FETUS_VOLUME, + .effect = EFFECT_BLOOD_EXPLOSION, .sound = SOUND_DEATH_BURST_SMALL, .subType = FETUS_POOF_SUBTYPE}; + default: + return {}; + } +} + +// Ipecac's (and Bob's head's) explosion: its tear effects, then the blast sized to the tear (half as strong off a +// water bounce), and a poison tear's green splat and cloud. The scale the explosion's poof draws at. +float Entity_Tear::explode(bool isRising) +{ + explosion_tear_flag_effects( + {.tearFlags = tearFlags, .position = pos, .source = this, .radius = EXPLOSION_FLAG_RADIUS}); + float damage = g_game->deathmatchManager.is_active() ? EXPLOSION_VERSUS_DAMAGE : collisionDamage; + if (isRising) damage *= SPLASH_HALF; + uint64_t damageFlags = DAMAGE_EXPLOSION | (variant == TEAR_BOBS_HEAD ? DAMAGE_IGNORE_ARMOR : 0); + float radius = size >= EXPLOSION_SIZE_FULL ? std::max(size + EXPLOSION_SIZE_REACH, IPECAC_RADIUS) + : std::max(IPECAC_RADIUS_MIN, size * IPECAC_RADIUS / EXPLOSION_SIZE_FULL); + float explosionScale = radius / IPECAC_RADIUS; + explosion_damage({.tearFlags = tearFlags, .position = pos, .source = this, .damageFlags = damageFlags, + .damage = damage, .radius = radius, .isDamageSource = false, .isLineCheck = true}); + if (!tearFlags[TEAR_POISON]) return explosionScale; + + Entity* splat = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float splatScale = (random_unit() + 1) * explosionScale; + splat->sprite.scale = vector_make(splatScale, splatScale); + splat->SetColor(IPECAC_SPLAT_COLOR, -1, TEAR_COLOR_PRIORITY, false, true); + splat->Update(); + + uint32_t seed = Random(); + Entity* cloud = g_game->Spawn({.position = pos, .subType = IPECAC_CLOUD_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, .seed = seed}); + cloud->SetColor(IPECAC_CLOUD_COLOR, -1, TEAR_COLOR_PRIORITY, false, true); + cloud->sprite.scale = vector_make(explosionScale, explosionScale * CLOUD_HEIGHT_SHARE); + cloud->renderDepthOffset = CLOUD_DEPTH_OFFSET; + cloud->Update(); + return explosionScale; +} + +// The tint the poof of a variant multiplies the tear's color with, or the tear's own color. +static ColorMod poof_color_get(Entity_Tear& tear) +{ + ColorMod color = tear.sprite.color; + auto tint = std::find_if(POOF_TINTS.begin(), POOF_TINTS.end(), [&tear](const PoofTint& t) { return t.variant == tear.variant; }); + const PoofTint* chosen = tint != POOF_TINTS.end() ? &*tint : tear.variant == TEAR_SPORE ? &SPORE_TINT : nullptr; + if (!chosen) return color; + + ColorMod tinted = chosen->color; + color_multiply(tinted, color); + return tinted; +} + +// Spawns the splash's poof where the tear died, at its height: a ripple sized by the tear off a water bounce, the +// other poofs (but the explosion and the small tear poofs) sized by its scale and turned at random, all scaled by an +// explosion's size and tinted by the variant. A remote player's poof fades. Game::Spawn returning nothing crashes the +// original. This skips the poof. +void Entity_Tear::poof_spawn(const TearSplash& splash, float explosionScale) +{ + Entity* poof = g_game->Spawn({.position = pos, .spawner = this, .subType = splash.subType, .type = ENTITY_EFFECT, + .variant = splash.effect, .seed = Random()}); + if (!poof) return; + + poof->posOffset = posOffset; + bool isUnscaled = splash.effect == EFFECT_BOMB_EXPLOSION || splash.effect == EFFECT_TEAR_POOF_SMALL || + splash.effect == EFFECT_TEAR_POOF_VERYSMALL; + if (!isUnscaled) + { + if (splash.effect == EFFECT_RIPPLE_POOF) + { + float scale = (size + RIPPLE_SIZE_OFFSET) / RIPPLE_SIZE_SPAN; + poof->sprite.scale = vector_make(scale, scale); + poof->posOffset = vector_make(posOffset.x, 0); + } + else + { + bool isSmall = splash.effect == EFFECT_SCYTHE_BREAK || variant == TEAR_PUPULA || variant == TEAR_PUPULA_BLOOD; + float scale = fScale * (isSmall ? POOF_SCALE_SMALL : POOF_SCALE_LARGE); + poof->sprite.scale = vector_make(scale, scale); + } + poof->sprite.rotation = (float)random_below(4) * TEAR_RIGHT_ANGLE; + } + if (explosionScale != 1) poof->sprite.scale = vector_scale(poof->sprite.scale, explosionScale); + + poof->SetColor(poof_color_get(*this), -1, TEAR_COLOR_PRIORITY, false, true); + Entity_Player* shooter = spawnerEntity ? spawnerEntity->ToPlayer() : nullptr; + if (!shooter || shooter->IsLocalPlayer()) return; + ColorMod faded = poof->sprite.color; + faded._tint[3] *= tear_remote_opacity_get(); + poof->SetColor(faded, -1, TEAR_COLOR_PRIORITY, false, true); +} + +// (006670f0's death) The dying tear's frame: Mom's Bracelet's rock breaks into its rock, a water tear bounces up off +// the floor, and the splash plays: its particles and sound, Ipecac's explosion, the pieces Cricket's Body, +// Haemolacria and Parasite break it into, its poof (none for a laser shot) and the stains. A tear that bounced flies +// on, the rest is removed. +void Entity_Tear::death_update() +{ + if (grident_break()) return; + + bool isRising = hydrobounce_revive(); + TearSplash splash = splash_make(); + float explosionScale = 1; + bool isExplosive = tearFlags[TEAR_EXPLOSIVE] && !(subtype & LUDOVICO_FAST); + if (isExplosive && tearFlags[TEAR_LUDOVICO] && hydroBounceCount < 2 && !(deathFlags & TEAR_DEATH_EXPLOSION)) + isExplosive = false; + if (isExplosive || variant == TEAR_BOBS_HEAD) + { + splash.effect = EFFECT_BOMB_EXPLOSION; + explosionScale = explode(isRising); + } + if (tearFlags[TEAR_LASERSHOT] && splash.effect != EFFECT_BOMB_EXPLOSION) splash.effect = 0; + if (isRising && splash.effect != EFFECT_BOMB_EXPLOSION) + { + splash.volume *= SPLASH_HALF; + splash.subType = splash.effect == EFFECT_BULLET_POOF; + splash.effect = EFFECT_RIPPLE_POOF; + } + if (splash.sound) npc_sound_play(splash.sound, splash.volume, TEAR_SOUND_DELAY, splash.pitch); + + if (tearFlags[TEAR_QUADSPLIT]) quadsplit_fire(isRising); + if (tearFlags[TEAR_BURSTSPLIT]) fire_split_projectiles(isRising); + if (tearFlags[TEAR_LASER] && (isDead || !techZeroTarget) && techZeroLaser) techZeroLaser->Remove(); + if (splash.effect) poof_spawn(splash, explosionScale); + if (std::find(TEAR_STAINING_VARIANTS.begin(), TEAR_STAINING_VARIANTS.end(), variant) != TEAR_STAINING_VARIANTS.end()) + blood_stains_spawn(); + if (isDead) Remove(); +} + +// Cricket's Body: four pieces at a random angle and its right angles, at the dying tear's speed (10 when it barely +// moved), from where it was a frame ago. They fly a little lower and slower, smaller and with half the damage, a +// water tear's pieces falling as its player's tears do. Off a water bounce they do not explode. +void Entity_Tear::quadsplit_fire(bool isRising) +{ + float speedSquared = vector_length_squared(velocity); + Vector direction = vector_scale(random_direction(), speedSquared < QUADSPLIT_SLOW_SQUARED ? QUADSPLIT_SLOW_SPEED + : vector_length(velocity)); + TearFlags flags = tearFlags; + for (int dropped : {TEAR_QUADSPLIT, TEAR_SPLIT, TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_ABSORB, TEAR_HYDROBOUNCE, + TEAR_FETUS_FLAG}) + flags.reset(dropped); + if (isRising) flags.reset(TEAR_EXPLOSIVE); + + for (int i = 0; i < QUADSPLIT_PIECES; i++) + { + Vector pieceVelocity = i < 2 ? direction : vector_make(direction.y, -direction.x); + if (i & 1) pieceVelocity = vector_scale(pieceVelocity, -1); + Entity_Player* player = GetRootPlayer(); + int pieceVariant = variant == TEAR_FETUS ? TEAR_BLOOD : variant; + Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = pieceVelocity, + .spawner = spawnerEntity, .type = type, .variant = pieceVariant, + .seed = Random()}); + Entity_Tear& piece = *spawned->ToTear(); + + piece.SetHeight((player ? player->tearHeight : PLAYER_TEAR_HEIGHT) * QUADSPLIT_HEIGHT_SHARE); + if (!tearFlags[TEAR_HYDROBOUNCE]) piece.fallingAccel = fallingAccel; + else piece.fallingAccel = player ? player->tearFallingAcceleration : 0; + float playerFall = g_game->GetPlayer(0)->tearFallingSpeed; + if (playerFall > 0) playerFall *= QUADSPLIT_FALL_SHARE; + piece.fallingSpeed = random_unit() * TEAR_FALL_SPREAD - playerFall; + piece.SetCollisionDamage(collisionDamage * QUADSPLIT_DAMAGE); + piece.SetTearFlags(flags); + piece.SetScale(fScale * QUADSPLIT_SCALE); + piece.SetColor(sprite.color, -1, TEAR_COLOR_PRIORITY, false, true); + piece.parent = parent; + piece.Update(); + } +} + +// Leaves up to four faint stains around the splash (an egg at least three): an egg's white, Eve's Mascara's darker, +// Number One's yellow and the eye tears' red. +void Entity_Tear::blood_stains_spawn() +{ + int count = random_below(STAIN_COUNT_MAX); + if (variant == TEAR_EGG) count = std::max(count, STAIN_COUNT_EGG); + Entity_Player* player = GetRootPlayer(); + + for (int i = 0; i < count; i++) + { + uint32_t seed = Random(); + Vector direction = random_direction(); + float distance = random_unit() * STAIN_SPREAD; + Vector position = vector_add(pos, vector_scale(direction, distance)); + Entity* stain = g_game->Spawn( + {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = seed}); + stain->sprite.scale = vector_make(STAIN_SCALE, STAIN_SCALE); + + ColorMod color = STAIN_COLOR; + bool isEye = variant == TEAR_EYE || variant == TEAR_EYE_BLOOD; + if (variant == TEAR_EGG) color = EGG_STAIN_COLOR; + else if (player && player->HasCollectible(COLLECTIBLE_EVES_MASCARA)) + color._tint[3] = random_unit() * MASCARA_ALPHA_SPREAD + MASCARA_ALPHA; + else if (player && player->HasCollectible(COLLECTIBLE_NUMBER_ONE)) color = NUMBER_ONE_STAIN_COLOR; + else if (isEye) color = EYE_STAIN_COLOR; + stain->SetColor(color, -1, TEAR_COLOR_PRIORITY, false, true); + stain->Update(); + } +} + +// 00676be0 Applies what its flags do when it dies above the floor: Parasite splits it in two and Compound Fracture +// into two shards. A tear bouncing back up off water splits too, without explosions. +void Entity_Tear::apply_death_flag_effects(Entity*) +{ + bool isRising = isDead && tearFlags[TEAR_HYDROBOUNCE] && fallingSpeed < 0; + bool isAbove = height < TEAR_FLOOR_HEIGHT; + if (tearFlags[TEAR_SPLIT] && collisionDamage > SPLIT_DAMAGE_MIN && (isAbove || isRising)) split_fire(isRising); + if (tearFlags[TEAR_BONE_FLAG] && isAbove) bone_shards_fire(isRising); + if (tearFlags[TEAR_JACOBS] && isAbove) + reconstruction_missing("Entity_Tear::apply_death_flag_effects 00676be0: Jacob's Ladder's lightning"); + if (tearFlags[TEAR_RIFT]) rift_open(); +} + +// Ocular Rift's rift where the tear died, once, inside the room: as big as the tear, half its damage, a second long +// (half that in versus). +void Entity_Tear::rift_open() +{ + tearFlags.reset(TEAR_RIFT); + Room& room = *g_game->room; + if (!room.IsPositionInRoom(pos, RIFT_MARGIN)) return; + + float damage = collisionDamage * 0.5f; + Vector at = room.GetClampedPositionImpl(pos, 0, 0, 0, 0); + Entity_Effect& rift = *static_cast(g_game->Spawn( + {.position = at, .spawner = spawnerEntity, .type = ENTITY_EFFECT, .variant = EFFECT_RIFT, .seed = Random()})); + rift.sprite.scale = vector_make(fScale, fScale); + rift.SetCollisionDamage(damage); + int frames = g_game->deathmatchManager.state >= DEATHMATCH_INTRO ? RIFT_VERSUS_FRAMES : RIFT_FRAMES; + rift.timeout = frames; + rift.lifespan = frames; + rift.Update(); + int sound = SOUND_OCCULAR_RIFT_PORTAL; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = RIFT_SOUND_VOLUME}); +} + +// What every piece a dying tear breaks into shares: its color (faded for a remote player), its flags, its parent, +// and a first update. +void Entity_Tear::child_setup(Entity_Tear& child, TearFlags flags, float alpha) +{ + ColorMod color = sprite.color; + color._tint[3] *= alpha; + child.SetColor(color, -1, TEAR_COLOR_PRIORITY, false, true); + child.SetTearFlags(flags); + child.parent = parent; + child.Update(); +} + +// Parasite: two plain tears out to the sides from where the tear was a frame ago, lower and with half its damage +// and size. Rising off water they start at the floor with a quarter. +void Entity_Tear::split_fire(bool isRising) +{ + TearFlags flags = tearFlags; + for (int dropped : {TEAR_LUDOVICO, TEAR_ABSORB, TEAR_HYDROBOUNCE, TEAR_FETUS_FLAG}) flags.reset(dropped); + if (isRising) flags.reset(TEAR_EXPLOSIVE); + float alpha = tear_shot_alpha_get(*this); + + for (int i = 0; i < 2; i++) + { + Vector side = i == 0 ? vector_make(velocity.y, -velocity.x) : vector_make(-velocity.y, velocity.x); + Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = side, + .spawner = spawnerEntity, .type = ENTITY_TEAR, .variant = TEAR_BLUE, + .seed = Random()}); + Entity_Tear& piece = *spawned->ToTear(); + piece.SetHeight(isRising ? SPLIT_RISING_HEIGHT : height / PARASITE_HEIGHT_SHARE); + piece.fallingSpeed = fallingSpeed; + if (isRising) piece.fallingAccel = SPLIT_RISING_ACCEL; + piece.SetCollisionDamage(collisionDamage * (isRising ? SPLIT_RISING_DAMAGE : SPLIT_DAMAGE)); + piece.baseScale = std::max(fScale * SPLIT_SCALE, TEAR_SCALE_MIN); + piece.fScale = piece.baseScale; + piece.ResetSpriteScale(); + child_setup(piece, flags, alpha); + } +} + +// Compound Fracture: two shards (bone tears, broken looking ones from a bone tear) flying off at random at the +// tear's speed with half its damage. +void Entity_Tear::bone_shards_fire(bool isRising) +{ + TearFlags flags = tearFlags; + for (int dropped : {TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_FETUS_FLAG}) flags.reset(dropped); + if (isRising) flags.reset(TEAR_EXPLOSIVE); + float alpha = tear_shot_alpha_get(*this); + int shardVariant = variant == TEAR_FETUS ? TEAR_BONE : variant; + + for (int i = 0; i < BONE_SHARDS; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float speed = vector_length(velocity); + Vector shardVelocity = vector_make(std::cos(angle) * speed, std::sin(angle) * speed); + Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = shardVelocity, + .spawner = spawnerEntity, .type = ENTITY_TEAR, .variant = shardVariant, + .seed = Random()}); + Entity_Tear& shard = *spawned->ToTear(); + if (shardVariant == TEAR_BONE) + { + shard.sprite.ReplaceSpritesheet(0, BROKEN_BONE_SHEET); + shard.sprite.LoadGraphics(); + } + shard.SetHeight(height); + shard.fallingSpeed = fallingSpeed; + shard.SetCollisionDamage(collisionDamage * BONE_DAMAGE); + child_setup(shard, flags, alpha); + } +} + +// Haemolacria's burst size: six to eleven tears, three to five with Monstro's Lung, Tech X or Dr. Fetus (four to +// seven with Brimstone), halved off a water bounce. +static int burst_count_get(Entity_Player* player, bool isHalved) +{ + int count = HAEMO_BURST_COUNT; + if (player) + { + bool isFew = player->HasCollectible(COLLECTIBLE_MONSTROS_LUNG) || player->HasCollectible(COLLECTIBLE_TECH_X); + if (!isFew && player->HasCollectible(COLLECTIBLE_BRIMSTONE)) count = HAEMO_BURST_COUNT_BRIMSTONE; + else if (isFew || player->HasCollectible(COLLECTIBLE_DR_FETUS)) count = HAEMO_BURST_COUNT_WEAPON; + } + count += (int)(Random() % (uint32_t)count); + return isHalved ? (count + 1) / 2 : count; +} + +// 00678080 Haemolacria: the dying tear bursts into blood tears flying off at random at ten times its player's shot +// speed, keeping most of its flags, smaller and weaker by a random share, falling back from the burst's height. +// A player with Brimstone, Dr. Fetus, Tech X or Technology bursts into those weapons instead. +void Entity_Tear::fire_split_projectiles(bool isHalved) +{ + Entity* owner = parent; + Entity_Player* player = nullptr; + if (owner && owner->is_player()) player = owner->ToPlayer(); + else if (owner && owner->type == ENTITY_FAMILIAR) player = static_cast(owner)->player; + int count = burst_count_get(player, isHalved); + float shotSpeed = player ? player->shotSpeed : 1; + float fallHeight = player ? player->tearHeight : PLAYER_TEAR_HEIGHT; + + TearFlags kept; + for (int flag : HAEMO_BURST_KEPT_FLAGS) + if (tearFlags[flag]) kept.set(flag); + for (int i = 0; i < count; i++) + { + bool isWeapon = player && (player->HasCollectible(COLLECTIBLE_BRIMSTONE) || + player->HasCollectible(COLLECTIBLE_DR_FETUS) || + player->HasCollectible(COLLECTIBLE_TECH_X) || + player->HasCollectible(COLLECTIBLE_TECHNOLOGY)); + if (isWeapon) + reconstruction_missing("Entity_Tear::fire_split_projectiles 00678080: Haemolacria's burst of a weapon"); + + uint32_t seed = Random(); + Vector burstVelocity = vector_scale(vector_from_angle(random_unit() * TEAR_FULL_TURN), shotSpeed * HAEMO_BURST_SPEED); + Entity* spawned = g_game->Spawn({.position = pos, .velocity = burstVelocity, .spawner = spawnerEntity, + .type = ENTITY_TEAR, .variant = TEAR_BLOOD, .seed = seed}); + Entity_Tear& piece = *spawned->ToTear(); + piece.SetTearFlags(kept); + float share = random_unit() * HAEMO_BURST_DAMAGE_SPREAD + HAEMO_BURST_DAMAGE_MIN; + piece.SetCollisionDamage(collisionDamage / HAEMO_BURST_DAMAGE_SHARE * share); + piece.baseScale = std::max(share * fScale * HAEMO_BURST_SCALE, TEAR_SCALE_MIN); + piece.fScale = piece.baseScale; + piece.ResetSpriteScale(); + piece.height = std::min(height, HAEMO_BURST_HEIGHT); + piece.posOffset.y = piece.get_height_offset_y(piece.height); + if (tear_room_is_crawlspace()) + { + piece.posOffset.y = BURST_CRAWLSPACE_OFFSET; + piece.height = std::min(piece.height, CRAWLSPACE_HEIGHT_MAX); + } + piece.fallingAccel = HAEMO_BURST_FALL_ACCEL; + piece.fallingSpeed = (random_unit() * HAEMO_BURST_FALL_SPREAD + HAEMO_BURST_FALL_MIN) * fallHeight * SPLASH_HALF; + piece.SetColor(sprite.color, -1, TEAR_COLOR_PRIORITY, false, true); + piece.isPrismTouched = isPrismTouched; + piece.isMultidimensionalTouched = isMultidimensionalTouched; + piece.Update(); + } +} diff --git a/src/entity_tear_flags.cpp b/src/entity_tear_flags.cpp new file mode 100644 index 0000000..e9f82d0 --- /dev/null +++ b/src/entity_tear_flags.cpp @@ -0,0 +1,1301 @@ +#include "entity_tear.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_laser.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_slot.h" +#include "game.h" +#include "grid_entity_door.h" +#include "grid_entity_lock.h" +#include "log.h" +#include "npc_ai.h" +#include "npc_caves.h" +#include "room.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include + +// Remote Detonator's tears blow up at once when its player sets it off. +constexpr float DETONATE_DAMAGE = 3; + +// A laser shot tear: the beam it hides in, short and following its flight, eased toward it, lasting while it flies. +constexpr float LASERSHOT_REACH = 30; +constexpr int LASERSHOT_TIMEOUT = 1000; +constexpr int LASERSHOT_LEFT_MAX = 10; +constexpr float LASERSHOT_EASE = 0.5f; + +// Tiny Planet's orbit: its radius (a boomerang tear's by its height), its pull back to it, the player's aim it is +// pushed off, and My Reflection's and the explosive tears' bounds. +constexpr float ORBIT_DISTANCE = 120; +constexpr float ORBIT_PULL_SHARE = 0.1f; +constexpr float ORBIT_AIM_OFFSET = 60; +constexpr float ORBIT_BOOMERANG_HIGH = -5; +constexpr float ORBIT_BOOMERANG_LOW = -24; +constexpr float ORBIT_BOOMERANG_MIN = 0.05f; +constexpr float ORBIT_BOOMERANG_MAX = 1.5f; +constexpr float ORBIT_EXPLOSIVE_MIN = 0.4f; +constexpr float ORBIT_PULL_BASE = 2.5f; +// The other orbits (Linger Bean's, the familiars'): their distance (closer while waiting), the side test, the +// steps they take toward their spot, and the Ludovico ring's. +constexpr float ORBIT_FAR = 90; +constexpr float ORBIT_NEAR = 30; +constexpr float ORBIT_SIDEWAYS_DOT = 0.8f; +constexpr float ORBIT_STEP_MIN = 5; +constexpr float ORBIT_STEP_SHARE = 0.5f; +constexpr float ORBIT_LUDOVICO_REACH = 100; +constexpr float ORBIT_LUDOVICO_PULL = 0.01f; +constexpr float ORBIT_ZERO_DISTANCE = 0.1f; + +// C Section's fetus: its drag over its first ten frames, its search and pull, and the +// turn it spins its sprite with. +constexpr float FETUS_DRAG_FRAMES = 10; +constexpr float FETUS_DRAG_SPAN = 2; +constexpr float FETUS_FRICTION_BASE = 0.9f; +constexpr float FETUS_FRICTION_SHARE = 0.1f; +constexpr float FETUS_HOMING_FRAMES = 45; +constexpr int FETUS_HIT_RESET_FRAMES = 8; +constexpr float FETUS_PULL_BASE = 1.35f; +constexpr float FETUS_PULL_DOT = 0.1f; +constexpr float FETUS_DRAG_BASE = 0.92f; +constexpr float FETUS_DRAG_DOT = 0.05f; +constexpr float FETUS_DRAG_NEAR = 0.08f; +constexpr float FETUS_DRAG_DISTANCE = 0.0005f; +constexpr float FETUS_DRAG_MAX = 0.98f; +constexpr float FETUS_TURN = 2; +constexpr float FETUS_TURN_HOMING = 12; +constexpr float FETUS_SPIN = 2; + +// Homing's search: every fourth frame, ahead of the tear, within 128, a random part, a target already hit last. +constexpr float HOMING_LOOK_AHEAD = 5; +constexpr float HOMING_RADIUS = 128; +constexpr float HOMING_SCORE_NONE = 1e9f; + +// Strange Attractor: its pull growing over its first frames (or a stuck tear's), reach and the point ahead of it. +constexpr float ATTRACT_START = 10; +constexpr float ATTRACT_STRENGTH = 20; +constexpr float ATTRACT_STUCK_STRENGTH = 8; +constexpr float ATTRACT_RADIUS = 250; +constexpr float ATTRACT_LOOK_AHEAD = 4; +// Game::AttractEntities: the nearest distance it pulls from, how close it drags instead, and the enemies' stronger pull. +constexpr float ATTRACT_DISTANCE_MIN = 5; +constexpr float ATTRACT_NEAR = 10; +constexpr float ATTRACT_NEAR_DRAG = 0.9f; +constexpr float ATTRACT_NEAR_SHARE = 100; +constexpr float ATTRACT_ENEMY_SCALE = 4; +constexpr int ENTITY_TYPE_ENEMY_FIRST = 10; +constexpr int ENTITY_TYPE_ENEMY_END = 1000; + +// The trails some tears leave every other frame: the balloons' smoke and blood, and the G-Fuel missiles' dust. +constexpr float TRAIL_SPEED_SHARE = 0.3f; +constexpr float TRAIL_SPREAD = 3; +constexpr float SMOKE_SCALE = 0.8f; +constexpr float HAEMO_SCALE = 0.5f; +constexpr float TRAIL_SIZE_MIN = 0.4f; +constexpr float TRAIL_SCALE_SPREAD = 0.4f; +constexpr float HAEMO_SPEED_MIN = 0.5f; +constexpr int TRAIL_RENDER_Z = -400; +constexpr float GFUEL_TRAIL_SPEED_SHARE = 0.14f; +constexpr float GFUEL_TRAIL_BACK = 5; +constexpr float GFUEL_TRAIL_SPIN_MIN = 2; +constexpr float GFUEL_TRAIL_SPIN_SPREAD = 10; +constexpr int GFUEL_TRAIL_TIMEOUT = 15; +constexpr float GFUEL_TRAIL_SCALE = 0.4f; +constexpr float GFUEL_TRAIL_DEPTH = -18; +constexpr ColorMod GFUEL_TRAIL_COLOR = {{1, 1, 1, 0.3f}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Godhead's aura: its reach by the tear's size, and the burn it deals every frame to what is inside it. +constexpr float GLOW_QUERY_SCALE = 3; +constexpr float GLOW_QUERY_REACH = 100; +constexpr float GLOW_REACH_SCALE = 4; +constexpr float GLOW_DAMAGE = 2; +constexpr int GLOW_COUNTDOWN = 30; + +// The slowing and speeding tears over their first ten frames, and the speeding ones' limit. +constexpr float SPEED_FLAG_FRAMES = 10; +constexpr float DECELERATE_END = 0.8f; +constexpr float ACCELERATE_START = 0.8f; +constexpr float ACCELERATE_END = 1.2f; +constexpr float ACCELERATE_MAX = 30; + +// Lachryphagy: its growth limit by its player's fire delay and damage, its drag, when it bursts, the burst's speed, +// and how much it grows by the tears it eats. +constexpr float ABSORB_FIRE_DELAY = 10; +constexpr float ABSORB_DAMAGE = 3.5f; +constexpr float ABSORB_SCALE_MIN = 3; +constexpr float ABSORB_SCALE_MAX = 10; +constexpr float ABSORB_FRICTION = 0.95f; +constexpr int ABSORB_START_FRAMES = 10; +constexpr float ABSORB_BURST_DELAYS = 5; +constexpr int ABSORB_BURST_FRAMES_MAX = 150; +constexpr int ABSORB_BURST_FRAMES_MIN = 80; +constexpr float ABSORB_BURST_PER_SCALE = 5; +constexpr float ABSORB_BURST_MAX = 8; +constexpr int ABSORB_BURST_SPLIT = 4; +constexpr float ABSORB_BURST_QUADSPLIT = 1.5f; +constexpr int ABSORB_BURST_MIN = 3; +constexpr float ABSORB_BURST_SPEED = 10; +constexpr float ABSORB_BURST_HEIGHT = -6; +constexpr float ABSORB_BURST_HALF = 0.5f; +constexpr float ABSORB_HYDRO_FALL = -15; +constexpr float ABSORB_HYDRO_ACCEL = 3; +constexpr float ABSORB_QUERY_SCALE = 4; +constexpr float ABSORB_REACH_MIN = 5; +constexpr float ABSORB_GROWTH_SHARE = 50; +constexpr float ABSORB_GROWTH_MIN = 0.2f; +constexpr float ABSORB_GROWTH_MAX = 1; + +// The chained tears: how long one looks for a link, the parent it hangs from first, the reach of the links it makes, +// the chain's length, and the springs between links. +constexpr float CHAIN_LINK_FRAMES = 8; +constexpr float CHAIN_PARENT_DISTANCE = 10; +constexpr float CHAIN_PARTNER_FRAMES = 15; +constexpr int CHAIN_PARTNER_INTERVAL = 4; +constexpr int CHAIN_LENGTH_MAX = 5; +constexpr int CHAIN_PARTNER_CHANCE = 10; +constexpr float CHAIN_NEAREST_REACH = 40; +constexpr float CHAIN_PARTNER_REACH = 20; +constexpr float CHAIN_REST_LENGTH = 10; +constexpr float CHAIN_STIFFNESS = 0.3f; +constexpr float CHAIN_FRICTION = 0.95f; + +// Pop!'s tears bounce off each other a little harder than they hit. +constexpr float POP_QUERY_SCALE = 4; +constexpr float POP_REACH_SHARE = 0.9f; +constexpr float POP_BOUNCE = 1.1f; +constexpr float POP_FRICTION = 0.96f; +constexpr int POP_BOUNCES_MAX = 8; +constexpr float POP_STILL_SQUARED = 0.01f; + +// A Chaos Card sticks in the wall it reaches, the keys open what they hit, the flames fade and weaken off their +// spawner, the steered tears ease back toward their parent, and Continuum's tears cycle their tint. +constexpr float CHAOS_CARD_MARGIN_TOP = -1; +constexpr float CHAOS_CARD_MARGIN_SIDE = -20; +constexpr float CHAOS_CARD_MARGIN_BOTTOM = -40; +constexpr float KEY_BRIDGE_REACH = 40; +constexpr int KEY_ROCK_CHANCE = 8; +constexpr float KEY_PICKUP_REACH = 24; + +constexpr float FIRE_FAR = 160; +constexpr float FIRE_FAR_DAMAGE = 0.4f; +constexpr float FIRE_FRAMES = 15; +constexpr float FIRE_SCALE_MIN = 0.3f; +constexpr float FIRE_FADE_FRAMES = 30; +constexpr float FIRE_FADE_MAX = 0.4f; +constexpr float FLAME_SIZE_MIN = 0.4f; +constexpr float FIRE_SIZE_SCALE = 5; +constexpr float STEER_REACH = 50; +constexpr float STEER_PULL = 0.1f; +constexpr float STEER_EASE = 0.3f; +constexpr float STEER_HEIGHT = -23; +constexpr float STEER_HEIGHT_EASE = 0.4f; +constexpr int STEER_TINT_FRAMES = 8; +constexpr float STEER_ANGLE_RESET = 0.015f; +constexpr ColorMod STEER_TINT = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.35f, 0.45f, 0.5f}}; +constexpr float CONTINUUM_MARGIN = -100; +constexpr int CONTINUUM_TINT_FRAMES = 2; +constexpr int CONTINUUM_TINT_STEPS = 9; +constexpr int CONTINUUM_BLACK_STEP = 5; + +// The sticking tears: their growth while stuck, the end of their hold, Explosivo's blast, and Mucormycosis' cloud and +// the spores it throws at the enemies nearby. +constexpr float STICKY_DAMAGE = 60; +// A fetus bounces off what it hits at half its speed plus two, at most ten. Dr. Fetus' bomb from its first hit: a +// weaker blast for a small fetus, its damage, lift, hop and fuse. +constexpr float FETUS_BOUNCE_SHARE = 0.5f; +constexpr float FETUS_BOUNCE_MIN = 2; +constexpr float FETUS_BOUNCE_MAX = 10; +constexpr float FETUS_BOMB_SMALL = 0.55f; +constexpr float FETUS_BOMB_MEDIUM = 0.75f; +constexpr float FETUS_BOMB_BLAST_SMALL = 0.65f; +constexpr float FETUS_BOMB_BLAST_MEDIUM = 0.8f; +constexpr float FETUS_BOMB_DAMAGE_SCALE = 5; +constexpr float FETUS_BOMB_DAMAGE_BASE = 30; +constexpr float FETUS_BOMB_DAMAGE_MAX = 10; +constexpr float FETUS_BOMB_LIFT = -3; +constexpr float FETUS_BOMB_HOP = 5; +constexpr int FETUS_BOMB_FUSE = 20; +// Eye of Belial's turned tear: its growth, largest scale and least glow. +constexpr float BELIAL_GROWTH = 1.3f; +constexpr float BELIAL_SCALE_MAX = 32; +constexpr float BELIAL_GLOW = 0.3f; +constexpr int STICK_FRAMES = 60; +constexpr int BOOGER_STICK_FRAMES = 300; +constexpr float STICK_QUERY_REACH = 100; +constexpr int STICK_TEARS_MAX = 15; +constexpr float STICKY_DAMAGE_BOMBS = 50; +constexpr float STICKY_BOMB_FLAGS_MIN = 1.5f; +constexpr float SPORE_FART_RADIUS = 85; +constexpr int SPORE_COUNT_MIN = 2; +constexpr int SPORE_COUNT_SPREAD = 3; +constexpr int SPORE_CHILD_COUNT_SPREAD = 2; +constexpr float SPORE_SPREAD = 0.8f; +constexpr float SPORE_SLOT_OFFSET = 0.4f; +constexpr float SPORE_QUERY_RADIUS = 200; +constexpr float SPORE_LEAD = 0.1f; +constexpr float SPORE_SPEED_MIN = 8; +constexpr float SPORE_SPEED_SPREAD = 4; +constexpr float SPORE_SCALE = 0.2f; + +// Black Isaac's seed blackens every tear. +constexpr ColorMod BLACK_TEAR_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Whether a tear carries Chain's flag (Entity_Tear's chain checks). +static bool is_chained(Entity* entity) +{ + return entity && entity->type == ENTITY_TEAR && static_cast(entity)->tearFlags[TEAR_CHAIN]; +} + +// 00705b90 Pulls the vulnerable enemies (four times as hard) and the free pickups and closed chests within a reach +// toward a point, harder the nearer, by their speed over their mass. Within 10 they drag and are pulled gently. +// The original passes a filter callback. Its one user, Entity_Effect::rift_attract_filter, spares one entity. +void entities_attract(const Attraction& attraction) +{ + bool isVersus = g_game->deathmatchManager.is_active(); + for (Entity* entity : g_game->room->entityList.updateEL) + { + bool isVersusPlayer = isVersus && entity->type == ENTITY_PLAYER; + bool isEnemy = isVersusPlayer || (entity->type >= ENTITY_TYPE_ENEMY_FIRST && entity->type < ENTITY_TYPE_ENEMY_END); + bool isTargetable = entity->entityCollisionClass > ENTCOLL_PLAYERONLY && !entity->isInvincible && + !entity->isDead && !entity->HasEntityFlags(FLAG_FRIENDLY) && + (!entity->HasEntityFlags(FLAG_NO_TARGET) || entity->type == ENTITY_HUSH || + entity->type == ENTITY_ULTRA_GREED); + bool isPickup = entity->type == ENTITY_PICKUP; + if (!(isEnemy && isTargetable) && !isPickup) continue; + if (isPickup) + { + auto& pickup = *static_cast(entity); + if (pickup.price != 0 || (Entity_Pickup::IsChest(pickup.variant) && pickup.subtype == 0)) continue; + } + if (entity == attraction.spared) continue; + + Vector toward = vector_sub(attraction.position, entity->pos); + float distanceSquared = vector_length_squared(toward); + if (distanceSquared >= attraction.radius * attraction.radius) continue; + float distance = std::sqrt(distanceSquared); + float reach = std::max(distance, ATTRACT_DISTANCE_MIN); + if (distance > 0) toward = vector_scale(toward, 1 / distance); + float strength = isEnemy && !isPickup ? attraction.strength * ATTRACT_ENEMY_SCALE : attraction.strength; + + float pull = strength / reach; + if (reach < ATTRACT_NEAR) + { + entity->velocity = vector_scale(entity->velocity, npc_friction_scaled(ATTRACT_NEAR_DRAG, entity->speedMultiplier)); + pull = reach / ATTRACT_NEAR_SHARE; + } + if (entity->mass != 0) + entity->velocity = vector_add(entity->velocity, vector_scale(toward, entity->speedMultiplier * pull / entity->mass)); + } +} + +// (006670f0's Remote Detonator) A tear its player detonates turns explosive and dies at once. +void Entity_Tear::detonate_update(Entity_Player* player) +{ + if (!tearFlags[TEAR_DETONATE] || !player || !player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_REMOTE_DETONATOR)) + return; + tearFlags.reset(TEAR_DETONATE); + tearFlags.set(TEAR_EXPLOSIVE); + SetCollisionDamage(DETONATE_DAMAGE); + isDead = true; + deathFlags = TEAR_DEATH_FORCED; +} + +// (006670f0's laser shot) A laser shot tear hides in a short Technology beam of its player's that it carries along +// its flight, eased toward its direction, which keeps going a little after it dies. Without the flag the beam goes. +void Entity_Tear::lasershot_update() +{ + if (!tearFlags[TEAR_LASERSHOT]) + { + if (!laserShotLaser) return; + isVisible = true; + entityCollisionClass = ENTCOLL_ALL; + laserShotLaser->Remove(); + laserShotLaser = nullptr; + return; + } + + Vector flight = waitFrames < 1 ? velocity : continueVelocity; + if (!laserShotLaser) + { + Entity_Player* player = GetRootPlayer(); + if (!player) player = g_game->GetPlayer(0); + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = pos, .posOffset = vector_make(0, height), + .source = player, .angleDegrees = vector_angle(velocity), + .timeout = LASERSHOT_TIMEOUT, .variant = LASER_SHOOP, + .isPoolKept = true}); + if (!laser) + { + tearFlags.reset(TEAR_LASERSHOT); + isVisible = true; + entityCollisionClass = ENTCOLL_ALL; + return; + } + laser->parent = this; + laser->maxDistance = LASERSHOT_REACH; + laser->SetCollisionDamage(collisionDamage); + laser->SetColor(sprite.color, -1, TEAR_COLOR_PRIORITY, false, true); + TearFlags flags = tearFlags; + for (int dropped : {TEAR_BOUNCE, TEAR_ORBIT, TEAR_HYDROBOUNCE, TEAR_SPLIT, TEAR_CONTINUUM}) flags.reset(dropped); + laser->tearFlags = flags; + laser->isDisableInitSound = true; + laser->isMultidimensionalTouched = true; + laser->isPrismTouched = true; + laser->set_aim_angle(vector_angle(flight)); + laser->Update(); + laserShotLaser = laser; + isVisible = false; + if (!tearFlags[TEAR_EXPLOSIVE]) entityCollisionClass = ENTCOLL_NONE; + } + + auto* laser = laserShotLaser->type == ENTITY_LASER ? static_cast(laserShotLaser.get()) : nullptr; + if (!laser) return; + laser->set_aim_angle(angle_lerp(laser->angleDegrees, vector_angle(flight), LASERSHOT_EASE)); + if (!isDead) + { + laser->timeout = LASERSHOT_TIMEOUT; + return; + } + laser->timeout = std::min(laser->timeout, LASERSHOT_LEFT_MAX); + laser->velocity = velocity; + laserShotLaser = nullptr; +} + +// (006670f0's Ludovico water bounce) A Ludovico water tear bobs on a sine of its height over its fall, splashing on +// the floor each time the bob turns. The vertical motion its sprite turns with, its fall speed otherwise. +float Entity_Tear::ludovico_hydrobounce_update() +{ + if (!tearFlags[TEAR_LUDOVICO] || !tearFlags[TEAR_HYDROBOUNCE]) return fallingSpeed; + + float rate = PI_F / fallingSpeed; + float before = std::sin((float)(FrameCount() - 1) * rate); + float now = std::sin((float)FrameCount() * rate); + posOffset.y = std::fabs(now) * height; + float motion = posOffset.y - std::fabs(before) * height; + if (now * before < 0) + { + deathFlags = TEAR_DEATH_FLOOR; + isDead = true; + apply_death_flag_effects(nullptr); + } + return motion; +} + +// Tiny Planet: the tear curves around its player (or the spot it was given), keeping 120 off it on its side, the +// player's aim pushing the circle ahead. My Reflection's tears circle closer the lower they fly. +void Entity_Tear::orbit_plain_update(Entity* center) +{ + float side = (tearIdx & 1) ? -1.0f : 1.0f; + Vector offset{}; + Vector centerVelocity{}; + Vector next = vector_add(pos, velocity); + if (!vector_is_zero(targetPosition)) + { + offset = vector_sub(next, targetPosition); + orbitVelocity = {}; + } + else + { + offset = vector_sub(next, center->pos); + centerVelocity = center->velocity; + } + if (vector_is_zero(targetPosition) && center->is_player()) + offset = vector_sub(offset, vector_scale(center->ToPlayer()->aimDirection, ORBIT_AIM_OFFSET)); + + float distance = vector_length(offset); + if (distance == 0) return; + Vector away = vector_scale(offset, 1 / distance); + velocity = vector_sub(velocity, orbitVelocity); + + float radius = ORBIT_DISTANCE; + float pullScale = ORBIT_PULL_SHARE; + if (tearFlags[TEAR_BOOMERANG]) + { + float t = lerp_clamped(height, ORBIT_BOOMERANG_HIGH, ORBIT_BOOMERANG_LOW, ORBIT_BOOMERANG_MIN, ORBIT_BOOMERANG_MAX); + if (tearFlags[TEAR_EXPLOSIVE]) t = std::max(t, ORBIT_EXPLOSIVE_MIN); + radius = t * ORBIT_DISTANCE; + pullScale = (ORBIT_PULL_BASE - t) * ORBIT_PULL_SHARE; + } + float pull = (radius - distance) * pullScale; + float weight = std::clamp(distance / radius, 0.0f, 1.0f); + float flightAngle = vector_angle(velocity); + float turn = angle_wrap(vector_angle(away) + side * TEAR_RIGHT_ANGLE - flightAngle) * weight * weight; + float speed = vector_length(velocity); + Vector turned = vector_add(vector_scale(vector_from_angle(flightAngle + turn), speed), vector_scale(away, pull)); + velocity = vector_add(vector_scale(vector_normalized(turned), speed), centerVelocity); + orbitVelocity = centerVelocity; +} + +// The steadier orbit (a waiting Tiny Planet tear's, ORBIT_ADVANCED's): the tear picks its side and speed once, then +// steps toward its spot on a circle of 90 (30 while waiting) around its center, going round by its speed. +void Entity_Tear::orbit_steady_update(Entity* center) +{ + Vector anchor = targetPosition; + Vector anchorVelocity{}; + if (vector_is_zero(targetPosition)) + { + anchor = center->pos; + anchorVelocity = vector_scale(center->velocity, 1 / center->friction); + } + if (orbitRadius == 0) + { + Vector offset = vector_sub(pos, anchor); + Vector motion = waitFrames > 1 ? continueVelocity : velocity; + if (vector_dot(vector_normalized(offset), vector_normalized(motion)) < ORBIT_SIDEWAYS_DOT) + { + float side = vector_dot(tear_vector_rotate(offset, TEAR_RIGHT_ANGLE), motion) >= 0 ? 1.0f : -1.0f; + orbitRadius = vector_length(motion) * side; + orbitAngle = vector_angle(offset); + } + else + { + orbitRadius = vector_length(motion) * ((tearIdx & 1) ? 1.0f : -1.0f); + orbitAngle = vector_angle(motion); + } + } + + float distance = waitFrames > 0 ? ORBIT_NEAR : ORBIT_FAR; + Vector spot = vector_add(anchor, vector_scale(vector_from_angle(orbitAngle), distance)); + Vector lead = vector_scale(anchorVelocity, 2); + Vector step = vector_scale(vector_sub(spot, vector_add(pos, lead)), ORBIT_STEP_SHARE); + float stepMax = std::max(ORBIT_STEP_MIN, std::fabs(orbitRadius)); + if (vector_length(step) > stepMax) step = vector_resized(step, stepMax); + velocity = vector_scale(vector_add(lead, step), 1 / friction); + orbitAngle = angle_wrap(orbitRadius / distance * TEAR_HALF_TURN / PI_F * speedMultiplier + orbitAngle); + if (waitFrames > 1) continueVelocity = vector_scale(vector_from_angle(orbitAngle), std::fabs(orbitRadius)); +} + +// (006670f0's orbits) A tear with no target circles its spawner (or parent, or its target spot): Tiny Planet's +// plainly, the steady orbit while waiting or for ORBIT_ADVANCED, and Ludovico's main tear swirls around it. A tear on +// the Tractor Beam does not orbit. +void Entity_Tear::orbit_update() +{ + if ((!tearFlags[TEAR_ORBIT] && !tearFlags[TEAR_ORBIT_ADVANCED]) || target) return; + Entity* center = spawnerEntity ? spawnerEntity.get() : parent.get(); + + if (tearFlags[TEAR_LUDOVICO]) + { + if (!is_not_familiar_spawned() || !center) return; + Vector offset = vector_sub(pos, center->pos); + float distance = vector_length(offset); + if (distance == 0) distance = ORBIT_ZERO_DISTANCE; + Vector away = vector_scale(offset, 1 / distance); + Vector side = vector_make(away.y, -away.x); + if (vector_dot(side, velocity) < 0) side = vector_scale(side, -1); + AddVelocity_divided(vector_add(side, vector_scale(away, (ORBIT_LUDOVICO_REACH - distance) * ORBIT_LUDOVICO_PULL)), false); + return; + } + if ((!center && vector_is_zero(targetPosition)) || tearFlags[TEAR_TRACTOR_BEAM]) return; + if (!tearFlags[TEAR_ORBIT_ADVANCED] && waitFrames < 2) return orbit_plain_update(center); + orbit_steady_update(center); +} + +// The vulnerable enemy a searching tear picks ahead of it, each skipped half the time, scored by its distance plus a +// random part: not its spawner's kin, nor marked friendly or untargetable. A homing tear skips the enemies it hit and +// the invisible players, and one colliding with the grid needs a clear line. In versus the other players' familiars +// count too. +Entity* homing_target_find(Entity_Tear& tear, bool isFetus) +{ + Entity* best = nullptr; + float bestScore = HOMING_SCORE_NONE; + Vector ahead = vector_add(tear.pos, vector_scale(tear.velocity, HOMING_LOOK_AHEAD)); + + for (Entity* enemy : entity_query_radius(ahead, HOMING_RADIUS, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr)) continue; + if (tear.spawnerEntity && tear.spawnerEntity->IsDescendantOf(enemy)) continue; + if (enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) continue; + if (!isFetus && EntityList::HitListContains(tear.hitList, *enemy)) continue; + if (!isFetus && enemy->type == ENTITY_PLAYER && static_cast(enemy)->IsInvisible()) continue; + if (random_below(2) == 0) continue; + if (tear.entityGridCollisionClass == GRIDCOLL_BULLET && + !room_check_line(tear.pos, enemy->pos, LINE_MODE_PROJECTILE, 0)) + continue; + + float score = vector_length(vector_sub(ahead, enemy->pos)) + random_unit() * HOMING_RADIUS; + if (score < bestScore) + { + best = enemy; + bestScore = score; + } + } + if (!isFetus && g_game->deathmatchManager.is_active()) + reconstruction_missing("Entity_Tear::Update 006670f0: homing on the versus mode's familiars"); + return best; +} + +// (006670f0's fetus) C Section's fetus: it drags hard over its first frames, forgets its hits every eighth frame, +// searches a target every fourth, and pulls and turns toward it, harder over its first 45 frames (and homing). +// The weapons it carries (a Tech X ring, a sword, a knife, a club, a Technology laser) are not written yet. +void Entity_Tear::fetus_update() +{ + for (int weapon : {TEAR_FETUS_TECHX, TEAR_FETUS_SWORD, TEAR_FETUS_KNIFE, TEAR_FETUS_BONE, TEAR_FETUS_TECH}) + if (tearFlags[weapon]) reconstruction_missing("Entity_Tear::Update 006670f0: a fetus' weapon"); + + float drag = 1 - std::clamp(updateTime / FETUS_DRAG_FRAMES, 0.0f, FETUS_DRAG_SPAN); + friction = drag * drag * FETUS_FRICTION_SHARE + FETUS_FRICTION_BASE; + float strength = std::min(updateTime / FETUS_HOMING_FRAMES, 1.0f); + if (IsFrame(FETUS_HIT_RESET_FRAMES, (int)index) && !stickTarget) hitList.clear(); + if (!target && IsFrame(TEAR_SEARCH_FRAMES, (int)index)) target = homing_target_find(*this, true); + if (!target) return; + + Vector fromTarget = vector_sub(pos, target->pos); + Vector away = vector_normalized(fromTarget); + float pull = (vector_dot(velocity, away) * FETUS_PULL_DOT + FETUS_PULL_BASE) * strength; + float near = std::max(0.0f, FETUS_DRAG_NEAR - vector_length(fromTarget) * FETUS_DRAG_DISTANCE); + float dragFactor = std::min(FETUS_DRAG_BASE - vector_dot(vector_normalized(velocity), away) * FETUS_DRAG_DOT + near, + FETUS_DRAG_MAX); + velocity = vector_sub(velocity, vector_scale(away, speedMultiplier * pull)); + velocity = vector_scale(velocity, npc_friction_scaled(dragFactor, speedMultiplier)); + float turn = (tearFlags[TEAR_HOMING] ? FETUS_TURN_HOMING : FETUS_TURN) * speedMultiplier; + float angle = angle_approach(vector_angle(velocity), vector_angle(vector_scale(fromTarget, -1)), turn); + velocity = vector_scale(vector_from_angle(angle), vector_length(velocity)); +} + +// (006670f0's fetus sprite) The fetus spins its frames with its speed, backwards flying left. +void Entity_Tear::fetus_spin() +{ + AnimationState& state = sprite.animState; + if (!state.animData) return; + float spin = vector_length(velocity) * FETUS_SPIN; + if (velocity.x < 0) spin = -spin; + float step = TEAR_FULL_TURN / (float)state.GetAnimationLength(); + float angle = angle_wrap(state.animFrame * step + spin * speedMultiplier); + if (angle < 0) angle += TEAR_FULL_TURN; + sprite.SetFrame(angle / step); +} + +// (006670f0's Strange Attractor) Pulls the enemies and pickups around toward a point ahead of the tear, harder as it +// flies on, steadily while it sticks in an enemy (which it spares). +void Entity_Tear::attractor_pull() +{ + if (!tearFlags[TEAR_ATTRACTOR]) return; + float t = std::clamp((updateTime - ATTRACT_START) / ATTRACT_START, 0.0f, 1.0f); + float strength = stickTarget ? ATTRACT_STUCK_STRENGTH : t * ATTRACT_STRENGTH * t; + entities_attract({.position = vector_add(pos, vector_scale(velocity, ATTRACT_LOOK_AHEAD)), + .spared = stickTarget.get(), + .radius = ATTRACT_RADIUS, + .strength = strength}); +} + +// (006670f0's trails) Every other frame the balloons leave a trail: the bomb balloon its smoke, the others blood, +// thrown back along their flight, sized by the tear and tinted like it. +void Entity_Tear::trail_spawn() +{ + bool isBomb = variant == TEAR_BALLOON_BOMB; + if ((!isBomb && variant != TEAR_BALLOON && variant != TEAR_BALLOON_BRIMSTONE) || !IsFrame(2, 0)) return; + + uint32_t seed = Random(); + Vector spread = vector_scale(random_direction(), random_unit() * TRAIL_SPREAD * fScale); + Vector trailVelocity = vector_add(vector_scale(velocity, TRAIL_SPEED_SHARE), spread); + Entity* trail = g_game->Spawn({.position = pos, .velocity = trailVelocity, .type = ENTITY_EFFECT, + .variant = isBomb ? EFFECT_DARK_BALL_SMOKE_PARTICLE : EFFECT_HAEMO_TRAIL, .seed = seed}); + if (!isBomb) trail->sprite.playbackSpeed = random_unit() * TRAIL_SCALE_SPREAD + HAEMO_SPEED_MIN; + float scale = fScale * (isBomb ? SMOKE_SCALE : HAEMO_SCALE) * (random_unit() * TRAIL_SCALE_SPREAD + TRAIL_SIZE_MIN); + trail->sprite.scale = vector_make(scale, scale); + trail->posOffset = posOffset; + trail->renderZOffset = TRAIL_RENDER_Z; + trail->sprite.color = sprite.color; + trail->Update(); +} + +// (006670f0's G-Fuel missiles) Every other tick a visible missile puffs dust behind it, faint and spinning. +void Entity_Tear::gfuel_trail_spawn(float angle) +{ + if (variant != TEAR_NAIL_BLOOD || !g_game->seedEffects.HasSeedEffect(SEED_G_FUEL)) return; + if (GetIntervalTicks(2, 0) == 0 || !isVisible) return; + + uint32_t seed = Random(); + Vector back = vector_scale(vector_from_angle(angle), GFUEL_TRAIL_BACK * fScale); + Entity* dust = g_game->Spawn({.position = vector_sub(pos, back), .velocity = vector_scale(velocity, GFUEL_TRAIL_SPEED_SHARE), + .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = seed}); + auto& effect = *static_cast(dust); + effect.SetColor(GFUEL_TRAIL_COLOR, -1, TEAR_COLOR_PRIORITY, false, true); + effect.rotation = random_unit() * GFUEL_TRAIL_SPIN_SPREAD + GFUEL_TRAIL_SPIN_MIN; + effect.SetTimeout(random_below(GFUEL_TRAIL_TIMEOUT) + GFUEL_TRAIL_TIMEOUT); + effect.sprite.scale = vector_make(fScale * GFUEL_TRAIL_SCALE, fScale * GFUEL_TRAIL_SCALE); + effect.renderDepthOffset = GFUEL_TRAIL_DEPTH; + effect.posOffset = posOffset; +} + +// (006670f0's Godhead) The glowing tear burns the vulnerable enemies in a ring around it every frame, beyond its +// own touch, but not its spawner's kin. +void Entity_Tear::glow_burn() +{ + if (!tearFlags[TEAR_GLOW]) return; + for (Entity* enemy : entity_query_radius(pos, size * GLOW_QUERY_SCALE + GLOW_QUERY_REACH, QUERY_ALL)) + { + if (!enemy->IsVulnerableEnemy(nullptr)) continue; + if (spawnerEntity && spawnerEntity->IsDescendantOf(enemy)) continue; + float inner = enemy->size + size; + float outer = enemy->size + size * GLOW_REACH_SCALE; + float distanceSquared = vector_length_squared(vector_sub(enemy->pos, pos)); + if (distanceSquared < outer * outer && distanceSquared > inner * inner) + enemy->TakeDamage(GLOW_DAMAGE, 0, EntityRef(this), GLOW_COUNTDOWN); + } +} + +// (006670f0's speed flags) Over its first ten frames a slowing tear drags harder and a speeding one speeds up, to at +// most 30. Lachryphagy's, Ludovico's and Pop!'s tears keep their speed. +void Entity_Tear::speed_flags_update() +{ + if (tearFlags[TEAR_ABSORB] || tearFlags[TEAR_LUDOVICO] || tearFlags[TEAR_POP]) return; + if (tearFlags[TEAR_DECELERATE]) + friction *= lerp_clamped(updateTime, 0, SPEED_FLAG_FRAMES, 1, DECELERATE_END); + if (!tearFlags[TEAR_ACCELERATE]) return; + float factor = lerp_clamped(updateTime, 0, SPEED_FLAG_FRAMES, ACCELERATE_START, ACCELERATE_END); + velocity = vector_resized(velocity, std::min(vector_length(velocity) * factor, ACCELERATE_MAX)); +} + +// Lachryphagy's burst: the tear breaks into tears around it (more for a bigger tear, Parasite and Cricket's Body +// adding some) at its player's shot speed, half its size and damage, and is removed. Too few and it just stops +// eating. Whether it burst. +bool Entity_Tear::absorb_burst(float shotSpeed) +{ + int count = (int)std::clamp(fScale * ABSORB_BURST_PER_SCALE, 0.0f, ABSORB_BURST_MAX); + if (tearFlags[TEAR_SPLIT]) count += ABSORB_BURST_SPLIT; + if (tearFlags[TEAR_QUADSPLIT]) count = (int)((float)count * ABSORB_BURST_QUADSPLIT); + if (count < ABSORB_BURST_MIN) + { + tearFlags.reset(TEAR_ABSORB); + fallingSpeed = 0; + return false; + } + + float start = random_unit() * TEAR_FULL_TURN; + float step = TEAR_FULL_TURN / (float)count; + TearFlags flags = tearFlags; + for (int dropped : {TEAR_SPLIT, TEAR_QUADSPLIT, TEAR_ABSORB, TEAR_LUDOVICO, TEAR_FETUS_FLAG}) flags.reset(dropped); + for (int i = 0; i < count; i++) + { + uint32_t seed = Random(); + Vector pieceVelocity = vector_scale(vector_from_angle((float)i * step + start), shotSpeed * ABSORB_BURST_SPEED); + int pieceVariant = variant == TEAR_HUNGRY ? TEAR_BLOOD : variant; + Entity* spawned = g_game->Spawn({.position = pos, .velocity = pieceVelocity, .spawner = spawnerEntity, + .type = ENTITY_TEAR, .variant = pieceVariant, .seed = seed}); + Entity_Tear& piece = *spawned->ToTear(); + piece.SetHeight(std::min(height, ABSORB_BURST_HEIGHT)); + piece.SetScale(baseScale * ABSORB_BURST_HALF); + piece.SetTearFlags(flags); + piece.SetCollisionDamage(collisionDamage * ABSORB_BURST_HALF); + piece.SetColor(sprite.color, -1, TEAR_COLOR_PRIORITY, false, true); + piece.isMultidimensionalTouched = isMultidimensionalTouched; + piece.isPrismTouched = isPrismTouched; + piece.targetPosition = pos; + if (!tearFlags[TEAR_HYDROBOUNCE]) continue; + piece.fallingSpeed = ABSORB_HYDRO_FALL - piece.fallingSpeed; + piece.fallingAccel = ABSORB_HYDRO_ACCEL; + } + Remove(); + return true; +} + +// (006670f0's Lachryphagy) The tear hovers at its player's tear height, slowing, and after ten frames bursts once it +// is as big as its player's fire delay and damage allow, flew long enough or hit a wall. Until then it eats the +// tears it touches, growing and taking the stronger damage plus its player's, a bigger eating tear eating it instead. +void Entity_Tear::absorb_update() +{ + if (!tearFlags[TEAR_ABSORB] || tearFlags[TEAR_LUDOVICO]) return; + + Entity_Player* player = GetRootPlayer(); + float tearHeight = player ? player->tearHeight : PLAYER_TEAR_HEIGHT; + float damage = player ? player->damage : ABSORB_DAMAGE; + float fireDelay = player ? player->maxFireDelay : ABSORB_FIRE_DELAY; + float shotSpeed = player ? player->shotSpeed : 1; + float delayShare = fireDelay / ABSORB_FIRE_DELAY; + float scaleMax = std::max(std::min(delayShare * delayShare * std::sqrt(damage), ABSORB_SCALE_MAX), ABSORB_SCALE_MIN); + SetHeight(tearHeight); + fallingAccel = 0; + fallingSpeed = 0; + if (!tearFlags[TEAR_ORBIT] && !tearFlags[TEAR_ORBIT_ADVANCED]) friction *= ABSORB_FRICTION; + if (FrameCount() <= ABSORB_START_FRAMES) return; + + int burstFrames = std::max(std::min((int)(fireDelay * ABSORB_BURST_DELAYS), ABSORB_BURST_FRAMES_MAX), ABSORB_BURST_FRAMES_MIN); + bool isBursting = fScale >= scaleMax || FrameCount() >= burstFrames || isCollidesWithGrid; + if (isBursting && absorb_burst(shotSpeed)) return; + if (isDead) return; + + for (Entity* other : entity_query_radius(pos, fScale * size * ABSORB_QUERY_SCALE, QUERY_TEARS)) + { + Entity_Tear* eaten = other->ToTear(); + if (!eaten || eaten == this || eaten->isDead || eaten->tearFlags[TEAR_LUDOVICO]) continue; + if (g_game->deathmatchManager.is_active() && !eaten->IsDescendantOf(spawnerEntity)) continue; + float reach = std::max(eaten->size + size, ABSORB_REACH_MIN); + if (vector_length_squared(vector_sub(eaten->pos, pos)) > reach * reach) continue; + + bool isEatenFirst = fScale <= eaten->fScale && eaten->tearFlags[TEAR_ABSORB]; + Entity_Tear& eater = isEatenFirst ? *eaten : *this; + float growth = std::clamp(fireDelay * eater.baseScale / ABSORB_GROWTH_SHARE, ABSORB_GROWTH_MIN, ABSORB_GROWTH_MAX); + eater.SetScale(std::min(eater.baseScale + growth, scaleMax)); + eater.SetCollisionDamage(damage + std::max(collisionDamage, eaten->collisionDamage)); + if (!isEatenFirst) + { + eaten->Remove(); + continue; + } + Remove(); + break; + } +} + +// (0067ae30) Joins the tear into a chain just before another: it takes the other's link back, and the other links +// back to it. +void Entity_Tear::link_before(Entity_Tear& next) +{ + linkNext = &next; + linkPrev = next.linkPrev; + if (Entity* previous = next.linkPrev; previous && previous->type == ENTITY_TEAR) + static_cast(previous)->linkNext = this; + next.linkPrev = this; +} + +// (0067adc0) How many chained tears follow from this one along the links forward. +int Entity_Tear::chain_length() +{ + int length = 0; + for (Entity* link = this; is_chained(link); length++) + { + link = static_cast(link)->linkNext; + if (!link || link->type != ENTITY_TEAR) return length + 1; + } + return length; +} + +// 0067a770 The nearest chained tear within 40 not already linked back to another tear, or none. +Entity_Tear* Entity_Tear::find_nearest_linkable_tear() +{ + Entity_Tear* nearestLink = nullptr; + float nearest = CHAIN_NEAREST_REACH; + for (Entity* other : entity_query(ENTITY_TEAR, -1)) + { + auto* tear = static_cast(other); + if (tear == this || !tear->tearFlags[TEAR_CHAIN]) continue; + if (tear->linkPrev && tear->linkPrev->type == ENTITY_TEAR) continue; + float distance = vector_length(vector_sub(pos, tear->pos)); + if (distance >= nearest) continue; + nearest = distance; + nearestLink = tear; + } + return nearestLink; +} + +// 0067a8f0 The nearest chained tear within 20 at the end of a chain this tear is not in, or none. +Entity_Tear* Entity_Tear::find_link_partner() +{ + Entity_Tear* partner = nullptr; + float nearest = CHAIN_PARTNER_REACH; + for (Entity* other : entity_query(ENTITY_TEAR, -1)) + { + auto* tear = static_cast(other); + if (tear == this || !tear->tearFlags[TEAR_CHAIN] || tear->linkNext) continue; + + bool isFree = true; + for (Entity* link = tear; is_chained(link); link = static_cast(link)->linkPrev) + if (link == this) + { + isFree = false; + break; + } + float distance = vector_length(vector_sub(pos, tear->pos)); + if (!isFree || distance >= nearest) continue; + nearest = distance; + partner = tear; + } + return partner; +} + +// 0067aaf0 Springs the tear toward the tears it links to (10 apart), damping their difference in speed, and drags it. +void Entity_Tear::apply_link_spring_forces() +{ + int frame = g_game->frameCount; + if (frame - spawnFrame <= 0) return; + + Vector spring{}; + for (Entity* link : {linkPrev.get(), linkNext.get()}) + { + if (!link || frame - link->spawnFrame <= 0) continue; + Vector offset = vector_sub(prevPosition, link->prevPosition); + float distance = vector_length(offset); + if (distance > 0) offset = vector_scale(offset, 1 / distance); + Vector stretch = vector_scale(offset, (distance - CHAIN_REST_LENGTH) * CHAIN_STIFFNESS / speedMultiplier); + Vector damping = vector_scale(vector_sub(prevVelocity, link->prevVelocity), CHAIN_STIFFNESS / speedMultiplier); + spring = vector_sub(vector_sub(spring, stretch), damping); + } + if (!vector_is_zero(spring)) velocity = vector_add(velocity, vector_scale(spring, speedMultiplier)); + friction *= CHAIN_FRICTION; +} + +// (006670f0's Chain) A chained tear without a link hangs from its parent once it leaves it, or joins the nearest free +// chain, until its eighth frame. Past its fifteenth frame a short chain now and then links on to the end of another +// one. The links spring it along. +void Entity_Tear::chain_update() +{ + if (!tearFlags[TEAR_CHAIN]) return; + + if (!linkPrev) + { + if (updateTime >= CHAIN_LINK_FRAMES) tearFlags.reset(TEAR_CHAIN); + else if (parent && vector_length(vector_sub(pos, parent->pos)) > CHAIN_PARENT_DISTANCE) linkPrev = parent; + else if (Entity_Tear* nearest = find_nearest_linkable_tear()) link_before(*nearest); + } + bool isLinked = linkPrev && linkPrev->type == ENTITY_TEAR; + if (updateTime > CHAIN_PARTNER_FRAMES && !isLinked && IsFrame(CHAIN_PARTNER_INTERVAL, (int)index) && + chain_length() < CHAIN_LENGTH_MAX && random_below(CHAIN_PARTNER_CHANCE) == 0) + if (Entity_Tear* partner = find_link_partner()) + { + linkPrev = partner; + partner->linkNext = this; + } + apply_link_spring_forces(); +} + +// (006670f0's Pop!) The tear bounces off the tears it overlaps (each pair once), trading their speed along the hit a +// little harder and pushing both apart, and drags a little. +void Entity_Tear::pop_update() +{ + if (!tearFlags[TEAR_POP] || tearFlags[TEAR_LUDOVICO]) return; + for (Entity* other : entity_query_radius(pos, size * POP_QUERY_SCALE, QUERY_TEARS)) + { + Entity_Tear* tear = other->ToTear(); + if (!tear || tear->index > index) continue; + Vector separation = vector_sub(pos, tear->pos); + float reach = (tear->size + size) * POP_REACH_SHARE; + float distanceSquared = vector_length_squared(separation); + if (distanceSquared > reach * reach || distanceSquared == 0) continue; + + Vector direction = vector_normalized(separation); + float mine = vector_dot(velocity, direction); + float theirs = vector_dot(tear->velocity, direction); + float push = (reach - vector_length(separation)) * 0.5f; + velocity = vector_add(velocity, vector_scale(direction, (theirs - mine) * POP_BOUNCE)); + tear->velocity = vector_add(tear->velocity, vector_scale(direction, (mine - theirs) * POP_BOUNCE)); + pos = vector_add(pos, vector_scale(direction, push)); + tear->pos = vector_sub(tear->pos, vector_scale(direction, push)); + popBounceCount++; + tear->popBounceCount++; + npc_sound_play(SOUND_PING_PONG, 1, TEAR_SOUND_DELAY, 1); + } + friction *= POP_FRICTION; +} + +// Whether a Pop! tear still bounces about instead of falling: under nine bounces and moving. +bool Entity_Tear::is_popping() +{ + return tearFlags[TEAR_POP] && popBounceCount <= POP_BOUNCES_MAX && vector_length_squared(velocity) >= POP_STILL_SQUARED; +} + +// (006670f0's Chaos Card) The card sticks in the wall it reaches (flipped or turned to face it) and stops, and +// destroys the grid entity it ends up on. +void Entity_Tear::chaos_card_stick() +{ + if (isDead) return; + Room& room = *g_game->room; + Vector clamped = room.GetClampedPositionImpl(pos, CHAOS_CARD_MARGIN_TOP, CHAOS_CARD_MARGIN_SIDE, + CHAOS_CARD_MARGIN_BOTTOM, CHAOS_CARD_MARGIN_SIDE); + if (clamped.x != pos.x || clamped.y != pos.y) + { + sprite.Play("Stuck"); + if (pos.x < room.topLeftPos.x) + { + sprite.rotation = TEAR_RIGHT_ANGLE; + sprite.isFlipX = true; + } + else if (pos.x > room.bottomRightPos.x) sprite.rotation = TEAR_RIGHT_ANGLE; + else if (pos.y < room.topLeftPos.y) sprite.isFlipX = velocity.x < 0; + else if (pos.y > room.bottomRightPos.y) + { + sprite.isFlipX = velocity.x > 0; + sprite.isFlipY = true; + } + velocity = {}; + entityGridCollisionClass = GRIDCOLL_NONE; + entityCollisionClass = ENTCOLL_NONE; + isDead = true; + deathFlags |= TEAR_DEATH_GRID | TEAR_DEATH_WALL; + } + int gridIndex = room.GetGridIndex(pos); + if (gridIndex >= 0) room_grid_destroy({.source = EntityRef(this), .gridIndex = gridIndex}); +} + +// (006670f0's keys) A player's key tear opens what it reaches: a door (unlocking a locked one, breaking a secret +// room's), a lock block, and the rocks now and then (bridging the pit behind them), dying on what it opened when it +// stops at walls. It also opens the chests and plays the shell game it touches. +void Entity_Tear::key_open() +{ + if ((variant != TEAR_KEY && variant != TEAR_KEY_BLOOD) || isDead) return; + Entity_Player* player = spawnerEntity ? spawnerEntity->ToPlayer() : nullptr; + if (!player) return; + + Room& room = *g_game->room; + Vector ahead = vector_add(pos, velocity); + if (!vector_is_zero(velocity)) ahead = vector_add(ahead, vector_scale(vector_normalized(velocity), size)); + int gridIndex = room.GetGridIndex(ahead); + GridEntity* grid = gridIndex >= 0 ? room.GetGridEntity(gridIndex) : nullptr; + uint32_t collision = room_grid_collision_at(ahead); + bool isWallStopped = entityGridCollisionClass == GRIDCOLL_WALLS; + bool isPickupsTouched = true; + if (grid && grid->type == GRID_DOOR && collision == COLLISION_WALL) + { + auto& door = *static_cast(grid); + if (door.IsLocked() && !(door.doorFlags & DOOR_FLAG_COIN_LOCK)) door.TryUnlock(*player, true); + else if (door.IsRoomType(ROOM_SECRET) || door.IsRoomType(ROOM_SUPERSECRET)) door.Destroy(false, EntityRef()); + else if (door.state == DOOR_STATE_OPEN) isPickupsTouched = false; + else door.Open(); + if (isPickupsTouched && isWallStopped) isDead = true; + } + else if (grid && grid->type == GRID_LOCK) + { + if (grid->state == 0) + { + static_cast(grid)->try_unlock(*player, true); + if (isWallStopped) isDead = true; + } + } + else if (grid && (collision == COLLISION_SOLID || collision == COLLISION_OBJECT) && grid->collisionClass == COLLISION_SOLID && + (isWallStopped || random_below(KEY_ROCK_CHANCE) == 0) && grid->Destroy(false, EntityRef(this))) + { + if (isWallStopped) isDead = true; + Vector gridPosition = room.GetGridPosition(grid->gridIndex); + Vector beyond = vector_add(gridPosition, vector_scale(vector_cardinal(vector_sub(gridPosition, pos)), KEY_BRIDGE_REACH)); + int pitIndex = room.GetGridIndex(beyond); + if (pitIndex >= 0) room_bridge_make(room.GetGridEntity(pitIndex), grid); + } + if (!isPickupsTouched) return; + + for (Entity* entity : entity_query_radius(pos, KEY_PICKUP_REACH, QUERY_PICKUPS)) + { + bool isChest = entity->type == ENTITY_PICKUP && (entity->variant == PICKUP_LOCKEDCHEST || + entity->variant == PICKUP_ETERNALCHEST || + entity->variant == PICKUP_OLDCHEST); + if (isChest) static_cast(entity)->TryOpenChest(player); + else if (entity->type == ENTITY_SLOT && entity->variant == SLOT_SHELL_GAME) Entity::ForceCollide(player, entity, true); + } +} + +// (006670f0's flames) A flame weakens to 40% the further it gets from its spawner (within 160), grows to full size +// over its first 15 frames, fades out over 30 and sizes its collision to its sprite. +void Entity_Tear::fire_update() +{ + if (variant != TEAR_FIRE) return; + float damage = baseDamage; + if (spawnerEntity) + damage = lerp_clamped(vector_length(vector_sub(spawnerEntity->pos, pos)), 0, FIRE_FAR, baseDamage, + baseDamage * FIRE_FAR_DAMAGE); + collisionDamage = damage; + float scale = std::clamp(updateTime / FIRE_FRAMES, FIRE_SCALE_MIN, 1.0f); + sprite.scale = vector_make(scale, scale); + sprite.color._tint[3] = 1 - std::clamp(updateTime / FIRE_FADE_FRAMES, 0.0f, FIRE_FADE_MAX); + size = config->collisionRadius * std::max(scale, FLAME_SIZE_MIN) * FIRE_SIZE_SCALE; +} + +// (006670f0's steering, flag 103) A steered tear follows its parent: it eases toward a spot 50 off it along its +// flight (on its interval), carried by the parent's motion (kept in its target position), rises to the tear height +// and tints now and then. Off its interval it flies on along its steering angle at its interval speed. Whether it +// steered, which ends the frame. +bool Entity_Tear::steer_update() +{ + if (!tearFlags[TEAR_PARENT_STEER]) return false; + bool isIntervalFrame = !tearFlags[TEAR_INTERVAL_FLAGS] || FrameCount() < 1 || + (interval > 0 && GetIntervalTicks((float)interval, 0) == 0); + if (parent && isIntervalFrame) + { + Vector offset = vector_sub(vector_add(pos, velocity), parent->pos); + float distance = vector_length(offset); + if (distance != 0) + { + Vector direction = vector_scale(offset, 1 / distance); + steerAngle = vector_angle(direction); + velocity = vector_sub(velocity, targetPosition); + Vector push = vector_scale(direction, (STEER_REACH - distance) * STEER_PULL); + velocity = vector_add(velocity, vector_scale(vector_sub(push, velocity), STEER_EASE)); + velocity = vector_add(velocity, parent->velocity); + targetPosition = parent->velocity; + } + height = std::lerp(height, STEER_HEIGHT, STEER_HEIGHT_EASE); + if (IsFrame(STEER_TINT_FRAMES, 0)) + { + ColorMod tint = STEER_TINT; + color_multiply(tint, color); + SetColor(tint, -1, TEAR_COLOR_PRIORITY, false, true); + } + return true; + } + velocity = vector_scale(vector_from_angle(steerAngle), intervalSpeed); + steerAngle = STEER_ANGLE_RESET; + return false; +} + +// (006670f0's sticking) A sticky, booger or spore tear rides the enemy it stuck in until it lets go (or the enemy +// goes, freeing it to hit again), the booger and spore sprites pausing while stuck. When its hold ends it dies: +// Explosivo's explodes harder (more with its player's bomb effects), Mucormycosis' bursts into a cloud and throws +// spores at the enemies nearby. +void Entity_Tear::sticky_update(float scaleFactor) +{ + if (!tearFlags[TEAR_STICKY] && !tearFlags[TEAR_BOOGER_FLAG] && !tearFlags[TEAR_SPORE_FLAG]) return; + bool isPausing = variant == TEAR_BOOGER || variant == TEAR_SPORE; + if (!stickTarget) + { + if (isPausing && !sprite.IsPlaying("")) sprite.Play(sprite.animState.GetAnimation()); + return; + } + if (!stickTarget->isVisible || stickTarget->entityCollisionClass == ENTCOLL_NONE) + { + stickTarget = nullptr; + hitList.clear(); + if (isPausing) sprite.Play(sprite.animState.GetAnimation()); + } + else + { + velocity = stickTarget->velocity; + pos = vector_add(stickTarget->pos, stickDiff); + if (isPausing && sprite.IsPlaying("")) sprite.Stop(); + } + if (--stickTimer >= 1) return; + + isDead = true; + deathFlags |= TEAR_DEATH_FORCED; + fScale = std::max(scaleFactor * baseScale, TEAR_SCALE_MIN); + ResetSpriteScale(); + if (tearFlags[TEAR_STICKY]) + { + tearFlags.set(TEAR_EXPLOSIVE); + deathFlags |= TEAR_DEATH_EXPLOSION; + collisionDamage += STICKY_DAMAGE; + Entity_Player* player = GetRootPlayer(); + if (player && player->check_bomb_tearflags(TearFlags()) >= STICKY_BOMB_FLAGS_MIN) collisionDamage += STICKY_DAMAGE_BOMBS; + } + if (tearFlags[TEAR_SPORE_FLAG]) spores_burst(); +} + +// Mucormycosis' burst: a fart cloud, and from a tear stuck in an enemy two to four spores (none or one from a spore) +// aimed around at the nearest enemies not already aimed at, leading them, piercing, spectral and homing. +void Entity_Tear::spores_burst() +{ + Entity_Player* player = GetRootPlayer(); + game_fart({.position = pos, .source = player ? static_cast(player) : this, .radius = SPORE_FART_RADIUS}); + if (!stickTarget) return; + + int count = HasEntityFlags(FLAG_REDUCE_GIBS) ? random_below(SPORE_CHILD_COUNT_SPREAD) + : random_below(SPORE_COUNT_SPREAD) + SPORE_COUNT_MIN; + float start = random_unit() * TEAR_FULL_TURN; + std::vector aimed; + hit_list_insert(aimed, *stickTarget); + EntityList_EL nearby = entity_query_radius(pos, SPORE_QUERY_RADIUS, QUERY_ENEMIES); + TearFlags flags = tearFlags; + for (int dropped : {TEAR_QUADSPLIT, TEAR_SPLIT, TEAR_LUDOVICO, TEAR_BONE_FLAG, TEAR_ABSORB, TEAR_HYDROBOUNCE}) + flags.reset(dropped); + for (int added : {TEAR_PIERCING, TEAR_SPECTRAL, TEAR_HOMING}) flags.set(added); + + for (int i = 0; i < count; i++) + { + float angle = (random_unit() * SPORE_SPREAD + ((float)i - SPORE_SLOT_OFFSET)) * TEAR_FULL_TURN / (float)count + start; + Vector direction = vector_from_angle(angle); + Entity* nearest = nullptr; + float best = HOMING_SCORE_NONE; + for (Entity* enemy : nearby) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->HasEntityFlags(FLAG_FRIENDLY) || + EntityList::HitListContains(aimed, *enemy)) + continue; + float distance = vector_length_squared(vector_sub(vector_add(pos, vector_scale(direction, SPORE_QUERY_RADIUS)), enemy->pos)); + if (distance >= best) continue; + best = distance; + nearest = enemy; + } + if (nearest) + { + hit_list_insert(aimed, *nearest); + float lead = vector_length(vector_sub(pos, nearest->pos)) * SPORE_LEAD; + Vector predicted = vector_add(nearest->pos, vector_scale(nearest->velocity, lead)); + direction = vector_normalized(vector_sub(predicted, pos)); + } + + uint32_t seed = Random(); + float speed = random_unit() * SPORE_SPEED_SPREAD + SPORE_SPEED_MIN; + Entity* spawned = g_game->Spawn({.position = vector_sub(pos, velocity), .velocity = vector_scale(direction, speed), + .spawner = spawnerEntity, .type = type, .variant = variant, .seed = seed}); + Entity_Tear& spore = *spawned->ToTear(); + spore.SetHeight(PLAYER_TEAR_HEIGHT); + spore.SetTearFlags(flags); + spore.SetScale(fScale * SPORE_SCALE); + spore.SetColor(sprite.color, -1, TEAR_COLOR_PRIORITY, false, true); + spore.parent = parent; + hit_list_insert(spore.hitList, *stickTarget); + spore.AddEntityFlags(FLAG_REDUCE_GIBS); + spore.Update(); + } +} + +// (00673660's sticking) A sticky, booger or spore tear that hits an active enemy sticks in it where it hit: for a +// second (a booger five, one in versus), its sprite paused, no longer growing or shrinking. A seventeenth tear stuck +// in the same enemy is removed instead. A Ludovico tear leaves a copy of the sticking kind (Explosivo for a sticky +// one) on the enemy's edge, which hits it at once. Whether the hit ends there: the removal, or a forced collision. +bool Entity_Tear::stick(Entity& enemy) +{ + if (tearFlags[TEAR_LUDOVICO]) + { + ludovico_stick_copy(enemy); + return false; + } + if (stickTarget) return false; + + int stuck = 0; + for (Entity* other : entity_query_radius(enemy.pos, enemy.size + enemy.size + STICK_QUERY_REACH, QUERY_TEARS)) + if (other->type == ENTITY_TEAR && static_cast(other)->stickTarget.get() == &enemy) stuck++; + if (stuck > STICK_TEARS_MAX) + { + Remove(); + return true; + } + + stickTarget = &enemy; + stickDiff = vector_sub(pos, enemy.pos); + if (tearFlags[TEAR_STICKY] || tearFlags[TEAR_SPORE_FLAG]) stickTimer = STICK_FRAMES; + else if (tearFlags[TEAR_BOOGER_FLAG]) + stickTimer = g_game->deathmatchManager.is_active() ? STICK_FRAMES : BOOGER_STICK_FRAMES; + if (sprite.animState.animData) sprite.animState.isPlaying = false; + tearFlags.reset(TEAR_GROW); + tearFlags.reset(TEAR_SHRINK); + return g_forceCollideDepth != 0; +} + +// A Ludovico tear's sticking copy: a tear of its sticking kind spawned on the enemy's edge where the Ludovico tear +// touches it, with its flags but Ludovico's, its damage and size (the player's tear size when it has one), made to +// hit the enemy at once. +void Entity_Tear::ludovico_stick_copy(Entity& enemy) +{ + Vector offset = vector_sub(pos, enemy.pos); + float distance = vector_length(offset); + if (enemy.size < distance && distance > 0) offset = vector_scale(offset, enemy.size / distance); + int copyVariant = tearFlags[TEAR_BOOGER_FLAG] ? TEAR_BOOGER : tearFlags[TEAR_SPORE_FLAG] ? TEAR_SPORE : TEAR_EXPLOSIVO; + + uint32_t seed = Random(); + Entity_Tear& copy = *g_game->Spawn({.position = vector_add(enemy.pos, offset), .spawner = spawnerEntity, + .type = ENTITY_TEAR, .variant = copyVariant, .seed = seed})->ToTear(); + copy.Update(); + TearFlags copyFlags = tearFlags; + copyFlags.reset(TEAR_LUDOVICO); + copy.SetTearFlags(copyFlags); + copy.SetCollisionDamage(collisionDamage); + float scale = std::max(fScale, TEAR_SCALE_MIN); + copy.baseScale = scale; + copy.fScale = scale; + copy.ResetSpriteScale(); + Entity* ancestor = GetPlayerAncestor(); + if (Entity_Player* player = ancestor ? ancestor->ToPlayer() : nullptr) + { + int displacement = (int)(Random() & 1) * 2 - 1; + copy.SetScale(player->GetTearHitParams(WEAPON_TEARS, 1, displacement, nullptr).tearScale); + } + g_forceCollideDepth++; + copy.HandleCollision(&enemy, true); + enemy.HandleCollision(©, false); + g_forceCollideDepth--; +} + +// (00673660's fetus hit) A fetus that hurts something bounces off it at half its speed plus two (at most ten) unless +// it pierces or lasts, and its first hit drops Dr. Fetus' bomb once: a small fetus bomb with its flags, half its size, +// a short fuse and a little hop, its blast weaker for a small player's fetus. Each hit counts, and Pop!'s bounces too. +void Entity_Tear::fetus_hit(Entity& enemy) +{ + if (!tearFlags[TEAR_PIERCING] && !tearFlags[TEAR_PERSISTENT]) + { + float bounce = std::min(vector_length(velocity) * FETUS_BOUNCE_SHARE + FETUS_BOUNCE_MIN, FETUS_BOUNCE_MAX); + velocity = vector_add(velocity, vector_scale(vector_resized(vector_sub(pos, enemy.pos), bounce), speedMultiplier)); + } + if (hitCount == 0 && tearFlags[TEAR_FETUS_BOMBER]) + { + tearFlags.reset(TEAR_FETUS_BOMBER); + float blast = 1; + float half = fScale * 0.5f; + if (GetPlayerAncestor()) blast = half <= FETUS_BOMB_SMALL ? FETUS_BOMB_BLAST_SMALL : half <= FETUS_BOMB_MEDIUM ? FETUS_BOMB_BLAST_MEDIUM : 1; + float damage = collisionDamage * 0.5f; + + Entity_Bomb& bomb = *static_cast( + g_game->Spawn({.position = pos, .spawner = spawnerEntity, .type = ENTITY_BOMB, .seed = Random()})); + bomb.isFetus = true; + bomb.spawnerType = spawnerType; + bomb.spawnerVariant = spawnerVariant; + bomb.tearFlags = tearFlags; + bomb.isLoadCostumes = true; + bomb.scale = half; + bomb.SetSize(half, vector_make(-1, -1), -1); + bomb.explosionDamage = std::min(damage * FETUS_BOMB_DAMAGE_SCALE + FETUS_BOMB_DAMAGE_BASE, damage * FETUS_BOMB_DAMAGE_MAX); + bomb.radiusMultiplier = blast; + float hop = random_unit(); + bomb.AddEntityFlags(FLAG_NO_KNOCKBACK | FLAG_NO_REWARD); + bomb.posOffset = vector_make(0, FETUS_BOMB_LIFT); + bomb.explosionCountdown = FETUS_BOMB_FUSE; + bomb.explosionCountdown2 = FETUS_BOMB_FUSE; + bomb.fallSpeed = FETUS_BOMB_LIFT - hop * FETUS_BOMB_HOP; + } + hitCount++; + if (tearFlags[TEAR_POP]) popBounceCount++; +} + +// (00673660's Eye of Belial) The first hit of an Eye of Belial tear turns it into a homing Belial tear (a balloon +// keeps its look) with double damage, a third larger unless Ludovico holds it (at most 32), glowing at least a little. +void Entity_Tear::belial_turn() +{ + tearFlags.reset(TEAR_BELIAL_FLAG); + tearFlags.set(TEAR_HOMING); + if (variant != TEAR_BALLOON && variant != TEAR_BALLOON_BRIMSTONE && variant != TEAR_BALLOON_BOMB) + ChangeVariant(TEAR_BELIAL); + collisionDamage += collisionDamage; + if (!tearFlags[TEAR_LUDOVICO]) SetScale(std::min(baseScale * BELIAL_GROWTH, BELIAL_SCALE_MAX)); + SetDeadEyeIntensity(std::max(deadEyeIntensity, BELIAL_GLOW)); +} + +// (006670f0's interval flags) Every interval a tear with flag 102 resets to its interval speed, and one with flag +// 101 swaps its flags with the ones it keeps aside (unless both sets hold 101 and 102 together). +void Entity_Tear::interval_update() +{ + auto isIntervalFrame = [this]() { return interval < 1 || GetIntervalTicks((float)interval, 0) != 0; }; + if (tearFlags[TEAR_INTERVAL_SPEED] && isIntervalFrame() && FrameCount() > 0) + { + velocity = vector_resized(velocity, intervalSpeed); + if (!intervalFlags[TEAR_INTERVAL_FLAGS] || !intervalFlags[TEAR_INTERVAL_SPEED]) tearFlags.reset(TEAR_INTERVAL_SPEED); + } + if (tearFlags[TEAR_INTERVAL_FLAGS] && FrameCount() > 0 && isIntervalFrame()) std::swap(tearFlags, intervalFlags); +} + +// (006670f0's Continuum) The tear wraps around the screen's edges (back to its parent on the Tractor Beam), carrying +// a Ludovico ring along, and cycles its tint through the rainbow every other frame. +void Entity_Tear::continuum_update() +{ + if (!tearFlags[TEAR_CONTINUUM] || (tearFlags[TEAR_LUDOVICO] && !is_not_familiar_spawned())) return; + + Vector wrapped = room_screen_wrap(pos, CONTINUUM_MARGIN); + Vector shift = vector_sub(wrapped, pos); + if ((wrapped.x != pos.x || wrapped.y != pos.y) && tearFlags[TEAR_TRACTOR_BEAM] && parent) wrapped = parent->pos; + pos = wrapped; + if (tearFlags[TEAR_LUDOVICO]) + for (Entity* link = child; link; link = link->child) link->pos = vector_add(link->pos, shift); + if (!IsFrame(CONTINUUM_TINT_FRAMES, (int)index)) return; + + static constexpr std::array, CONTINUUM_TINT_STEPS> RAINBOW = {{ + {1, 0.33f, 1}, {1, 0.66f, 1}, {1, 1, 1}, {0.66f, 0.66f, 0.66f}, {0.33f, 0.33f, 0.33f}, + {0, 0, 0}, {0.33f, 0, 0.33f}, {0.66f, 0, 0.66f}, {1, 0, 1}}}; + ColorMod tint = COLOR_DEFAULT; + int step = FrameCount() / 2 % CONTINUUM_TINT_STEPS; + for (int i = 0; i < 3; i++) + { + if (step == CONTINUUM_BLACK_STEP) tint._tint[i] = 0; + else tint._colorize[i] = RAINBOW[step][i]; + } + if (step != CONTINUUM_BLACK_STEP) tint._colorize[3] = 1; + SetColor(tint, -1, TEAR_COLOR_PRIORITY, false, true); +} + +// Black Isaac's seed paints the tear black. +void Entity_Tear::black_seed_paint() +{ + if (!g_game->seedEffects.HasSeedEffect(SEED_BLACK_ISAAC)) return; + SetColor(BLACK_TEAR_COLOR, -1, TEAR_COLOR_PRIORITY, false, true); + sprite.color = BLACK_TEAR_COLOR; +} diff --git a/src/familiar_ai.cpp b/src/familiar_ai.cpp index 5d02f99..10f7126 100644 --- a/src/familiar_ai.cpp +++ b/src/familiar_ai.cpp @@ -566,9 +566,9 @@ void Entity_Familiar::TriggerRoomClear() } if (variant == GB_BUG && subtype != 0) state = 1; - if (variant == PASCHAL_CANDLE || variant == WISP) - reconstruction_missing("Entity_Familiar::TriggerRoomClear 0062aab0 " - "(Paschal Candle and the wisps)"); + if (variant == PASCHAL_CANDLE) + reconstruction_missing("Entity_Familiar::TriggerRoomClear 0062aab0 (Paschal Candle)"); + if (variant == WISP && !isDead && g_game->frameCount - spawnFrame > 1) wisp_room_clear(*this); } // 0062b750 Its player was hurt: Smart Fly turns aggressive, the Mystery Egg cracks, Damocles falls on a real hit. @@ -605,7 +605,7 @@ void Entity_Familiar::level_start() else if (variant == BUDDY_IN_A_BOX || variant == BUM_FRIEND) subtype = 0; else if (variant == UMBILICAL_BABY) Remove(); else if ((variant == LOST_SOUL && !g_game->isStartingFromState) || variant == BLOOD_OATH || - variant == PASCHAL_CANDLE || variant == WISP || variant == STAR_OF_BETHLEHEM) + variant == PASCHAL_CANDLE || variant == STAR_OF_BETHLEHEM) reconstruction_missing("Entity_Familiar::level_start 0062b360 (this familiar's new floor)"); pos = GetFollowTargetPosition(FOLLOW_EXACT); @@ -699,13 +699,13 @@ void Entity_Familiar::room_enter() case PUNCHING_BAG: case SPIDER_MOD: case SPIDER_BABY: - case WISP: - case ITEM_WISP: case STAR_OF_BETHLEHEM: case LOST_SOUL: case UMBILICAL_BABY: case BLOOD_PUPPY: case VANISHING_TWIN: reconstruction_missing("Entity_Familiar::room_enter 0062bb70 (this familiar's new room)"); + case WISP: + case ITEM_WISP: pos = GetOrbitPosition(player->pos); break; } if (isNotCountedAsFollower && !g_game->isStartingFromState && !isHourglassRewound) Remove(); diff --git a/src/familiar_collision.cpp b/src/familiar_collision.cpp index 94edba1..225be3b 100644 --- a/src/familiar_collision.cpp +++ b/src/familiar_collision.cpp @@ -25,10 +25,10 @@ constexpr int CONTACT_VARIANTS[] = {33, 60, 15, 14, 79, 77, 3, 104, 44, 4 32, 83, 121, 126, 226, 224, 210, 218, 206, 237, 229, 204}; // The familiars whose touch, block or hit has an effect of its own not reconstructed yet. -constexpr int UNWRITTEN_TOUCH_VARIANTS[] = {87, 243, 200, 105, 127, 206, 131, 204, 231, 237, 93}; +constexpr int UNWRITTEN_TOUCH_VARIANTS[] = {87, 243, 200, 105, 127, 131, 204, 231, 93}; constexpr int UNWRITTEN_BLOCK_VARIANTS[] = {228, 238, 201, 216, 217, 231}; -constexpr int UNWRITTEN_ENEMY_TOUCH_VARIANTS[] = {228, 238, 201, 216, 217, 206, 237}; -constexpr int UNWRITTEN_DEATH_VARIANTS[] = {128, 216, 217, 206, 237, 229, 234, 201, 238}; +constexpr int UNWRITTEN_ENEMY_TOUCH_VARIANTS[] = {228, 238, 201, 216, 217}; +constexpr int UNWRITTEN_DEATH_VARIANTS[] = {128, 216, 217, 229, 234, 201, 238}; // The familiars whose contact damage stays off until their dash or throw (a cooldown of -1), or while they rest. constexpr int DASHING_VARIANTS[] = {130, 232, 223}; @@ -524,9 +524,12 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) bool isOwnersFoe = !spawnerEntity || !spawnerEntity->IsDescendantOf(collider); if (isOwnersFoe && collider->IsActiveEnemy(DEAD_EXCLUDED) && - (collider->IsVulnerableEnemy(nullptr) || collider->CanShutDoors()) && - familiar_listed(UNWRITTEN_ENEMY_TOUCH_VARIANTS, variant)) - reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this familiar's enemy touch)"); + (collider->IsVulnerableEnemy(nullptr) || collider->CanShutDoors())) + { + if (familiar_listed(UNWRITTEN_ENEMY_TOUCH_VARIANTS, variant)) + reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this familiar's enemy touch)"); + if ((variant == WISP || variant == ITEM_WISP) && wisp_touch(*this, *collider)) return true; + } if (collider->type == ENTITY_PLAYER) { @@ -575,11 +578,14 @@ bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const Entit { if (IsDamageSourceFriendly(source) || source.IsFriendly()) return false; if ((damageFlags & (DAMAGE_SPIKES | DAMAGE_POOP)) && variant != ISAACS_HEART) return false; - if (variant == WISP || variant == ITEM_WISP || variant == LOST_SOUL || variant == MILK) + if (variant == LOST_SOUL || variant == MILK) reconstruction_missing("Entity_Familiar::TakeDamage 0062cdc0 (this familiar's hit)"); + bool isWisp = variant == WISP || variant == ITEM_WISP; + if (isWisp && !wisp_take_damage(source, damageFlags)) return false; + if (isWisp) damageCountdown = wisp_hit_countdown(damageCountdown); if (variant == BLOOD_BABY && counter > 0) return false; - bool isPassed = variant == ISAACS_HEART || (g_game->challenge == CHALLENGE_PONG && variant == PUNCHING_BAG); + bool isPassed = variant == ISAACS_HEART || (g_game->challenge == CHALLENGE_GUARDIAN && variant == PUNCHING_BAG); bool isDamaged = isPassed ? player->TakeDamage(damage, damageFlags | DAMAGE_ISAACS_HEART, source, damageCountdown) : Entity::TakeDamage(damage, damageFlags | DAMAGE_COUNTDOWN, source, damageCountdown); if (!isDamaged || damage <= 0) return isDamaged; @@ -591,17 +597,19 @@ bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const Entit } if (variant == DIP && (Random() & 1) == 0) familiar_sound_play(SOUND_DIP_HURT, {.volume = DIP_HURT_VOLUME, .frameDelay = DIP_HURT_DELAY}); + if (isWisp) wisp_countdown_share(*this); return isDamaged; } -// 00610540 A familiar's death: blood, then the entity's own kill and its removal. The familiars that die their own way -// (the bone orbitals, the wisps, the swarm flies, the Dips, the clots) stop the game. +// 00610540 A familiar's death: blood, then the entity's own kill and its removal. A wisp's flame goes out instead. The +// familiars that die their own way (the bone orbitals, the swarm flies, the Dips, the clots) stop the game. void Entity_Familiar::Kill(const EntityRef& source) { if (!isDead) { if (familiar_listed(UNWRITTEN_DEATH_VARIANTS, variant)) reconstruction_missing("Entity_Familiar::Kill 00610540 (this familiar's death)"); + if (variant == WISP || variant == ITEM_WISP) return wisp_death(source); Entity* blood = g_game->Spawn({.position = pos, .subType = 1, diff --git a/src/familiar_evaluate.cpp b/src/familiar_evaluate.cpp index 47c5910..8c5523e 100644 --- a/src/familiar_evaluate.cpp +++ b/src/familiar_evaluate.cpp @@ -5,6 +5,8 @@ #include "lua_engine.h" #include "manager.h" #include +#include +#include // How a collectible's familiars are counted: copies held and in effects, copies held only (at most one), copies in // effects only, held plus a null effect's copies, or twice the held ones. @@ -58,13 +60,10 @@ constexpr FamiliarSource LATE_FAMILIAR_SOURCES[] = {{565, 241}, {697, 242}}; constexpr int TRINKET_APOLLYONS_BEST_FRIEND = 186; constexpr int NULLITEM_SPIN_TO_WIN_FAMILIAR = 131; constexpr int FAMILIAR_SPIN_TO_WIN = 244; -constexpr int COLLECTIBLE_LEPROSY = 525; constexpr int COLLECTIBLE_MILK = 436; constexpr int COLLECTIBLE_HALO_OF_FLIES = 10; -constexpr int PILLEFFECT_PRETTY_FLY = 10; constexpr int NULLITEM_HALO_FLY_LOSS = 107; constexpr int HALO_FLY_CAP = 10; -constexpr int COLLECTIBLE_BEST_BUD = 274; constexpr int ACHIEVEMENT_CUBE_OF_MEAT_FULL = 144; constexpr int ACHIEVEMENT_BALL_OF_BANDAGES_FULL = 19; constexpr int COLLECTIBLE_BROWN_NUGGET = 504; @@ -78,7 +77,6 @@ constexpr int GIANTBOOK_SUPER_BUM = 38; constexpr std::pair SUPER_BUM_PARTS[] = {{COLLECTIBLE_KEY_BUM, Entity_Familiar::KEY_BUM}, {COLLECTIBLE_DARK_BUM, Entity_Familiar::DARK_BUM}, {COLLECTIBLE_BUM_FRIEND, Entity_Familiar::BUM_FRIEND}}; -constexpr int COLLECTIBLE_BIRD_CAGE = 610; constexpr int COLLECTIBLE_PEEPER_2 = 605; constexpr int TRINKET_ISAACS_HEAD = 54; constexpr int TRINKET_SOUL = 57; @@ -172,17 +170,90 @@ static void stages_check(Entity_Player& p, int collectible, int firstVariant, in if (full > 0) g_manager->persistentGameData.TryUnlock(achievement); } -// The shared pieces (the key and knife pieces counted across players) wait for their takeover. Holding Key Bum, -// Dark Bum and Bum Friend together makes Super Bum (with its page the first time) in place of the three. -static void shared_pieces_check(Entity_Player& p) -{ - for (Entity_Player* other : g_game->playerManager.playerList) - if (other->variant == PLAYER_VARIANT_PLAYER && - (other->GetCollectibleNum(COLLECTIBLE_KEY_PIECE_1) || other->GetCollectibleNum(COLLECTIBLE_KEY_PIECE_2) || - other->GetCollectibleNum(COLLECTIBLE_KNIFE_PIECE_1) || - other->GetCollectibleNum(COLLECTIBLE_KNIFE_PIECE_2))) - reconstruction_missing("Entity_Player::EvaluateItems 00763570 (the key and knife pieces)"); +// The key and knife pieces, each a first piece, a second one and the full familiar they make together. +constexpr int ACHIEVEMENT_DADS_KEY = 58; +constexpr int ACHIEVEMENT_FILIGREE_FEATHER = 370; +// One player's pieces of a kind: the first and second pieces held and the full ones they joined into. +struct HeldPieces +{ + int first = 0; + int full = 0; + int second = 0; +}; + +// One kind of pieces: the collectibles of its two pieces and the familiars of the pieces and the whole. +struct PieceKind +{ + int firstCollectible; + int secondCollectible; + int firstVariant; + int secondVariant; + int fullVariant; +}; + +constexpr PieceKind PIECE_KINDS[] = { + {COLLECTIBLE_KEY_PIECE_1, COLLECTIBLE_KEY_PIECE_2, Entity_Familiar::KEY_PIECE_1, Entity_Familiar::KEY_PIECE_2, + Entity_Familiar::KEY_FULL}, + {COLLECTIBLE_KNIFE_PIECE_1, COLLECTIBLE_KNIFE_PIECE_2, Entity_Familiar::KNIFE_PIECE_1, + Entity_Familiar::KNIFE_PIECE_2, Entity_Familiar::KNIFE_FULL}}; + +// Part of 00763570: the pieces of every player. A player's first pieces join the second pieces of each player in turn +// (their own included) into full ones of their own, then every player keeps the familiars of the pieces left and the +// full ones. A full key unlocks Dad's Key and Filigree Feather. +static void pieces_check() +{ + size_t count = g_game->playerManager.playerList.size(); + std::vector> held(count); + + for (size_t i = 0; i < count; i++) + { + Entity_Player& player = *g_game->GetPlayer((int)i); + if (player.variant != PLAYER_VARIANT_PLAYER) continue; + for (size_t kind = 0; kind < held[i].size(); kind++) + held[i][kind] = {.first = player.GetCollectibleNum(PIECE_KINDS[kind].firstCollectible), + .second = player.GetCollectibleNum(PIECE_KINDS[kind].secondCollectible)}; + } + for (size_t a = 0; a < count; a++) + for (size_t b = 0; b < count && (held[a][0].first || held[a][1].first); b++) + for (size_t kind = 0; kind < held[a].size(); kind++) + { + int joined = std::min(held[a][kind].first, held[b][kind].second); + held[a][kind].first -= joined; + held[b][kind].second -= joined; + held[a][kind].full += joined; + } + + for (size_t i = 0; i < count; i++) + { + Entity_Player& player = *g_game->GetPlayer((int)i); + if (player.variant != PLAYER_VARIANT_PLAYER) continue; + for (size_t kind = 0; kind < held[i].size(); kind++) + { + const PieceKind& pieces = PIECE_KINDS[kind]; + ItemConfig& items = g_manager->itemConfig; + RNG* firstRng = &player.GetCollectibleRNG(pieces.firstCollectible); + + familiar_check(player, {.item = items.GetCollectible(pieces.firstCollectible), + .rng = firstRng, + .count = held[i][kind].first, + .variant = pieces.firstVariant}); + familiar_check(player, {.item = items.GetCollectible(pieces.secondCollectible), + .rng = &player.GetCollectibleRNG(pieces.secondCollectible), + .count = held[i][kind].second, + .variant = pieces.secondVariant}); + familiar_check(player, {.rng = firstRng, .count = held[i][kind].full, .variant = pieces.fullVariant}); + if (kind != 0 || held[i][kind].full == 0) continue; + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_DADS_KEY); + g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_FILIGREE_FEATHER); + } + } +} + +// Holding Key Bum, Dark Bum and Bum Friend together makes Super Bum (with its page the first time) in place of the +// three. +static void super_bum_check(Entity_Player& p) +{ if (!p.HasCollectible(COLLECTIBLE_KEY_BUM) || !p.HasCollectible(COLLECTIBLE_DARK_BUM) || !p.HasCollectible(COLLECTIBLE_BUM_FRIEND)) { @@ -269,7 +340,8 @@ void familiars_evaluate(Entity_Player& p) effect_check(p, COLLECTIBLE_SCISSORS, Entity_Familiar::SCISSORS); effect_check(p, COLLECTIBLE_BROWN_NUGGET, Entity_Familiar::BROWN_NUGGET_POOTER); effect_check(p, COLLECTIBLE_SPRINKLER, Entity_Familiar::SPRINKLER); - shared_pieces_check(p); + pieces_check(); + super_bum_check(p); unwritten_familiars_check(p); familiar_check(p, {.rng = &formRng, diff --git a/src/familiar_follow.cpp b/src/familiar_follow.cpp index 42ba64e..3da82d2 100644 --- a/src/familiar_follow.cpp +++ b/src/familiar_follow.cpp @@ -291,7 +291,7 @@ void Entity_Familiar::FollowParent() if (player->HasTrinket(TRINKET_DUCT_TAPE)) return move_to_parent_offset(); if (!vector_is_zero(formationOffset)) reset_follow_target(); - if (g_game->challenge == CHALLENGE_PONG && variant == ISAACS_HEART) + if (g_game->challenge == CHALLENGE_GUARDIAN && variant == ISAACS_HEART) return reconstruction_missing("Entity_Familiar::FollowParent 00612bb0 (the punching bag challenge)"); bool isLilithBirthright = player->playerType == PLAYER_LILITH && player->HasCollectible(COLLECTIBLE_BIRTHRIGHT); if (isLilithBirthright && is_counted_follower()) diff --git a/src/familiar_missing.cpp b/src/familiar_missing.cpp index 45ca261..abb2336 100644 --- a/src/familiar_missing.cpp +++ b/src/familiar_missing.cpp @@ -10,34 +10,14 @@ void Entity_Familiar::ai_umbilical_baby(bool) } // 00436330 -void Entity_Familiar::WispInit() -{ - reconstruction_missing("Entity_Familiar::WispInit 00436330"); -} // 00436fd0 -uint32_t Entity_Familiar::wisp_kill() -{ - reconstruction_missing("Entity_Familiar::wisp_kill 00436fd0"); -} // 004386f0 -Entity_Tear* Entity_Familiar::fire_wisp_projectile(Vector) -{ - reconstruction_missing("Entity_Familiar::fire_wisp_projectile 004386f0"); -} // 0043a5e0 -uint32_t Entity_Familiar::wisp_take_damage(float*, uint32_t*, int*) -{ - reconstruction_missing("Entity_Familiar::wisp_take_damage 0043a5e0"); -} // 0043aa90 -void Entity_Familiar::ai_wisp() -{ - reconstruction_missing("Entity_Familiar::ai_wisp 0043aa90"); -} // 0043db20 void Entity_Familiar::ai_mr_me_wisp() @@ -52,10 +32,6 @@ void Entity_Familiar::ai_mega_blast_wisp() } // 0043eb10 -int Entity_Familiar::GetRandomWisp(RNG*) -{ - reconstruction_missing("Entity_Familiar::GetRandomWisp 0043eb10"); -} // 005ae490 void Entity_Familiar::ai_buddy_inbox() @@ -99,12 +75,6 @@ void Entity_Familiar::ai_orbital_variant_50() reconstruction_missing("Entity_Familiar::ai_orbital_variant_50 0061c150"); } -// 0061d6b0 -void Entity_Familiar::ai_key_full() -{ - reconstruction_missing("Entity_Familiar::ai_key_full 0061d6b0"); -} - // 0062c8d0 void Entity_Familiar::farting_baby_fart() { diff --git a/src/familiar_shoot.cpp b/src/familiar_shoot.cpp index c63fc32..ec11ce2 100644 --- a/src/familiar_shoot.cpp +++ b/src/familiar_shoot.cpp @@ -148,7 +148,7 @@ float Entity_Familiar::GetMultiplier() // of 00614b10 and 00619270). void Entity_Familiar::play_idle_anim() { - if (variant == WISP) return reconstruction_missing("Entity_Familiar::Shoot 00614b10 (a wisp's look)"); + if (variant == WISP) return wisp_anim_play(*this, "Idle"); if (variant == ITEM_WISP) return (void)sprite.SetAnimation("Idle", SWITCH_KEEP_FRAME); if (variant == BLOOD_BABY) return; @@ -160,7 +160,7 @@ void Entity_Familiar::play_idle_anim() // 00614500 Turns its head to shoot in a direction. void Entity_Familiar::PlayShootAnim(int direction) { - if (variant == WISP) return reconstruction_missing("Entity_Familiar::PlayShootAnim 00614500 (a wisp's look)"); + if (variant == WISP) return wisp_anim_play(*this, "Shoot"); if (variant == ITEM_WISP) return (void)sprite.SetAnimation("Shoot", SWITCH_KEEP_FRAME); if (variant == BLOOD_BABY) return; @@ -190,7 +190,7 @@ void Entity_Familiar::PlayShootAnim(int direction) void Entity_Familiar::PlayFloatAnim(int direction) { if (variant == BUMBO) return; - if (variant == WISP) return reconstruction_missing("Entity_Familiar::PlayFloatAnim 00613df0 (a wisp's look)"); + if (variant == WISP) return wisp_anim_play(*this, "Idle"); if (variant == ITEM_WISP) return (void)sprite.SetAnimation("Idle", SWITCH_KEEP_FRAME); if (variant == BLOOD_BABY) return; diff --git a/src/familiar_wisp.cpp b/src/familiar_wisp.cpp new file mode 100644 index 0000000..10145fe --- /dev/null +++ b/src/familiar_wisp.cpp @@ -0,0 +1,580 @@ +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "game_over.h" +#include "kage_graphics.h" +#include "item_config.h" +#include "level.h" +#include "manager.h" +#include "room.h" +#include +#include +#include +#include + +constexpr int WISP_SHEET_WIDE = 128; +constexpr int WISP_HEAD_FRAMES = 12; +constexpr int WISP_HEAD_FLOAT = 9; +constexpr int WISP_TOUCH_COUNTDOWN = 30; +constexpr int WISP_HIT_COUNTDOWN_MAX = 10; +constexpr int WISP_HIT_COUNTDOWN_DIVISOR = 3; +constexpr int WISP_TOUCH_SETTLE_FRAMES = 15; +constexpr int WISP_TOUCH_SOUND_DELAY = 20; +constexpr float WISP_TOUCH_SOUND_VOLUME = 0.7f; +constexpr float WISP_TOUCH_SELF_DAMAGE = 2; +constexpr float ITEM_WISP_TOUCH_SELF_DAMAGE = 1; +constexpr float WISP_SIZE_HEALTH_SCALE = 0.4f; +constexpr float WISP_SIZE_BASE = 0.6f; +constexpr float WISP_PULL = 0.01f; +constexpr float WISP_PULL_MAX = 8; +constexpr float WISP_ORBIT_SLACK = 10; +constexpr float WISP_ORBIT_FALLOFF = 160; +constexpr float WISP_STEER = 0.5f; +constexpr float WISP_STEER_LIMIT = 5; +constexpr float WISP_STEER_SPEED = 4; +constexpr float WISP_TEAR_SCALE = 0.8f; +constexpr float WISP_TEAR_FALL_JITTER = 0.2f; +constexpr float WISP_POOF_HEIGHT = -6; +constexpr float GELLO_PARENT_SLOWDOWN = 0.5f; +constexpr ColorMod ITEM_WISP_ICON_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0.8f}}; +constexpr ColorMod ITEM_WISP_POOF_COLOR = {{1.4f, 0.7f, 1.6f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The subtypes whose wisps act, shoot, die or take hits their own way (ai_wisp 0043aa90, WispInit 00436330, +// wisp_kill 00436fd0, fire_wisp_projectile 004386f0, wisp_take_damage 0043a5e0). Plain wisps share one behaviour. +constexpr std::array WISP_UNWRITTEN_SUBTYPES = { + 35, 37, 38, 40, 42, 44, 47, 49, 56, 58, 65, 66, 77, 78, 85, 93, 102, 111, 123, 127, 130, 145, + 158, 160, 164, 175, 181, 263, 282, 287, 288, 289, 290, 293, 294, 295, 298, 323, 324, 325, 338, 347, 348, 349, + 351, 352, 383, 396, 406, 419, 421, 427, 437, 441, 478, 479, 483, 484, 485, 487, 504, 516, 521, 523, 527, 545, + 556, 578, 580, 582, 604, 609, 611, 635, 638, 639, 640, 650, 702, 703, 705, 709, 722, 729, 65536, 65537, + 65538, 65539, 65540, 65541, 65542, 65543, 65544, 65545, 65546, 65547, 65548, 65549, 65550, 65551, 65552, 65553, + 65554, 65555, 65556, 65557, 65558, 65559, 65560, 65561, 65562, 65563, 65564, 65565, 65566, 65567, 65568, 65569, + 65570, 65571, 65572, 65573, 65574, 65575, 65576, 65577, 65578, 65579}; + +// The item a wisp takes its wisps.xml entry from: an item wisp's source, a wisp's subtype, else Book of Virtues. +static int wisp_item_get(Entity_Familiar& wisp) +{ + if (wisp.variant == Entity_Familiar::ITEM_WISP) return wisp.wispCollectibleType; + return wisp.variant == Entity_Familiar::WISP ? wisp.subtype : COLLECTIBLE_BOOK_OF_VIRTUES; +} + +// Whether a wisp is one with its own behaviour, which stops the game until reconstructed. +static bool is_wisp_unwritten(Entity_Familiar& wisp) +{ + if (wisp.variant != Entity_Familiar::WISP) return false; + return std::ranges::find(WISP_UNWRITTEN_SUBTYPES, wisp.subtype) != WISP_UNWRITTEN_SUBTYPES.end(); +} + +// Stops the game in a special wisp's own code. +static void wisp_unwritten_stop(Entity_Familiar& wisp, std::string_view function) +{ + reconstruction_missing((std::string(function) + " (wisp " + std::to_string(wisp.subtype) + ")").c_str()); +} + +// 005c93b0 Adds a Book of Virtues wisp of a collectible: Wavy Cap keeps one, a full ring passes it on to the next unless +// the layer is fixed, and a ring still full heals the weakest wisp of the same kind instead or loses its least +// important one. +Entity_Familiar* Entity_Player::AddWisp(int collectible, Vector position, bool isAdjustOrbitLayer, bool isDontUpdate) +{ + WispEntry* config = ItemConfig::wisp_config_get(collectible); + int ring = config->layer; + if (ring >= 0) + { + std::array leastImportant{}; + std::array lowestPriority = {WISP_PRIORITY_NONE, WISP_PRIORITY_NONE, WISP_PRIORITY_NONE}; + std::array counts{}; + Entity_Familiar* weakestSame = nullptr; + float weakestHealth = WISP_PRIORITY_NONE; + for (Entity* entity : entity_query(ENTITY_FAMILIAR, Entity_Familiar::WISP)) + { + auto* wisp = static_cast(entity); + if (!wisp->isExists || wisp->player != this) continue; + if (collectible == COLLECTIBLE_WAVY_CAP && wisp->subtype == COLLECTIBLE_WAVY_CAP) return nullptr; + + WispEntry* other = ItemConfig::wisp_config_get(wisp_item_get(*wisp)); + int layer = wisp->orbitLayer - WISP_RING_FIRST_LAYER; + if (wisp->subtype == collectible && wisp->health < weakestHealth) + { + weakestSame = wisp; + weakestHealth = wisp->health; + } + if (layer < 0 || layer >= 3) continue; + if (other->priority < lowestPriority[layer]) + { + lowestPriority[layer] = other->priority; + leastImportant[layer] = wisp; + } + counts[layer]++; + } + for (int i = 0; isAdjustOrbitLayer && i < 3 && counts[ring] >= WISP_RING_CAPACITY[ring]; i++) + ring = (ring + 1) % 3; + if (counts[ring] >= WISP_RING_CAPACITY[ring]) + { + if (weakestSame) + { + weakestSame->health = std::min(weakestSame->health + config->hp, config->hp); + return nullptr; + } + if (leastImportant[ring]) leastImportant[ring]->Remove(); + } + } + + uint32_t seed = GetCollectibleRNG(COLLECTIBLE_BOOK_OF_VIRTUES).Next(); + auto* wisp = static_cast( + g_game->Spawn({position, {}, this, collectible, ENTITY_FAMILIAR, Entity_Familiar::WISP, seed})); + if (isAdjustOrbitLayer && ring >= 0) wisp->AddToOrbit(ring + WISP_RING_FIRST_LAYER); + if (!isDontUpdate) wisp->Update(); + return wisp; +} + +// The items Book of Sin's wisps copy, one picked at random (the exe's table at 00b62c9c). +constexpr int BOOK_OF_SIN_WISPS[] = {45, 37, 65, 42, 102, 177, 49}; +constexpr int PORTABLE_SLOT_WISPS = 3; + +// 005ca470 Book of Virtues' wisps for an active used: as many as the item's entry gives (Book of Sin's a random +// pickup item's, three for Portable Slot), twice as many with Car Battery, with a candle's sound. +void Entity_Player::TriggerBookOfVirtues(int collectibleId, int) +{ + if (!HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) return; + + int wispItem = collectibleId; + if (collectibleId == COLLECTIBLE_BOOK_OF_SIN) + wispItem = BOOK_OF_SIN_WISPS[GetCollectibleRNG(COLLECTIBLE_BOOK_OF_VIRTUES).Next() % std::size(BOOK_OF_SIN_WISPS)]; + bool isSinSlot = collectibleId == COLLECTIBLE_BOOK_OF_SIN && wispItem == COLLECTIBLE_PORTABLE_SLOT; + int count = isSinSlot ? PORTABLE_SLOT_WISPS : ItemConfig::wisp_config_get(wispItem)->count; + if (HasCollectible(COLLECTIBLE_CAR_BATTERY)) count *= 2; + if (count <= 0) return; + + for (int i = 0; i < count; i++) AddWisp(wispItem, pos, false, false); + sound_play(SOUND_CANDLE_LIGHT); +} + +// 005c96f0 Adds an item wisp of a collectible on Lemegeton's ring (or Book of Virtues' Lemegeton ring): a full ring +// passes it on to the next unless the layer is fixed, and a ring still full loses its least important wisp. +Entity_Familiar* Entity_Player::AddItemWisp(int collectibleId, Vector position, bool isAdjustOrbitLayer) +{ + WispEntry* own = ItemConfig::wisp_config_get(HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) ? LEMEGETON_VIRTUES_WISP + : COLLECTIBLE_LEMEGETON); + int ring = own->layer; + if (ring >= 0) + { + std::array weakest{}; + std::array lowestPriority = {WISP_PRIORITY_NONE, WISP_PRIORITY_NONE, WISP_PRIORITY_NONE}; + std::array counts{}; + for (Entity* entity : g_game->room->GetEntities()->updateEL) + { + auto* wisp = entity && entity->type == ENTITY_FAMILIAR ? static_cast(entity) : nullptr; + bool isWisp = wisp && (wisp->variant == Entity_Familiar::WISP || wisp->variant == Entity_Familiar::ITEM_WISP); + if (!isWisp || wisp->player != this) continue; + + int wispItem = wisp->variant == Entity_Familiar::ITEM_WISP ? wisp->wispCollectibleType : wisp->subtype; + int layer = wisp->orbitLayer - WISP_RING_FIRST_LAYER; + if (layer < 0 || layer >= 3) continue; + int priority = ItemConfig::wisp_config_get(wispItem)->priority; + if (wisp->variant == Entity_Familiar::WISP || priority < lowestPriority[layer]) + { + lowestPriority[layer] = priority; + weakest[layer] = wisp; + } + counts[layer]++; + } + for (int i = 0; isAdjustOrbitLayer && i < 3 && counts[ring] >= WISP_RING_CAPACITY[ring]; i++) + ring = (ring + 1) % 3; + if (counts[ring] >= WISP_RING_CAPACITY[ring] && weakest[ring]) weakest[ring]->Remove(); + } + + uint32_t seed = GetCollectibleRNG(COLLECTIBLE_LEMEGETON).Next(); + auto* wisp = static_cast( + g_game->Spawn({position, {}, this, collectibleId, ENTITY_FAMILIAR, Entity_Familiar::ITEM_WISP, seed})); + if (isAdjustOrbitLayer && ring >= 0) wisp->AddToOrbit(ring + WISP_RING_FIRST_LAYER); + wisp->Update(); + return wisp; +} + +// 0043eb10 A random collectible that has a Book of Virtues wisp, Book of Virtues' own when none has. +int Entity_Familiar::GetRandomWisp(RNG* rng) +{ + std::vector wispItems; + for (ItemConfig_Item* item : g_manager->itemConfig.GetTaggedItems(TAG_WISP)) + if (item->wispConfig && item->wispConfig->count > 0) wispItems.push_back(item->id); + if (wispItems.empty()) return COLLECTIBLE_BOOK_OF_VIRTUES; + return wispItems[rng->Next() % wispItems.size()]; +} + +// 00436330 Sets a wisp up from its wisps.xml entry: health, sheets and colours. An item wisp takes Lemegeton's (or +// Book of Virtues' Lemegeton) entry and reveals the map when its item is a map, Eden's Soul and Mystery Gift wisps +// become a random wisp, and the item wisps are counted as held. +void Entity_Familiar::WispInit() +{ + int item = subtype; + if (variant == ITEM_WISP) + { + wispCollectibleType = player->HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) ? LEMEGETON_VIRTUES_WISP + : COLLECTIBLE_LEMEGETON; + item = wispCollectibleType; + } + if (variant == WISP && (item == COLLECTIBLE_MYSTERY_GIFT || item == COLLECTIBLE_EDENS_SOUL)) + { + wispCollectibleType = item; + subtype = GetRandomWisp(&dropRNG); + } + if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::WispInit 00436330"); + if (variant == WISP && subtype == COLLECTIBLE_FORTUNE_COOKIE) player->cacheFlags |= CACHE_LUCK; + + if (variant == ITEM_WISP) + { + Level& level = *g_game; + if (subtype == COLLECTIBLE_BLUE_MAP || subtype == COLLECTIBLE_MIND) level.ApplyBlueMapEffect(); + if (subtype == COLLECTIBLE_TREASURE_MAP || subtype == COLLECTIBLE_MIND) level.ApplyMapEffect(); + if (subtype == COLLECTIBLE_COMPASS || subtype == COLLECTIBLE_MIND) level.ApplyCompassEffect(true); + } + + WispEntry* config = ItemConfig::wisp_config_get(wisp_item_get(*this)); + maxHitPoints = config->hp; + health = config->hp; + if (!config->coreGfx.empty()) sprite.ReplaceSpritesheet(0, config->coreGfx); + if (!config->flameGfx.empty()) sprite.ReplaceSpritesheet(1, config->flameGfx); + if (!config->coreGfx.empty() || !config->flameGfx.empty()) sprite.LoadGraphics(); + sprite.GetLayer(0)->color = config->coreColor; + sprite.GetLayer(1)->color = config->flameColor; + + if (variant == ITEM_WISP) player->RecomputeWispCollectibles(this); + g_game->UpdateVisibility(); +} + +// 0043d7f0 Turns a wisp into another kind, keeping its health below the new kind's. +void wisp_morph(Entity_Familiar& wisp, int newSubtype) +{ + if (newSubtype == wisp.subtype) return; + + wisp.subtype = newSubtype; + wisp.ResetColor(); + wisp.LoadEntityConfig(); + wisp.health = std::min(wisp.health, wisp.maxHitPoints); + wisp.entityGridCollisionClass = GRIDCOLL_NONE; + wisp.WispInit(); +} + +// Part of 0062aab0: a cleared room heals an Eden's Soul or Mystery Gift wisp, an Eden's Soul one turning into another +// random wisp first. +void wisp_room_clear(Entity_Familiar& wisp) +{ + if (wisp.wispCollectibleType == COLLECTIBLE_EDENS_SOUL) + wisp_morph(wisp, Entity_Familiar::GetRandomWisp(&wisp.dropRNG)); + if (wisp.wispCollectibleType == COLLECTIBLE_EDENS_SOUL || wisp.wispCollectibleType == COLLECTIBLE_MYSTERY_GIFT) + wisp.health = wisp.maxHitPoints; +} + +// Part of 00614500, 00613df0 and 00614b10: a wisp's animation, the wide one for a sheet wider than 128 pixels. +void wisp_anim_play(Entity_Familiar& wisp, std::string_view name) +{ + LayerState* core = wisp.sprite.GetLayer(0); + bool isWide = core && core->spriteSheet && core->spriteSheet->width > WISP_SHEET_WIDE; + wisp.sprite.SetAnimation(isWide ? std::string(name) + "2" : std::string(name), SWITCH_KEEP_FRAME); +} + +// The orbit part of ai_wisp: an orbiting wisp is pulled back toward its parent when far from its ring and steered +// onto its spot on the ring, at most four a frame, carried along by the parent's own motion. One off the orbits holds +// the spot its formation offset names. +static void wisp_orbit_move(Entity_Familiar& wisp) +{ + if (wisp.orbitLayer < 0) + { + if (vector_is_zero(wisp.formationOffset)) return; + wisp.pos = wisp.formationOffset; + wisp.velocity = {}; + return; + } + + Entity* parent = wisp.get_orbit_parent(); + Vector parentVelocity = parent->velocity; + if (parent->type == ENTITY_FAMILIAR && parent->variant == Entity_Familiar::UMBILICAL_BABY) + parentVelocity = vector_scale(parentVelocity, GELLO_PARENT_SLOWDOWN); + Vector spot = wisp.GetOrbitPosition(parent->pos); + + Vector toParent = vector_sub(parent->pos, wisp.pos); + float distance = vector_length(toParent); + Vector pull = vector_scale(toParent, WISP_PULL); + float pullLength = vector_length(pull); + if (pullLength > WISP_PULL_MAX) pull = vector_scale(pull, WISP_PULL_MAX / pullLength); + + float ringRadius = std::max(wisp.orbitDistance.x, wisp.orbitDistance.y); + float t = std::clamp((distance - (ringRadius + WISP_ORBIT_SLACK)) / WISP_ORBIT_FALLOFF, 0.0f, 1.0f); + float pullShare = 1 - (1 - t) * (1 - t); + Vector carried = vector_scale(parentVelocity, (1 - pullShare) * 2 / parent->friction); + + Vector steer = vector_scale(vector_sub(spot, vector_add(wisp.pos, carried)), WISP_STEER); + if (vector_length(steer) > WISP_STEER_LIMIT && !wisp.HasEntityFlags(FLAG_SPIN)) + steer = vector_scale(vector_normalized(steer), WISP_STEER_SPEED); + Vector settled = vector_scale(vector_add(steer, carried), 1 / wisp.friction); + wisp.velocity = vector_add(vector_scale(vector_sub(vector_add(pull, wisp.velocity), settled), pullShare), settled); +} + +// 0043aa90 A wisp's frame: it keeps to its ring, grows and shrinks with its health, hits as hard as twice its player's +// melee damage (twice again with BFFS!), and fires along its player's aim at the rate its entry sets. The wisps with +// their own behaviour stop the game. +void Entity_Familiar::ai_wisp() +{ + if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::ai_wisp 0043aa90"); + + WispEntry* config = ItemConfig::wisp_config_get(wisp_item_get(*this)); + if (state == 0) wisp_orbit_move(*this); + + float size = health / maxHitPoints * WISP_SIZE_HEALTH_SCALE + WISP_SIZE_BASE; + float coreSize = std::sqrt(size); + sprite.GetLayer(0)->size = vector_make(coreSize, coreSize); + sprite.GetLayer(1)->size = vector_make(size, size); + collisionDamage = player->meleeDamage + player->meleeDamage; + int fireDelay = (int)config->fireDelay; + + if (player->HasCollectible(COLLECTIBLE_BFFS)) collisionDamage += collisionDamage; + if (counter > 0) counter--; + if (state != 0 || !config->isCanShoot) return; + if (fireCooldown > 0) fireCooldown--; + + int direction = player->fireDirection; + if (direction == DIRECTION_NONE || fireDelay <= 0) + { + if (headFrameDelay >= 0 && --headFrameDelay < 0) PlayFloatAnim(DIRECTION_DOWN); + return; + } + + Vector aim = direction_unit(direction); + TryAimAtMarkedTarget(aim, direction, nullptr); + if (fireCooldown < 1) + { + FireProjectile(aim, FIRE_INHERIT_MOTION); + fireCooldown = fireDelay; + headFrameDelay = WISP_HEAD_FRAMES; + } + else if (headFrameDelay < WISP_HEAD_FLOAT) + { + PlayFloatAnim(direction); + headFrameDelay = WISP_HEAD_FLOAT - 1; + return; + } + PlayShootAnim(direction); + headFrameDelay--; +} + +// 004386f0 A wisp's tear: its entry's damage (rising each floor, an alternate floor counting one deeper), size and +// look, the second kind of tear by its chance, spectral, at its entry's shot speed. BFFS! doubles the damage and keeps +// the size whole. The wisps that shoot their own way stop the game. +Entity_Tear* Entity_Familiar::fire_wisp_projectile(Vector velocity) +{ + if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::fire_wisp_projectile 004386f0"); + + WispEntry* config = ItemConfig::wisp_config_get(wisp_item_get(*this)); + bool isBffs = player->HasCollectible(COLLECTIBLE_BFFS); + Level& level = *g_game; + int stage = (int)level.stage + (level.IsAltPath() ? 1 : 0); + float baseDamage = (float)(stage - 1) * config->stageDamage + config->damage; + WispTears& tears = random_unit() < config->procChance ? config->tears2 : config->tears; + + TearFlags flags = tears.flags; + flags.set(TEAR_SPECTRAL); + velocity = vector_scale(velocity, config->shotSpeed); + auto* tear = static_cast(g_game->Spawn({.position = pos, + .velocity = velocity, + .spawner = this, + .type = ENTITY_TEAR, + .variant = tears.variant, + .seed = Random()})); + tear->fallingSpeed = random_unit() * WISP_TEAR_FALL_JITTER; + tear->fallingAccel = 0; + tear->SetCollisionDamage(wispDamageMultiplier * tears.damageMultiplier * wispScale * baseDamage * (isBffs ? 2 : 1)); + tear->SetTearFlags(flags); + tear->SetScale(std::sqrt(wispDamageMultiplier) * tears.scale * (isBffs ? 1 : WISP_TEAR_SCALE)); + tear->parent = this; + tear->SetColor(tears.color, -1, 255, false, true); + tear->tearIdx = (int)(Random() & 1); + if (player->HasTrinket(TRINKET_BABY_BENDER)) TryFireTear(tear); + return tear; +} + +// 0043a5e0 Whether a hit reaches a wisp: none while its player is invincible, nor its own side's crushing blows. The +// wisps that answer hits their own way stop the game. +bool Entity_Familiar::wisp_take_damage(const EntityRef& source, uint64_t damageFlags) +{ + if (player->HasInvincibility(0, EntityRef())) return false; + if ((source.type == ENTITY_PLAYER || source.type == ENTITY_FAMILIAR) && (damageFlags & DAMAGE_CRUSH)) return false; + if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::wisp_take_damage 0043a5e0"); + return true; +} + +// The countdown a wisp's hit lasts, a third of the hit's and at most ten frames (part of 0062cdc0). +int wisp_hit_countdown(int damageCountdown) +{ + return std::min(damageCountdown / WISP_HIT_COUNTDOWN_DIVISOR, WISP_HIT_COUNTDOWN_MAX); +} + +// Part of 0062cdc0: a hurt wisp shares its countdown with the rest of its player's living wisps. +void wisp_countdown_share(Entity_Familiar& hurt) +{ + if (hurt.damageCountdown <= 0) return; + + for (Entity* entity : g_game->room->entityList.persistentEL) + { + auto* wisp = entity && entity->type == ENTITY_FAMILIAR ? static_cast(entity) : nullptr; + bool isWisp = wisp && (wisp->variant == Entity_Familiar::WISP || wisp->variant == Entity_Familiar::ITEM_WISP); + if (isWisp && wisp->isExists && !wisp->isDead && wisp->player == hurt.player) + wisp->damageCountdown = std::max(wisp->damageCountdown, hurt.damageCountdown); + } +} + +// Part of 006261f0: an enemy touching a wisp hurts it once the room has run for a while (twice its damage multiplier, +// an item wisp one), and the wisp burns the enemy once per hit list, pushing it away from the player. False in the +// room's first frames, when the touch goes on as any familiar's. +bool wisp_touch(Entity_Familiar& wisp, Entity& enemy) +{ + if (g_game->room->GetFrameCount() < WISP_TOUCH_SETTLE_FRAMES) return false; + if (wisp.collisionDamage <= 0) return true; + + if (wisp.damageCountdown < 1 && !wisp.player->HasInvincibility(0, EntityRef()) && !wisp.isInvincible) + { + float hurt = wisp.variant == Entity_Familiar::WISP ? wisp.wispDamageMultiplier * WISP_TOUCH_SELF_DAMAGE + : ITEM_WISP_TOUCH_SELF_DAMAGE; + wisp.TakeDamage(hurt, 0, EntityRef(&enemy), WISP_TOUCH_COUNTDOWN); + } + if (EntityList::HitListContains(wisp.hitList, enemy)) return true; + + familiar_sound_play(SOUND_FIREDEATH_HISS, + {.volume = WISP_TOUCH_SOUND_VOLUME, .frameDelay = WISP_TOUCH_SOUND_DELAY}); + if (enemy.friction > 0 && enemy.mass > 0) + { + Vector away = vector_normalized(vector_sub(enemy.pos, wisp.player->pos)); + enemy.AddVelocity_divided(vector_scale(away, wisp.mass / enemy.mass), true); + } + enemy.TakeDamage(wisp.collisionDamage, 0, EntityRef(&wisp), WISP_TOUCH_COUNTDOWN); + hit_list_insert(wisp.hitList, enemy); + return true; +} + +// The flame a dying wisp leaves: a poof in its entry's colour and its own tears' splash in its blood colour, each +// falling back on the flame and core colours. +static void wisp_death_poofs(Entity_Familiar& wisp, WispEntry& config) +{ + Entity* poof = g_game->Spawn({.position = wisp.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->posOffset = vector_make(0, WISP_POOF_HEIGHT); + ColorMod flameTint = COLOR_DEFAULT; + std::copy(std::begin(wisp.sprite.GetLayer(1)->color._tint), std::end(wisp.sprite.GetLayer(1)->color._tint), + flameTint._colorize); + poof->sprite.color = config.poofColor._tint[3] >= 0 ? config.poofColor : flameTint; + + Entity* splash = g_game->Spawn({.position = wisp.pos, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_TEAR_POOF_A, + .seed = Random()}); + splash->posOffset = vector_make(0, WISP_POOF_HEIGHT); + ColorMod coreTint = COLOR_DEFAULT; + std::copy(std::begin(wisp.sprite.GetLayer(0)->color._tint), std::end(wisp.sprite.GetLayer(0)->color._tint), + coreTint._colorize); + splash->sprite.color = config.bloodColor._tint[3] >= 0 ? config.bloodColor : coreTint; + sound_play(SOUND_STEAM_HALFSEC); +} + +// 00436fd0 A wisp's death: an Eden's Soul or Mystery Gift wisp comes back after the next clear, then the flame goes +// out. The wisps that die their own way stop the game. True when it dies. +bool Entity_Familiar::wisp_kill() +{ + if (is_wisp_unwritten(*this)) wisp_unwritten_stop(*this, "Entity_Familiar::wisp_kill 00436fd0"); + if (wispCollectibleType == COLLECTIBLE_EDENS_SOUL || wispCollectibleType == COLLECTIBLE_MYSTERY_GIFT) + player->pendingWisps.push_back(wispCollectibleType); + wisp_death_poofs(*this, *ItemConfig::wisp_config_get(wisp_item_get(*this))); + return true; +} + +// Part of 00610540: an item wisp's purple poof and splash. +static void item_wisp_death_poofs(Entity_Familiar& wisp) +{ + for (int effect : {EFFECT_POOF01, EFFECT_TEAR_POOF_A}) + { + Entity* poof = g_game->Spawn({.position = wisp.pos, + .subType = effect == EFFECT_TEAR_POOF_A ? 1 : 0, + .type = ENTITY_EFFECT, + .variant = effect, + .seed = Random()}); + poof->posOffset = vector_make(0, WISP_POOF_HEIGHT); + poof->sprite.color = ITEM_WISP_POOF_COLOR; + } + sound_play(SOUND_STEAM_HALFSEC); +} + +// Part of 00610540: a wisp's death, its flame going out, its ring closing up, then the entity's own kill and its +// removal. An item wisp's player stops holding its item. +void Entity_Familiar::wisp_death(const EntityRef& source) +{ + if (variant == WISP && !wisp_kill()) return; + if (variant == ITEM_WISP) item_wisp_death_poofs(*this); + if (orbitLayer >= 0) + { + if (!isSubtype55555) RecalculateOrbitOffset(orbitLayer, ORBIT_LEAVE); + orbitLayer = -1; + } + Entity::Kill(source); + Remove(); + if (variant == ITEM_WISP && player) player->RecomputeWispCollectibles(nullptr); +} + +// Part of 00624e10: an item wisp's item icon over its flame, glowing additively, where its core's frame sits. +void item_wisp_icon_render(Entity_Familiar& wisp) +{ + const AnimationFrame* frame = wisp.sprite.animState.GetLayerFrame(0); + if (!wisp.isVisible || !frame || !frame->isVisible) return; + + Vector coreSize = wisp.sprite.GetLayer(0)->size; + ModSpriteDraw draw; + bool isPremultiplied = KAGE::Graphics::manager.isPremultipliedAlpha; + draw.blendMode = {BLEND_EQUATION_ADD, isPremultiplied ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA, BLEND_FACTOR_ONE, + BLEND_FACTOR_ONE, BLEND_FACTOR_ONE}; + draw.color = ITEM_WISP_ICON_COLOR; + draw.position = vector_add(wisp.renderPosition, frame->pos); + draw.scale = vector_make(coreSize.x * frame->scale.x, coreSize.y * frame->scale.y); + g_game->gameOver.render_collectible_icon(wisp.subtype, draw); +} + +// 007d7740 Counts the collectibles the player's living item wisps (and a wisp just joining) lend it: an item gained or +// changed in count asks for its stats and dresses its costume, one gone runs its removal and takes the costume off +// unless still held, then the stats are evaluated. +void Entity_Player::RecomputeWispCollectibles(Entity_Familiar* joining) +{ + std::map lent; + if (joining && joining->type == ENTITY_FAMILIAR && joining->variant == Entity_Familiar::ITEM_WISP && + !joining->isDead) + lent[joining->subtype]++; + for (Entity* entity : g_game->room->entityList.persistentEL) + if (entity && entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::ITEM_WISP && + static_cast(entity)->player == this && entity->isExists && !entity->isDead) + lent[entity->subtype]++; + + ItemConfig& items = g_manager->itemConfig; + std::vector removedIds; + for (auto [id, count] : itemWispsList) + { + if (lent.contains(id)) continue; + ItemConfig_Item* item = items.GetCollectible(id); + if (item) cacheFlags |= item->cacheFlags; + removedIds.push_back(id); + } + for (auto [id, count] : lent) + { + auto old = itemWispsList.find(id); + if (old != itemWispsList.end() && old->second == count) continue; + + ItemConfig_Item* item = items.GetCollectible(id); + if (item) cacheFlags |= item->cacheFlags; + if (old == itemWispsList.end() && item && item->isAddCostumeOnPickup) AddCostume(item, false); + } + itemWispsList = std::move(lent); + + for (int id : removedIds) + { + ItemConfig_Item* item = items.GetCollectible(id); + TriggerCollectibleRemoved(id); + if (item && item->isAddCostumeOnPickup && !HasCollectible(id)) RemoveCostume(item); + } + EvaluateItems(); +} diff --git a/src/game.h b/src/game.h index 21a0ee7..28b3985 100644 --- a/src/game.h +++ b/src/game.h @@ -72,7 +72,8 @@ enum GameStateFlag : int GAME_STATE_BLUEWOMB_DOOR_SPAWNED = 39, GAME_STATE_BLUEWOMB_DONE = 40, GAME_STATE_SECRET_PATH = 44, - GAME_STATE_BACKWARDS_PATH = 48 + GAME_STATE_BACKWARDS_PATH = 48, + GAME_STATE_MEGA_SATAN_DOOR_OPENED = 49 }; // The string table keys of the co-op awards, in the order of Game's award table. diff --git a/src/game_over.cpp b/src/game_over.cpp index 279cc51..242ff1b 100644 --- a/src/game_over.cpp +++ b/src/game_over.cpp @@ -38,6 +38,8 @@ constexpr float DIARY_ROW_END = 128; constexpr float DIARY_ROW_BACK_X = 132; constexpr float DIARY_ROW_BACK_Y = 4; constexpr float DIARY_CENTER_OFFSET = 16; +constexpr float DIARY_ICON_X = 84; +constexpr float DIARY_ICON_Y = -20; constexpr float SEED_OFFSET_X = 4; constexpr float SEED_LINE_1_Y = 2; constexpr float SEED_LINE_2_Y = 17; @@ -60,7 +62,6 @@ constexpr int PORTRAIT_UNKNOWN = 149; constexpr int PORTRAIT_BOMB = 65; constexpr uint64_t DAMAGE_TIMER = 1ull << 17; -constexpr uint64_t DAMAGE_IV_BAG = 1ull << 18; // The portraits of the deaths no entity caused: by the damage source's id, then by the damage flags, first match first. constexpr std::pair SOURCE_PORTRAITS[] = {{25, 202}, {10000, 229}, {10001, 235}, {10002, 239}, {10003, 253}}; @@ -284,6 +285,39 @@ static void diary_seed_render(ANM2& sprite) vector_make(x, y + SEED_LINE_2_Y), vector_make(1, 1), kcolor_argb(SEED_COLOR_ARGB), settings); } +// 0099a300 Draws a collectible's diary icon anywhere, in a look of the caller's: from the diary's item sheet (loading the +// page if the screen never showed), a modded or glitched one by its mod. The items layer is put back after. +void GameOver::render_collectible_icon(int collectibleId, ModSpriteDraw& draw) +{ + if (collectibleId == 0) return; + if ((unsigned int)collectibleId >= (unsigned int)COLLECTIBLE_VANILLA_COUNT) + return g_manager->modManager.RenderCustomCollectionItem(collectibleId, draw); + + if (!sprite.isLoaded) + { + sprite.Load(DEATH_SCREEN_ANM2, GRAPHICS_LOAD); + if (sprite.SetAnimation(DIARY_ANIMATION, SWITCH_RESET) && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(0); + sprite.animState.isPlaying = false; + } + } + LayerState* layer = sprite.GetLayer(DIARY_LAYER_ITEMS); + LayerState saved = *layer; + layer->pos = vector_make(DIARY_ICON_X, DIARY_ICON_Y); + layer->rotation = 0; + layer->size = draw.scale; + layer->color = draw.color; + layer->blendMode = draw.blendMode; + sprite.SetLayerFrame(DIARY_LAYER_ITEMS, collectibleId - 1); + sprite.RenderLayer(DIARY_LAYER_ITEMS, {draw.position}); + layer->pos = saved.pos; + layer->rotation = saved.rotation; + layer->size = saved.size; + layer->color = saved.color; + layer->blendMode = saved.blendMode; +} + // 00998880 Draws the diary over the shaded run: the page (a modded character's portrait by its mod), the items taken, // a modded enemy's portrait and the seed. // Online, the original draws the Deeds page with each player's deeds instead. Netplay is offline. diff --git a/src/game_over.h b/src/game_over.h index d78b3d7..468b845 100644 --- a/src/game_over.h +++ b/src/game_over.h @@ -3,6 +3,7 @@ #include "anm2.h" #include "classes.h" #include "game_end.h" +#include "mod_manager.h" // Whether the game over screen is up. Show is the only writer of a shown state. enum GameOverState : int @@ -26,4 +27,5 @@ struct GameOver void Show(); void Update(); void Render(); + void render_collectible_icon(int collectibleId, ModSpriteDraw& draw); }; diff --git a/src/game_restore.cpp b/src/game_restore.cpp index 5a9613a..7215de4 100644 --- a/src/game_restore.cpp +++ b/src/game_restore.cpp @@ -600,6 +600,9 @@ void Entity_Player::RestoreGameState(GameStatePlayer& saved) bagOfCraftingOutput = saved.bagOfCraftingOutput; bagOfCraftingPool = saved.bagOfCraftingPool; std::ranges::copy(saved.poopSpellQueue | std::views::take(poopSpellQueue.size()), poopSpellQueue.begin()); + std::ranges::copy(saved.poopSpellQueue | std::views::drop(poopSpellQueue.size()), poopSpellBag.begin()); + poopSpellBagCount = saved.poopSpellCounter; + poopSpellCharge = saved.poopSpellFloat; poopMana = saved.poopMana; effectiveBloodCharge = saved.effectiveBloodCharge; itemCards = saved.itemCards; @@ -672,6 +675,7 @@ void Entity_Player::RestoreGameState(GameStatePlayer& saved) goldenHearts = saved.goldenHearts; planCKillCountdown = saved.planCKillCountdown; imExcitedSpeedupCountdown = saved.imExcitedSpeedupCountdown; + lastPillColor = saved.lastPillColor; holyMantleStacks = saved.holyMantleStacks; ductTapeMode = saved.ductTapeMode; isDead = false; diff --git a/src/game_save.cpp b/src/game_save.cpp index c7a7261..222a467 100644 --- a/src/game_save.cpp +++ b/src/game_save.cpp @@ -409,6 +409,9 @@ void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTempor state.bagOfCraftingOutput = bagOfCraftingOutput; state.bagOfCraftingPool = bagOfCraftingPool; std::copy(poopSpellQueue.begin(), poopSpellQueue.end(), state.poopSpellQueue.begin()); + std::copy(poopSpellBag.begin(), poopSpellBag.end(), state.poopSpellQueue.begin() + poopSpellQueue.size()); + state.poopSpellCounter = (uint8_t)poopSpellBagCount; + state.poopSpellFloat = poopSpellCharge; state.poopMana = poopMana; state.effectiveBloodCharge = effectiveBloodCharge; state.itemCards = itemCards; @@ -485,6 +488,7 @@ void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTempor state.goldenHearts = goldenHearts; state.planCKillCountdown = planCKillCountdown; state.imExcitedSpeedupCountdown = imExcitedSpeedupCountdown; + state.lastPillColor = lastPillColor; std::vector& entities = game.room->entityList.updateEL; Entity_Player* twin = static_cast(twinPlayer.get()); diff --git a/src/grid_entity_door.cpp b/src/grid_entity_door.cpp index 66e00b4..735fe8a 100644 --- a/src/grid_entity_door.cpp +++ b/src/grid_entity_door.cpp @@ -32,12 +32,11 @@ constexpr float HOME_ALT_TINT[3] = {0.5f, 0.5f, 0.54f}; constexpr int GREED_EXIT_WAVE = 10; // The run state bits doors set and read: Mega Satan's door unlocked, and Mom's Heart's exit opened. -constexpr uint64_t GAME_STATE_MEGA_SATAN_DOOR_OPENED = 1ull << 49; constexpr uint64_t GAME_STATE_HEART_EXIT_OPENED = 1ull << 52; // The items, trinkets and challenge doors answer to. constexpr uint32_t CHALLENGE_PAY_TO_PLAY = 24; -constexpr int FAMILIAR_KEY_FULL = 236; +constexpr int FAMILIAR_KEY_FULL = 28; constexpr int FAMILIAR_STATE_KEY_DOOR = 1; // How far a door's sprite stands out from the wall, and the angles its sprites turn to by direction. @@ -840,7 +839,7 @@ void GridEntity_Door::Update() { Room& room = *g_game->room; updateCount++; - if (variant == DOOR_LOCKED_KEYFAMILIAR && (g_game->gameStateFlags & GAME_STATE_MEGA_SATAN_DOOR_OPENED)) + if (variant == DOOR_LOCKED_KEYFAMILIAR && (g_game->gameStateFlags & (1ull << GAME_STATE_MEGA_SATAN_DOOR_OPENED))) { variant = DOOR_UNLOCKED; UpdateAnimation(); @@ -855,7 +854,7 @@ void GridEntity_Door::Update() if (variant != DOOR_LOCKED_BARRED) { if (variant == DOOR_LOCKED_KEYFAMILIAR) - g_game->gameStateFlags |= GAME_STATE_MEGA_SATAN_DOOR_OPENED; + g_game->gameStateFlags |= 1ull << GAME_STATE_MEGA_SATAN_DOOR_OPENED; variant = DOOR_UNLOCKED; UpdateAnimation(); } @@ -1073,7 +1072,7 @@ void GridEntity_Door::Open() } if (variant == DOOR_LOCKED_KEYFAMILIAR) - g_game->gameStateFlags |= GAME_STATE_MEGA_SATAN_DOOR_OPENED; + g_game->gameStateFlags |= 1ull << GAME_STATE_MEGA_SATAN_DOOR_OPENED; if (variant == DOOR_LOCKED_GREED && targetRoomType == ROOM_TREASURE && targetRoomIdx == (int)g_game->greedModeTreasureRoomIdx) { @@ -1116,7 +1115,7 @@ void GridEntity_Door::SetLocked(bool isLocked) if (variant == DOOR_LOCKED_BARRED && !isLocked) return; if (variant == DOOR_LOCKED_KEYFAMILIAR && !isLocked) - g_game->gameStateFlags |= GAME_STATE_MEGA_SATAN_DOOR_OPENED; + g_game->gameStateFlags |= 1ull << GAME_STATE_MEGA_SATAN_DOOR_OPENED; variant = isLocked ? DOOR_LOCKED : DOOR_UNLOCKED; UpdateAnimation(); } diff --git a/src/grid_entity_pressure_plate.cpp b/src/grid_entity_pressure_plate.cpp index 8d56c5a..67af36b 100644 --- a/src/grid_entity_pressure_plate.cpp +++ b/src/grid_entity_pressure_plate.cpp @@ -17,7 +17,6 @@ constexpr int SOUND_BUTTON_PRESS = 469; // Who presses a plate, and how close: the entities a query finds around it, within reach of its center. -constexpr int ENTITY_DOPLE = 53; constexpr float PLATE_QUERY_RADIUS = 60; constexpr float PLATE_PRESS_RADIUS = 30; diff --git a/src/grid_entity_tnt.cpp b/src/grid_entity_tnt.cpp index 77fe21c..82229c5 100644 --- a/src/grid_entity_tnt.cpp +++ b/src/grid_entity_tnt.cpp @@ -20,7 +20,7 @@ constexpr float WOOD_SPEED_EXTRA = 4; constexpr uint32_t TRINKET_DROP_ODDS = 100; // 0071f3f0 Throws the barrel's wooden pieces about. -static void wood_particles_spawn(const Vector& position) +void wood_particles_spawn(const Vector& position) { float speed = (float)Random() * 2.3283064e-10f * WOOD_SPEED_EXTRA + WOOD_SPEED_MIN; int count = (int)(Random() % WOOD_COUNT_EXTRA) + WOOD_COUNT_MIN; @@ -28,7 +28,7 @@ static void wood_particles_spawn(const Vector& position) } // 0071f4b0 One blown barrel in 100, by its seed, leaves a trinket. -static void trinket_drop_try(uint32_t seed) +void trinket_drop_try(uint32_t seed) { RNG rng = {seed, 1, 5, 16}; if (rng.Next() % TRINKET_DROP_ODDS == 0) diff --git a/src/grid_entity_tnt.h b/src/grid_entity_tnt.h index 3c02f2e..111da9e 100644 --- a/src/grid_entity_tnt.h +++ b/src/grid_entity_tnt.h @@ -6,6 +6,9 @@ constexpr int TNT_STATE_READY = 3; constexpr int TNT_STATE_BLOWN = 4; +void wood_particles_spawn(const Vector& position); +void trinket_drop_try(uint32_t seed); + // Destruction (0070bdd0) is the default. // A TNT barrel on the grid (Lua's GRID_TNT): hurt in stages, it explodes. struct GridEntity_TNT : GridEntity diff --git a/src/item_config.cpp b/src/item_config.cpp index ae9f197..2b765fa 100644 --- a/src/item_config.cpp +++ b/src/item_config.cpp @@ -42,7 +42,6 @@ constexpr int SPECIAL_CHARGE_SEGMENTS_LAST = 12; // Ids and values the availability and charge rules name. constexpr int COLLECTIBLE_SACRED_ORB = 691; constexpr int COLLECTIBLE_VANISHING_TWIN = 697; -constexpr int CARD_SUICIDE_KING = 46; constexpr unsigned int CHALLENGE_ONANS_STREAK = 29; constexpr unsigned int SPECIAL_DAILY_BANNED_SET = 52; constexpr uint32_t STAGE_VANISHING_TWIN_LAST = 6; diff --git a/src/item_config.h b/src/item_config.h index 2131020..b6d5627 100644 --- a/src/item_config.h +++ b/src/item_config.h @@ -161,6 +161,80 @@ enum CardType : int CARD_TAROT_REVERSE }; +// The cards and runes the code names (Lua's Card). +enum CardId : int +{ + CARD_FOOL = 1, + CARD_MAGICIAN = 2, + CARD_HIGH_PRIESTESS = 3, + CARD_EMPRESS = 4, + CARD_EMPEROR = 5, + CARD_HIEROPHANT = 6, + CARD_LOVERS = 7, + CARD_CHARIOT = 8, + CARD_JUSTICE = 9, + CARD_HERMIT = 10, + CARD_WHEEL_OF_FORTUNE = 11, + CARD_STRENGTH = 12, + CARD_HANGED_MAN = 13, + CARD_DEATH = 14, + CARD_TEMPERANCE = 15, + CARD_DEVIL = 16, + CARD_TOWER = 17, + CARD_STARS = 18, + CARD_MOON = 19, + CARD_SUN = 20, + CARD_JUDGEMENT = 21, + CARD_WORLD = 22, + CARD_CLUBS_2 = 23, + CARD_DIAMONDS_2 = 24, + CARD_SPADES_2 = 25, + CARD_HEARTS_2 = 26, + CARD_ACE_OF_CLUBS = 27, + CARD_ACE_OF_DIAMONDS = 28, + CARD_ACE_OF_SPADES = 29, + CARD_ACE_OF_HEARTS = 30, + CARD_JOKER = 31, + RUNE_HAGALAZ = 32, + RUNE_JERA = 33, + RUNE_EHWAZ = 34, + RUNE_DAGAZ = 35, + RUNE_ANSUZ = 36, + RUNE_PERTHRO = 37, + RUNE_BERKANO = 38, + RUNE_ALGIZ = 39, + RUNE_BLANK = 40, + RUNE_BLACK = 41, + CARD_CHAOS = 42, + CARD_CREDIT = 43, + CARD_RULES = 44, + CARD_HUMANITY = 45, + CARD_SUICIDE_KING = 46, + CARD_GET_OUT_OF_JAIL = 47, + CARD_QUESTIONMARK = 48, + CARD_DICE_SHARD = 49, + CARD_EMERGENCY_CONTACT = 50, + CARD_HOLY = 51, + CARD_HUGE_GROWTH = 52, + CARD_ANCIENT_RECALL = 53, + CARD_ERA_WALK = 54, + RUNE_SHARD = 55, + CARD_REVERSE_MAGICIAN = 57, + CARD_REVERSE_HIGH_PRIESTESS = 58, + CARD_REVERSE_EMPRESS = 59, + CARD_REVERSE_EMPEROR = 60, + CARD_REVERSE_STRENGTH = 67, + CARD_REVERSE_HANGED_MAN = 68, + CARD_REVERSE_DEATH = 69, + CARD_REVERSE_TEMPERANCE = 70, + CARD_REVERSE_DEVIL = 71, + CARD_REVERSE_MOON = 74, + CARD_REVERSE_JUDGEMENT = 76, + CARD_CRACKED_KEY = 78, + CARD_QUEEN_OF_HEARTS = 79, + CARD_WILD = 80 +}; + // Whether a pill effect is the good (+) or bad (-) side of its class, as pocketitems.xml writes "class". enum PillClassModifier : uint8_t { diff --git a/src/item_overlay.h b/src/item_overlay.h index 658febc..eb2d22f 100644 --- a/src/item_overlay.h +++ b/src/item_overlay.h @@ -24,11 +24,24 @@ enum GiantbookOverlay : int GIANTBOOK_ETERNAL_SOUL_HEART = 6, GIANTBOOK_ETERNAL_HEART = 13, GIANTBOOK_NECRONOMICON = 12, + GIANTBOOK_MISSING_PAGE_2 = 31, GIANTBOOK_CLICKER = 39, GIANTBOOK_SLEEP_NIGHTMARE = 44, GIANTBOOK_MEGA_MUSH = 45, GIANTBOOK_ETERNAL_BLACK_HEART = 46, - GIANTBOOK_NECROMANCER = 47 + GIANTBOOK_NECROMANCER = 47, + GIANTBOOK_EMPRESS = 3, + GIANTBOOK_SUN = 5, + GIANTBOOK_JERA = 21, + GIANTBOOK_EHWAZ = 22, + GIANTBOOK_DAGAZ = 23, + GIANTBOOK_ANSUZ = 24, + GIANTBOOK_PERTHRO = 25, + GIANTBOOK_BERKANO = 26, + GIANTBOOK_ALGIZ = 27, + GIANTBOOK_REVERSE_DEVIL = 10, + GIANTBOOK_REVERSE_EMPRESS = 42, + GIANTBOOK_DEVIL = 34 }; // Destruction (009abd80) is the default. diff --git a/src/item_pickup.cpp b/src/item_pickup.cpp index 8ec8a27..c6a79b6 100644 --- a/src/item_pickup.cpp +++ b/src/item_pickup.cpp @@ -83,7 +83,6 @@ constexpr int SOUND_POWERUP3 = 130; constexpr int SOUND_BAND_AID_PICK_UP = 169; constexpr int ONE_UP_FRAME_DELAY = 30; constexpr float ITEM_SOUND_HALF_VOLUME = 0.5f; -constexpr int COLLECTIBLE_MAGIC_MUSHROOM = 12; constexpr int COLLECTIBLE_SUPER_BANDAGE = 92; constexpr int COLLECTIBLE_MINI_MUSH = 71; diff --git a/src/item_pool.cpp b/src/item_pool.cpp index cb243b0..0ebfc29 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -93,7 +93,6 @@ constexpr int BOSS_THE_FALLEN = 23; constexpr int HOME_CHEST_SUBTYPE = 2; constexpr int COLLECTIBLE_ROSARY = 72; -constexpr int COLLECTIBLE_VIRGO = 303; constexpr int COLLECTIBLE_CHAOS = 402; constexpr uint32_t CHALLENGE_ONANS_STREAK = 29; constexpr int ACHIEVEMENT_GOLDEN_TRINKETS = 617; @@ -125,10 +124,6 @@ constexpr int PILL_GOLD = 14; constexpr int PILL_GOLD_ODDS = 140; constexpr int PILL_HORSE_ODDS = 70; constexpr int PILL_EFFECT_NONE = -1; -constexpr int PILLEFFECT_BAD_TRIP = 1; -constexpr int PILLEFFECT_EXPLOSIVE_DIARRHEA = 4; -constexpr int PILLEFFECT_HEALTH_DOWN = 6; -constexpr int PILLEFFECT_I_FOUND_PILLS = 8; // The effect class each shuffled color slot must have, or -1 for any. constexpr int PILL_SLOT_CLASSES[PILL_COLOR_SLOTS - 1] = {3, 3, 3, 3, 2, 1, 0, -1, -1, 3, 2, 1, -1, -1}; // PHD's good side of a bad pill (0x00b6a240), and False PHD's bad side of a good one (its jump table at 0x00734c40). diff --git a/src/level.cpp b/src/level.cpp index a86b4e3..95a9fca 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -1,5 +1,6 @@ #include "level.h" #include "boss_pool.h" +#include "entity_effect.h" #include "entity_familiar.h" #include "entity_player.h" #include "game.h" @@ -13,6 +14,7 @@ #include "npc_ai.h" #include "platform.h" #include "room.h" +#include "room_config.h" #include "room_transition.h" #include "texture_cache.h" #include @@ -20,6 +22,7 @@ #include #include #include +#include #include // Where GetEnterPosition puts the players: a crawlspace's ladder down and its ladder back up, the Black Market's @@ -94,14 +97,12 @@ constexpr int EVENT_COUNTER_SUPER_SINS_B = 25; constexpr int EVENT_COUNTER_CURSE_ODDS = 11; constexpr int COLLECTIBLE_XRAY_VISION = 76; constexpr int COLLECTIBLE_MAGIC_8_BALL = 194; -constexpr int COLLECTIBLE_MOMS_SHOVEL = 552; constexpr int TRINKET_GOLDEN_HORSE_SHOE = 82; constexpr int TRINKET_FRAGMENTED_CARD = 102; constexpr int TRINKET_SILVER_DOLLAR = 110; constexpr int TRINKET_TELESCOPE_LENS = 152; constexpr int COLLECTIBLE_VOODOO_HEAD = 599; constexpr int TRINKET_MYOSOTIS = 137; -constexpr int TRINKET_DEVILS_CROWN = 146; constexpr int TREASURE_SUBTYPE_KNIFE_PIECE = 34; constexpr int LIL_PORTAL_ROOM_VARIANT = 2; constexpr int GRID_SPAWN_PIT_FIRST = 3000; @@ -376,6 +377,34 @@ static bool is_devils_crown_room(Level& level, RoomDescriptor& room) (!is_greed() || (uint32_t)room.gridIndex == level.greedModeTreasureRoomIdx) && room.visitedCount == 0; } +// The Void's rooms' distances from Delirium's room in steps of up to two doors, the rooms that near it at 1. The +// original walks them from a stack, so a distance is the first path's and not always the shortest. +static void delirium_distances_set(Level& level) +{ + std::vector pending; + + for (int idx : level.get_rooms_within_two_doors(level.roomList[level.firstBossRoomListIdx].gridIndex)) + { + level.GetRoomByIdx(idx)->deliriumDistance = 1; + pending.push_back(idx); + } + while (!pending.empty()) + { + int idx = pending.back(); + int distance = level.GetRoomByIdx(idx)->deliriumDistance + 1; + + pending.pop_back(); + for (int nearby : level.get_rooms_within_two_doors(idx)) + { + RoomDescriptor& room = *level.GetRoomByIdx(nearby); + + if (room.deliriumDistance >= 1) continue; + room.deliriumDistance = distance; + pending.push_back(nearby); + } + } +} + // 00744940 Lays out the floor: seeds its RNGs from the stage seed, rolls its curse, loads the stage's rooms, generates // the layout the floor calls for, then enters the start room (or the boss room on the Ascent) and starts the floor. void Level::Init(bool isResetLilPortalRoom) @@ -523,7 +552,7 @@ void Level::Init(bool isResetLilPortalRoom) else if (stage == STAGE_HOME) generate_home_level(); else if (stage <= ASCENT_LAST_STAGE && game_flag_get(LEVEL_GAME_STATE_BACKWARDS_PATH)) generate_backwards(); else if (game.challenge == CHALLENGE_RED_REDEMPTION) generate_random_layout(); - else if (stage == STAGE_BLUE_WOMB) generate_home(); + else if (stage == STAGE_BLUE_WOMB) generate_blue_womb(); else { game.roomConfig.ResetRoomWeights(STAGE_ID_SPECIAL_ROOMS, ROOM_MODE_CURRENT); @@ -532,8 +561,7 @@ void Level::Init(bool isResetLilPortalRoom) update_all_room_doors(); dungeonPlacementSeed = generationRNG.Next(); - if (!is_greed() && stage == STAGE_VOID && firstBossRoomListIdx >= 0) - reconstruction_missing("Level::Init 00744940: the Void's Delirium distances (get_rooms_within_two_doors)"); + if (!is_greed() && stage == STAGE_VOID && firstBossRoomListIdx >= 0) delirium_distances_set(*this); currentRoomIdx = startingRoomIdx; lastRoomIdx = startingRoomIdx; @@ -2696,10 +2724,83 @@ void Level::generate_greed() reconstruction_missing("Level::generate_greed 00743550"); } -// 0074a500 Lays out the Blue Womb. -void Level::generate_home() +// A room the Blue Womb lays by hand: its cell, shape, the cell it joins the start room through and from which side, +// and the type drawn for it. +struct BlueWombRoom { - reconstruction_missing("Level::generate_home 0074a500"); + XY position; + RoomShape shape = ROOMSHAPE_1x1; + XY linkPos; + int connectDirection = DIRECTION_NONE; + int type = ROOM_DEFAULT; +}; + +// The Blue Womb's rooms: the tall start room, the shop below it, a treasure room on each side and Hush's room above. +constexpr std::array BLUE_WOMB_ROOMS = {{ + {{6, 6}, ROOMSHAPE_1x2, XY_NONE, DIRECTION_NONE, ROOM_DEFAULT}, + {{6, 8}, ROOMSHAPE_1x1, {6, 8}, DIRECTION_DOWN, ROOM_SHOP}, + {{7, 7}, ROOMSHAPE_1x1, {7, 7}, DIRECTION_RIGHT, ROOM_TREASURE}, + {{5, 7}, ROOMSHAPE_1x1, {5, 7}, DIRECTION_LEFT, ROOM_TREASURE}, + {{6, 4}, ROOMSHAPE_2x2, {6, 5}, DIRECTION_UP, ROOM_BOSS}, +}}; + +// 0074a500 Lays out the Blue Womb by hand from its own rooms, Tainted Keeper's shop when he plays. Then the rooms off +// the map, all drawn from the generation RNG: the error room, black market, crawl space, Mega Satan's, the Void's +// entrance, the Member Card's shop and the angel shop. +void Level::generate_blue_womb() +{ + RoomConfig& roomConfig = g_game->roomConfig; + LevelGenerator generator(generationRNG.Next()); + std::array configs{}; + bool isTaintedKeeper = g_game->playerManager.FirstPlayerByType(PLAYER_KEEPER_B); + + for (const BlueWombRoom& room : BLUE_WOMB_ROOMS) + { + LevelGenerator_Room slot; + + slot.linkPos = room.linkPos; + slot.position = room.position; + slot.shape = room.shape; + slot.connectDirection = room.connectDirection; + generator.CreateRoom(slot); + } + configs[0] = roomConfig.GetRoomByStageTypeAndVariant(STAGE_ID_BLUE_WOMB, ROOM_DEFAULT, 0, ROOM_MODE_CURRENT); + for (size_t i = 1; i < BLUE_WOMB_ROOMS.size(); i++) + { + RoomQuery query = room_query(STAGE_ID_BLUE_WOMB, BLUE_WOMB_ROOMS[i].type, -1); + + query.shape = BLUE_WOMB_ROOMS[i].shape; + query.requiredDoors = generator.rooms[i].doors; + if (BLUE_WOMB_ROOMS[i].type == ROOM_SHOP) query.subtype = isTaintedKeeper ? SHOP_SUBTYPE_TAINTED_KEEPER : 0; + configs[i] = random_room_get(generationRNG.Next(), query); + } + + roomMap.fill(-1); + nbRooms = 0; + for (size_t i = 0; i < BLUE_WOMB_ROOMS.size(); i++) + place_room(generator.rooms[i], configs[i], generationRNG.Next(), nullptr); + lastBossRoomListIdx = generator.rooms.back().generationIndex; + + RoomQuery voidQuery = room_query(STAGE_ID_BLUE_WOMB, ROOM_DEFAULT, 1); + + voidQuery.minDifficulty = voidQuery.maxDifficulty = 0; + off_map_room_init(*this, ROOM_ERROR_IDX, generationRNG, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_ERROR, -1)); + off_map_room_init(*this, ROOM_BLACK_MARKET_IDX, generationRNG, + room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_BLACK_MARKET, -1)); + off_map_room_init(*this, ROOM_DUNGEON_IDX, generationRNG, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_DUNGEON, -1)); + off_map_room_init(*this, ROOM_MEGA_SATAN_IDX, generationRNG, + room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_BOSS, BOSS_MEGA_SATAN)); + off_map_room_init(*this, ROOM_THE_VOID_IDX, generationRNG, voidQuery); + + RNG shopRng = {generationRNG.Next(), 3, 3, 26}; + uint32_t lowLevel = + shopRng.RandomInt(1 + is_unlocked(ACHIEVEMENT_STORE_UPGRADE_2) + is_unlocked(ACHIEVEMENT_STORE_UPGRADE_4)); + uint32_t highLevel = shopRng.RandomInt(1 + is_unlocked(ACHIEVEMENT_STORE_UPGRADE_3)); + + off_map_room_init(*this, ROOM_SECRET_SHOP_IDX, generationRNG, + room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_SHOP, (int)(lowLevel + highLevel))); + generationRNG.Next(); + off_map_room_init(*this, ROOM_ANGEL_SHOP_IDX, generationRNG, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_ANGEL, 1)); } // 0074de30 Lays out Home. @@ -2964,10 +3065,48 @@ int Level::GetNonCompleteRoomIndex() reconstruction_missing("Level::GetNonCompleteRoomIndex 00740a60"); } -// 007484c0 A room of a type. -int Level::QueryRoomTypeIndex(int, bool, RNG&, bool) +// 007484c0 The safe grid index of a random room of a type in the current dimension and room group (any group when +// asked), a visited or unvisited one first as asked, else a random plain room's. The devil and angel rooms are made +// now and found at -1, the error room at -2 and the black market at -6. +int Level::QueryRoomTypeIndex(int roomType, bool isVisited, RNG& rng, bool isIgnoreGroup) { - reconstruction_missing("Level::QueryRoomTypeIndex 007484c0"); + constexpr int QUERY_ROOM_DEFAULT = 1; + constexpr int QUERY_ROOM_ERROR = 3; + constexpr int QUERY_ROOM_DEVIL = 14; + constexpr int QUERY_ROOM_ANGEL = 15; + constexpr int QUERY_ROOM_BLACK_MARKET = 22; + + if (roomType == QUERY_ROOM_ANGEL || roomType == QUERY_ROOM_DEVIL) + { + InitializeDevilAngelRoom(false, false); + return ROOM_DEVIL_IDX; + } + if (roomType == QUERY_ROOM_ERROR) return ROOM_ERROR_IDX; + if (roomType == QUERY_ROOM_BLACK_MARKET) return ROOM_BLACK_MARKET_IDX; + + int group = room->descriptor->group; + auto candidates_find = [&](int type) + { + std::vector found; + for (int i = 0; i < nbRooms; i++) + { + RoomDescriptor& each = roomList[i]; + bool isGroup = isIgnoreGroup || each.group == -1 || each.group == group; + if (each.data && each.data->type == type && each.dimension == currentDimensionIdx && isGroup) found.push_back(i); + } + RNG::Shuffle(&rng, found.data(), found.data() + found.size()); + return found; + }; + + std::vector candidates = candidates_find(roomType); + if (candidates.empty()) + { + candidates = candidates_find(QUERY_ROOM_DEFAULT); + return candidates.empty() ? -1 : roomList[candidates[0]].safeGridIndex; + } + for (int index : candidates) + if ((roomList[index].visitedCount != 0) == isVisited) return roomList[index].safeGridIndex; + return roomList[candidates[0]].safeGridIndex; } // 0074a090 Where the players enter the current room when no door brings them: a crawlspace's ladder (by the @@ -3022,10 +3161,43 @@ bool Level::TryInitializeExtraBossRoom(uint32_t) reconstruction_missing("Level::TryInitializeExtraBossRoom 0074d780"); } -// 0074d920 Refreshes the treasure rooms' doors for a trinket. +// 0074d920 Devil's Crown taken or dropped: the floor's unvisited treasure rooms (only the Greed mode's own in Greed) +// turn into devil treasure rooms or back, and the doors of the current room leading to one change with a poof. The +// visible map follows. void Level::update_treasure_room_doors_for_trinket() { - reconstruction_missing("Level::update_treasure_room_doors_for_trinket 0074d920"); + constexpr int SUBTYPE_KNIFE_PIECE = 34; + Game& game = *g_game; + bool isCrownHeld = game.playerManager.AnyoneHasTrinket(TRINKET_DEVILS_CROWN); + bool isGreed = game.difficulty == DIFFICULTY_GREED || game.difficulty == DIFFICULTY_GREEDIER; + std::set changed; + + for (int i = 0; i < game.nbRooms; i++) + { + RoomDescriptor& room = game.roomList[i]; + bool isTreasure = room.data->type == ROOM_TREASURE && room.data->subtype != SUBTYPE_KNIFE_PIECE && + (!isGreed || room.gridIndex == (int)game.greedModeTreasureRoomIdx); + bool isDevil = room.flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE; + if (!isTreasure || room.visitedCount != 0 || isDevil == isCrownHeld) continue; + room.flags = isCrownHeld ? room.flags | ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE : room.flags & ~ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE; + changed.insert(i); + } + if (changed.empty()) return; + + Room& current = *game.room; + bool isSecret = current.roomType == ROOM_SECRET || current.roomType == ROOM_SUPERSECRET || + current.roomType == ROOM_ULTRASECRET; + for (GridEntity_Door* door : current.doors) + { + if (isSecret || !door || door->targetRoomType != ROOM_TREASURE || door->targetRoomIdx < 0 || + door->targetRoomIdx >= ROOM_MAP_CELLS || !changed.contains(game.roomMap[door->targetRoomIdx])) + continue; + uint32_t seed = Random(); + game.Spawn({.position = current.GetGridPosition(door->gridIndex), .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = seed}); + door->LoadSprite(); + door->UpdateAnimation(); + } + game.UpdateVisibility(); } // 0074beb0 Sets up Rotgut's room. diff --git a/src/level.h b/src/level.h index 6fe5863..0d485a8 100644 --- a/src/level.h +++ b/src/level.h @@ -250,7 +250,7 @@ public: bool place_room(const LevelGenerator_Room& slot, RoomConfig_Room* data, uint32_t seed, RoomDescriptor** outDesc); void generate_backwards(); void generate_greed(); - void generate_home(); + void generate_blue_womb(); void generate_home_level(); void generate_random_layout(); void generate_mirror_world(); diff --git a/src/lua_api_game.cpp b/src/lua_api_game.cpp index dcc30b1..0395ba8 100644 --- a/src/lua_api_game.cpp +++ b/src/lua_api_game.cpp @@ -49,7 +49,7 @@ void Game::ChangeRoom(int roomIndex, int dimension) // 00703850 A random player within a radius of a position, else the last of the shuffled players. // The original reads before an empty player list. Here there is no player then. -static Entity_Player* game_random_player(Game& game, Vector position, float radius) +Entity_Player* game_random_player(Game& game, Vector position, float radius) { std::vector players = game.playerManager.playerList; if (players.empty()) return nullptr; diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index 65239ea..0f1bac8 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -4,9 +4,11 @@ #include "game.h" #include "manager.h" #include "npc_fireplace.h" +#include "room_grid.h" #include "room_special.h" #include "sfx_manager.h" #include "mines.h" +#include "entity_player_characters.h" #include "tainted_characters.h" // The Beast's forms, by variant: its stalactites, rocks and soul, the four ultra horsemen and their summons, and @@ -72,6 +74,75 @@ static void mother_update(Entity_NPC& npc) } } +// A heart spawned for a Mask, charmed with it. +static Entity* mask_heart_spawn(Entity_NPC& npc, Vector position, int subType, uint32_t seed, bool isCharmed) +{ + Entity* heart = g_game->Spawn( + {.position = position, .spawner = &npc, .subType = subType, .type = ENTITY_HEART, .variant = npc.variant, .seed = seed}); + if (isCharmed) heart->AddCharmed(EntityRef(), -1, false, false); + return heart; +} + +// Part of 006c2990: a Mask (93) takes the nearest free Heart of its variant and friendliness, else brings its own (a +// linked pair for variant 1). It is invulnerable while its heart beats. +static void mask_heart_pair(Entity_NPC& npc) +{ + constexpr float HEART_SEARCH = 40; + constexpr float HEART_PAIR_GAP = 15; + constexpr float HEART_SCORE = 1000; + bool isCharmed = npc.HasEntityFlags(FLAG_FRIENDLY); + if (!npc.parent) + { + Entity* best = nullptr; + float bestScore = 0; + for (Entity* heart : entity_query(ENTITY_HEART, npc.variant)) + { + if (heart->child || heart->HasEntityFlags(FLAG_FRIENDLY) != isCharmed) continue; + float score = HEART_SCORE - vector_length(vector_sub(npc.pos, heart->pos)); + if (best && score <= bestScore) continue; + best = heart; + bestScore = score; + } + if (best) + { + best->child = &npc; + npc.parent = best; + if (best->parent) npc.entityRef = best->parent.get(); + } + } + if (!npc.parent) + { + Vector spot = room_free_pickup_position_find({.position = npc.pos, .step = HEART_SEARCH}); + if (npc.variant == 1) + { + auto* left = static_cast( + mask_heart_spawn(npc, vector_make(spot.x - HEART_PAIR_GAP, spot.y), 0, Random(), isCharmed)); + left->child = &npc; + npc.parent = left; + auto* right = static_cast( + mask_heart_spawn(npc, vector_make(spot.x + HEART_PAIR_GAP, spot.y), 1, Random(), isCharmed)); + right->child = left; + left->parent = right; + npc.entityRef = right; + left->entityRef = right; + right->entityRef = left; + left->Update(); + } + else + { + uint32_t seed = Random(); + Entity* heart = mask_heart_spawn(npc, room_free_pickup_position_find({.position = npc.pos, .step = HEART_SEARCH}), 0, + seed, isCharmed); + heart->child = &npc; + npc.parent = heart; + heart->Update(); + } + } + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_HIDE_HP_BAR); + npc.state = NPC_STATE_MOVE; + npc.isInvincible = true; +} + // The AI routine of each NPC type. Types it does not list (the ones the game left without an AI) do nothing. static void npc_ai_routine_run(Entity_NPC& npc) { @@ -175,7 +246,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 41: case 254: case 283: - return (void)NpcAI::ENTITY_KNIGHT(&npc); + return npc_knight_update(npc); case 42: case 203: case 235: @@ -258,11 +329,12 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 229: case 230: case 253: - return (void)NpcAI::ENTITY_SWARMER(&npc); + return npc_swarmer_update(npc); case 92: return (void)NpcAI::ENTITY_HEART(&npc); case 93: - reconstruction_missing("npc_ai_update 006c2990: Mask pairing with its Heart"); + if (npc.state == NPC_STATE_INIT) return mask_heart_pair(npc); + return boss_mask_of_infamy_update(npc); case 96: return npc_eternal_fly_update(npc); case 97: @@ -312,7 +384,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 222: return npc_ring_fly_update(npc); case 224: - return (void)NpcAI::ENTITY_OOB(&npc); + return npc_oob_update(npc); case 225: return (void)NpcAI::ENTITY_BLACK_MAW(&npc); case 226: @@ -321,7 +393,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) return npc_skinny_update(npc); case 228: case 251: - return (void)NpcAI::ENTITY_HOMUNCULUS(&npc); + return npc_homunculus_update(npc); case 231: case 964: return npc_nerve_ending_update(npc); @@ -339,7 +411,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 289: return npc_round_worm_update(npc); case 245: - return (void)NpcAI::ENTITY_POOP(&npc); + return npc_poop_update(npc); case 256: return npc_dart_fly_update(npc); case 258: @@ -374,8 +446,8 @@ static void npc_ai_routine_run(Entity_NPC& npc) return boss_lamb_update(npc); case 274: case 275: - if (npc.variant != 0) return NpcAI::ENTITY_MEGA_SATAN_hand(&npc); - NpcAI::ENTITY_MEGA_SATAN(&npc); + if (npc.variant != 0) return boss_mega_satan_hand_update(npc); + boss_mega_satan_update(npc); if (npc.isDead) npc.ClearEntityFlags(FLAG_NO_DEATH_TRIGGER); return; case 281: @@ -393,13 +465,13 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 294: return (void)NpcAI::ENTITY_ULTRA_DOOR(&npc); case 295: - return (void)NpcAI::ENTITY_CORN_MINE(&npc); + return npc_corn_mine_update(npc); case 296: - return (void)NpcAI::ENTITY_HUSH_FLY(&npc); + return npc_hush_fly_update(npc); case 297: return npc_hush_gaper_update(npc); case 298: - return (void)NpcAI::ENTITY_HUSH_BOIL(&npc); + return npc_hush_boil_update(npc); case 299: return npc_greed_gaper_update(npc); case 300: @@ -413,27 +485,27 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 308: return (void)NpcAI::ENTITY_FISTULOID(&npc); case 309: - return (void)NpcAI::ENTITY_GUSH(&npc); + return npc_gush_update(npc); case 310: - return (void)NpcAI::ENTITY_LEPER(&npc); + return npc_leper_update(npc); case 311: return (void)NpcAI::ENTITY_MR_MINE(&npc); case 402: - return (void)NpcAI::ENTITY_BROWNIE(&npc); + return boss_brownie_update(npc); case 403: return (void)NpcAI::ENTITY_FORSAKEN(&npc); case 404: return boss_little_horn_update(npc); case 405: - return (void)NpcAI::ENTITY_RAG_MAN(&npc); + return boss_rag_man_update(npc); case 406: return (void)NpcAI::ENTITY_ULTRA_GREED(&npc); case 407: return boss_hush_update(npc); case 409: - return (void)NpcAI::ENTITY_RAG_MEGA(&npc); + return boss_rag_mega_update(npc); case 410: - return (void)NpcAI::ENTITY_SISTERS_VIS(&npc); + return boss_sisters_vis_update(npc); case 411: return (void)NpcAI::ENTITY_BIG_HORN(&npc); case 412: @@ -449,7 +521,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 806: return (void)NpcAI::ENTITY_BUBBLES(&npc); case 808: - return (void)NpcAI::ENTITY_WILLO(&npc); + return npc_willo_update(npc); case 809: return npc_bomb_grimace_update(npc); case 810: @@ -487,7 +559,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 828: return (void)NpcAI::ENTITY_NECRO(&npc); case 829: - return (void)NpcAI::ENTITY_MOLE(&npc); + return npc_mole_update(npc); case 830: return (void)NpcAI::ENTITY_BIG_BONY(&npc); case 831: @@ -567,7 +639,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 885: return (void)NpcAI::ENTITY_CULTIST(&npc); case 886: - return (void)NpcAI::ENTITY_VIS_FATTY(&npc); + return npc_vis_fatty_update(npc); case 887: return (void)NpcAI::ENTITY_DUSTY_DEATHS_HEAD(&npc); case 888: @@ -583,7 +655,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 893: return (void)NpcAI::ENTITY_BALL_AND_CHAIN(&npc); case 900: - return (void)NpcAI::ENTITY_REAP_CREEP(&npc); + return boss_reap_creep_update(npc); case 901: return (void)NpcAI::ENTITY_LIL_BLUB(&npc); case 902: @@ -601,7 +673,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 906: return npc.Hornfel_UpdateAI(); case 907: - return (void)NpcAI::ENTITY_GIDEON(&npc); + return boss_gideon_update(npc); case 908: return boss_baby_plum_update(npc); case 909: @@ -614,7 +686,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 912: return mother_update(npc); case 913: - return (void)NpcAI::ENTITY_MIN_MIN(&npc); + return boss_min_min_update(npc); case 914: return (void)NpcAI::ENTITY_CLOG(&npc); case 915: diff --git a/src/npc_ai.h b/src/npc_ai.h index f2434a0..8be9252 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -13,6 +13,9 @@ constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; constexpr float RANDOM_HALF_TURN = 3.14f; constexpr float DEGREES_TO_RADIANS = 0.017453292f; constexpr float RADIANS_TO_DEGREES = 57.295776f; +constexpr float FULL_TURN_DEGREES = 360; +constexpr float HALF_TURN_DEGREES = 180; +constexpr float RIGHT_ANGLE_DEGREES = 90; inline Vector vector_add(Vector a, Vector b) { @@ -104,6 +107,8 @@ inline int npc_ticks_get(Entity_NPC& npc) return (int)npc.updateTime - (int)npc.prevUpdateTime; } +float normalize_angle_degrees(float angle); + void npc_ai_update(Entity_NPC& npc); void npc_fly_update(Entity_NPC& npc); void npc_gaper_update(Entity_NPC& npc); @@ -111,5 +116,21 @@ void npc_horf_update(Entity_NPC& npc); void npc_dip_update(Entity_NPC& npc); void npc_sin_update(Entity_NPC& npc); -// The corn dip's variant. +// The drawings of the NPCs that draw themselves their own way (npc_render_parts.cpp). +void peeping_fatty_render(Entity_NPC& npc, const Vector& offset); +void evis_render(Entity_NPC& npc, const Vector& offset); +void scourge_chain_render(Entity_NPC& npc, const Vector& offset); +void chimera_child_render(Entity_NPC& npc, const Vector& offset); +void horny_boys_render(Entity_NPC& npc, const Vector& offset); +void hornfel_render(Entity_NPC& npc, const Vector& offset); +void hornfel_minecart_render(Entity_NPC& npc, ANM2& cart, const Vector& position); +void ball_and_chain_render(Entity_NPC& npc, const Vector& offset); + +// The variants other AIs spawn or test: the corn and Brownie's dips, the Dank Squirt, Rag Man's Ragling, the Black +// Knight and Dingle's Dangle. constexpr int DIP_CORN = 1; +constexpr int DIP_BROWNIE = 2; +constexpr int SQUIRT_DANK = 1; +constexpr int RAGLING_RAG_MAN = 1; +constexpr int KNIGHT_BLACK = 4; +constexpr int DANGLE = 1; diff --git a/src/npc_alt.h b/src/npc_alt.h index 7ed9487..e9b12dc 100644 --- a/src/npc_alt.h +++ b/src/npc_alt.h @@ -1,6 +1,7 @@ #pragma once #include "npc_depths.h" +#include "game.h" // The splat of the stone and lava enemies: black, lifted a little. constexpr ColorMod ROCK_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {30 / 255.0f, 30 / 255.0f, 30 / 255.0f}}; @@ -26,3 +27,37 @@ void npc_quake_grimace_update(Entity_NPC& npc); void npc_strider_update(Entity_NPC& npc); void npc_fire_worm_update(Entity_NPC& npc); void npc_rock_spider_update(Entity_NPC& npc); + +// The Great Gideon (boss_gideon.cpp): its AI, its death step, its leaving a chain, and the spawn pentagram its waves +// rise from (entity_effect_alt.cpp). +void boss_gideon_update(Entity_NPC& npc); +void gideon_death_update(Entity_NPC& npc); +void gideon_chain_unlink(Entity_NPC& npc); +Entity_Effect* pentagram_spawn(const EntitySpawn& spawn, int gridIndex); + +// Big Horn's death start and splash, which Entity_NPC::Update runs (boss_big_horn.cpp). +void big_horn_death_play(Entity_NPC& npc); +void big_horn_splash(Entity_NPC& npc); + +// The Tuff Twins and the Shell (boss_tuff_twins.cpp), which Larry Jr.'s AI hands its variants 2 and 3. +void boss_tuff_twins_update(Entity_NPC& npc); + +// The Mole and Tainted Mole (npc_mole.cpp). +void npc_mole_update(Entity_NPC& npc); + +// The Vis Fatty and its Fetal Demon (npc_vis_fatty.cpp). +void npc_vis_fatty_update(Entity_NPC& npc); + +// Min-Min and its Willos (boss_min_min.cpp): their AIs, Min-Min's death bursts, and a Willo rising for a spawner. +void boss_min_min_update(Entity_NPC& npc); +void min_min_death_update(Entity_NPC& npc); +void npc_willo_update(Entity_NPC& npc); +Entity_NPC* willo_spawn(const Vector& position, Entity* spawner, float ringRadius, int subType); +Vector willo_slot(Entity_NPC& npc, int slot); + +// A bound Willo only touches a player within 30 of its slot. +constexpr float WILLO_TOUCH_REACH = 30; + +// A Willo spawner's states: waiting, or woken to send up its Willo. +constexpr int SPAWNER_WAITING = 0; +constexpr int SPAWNER_WOKEN = 1; diff --git a/src/npc_caves.h b/src/npc_caves.h index b78471a..dac6fbe 100644 --- a/src/npc_caves.h +++ b/src/npc_caves.h @@ -21,6 +21,13 @@ void npc_gurgle_update(Entity_NPC& npc); void npc_eternal_fly_update(Entity_NPC& npc); void npc_pitfall_update(Entity_NPC& npc); void npc_pustule_update(Entity_NPC& npc); +void npc_swarmer_update(Entity_NPC& npc); +void npc_homunculus_update(Entity_NPC& npc); +void npc_knight_update(Entity_NPC& npc); +void npc_gush_update(Entity_NPC& npc); +void npc_oob_update(Entity_NPC& npc); +void npc_leper_update(Entity_NPC& npc); +void npc_corn_mine_update(Entity_NPC& npc); // Pushes a bouncer (the Boom Fly, the floating Host) along its diagonal, steered by its controller. False when a // confused one wanders instead. diff --git a/src/npc_clotty.cpp b/src/npc_clotty.cpp index 2a1e413..8482a81 100644 --- a/src/npc_clotty.cpp +++ b/src/npc_clotty.cpp @@ -52,8 +52,6 @@ constexpr float CLOGGY_ANGLE = 0.9424779f; // five enemies are left) or spreads four pools of creep within 40, lasting 210 frames. It splits in two Clotties. constexpr float MEGA_RING_SPEED = 10; constexpr float MEGA_RING_SHOTS = 6; -constexpr float HALF_TURN_DEGREES = 180; -constexpr float FULL_TURN_DEGREES_CLOTTY = 360; constexpr float MEGA_SOUND_VOLUME = 0.8f; constexpr int MEGA_SPAWN_LIMIT = 5; constexpr float MEGA_SPAWN_STEP = 40; @@ -167,7 +165,7 @@ static void mega_clotty_shoot(Entity_NPC& npc) if (mega_clotty_ring_get(npc, aim)) { ProjectileParams params; - params.circleAngle = random_unit() * FULL_TURN_DEGREES_CLOTTY - HALF_TURN_DEGREES; + params.circleAngle = random_unit() * FULL_TURN_DEGREES - HALF_TURN_DEGREES; npc.FireProjectiles(npc.pos, vector_make(MEGA_RING_SPEED, MEGA_RING_SHOTS), PROJECTILES_RING, params); return; } diff --git a/src/npc_collision.cpp b/src/npc_collision.cpp index 1b983bf..a3616d8 100644 --- a/src/npc_collision.cpp +++ b/src/npc_collision.cpp @@ -15,11 +15,7 @@ #include // The NPC types whose contacts differ from the generic ones. -constexpr int ENTITY_DEATH = 66; constexpr int ENTITY_HORSEMAN_HEAD = 83; -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_SWARM = 281; constexpr int ENTITY_ULTRA_COIN = 293; @@ -37,7 +33,6 @@ constexpr int FIREPLACE_FRIENDLY_FIRST = 10; constexpr int FIREPLACE_MOVABLE = 11; constexpr int FIREPLACE_FRIENDLY_RED = 12; constexpr int FIREPLACE_FRIENDLY_BLUE = 13; -constexpr int KNIGHT_BLACK = 4; constexpr int MINECART_EXIT = 10; constexpr int LARRY_SEGMENT_VARIANT = 3; constexpr int VIS_CHUBBER_VARIANT = 22; @@ -366,8 +361,8 @@ static Verdict contact_kinds(Contact& contact) if (collider.type == ENTITY_PLAYER) { if (npc.projectileCooldown > 0) return contact.isIgnored; - if (npc.subtype == 0) - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: Willo's slot (NpcHelper::willo_slot)"); + if (npc.subtype == 0 && vector_length(vector_sub(willo_slot(npc, 0), npc.pos)) > WILLO_TOUCH_REACH) + return contact.isIgnored; } if (collider.IsEnemy() || collider.type == ENTITY_BOMB) return contact.isIgnored; break; @@ -675,7 +670,7 @@ static Verdict moms_hand_player_grab(Contact& contact, bool& isBumpNext) npc.isInvincible = true; npc.entityCollisionClass = ENTCOLL_NONE; npc.stateFrame = 0; - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: Mom's hand taking a player (Entity_Player 0x189c)"); + moms_hand_player_grab(player); return contact.isIgnored; } diff --git a/src/npc_corn_mine.cpp b/src/npc_corn_mine.cpp new file mode 100644 index 0000000..805ae0b --- /dev/null +++ b/src/npc_corn_mine.cpp @@ -0,0 +1,57 @@ +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_projectile.h" +#include "npc_caves.h" + +// The Corn Mine waits (6 seconds at most), pulses once its target comes within 60, then bursts. +constexpr int CORN_MINE_PULSE = NPC_STATE_ATTACK; +constexpr float CORN_MINE_REACH = 60; +constexpr float CORN_MINE_PULSE_FRAME = 50; +constexpr int CORN_MINE_FUSE = 181; +constexpr float CORN_MINE_FRICTION = 0.1f; +constexpr float CORN_MINE_FART_RADIUS = 85; +constexpr float CORN_MINE_DAMAGE = 40; +constexpr float CORN_MINE_SHOT_SPEED = 10; + +// Its burst: it dies in a fart and a blast as big as itself, spraying corn shots that hurt enemies too. +static void corn_mine_burst(Entity_NPC& npc) +{ + npc.Kill(EntityRef()); + game_fart({.position = npc.pos, .source = &npc, .radius = CORN_MINE_FART_RADIUS}); + explosion_damage({.position = npc.pos, + .source = &npc, + .damage = CORN_MINE_DAMAGE, + .radius = npc.size, + .isLineCheck = false}); + ProjectileParams params; + params.bulletFlags |= PROJECTILE_HIT_ENEMIES; + params.variant = PROJECTILE_CORN; + npc.FireProjectiles(npc.pos, vector_make(CORN_MINE_SHOT_SPEED, 0), PROJECTILES_EIGHT, params); +} + +// 0048ee30 The Corn Mine (295) Brownie drops: immune to status effects and spikes, it bursts once pulsed or killed. +void npc_corn_mine_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_BLOOD_SPLASH | FLAG_NO_SPIKE_DAMAGE); + npc.state = NPC_STATE_IDLE; + return; + } + if (npc.state == NPC_STATE_IDLE) + { + if (vector_length(vector_sub(npc.pos, npc.CalcTargetPosition(0))) < CORN_MINE_REACH) + { + npc.sprite.Play("Pulse"); + if (npc.sprite.animState.animData) npc.sprite.animState.SetFrameFloat(CORN_MINE_PULSE_FRAME); + npc.state = CORN_MINE_PULSE; + } + if (++npc.stateFrame >= CORN_MINE_FUSE) npc.state = CORN_MINE_PULSE; + } + if (npc.state == CORN_MINE_PULSE || npc.isDead) + { + npc_anim_loop(npc.sprite, "Pulse"); + if (npc_anim_is_done(npc) || npc.isDead) corn_mine_burst(npc); + } + npc.friction *= CORN_MINE_FRICTION; +} diff --git a/src/npc_depths.h b/src/npc_depths.h index 1c3fcdf..404d108 100644 --- a/src/npc_depths.h +++ b/src/npc_depths.h @@ -26,5 +26,7 @@ void npc_wizoob_update(Entity_NPC& npc); void npc_mr_maw_update(Entity_NPC& npc); void npc_cod_worm_update(Entity_NPC& npc); void npc_moms_hand_update(Entity_NPC& npc); +void moms_hand_player_grab(Entity_Player& player); +void moms_hand_player_release_update(Entity_Player& player); void npc_hush_gaper_update(Entity_NPC& npc); void npc_greed_gaper_update(Entity_NPC& npc); diff --git a/src/npc_dip.cpp b/src/npc_dip.cpp index e075602..5f14786 100644 --- a/src/npc_dip.cpp +++ b/src/npc_dip.cpp @@ -5,7 +5,6 @@ #include "game.h" #include "room.h" -constexpr int DIP_BROWNIE = 2; constexpr int DIP_BIG_CORN = 3; constexpr int FAMILIAR_DIP_CORN = 2; constexpr int FAMILIAR_DIP_BROWNIE = 20; diff --git a/src/npc_gaper.cpp b/src/npc_gaper.cpp index a5636d6..8956599 100644 --- a/src/npc_gaper.cpp +++ b/src/npc_gaper.cpp @@ -82,7 +82,6 @@ constexpr float BEAM_SOUND_VOLUME = 0.7f; constexpr float BEAM_BLOOD_BACK = 5; constexpr float BEAM_BLOOD_RISE = -16; constexpr float BEAM_BLOOD_DEPTH = 10; -constexpr float FULL_TURN_DEGREES = 360; constexpr ColorMod BEAM_BLOOD_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.08f, 0.5f, 0.01f}}; constexpr ColorMod BEAM_SPLAT_COLOR = {{0, 0, 0, 0.5f}, {0, 0, 0, 0}, {0.08f, 0.5f, 0.01f}}; diff --git a/src/npc_gush.cpp b/src/npc_gush.cpp new file mode 100644 index 0000000..3dccbbf --- /dev/null +++ b/src/npc_gush.cpp @@ -0,0 +1,133 @@ +#include "boss_ai.h" +#include "npc_caves.h" +#include + +// The Gush spews black creep: a puddle under it, then now and then another near one of its own puddles. +constexpr ColorMod GUSH_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int GUSH_GRID_MARK = 900; +constexpr int GUSH_GRID_MARK_LIMIT = 951; +constexpr float GUSH_FRICTION = 0.8f; +constexpr int GUSH_REST_MIN = 1; +constexpr uint32_t GUSH_REST_RANGE = 10; +constexpr float GUSH_CREEP_SCALE = 2; +constexpr int GUSH_CREEP_TIMEOUT = 30; +constexpr int GUSH_SPEW_TIMEOUT = 45; +constexpr size_t GUSH_CREEP_LIMIT = 256; +constexpr int GUSH_SPEW_TRIES = 10; +constexpr float GUSH_SPEW_REACH = 200; +constexpr float GUSH_SPEW_REACH_STEP = 100; +constexpr float GUSH_OWN_CREEP_REACH_SQUARED = 5625; +constexpr float GUSH_CROWDED_SQUARED = 1600; +constexpr int GUSH_CREEP_HELD = 30; +constexpr float GUSH_CREEP_GROW_START = 45; +constexpr float GUSH_CREEP_GROW_SPAN = -15; +constexpr float GUSH_CREEP_GROWN = 1.5f; +constexpr float GUSH_SPLAT_MIN = 0.8f; +constexpr float GUSH_SPLAT_RANGE = 0.4f; + +// A puddle of its creep, scaled, lasting a while. +static Entity_Effect* gush_creep_spawn(Entity_NPC& npc, Vector position, int timeout) +{ + auto* creep = static_cast(g_game->Spawn( + {.position = position, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_BLACK, .seed = Random()})); + creep->timeout = timeout; + creep->lifespan = timeout; + creep->parent = &npc; + creep->sprite.scale = vector_make(GUSH_CREEP_SCALE, GUSH_CREEP_SCALE); + creep->Update(); + return creep; +} + +// Its puddles grow in as they spread and stay until it dies, each leaving a black splat as it settles. +static void gush_creep_update(Entity_NPC& npc, std::vector& creeps) +{ + for (Entity* entity : creeps) + { + auto* creep = static_cast(entity); + if (creep->parent.get() != &npc) continue; + if (creep->timeout <= GUSH_CREEP_HELD) + { + creep->timeout = GUSH_CREEP_HELD; + creep->lifespan = GUSH_CREEP_HELD; + continue; + } + + float grown = std::clamp(((float)creep->timeout - GUSH_CREEP_GROW_START) / GUSH_CREEP_GROW_SPAN, 0.0f, 1.0f); + creep->sprite.scale = vector_make(grown * GUSH_CREEP_GROWN, grown * GUSH_CREEP_GROWN); + if (creep->timeout != GUSH_CREEP_HELD + 1) continue; + + Entity* splat = g_game->Spawn( + {.position = creep->pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float size = random_unit() * GUSH_SPLAT_RANGE + GUSH_SPLAT_MIN; + splat->sprite.scale = vector_make(size, size); + splat->SetColor(GUSH_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + } +} + +// A new puddle, in ten tries further out each time: on a free spot in the room, clear of every puddle within 40 and +// near one of its own within 75. It grows in from nothing. +static void gush_spew(Entity_NPC& npc) +{ + Room& room = *g_game->room; + float reach = GUSH_SPEW_REACH; + for (int i = 0; i < GUSH_SPEW_TRIES; i++, reach += GUSH_SPEW_REACH_STEP) + { + float spread = random_unit(); + Vector direction = random_direction(); + Vector spot = vector_add(npc.pos, vector_scale(direction, spread * spread * reach)); + if (!room.IsPositionInRoom(spot, 0) || room.GetGridCollision(room.GetGridIndex(spot)) != 0) continue; + + std::vector creeps = entity_query(ENTITY_EFFECT, EFFECT_CREEP_BLACK); + bool isOwnNear = false; + bool isCrowded = false; + for (Entity* creep : creeps) + { + float distance = vector_length_squared(vector_sub(spot, creep->pos)); + if (distance < GUSH_OWN_CREEP_REACH_SQUARED && creep->parent.get() == &npc) isOwnNear = true; + if (distance < GUSH_CROWDED_SQUARED) isCrowded = true; + if (isCrowded) break; + } + if (isCrowded || !isOwnNear) continue; + + gush_creep_spawn(npc, spot, GUSH_SPEW_TIMEOUT)->sprite.scale = {}; + return; + } +} + +// 00547330 The Gush (309): it sits in its creep, marking its cell for the pathfinder, and spews more every few frames. +void npc_gush_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + int column = (int)((npc.pos.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((npc.pos.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + int cell = row * room.gridWidth + column; + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight && cell < ROOM_GRID_CELLS; + if (isInside && room.gridPaths[cell] < GUSH_GRID_MARK_LIMIT) room.gridPaths[cell] = GUSH_GRID_MARK; + + if (npc.state == NPC_STATE_INIT) + { + npc.splatColor = GUSH_SPLAT_COLOR; + npc.state = NPC_STATE_IDLE; + npc.targetPosition = npc.pos; + npc.AddEntityFlags(FLAG_NO_PLAYER_CONTROL); + npc.i1 = (int)(Random() % GUSH_REST_RANGE) + GUSH_REST_MIN; + gush_creep_spawn(npc, npc.pos, GUSH_CREEP_TIMEOUT); + return; + } + + if (npc.state == NPC_STATE_IDLE) + { + npc.sprite.Play("Spew"); + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + std::vector creeps = entity_query(ENTITY_EFFECT, EFFECT_CREEP_BLACK); + gush_creep_update(npc, creeps); + if (npc.i1 >= 1) npc.i1 -= npc_ticks_get(npc); + else if (creeps.size() < GUSH_CREEP_LIMIT) + { + npc.i1 = (int)(Random() % GUSH_REST_RANGE) + GUSH_REST_MIN; + gush_spew(npc); + } + } + npc.friction = GUSH_FRICTION; +} diff --git a/src/npc_homunculus.cpp b/src/npc_homunculus.cpp new file mode 100644 index 0000000..4ea6d23 --- /dev/null +++ b/src/npc_homunculus.cpp @@ -0,0 +1,339 @@ +#include "boss_ai.h" +#include "menu_manager.h" +#include "grid_entity.h" +#include "level.h" +#include "npc_basement.h" +#include "npc_caves.h" +#include "room_descriptor.h" + +// The Homunculus (228) and the Begotten (251) are leashed to a wall or a block by their cord (variant 10), until they +// struggle free. The Cage's Begotten (from 265.1) starts free. +constexpr int HOMUNCULUS_CORD = 10; +constexpr int CAGE_BEGOTTEN_SPAWNER = 265; +constexpr int CAGE_BEGOTTEN_VARIANT = 1; +constexpr int HOMUNCULUS_FREE = NPC_STATE_ATTACK; +constexpr int UMBILICAL_SEGMENTS = 8; +constexpr float CORD_SEGMENT_LAST = 7; +constexpr float UMBILICAL_SAG = 10; +constexpr float CORD_DROP = 7; +constexpr float CORD_STAKE_LIFT = 2; +constexpr int CORD_DEPTH = -1000; +constexpr ColorMod BEGOTTEN_SPLAT_COLOR = {{0.1f, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Where its cord is staked: the nearest wall (20 past the sides, 40 below the bottom) or, when that is over 40 away, a +// block next to it. +constexpr float LEASH_WALL_SIDE = 20; +constexpr float LEASH_WALL_BOTTOM = 40; +constexpr float LEASH_FAR = 10000; +constexpr float LEASH_BLOCK_REACH = 40; +constexpr float LEASH_NEIGHBOURS[][2] = {{0, -40}, {0, 40}, {-40, 0}, {40, 0}}; +constexpr float LEASH_LENGTH = 100; +constexpr float LEASH_PULL_BACK = 0.01f; +constexpr float LEASH_SNAP_FRICTION = 0.2f; +constexpr float LEASH_CONTROLLED_FRICTION = 0.85f; +constexpr float LEASH_CONTROLLED_PULL = 0.8f; +constexpr uint32_t STRUGGLE_CONTROLLED_ODDS_MASK = 3; +constexpr int STRUGGLE_MIN_FRAMES = 60; +constexpr uint32_t STRUGGLE_FRAME_RANGE = 30; +constexpr int STRUGGLE_CHECK_FRAMES = 30; +constexpr uint32_t STRUGGLE_ODDS = 5; +constexpr int BOSS_ID_NO_STRUGGLE = 53; +constexpr int ROOM_STAGE_HOME = 35; +constexpr int GRID_PATH_BLOCKED_MIN = 1000; +constexpr int GRID_PATH_OPEN_AGAIN = 3000; +constexpr int GRID_PATH_BLOCKED_AGAIN = 4000; + +constexpr float HOMUNCULUS_PATH_SPEED = 1.5f; +constexpr float HOMUNCULUS_FREE_SPEED = 2; +constexpr int HOMUNCULUS_FREE_PATH_MARKER = 900; +constexpr float HOMUNCULUS_EVADE_FRICTION = 0.8f; +constexpr float HOMUNCULUS_FREE_EVADE_FRICTION = 0.9f; +constexpr float HOMUNCULUS_FRICTION = 0.8f; +constexpr float HOMUNCULUS_WALK_THRESHOLD = 0.1f; +constexpr float BREAK_CLAMP_TOP = 30; +constexpr float BREAK_CLAMP_BOTTOM = 10; +constexpr float BREAK_STAKE_REACH = 60; +constexpr float BREAK_SHOT_SPEED = 10; +constexpr float BREAK_SHOTS = 6; +constexpr int BEGOTTEN_DARKNESS_FRAMES = 150; +constexpr float BEGOTTEN_FADE = 0.1f; +constexpr float CORD_CREEP_SPREAD = 20; +constexpr float CORD_CREEP_SIZE_MIN = 0.25f; + +// Restarts an overlay animation from its first frame. +static void overlay_restart(ANM2& sprite, std::string_view name) +{ + if (!sprite.SetOverlayAnimation(name, SWITCH_KEEP_FRAME)) return; + + sprite.overlayAnimState.Rewind(); + sprite.overlayAnimState.isPlaying = true; +} + +// Keeps an overlay animation playing, restarting it once it ends unless it holds its last frame. +static void overlay_loop(ANM2& sprite, std::string_view name) +{ + const AnimationData* data = sprite.overlayAnimState.animData; + bool isShown = data && data->name == name && (!data->isLooping || sprite.overlayAnimState.isPlaying); + if (!isShown) overlay_restart(sprite, name); +} + +static bool is_cage_begotten(const Entity_NPC& npc) +{ + return npc.spawnerType == CAGE_BEGOTTEN_SPAWNER && npc.spawnerVariant == CAGE_BEGOTTEN_VARIANT && npc.type == ENTITY_BEGOTTEN; +} + +// Stakes the cord on the nearest wall, or a block next to it (its grid index in i1, else -1). +static void leash_stake(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.i1 = -1; + float left = room.topLeftPos.x - LEASH_WALL_SIDE; + float right = room.bottomRightPos.x + LEASH_WALL_SIDE; + float top = room.topLeftPos.y; + float bottom = room.bottomRightPos.y + LEASH_WALL_BOTTOM; + float nearest = LEASH_FAR; + if (std::abs(left - npc.pos.x) < nearest) + { + npc.targetPosition = vector_make(left, npc.pos.y); + nearest = std::abs(left - npc.pos.x); + } + if (std::abs(right - npc.pos.x) < nearest) + { + npc.targetPosition = vector_make(right, npc.pos.y); + nearest = std::abs(right - npc.pos.x); + } + // The original measures the top and bottom walls 20 nearer once chosen. + if (std::abs(top - npc.pos.y) < nearest) + { + npc.targetPosition = vector_make(npc.pos.x, top); + nearest = std::abs(top - LEASH_WALL_SIDE - npc.pos.y); + } + if (std::abs(bottom - npc.pos.y) < nearest) + { + npc.targetPosition = vector_make(npc.pos.x, bottom); + nearest = std::abs(bottom - LEASH_WALL_SIDE - npc.pos.y); + } + if (nearest <= LEASH_BLOCK_REACH) return; + + for (const auto& step : LEASH_NEIGHBOURS) + { + int column = (int)((npc.pos.x + step[0] - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((npc.pos.y + step[1] - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) continue; + uint32_t cell = (uint32_t)(room.gridWidth * row + column); + GridEntity* block = cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + if (!block || block->type != GRID_ROCKB) continue; + + npc.targetPosition = vector_make((float)(block->gridIndex % room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X, + (float)(block->gridIndex / room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y); + npc.i1 = block->gridIndex; + return; + } +} + +// Its cord: eight segments from it to the stake (seven to a block, raised), each knowing its share along the cord. +static void cord_spawn(Entity_NPC& npc) +{ + for (int i = 0; i < UMBILICAL_SEGMENTS; i++) + { + if (npc.i1 >= 0 && i == 0) continue; + + auto* segment = static_cast( + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = npc.type, .variant = HOMUNCULUS_CORD, .seed = Random()})); + segment->parent = &npc; + segment->targetPosition = npc.targetPosition; + segment->ClearEntityFlags(FLAG_APPEAR); + segment->v1.y = (float)i / CORD_SEGMENT_LAST; + if (npc.i1 >= 0) segment->sprite.offset = vector_make(0, (CORD_SEGMENT_LAST - (float)i) * CORD_STAKE_LIFT); + segment->Update(); + } +} + +// Its start: the body wakes leashed (its cord staked and spawned, pulled back within reach), the cord lies flat +// behind everything. +static void homunculus_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_IDLE; + if (npc.variant == 0) + { + npc.stateFrame = 0; + if (npc.sprite.SetOverlayAnimation("Awaken", SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + if (is_cage_begotten(npc)) npc.i2 = 1; + else + { + npc.i2 = 0; + leash_stake(npc); + Vector toStake = vector_sub(npc.targetPosition, npc.pos); + float distance = vector_length(toStake); + if (distance > LEASH_LENGTH) + npc.velocity = vector_add(npc.velocity, vector_scale(toStake, (LEASH_LENGTH / distance - 1) * LEASH_PULL_BACK * npc.speedMultiplier)); + cord_spawn(npc); + } + } + else if (npc.variant == HOMUNCULUS_CORD) + { + npc.sprite.Play("UmbilicalCord"); + npc.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + npc.renderZOffset = CORD_DEPTH; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + } + if (npc.type == ENTITY_BEGOTTEN) npc.splatColor = BEGOTTEN_SPLAT_COLOR; +} + +// A cord segment hangs on its share of the way from the stake to the body, sagging in the middle. Once the body is gone +// or free it goes (the Homunculus' leaving a puddle). +static void cord_update(Entity_NPC& npc) +{ + auto* body = static_cast(npc.parent.get()); + if (body && body->state != HOMUNCULUS_FREE) + { + float share = npc.v1.y; + float bend = std::abs(share - 0.5f) * 2; + npc.pos.x = (body->pos.x - npc.sprite.offset.x - npc.targetPosition.x) * share + npc.targetPosition.x; + npc.pos.y = (1 - bend * bend) * UMBILICAL_SAG + (body->pos.y - npc.sprite.offset.y - npc.targetPosition.y) * share + + npc.targetPosition.y + CORD_DROP; + npc.friction = 0; + return; + } + + if (npc.type == ENTITY_HOMUNCULUS) + { + uint32_t seed = Random(); + Vector direction = random_direction(); + float reach = random_unit() * CORD_CREEP_SPREAD; + Entity* creep = g_game->Spawn({.position = vector_add(npc.pos, vector_scale(direction, reach)), + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_RED, + .seed = seed}); + float size = random_unit() + CORD_CREEP_SIZE_MIN; + creep->sprite.scale = vector_make(size, size); + } + npc.Remove(); +} + +// Whether the block its cord is staked on still holds. In a crawlspace at home nothing holds. +static bool is_stake_holding(Entity_NPC& npc) +{ + Room& room = *g_game->room; + RoomConfig_Room* data = room.descriptor->data; + if (data && data->type == ROOM_DUNGEON && data->stageId == ROOM_STAGE_HOME) return false; + if (GridEntity* block = room.gridEntities[npc.i1]) return block->type > GRID_DECORATION; + + int path = room.gridPaths[npc.i1]; + if (path < GRID_PATH_OPEN_AGAIN) return path >= GRID_PATH_BLOCKED_MIN; + return path >= GRID_PATH_BLOCKED_AGAIN; +} + +// Leashed: it chases its target, held within 100 of the stake, until it struggles free (now and then once it pulled +// for a while, at once with a controller's action) or its stake breaks. Free, it bursts a ring of shots at the stake +// (the Begotten also darkening the room). +static void homunculus_leashed(Entity_NPC& npc) +{ + overlay_loop(npc.sprite, "Head"); + if (is_cage_begotten(npc)) + { + npc.state = HOMUNCULUS_FREE; + return; + } + + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), HOMUNCULUS_PATH_SPEED, 0, DIRECT_PATH_FAR); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= HOMUNCULUS_EVADE_FRICTION; + } + + bool isTaut = vector_length_squared(vector_sub(vector_add(npc.pos, npc.velocity), npc.targetPosition)) > LEASH_LENGTH * LEASH_LENGTH; + if (isTaut) + { + Vector held = vector_add(npc.targetPosition, vector_scale(vector_normalized(vector_sub(npc.pos, npc.targetPosition)), LEASH_LENGTH)); + if (npc.controllerID == -1) + { + npc.friction *= LEASH_SNAP_FRICTION; + npc.pos = held; + } + else + { + npc.friction *= LEASH_CONTROLLED_FRICTION; + npc.velocity = vector_add(npc.velocity, vector_scale(vector_sub(held, npc.pos), LEASH_CONTROLLED_PULL * npc.speedMultiplier)); + } + } + if (npc.IsControllerActionTriggered(ACTION_ITEM) && isTaut && (Random() & STRUGGLE_CONTROLLED_ODDS_MASK) == 0) + npc.i2 = 1; + + int pulled = npc.stateFrame; + npc.stateFrame += npc_ticks_get(npc); + bool isRolled = isTaut && g_game->room->bossId != BOSS_ID_NO_STRUGGLE && + pulled > (int)(Random() % STRUGGLE_FRAME_RANGE) + STRUGGLE_MIN_FRAMES && + npc.IsFrame(STRUGGLE_CHECK_FRAMES, (int)npc.index) && Random() % STRUGGLE_ODDS == 0; + bool isStruggle = isTaut && (isRolled || npc.i2 >= 1); + if (!isStruggle && (npc.i1 < 0 || is_stake_holding(npc))) return; + + npc.state = HOMUNCULUS_FREE; + if (npc.i1 < 0) + npc.targetPosition = g_game->room->GetClampedPositionImpl(npc.targetPosition, BREAK_CLAMP_TOP, 0, BREAK_CLAMP_BOTTOM, 0); + else npc.targetPosition = vector_add(npc.targetPosition, vector_resized(vector_sub(npc.pos, npc.targetPosition), BREAK_STAKE_REACH)); + npc.FireProjectiles(npc.targetPosition, vector_make(BREAK_SHOT_SPEED, BREAK_SHOTS), PROJECTILES_RING, ProjectileParams()); + if (npc.type != ENTITY_BEGOTTEN) return; + + g_game->darknessStrength = 1; + g_game->darknessTimeout = BEGOTTEN_DARKNESS_FRAMES; +} + +// Free: it chases its target faster, the Begotten fading out as it goes. +static void homunculus_free(Entity_NPC& npc) +{ + if (npc.type == ENTITY_BEGOTTEN) + { + npc.sprite.color._tint[3] -= BEGOTTEN_FADE; + npc.isVisible = npc.sprite.color._tint[3] > 0; + } + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + { + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), HOMUNCULUS_FREE_SPEED, HOMUNCULUS_FREE_PATH_MARKER, DIRECT_PATH_FAR); + return; + } + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= HOMUNCULUS_FREE_EVADE_FRICTION; +} + +// 00539b90 The Homunculus (228) and the Begotten (251), and their cords (variant 10). +void npc_homunculus_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + return homunculus_init(npc); + case NPC_STATE_IDLE: + if (npc.variant == HOMUNCULUS_CORD) cord_update(npc); + else if (npc.variant == 0) + { + if (npc.stateFrame == 0) + { + overlay_restart(npc.sprite, "Awaken"); + npc.stateFrame++; + } + if (!npc.sprite.overlayAnimState.animData || !npc.sprite.overlayAnimState.isPlaying) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + } + } + break; + case NPC_STATE_MOVE: + homunculus_leashed(npc); + break; + case HOMUNCULUS_FREE: + homunculus_free(npc); + break; + } + + if (npc.HasEntityFlags(FLAG_CONFUSION)) npc.friction *= HOMUNCULUS_FRICTION; + if (npc.variant != 0) return; + npc.friction *= HOMUNCULUS_FRICTION; + npc.AnimWalkFrame("WalkHori", "WalkVert", HOMUNCULUS_WALK_THRESHOLD); +} diff --git a/src/npc_hopper.cpp b/src/npc_hopper.cpp index 50fbe88..f4110d1 100644 --- a/src/npc_hopper.cpp +++ b/src/npc_hopper.cpp @@ -1,17 +1,25 @@ #include "npc_basement.h" #include "boss_ai.h" +#include "npc_caves.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. -constexpr int ENTITY_RAGLING = 246; constexpr int ENTITY_MINISTRO = 305; -constexpr int ENTITY_PON = 840; constexpr int HOPPER_EGGY = 2; constexpr int HOPPER_TAINTED = 3; -constexpr int RAGLING_RAG_MAN = 1; +constexpr uint32_t EGGY_SHORT_HOP_ODDS = 3; +constexpr int TAINTED_SHORT_HOPS = 3; +constexpr int SHORT_HOP_REST = 9999; +constexpr float STICKY_HOP_CREEP_SCALE = 1.5f; +constexpr float PON_CREEP_SCALE = 1.25f; +constexpr float EGGY_CREEP_SCALE = 0.8f; +constexpr int EGGY_CREEP_TIMEOUT = 150; +constexpr float HOPPER_BLOOD_DEPTH = -10; +constexpr int HOPPER_LANDING_PATH = 900; +constexpr float TAINTED_BURST_FALL_ACCEL = -0.07f; constexpr ColorMod BROWN_SPLAT_COLOR = {{0.4f, 0.2f, 0.2f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod FLAMING_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.14117648f, 0.12156863f, 0.10980392f}}; @@ -67,6 +75,10 @@ constexpr uint64_t RAGLING_SHOT_FLAGS = 1ull << 11 | 1ull << 13; // The Ragling marks its cell for the pathfinder and, once Rag Man is gone, leaves a poof as it dies. constexpr int RAGLING_GRID_PATH = 500; + +// A Ragling falling while Rag Man lives plays dead, slowed, in a splash of its color until he revives it. +constexpr float RAGLING_DEAD_FRICTION = 0.3f; +constexpr float RAGLING_DEAD_SPLASH_HEIGHT = -5; 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), @@ -278,15 +290,92 @@ static void hopper_hop_start(Entity_NPC& npc, const HopperJump& jump, const Hopp npc.stateFrame = 0; } -// The landing of a hop: a thud, and the bursts of the kinds that land hard. +// A puddle of creep where a hopper lands, lasting a while if timed. +static void hopper_land_creep(Entity_NPC& npc, int variant, float scale, int timeout) +{ + auto* creep = static_cast( + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = variant, .seed = Random()})); + creep->sprite.scale = vector_make(scale, scale); + if (timeout > 0) + { + creep->timeout = timeout; + creep->lifespan = timeout; + } + creep->Update(); +} + +// The tainted hopper's landing burst, growing with its hops (i1): a plus, then rings of 6, 8 and 12. +static void tainted_hopper_burst(Entity_NPC& npc) +{ + constexpr float BURSTS[][2] = {{8, 0}, {10, 6}, {8, 8}, {10, 12}}; + if (npc.i1 < 0 || npc.i1 > 3) return; + + ProjectileParams params; + params.circleAngle = 0; + params.fallingAccelModifier = TAINTED_BURST_FALL_ACCEL; + Vector burst = vector_make(BURSTS[npc.i1][0], BURSTS[npc.i1][1]); + npc.FireProjectiles(npc.pos, burst, npc.i1 == 0 ? PROJECTILES_PLUS : PROJECTILES_RING, params); +} + +// The landing of a hop: a thud, and what the heavy kinds leave: Pon's blood, the sticky Leaper's black creep, Eggy's +// white creep and the tainted hopper's splat and burst, their spots marked for the pathfinder. static void hopper_land(Entity_NPC& npc) { npc.PlaySound(SOUND_HOPPER_LAND, 1, 2, false, 1); - if (npc.type == ENTITY_PON) reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: Pon's landing"); - if (npc.type == ENTITY_LEAPER && npc.variant == 1) - reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: the sticky Leaper's landing creep"); - if (npc.type == ENTITY_HOPPER && (npc.variant == HOPPER_EGGY || npc.variant == HOPPER_TAINTED)) - reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: Eggy's and the tainted hopper's landings"); + bool isMarked = true; + if (npc.type == ENTITY_PON) + { + hopper_land_creep(npc, EFFECT_CREEP_RED, PON_CREEP_SCALE, 0); + blood_explosion_spawn(2, npc.pos, {}, COLOR_DEFAULT, {})->renderDepthOffset = HOPPER_BLOOD_DEPTH; + } + else if (npc.type == ENTITY_LEAPER && npc.variant == LEAPER_STICKY) + { + hopper_land_creep(npc, EFFECT_CREEP_BLACK, STICKY_HOP_CREEP_SCALE, STICKY_CREEP_TIMEOUT); + blood_explosion_spawn(2, npc.pos, {}, npc.splatColor, {})->renderDepthOffset = HOPPER_BLOOD_DEPTH; + } + else if (npc.type == ENTITY_HOPPER && npc.variant == HOPPER_EGGY) + { + isMarked = !npc.HasEntityFlags(FLAG_SHRINK); + if (isMarked) hopper_land_creep(npc, EFFECT_CREEP_WHITE, EGGY_CREEP_SCALE, EGGY_CREEP_TIMEOUT); + } + else if (npc.type == ENTITY_HOPPER && npc.variant == HOPPER_TAINTED) + { + blood_explosion_spawn(2, npc.pos, {}, COLOR_DEFAULT, {})->renderDepthOffset = HOPPER_BLOOD_DEPTH; + npc.MakeSplat(1); + Room& room = *g_game->room; + room.SetGridPath(room.GetGridIndex(npc.pos), HOPPER_LANDING_PATH); + return tainted_hopper_burst(npc); + } + else isMarked = false; + if (!isMarked) return; + + Room& room = *g_game->room; + room.SetGridPath(room.GetGridIndex(npc.pos), HOPPER_LANDING_PATH); +} + +// Eggy stops short one landing in three, and the tainted hopper after each of its first three hops (counted in i1), +// resting long. +static void hopper_short_hop_land(Entity_NPC& npc, const HopperAnims& anims) +{ + if (!npc.sprite.IsEventTriggered("Land")) return; + + std::string_view idle = anims.idle; + if (npc.variant == HOPPER_EGGY) + { + if (Random() % EGGY_SHORT_HOP_ODDS != 0) return; + } + else if (npc.variant != HOPPER_TAINTED) return; + else if (npc.i1 >= TAINTED_SHORT_HOPS) + { + npc.i1 = 0; + return; + } + else idle = ++npc.i1 % 2 == 0 ? "Idle" : "Idle2"; + + npc.targetPosition = {}; + npc.state = NPC_STATE_IDLE; + npc.stateFrame = SHORT_HOP_REST; + npc.sprite.Play(idle); } // A hop in the air (until its animation loops): it leaves the ground on its Jump event, lands with a thud, and moves @@ -324,6 +413,7 @@ static void hopper_hop_update(Entity_NPC& npc, const HopperAnims& anims) hopper_idle_reset(npc); npc.sprite.Play(anims.idle); } + if (npc.type == ENTITY_HOPPER) hopper_short_hop_land(npc, anims); if (npc.friction != 0) { @@ -419,7 +509,8 @@ static void leaper_big_jump_start(Entity_NPC& npc, const Vector& aim) 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. +// Rag Man's Ragling marks its cell for the pathfinder, plays dead while he lives and regenerates when he revives it, +// and dies in a poof once he is gone. static void ragling_update(Entity_NPC& npc) { Room& room = *g_game->room; @@ -435,9 +526,32 @@ static void ragling_update(Entity_NPC& npc) return; } if (npc.isDead && npc.parent) - reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: a Ragling playing dead for Rag Man"); + { + if (!npc.HasEntityFlags(FLAG_DELIRIUM_FORM)) + { + npc.isDead = false; + npc.health = npc.maxHitPoints; + npc.state = NPC_STATE_SPECIAL; + npc.isInvincible = true; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.friction *= RAGLING_DEAD_FRICTION; + npc.RemoveStatusEffects(); + } + blood_explosion_spawn(3, npc.pos, vector_make(0, RAGLING_DEAD_SPLASH_HEIGHT), npc.splatColor, {}); + } + if (npc.state == NPC_STATE_APPEAR_CUSTOM) - reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: a Ragling regenerating"); + { + npc.sprite.Play("Regen"); + if (!npc_anim_is_done(npc)) return; + + npc.isInvincible = false; + npc.state = NPC_STATE_IDLE; + npc.targetPosition = {}; + npc.entityCollisionClass = ENTCOLL_ALL; + } + else if (npc.state == NPC_STATE_SPECIAL) npc.sprite.Play("Die"); } // 00526470 The hoppers' AI: they rest, then hop to a cell toward their target (or anywhere when it is out of range), diff --git a/src/npc_hush.cpp b/src/npc_hush.cpp new file mode 100644 index 0000000..6ce299f --- /dev/null +++ b/src/npc_hush.cpp @@ -0,0 +1,381 @@ +#include "boss_ai.h" +#include "npc_caves.h" +#include "platform.h" +#include +#include +#include +#include +#include + +// A Hush fly's look, one of three picked at random. +constexpr std::array HUSH_FLY_SHEETS = {"gfx/Monsters/Afterbirth/Monster_010_Fly_Hush_1.png", + "gfx/Monsters/Afterbirth/Monster_010_Fly_Hush_2.png", + "gfx/Monsters/Afterbirth/Monster_010_Fly_Hush_3.png"}; + +// A fly starts at a random place along its group's path with 400 to 599 health over its maximum, shedding 4 a frame +// down to it. Its formation is two shapes of 80 about the room's middle, each picked from six. +constexpr int FLY_PROGRESS_RANGE = 1000; +constexpr int FLY_SHAPE_COUNT = 6; +constexpr int FLY_DEFAULT_REACH = 80; +constexpr uint32_t FLY_EXTRA_HEALTH_RANGE = 200; +constexpr uint32_t FLY_EXTRA_HEALTH = 400; +constexpr float FLY_HEALTH_DECAY = 4; + +// The shapes a formation takes: a five and a six pointed star, then polygons, the circle having 31 sides. +constexpr int SHAPE_FIVE_STAR = 1; +constexpr int SHAPE_SIX_STAR = 2; +constexpr int SHAPE_CIRCLE = 6; +constexpr int FIVE_STAR_POINTS = 10; +constexpr int SIX_STAR_POINTS = 12; +constexpr int CIRCLE_SIDES = 31; +constexpr float FIVE_STAR_INNER = 0.382f; +constexpr float SIX_STAR_INNER = 0.577f; + +// The group's leader moves the formation along its heading (homing turns it a tenth toward the target), and each frame +// moves every fly 10 thousandths further along both paths, 2 away from its nearest neighbour. The paths spin a degree +// a frame and are squashed to 0.7 high, the flies blending between the two as a sine of the leader's time swings. +constexpr int FLY_PATH_STEP = 10; +constexpr int FLY_SPACING_STEP = 2; +constexpr float FLY_PATH_SCALE = 0.001f; +constexpr float FLY_PROGRESS_TO_RADIANS = 0.006283186f; +constexpr float FLY_RADIANS_TO_PROGRESS = 159.15494f; +constexpr float FLY_HOMING_TURN = 0.1f; +constexpr float FLY_SQUASH = 0.7f; +constexpr float FLY_BLEND_RATE = 0.1f; +constexpr float FLY_BLEND_OFFSET = 0.5f; +constexpr float FLY_BLEND_SCALE = 0.7f; +constexpr float FLY_LEAVE_MARGIN = -200; + +// It steers 0.3 of the way to its spot each frame, at 10 at most, under friction 0.8. +constexpr float FLY_STEER = 0.3f; +constexpr float FLY_MAX_SPEED = 10; +constexpr float HUSH_FLY_FRICTION = 0.8f; + +// The fly's i2: its two shapes and their reach, one byte each, and whether the formation homes. +constexpr int SHAPE_SECOND_SHIFT = 8; +constexpr int REACH_SHIFT = 16; +constexpr int HOMING_SHIFT = 24; +constexpr int BYTE_MASK = 0xff; + +// A boil grows and shrinks over the 13 frames of "Shrink", showing the more of its health and its growth. One roll in +// 50 a frame it grows to fire (when its target is within 420, or one roll in 6), else it shakes. Delirium's (variant 2) +// rather shakes while more than a few enemies are about. +constexpr int HUSH_BOIL_SHRINK_FRAMES = 13; +constexpr float HUSH_BOIL_GROWTH_STEP = 1.0f / HUSH_BOIL_SHRINK_FRAMES; +constexpr uint32_t HUSH_BOIL_ACT_ODDS = 50; +constexpr uint32_t HUSH_BOIL_FAR_FIRE_ODDS = 6; +constexpr float HUSH_BOIL_FIRE_REACH = 420; +constexpr int HUSH_BOIL_DELIRIUM = 2; +constexpr int HUSH_BOIL_CROWD_LIMIT = 7; +constexpr float HUSH_BOIL_FRICTION = 0.8f; + +// Its shot: 1.6 big, homing 1.1, aimed at 7.5 within 40 of its target, one or three of them. +constexpr float HUSH_BOIL_SHOT_SCALE = 1.6f; +constexpr float HUSH_BOIL_SHOT_ACCELERATION = 0.01f; +constexpr float HUSH_BOIL_SHOT_FALL_ACCEL = -0.12f; +constexpr float HUSH_BOIL_SHOT_HOMING = 1.1f; +constexpr float HUSH_BOIL_SHOT_SPREAD = 40; +constexpr float HUSH_BOIL_SHOT_SPEED = 7.5f; + +// A point of a formation's closed path: where it is, the path's length up to it and the length of the segment it +// starts. +struct PathPoint +{ + Vector position{}; + float distance = 0; + float segmentLength = 0; +}; + +// A formation's closed path (NpcHelper's path): its points, the first repeated at the end, and its length. +struct FlyPath +{ + std::vector points; + float length = 0; +}; + +// 009bfd40 NpcHelper::hush_fly_shape_build: the closed path of a shape at a reach, none for shape 0. An unknown shape, +// which the original sized from an unset count, is a polygon of that many sides. +static FlyPath fly_path_build(int shape, float reach) +{ + FlyPath path; + if (shape == 0) return path; + + int sides = shape; + if (shape == SHAPE_CIRCLE) sides = CIRCLE_SIDES; + else if (shape == SHAPE_FIVE_STAR) sides = FIVE_STAR_POINTS; + else if (shape == SHAPE_SIX_STAR) sides = SIX_STAR_POINTS; + + path.points.reserve((size_t)sides + 1); + for (int i = 0; i <= sides; i++) + { + float angle = (float)i * (2 * PI_F) / (float)sides; + Vector point = vector_make(std::cos(angle) * reach, std::sin(angle) * reach); + + if (i % 2 == 1 && shape == SHAPE_FIVE_STAR) point = vector_scale(point, FIVE_STAR_INNER); + else if (i % 2 == 1 && shape == SHAPE_SIX_STAR) point = vector_scale(point, SIX_STAR_INNER); + if (!path.points.empty()) + { + PathPoint& last = path.points.back(); + + last.segmentLength = vector_length(vector_sub(point, last.position)); + path.length += last.segmentLength; + } + path.points.push_back({point, path.length, 0}); + } + return path; +} + +// 009bffb0 NpcHelper::path_point_at: the point a share of the way round a path by length, wrapping past 1. A path of +// fewer than two points, which the original read past, gives the origin. +static Vector fly_path_point(const FlyPath& path, float share) +{ + if (path.points.size() < 2) + { + log_printf(LOG_ASSERT, "Path is incomplete"); + return {}; + } + + float travelled = std::fmod(share, 1.0f) * path.length; + size_t segment = 0; + + for (size_t i = 1; i < path.points.size(); i++) + if (travelled < path.points[i].distance) + { + segment = i - 1; + break; + } + + const PathPoint& from = path.points[segment]; + const PathPoint& to = path.points[segment + 1]; + + if (from.segmentLength == 0) log_printf(LOG_ASSERT, "Start and End parameters cannot be the same!"); + float t = (travelled - from.distance) / from.segmentLength; + return vector_make((to.position.x - from.position.x) * t + from.position.x, + (to.position.y - from.position.y) * t + from.position.y); +} + +// 004be670 NpcHelper::query_nearest_other: the fly of a group nearest a spot, other than one. +static Entity_NPC* fly_nearest_other(const std::vector& group, const Entity_NPC& excluded, Vector spot) +{ + Entity_NPC* nearest = nullptr; + float nearestDistance = 0; + + for (Entity_NPC* candidate : group) + { + float distance = vector_length_squared(vector_sub(spot, candidate->pos)); + + if (candidate != &excluded && (distance < nearestDistance || !nearest)) + { + nearest = candidate; + nearestDistance = distance; + } + } + return nearest; +} + +// A path point turned by an angle and squashed to the formation's height. +static Vector fly_path_turn(Vector point, float angle) +{ + float cosine = std::cos(angle); + float sine = std::sin(angle); + + return vector_make(point.x * cosine - point.y * sine, (point.y * cosine + point.x * sine) * FLY_SQUASH); +} + +// The leader's frame for its group: the formation's centre moves on (with the homing turn, or kept on Hush for his +// ring), then every fly of the group moves along both paths, spaced from its nearest, gets its spot and the +// formation's state, and is removed once well out of the room. +static void fly_group_lead(Entity_NPC& npc, Entity_NPC* parent) +{ + std::vector group = Entity_NPC::QueryNPCsGroup(npc.groupIdx); + float reach = (float)(npc.i2 >> REACH_SHIFT & BYTE_MASK); + FlyPath first = fly_path_build(npc.i2 & BYTE_MASK, reach); + FlyPath second = fly_path_build(npc.i2 >> SHAPE_SECOND_SHIFT & BYTE_MASK, reach); + float spin = (float)g_game->frameCount * DEGREES_TO_RADIANS; + float swing = (std::sin(npc.updateTime * FLY_BLEND_RATE) + FLY_BLEND_OFFSET) * FLY_BLEND_SCALE; + float blend = std::clamp(swing, 0.0f, 1.0f); + + npc.v1 = vector_add(npc.v1, vector_scale(npc.v2, npc.speedMultiplier)); + if ((npc.i2 >> HOMING_SHIFT & BYTE_MASK) == 1) + { + float speed = vector_length(npc.v2); + Vector toward = vector_resized(vector_sub(npc.GetPlayerTarget()->pos, npc.v1), speed); + + npc.v2 = vector_resized(vector_add(npc.v2, vector_scale(vector_sub(toward, npc.v2), FLY_HOMING_TURN)), speed); + } + if (npc.groupIdx == HUSH_FLY_RING_GROUP && parent) npc.v1 = parent->pos; + + for (Entity_NPC* fly : group) + { + if (fly->type != ENTITY_HUSH_FLY) continue; + + fly->i1 += FLY_PATH_STEP; + Entity_NPC* nearest = fly_nearest_other(group, *fly, fly->pos); + if (nearest && nearest != fly) + { + float apart = ((float)nearest->i1 - (float)fly->i1) * FLY_PROGRESS_TO_RADIANS; + float wrapped = std::atan2(std::sin(apart), std::cos(apart)) * FLY_RADIANS_TO_PROGRESS; + + if (wrapped < 0) fly->i1 += FLY_SPACING_STEP; + if (wrapped > 0) fly->i1 -= FLY_SPACING_STEP; + } + + float share = (float)fly->i1 * FLY_PATH_SCALE; + Vector from = vector_add(fly_path_turn(fly_path_point(first, share), spin), npc.v1); + Vector to = vector_add(fly_path_turn(fly_path_point(second, share), spin), npc.v1); + + fly->targetPosition = vector_add(from, vector_scale(vector_sub(to, from), blend)); + fly->v1 = npc.v1; + fly->v2 = npc.v2; + fly->i2 = npc.i2; + if (!g_game->room->IsPositionInRoom(fly->pos, FLY_LEAVE_MARGIN)) fly->Remove(); + } +} + +// 004bf310 NpcAI::ENTITY_HUSH_FLY: a fly of one of Hush's formations. The first of its group to update each frame +// leads it, setting every fly's spot. Each steers to its spot and, flung out of Hush, only hits players once clear of +// him. +void npc_hush_fly_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.state = NPC_STATE_IDLE; + npc.sprite.ReplaceSpritesheet(0, HUSH_FLY_SHEETS[Random() % HUSH_FLY_SHEETS.size()]); + npc.sprite.LoadGraphics(); + npc.i1 = (int)(random_unit() * FLY_PROGRESS_RANGE); + npc.groupIdx = g_game->frameCount; + npc.v1 = Room::GetCenterPos(); + + int firstShape = (int)(Random() % FLY_SHAPE_COUNT) + 1; + int secondShape = (int)(Random() % FLY_SHAPE_COUNT) + 1; + + npc.i2 = firstShape | secondShape << SHAPE_SECOND_SHIFT | FLY_DEFAULT_REACH << REACH_SHIFT; + npc.health += (float)(Random() % FLY_EXTRA_HEALTH_RANGE + FLY_EXTRA_HEALTH); + } + if (npc.health > npc.maxHitPoints) npc.health = std::max(npc.health - FLY_HEALTH_DECAY, npc.maxHitPoints); + + auto* parent = dynamic_cast(npc.parent.get()); + if (vector_is_zero(npc.targetPosition)) fly_group_lead(npc, parent); + + Vector steer = vector_sub(vector_add(vector_sub(npc.targetPosition, npc.pos), npc.v2), npc.velocity); + + npc.velocity = vector_add(npc.velocity, vector_scale(steer, FLY_STEER)); + if (vector_length_squared(npc.velocity) > FLY_MAX_SPEED * FLY_MAX_SPEED) + npc.velocity = vector_resized(npc.velocity, FLY_MAX_SPEED); + npc.friction *= HUSH_FLY_FRICTION; + npc.velocity = vector_scale(npc.velocity, npc_friction_scaled(1 / npc.friction, npc.speedMultiplier)); + npc.sprite.Play("Fly"); + npc.targetPosition = {}; + + if (npc.entityCollisionClass != ENTCOLL_PLAYEROBJECTS) return; + float clearance = parent ? npc.size + parent->size : 0; + if (!parent || vector_length_squared(vector_sub(parent->pos, npc.pos)) > clearance * clearance) + npc.entityCollisionClass = ENTCOLL_ALL; +} + +// Shows a boil's size on its "Shrink" frames: the more of its health and a growth. +static void boil_size_show(Entity_NPC& npc, float growth) +{ + float shown = std::max(npc.health / npc.maxHitPoints, growth) * HUSH_BOIL_SHRINK_FRAMES; + + npc.sprite.SetFrame("Shrink", HUSH_BOIL_SHRINK_FRAMES - (int)(uint32_t)shown); +} + +// Whether an explosion hurting a boil is a player's (or a familiar's), or TNT's, which are the ones it takes. +static bool is_boil_hurt(const DamageEvent& event) +{ + return !(event.damageFlags & DAMAGE_EXPLOSION) || event.source.type == ENTITY_PLAYER || + event.source.spawnerType == ENTITY_PLAYER || event.source.spawnerType == ENTITY_FAMILIAR || + (event.damageFlags & DAMAGE_TNT); +} + +// A boil fires its shot near its target. +static void boil_fire(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_BLOODSHOOT, 1, 2, false, 1); + Random(); + + ProjectileParams params; + params.scale = HUSH_BOIL_SHOT_SCALE; + params.acceleration = HUSH_BOIL_SHOT_ACCELERATION; + params.fallingAccelModifier = HUSH_BOIL_SHOT_FALL_ACCEL; + params.homingStrength = HUSH_BOIL_SHOT_HOMING; + + Vector target = npc.GetPlayerTarget()->pos; + Vector direction = random_direction(); + float reach = random_unit() * HUSH_BOIL_SHOT_SPREAD; + Vector aim = vector_make(direction.x * reach + target.x - npc.pos.x, direction.y * reach + target.y - npc.pos.y); + ProjectilesMode mode = (Random() & 1) ? PROJECTILES_THREE : PROJECTILES_SINGLE; + + npc.FireProjectiles(npc.pos, vector_resized(aim, HUSH_BOIL_SHOT_SPEED), mode, params); +} + +// 004be6f0 NpcAI::ENTITY_HUSH_BOIL: a boil Hush leaves, held where it landed. It only takes the explosions of players, +// familiars and TNT. It grows to fire a homing shot at its target, or shakes, then shrinks back as its health shows. +void npc_hush_boil_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.v1.x = 0; + npc.targetPosition = npc.pos; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.state = NPC_STATE_IDLE; + return boil_size_show(npc, 0); + } + + npc.friction *= HUSH_BOIL_FRICTION; + if (npc.pendingDamage > 0) + { + float taken = 0; + + for (DamageEvent& event : npc.damageEvents) + { + if (is_boil_hurt(event)) taken += event.damage; + else event.damage = 0; + } + if (taken > 0) npc.v1.x = 0; + } + + float distance = vector_length(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + bool isCalm = !npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK); + + if (npc.state == NPC_STATE_IDLE && isCalm) + { + npc.v1.y = std::max(npc.v1.y - HUSH_BOIL_GROWTH_STEP, 0.0f); + if (Random() % HUSH_BOIL_ACT_ODDS == 0) + { + bool isFiring = distance < HUSH_BOIL_FIRE_REACH || Random() % HUSH_BOIL_FAR_FIRE_ODDS == 0; + + if (isFiring && npc.variant == HUSH_BOIL_DELIRIUM) + { + int crowd = g_game->room->GetAliveEnemiesCount(); + + isFiring = crowd <= HUSH_BOIL_CROWD_LIMIT && random_below(crowd) == 0; + } + npc.state = isFiring ? NPC_STATE_ATTACK : NPC_STATE_ATTACK2; + } + boil_size_show(npc, npc.v1.y); + } + else if (npc.state == NPC_STATE_ATTACK) + { + npc.v1.y += HUSH_BOIL_GROWTH_STEP; + if (npc.v1.y < 1) + { + npc.v1.y = std::min(npc.v1.y + HUSH_BOIL_GROWTH_STEP, 1.0f); + boil_size_show(npc, npc.v1.y); + } + else + { + npc.sprite.Play("Shoot"); + if (npc.sprite.IsEventTriggered("Shoot")) boil_fire(npc); + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_IDLE; + } + } + else + { + npc.sprite.Play("Shake"); + if (npc_anim_is_done(npc)) npc.state = NPC_STATE_IDLE; + } + npc.velocity = vector_sub(npc.targetPosition, npc.pos); +} diff --git a/src/npc_knight.cpp b/src/npc_knight.cpp new file mode 100644 index 0000000..e7ed514 --- /dev/null +++ b/src/npc_knight.cpp @@ -0,0 +1,447 @@ +#include "boss_ai.h" +#include "active_items.h" +#include "entity_player.h" +#include "menu_manager.h" +#include "npc_basement.h" +#include "npc_caves.h" +#include "room_grid.h" + +// The knights this AI runs: the Knight (41) with the Selfless, Loose, Empty and Black Knight as its variants, the +// Floating Knight (254) and the Bone Knight (283). The Loose Knight's Pon (840) carries the Empty Knight. +constexpr int KNIGHT_SELFLESS = 1; +constexpr int KNIGHT_LOOSE = 2; +constexpr int KNIGHT_EMPTY = 3; +constexpr int KNIGHT_CHARGE = NPC_STATE_ATTACK; +constexpr int KNIGHT_SLAM = NPC_STATE_STOMP; + +constexpr uint32_t KNIGHT_GROWL_ODDS = 100; +constexpr int KNIGHT_GROWL_DELAY = 60; + +constexpr float KNIGHT_WALK_SPEED = 0.75f; +constexpr float SELFLESS_WALK_SPEED = 1.25f; +constexpr float LOOSE_WALK_SPEED = 0.6f; +constexpr float BLACK_WALK_SPEED = 0.66f; +constexpr float KNIGHT_FRICTION = 0.8f; +constexpr float EMPTY_FRICTION = 0.88f; +constexpr float BLACK_LANDING_FRICTION = 0.88f; +constexpr int KNIGHT_GRID_MARK = 900; +constexpr int KNIGHT_GRID_MARK_STEP = 1000; + +constexpr float FLOATING_PUSH = 0.75f; +constexpr int FLOATING_TURN_MIN = 30; +constexpr uint32_t FLOATING_TURN_RANGE = 15; +constexpr uint32_t FLOATING_DIRECTIONS_MASK = 3; + +constexpr int KNIGHT_LOOK_FRAMES = 3; +constexpr float KNIGHT_LEAD_FRAMES = 16; +constexpr float KNIGHT_LOOK_MARGIN = 20; +constexpr float KNIGHT_LINE_SLACK = 20; +constexpr float KNIGHT_SIGHT = 200; +constexpr float KNIGHT_CHARGE_SPEED = 1.35f; +constexpr float SELFLESS_CHARGE_SPEED = 1.65f; +constexpr float BLACK_CHARGE_SPEED = 0.7f; +constexpr float BLACK_CHARGE_GAIN = 0.07f; +constexpr float BLACK_CHARGE_FULL = 4; +constexpr float KNIGHT_RAIL_PULL = 0.1f; +constexpr float KNIGHT_STOP_DRAG = 0.01f; +constexpr float BONE_KNIGHT_REACH = 40; + +constexpr float BLACK_JUMP_GRAVITY = 1.1f; +constexpr int BLACK_JUMP_ODDS_FRAMES = 20; +constexpr uint32_t BLACK_JUMP_ODDS = 10; +constexpr int BLACK_CHASE_MIN = 90; +constexpr uint32_t BLACK_CHASE_ODDS = 20; +constexpr float BLACK_CHASE_SPEED = 0.66f; +constexpr float BLACK_SLAM_SPEED = 8; +constexpr float BLACK_SLAM_SQUARENESS = 0.9f; +constexpr int BLACK_SLAM_SHAKE = 4; +constexpr float BLACK_SLAM_STOMP_VOLUME = 0.6f; +constexpr float BLACK_SLAM_BURST_VOLUME = 0.7f; +constexpr int BLACK_SLAM_BURST_DELAY = 45; +constexpr float BLACK_SLAM_BOUNCE = 5; +constexpr float BLACK_SLAM_HOP = -5; +constexpr int BLACK_SLAM_DAZE = -45; +constexpr ColorMod BLACK_SLAM_POOF_COLOR = {{1, 1, 1, 1}, {2, 0.5f, 0, 1}, {0, 0, 0}}; +constexpr ColorMod BLACK_SLAM_CRACK_COLOR = {{2, 2, 2, 1}, {0, 0, 0, 0}, {0, -1, -1}}; +constexpr float BLACK_GLOW_SPEED = 8; +constexpr float BLACK_GLOW_SCALE = 0.125f; +constexpr float BLACK_GLOW_MIN = 0.05f; +constexpr int BLACK_GLOW_FRAMES = 3; +constexpr int BLACK_TURN_COOLDOWN = 15; +constexpr float KNIGHT_STILL_SQUARED = 0.01f; + +constexpr int BONE_CREEP_FRAMES = 7; +constexpr float BONE_CREEP_SCALE = 0.5f; +constexpr int BONE_CREEP_TIMEOUT = 20; +constexpr float PON_DROP = 10; + +static bool is_black_knight(const Entity_NPC& npc) +{ + return npc.type == ENTITY_KNIGHT && npc.variant == KNIGHT_BLACK; +} + +// Whether the Black Knight is in the air or dazed, which stops its charges and its walk animation. +static bool is_black_knight_down(const Entity_NPC& npc) +{ + return npc.v2.x < 0 || npc.posOffset.y < 0 || npc.projectileDelay < 0; +} + +// The Black Knight shrugs off its own shockwaves and falls back down from its hops. +static void black_knight_prelude(Entity_NPC& npc) +{ + for (DamageEvent& event : npc.damageEvents) + { + bool isOwnWave = event.source.type == ENTITY_EFFECT && event.source.variant == EFFECT_FIRE_JET && + event.source.spawnerType != ENTITY_PLAYER; + if (isOwnWave) event.damage = 0; + } + if (npc.posOffset.y >= 0 && npc.v2.x >= 0) return; + + npc.posOffset.y += npc.v2.x; + npc.v2.x += BLACK_JUMP_GRAVITY; + if (npc.posOffset.y <= 0) return; + npc.posOffset.y = 0; + npc.v2.x = 0; +} + +// The Empty Knight is invulnerable and takes the nearest free Pon to carry it. +static void empty_knight_init(Entity_NPC& npc) +{ + Entity* nearest = nullptr; + float nearestDistance = 0; + for (Entity* pon : entity_query(ENTITY_PON, -1)) + { + if (pon->parent) continue; + + float distance = vector_length_squared(vector_sub(npc.pos, pon->pos)); + if (nearest && distance >= nearestDistance) continue; + nearest = pon; + nearestDistance = distance; + } + if (nearest) + { + npc.child = nearest; + nearest->parent = &npc; + } + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_HIDE_HP_BAR); + npc.isInvincible = true; +} + +// The Floating Knight drifts along an axis, turning every second or so (controlled, along its input), and turns back +// off the walls. +static void floating_knight_drift(Entity_NPC& npc, int ticks) +{ + float push = 1; + npc.stateFrame -= ticks; + if (npc.controllerID == -1) + { + if (ticks != 0 && npc.stateFrame < 1) + { + npc.stateFrame = (int)(Random() % FLOATING_TURN_RANGE) + FLOATING_TURN_MIN; + npc.i1 = (int)(Random() & FLOATING_DIRECTIONS_MASK); + } + } + else + { + Vector input = npc.GetControllerInput(0); + npc.stateFrame = (int)(Random() % FLOATING_TURN_RANGE) + FLOATING_TURN_MIN; + if (std::abs(input.x) <= std::abs(input.y)) npc.i1 = input.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP; + else npc.i1 = input.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + push = vector_length(input); + } + if (npc.i1 < DIRECTION_LEFT || npc.i1 > DIRECTION_DOWN) return; + + Vector step = vector_from_direction(npc.i1); + npc.velocity = vector_add(npc.velocity, vector_scale(step, push * FLOATING_PUSH * npc.speedMultiplier)); + if (!npc.isCollidesWithGrid) return; + + npc.i1 = (npc.i1 + 2) % 4; + npc.pos = vector_sub(npc.pos, npc.velocity); +} + +// The Black Knight walks, then chases its target along the grid's axes, now and then (or when hindered) giving up. +static void black_knight_walk(Entity_NPC& npc, float walkSpeed) +{ + npc.pathfinder.MoveRandomlyAxisAligned(walkSpeed, STATUS_OBEYED); + if (npc.state == KNIGHT_SLAM) + { + if (npc.GetIntervalTicks(BLACK_JUMP_ODDS_FRAMES, 0) != 0 && Random() % BLACK_JUMP_ODDS == 0) + { + npc.projectileDelay = 0; + npc.state = KNIGHT_SLAM; + } + return; + } + + npc.projectileDelay++; + bool isHindered = npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK); + if (isHindered || (npc.projectileDelay > BLACK_CHASE_MIN && Random() % BLACK_CHASE_ODDS == 0)) npc.state = NPC_STATE_MOVE; + npc.pathfinder.FindGridPath(npc.GetPlayerTarget()->pos, BLACK_CHASE_SPEED, 0, DIRECT_PATH_FAR); + npc.velocity = vector_scale(vector_cardinal(npc.velocity), vector_length(npc.velocity)); +} + +// A charge's direction once its target lines up within 200 in sight (any distance for the Floating Knight): along +// the axis it leans on, away when feared. +static void knight_charge_look(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Entity* target = npc.GetPlayerTarget(); + Vector targetVelocity = npc.GetPlayerTarget()->velocity; + Vector lead = vector_add(target->pos, vector_scale(targetVelocity, random_unit() * KNIGHT_LEAD_FRAMES)); + Vector aim = room.GetClampedPositionImpl(lead, KNIGHT_LOOK_MARGIN, KNIGHT_LOOK_MARGIN, KNIGHT_LOOK_MARGIN, KNIGHT_LOOK_MARGIN); + Vector cell = room.GetGridPosition(npc.pathfinder.gridIndex); + Vector gap = vector_sub(cell, aim); + bool isLined = (std::abs(gap.x) < KNIGHT_LINE_SLACK || std::abs(gap.y) < KNIGHT_LINE_SLACK) && vector_length(gap) < KNIGHT_SIGHT; + if (!isLined || (!room_check_line(cell, aim, 0, 0) && npc.type != ENTITY_FLOATING_KNIGHT)) return; + + if (std::abs(gap.x) <= std::abs(gap.y)) npc.targetPosition = vector_make(0, gap.y >= 0 ? -1.0f : 1.0f); + else npc.targetPosition = vector_make(gap.x >= 0 ? -1.0f : 1.0f, 0); + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) npc.targetPosition = vector_scale(npc.targetPosition, -1); + npc.state = KNIGHT_CHARGE; + npc.projectileDelay = 0; + if (is_black_knight(npc)) npc.targetPosition = vector_scale(npc.targetPosition, BLACK_CHARGE_SPEED); +} + +// Walking: the Floating Knight drifts, the others wander along the grid (the Black Knight chasing), growling now and +// then, until a charge lines up (a controller's action, along its input). +static void knight_walk(Entity_NPC& npc, float walkSpeed, float friction, int ticks) +{ + bool isBlack = is_black_knight(npc); + float kept = 1; + if (npc.type == ENTITY_FLOATING_KNIGHT) + { + floating_knight_drift(npc, ticks); + kept = friction; + } + else if (!isBlack) + { + npc.pathfinder.MoveRandomlyAxisAligned(walkSpeed, STATUS_OBEYED); + kept = friction; + } + else if (npc.v2.x >= 0 && npc.posOffset.y >= 0) + { + if (npc.projectileDelay >= 0) + { + black_knight_walk(npc, walkSpeed); + kept = friction; + } + else + { + kept = BLACK_LANDING_FRICTION; + npc.projectileDelay++; + } + } + npc.friction *= kept; + + bool isGrowling = (npc.type == ENTITY_KNIGHT || npc.type == ENTITY_FLOATING_KNIGHT) && Random() % KNIGHT_GROWL_ODDS == 0; + if (isGrowling && npc.type == ENTITY_FLOATING_KNIGHT) npc_sound_play(SOUND_FLOATING_KNIGHT_GROWL, 1, KNIGHT_GROWL_DELAY, 1); + else if (isGrowling && (npc.variant == 0 || npc.variant == KNIGHT_BLACK)) + npc_sound_play(SOUND_KNIGHT_GROWL, 1, KNIGHT_GROWL_DELAY, 1); + else if (isGrowling && (npc.variant == KNIGHT_SELFLESS || npc.variant == KNIGHT_LOOSE)) + npc_sound_play(SOUND_SELFLESS_KNIGHT_GROWL, 1, KNIGHT_GROWL_DELAY, 1); + if (isBlack && is_black_knight_down(npc)) return; + + bool isFast = npc.variant == KNIGHT_SELFLESS || npc.type == ENTITY_BONE_KNIGHT; + if (npc.controllerID != -1) + { + Vector input = npc.GetControllerInput(0.1f); + if (input_is_action_pressed(ACTION_ITEM, npc.controllerID, &npc) && !vector_is_zero(input)) + { + npc.targetPosition = vector_cardinal(input); + npc.state = KNIGHT_CHARGE; + } + if (isFast && npc.state == KNIGHT_CHARGE) npc.targetPosition = vector_scale(npc.targetPosition, SELFLESS_CHARGE_SPEED); + npc.targetPosition = vector_scale(npc.targetPosition, KNIGHT_CHARGE_SPEED); + return; + } + if (!npc.IsFrame(KNIGHT_LOOK_FRAMES, (int)npc.index) || npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return; + + knight_charge_look(npc); + if (isFast && npc.state == KNIGHT_CHARGE) npc.targetPosition = vector_scale(npc.targetPosition, SELFLESS_CHARGE_SPEED); +} + +// Stops a charge. +static void knight_charge_stop(Entity_NPC& npc) +{ + npc.pathfinder.movementTarget = {}; + npc.pathfinder.moveDirection = {}; + npc.state = NPC_STATE_MOVE; + npc.targetPosition = {}; + if (npc.isCollidesWithGrid) npc.velocity = vector_scale(npc.velocity, KNIGHT_STOP_DRAG); +} + +// The Black Knight slamming a wall head on at speed: the room shakes, it bounces back dazed, and cracks and a +// shockwave burst from the spot. +static void black_knight_slam(Entity_NPC& npc) +{ + if (!npc.isCollidesWithGrid || vector_length(npc.gridCollisionVelocity) <= BLACK_SLAM_SPEED) return; + if (vector_dot(npc.gridCollisionNormal, vector_normalized(npc.gridCollisionVelocity)) <= BLACK_SLAM_SQUARENESS) return; + + game_shake_screen(BLACK_SLAM_SHAKE); + npc_sound_play(SOUND_FORESTBOSS_STOMPS, BLACK_SLAM_STOMP_VOLUME, 2, 1); + npc_sound_play(SOUND_FLAME_BURST, BLACK_SLAM_BURST_VOLUME, BLACK_SLAM_BURST_DELAY, 1); + Room& room = *g_game->room; + Vector cell = room.GetGridPosition(room.GetGridIndex(npc.pos)); + blood_explosion_spawn(2, npc.pos, {}, COLOR_DEFAULT, {}); + Entity* poof = g_game->Spawn({.position = cell, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + poof->SetColor(BLACK_SLAM_POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->Update(); + for (int side = -1; side < 2; side++) + { + auto* crack = static_cast(g_game->Spawn( + {.position = cell, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_FIRE_WAVE, .seed = Random()})); + crack->SetColor(BLACK_SLAM_CRACK_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + crack->parent = &npc; + crack->rotation = vector_angle(npc.targetPosition) + HALF_TURN_DEGREES + (float)side * RIGHT_ANGLE_DEGREES; + } + + npc.v2.x = BLACK_SLAM_HOP; + float into = vector_dot(npc.gridCollisionNormal, npc.gridCollisionVelocity); + npc.velocity = vector_sub(npc.velocity, vector_scale(npc.gridCollisionNormal, into * BLACK_SLAM_BOUNCE)); + npc.projectileDelay = BLACK_SLAM_DAZE; + knight_charge_stop(npc); +} + +// Charging: straight on along its rail until it hits a wall or is hindered. The Bone Knight stops once past its +// target (controlled, once its action is let go). The Black Knight speeds up, glows, and slams walls. +static void knight_charge(Entity_NPC& npc, float friction) +{ + bool isBlack = is_black_knight(npc); + if (isBlack) + { + black_knight_slam(npc); + float glow = (vector_length(npc.velocity) - BLACK_GLOW_SPEED) * BLACK_GLOW_SCALE; + if (glow > 0 && npc.IsFrame(BLACK_GLOW_FRAMES, 0)) + npc.SetColor({{1, 1, 1, 1}, {3, 0.3f, 0, glow + BLACK_GLOW_MIN}, {0, 0, 0}}, BLACK_GLOW_FRAMES, 1, true, true); + } + if (npc.state == NPC_STATE_MOVE) return; + if (npc.isCollidesWithGrid || npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return knight_charge_stop(npc); + + if (npc.type == ENTITY_BONE_KNIGHT) + { + bool isOver = !npc.IsControllerActionPressed(ACTION_ITEM); + if (npc.controllerID == -1) + { + Vector behind = vector_sub(npc.pos, vector_resized(npc.targetPosition, BONE_KNIGHT_REACH)); + isOver = vector_dot(vector_sub(npc.GetPlayerTarget()->pos, behind), npc.velocity) < 0; + } + if (isOver) return knight_charge_stop(npc); + } + npc.friction *= friction; + npc.AddVelocity_divided(npc.targetPosition, false); + if (isBlack && vector_length(npc.targetPosition) < BLACK_CHARGE_FULL) + npc.targetPosition = vector_add(npc.targetPosition, vector_scale(vector_normalized(npc.targetPosition), BLACK_CHARGE_GAIN * npc.speedMultiplier)); + + Vector rail = g_game->room->GetGridPosition(npc.pathfinder.gridIndex); + if (std::abs(npc.velocity.x) <= std::abs(npc.velocity.y)) npc.pos.x = rail.x * KNIGHT_RAIL_PULL + npc.pos.x * (1 - KNIGHT_RAIL_PULL); + else npc.pos.y = rail.y * KNIGHT_RAIL_PULL + npc.pos.y * (1 - KNIGHT_RAIL_PULL); +} + +// It faces the way it moves (charging, the way it charges), walking that way. The Black Knight pauses a moment after +// turning, and stands still while down. +static void knight_animate(Entity_NPC& npc) +{ + Vector heading = npc.state == KNIGHT_CHARGE ? npc.targetPosition : npc.velocity; + std::string_view anim = "Hori"; + int direction = heading.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + if (std::abs(heading.x) <= std::abs(heading.y)) + { + anim = heading.y >= 0 ? "Down" : "Up"; + direction = heading.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP; + } + npc.forwardVector = vector_from_direction(direction); + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + + bool isBlack = is_black_knight(npc); + if (isBlack) + { + const AnimationData* data = npc.sprite.animState.animData; + bool isTurned = std::abs(npc.velocity.y) < std::abs(npc.velocity.x) && npc.sprite.isFlipX != (npc.velocity.x < 0); + if (!data || data->name != anim || isTurned) npc.projectileCooldown = BLACK_TURN_COOLDOWN; + } + if (isBlack && is_black_knight_down(npc)) return; + + if (vector_length_squared(npc.velocity) >= KNIGHT_STILL_SQUARED) + { + npc.sprite.Play(anim); + if (std::abs(npc.velocity.x) > std::abs(npc.velocity.y)) npc.sprite.isFlipX = npc.velocity.x < 0; + } + else if (npc.sprite.animState.animData) + { + npc.sprite.animState.isPlaying = false; + npc.sprite.animState.SetFrameFloat(0); + } +} + +// The Loose Knight's death: its Pon leaps out and it carries on as the Empty Knight. +static void loose_knight_split(Entity_NPC& npc) +{ + uint32_t seed = Random(); + Vector spot = vector_add(npc.pos, vector_scale(random_direction(), PON_DROP)); + auto* pon = static_cast(g_game->Spawn({.position = spot, .type = ENTITY_PON, .seed = seed})); + if (npc.isChampion) pon->Morph(pon->type, pon->variant, pon->subtype, npc.championColorIdx); + pon->parent = &npc; + npc.child = pon; + pon->ClearEntityFlags(FLAG_APPEAR); + pon->Update(); + npc.Morph(npc.type, KNIGHT_EMPTY, npc.subtype, 0); + npc.isDead = false; +} + +// 005135d0 The knights: they wander along the grid's axes (the Floating Knight drifts) and charge their target once +// it lines up. The Empty Knight rides its Pon and dies with it, the Bone Knight bleeds as it goes. +void npc_knight_update(Entity_NPC& npc) +{ + bool isBlack = is_black_knight(npc); + if (isBlack) black_knight_prelude(npc); + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + if (npc.type == ENTITY_FLOATING_KNIGHT) npc.entityGridCollisionClass = GRIDCOLL_WALLS; + else if (npc.type == ENTITY_KNIGHT && npc.variant == KNIGHT_EMPTY) empty_knight_init(npc); + return; + } + if (npc.type == ENTITY_KNIGHT && npc.variant == KNIGHT_EMPTY) + { + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_HIDE_HP_BAR); + npc.isInvincible = true; + if (vector_is_zero(npc.targetPosition)) npc.pathfinder.MoveRandomly(STATUS_IGNORED); + if (!npc.child || npc.child->isDead) npc.Kill(EntityRef()); + } + + Room& room = *g_game->room; + int column = (int)((npc.pos.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((npc.pos.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + if (column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight && row * room.gridWidth + column < ROOM_GRID_CELLS) + { + int& mark = room.gridPaths[row * room.gridWidth + column]; + if (mark % KNIGHT_GRID_MARK_STEP < KNIGHT_GRID_MARK) mark = mark - mark % KNIGHT_GRID_MARK_STEP + KNIGHT_GRID_MARK; + } + Vector walker = npc.pathfinder.entity->pos; + int walkerColumn = (int)((walker.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int walkerRow = (int)((walker.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + bool isInside = walkerColumn >= 0 && walkerColumn < room.gridWidth && walkerRow >= 0 && walkerRow < room.gridHeight; + npc.pathfinder.gridIndex = isInside ? room.gridWidth * walkerRow + walkerColumn : -1; + + float walkSpeed = KNIGHT_WALK_SPEED; + float friction = KNIGHT_FRICTION; + if (npc.type == ENTITY_KNIGHT && npc.variant == KNIGHT_SELFLESS) walkSpeed = SELFLESS_WALK_SPEED; + else if (npc.type == ENTITY_KNIGHT && npc.variant == KNIGHT_LOOSE) walkSpeed = LOOSE_WALK_SPEED; + else if (npc.type == ENTITY_KNIGHT && npc.variant == KNIGHT_EMPTY) friction = EMPTY_FRICTION; + else if (isBlack) walkSpeed = BLACK_WALK_SPEED; + + if (npc.state == NPC_STATE_MOVE || npc.state == KNIGHT_SLAM) knight_walk(npc, walkSpeed, friction, npc_ticks_get(npc)); + else knight_charge(npc, friction); + knight_animate(npc); + + if (npc.type == ENTITY_BONE_KNIGHT && npc.IsFrame(BONE_CREEP_FRAMES, (int)npc.index) && !npc.HasEntityFlags(FLAG_SHRINK)) + { + auto* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = Random()})); + creep->sprite.scale = vector_make(BONE_CREEP_SCALE, BONE_CREEP_SCALE); + creep->timeout = BONE_CREEP_TIMEOUT; + creep->lifespan = BONE_CREEP_TIMEOUT; + creep->Update(); + } + if (npc.isDead && npc.type == ENTITY_KNIGHT && npc.variant == KNIGHT_LOOSE) loose_knight_split(npc); +} diff --git a/src/npc_leper.cpp b/src/npc_leper.cpp new file mode 100644 index 0000000..2e19fae --- /dev/null +++ b/src/npc_leper.cpp @@ -0,0 +1,252 @@ +#include "boss_ai.h" +#include "entity_player.h" +#include "menu_manager.h" +#include "npc_caves.h" +#include +#include + +// The Leper (310) sheds its flesh (variant 1) as it is hurt, a stage (subtype) per quarter of its health, slowing +// less and leaking more at each. It runs from its target until it turns to chase it now and then. +constexpr int LEPER_FLESH = 1; +constexpr int LEPER_LAST_STAGE = 3; +constexpr int LEPER_SHEDDING = NPC_STATE_SPECIAL; +constexpr float LEPER_FRICTION = 0.8f; +constexpr float LEPER_CHASE_FRICTION = 0.9f; +constexpr float LEPER_CHASE_SPEEDS[] = {0.5f, 0.5f, 0.7f, 0.9f}; +constexpr int LEPER_WHIMPER_DELAY_MIN = 45; +constexpr uint32_t LEPER_WHIMPER_DELAY_RANGE = 100; +constexpr int LEPER_WHIMPER_GRACE = 10; +constexpr uint32_t LEPER_CHASE_ODDS = 10; +constexpr int LEPER_CHASE_FRAMES = 90; +constexpr int LEPER_REST_MIN = 30; +constexpr uint32_t LEPER_REST_RANGE = 60; +constexpr float LEPER_WALK_THRESHOLD = 0.1f; +constexpr int LEPER_LEAK_FRAMES = 10; +constexpr float LEPER_CREEP_MIN = 0.2f; +constexpr float LEPER_CREEP_RANGE = 0.3f; +constexpr int LEPER_CREEP_TIMEOUT = 30; +constexpr float LEPER_SPLAT_MIN = 0.4f; +constexpr float LEPER_SPLAT_RANGE = 0.4f; +constexpr float LEPER_HURT_CHASE = 2; +constexpr float LEPER_SHED_PUSH = 10; +constexpr float LEPER_SHED_SPREAD = 90; +constexpr float LEPER_SHED_SPEED_MIN = 5; +constexpr float LEPER_SHED_SPEED_RANGE = 5; +constexpr float LEPER_SHED_REACH = 20; +constexpr float LEPER_SHED_BLOOD_SHARE = 0.3f; +constexpr float LEPER_SHED_BLOOD_HEIGHT = -6; +constexpr float LEPER_SHED_BLOOD_DEPTH = 1; +constexpr float LEPER_DEATH_FLESH_SPEED_MIN = 2; +constexpr float LEPER_REVIVE_FLOOR = -25; +constexpr int LEPER_REVIVE_COOLDOWN_MIN = 20; +constexpr uint32_t LEPER_REVIVE_COOLDOWN_RANGE = 20; +constexpr std::string_view LEPER_GUSHER_SHEET = "gfx/Monsters/Classic/Monster_000_Bodies02_scarred.png"; + +// Its flesh wanders toward its target, trailing gore, and spits a shot at it once it dies. +constexpr std::string_view FLESH_IDLES[] = {"Idle1", "Idle2", "Idle3", "Idle4", "Idle5", "Idle6"}; +constexpr uint32_t FLESH_PICK_SHIFT = 9; +constexpr float FLESH_FRICTION = 0.95f; +constexpr float FLESH_WANDER = 2; +constexpr float FLESH_PUSH = 0.15f; +constexpr int FLESH_TRAIL_FRAMES = 6; +constexpr float FLESH_TRAIL_SPREAD = 3; +constexpr float FLESH_TRAIL_SHARE = 0.3f; +constexpr float FLESH_TRAIL_PLAYBACK_MIN = 0.5f; +constexpr float FLESH_TRAIL_PLAYBACK_RANGE = 0.6f; +constexpr float FLESH_TRAIL_SIZE_MIN = 0.6f; +constexpr float FLESH_TRAIL_SIZE_RANGE = 0.6f; +constexpr float FLESH_TRAIL_HEIGHT = -22; +constexpr int FLESH_TRAIL_DEPTH = -400; +constexpr float FLESH_SHOT_LEAD = 0.1f; +constexpr float FLESH_SHOT_SPEED = 10; +constexpr ColorMod FLESH_SHOT_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.3f, 0, 0}}; + +// A splat every 10 frames. +static void leper_splat(Entity_NPC& npc) +{ + npc.MakeSplat(random_unit() * LEPER_SPLAT_RANGE + LEPER_SPLAT_MIN); +} + +// 00548720 (NpcHelper::leper_flesh_ai) A piece of the Leper's flesh: a random look, drifting at its target (controlled, +// along its input, bursting on its action), and a shot at its target when it dies. +static void leper_flesh_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + RNG pick = rng_make(npc.initSeed, FLESH_PICK_SHIFT); + npc_anim_loop(npc.sprite, FLESH_IDLES[pick.Next() % std::size(FLESH_IDLES)]); + npc.state = NPC_STATE_MOVE; + npc.sprite.isFlipX = (pick.Next() & 1) == 0; + npc.isKillOnTouch = true; + } + else if (npc.state == NPC_STATE_MOVE) + { + npc.friction *= FLESH_FRICTION; + Vector toward = vector_normalized(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + if (npc.controllerID != -1) toward = npc.GetControllerInput(0); + Vector wander = random_direction(); + Vector push = vector_add(vector_scale(wander, FLESH_WANDER), toward); + npc.velocity = vector_add(npc.velocity, vector_scale(push, FLESH_PUSH * npc.speedMultiplier)); + } + + if (npc.IsFrame(LEPER_LEAK_FRAMES, 0)) leper_splat(npc); + if (npc.IsFrame(FLESH_TRAIL_FRAMES, 0)) + { + uint32_t seed = Random(); + Vector direction = random_direction(); + float reach = random_unit() * FLESH_TRAIL_SPREAD; + Vector velocity = vector_add(vector_scale(direction, reach), vector_scale(npc.velocity, FLESH_TRAIL_SHARE)); + Entity* trail = g_game->Spawn({.position = npc.pos, .velocity = velocity, .type = ENTITY_EFFECT, .variant = EFFECT_HAEMO_TRAIL, .seed = seed}); + trail->sprite.playbackSpeed = random_unit() * FLESH_TRAIL_PLAYBACK_RANGE + FLESH_TRAIL_PLAYBACK_MIN; + float size = npc.scale * 0.5f * (random_unit() * FLESH_TRAIL_SIZE_RANGE + FLESH_TRAIL_SIZE_MIN); + trail->sprite.scale = vector_make(size, size); + trail->posOffset = vector_make(0, FLESH_TRAIL_HEIGHT); + trail->renderZOffset = FLESH_TRAIL_DEPTH; + } + if (npc.controllerID != -1 && input_is_action_pressed(ACTION_ITEM, npc.controllerID, &npc)) npc.Kill(EntityRef()); + if (!npc.isDead || npc.HasEntityFlags(FLAG_SHRINK)) return; + + Entity* target = npc.GetPlayerTarget(); + float distance = vector_length(vector_sub(npc.pos, target->pos)); + Vector lead = vector_sub(vector_add(target->pos, vector_scale(target->velocity, FLESH_SHOT_LEAD * distance)), npc.pos); + ProjectileParams params; + params.color = FLESH_SHOT_COLOR; + npc.FireProjectiles(npc.pos, vector_scale(vector_normalized(lead), FLESH_SHOT_SPEED), PROJECTILES_SINGLE, params); +} + +// Running from its target (whimpering) until it turns to chase now and then, or, while chasing (always at its last +// stage), toward it at its stage's speed until it rests and runs again. +static void leper_walk(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + if (npc.i1 < 1 && npc.subtype != LEPER_LAST_STAGE && npc.controllerID == -1) + { + npc.pathfinder.EvadeTarget(npc.CalcTargetPosition(0), STATUS_OBEYED); + if (npc.pathfinder.evadeMovementCountdown > 0 && g_game->frameCount - npc.spawnFrame > LEPER_WHIMPER_GRACE) + npc.PlaySound(SOUND_SCARED_WHIMPER, 1, (int)(Random() % LEPER_WHIMPER_DELAY_RANGE) + LEPER_WHIMPER_DELAY_MIN, false, 1); + if (npc.i1 < 0) npc.i1 = std::min(npc.i1 + ticks, 0); + if (npc.i1 == 0 && npc.pathfinder.evadeMovementCountdown < 1 && Random() % LEPER_CHASE_ODDS == 0) + npc.i1 = LEPER_CHASE_FRAMES; + npc.friction *= LEPER_FRICTION; + } + else + { + float speed = LEPER_CHASE_SPEEDS[std::clamp(npc.subtype, 0, LEPER_LAST_STAGE)]; + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), speed, 0, DIRECT_PATH_FAR); + npc.friction *= LEPER_CHASE_FRICTION; + npc.i1 = std::max(npc.i1 - ticks, 0); + if (npc.i1 == 0) npc.i1 = -LEPER_REST_MIN - (int)(Random() % LEPER_REST_RANGE); + } + npc.AnimWalkFrame("WalkHori", "WalkVert", LEPER_WALK_THRESHOLD); + if (npc_anim_is_done(npc)) + { + if (npc.sprite.SetOverlayAnimation("Walk", SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + } + else npc.sprite.PlayOverlay("Walk"); +} + +// Losing a quarter of its health sheds a piece of flesh flung off away from its target (each stage passed at once +// sheds one), pushes it back, and turns it into its next stage. +static void leper_shed(Entity_NPC& npc) +{ + int stage = npc.subtype; + float health = npc.health - npc.pendingDamage; + while (npc.subtype < LEPER_LAST_STAGE) + { + int next = npc.subtype; + if ((float)(LEPER_LAST_STAGE - next) * npc.maxHitPoints / (float)(LEPER_LAST_STAGE + 1 - next) < health) break; + + npc.subtype = next + 1; + npc.BloodExplode(); + Vector away = vector_normalized(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); + npc.velocity = vector_add(npc.velocity, vector_scale(away, LEPER_SHED_PUSH * npc.speedMultiplier)); + uint32_t seed = Random(); + float angle = (random_unit() * LEPER_SHED_SPREAD - LEPER_SHED_SPREAD / 2) * DEGREES_TO_RADIANS; + Vector turned = vector_make(away.x * std::cos(angle) - away.y * std::sin(angle), away.y * std::cos(angle) + away.x * std::sin(angle)); + float speed = random_unit() * LEPER_SHED_SPEED_RANGE + LEPER_SHED_SPEED_MIN; + Entity* flesh = g_game->Spawn({.position = vector_add(npc.pos, vector_scale(away, LEPER_SHED_REACH)), + .velocity = vector_scale(turned, speed), + .spawner = &npc, + .type = ENTITY_LEPER, + .variant = LEPER_FLESH, + .seed = seed}); + flesh->ClearEntityFlags(FLAG_APPEAR); + Entity* blood = g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(flesh->velocity, LEPER_SHED_BLOOD_SHARE), + .subType = 2, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->SetColor(COLOR_DEFAULT, -1, COLOR_PRIORITY_DEFAULT, false, false); + blood->sprite.offset = vector_make(0, LEPER_SHED_BLOOD_HEIGHT); + blood->renderDepthOffset = LEPER_SHED_BLOOD_DEPTH; + } + if (npc.subtype <= stage) return; + + int variant = npc.variant; + npc.variant = -1; + npc.Morph(npc.type, variant, npc.subtype, -1); + npc.state = LEPER_SHEDDING; + npc.sprite.PlayOverlay("Transition"); +} + +// Its death: a last piece of flesh, and one time in two (unless overkilled) it rises again as a scarred Gusher. +static void leper_death(Entity_NPC& npc) +{ + Vector direction = random_direction(); + uint32_t seed = Random(); + float speed = random_unit() * 2 + LEPER_DEATH_FLESH_SPEED_MIN; + Entity* flesh = g_game->Spawn({.position = vector_add(npc.pos, vector_scale(direction, LEPER_SHED_REACH)), + .velocity = vector_scale(direction, speed), + .spawner = &npc, + .type = ENTITY_LEPER, + .variant = LEPER_FLESH, + .seed = seed}); + flesh->ClearEntityFlags(FLAG_APPEAR); + if (npc.health <= LEPER_REVIVE_FLOOR || (Random() & 1) != 0) return; + + npc.Morph(ENTITY_GUSHER, 0, 0, -1); + npc.sprite.ReplaceSpritesheet(0, npc_sheet_path_get(npc, std::string(LEPER_GUSHER_SHEET))); + npc.sprite.LoadGraphics(); + npc.isDead = false; + npc.health = npc.maxHitPoints; + npc.projectileCooldown = (int)(Random() % LEPER_REVIVE_COOLDOWN_RANGE) + LEPER_REVIVE_COOLDOWN_MIN; +} + +// 00547b60 The Leper (310) and its flesh: it flees and chases by turns, leaking more at each stage, sheds flesh as it +// is hurt (hurt cutting its chases short), and may rise again as a Gusher. +void npc_leper_update(Entity_NPC& npc) +{ + if (npc.variant == LEPER_FLESH) return leper_flesh_update(npc); + + if (npc.state == NPC_STATE_INIT) + { + npc.i1 = 0; + npc.state = NPC_STATE_MOVE; + } + else if (npc.state == NPC_STATE_MOVE) leper_walk(npc); + else if (npc.state == LEPER_SHEDDING) + { + npc.friction *= LEPER_FRICTION; + npc.AnimWalkFrame("WalkHori", "WalkVert", LEPER_WALK_THRESHOLD); + if (!npc.sprite.overlayAnimState.animData || !npc.sprite.overlayAnimState.isPlaying) npc.state = NPC_STATE_MOVE; + } + + if (npc.IsFrame(LEPER_LEAK_FRAMES, 0)) + { + if (npc.subtype == LEPER_LAST_STAGE) + { + Entity* creep = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = Random()}); + float size = random_unit() * LEPER_CREEP_RANGE + LEPER_CREEP_MIN; + creep->sprite.scale = vector_make(size, size); + creep->Update(); + static_cast(creep)->timeout = LEPER_CREEP_TIMEOUT; + static_cast(creep)->lifespan = LEPER_CREEP_TIMEOUT; + } + if (npc.subtype != 0) leper_splat(npc); + } + if (npc.i1 > 0 && npc.pendingDamage > 0) npc.i1 = std::max(npc.i1 - (int)std::ceil(npc.pendingDamage * LEPER_HURT_CHASE), 1); + if (npc.subtype < LEPER_LAST_STAGE && npc.pendingDamage > 0) leper_shed(npc); + if (npc.isDead) leper_death(npc); +} diff --git a/src/npc_mole.cpp b/src/npc_mole.cpp new file mode 100644 index 0000000..f999de4 --- /dev/null +++ b/src/npc_mole.cpp @@ -0,0 +1,417 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect_combat.h" +#include "grid_entity.h" +#include "room_descriptor.h" +#include "room_grid.h" +#include "seeds.h" +#include +#include + +// The Mole (variant 0) and Tainted Mole (variant 1) burrow toward their target, leaving a trail of dirt piles (the +// Tainted Mole's crushing what stands on them), dig out near it, shoot (three shots, or up to four big ones), and jump +// back under to a nearby cell, leaving a poop where they went down. In darkness they use their glowing animations. +constexpr int TAINTED_MOLE = 1; +constexpr float DARKNESS_SEEN = 0.8f; +constexpr float MOLE_CHARGE_BAR_FULL = 150; + +// Its states beyond the shared ones: jumping back under, burrowing (the shared move), digging out and shooting. +constexpr int MOLE_JUMP = NPC_STATE_IDLE; +constexpr int MOLE_DIG_OUT = NPC_STATE_JUMP; +constexpr int MOLE_SHOOT = NPC_STATE_ATTACK; + +// Jumping under: it picks the farthest of ten spots within 120 it can reach on a free cell (its target 1 time in 4, +// else one 90 away), or its controller's way, and leaves a poop of 125 or 250 health where it went down. +constexpr int JUMP_TRIES = 10; +constexpr int JUMP_TARGET_MASK = 3; +constexpr float JUMP_STEP = 90; +constexpr float JUMP_CONTROLLED_REACH = 120; +constexpr float JUMP_CONTROLLED_SHRINK = 5; +constexpr int JUMP_CONTROLLED_FREE_TRIES = 3; +constexpr float JUMP_FREE_RADIUS = 64; +constexpr float JUMP_REACH = 120; +constexpr int JUMP_BLOCKED_PATH = 500; +constexpr int POOP_HEALTH_STEP = 125; +constexpr int DIRT_PARTICLES = 4; +constexpr float DIRT_PARTICLE_SPEED = 5; +constexpr int GRID_MARKED_PATH = 900; +constexpr float JUMP_PULL_GROWTH = 0.04f; +constexpr float MOLE_JUMP_FRICTION = 0.4f; + +// Burrowing: it heads 0.8 fast at its target when in line (aiming a little ahead), else paths there, and digs out 1 +// time in 10 within 90 (or within 200 after 90 frames). A controlled one digs out on its button or after 150 frames. +constexpr float BURROW_SPEED = 0.8f; +constexpr int BURROW_PATH_MARKER = 499; +constexpr int BURROW_SNAPSHOT_FRAMES = 30; +constexpr float BURROW_LEAD = 0.4f; +constexpr float BURROW_WOBBLE_MIN = 128; +constexpr float BURROW_WOBBLE_SHARE = 0.5f; +constexpr float BURROW_FRICTION = 0.8f; +constexpr uint32_t DIG_OUT_ODDS = 10; +constexpr float DIG_OUT_NEAR_SQUARED = 8100; +constexpr float DIG_OUT_FAR_SQUARED = 40000; +constexpr int DIG_OUT_LATE_FRAMES = 90; +constexpr int DIG_OUT_CONTROLLED_FRAMES = 150; +constexpr int CONTROLLER_ATTACK_ACTION = 9; +constexpr float CONTROLLED_ATTACK_RANGE = 1000; +constexpr int CONTROLLED_ATTACK_EVERY = 7; +constexpr float DIRT_PILE_SPACING_SQUARED = 144; +constexpr float TAINTED_CRUSH_DAMAGE = 10; +constexpr float TAINTED_CRUSH_RADIUS = 20; +constexpr float ROCK_EXPLOSION_DEPTH = 10; + +// Digging out: a crush and shockwave for the Tainted Mole, a poof of dust, then 1 time in 10 a frame it shoots. +constexpr float MOLE_SHOCKWAVE_MAX_RADIUS = 50; +constexpr int MOLE_SHOCKWAVE_FRAMES = 5; +constexpr int DIG_OUT_SHAKE = 4; +constexpr ColorMod DIG_OUT_POOF_COLOR = tint_color_make(0.9f, 0.9f, 0.9f, 0.6f); +constexpr uint32_t MOLE_SHOOT_ODDS = 10; + +// Its shots: three 8 fast (spread a little), or the Tainted Mole's big ones up to four times. +constexpr float MOLE_SHOT_SPEED = 8; +constexpr float MOLE_SHOT_SPREAD = 0.4f; +constexpr float TAINTED_SHOT_SCALE = 1.4f; +constexpr int TAINTED_VOLLEYS = 3; +constexpr int SHOT_BLOOD = 2; +constexpr float SHOT_BLOOD_RISE = -20; +constexpr float SHOT_PITCH = 1.2f; + +// Whether the room is too dark to see a plain Mole: Curse of the Darkness, a pitch black room, or deep darkness. +static bool mole_is_dark() +{ + Game& game = *g_game; + uint32_t curses = (Seeds::GetForcedCurses() | game.debugCurses | game.curses) & ~Seeds::GetPreventedCurses(); + float darkness = (curses & CURSE_OF_DARKNESS) ? 1 : game.darknessStrength * game.darknessModifier; + return (game.room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK) || darkness > DARKNESS_SEEN; +} + +// The cell a position falls in, or -1 off the grid. +static int cell_get(Room& room, const Vector& position, int& column, int& row) +{ + column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + return isInside ? row * room.gridWidth + column : -1; +} + +// A cell's center. +static Vector cell_center(Room& room, int cell) +{ + return vector_make((float)(cell % room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X, + (float)(cell / room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y); +} + +// Marks a cell as taken for the walkers' paths. +static void cell_mark(Room& room, int cell) +{ + if (cell >= 0 && cell < ROOM_GRID_CELLS) room.gridPaths[cell] = GRID_MARKED_PATH; +} + +// The poop it leaves, placed as Room::SpawnGridEntityDesc places a saved one unless the cell is taken. The poop rarely +// drops anything. +static void dug_poop_spawn(Room& room, int cell) +{ + if (cell < 0 || cell >= ROOM_GRID_CELLS) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"SpawnGridEntity: Grid index invalid\n"); + if (room.gridPaths[cell] > GRID_MARKED_PATH) return; + GridEntity* poop = CreateGridEntity(GRID_POOP, cell); + if (!poop) return; + + poop->state = (int)((Random() & 1) + 1) * POOP_HEALTH_STEP; + poop->spawnSeed = Random(); + poop->variableSeed = Random(); + delete room.gridEntities[cell]; + room.gridEntities[cell] = poop; + poop->collisionClass = COLLISION_NONE; + poop->subclass_init(); + poop->spawnCount++; + poop->isInitialized = true; + poop->spawnFrame = g_game->frameCount; + poop->varData = 1; + poop->PostInit(); +} + +// A spot to jump to on this try: its controller's way, its target 1 time in 4, or a random one 90 away. +static Vector jump_spot_get(Entity_NPC& npc, int tries) +{ + if (npc.controllerID != -1) + { + Vector input = npc.GetControllerInput(0); + return vector_add(npc.pos, vector_scale(input, JUMP_CONTROLLED_REACH - (float)tries * JUMP_CONTROLLED_SHRINK)); + } + if ((Random() & JUMP_TARGET_MASK) == 0) return npc.CalcTargetPosition(0); + float angle = random_unit() * RANDOM_HALF_TURN * 2; + return vector_add(npc.pos, vector_make(std::cos(angle) * JUMP_STEP, std::sin(angle) * JUMP_STEP)); +} + +// On Shoot of its jump it picks where to come up, leaves its poop behind, and drops underground (forward if lower). +static void mole_dig_in(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.shadowSize = npc.config->shadowSize; + npc.targetPosition = {}; + float farthest = 0; + int start = room.GetGridIndex(npc.pos); + int best = start; + for (int tries = 0; tries < JUMP_TRIES; tries++) + { + Vector spot = jump_spot_get(npc, tries); + if (npc.controllerID == -1 || tries > JUMP_CONTROLLED_FREE_TRIES) spot = room_free_tile_position_find(spot, JUMP_FREE_RADIUS); + float distance = vector_length(vector_sub(npc.pos, spot)); + int column = 0; + int row = 0; + int cell = cell_get(room, spot, column, row); + bool isOpen = cell < 0 || cell >= ROOM_GRID_CELLS || room.gridPaths[cell] < JUMP_BLOCKED_PATH; + if (!isOpen || !npc.pathfinder.HasPathToPos(spot, false) || distance >= JUMP_REACH || farthest >= distance) + continue; + + farthest = distance; + best = cell; + if (npc.controllerID != -1) break; + } + + if (start != best && room.CanSpawnObstacleAtPosition(start, false)) + { + npc_sound_play(SOUND_ROCK_CRUMBLE, 1, 2, 1); + dug_poop_spawn(room, start); + game_particles_spawn({.position = npc.pos, .speed = DIRT_PARTICLE_SPEED, .count = DIRT_PARTICLES, + .variant = EFFECT_ROCK_PARTICLE}); + } + npc.targetPosition = cell_center(room, best); + npc.v1.x = 0; + if (npc.pos.y <= npc.targetPosition.y) + { + npc.entityGridCollisionClass = GRIDCOLL_NONE; + return; + } + + int frame = npc.sprite.animState.animData ? (int)std::floor(npc.sprite.animState.animFrame) : -1; + npc.sprite.Play("JumpBack"); + npc.sprite.SetFrame((float)frame); + npc.forwardVector = vector_make(0, -1); + npc.entityGridCollisionClass = GRIDCOLL_NONE; +} + +// Jumping back under: picking its spot on Shoot, gone from sight on Shoot2, then burrowing. +static void mole_jump(Entity_NPC& npc) +{ + ANM2& sprite = npc.sprite; + if (!sprite.animState.animData || !sprite.WasEventTriggered("Shoot")) cell_mark(*g_game->room, g_game->room->GetGridIndex(npc.pos)); + if (sprite.animState.animData && sprite.IsEventTriggered("Shoot")) mole_dig_in(npc); + if (sprite.animState.animData) + { + if (sprite.IsEventTriggered("Shoot2")) + { + npc.shadowSize = 0; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + } + if (sprite.IsPlaying()) return; + } + npc.state = NPC_STATE_MOVE; + npc.targetPosition = {}; +} + +// Whether it digs out now: 1 time in 10 near its target, or by its controller. +static bool mole_is_digging_out(Entity_NPC& npc) +{ + float distanceSquared = vector_length_squared(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + if (npc.controllerID == -1) + return Random() % DIG_OUT_ODDS == 0 && + (distanceSquared < DIG_OUT_NEAR_SQUARED || + (npc.stateFrame > DIG_OUT_LATE_FRAMES && distanceSquared < DIG_OUT_FAR_SQUARED)); + return npc.IsControllerActionPressed(CONTROLLER_ATTACK_ACTION) || + npc.IsTargetInAttackRange(CONTROLLED_ATTACK_RANGE, 0, CONTROLLED_ATTACK_EVERY) || + npc.stateFrame > DIG_OUT_CONTROLLED_FRAMES; +} + +// Its dirt trail: a pile wherever none lies within 12, the Tainted Mole's with a rock burst crushing what stands there. +static void dirt_pile_leave(Entity_NPC& npc) +{ + for (Entity* pile : entity_query(ENTITY_EFFECT, EFFECT_DIRT_PILE)) + if (vector_length_squared(vector_sub(npc.pos, pile->pos)) < DIRT_PILE_SPACING_SQUARED) return; + + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_DIRT_PILE, .seed = Random()}); + if (npc.variant != TAINTED_MOLE) return; + + Entity* burst = + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_ROCK_EXPLOSION, .seed = Random()}); + burst->renderDepthOffset = ROCK_EXPLOSION_DEPTH; + explosion_damage({.position = npc.pos, + .source = npc.parent.get(), + .damageFlags = DAMAGE_CRUSH, + .damage = TAINTED_CRUSH_DAMAGE, + .radius = TAINTED_CRUSH_RADIUS, + .isLineCheck = false}); + npc_sound_play(SOUND_ROCK_CRUMBLE, 1, 2, 1); +} + +// Burrowing to its target (straight at it, a little ahead, when in line), digging out on a free cell near it. +static void mole_burrow(Entity_NPC& npc, bool isDark) +{ + Room& room = *g_game->room; + Vector target = npc.CalcTargetPosition(0); + Entity* player = npc.GetPlayerTarget(); + if (npc.IsFrame(BURROW_SNAPSHOT_FRAMES, (int)npc.index)) npc.v2 = player->velocity; + + if (npc.controllerID == -1 && room_check_line(npc.pos, target, LINE_MODE_GROUND, 0)) + { + RNG rng = {npc.initSeed + npc.index, 5, 9, 7}; + float distance = vector_length(vector_sub(npc.pos, target)); + target = vector_add(target, vector_scale(npc.v2, distance * rng.RandomFloat() * BURROW_LEAD)); + // The original clamps this wobble's radius to nothing, so only its draws are left. + float wobble = std::min(std::max(BURROW_WOBBLE_MIN, vector_length(vector_sub(npc.pos, target)) * BURROW_WOBBLE_SHARE), 0.0f); + float age = rng.RandomFloat() * (float)(g_game->frameCount - npc.spawnFrame); + float angle = (rng.RandomFloat() * DEGREES_PER_TURN + age + age) * DEGREES_TO_RADIANS; + target = vector_add(target, vector_make(std::cos(angle) * wobble, std::sin(angle) * wobble)); + npc.friction *= BURROW_FRICTION; + npc_push(npc, vector_scale(vector_normalized(vector_sub(target, npc.pos)), BURROW_SPEED)); + } + else npc.pathfinder.FindGridPath(target, BURROW_SPEED, BURROW_PATH_MARKER, DIRECT_PATH_FAR); + + if (mole_is_digging_out(npc)) + { + int cell = room.GetGridIndex(npc.pos); + bool isFree = cell >= 0 && room_grid_collision_at(npc.pos) == 0 && + (npc.controllerID != -1 || cell >= ROOM_GRID_CELLS || room.gridPaths[cell] < JUMP_BLOCKED_PATH); + if (isFree) + { + npc.pos = cell_center(room, cell); + npc.state = MOLE_DIG_OUT; + npc.targetPosition = npc.pos; + npc.stateFrame = 0; + npc.sprite.Play(isDark ? "DigOut2" : "DigOut"); + npc.UpdateDirtColor(true); + return; + } + if (npc.stateFrame > DIG_OUT_CONTROLLED_FRAMES && npc.controllerID != -1) + reconstruction_missing("NpcAI::ENTITY_MOLE 004fdf80: a controlled mole kept under too long"); + } + npc.stateFrame += npc_ticks_get(npc); + dirt_pile_leave(npc); +} + +// Digging out: on Shoot it is solid again (the Tainted Mole with a shockwave and crush), then 1 time in 10 (or on its +// controller's aim) it shoots. A controlled one not aiming jumps back under. +static void mole_dig_out(Entity_NPC& npc, bool isDark) +{ + if (npc.controllerID != -1) npc.SpawnControlTarget(0, -1); + if (npc.sprite.animState.animData) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + if (npc.variant == TAINTED_MOLE) + { + auto* wave = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_SHOCKWAVE, + .seed = Random()})); + wave->parent = &npc; + wave->SetRadii(npc.size, MOLE_SHOCKWAVE_MAX_RADIUS); + wave->SetTimeout(MOLE_SHOCKWAVE_FRAMES); + npc.PlaySound(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, false, 1); + game_shake_screen(DIG_OUT_SHAKE); + npc.MakeGroundPoof(npc.pos, DIG_OUT_POOF_COLOR, 1); + } + } + if (npc.sprite.IsPlaying()) return; + } + + bool isShooting = npc.controllerID == -1 ? Random() % MOLE_SHOOT_ODDS == 0 + : !vector_is_zero(vector_sub(npc.GetAimTargetPosition(), npc.pos)); + if (isShooting) + { + npc.state = MOLE_SHOOT; + npc.i2 = 0; + } + else if (npc.controllerID != -1) + { + npc.state = MOLE_JUMP; + npc.sprite.Play(isDark ? "Jump2" : "Jump"); + } +} + +// Its shots on Shoot at its target (or its controller's aim), the Tainted Mole firing up to three more volleys. +static void mole_shoot(Entity_NPC& npc, bool isDark) +{ + if (npc.controllerID != -1) npc.SpawnControlTarget(0, -1); + npc.sprite.Play("Shoot"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + Vector at = npc.GetPlayerTarget()->pos; + if (npc.controllerID != -1) at = npc.GetAimTargetPosition(); + ProjectileParams params; + if (npc.variant == TAINTED_MOLE) params.scale = TAINTED_SHOT_SCALE; + else params.spread = MOLE_SHOT_SPREAD; + Vector aim = vector_scale(vector_normalized(vector_sub(at, npc.pos)), MOLE_SHOT_SPEED); + npc.FireProjectiles(npc.pos, aim, PROJECTILES_THREE, params); + blood_explosion_spawn(SHOT_BLOOD, npc.pos, vector_make(npc.sprite.scale.x * 0, npc.sprite.scale.y * SHOT_BLOOD_RISE), + COLOR_DEFAULT, {}); + bool isTainted = npc.variant == TAINTED_MOLE; + npc.PlaySound(isTainted ? SOUND_MONSTER_GRUNT_2 : SOUND_WHEEZY_COUGH, 1, 2, false, isTainted ? 1 : SHOT_PITCH); + npc.sprite.isFlipX = at.x < npc.pos.x; + } + if (npc.variant == TAINTED_MOLE && npc.sprite.animState.animData && npc.sprite.IsEventTriggered("Shoot2") && + npc.i2 < TAINTED_VOLLEYS) + { + npc.sprite.Play("Shoot", PLAY_FORCED); + npc.i2++; + } + if (npc.sprite.IsPlaying()) return; + npc.state = MOLE_JUMP; + npc.sprite.Play(isDark ? "Jump2" : "Jump"); +} + +// 004fdf80 (NpcAI::ENTITY_MOLE) The Mole and Tainted Mole: immune to its kind's own hits, it burrows, digs out, shoots +// and jumps back under, drawn toward its spot while it moves. +void npc_mole_update(Entity_NPC& npc) +{ + bool isDark = mole_is_dark(); + if (npc.type == ENTITY_MOLE && npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + if (!event.source.IsCharmed() && (event.source.type == npc.type || event.source.spawnerType == npc.type)) + event.damage = 0; + npc.UpdateChargeBar(MOLE_CHARGE_BAR_FULL, 0, (float)npc.stateFrame, true); + npc.forwardVector = vector_make(0, 1); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.shadowSize = 0; + npc.v2 = {}; + break; + case MOLE_JUMP: + mole_jump(npc); + break; + case NPC_STATE_MOVE: + mole_burrow(npc, isDark); + break; + case MOLE_DIG_OUT: + mole_dig_out(npc, isDark); + break; + case MOLE_SHOOT: + mole_shoot(npc, isDark); + break; + } + + npc.UpdateDirtColor(false); + if (vector_is_zero(npc.targetPosition)) return; + if (npc.state == MOLE_JUMP) + { + npc.v1.x = std::clamp(npc.v1.x + JUMP_PULL_GROWTH, 0.0f, 1.0f); + npc.friction *= MOLE_JUMP_FRICTION; + npc.velocity = vector_scale(vector_sub(npc.targetPosition, npc.pos), npc.v1.x / npc.friction); + return; + } + npc.friction *= BURROW_FRICTION; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + int column = 0; + int row = 0; + int cell = cell_get(*g_game->room, npc.pos, column, row); + if (cell >= 0) cell_mark(*g_game->room, cell); +} diff --git a/src/npc_moms_hand.cpp b/src/npc_moms_hand.cpp index 672be4d..ce0ebb8 100644 --- a/src/npc_moms_hand.cpp +++ b/src/npc_moms_hand.cpp @@ -1,4 +1,5 @@ #include "boss_ai.h" +#include "entity_player.h" #include "npc_depths.h" #include "room_grid.h" #include "room_transition.h" @@ -123,7 +124,17 @@ static void moms_hand_carry(Entity_NPC& npc) npc.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); npc.isInvincible = false; if (npc.i1 == ENTITY_PLAYER && npc.i2 == 0) - reconstruction_missing("NpcAI::ENTITY_MOMS_HAND 00533b80: releasing grabbed players (Entity_Player 0x189c)"); + { + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->momsHandTimer > 0) + { + player->isControlsEnabled = true; + player->entityCollisionClass = ENTCOLL_ALL; + player->momsHandTimer = 0; + } + g_game->leaveDoor = -1; + g_game->StartRoomTransition({.animation = TRANSITION_FADE, .roomIndex = g_game->startingRoomIdx}); + } npc.entityCollisionClass = ENTCOLL_NONE; npc.shadowSize *= HAND_SHADOW_FADE; npc.state = NPC_STATE_MOVE; @@ -180,3 +191,33 @@ void npc_moms_hand_update(Entity_NPC& npc) Entity_NPC::ThrowSpider(npc.pos, &npc, spot, false, HAND_SPIDER_HEIGHT); } } + +// A player Mom's hand carries off stays away 240 frames. +constexpr int GRABBED_FRAMES = 240; + +// 007b9a60 Taken by Mom's hand: a player vanishes untouchable and without control for a while, a co-op baby is gone. +void moms_hand_player_grab(Entity_Player& player) +{ + if (player.variant == PLAYER_VARIANT_PLAYER) + { + player.isControlsEnabled = false; + player.isVisible = false; + player.entityCollisionClass = ENTCOLL_NONE; + player.momsHandTimer = GRABBED_FRAMES; + } + else if (player.variant == PLAYER_VARIANT_COOP_BABY) g_game->playerManager.RemoveCoPlayer(&player); +} + +// 007b9aa0 Outside room transitions a carried player's time runs out, and it drops back in where it was taken. +void moms_hand_player_release_update(Entity_Player& player) +{ + if (g_game->roomTransition.mode != TRANSITION_NONE || player.momsHandTimer <= 0 || --player.momsHandTimer != 0) + return; + + player.isControlsEnabled = true; + player.entityCollisionClass = ENTCOLL_ALL; + player.momsHandTimer = 0; + npc_sound_play(SOUND_HELL_PORTAL1, 1, 2, 1); + player.PlayExtraAnimation("TeleportDown"); + player.isVisible = true; +} diff --git a/src/npc_oob.cpp b/src/npc_oob.cpp new file mode 100644 index 0000000..4aea1a2 --- /dev/null +++ b/src/npc_oob.cpp @@ -0,0 +1,141 @@ +#include "boss_ai.h" +#include "menu_manager.h" +#include "npc_caves.h" + +// The Oob's states: crawling, the charge across the room (wrapping past its walls) and laying a Brain. +constexpr int OOB_CHARGE = NPC_STATE_ATTACK; +constexpr int OOB_LAY = NPC_STATE_SUMMON; + +constexpr ColorMod OOB_SPLAT_COLOR = {{0.5f, 0.1f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0.1f, 0.1f}}; +constexpr int OOB_LAY_MIN = 30; +constexpr uint32_t OOB_LAY_RANGE = 45; +constexpr float OOB_FRICTION = 0.8f; +constexpr float OOB_TARGET_LEAD = 10; +constexpr float OOB_CONTROL_REACH = 100; +constexpr int OOB_WANDER_MIN = 15; +constexpr uint32_t OOB_WANDER_RANGE = 30; +constexpr float OOB_WANDER_MIN_REACH = 20; +constexpr float OOB_VERTICAL_WEIGHT = 3; +constexpr float OOB_CHARGE_ROW = 20; +constexpr float OOB_CHARGE_WARMUP = 45; +constexpr float OOB_CHARGE_SPEED = 25; +constexpr float OOB_WRAP_MARGIN = 160; + +// Back to crawling. +static void oob_crawl_start(Entity_NPC& npc) +{ + npc.stateFrame = 0; + npc.velocity = {}; +} + +// Crawling: toward its target (confused, a remembered way, rerolled now and then), slow up and down. Once its target +// shares its row (a controller's action) it charges, and when rested it lays a Brain (controlled, on its other action). +static void oob_crawl(Entity_NPC& npc) +{ + npc.sprite.Play("Walk"); + Vector move = vector_sub(npc.CalcTargetPosition(OOB_TARGET_LEAD), npc.pos); + if (npc.controllerID != -1) move = vector_scale(npc.GetControllerInput(0), OOB_CONTROL_REACH); + if (npc.HasEntityFlags(FLAG_CONFUSION) && npc.controllerID == -1) + { + int every = (int)(Random() % OOB_WANDER_RANGE) + OOB_WANDER_MIN; + if (!npc.IsFrame(every, (int)npc.index) && !npc.isCollidesWithGrid) move = npc.v1; + else npc.v1 = move; + float reach = vector_length_squared(move); + if (reach < OOB_WANDER_MIN_REACH * OOB_WANDER_MIN_REACH && reach != 0) move = vector_resized(move, OOB_WANDER_MIN_REACH); + } + npc.friction *= OOB_FRICTION; + move.y *= OOB_VERTICAL_WEIGHT; + npc_push(npc, vector_normalized(move)); + if (npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return; + + if (npc.i1 >= 0) npc.i1 -= npc_ticks_get(npc); + bool isCharge = npc.controllerID == -1 ? std::abs(move.y) < OOB_CHARGE_ROW && npc.updateTime > OOB_CHARGE_WARMUP + : npc.IsControllerActionPressed(ACTION_ITEM); + if (isCharge) + { + npc.sprite.isFlipX = move.x < 0; + npc_anim_restart(npc.sprite, "Charge"); + npc.PlaySound(SOUND_MONSTER_YELL_A, 1, 2, false, 1); + npc.targetPosition = npc.pos; + npc.entityGridCollisionClass = GRIDCOLL_WALLS_Y; + npc.state = OOB_CHARGE; + return oob_crawl_start(npc); + } + if (npc.i1 >= 0 || (npc.controllerID != -1 && !npc.IsControllerActionPressed(ACTION_BOMB))) return; + + npc.i1 = npc.controllerID == -1 ? (int)(Random() % OOB_LAY_RANGE) + OOB_LAY_MIN : OOB_LAY_MIN; + npc_anim_restart(npc.sprite, "Spawn"); + npc.state = OOB_LAY; + oob_crawl_start(npc); +} + +// The charge: once its shake ends (or it shot off) it races across, coming back in from the far wall, and stops once +// past where it started. +static void oob_charge(Entity_NPC& npc) +{ + npc.velocity = {}; + if (npc_anim_is_done(npc)) npc_anim_loop(npc.sprite, "Charge Shake"); + const AnimationData* data = npc.sprite.animState.animData; + bool isShaking = data && npc.sprite.animState.isPlaying && data->name == "Charge Shake"; + if (data && (isShaking || npc.sprite.animState.WasEventTriggered("Shoot"))) + npc.velocity.x = npc.sprite.isFlipX ? -OOB_CHARGE_SPEED : OOB_CHARGE_SPEED; + + Room& room = *g_game->room; + float speed = npc.velocity.x; + if (speed > 0 && npc.pos.x > room.bottomRightPos.x + OOB_WRAP_MARGIN) + { + npc.stateFrame++; + npc.pos.x = room.topLeftPos.x - OOB_WRAP_MARGIN; + } + else if (speed < 0 && npc.pos.x < room.topLeftPos.x - OOB_WRAP_MARGIN) + { + npc.stateFrame++; + npc.pos.x = room.bottomRightPos.x + OOB_WRAP_MARGIN; + } + if (npc.stateFrame < 1) return; + + bool isBack = (speed < 0 && npc.targetPosition.x > npc.pos.x) || (speed > 0 && npc.pos.x > npc.targetPosition.x); + if (!isBack) return; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.state = NPC_STATE_MOVE; +} + +// Laying: a Brain on its Shoot event where the floor is free, then back to crawling. +static void oob_lay(Entity_NPC& npc) +{ + npc.velocity = {}; + if (npc_anim_is_done(npc)) + { + npc.state = NPC_STATE_MOVE; + return; + } + if (!npc.sprite.IsEventTriggered("Shoot") || room_grid_collision_at(npc.pos) != 0) return; + + npc.PlaySound(SOUND_SUMMONSOUND, 1, 2, false, 1); + g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_BRAIN, .seed = Random()}); +} + +// 0053ab40 The Oob (224): it crawls after its target, charges across the room when lined up, and lays Brains. +void npc_oob_update(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.state = NPC_STATE_MOVE; + npc.i1 = OOB_LAY_MIN + (npc.controllerID == -1 ? (int)(Random() % OOB_LAY_RANGE) : 0); + npc.v1 = {}; + npc.splatColor = OOB_SPLAT_COLOR; + return; + case NPC_STATE_MOVE: + oob_crawl(npc); + if (npc.velocity.x < 0 && !npc.sprite.isFlipX) npc.sprite.isFlipX = true; + else if (npc.velocity.x > 0 && npc.sprite.isFlipX) npc.sprite.isFlipX = false; + return; + case OOB_CHARGE: + return oob_charge(npc); + case OOB_LAY: + return oob_lay(npc); + } +} diff --git a/src/npc_poop.cpp b/src/npc_poop.cpp new file mode 100644 index 0000000..1522422 --- /dev/null +++ b/src/npc_poop.cpp @@ -0,0 +1,455 @@ +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_poop.h" +#include "npc_ai.h" +#include "player_manager.h" +#include "room.h" +#include +#include +#include + +constexpr uint64_t POOP_NPC_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | + FLAG_NO_DEATH_TRIGGER | FLAG_NO_SPIKE_DAMAGE | FLAG_NO_FLASH_ON_DAMAGE; +constexpr uint64_t POOP_NPC_CLEARED_FLAG = 1ull << 2; +constexpr float POOP_FULL_HEALTH = 6; +constexpr int POOP_STAGE_LAST = 5; +constexpr int POOP_STATE_READY = 3; +constexpr float POOP_REWARD_SCALE = 250; +constexpr float POOP_THROWN_HIT = 15; +constexpr int POOP_THROWN_HIT_COUNTDOWN = 30; +constexpr float POOP_THROWN_PUSH = 0.5f; +constexpr float POOP_GRAVITY = 2; +constexpr float POOP_STONE_GRAVITY = 0.8f; +constexpr float POOP_HIGH = -26; +constexpr float POOP_RISING = -3; +constexpr float POOP_LANDING_SLOWDOWN = 0.6f; +constexpr float POOP_REST_FRICTION = 0.5f; +constexpr int POOP_GRID_PATH = 900; +constexpr int POOP_GRID_PATH_MOD = 1000; +constexpr int POOP_GAS_INTERVAL = 15; +constexpr int POOP_GAS_THROWN_INTERVAL = 2; +constexpr int POOP_GAS_FRAMES = 60; +constexpr float POOP_GAS_SPREAD = 2; +constexpr int POOP_GAS_BURST = 8; +constexpr float POOP_GAS_BURST_STEP = 45; +constexpr float POOP_GAS_BURST_JITTER = 30; +constexpr float POOP_GAS_BURST_SPEED = 8; +constexpr int POOP_GAS_BURST_FRAMES = 150; +constexpr int POOP_FIRE_FRAMES = 150; +constexpr float POOP_CREEP_SCALE_MIN = 0.8f; +constexpr float POOP_CREEP_SCALE_SPREAD = 0.4f; +constexpr int POOP_AURA_PERIOD = 3; +constexpr float POOP_AURA_REACH = 70; +constexpr int POOP_AURA_FRAMES = 4; +constexpr uint32_t POOP_AURA_CACHE = 0x63; +constexpr float POOP_AURA_OFFSET_Y = -4; +constexpr int POOP_AURA_DEPTH = 10000; +constexpr int POOP_FLY_PERIOD = 60; +constexpr int POOP_FLY_SLOTS = 3; +constexpr int POOP_FLY_ORBIT = 1; +constexpr int POOP_BROKEN_DEPTH = 3100; + +// The movable poop piles (ENTITY_POOP's variants): plain, golden, and Tainted ???'s spells. +enum PoopNpcVariant +{ + POOP_NPC_NORMAL, + POOP_NPC_GOLDEN, + POOP_NPC_SPELL = 10, + POOP_NPC_STONE, + POOP_NPC_CORNY, + POOP_NPC_BURNING, + POOP_NPC_STINKY, + POOP_NPC_BLACK, + POOP_NPC_HOLY +}; + +// The poop grid variant whose gibs, drops and rewards a pile shares. +static int poop_grid_variant(int variant) +{ + switch (variant) + { + case POOP_NPC_GOLDEN: return POOP_GOLDEN; + case POOP_NPC_STONE: return POOP_STONE; + case POOP_NPC_CORNY: return POOP_CORNY; + case POOP_NPC_BURNING: return POOP_FLAMING; + case POOP_NPC_STINKY: return POOP_STINKY; + case POOP_NPC_BLACK: return POOP_BLACK; + case POOP_NPC_HOLY: return POOP_WHITE; + default: return POOP_NORMAL; + } +} + +// How broken a pile is, 1 whole to 5 gone, from its health. +static int poop_stage(float health) +{ + return (int)std::clamp(POOP_FULL_HEALTH - health, 1.0f, (float)POOP_STAGE_LAST); +} + +// The sheet a pile wears by variant, plain and holy ones picking one of three. +static std::string poop_sheet(Entity_NPC& npc) +{ + switch (npc.variant) + { + case POOP_NPC_GOLDEN: return "gfx/grid/grid_poop_gold.png"; + case POOP_NPC_STONE: return "gfx/grid/grid_poop_stone.png"; + case POOP_NPC_CORNY: return "gfx/grid/grid_poop_corn.png"; + case POOP_NPC_BURNING: return "gfx/grid/grid_poop_flaming.png"; + case POOP_NPC_STINKY: return "gfx/grid/grid_poop_stinky.png"; + case POOP_NPC_BLACK: return "gfx/grid/grid_poop_black.png"; + case POOP_NPC_HOLY: return "gfx/grid/grid_poop_white_" + std::to_string(npc.dropRNG.RandomInt(3)) + ".png"; + default: return "gfx/grid/grid_poop_" + std::to_string(npc.dropRNG.RandomInt(3)) + ".png"; + } +} + +// An effect a pile leaves that lasts a while, the spawner type set to a player's. +static Entity_Effect* poop_effect_spawn(Entity_NPC& npc, int variant, Vector velocity, int subType, uint32_t seed, + int frames) +{ + auto* effect = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = velocity, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = variant, + .seed = seed})); + effect->spawnerType = ENTITY_PLAYER; + effect->timeout = frames; + effect->lifespan = frames; + return effect; +} + +// The thrown pile's touch (the collision phase): it breaks and hits an active enemy for 15, a stone one crushing, +// passing half its speed on. +static void poop_touch(Entity_NPC& npc) +{ + Entity* enemy = npc.collisionEntity; + if (!npc.HasEntityFlags(FLAG_THROWN) || !enemy->IsActiveEnemy(DEAD_EXCLUDED)) return; + + npc.Kill(EntityRef()); + uint64_t damageFlags = npc.variant == POOP_NPC_STONE ? DAMAGE_CRUSH : 0; + Entity* source = npc.spawnerEntity ? npc.spawnerEntity.get() : &npc; + enemy->TakeDamage(POOP_THROWN_HIT, damageFlags, EntityRef(source), POOP_THROWN_HIT_COUNTDOWN); + npc.collisionResult = 0; + enemy->velocity = vector_add(enemy->velocity, vector_scale(npc.velocity, POOP_THROWN_PUSH)); +} + +// The stinky pile's gas: a cloud drifting off every 15 frames (2 while flying). +static void poop_gas_update(Entity_NPC& npc) +{ + float interval = npc.HasEntityFlags(FLAG_THROWN) ? POOP_GAS_THROWN_INTERVAL : POOP_GAS_INTERVAL; + if (npc.health <= 1 || !npc.GetIntervalTicks(interval, 0)) return; + + uint32_t seed = Random(); + int subType = (int)(Random() & 1); + Vector direction = random_direction(); + float push = random_unit() * POOP_GAS_SPREAD; + poop_effect_spawn(npc, EFFECT_SMOKE_CLOUD, vector_add(vector_scale(direction, push), npc.velocity), subType, seed, + POOP_GAS_FRAMES) + ->Update(); +} + +// The holy pile's aura: Hallowed Ground around it, strengthening the players close by every third frame, until the +// pile is down to its last health and lets the aura go. +static void poop_aura_update(Entity_NPC& npc) +{ + if (npc.health <= 1) + { + if (!npc.entityRef) return; + npc.entityRef->isVisible = true; + npc.entityRef->parent = nullptr; + npc.entityRef = nullptr; + return; + } + if (npc.IsFrame(POOP_AURA_PERIOD, 0)) + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (vector_length(vector_sub(npc.pos, player->pos)) >= player->size + POOP_AURA_REACH) continue; + + int before = player->hallowedGroundCountdown; + player->hallowedGroundCountdown = std::min(before + POOP_AURA_FRAMES, POOP_AURA_FRAMES); + if ((before > 0) == (player->hallowedGroundCountdown > 0)) continue; + player->cacheFlags |= POOP_AURA_CACHE; + player->EvaluateItems(); + } + if (npc.entityRef) return; + + auto* aura = static_cast( + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_HALLOWED_GROUND, .seed = Random()})); + aura->FollowParent(&npc); + aura->sprite.offset = vector_make(0, POOP_AURA_OFFSET_Y); + aura->renderZOffset = POOP_AURA_DEPTH; + aura->Update(); + npc.entityRef = aura; +} + +// The black pile's creep, laid every 15 frames (2 while flying) at a random size. +static void poop_creep_update(Entity_NPC& npc) +{ + float interval = npc.HasEntityFlags(FLAG_THROWN) ? POOP_GAS_THROWN_INTERVAL : POOP_GAS_INTERVAL; + if (!npc.GetIntervalTicks(interval, 0)) return; + + Entity_Effect* creep = poop_effect_spawn(npc, EFFECT_PLAYER_CREEP_BLACK, {}, 0, Random(), POOP_GAS_FRAMES); + float scale = random_unit() * POOP_CREEP_SCALE_SPREAD + POOP_CREEP_SCALE_MIN; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); +} + +// The flight of a thrown pile: it rises and falls (a stone one faster), flies over obstacles while high, and lands +// slowed with a thud, resting again. The interpolation only places it at its height. +static void poop_flight_update(Entity_NPC& npc) +{ + if (!npc.HasEntityFlags(FLAG_THROWN)) return; + if (npc.aiCallPhase == AI_PHASE_INTERPOLATE) + { + npc.posOffset.y = npc.v1.y * npc.speedMultiplier * 0.5f + npc.v1.x; + return; + } + + npc.targetPosition = {}; + npc.v1.x += npc.v1.y * npc.speedMultiplier; + npc.v1.y += POOP_GRAVITY; + bool isRising = npc.v1.y < POOP_RISING; + if (npc.variant == POOP_NPC_STONE) npc.v1.y += POOP_STONE_GRAVITY; + if (npc.v1.x < POOP_HIGH) npc.entityGridCollisionClass = GRIDCOLL_WALLS; + else npc.entityGridCollisionClass = isRising ? GRIDCOLL_NOPITS : GRIDCOLL_GROUND; + if (npc.v1.x >= 0) + { + npc.flags &= ~FLAG_THROWN; + npc.velocity = vector_scale(npc.velocity, POOP_LANDING_SLOWDOWN); + npc.PlaySound(npc.variant == POOP_NPC_STONE ? SOUND_STONE_IMPACT : SOUND_MEAT_IMPACTS, 1, 2, false, 1); + if (npc.sprite.SetAnimation("State" + std::to_string(poop_stage(npc.health)), SWITCH_RESET)) + { + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + } + npc.v1 = {}; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.entityCollisionClass = ENTCOLL_ALL; + } + npc.posOffset.y = npc.v1.x; +} + +// The corny pile a player made keeps up to three blue flies circling it, one more every 60 frames. +static void poop_flies_update(Entity_NPC& npc) +{ + Entity* spawner = npc.spawnerEntity.get(); + if (!spawner || spawner->type != ENTITY_PLAYER || npc.variant != POOP_NPC_CORNY || !npc.IsFrame(POOP_FLY_PERIOD, 0) || + npc.health <= 1) + return; + + if (npc.entityDeque.size() < POOP_FLY_SLOTS) npc.entityDeque.resize(POOP_FLY_SLOTS); + for (int slot = 0; slot < POOP_FLY_SLOTS; slot++) + { + if (npc.entityDeque[slot]) continue; + + auto* fly = static_cast(static_cast(spawner)->AddBlueFlies(1, npc.pos, nullptr)); + if (!fly) return; + npc.entityDeque[slot] = fly; + fly->parent = &npc; + fly->AddToOrbit(POOP_FLY_ORBIT); + return; + } +} + +// The break of a pile's last stage: its splat and drops, a burning pile's fire and a stinky pile's ring of gas. +static void poop_break(Entity_NPC& npc, int gridVariant, const EntityRef& source) +{ + GridEntity_Poop::destroy_effects(npc.pos, gridVariant); + GridEntity_Poop::spawn_drops({.source = source, .position = npc.pos, .seed = npc.initSeed, .variant = gridVariant}); + if (npc.variant == POOP_NPC_BURNING) + { + Entity_Effect* fire = poop_effect_spawn(npc, EFFECT_HOT_BOMB_FIRE, {}, 0, Random(), POOP_FIRE_FRAMES); + fire->spawnerType = 0; + fire->Update(); + } + if (npc.variant != POOP_NPC_STINKY) return; + + float start = random_unit() * FULL_TURN_DEGREES; + for (int puff = 0; puff < POOP_GAS_BURST; puff++) + { + float degrees = random_unit() * POOP_GAS_BURST_JITTER + ((float)puff * POOP_GAS_BURST_STEP + start - 15); + uint32_t seed = Random(); + int subType = (int)(Random() & 1); + float speed = random_unit() * 2 + POOP_GAS_BURST_SPEED; + float radians = degrees * DEGREES_TO_RADIANS; + Vector velocity = vector_make(std::cos(radians) * speed, std::sin(radians) * speed); + poop_effect_spawn(npc, EFFECT_SMOKE_CLOUD, velocity, subType, seed, POOP_GAS_BURST_FRAMES)->Update(); + } +} + +// The hits a pile took this frame (fire's left out): one stage, four for an explosion or a kill, sometimes more, a +// golden or stone pile taking only a share. It gives the poop rewards, throws gibs and Dirty Mind's Dips as it breaks, +// and breaks for good at its last stage, a thrown pile or one on a minecart vanishing. True when the stage changed; +// false and gone when it vanished. +static bool poop_hits_update(Entity_NPC& npc, bool& isGone) +{ + float pending = 0; + for (DamageEvent& hit : npc.damageEvents) + { + if (hit.source.type == ENTITY_EFFECT && hit.source.variant == EFFECT_HOT_BOMB_FIRE) hit.damage = 0; + pending += hit.damage; + } + npc.pendingDamage = pending; + int stageBefore = poop_stage(npc.health); + bool isChanged = false; + + if (npc.isDead || pending > 0) + { + bool isHard = npc.isDead || (npc.pendingDamageFlags & DAMAGE_EXPLOSION); + float hits = isHard ? 4 : 1; + if (Random() % 3 == 0) hits++; + bool isTough = npc.variant == POOP_NPC_GOLDEN || npc.variant == POOP_NPC_STONE; + if (!isTough && Random() % 3 == 0) hits++; + float damage = isTough ? (random_unit() * 0.3f + 0.2f) * hits : hits; + EntityRef source = npc.damageEvents.empty() ? EntityRef() : npc.damageEvents.back().source; + + if (damage > 0) + { + float before = npc.health; + npc.health = std::max(before - damage, 1.0f); + isChanged = true; + int stageAfter = poop_stage(npc.health); + int gridVariant = poop_grid_variant(npc.variant); + GridEntity_Poop::spawn_rewards({.source = source, + .position = npc.pos, + .seed = npc.initSeed, + .damage = (int)(damage * POOP_REWARD_SCALE), + .previousState = (int)((POOP_STAGE_LAST - before) * POOP_REWARD_SCALE), + .variant = gridVariant}); + if (stageBefore < stageAfter) + { + GridEntity_Poop::spawn_hit_gibs(npc.pos, gridVariant, random_below(stageBefore) + 1); + Entity_Player* owner = g_game->playerManager.RandomCollectibleOwner(COLLECTIBLE_DIRTY_MIND, Random(), nullptr); + for (int i = 0; owner && i < stageAfter - stageBefore; i++) + if (stageAfter == POOP_STAGE_LAST || g_game->playerManager.AnyoneHasTrinket(TRINKET_PETRIFIED_POOP) || + (Random() & 1) == 0) + { + Vector zero{}; + spawn_dip_at(gridVariant, &npc.pos, owner, &zero); + } + } + if (stageAfter == POOP_STAGE_LAST && stageBefore < POOP_STAGE_LAST) + { + poop_break(npc, gridVariant, source); + if (npc.minecart || npc.HasEntityFlags(FLAG_THROWN)) + { + npc.Remove(); + isGone = true; + return false; + } + } + } + } + npc.isDead = false; + npc.damageEvents.clear(); + npc.pendingDamage = 0; + npc.pendingDamageFlags = 0; + return isChanged; +} + +// A pile's first frame: its flags and AI calls, its sheet and side, a burning pile's fire following it. +static void poop_init(Entity_NPC& npc) +{ + npc.flags = (npc.flags & ~POOP_NPC_CLEARED_FLAG) | POOP_NPC_FLAGS; + npc.aiCallFlags = AI_CALL_PRE_UPDATE | AI_CALL_INTERPOLATE | AI_CALL_COLLISION; + npc.sprite.ReplaceSpritesheet(0, poop_sheet(npc)); + npc.sprite.LoadGraphics(); + npc.sprite.isFlipX = npc.dropRNG.RandomInt(2) != 0; + if (npc.variant == POOP_NPC_BURNING && npc.health > 1) + { + auto* fire = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_HOT_BOMB_FIRE, .seed = Random()})); + fire->FollowParent(&npc); + fire->timeout = -1; + fire->lifespan = -1; + npc.entityRef = fire; + fire->Update(); + fire->isVisible = false; + } + npc.state = POOP_STATE_READY; +} + +// The pile's look for its stage: it appears whole, then plays the stage it is at, and once gone stops colliding and +// lies under everything. +static void poop_stage_show(Entity_NPC& npc, bool isJustMade) +{ + int stage = poop_stage(npc.health); + if (stage == 1 && isJustMade) + { + if (!npc.sprite.SetAnimation("Appear", SWITCH_RESET)) return; + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + return; + } + + std::string animation = "State" + std::to_string(stage); + AnimationState& state = npc.sprite.animState; + bool isShowing = state.animData && state.GetAnimation() == animation && (!state.animData->isLooping || state.isPlaying); + if (!isShowing && npc.sprite.SetAnimation(animation, SWITCH_RESET)) + { + state.Rewind(); + state.isPlaying = true; + } + if (stage != POOP_STAGE_LAST) return; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.sortingLayer = SORTING_BACKGROUND; + npc.renderZOffset = POOP_BROKEN_DEPTH; +} + +// The main frame: Midas's touch gilds a plain pile, a resting pile slides to a stop, corny piles keep their flies, a +// pile led to a spot marks its path there, and its hits break it stage by stage. +static void poop_frame(Entity_NPC& npc) +{ + bool isChanged = false; + if (npc.HasEntityFlags(FLAG_MIDAS_FREEZE) && npc.variant == POOP_NPC_NORMAL) + { + npc.variant = POOP_NPC_GOLDEN; + npc.sprite.ReplaceSpritesheet(0, "gfx/grid/grid_poop_gold.png"); + npc.sprite.LoadGraphics(); + isChanged = true; + } + if (npc.state == NPC_STATE_INIT) + { + poop_init(npc); + return poop_stage_show(npc, true); + } + + if (!npc.HasEntityFlags(FLAG_THROWN)) + { + npc.friction *= POOP_REST_FRICTION; + poop_flies_update(npc); + } + if (!vector_is_zero(npc.targetPosition)) + { + Room& room = *g_game->room; + int cell = room.GetGridIndex(npc.targetPosition); + if (cell >= 0 && room.gridPaths[cell] % POOP_GRID_PATH_MOD < POOP_GRID_PATH) + room.gridPaths[cell] += POOP_GRID_PATH - room.gridPaths[cell] % POOP_GRID_PATH_MOD; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + } + if (!npc.isDead && npc.health > 1 && npc.controllerID != -1) + reconstruction_missing("NpcAI::ENTITY_POOP 00571280 (a controlled poop)"); + + bool isGone = false; + if (poop_hits_update(npc, isGone)) isChanged = true; + if (!isGone && isChanged) poop_stage_show(npc, false); +} + +// 00571280 The movable poop piles (Tainted ???'s spells among them): the main frame breaks them by their hits, the +// frame before it runs a pile's gas, aura or creep and the flight of a thrown one, which breaks on the enemy it hits. +void npc_poop_update(Entity_NPC& npc) +{ + switch (npc.aiCallPhase) + { + case AI_PHASE_COLLISION: return poop_touch(npc); + case AI_PHASE_INTERPOLATE: return poop_flight_update(npc); + case AI_PHASE_PRE_UPDATE: + if (npc.variant == POOP_NPC_STINKY) poop_gas_update(npc); + if (npc.variant == POOP_NPC_HOLY) poop_aura_update(npc); + if (npc.variant == POOP_NPC_BLACK) poop_creep_update(npc); + return poop_flight_update(npc); + default: return poop_frame(npc); + } +} diff --git a/src/npc_portal.cpp b/src/npc_portal.cpp index 5fc272d..3708fb9 100644 --- a/src/npc_portal.cpp +++ b/src/npc_portal.cpp @@ -44,7 +44,6 @@ constexpr std::array PORTAL_ENEMIES = { 10, 217, 85, 244, 16, 29, 18, 25, 61, 26, 234, 258, 208, 23, 24, 41, 34, 227, 212, 229, 32, 32, 15, 58, 56, 59, 55, 204, 38, 55, 86, 90, 260, 219, 86, 259, 252, 225, 55, 278, 258, 55, 10, 810, 814, 813, 817, 15, 806, 10, 810, 870, 813, 817, 872, 806}; -constexpr int ENTITY_SWARMER = 260; constexpr int SWARMER_PORTAL_VARIANT = 10; // The stage's chapter group of summons. The Void's rooms count as the chapter their layout comes from. @@ -120,7 +119,7 @@ static void portal_summon(Entity_NPC& npc) if (type == ENTITY_LEECH && group == PORTAL_GROUP_CATHEDRAL) variant = 2; else if (type == ENTITY_LEECH && group == PORTAL_GROUP_SHEOL) variant = 1; else if (type == ENTITY_FATTY) variant = 1; - else if (type == ENTITY_SWARMER) variant = SWARMER_PORTAL_VARIANT; + else if (type == ENTITY_THE_HAUNT) variant = SWARMER_PORTAL_VARIANT; else if (type == ENTITY_DEATHS_HEAD) variant = npc.HasEntityFlags(FLAG_CHARM) ? 1 : 0; auto* enemy = static_cast(g_game->Spawn( diff --git a/src/npc_render_parts.cpp b/src/npc_render_parts.cpp new file mode 100644 index 0000000..969d48f --- /dev/null +++ b/src/npc_render_parts.cpp @@ -0,0 +1,205 @@ +#include "npc_depths.h" +#include "beam_renderer.h" +#include "game.h" + +// The Peeping Fatty's eyes (its first two queued entities), Evis' cord (its variant), the Scourge's chain links and +// the Chimera's body, as their renders know them. +constexpr size_t PEEPING_FATTY_EYES = 2; +constexpr int EVIS_CORD = 10; +constexpr int EVIS_CORD_LAYER = 1; +constexpr int SCOURGE_CHAIN_LINK = 10; +constexpr int SCOURGE_LINK_SHOWN = NPC_STATE_JUMP; +constexpr int CHIMERA_BODY = 1; +constexpr int CHIMERA_BODY_LAYER = 2; +constexpr int CHIMERA_SPLIT = NPC_STATE_SPECIAL; + +// Horny Boys draw the segments they carry on their layers 3 to 5. +constexpr int HORNY_BOYS_FIRST_LAYER = 3; +constexpr int HORNY_BOYS_LAYERS = 3; + +// Hornfel's segments ride its layers 5 and 6, and its cart's front (its layer 4) follows the cart's layer 1, 224 up. +constexpr int HORNFEL_FIRST_SEGMENT_LAYER = 5; +constexpr int HORNFEL_CART_LAYER = 1; +constexpr int HORNFEL_FRONT_LAYER = 4; +constexpr float HORNFEL_CART_RAISE = 224; + +// The Ball and Chain's chain (layer 1) runs from 4 out of its anchor (raised 8, flattened) to 10 short of the ball. +// The anchor ring (layer 2) draws upright. +constexpr int CHAIN_LAYER = 1; +constexpr int CHAIN_ANCHOR_LAYER = 2; +constexpr float CHAIN_ANCHOR_OUT = 4; +constexpr float CHAIN_ANCHOR_FLATTEN = 0.6f; +constexpr float CHAIN_ANCHOR_RAISE = 8; +constexpr float CHAIN_BALL_INSET = 10; + +// 005579b0 The Peeping Fatty draws itself, then the overlays of its two eyes (or of the players they became in versus). +void peeping_fatty_render(Entity_NPC& npc, const Vector& offset) +{ + npc.Entity::Render(offset); + if (npc.variant != 0) return; + + bool isVersus = g_game->deathmatchManager.is_active(); + // The original reads both slots whatever the queue holds. Here a shorter queue draws fewer eyes. + for (size_t i = 0; i < std::min(PEEPING_FATTY_EYES, npc.entityDeque.size()); i++) + { + Entity* eye = npc.entityDeque[i].get(); + bool isDrawn = eye && ((isVersus && eye->type == ENTITY_PLAYER) || (eye->type >= ENTITY_FIRST_ENEMY && eye->type < ENTITY_EFFECT)); + if (isDrawn) static_cast(eye)->render_overlay(offset, false); + } +} + +// 004e07a0 Evis' cord draws its overlay, then its cord layer where its target stands. The rest of Evis draws plainly. +void evis_render(Entity_NPC& npc, const Vector& offset) +{ + if (npc.variant != EVIS_CORD) return npc.Entity::Render(offset); + + npc.render_overlay(offset, false); + Entity* target = npc.target.get(); + if (!target) return; + + Vector anchor = render_position_get(vector_add(target->pos, npc.posOffset), RENDER_SNAPPED); + npc.sprite.RenderLayer(EVIS_CORD_LAYER, SpriteDraw{vector_add(anchor, offset), {}, {}}); +} + +// 00589de0 A link of the Scourge's chain: the first draws the whole chain, the others draw themselves unflipped only +// while thrown. +void scourge_chain_render(Entity_NPC& npc, const Vector& offset) +{ + Entity* parent = npc.parent.get(); + bool isFirstLink = !parent || parent->type != ENTITY_SCOURGE || parent->variant != SCOURGE_CHAIN_LINK; + if (isFirstLink) return reconstruction_missing("NpcHelper::scourge_chain_render 005832c0"); + if (npc.state != SCOURGE_LINK_SHOWN) return; + + bool isFlipX = npc.sprite.isFlipX; + npc.sprite.isFlipX = false; + npc.Entity::Render(offset); + npc.sprite.isFlipX = isFlipX; +} + +// 004a1000 Once split, the Chimera's body draws its hidden head where its own third layer shows, flipped with it. +void chimera_child_render(Entity_NPC& npc, const Vector& offset) +{ + auto* head = static_cast(npc.child.get()); + bool isShown = npc.variant == CHIMERA_BODY && npc.state == CHIMERA_SPLIT && head && head->state == CHIMERA_SPLIT && + !head->isVisible; + if (!isShown) return; + const AnimationFrame* frame = npc.sprite.animState.GetLayerFrame(CHIMERA_BODY_LAYER); + if (!frame || !frame->isVisible) return; + + Vector savedPos = head->pos; + Vector savedOffset = head->sprite.offset; + Vector savedScale = head->sprite.scale; + head->pos = npc.pos; + float frameX = npc.sprite.GetLayer(CHIMERA_BODY_LAYER)->isFlipX ? -frame->pos.x : frame->pos.x; + head->sprite.offset = vector_make(frameX, frame->pos.y); + head->sprite.scale = frame->scale; + head->isVisible = true; + head->Render(offset); + head->sprite.offset = savedOffset; + head->sprite.scale = savedScale; + head->pos = savedPos; + head->isVisible = false; +} + +// A segment an NPC carries drawn at its own render position, placed by one of its layers' keyframe. +static void carried_segment_render(Entity_NPC& npc, size_t slot, const AnimationFrame& frame) +{ + Entity* segment = slot < npc.entityDeque.size() ? npc.entityDeque[slot].get() : nullptr; + if (!segment) return; + + segment->sprite.offset = frame.pos; + segment->sprite.rotation = frame.rotation; + segment->sprite.scale = frame.scale; + segment->sprite.Render(SpriteDraw{npc.renderPosition, {}, {}}); + segment->sprite.offset = {}; + segment->sprite.rotation = 0; + segment->sprite.scale = vector_make(1, 1); +} + +// Where the NPC draws on screen. +static void npc_render_position_update(Entity_NPC& npc, const Vector& offset) +{ + npc.renderPosition = vector_add(render_position_get(vector_add(npc.pos, npc.posOffset), RENDER_SNAPPED), offset); +} + +// 004bcfd0 Horny Boys draw themselves, then the three segments they carry where their layers 3 to 5 show. +void horny_boys_render(Entity_NPC& npc, const Vector& offset) +{ + npc.Entity::Render(offset); + npc_render_position_update(npc, offset); + const AnimationData* data = npc.sprite.animState.animData; + if (!data) return; + + for (const AnimationLayer& track : data->animLayers) + { + const AnimationFrame* frame = npc.sprite.animState.GetLayerFrame(track.layerId); + int slot = track.layerId - HORNY_BOYS_FIRST_LAYER; + if (frame && frame->isVisible && slot >= 0 && slot < HORNY_BOYS_LAYERS) carried_segment_render(npc, (size_t)slot, *frame); + } +} + +// 004bbe30 Hornfel draws layer by layer, its two carried segments where its layers 5 and 6 show. +void hornfel_render(Entity_NPC& npc, const Vector& offset) +{ + if (!npc.isExists || !npc.isVisible) return; + + npc_render_position_update(npc, offset); + const AnimationData* data = npc.sprite.animState.animData; + if (!data) return; + + for (const AnimationLayer& track : data->animLayers) + { + const AnimationFrame* frame = npc.sprite.animState.GetLayerFrame(track.layerId); + if (!frame || !frame->isVisible) continue; + + if (track.layerId == HORNFEL_FIRST_SEGMENT_LAYER || track.layerId == HORNFEL_FIRST_SEGMENT_LAYER + 1) + carried_segment_render(npc, (size_t)(track.layerId - HORNFEL_FIRST_SEGMENT_LAYER), *frame); + else npc.sprite.animState.RenderLayer(track.layerId, SpriteDraw{npc.renderPosition, {}, {}}, npc.sprite); + } +} + +// 004b7c30 Hornfel's cart front: its own layer 4 drawn in the cart's layer 1 keyframe, moved by its layer 4 keyframe and +// faded as the cart is. +void hornfel_minecart_render(Entity_NPC& npc, ANM2& cart, const Vector& position) +{ + if (!npc.isVisible) return; + const AnimationFrame* cartFrame = cart.animState.animData ? cart.animState.GetLayerFrame(HORNFEL_CART_LAYER) : nullptr; + const AnimationFrame* ownFrame = npc.sprite.animState.animData ? npc.sprite.animState.GetLayerFrame(HORNFEL_FRONT_LAYER) : nullptr; + if (!cartFrame || !ownFrame) return; + + AnimationLayer front{.frames = {*cartFrame}, .layerId = HORNFEL_FRONT_LAYER, .isVisible = true}; + front.frames[0].pos = vector_make(cartFrame->pos.x + ownFrame->pos.x, cartFrame->pos.y - HORNFEL_CART_RAISE + ownFrame->pos.y); + LayerState* layer = npc.sprite.GetLayer(HORNFEL_FRONT_LAYER); + layer->isVisible = true; + layer->color._tint[3] = cart.color._tint[3]; + front.RenderFrame(SpriteDraw{position, {}, {}}, 0, npc.sprite); + layer->isVisible = false; +} + +// 004f5f20 The Ball and Chain's chain from its anchor to the ball along layer 1, then the anchor ring upright. +void ball_and_chain_render(Entity_NPC& npc, const Vector& offset) +{ + if (vector_is_zero(npc.targetPosition)) return; + + Vector toBall = vector_normalized(vector_sub(npc.pos, npc.targetPosition)); + Vector anchor = vector_make(npc.targetPosition.x + toBall.x * CHAIN_ANCHOR_OUT, + toBall.y * CHAIN_ANCHOR_OUT * CHAIN_ANCHOR_FLATTEN + npc.targetPosition.y - CHAIN_ANCHOR_RAISE); + Vector start = vector_add(render_position_get(anchor, RENDER_SNAPPED), offset); + Vector ball = vector_add(vector_sub(npc.pos, vector_scale(toBall, CHAIN_BALL_INSET)), npc.posOffset); + Vector end = vector_add(render_position_get(ball, RENDER_SNAPPED), offset); + + npc.sprite.GetLayer(CHAIN_LAYER)->isVisible = true; + g_beamRenderer.Begin(npc.sprite, CHAIN_LAYER, BEAM_FRAME_OVERLAY, BEAM_COORDINATE_PIXELS); + g_beamRenderer.Add({.pos = start, .coordinate = 0, .width = 1}); + g_beamRenderer.Add({.pos = end, .coordinate = vector_length(vector_sub(end, start)), .width = 1}); + g_beamRenderer.End(); + npc.sprite.GetLayer(CHAIN_LAYER)->isVisible = false; + + Vector ring = vector_make(npc.targetPosition.x, npc.targetPosition.y - CHAIN_ANCHOR_RAISE); + float rotation = npc.sprite.rotation; + npc.sprite.rotation = 0; + npc.sprite.GetLayer(CHAIN_ANCHOR_LAYER)->isVisible = true; + npc.sprite.RenderLayer(CHAIN_ANCHOR_LAYER, SpriteDraw{vector_add(render_position_get(ring, RENDER_SNAPPED), offset), {}, {}}); + npc.sprite.GetLayer(CHAIN_ANCHOR_LAYER)->isVisible = false; + npc.sprite.rotation = rotation; +} diff --git a/src/npc_squirt.cpp b/src/npc_squirt.cpp index 1ee850f..81b5370 100644 --- a/src/npc_squirt.cpp +++ b/src/npc_squirt.cpp @@ -6,7 +6,6 @@ // The Squirt's variants: the brown one that splits into dips, and the dank one that splits into clots, leaving black // creep as it slides. -constexpr int SQUIRT_DANK = 1; constexpr int CLOTTY_CLOT = 1; constexpr ColorMod SQUIRT_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; constexpr ColorMod DANK_SQUIRT_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; diff --git a/src/npc_swarmer.cpp b/src/npc_swarmer.cpp new file mode 100644 index 0000000..4e45edd --- /dev/null +++ b/src/npc_swarmer.cpp @@ -0,0 +1,425 @@ +#include "boss_ai.h" +#include "menu_manager.h" +#include "entity_config.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "npc_basement.h" +#include "npc_caves.h" +#include "player_manager.h" +#include +#include + +// The floaters this AI runs: the Swarmer (spitting Pooters), the Tumor (the Planetoid, its variant, keeps shots in +// orbit), the Psy Tumor and Camillo Jr. +constexpr int TUMOR_PLANETOID = 1; + +constexpr ColorMod SWARMER_SPLAT_COLOR = {{1, 1, 1, 1}, {0.6f, 0.4f, 0.4f, 1}, {0, 0, 0}}; +constexpr float SWARMER_FRICTION = 0.77f; +constexpr float SWARMER_SHOOT_FRICTION = 0.2f; +constexpr float SWARMER_FLOAT_FRICTION = 0.9f; +constexpr float SWARMER_SPEED = 0.45f; +constexpr float SWARMER_SKATOLE_SPEED = 0.25f; +constexpr float PLANETOID_SPEED = 1.8f; +constexpr float SWARMER_FLEE_REACH = 80; +constexpr float SWARMER_FLEE_PUSH = 0.02f; +constexpr float SWARMER_AIM_REACH = 100; +constexpr float SWARMER_CONTROL_DEADZONE = 0.1f; +constexpr float SWARMER_SHOT_INTERVAL = 5; +constexpr float SWARMER_HURT_SCALE = 0.1f; +constexpr float SWARMER_SHRINK = 4; +constexpr float SWARMER_SPITS_PER_HURT = 100; +constexpr int SWARMER_FLOAT_FRAMES = 15; +constexpr float SWARMER_CONTROL_DRAIN = 60; +constexpr float SWARMER_CONTROL_FLOOR = -2; +constexpr float SWARMER_CONTROL_STEP = 0.1f; + +constexpr float SWARMER_DUST_HEIGHT = -34; +constexpr float SWARMER_DUST_SPREAD = 40; +constexpr float SWARMER_DUST_SPEED_MIN = 3; +constexpr float SWARMER_DUST_SPEED_RANGE = 3; +constexpr float SWARMER_DUST_SPIN_MIN = 2; +constexpr float SWARMER_DUST_SPIN_RANGE = 10; +constexpr int SWARMER_DUST_LIFE_MIN = 15; +constexpr uint32_t SWARMER_DUST_LIFE_RANGE = 15; +constexpr float SWARMER_DUST_ALPHA_MIN = 0.2f; +constexpr float SWARMER_DUST_ALPHA_RANGE = 0.5f; +constexpr int SWARMER_POOTER_LIMIT = 7; +constexpr float SWARMER_POOTER_SPEED = 10; +constexpr float SWARMER_POOTER_LEAD = 0.1f; +constexpr uint32_t SWARMER_FLY_ODDS = 100; +constexpr int SWARMER_FLY_LIMIT = 10; +constexpr float SWARMER_FLY_SPEED = 10; + +constexpr uint32_t TUMOR_SHOOT_ODDS = 100; +constexpr uint32_t PLANETOID_SHOOT_ODDS = 40; +constexpr size_t PLANETOID_LOW_ORBIT = 3; +constexpr size_t PLANETOID_FEW_ORBIT = 5; +constexpr int PLANETOID_BLOW_MIN = 3; +constexpr int PLANETOID_BLOW_MANY = 6; +constexpr uint32_t PLANETOID_BLOW_ODDS = 3; +constexpr float PLANETOID_BLOW_HURT = 0.05f; +constexpr uint32_t PLANETOID_EAGER_ODDS = 10; +constexpr float PLANETOID_EAGER = 0.1f; +constexpr float TUMOR_SHOT_SPEED = 10; +constexpr float TUMOR_SHOTS = 6; +constexpr float PLANETOID_SHOT_SPEED = 8; +constexpr float PLANETOID_ORBIT = 80; +constexpr float PLANETOID_ORBIT_FALL = -0.095f; +constexpr float PLANETOID_BLOOD_HEIGHT = -18; +constexpr float PLANETOID_BLOOD_DEPTH = -10; +constexpr float PLANETOID_BLOW_COOLDOWN = 60; +constexpr float PLANETOID_BLOW_RADIUS = 120; +constexpr float PLANETOID_BLOW_HEIGHT = -23; +constexpr float PLANETOID_BLOW_FALL = -0.085f; +constexpr float PLANETOID_BLOW_SPEED = 10; +constexpr float PLANETOID_RELEASE_FALL = -0.04f; +constexpr int CAMILLO_LASER_VARIANT = 2; +constexpr int CAMILLO_LASER_TIMEOUT = 3; +constexpr int CAMILLO_COOLDOWN = 60; +constexpr float CAMILLO_NULL_SCALE = 0.65f; +constexpr float CAMILLO_FRONT_DEPTH = 3000; +constexpr float CAMILLO_BACK_DEPTH = -10; + +static bool is_tumor_kind(const Entity_NPC& npc) +{ + return npc.type == ENTITY_TUMOR || npc.type == ENTITY_PSY_TUMOR || npc.type == ENTITY_CAMILLO_JR; +} + +// The shots a Planetoid keeps in orbit. +static int planetoid_shots_count(Entity_NPC& npc) +{ + return (int)std::ranges::count_if(npc.entityDeque, [](EntityPtr& shot) { return shot && shot->type == ENTITY_PROJECTILE; }); +} + +// Lets a shot fall out of orbit, as it was or flung out. +static void planetoid_shot_release(Entity_Projectile& shot) +{ + shot.projectileFlags &= ~PROJECTILE_ORBIT_PARENT; + shot.fallingAccel = PLANETOID_RELEASE_FALL; + shot.orbitDistance = 0; +} + +// The Planetoid's extra calls before its update and while interpolating: its orbit forgets the shots gone, and lets +// the rest fall once it dies. +static void planetoid_orbit_update(Entity_NPC& npc) +{ + while (!npc.entityDeque.empty() && !npc.entityDeque.front()) npc.entityDeque.pop_front(); + while (!npc.entityDeque.empty() && !npc.entityDeque.back()) npc.entityDeque.pop_back(); + for (EntityPtr& shot : npc.entityDeque) + if (shot && shot->type == ENTITY_PROJECTILE && npc.isDead) planetoid_shot_release(*static_cast(shot.get())); + if (npc.isDead) npc.ClearDequeRefs(); +} + +// The Tumors' shooting animation: up or down at their target, the Planetoid's own. +static std::string_view tumor_shoot_anim(Entity_NPC& npc, float aimY) +{ + if (npc.type == ENTITY_TUMOR && npc.variant == TUMOR_PLANETOID) return "Shoot"; + return aimY >= 0 ? "ShootDown" : "ShootUp"; +} + +// Whether the Planetoid blows its orbit away instead of adding to it: with enough shots, more likely with many or +// when hurt. A controlled one blows while its action is held. +static bool is_planetoid_blowing(Entity_NPC& npc, float hurt, bool isActionHeld) +{ + if (npc.controllerID != -1) return isActionHeld; + + int shots = planetoid_shots_count(npc); + if (shots < PLANETOID_BLOW_MIN) return false; + return !(Random() % PLANETOID_BLOW_ODDS != 0 && shots < PLANETOID_BLOW_MANY && hurt <= PLANETOID_BLOW_HURT); +} + +// Starting an attack: more often as it is hurt (or while a controlled Planetoid's action is held), once rested. +static void swarmer_attack_start(Entity_NPC& npc, Vector aim, float hurt, Vector input, bool isActionHeld) +{ + bool isPlanetoid = npc.type == ENTITY_TUMOR && npc.variant == TUMOR_PLANETOID; + if (isPlanetoid && npc.entityDeque.size() < PLANETOID_LOW_ORBIT && Random() % PLANETOID_EAGER_ODDS == 0) + hurt += PLANETOID_EAGER; + if (npc.type == ENTITY_SWARMER) + { + float shrink = 1 - hurt * SWARMER_SHRINK; + npc.shadowSize = shrink * npc.config->shadowSize; + npc.sprite.GetLayer(1)->size = vector_make(shrink, shrink); + } + + bool isWilling = (npc.controllerID == -1 || !vector_is_zero(input)) && npc.v1.x < hurt * SWARMER_SPITS_PER_HURT; + if (!(isWilling || isActionHeld) || npc.projectileCooldown != 0) return; + + if (npc.sprite.animState.animData && npc.sprite.animState.animData->isLooping) npc.v1.x += 1; + if (npc.type == ENTITY_SWARMER) npc.sprite.Play("Attack"); + else if (is_tumor_kind(npc)) + { + std::string_view anim = tumor_shoot_anim(npc, aim.y); + if (isPlanetoid && is_planetoid_blowing(npc, hurt, isActionHeld)) anim = "Blow"; + npc.sprite.Play(anim); + npc.targetPosition = aim; + } + npc.sprite.isFlipX = aim.x < 0; + npc.controllerMovement = npc.controllerID == -1 ? Vector{} : npc.GetControllerMovementInput(SWARMER_CONTROL_DEADZONE); +} + +// The Swarmer's spit: a puff of dust from its side, then a Pooter per spit it owes, flung toward its aim. +static void swarmer_spit(Entity_NPC& npc, Vector aim) +{ + npc.PlaySound(SOUND_WHEEZY_COUGH, 1, 2, false, 1); + float side = npc.sprite.isFlipX ? -1.0f : 1.0f; + float angle = (random_unit() * SWARMER_DUST_SPREAD - SWARMER_DUST_SPREAD / 2) * DEGREES_TO_RADIANS; + Vector direction = vector_make(side * std::cos(angle) - std::sin(angle) * 0.0f, side * std::sin(angle) + std::cos(angle) * 0.0f); + Vector velocity = vector_scale(direction, random_unit() * SWARMER_DUST_SPEED_RANGE + SWARMER_DUST_SPEED_MIN); + auto* dust = static_cast(g_game->Spawn({.position = vector_add(npc.pos, vector_make(0, SWARMER_DUST_HEIGHT)), + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, + .seed = Random()})); + float spin = vector_dot(vector_sub(dust->pos, npc.pos), vector_make(velocity.y, -velocity.x)) < 0 ? -1.0f : 1.0f; + dust->rotation = (random_unit() * SWARMER_DUST_SPIN_RANGE + SWARMER_DUST_SPIN_MIN) * spin; + dust->timeout = (int)(Random() % SWARMER_DUST_LIFE_RANGE) + SWARMER_DUST_LIFE_MIN; + dust->lifespan = dust->timeout; + ColorMod dustColor = COLOR_DEFAULT; + dustColor._tint[3] = random_unit() * SWARMER_DUST_ALPHA_RANGE + SWARMER_DUST_ALPHA_MIN; + dust->SetColor(dustColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + dust->Update(); + + if (npc.controllerID != -1) npc.v1.y = npc.v1.x - SWARMER_CONTROL_STEP; + while (npc.v1.y < npc.v1.x) + { + npc.v1.y += random_unit() + 1; + if (npc.GetAliveEnemyCount() >= SWARMER_POOTER_LIMIT) continue; + + float x = std::cos(random_unit() * PI_F * 2) * SWARMER_POOTER_SPEED; + float y = std::sin(random_unit() * PI_F * 2) * SWARMER_POOTER_SPEED; + Vector pooterVelocity = vector_make(aim.x * SWARMER_POOTER_LEAD + x, aim.y * SWARMER_POOTER_LEAD + y); + g_game->Spawn({.position = npc.pos, .velocity = pooterVelocity, .spawner = &npc, .type = ENTITY_POOTER, .seed = Random()}); + } +} + +// One shot as FireProjectiles fires it alone, kept to be sent into orbit. +static Entity_Projectile* planetoid_shot_fire(Entity_NPC& npc, Vector velocity, const ProjectileParams& params) +{ + auto* shot = static_cast(g_game->Spawn({.position = vector_add(npc.pos, params.positionOffset), + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_PROJECTILE, + .variant = params.variant, + .seed = Random()})); + npc.projectile_params_apply(*shot, params); + npc.fire_projectile_from_params(shot); + return shot; +} + +// The Planetoid's shot: one or two more shots sent into orbit, or with its Blow the whole orbit flung out in a fart. +static void planetoid_shoot(Entity_NPC& npc) +{ + if (npc.sprite.IsPlaying("Blow")) + { + npc.v2.x = PLANETOID_BLOW_COOLDOWN; + game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = PLANETOID_BLOW_RADIUS}); + for (EntityPtr& entry : npc.entityDeque) + { + if (!entry || entry->type != ENTITY_PROJECTILE) continue; + + auto& shot = *static_cast(entry.get()); + shot.orbitDistance = 0; + shot.height = PLANETOID_BLOW_HEIGHT; + shot.fallingSpeed = 0; + shot.fallingAccel = PLANETOID_BLOW_FALL; + shot.projectileFlags &= ~PROJECTILE_ORBIT_PARENT; + shot.velocity = vector_resized(shot.velocity, PLANETOID_BLOW_SPEED); + } + npc.ClearDequeRefs(); + return; + } + + int count = (int)(Random() & 1) + 1; + float angle = random_unit() * FULL_TURN_DEGREES; + float step = FULL_TURN_DEGREES / (float)count; + ProjectileParams params; + params.bulletFlags = PROJECTILE_ORBIT_PARENT | PROJECTILE_NO_WALL_COLLIDE | + ((npc.initSeed & 1) == 0 ? PROJECTILE_ORBIT_CW : PROJECTILE_ORBIT_CCW); + params.targetPosition = npc.pos; + for (int i = 0; i < count; i++, angle += step) + { + Entity_Projectile* shot = planetoid_shot_fire(npc, vector_scale(vector_from_angle(angle), PLANETOID_SHOT_SPEED), params); + shot->orbitDistance = PLANETOID_ORBIT; + shot->fallingSpeed = 0; + shot->fallingAccel = PLANETOID_ORBIT_FALL; + shot->parent = &npc; + npc.entityDeque.emplace_back(); + npc.entityDeque.back() = shot; + } + Entity* blood = blood_explosion_spawn(3, npc.pos, vector_make(0, PLANETOID_BLOOD_HEIGHT), COLOR_DEFAULT, {}); + static_cast(blood)->FollowParent(&npc); + blood->renderDepthOffset = PLANETOID_BLOOD_DEPTH; + npc.PlaySound(SOUND_WHEEZY_COUGH, 1, 2, false, 1); +} + +// The Tumors' shots on their Shoot event: a spray, a homing spray (the Psy Tumor), the Planetoid's orbit or Camillo +// Jr.'s beam while on screen. +static void tumor_shoot(Entity_NPC& npc, float aimY) +{ + if (npc.type == ENTITY_CAMILLO_JR && npc.projectileCooldown > 0) npc.projectileCooldown--; + if (!npc.sprite.animState.animData || !npc.sprite.animState.IsEventTriggered("Shoot")) return; + + if (npc.type == ENTITY_TUMOR && npc.variant == TUMOR_PLANETOID) return planetoid_shoot(npc); + if (npc.type == ENTITY_TUMOR || npc.type == ENTITY_PSY_TUMOR) + { + npc.PlaySound(SOUND_WHEEZY_COUGH, 1, 2, false, 1); + ProjectileParams params; + if (npc.type == ENTITY_PSY_TUMOR) params.bulletFlags |= PROJECTILE_SMART; + npc.FireProjectiles(npc.pos, vector_make(TUMOR_SHOT_SPEED, TUMOR_SHOTS), PROJECTILES_RING, params); + return; + } + if (!g_game->room->camera->IsPosVisible(npc.pos)) return; + + // The original reads the ShootPos null unchecked. Here a sprite without one fires from the center. + const NullFrame* shootPos = npc.sprite.GetNullFrame("ShootPos"); + Vector offset = shootPos ? vector_scale(shootPos->pos, 1 / CAMILLO_NULL_SCALE) : Vector{}; + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = npc.pos, + .posOffset = offset, + .source = &npc, + .angleDegrees = vector_angle(npc.targetPosition), + .timeout = CAMILLO_LASER_TIMEOUT, + .variant = CAMILLO_LASER_VARIANT}); + laser->renderDepthOffset = aimY >= 0 ? CAMILLO_FRONT_DEPTH : CAMILLO_BACK_DEPTH; + laser->Update(); + npc.projectileCooldown = CAMILLO_COOLDOWN; +} + +// Its idle floating: the Swarmer idles, the Tumors float up or down toward their target. +static void swarmer_float(Entity_NPC& npc, float aimY) +{ + if (npc.type == ENTITY_SWARMER) npc.sprite.Play("Idle"); + else if (is_tumor_kind(npc)) + { + std::string_view anim = aimY >= 0 ? "FloatDown" : "FloatUp"; + if (npc.type == ENTITY_TUMOR && npc.variant == TUMOR_PLANETOID) anim = "Float"; + npc.sprite.Play(anim); + } + npc.stateFrame = 0; +} + +// It drifts diagonally (slower for a Swarmer while a player has Skatole), steered by its controller, backing away +// from its target when feared. Confused, it wanders. +static void swarmer_drift(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_CONFUSION) && npc.controllerID == -1) + { + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return; + } + + float speed = SWARMER_SPEED; + bool isSkatole = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SKATOLE, LAZARUS_SHARE_CHECK) && + npc.type == ENTITY_SWARMER && !npc.HasEntityFlags(FLAG_FRIENDLY); + if (isSkatole) speed = SWARMER_SKATOLE_SPEED; + if (npc.type == ENTITY_TUMOR && npc.variant == TUMOR_PLANETOID) speed *= PLANETOID_SPEED; + Vector push = vector_make(npc.velocity.x < 0 ? -speed : speed, npc.velocity.y < 0 ? -speed : speed); + if (npc.controllerID != -1) + { + float steer = vector_length(push) * 0.5f; + push = vector_add(push, vector_scale(npc.GetControllerInput(0), steer)); + } + npc_push(npc, push); + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.controllerID != -1) return; + + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float flee = std::clamp((SWARMER_FLEE_REACH - vector_length(away)) * SWARMER_FLEE_PUSH, 0.0f, 1.0f); + npc_push(npc, vector_resized(away, flee)); +} + +// 00518e20 The Swarmer (91), the Tumor and Planetoid (229), Camillo Jr. (230) and the Psy Tumor (253): they drift +// about bouncing off walls and attack more often as they are hurt. The Swarmer spits Pooters (and Attack Flies now +// and then), shrinking, and leaves a Boom Fly. The Tumors spray shots, Camillo Jr. fires a beam, and the Planetoid +// gathers shots in orbit until it blows them away. +void npc_swarmer_update(Entity_NPC& npc) +{ + bool isPlanetoid = npc.type == ENTITY_TUMOR && npc.variant == TUMOR_PLANETOID; + int ticks = npc_ticks_get(npc); + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE || npc.aiCallPhase == AI_PHASE_INTERPOLATE) return planetoid_orbit_update(npc); + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.v1 = {}; + npc.stateFrame = 0; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.velocity = random_direction(); + if (npc.type == ENTITY_SWARMER) npc.splatColor = SWARMER_SPLAT_COLOR; + else if (npc.type == ENTITY_CAMILLO_JR) npc.splatColor = COLOR_DEFAULT; + if (isPlanetoid) npc.aiCallFlags |= AI_CALL_PRE_UPDATE | AI_CALL_INTERPOLATE; + return; + } + + npc.friction *= SWARMER_FRICTION; + Vector aim = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + Vector input{}; + bool isActionHeld = isPlanetoid && npc.IsControllerActionPressed(ACTION_ITEM); + if (npc.controllerID != -1) + { + input = npc.GetControllerMovementInput(SWARMER_CONTROL_DEADZONE); + if (isPlanetoid && npc.IsControllerActionPressed(ACTION_ITEM)) input = vector_make(0, 1); + aim = vector_scale(input, SWARMER_AIM_REACH); + } + + float hurt = (1 - npc.health / npc.maxHitPoints) * SWARMER_HURT_SCALE; + if (npc.GetIntervalTicks(SWARMER_SHOT_INTERVAL, 0) == 0 && vector_is_zero(input)) + { + if (npc.stateFrame == 0) npc.sprite.isFlipX = npc.velocity.x < 0; + } + else swarmer_attack_start(npc, aim, hurt, input, isActionHeld); + + if (npc.type == ENTITY_SWARMER && npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) + swarmer_spit(npc, aim); + if (npc.controllerID != -1) + { + if (npc.v1.x > SWARMER_CONTROL_FLOOR) + npc.v1.x = std::max(npc.v1.x - npc.speedMultiplier / SWARMER_CONTROL_DRAIN, SWARMER_CONTROL_FLOOR); + if (!npc.sprite.animState.animData || !npc.sprite.animState.animData->isLooping) + { + npc.UpdateControllerMovement(false); + if (!vector_is_zero(npc.controllerMovement)) npc.targetPosition = npc.controllerMovement; + } + } + + if (npc.type == ENTITY_SWARMER) + { + bool isFly = Random() % SWARMER_FLY_ODDS == 0 && npc.GetAliveEnemyCount() < SWARMER_FLY_LIMIT && + !npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK); + if (isFly) + { + float y = std::sin(random_unit() * PI_F * 2) * SWARMER_FLY_SPEED; + float x = std::cos(random_unit() * PI_F * 2) * SWARMER_FLY_SPEED; + Entity* fly = g_game->Spawn({.position = npc.pos, .velocity = vector_make(x, y), .spawner = &npc, + .type = ENTITY_ATTACKFLY, .seed = Random()}); + fly->ClearEntityFlags(FLAG_APPEAR); + } + } + else if (is_tumor_kind(npc) && npc.controllerID == -1) + { + bool isShot = Random() % TUMOR_SHOOT_ODDS == 0 || + (isPlanetoid && npc.entityDeque.size() < PLANETOID_FEW_ORBIT && Random() % PLANETOID_SHOOT_ODDS == 0); + if (isShot && !npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK) && npc.projectileCooldown == 0) + { + npc.sprite.Play(tumor_shoot_anim(npc, aim.y)); + npc.targetPosition = aim; + npc.sprite.isFlipX = aim.x < 0; + } + } + + npc.stateFrame += ticks; + if (npc.v2.x > 0) npc.v2.x -= npc.speedMultiplier; + if (npc_anim_is_done(npc)) swarmer_float(npc, aim.y); + else if (npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK) && npc.type != ENTITY_SWARMER && + npc.IsFrame(SWARMER_FLOAT_FRAMES, (int)npc.index)) + swarmer_float(npc, aim.y); + if (is_tumor_kind(npc)) tumor_shoot(npc, aim.y); + + const AnimationData* data = npc.sprite.animState.animData; + bool isShooting = data && ((npc.type == ENTITY_CAMILLO_JR && data->name == "ShootUp") || data->name == "ShootDown"); + npc.friction *= isShooting ? SWARMER_SHOOT_FRICTION : SWARMER_FLOAT_FRICTION; + swarmer_drift(npc); + + if (!npc.isDead || npc.type != ENTITY_SWARMER || npc.championRegenCount != 0) return; + Entity* boomFly = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_BOOMFLY, .seed = Random()}); + boomFly->entityGridCollisionClass = GRIDCOLL_WALLS; +} diff --git a/src/npc_vis_fatty.cpp b/src/npc_vis_fatty.cpp new file mode 100644 index 0000000..721a9c0 --- /dev/null +++ b/src/npc_vis_fatty.cpp @@ -0,0 +1,600 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_config.h" +#include "entity_laser.h" +#include "npc_basement.h" +#include +#include + +// A cord's points sit in vectorDeque1 as triples: the point, its velocity, and its height with the height's speed. +// UpdateCordChain writes the next step into vectorDeque2, which render_overlay draws. +constexpr size_t CORD_STRIDE = 3; +constexpr float CORD_GRAVITY = 0.4f; +constexpr float CORD_SPRING = 0.3f; +constexpr float CORD_DAMPING = 0.95f; +constexpr float CORD_FLOOR_FRICTION = 0.85f; +constexpr float CORD_TAUT_START = 90; +constexpr float CORD_TAUT_SPAN = 110; +constexpr float CORD_STRAIGHTEN = 0.8f; +constexpr float CORD_HALF_STEP = 0.5f; +constexpr float DOGMA_CORD_SEGMENT = 16; +constexpr float CORD_SEGMENT_PER_STRETCH = 10; + +// 004e8fa0 Steps a cord (Dogma's tethers, Evis's, the Vis Fatty's): each point springs toward its neighbours a +// segment apart and falls, sliding to a stop on the floor, and the whole cord straightens as its ends draw apart. +// A half step (on an interpolation) is drawn but not kept. +void Entity_NPC::UpdateCordChain(bool isHalfScale) +{ + float step = isHalfScale ? CORD_HALF_STEP : 1; + float segment = type == ENTITY_DOGMA ? DOGMA_CORD_SEGMENT + : type == ENTITY_EVIS ? aiFloat + : (v1.x + 1) * CORD_SEGMENT_PER_STRETCH; + std::deque& now = vectorDeque1; + std::deque& next = vectorDeque2; + if (next.size() < now.size()) next.resize(now.size()); + + // The pull of a neighbour j on point i: a spring of the segment's length, damped by their relative speed. + auto spring = [&](size_t i, size_t j, float force[3]) { + float delta[3] = {now[i].x - now[j].x, now[i].y - now[j].y, now[i + 2].x - now[j + 2].x}; + float length = std::sqrt(delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2]); + float stretch = length - segment; + float speed[3] = {now[i + 1].x - now[j + 1].x, now[i + 1].y - now[j + 1].y, now[i + 2].y - now[j + 2].y}; + for (int axis = 0; axis < 3; axis++) + force[axis] = force[axis] - delta[axis] / length * stretch * CORD_SPRING - speed[axis] * CORD_SPRING; + }; + + for (size_t i = 0; i < now.size(); i += CORD_STRIDE) + { + float force[3] = {0, 0, CORD_GRAVITY}; + if (i != 0) spring(i, i - CORD_STRIDE, force); + if (i + CORD_STRIDE < now.size()) spring(i, i + CORD_STRIDE, force); + + next[i] = vector_add(now[i], vector_scale(now[i + 1], step)); + next[i + 1] = vector_scale(vector_make(force[0] * step + now[i + 1].x, force[1] * step + now[i + 1].y), + CORD_DAMPING); + next[i + 2] = vector_make(step * now[i + 2].y + now[i + 2].x, (force[2] * step + now[i + 2].y) * CORD_DAMPING); + if (next[i + 2].x > 0) + { + next[i + 2] = {}; + next[i + 1] = vector_scale(next[i + 1], CORD_FLOOR_FRICTION); + } + + const Vector& first = now.front(); + const Vector& last = now[now.size() - CORD_STRIDE]; + float taut = std::clamp((vector_length(vector_sub(last, first)) - CORD_TAUT_START) / CORD_TAUT_SPAN, 0.0f, 1.0f); + if (taut <= 0) continue; + + float along = (float)(i / CORD_STRIDE) / (float)(now.size() / CORD_STRIDE - 1); + Vector line = vector_add(vector_scale(first, 1 - along), vector_scale(last, along)); + float lineHeight = along * now.back().x + (1 - along) * now[2].x; + Vector pull = vector_sub(vector_scale(vector_sub(line, now[i]), CORD_STRAIGHTEN), + vector_scale(now[i + 1], CORD_STRAIGHTEN)); + next[i + 1] = vector_add(next[i + 1], vector_scale(pull, taut * step)); + next[i + 2].y += ((lineHeight - now[i + 2].x) * CORD_STRAIGHTEN - now[i + 2].y * CORD_STRAIGHTEN) * taut * step; + } + if (!isHalfScale) now = next; +} + +// The Vis Fatty (variant 0) drags its Fetal Demon (variant 1) on a cord of six points hung from its CordPos null. +// It walks to its target, pumps blood down the cord to its demon on an attack, and without its demon it rages back and +// forth breathing a laser. Damage it takes fills a rage meter (v1.y) that lets it attack sooner. +constexpr int FETAL_DEMON = 1; +constexpr int CORD_POINTS = 6; +constexpr float CORD_POINT_SPACING = 5; +constexpr float CORD_HANG = -20; +constexpr float CORD_CHILD_DRAG = 0.2f; +constexpr int CORD_SETTLE_STEPS = 10; +constexpr int CORD_SETTLE_FRAMES = 2; +constexpr float DEMON_SPAWN_SPREAD = 40; +constexpr float DEMON_SPAWN_DROP = 20; +constexpr int VIS_CORD_LAYER = 2; + +// The cord's leash: loose to 75 (105 while the demon charges) times its swell, then pulling both ends together. +constexpr float LEASH_REACH = 75; +constexpr float LEASH_REACH_CHARGING = 105; +constexpr float VIS_LEASH_PULL = 0.1f; +constexpr float LEASH_PULL_CHARGING = 0.3f; +constexpr float LEASH_SHARE = 0.3f; + +// Its walk and attack: it pumps blood once its demon has charged 27 frames, 1 time in 7 (always with rage over 7). +constexpr uint64_t VIS_FATTY_DAZED = FLAG_FEAR | FLAG_SHRINK; +constexpr float VIS_FATTY_WALK_SPEED = 0.3f; +constexpr int VIS_FATTY_PATH_MARKER = 900; +constexpr float VIS_FATTY_FRICTION = 0.8f; +constexpr int PUMP_CHARGE_FRAMES = 26; +constexpr uint32_t PUMP_ODDS = 7; +constexpr float RAGE_FULL = 7; +constexpr float VIS_RAGE_DRAIN = 0.02f; +constexpr uint32_t VIS_SPLAT_ODDS = 10; +constexpr float VIS_SPLAT_SIZE_MIN = 0.2f; +constexpr float VIS_SPLAT_SIZE_RANGE = 0.5f; +constexpr uint32_t GRUNT_ODDS = 3; +constexpr int GRUNT_DELAY = 60; + +// The pump: a fart cloud and red creep about it, the cord swelling to 1.5 and a pulse down it every other frame. +constexpr float PUMP_FART_RADIUS = 120; +constexpr ColorMod PUMP_FART_COLOR = {{1, 1, 1, 1}, {0.8f, 0, 0, 1}, {0, 0, 0}}; +constexpr float PUMP_CREEP_SCALE = 2; +constexpr int PUMP_CREEP_FRAMES = 150; +constexpr float PUMP_SWELL = 1.5f; +constexpr int PUMP_DEMON_DELAY = 15; +constexpr float SWELL_DRAIN = 0.03f; +constexpr float PULSE_VOLUME = 0.8f; +constexpr float PULSE_CREEP_SCALE = 0.5f; +constexpr int PULSE_CREEP_FRAMES = 60; +constexpr float PULSE_END_CREEP_SCALE = 1.5f; +constexpr int PULSE_END_CREEP_FRAMES = 90; +constexpr int PULSE_BLOOD = 2; +constexpr int PULSE_END_BLOOD = 3; +constexpr float PULSE_BLOOD_DEPTH = 60; + +// Its rage without its demon: it charges along a diagonal away from its target, breathing a laser behind it and +// sparks, bouncing off walls, healed a quarter. +constexpr float RAGE_VOLUME = 0.8f; +constexpr float RAGE_DIAGONAL = 0.70710677f; +constexpr ColorMod VIS_RAGE_TRACER_COLOR = tint_color_make(0.6f, 0.05f, 0, 0.8f); +constexpr float RAGE_TRACER_RISE = -20; +constexpr int RAGE_TRACER_FRAMES = 30; +constexpr float VIS_RAGE_TRACER_SCALE = 4; +constexpr float HEAL_SHARE = 0.25f; +constexpr float RAGE_FRICTION = 0.95f; +constexpr float RAGE_MASS = 6; +constexpr float RAGE_PUSH = 0.55f; +constexpr int RAGE_LASER_VARIANT = 1; +constexpr int RAGE_LASER_FRAMES = 10; +constexpr float RAGE_MOUTH = -31; +constexpr float RAGE_LASER_IN_FRONT = 0.5f; +constexpr float RAGE_LASER_FRONT_DEPTH = 3000; +constexpr float RAGE_LASER_BACK_DEPTH = -10; +constexpr float RAGE_SPARK_SPREAD = 20; +constexpr float RAGE_SPARK_SPEED_MIN = 5; +constexpr float RAGE_SPARK_SPEED_RANGE = 5; +constexpr float RAGE_SPARK_SCALE_MIN = 0.6f; +constexpr float RAGE_SPARK_SCALE_RANGE = 0.3f; +constexpr float VIS_WALL_BOUNCE = 0.2f; + +// The burst when the cord snaps: blood and a splat at each point. +constexpr int SNAP_BLOOD = 1; +constexpr float SNAP_BLOOD_DEPTH = 10; +constexpr float SNAP_SPLAT_SCALE = 0.4f; + +// The Fetal Demon: it crawls after its target 0.8 a frame and charges (2.6 a frame, steering in its last 20 frames) +// while its Vis Fatty is in reach and 1 time in 5 (1 in 3 with the Vis Fatty enraged), for 30 to 44 frames, then rests +// 60 to 89. Alone it wanders on, heavier. +constexpr float DEMON_CRAWL = 0.8f; +constexpr float DEMON_CHARGE_REACH = 57600; +constexpr float DEMON_RAGE_REACH = 160000; +constexpr uint32_t DEMON_CHARGE_ODDS = 5; +constexpr uint32_t DEMON_RAGE_ODDS = 3; +constexpr float DEMON_LEAD = 0.2f; +constexpr uint32_t DEMON_CHARGE_RANGE = 15; +constexpr int DEMON_CHARGE_MIN = 30; +constexpr uint32_t DEMON_REST_RANGE = 30; +constexpr int DEMON_REST_MIN = 60; +constexpr int DEMON_START_REST = 15; +constexpr int DEMON_STEER_FRAMES = 20; +constexpr float DEMON_STEER = 0.5f; +constexpr float DEMON_CHARGE_SPEED = 2.6f; +constexpr uint64_t DEMON_DAZED = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; +constexpr float DEMON_DRIFT = 1.1764705f; +constexpr float DEMON_LONE_SPEED = 0.5f; +constexpr float DEMON_LONE_MASS = 8; + +// The cord's points between the Vis Fatty and its demon, still, hanging 20 low at the demon's end. +static void cord_lay(Entity_NPC& npc) +{ + Vector from = npc.vectorDeque1[0]; + float fromHeight = npc.vectorDeque1[2].x; + for (int point = 1; point < CORD_POINTS; point++) + { + float along = (float)point / CORD_POINT_SPACING; + size_t i = point * CORD_STRIDE; + npc.vectorDeque1[i] = vector_add(from, vector_scale(vector_sub(npc.child->pos, from), along)); + npc.vectorDeque1[i + 1] = {}; + npc.vectorDeque1[i + 2] = vector_make((CORD_HANG - fromHeight) * along + fromHeight, 0); + } + npc.vectorDeque2 = npc.vectorDeque1; +} + +// The cord's ends follow the Vis Fatty's CordPos and the demon, then it steps (laid anew on the room's first frames), +// and a stretched cord pulls the two together. +static void cord_update(Entity_NPC& npc) +{ + Entity& demon = *npc.child; + std::deque& cord = npc.vectorDeque1; + Vector anchor = npc.GetNullOffset("CordPos"); + cord[0] = vector_make(anchor.x + npc.pos.x, npc.pos.y); + cord[1] = npc.velocity; + cord[2] = vector_make(anchor.y, 0); + cord[cord.size() - 3] = demon.pos; + cord[cord.size() - 2] = vector_scale(demon.velocity, CORD_CHILD_DRAG); + cord[cord.size() - 1] = vector_make(CORD_HANG, 0); + + Room& room = *g_game->room; + if (!room.isInitialized || g_game->frameCount - room.enterFrame < CORD_SETTLE_FRAMES) cord_lay(npc); + else npc.UpdateCordChain(npc.aiCallPhase == AI_PHASE_INTERPOLATE); + + Vector apart = vector_sub(demon.pos, npc.pos); + float distance = vector_length(apart); + bool isActor = (g_game->deathmatchManager.is_active() && demon.type == ENTITY_PLAYER) || + (demon.type >= ENTITY_FIRST_ENEMY && demon.type < ENTITY_EFFECT); + bool isCharging = isActor && static_cast(demon).state == NPC_STATE_ATTACK; + float reach = (npc.v1.x + 1) * (isCharging ? LEASH_REACH_CHARGING : LEASH_REACH); + if (distance <= reach) return; + + Vector pull = vector_scale(apart, (distance - reach) * (isCharging ? LEASH_PULL_CHARGING : VIS_LEASH_PULL) / distance); + npc.velocity = vector_add(npc.velocity, vector_scale(pull, LEASH_SHARE * npc.speedMultiplier)); + demon.velocity = vector_sub(demon.velocity, vector_scale(pull, demon.speedMultiplier)); +} + +// The cord snaps once the demon is gone or the Vis Fatty dies: blood bursts along it and it is no longer drawn. +static void cord_snap(Entity_NPC& npc) +{ + npc.i1 = 1; + for (size_t i = 0; i < npc.vectorDeque1.size(); i += CORD_STRIDE) + { + Vector at = npc.vectorDeque1[i]; + Entity* blood = g_game->Spawn({.position = at, + .subType = SNAP_BLOOD, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + blood->SetColor(COLOR_DEFAULT, -1, 255, false, true); + blood->sprite.offset = vector_make(0, npc.vectorDeque1[i + 2].x); + blood->renderDepthOffset = SNAP_BLOOD_DEPTH; + Entity* splat = g_game->Spawn( + {.position = at, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + splat->sprite.scale = vector_make(SNAP_SPLAT_SCALE, SNAP_SPLAT_SCALE); + splat->Update(); + } + npc.vectorDeque2.clear(); +} + +// A red creep pool of a size that dries in some frames. +static void creep_spawn(Entity_NPC& npc, const Vector& at, float scale, int frames) +{ + auto* creep = static_cast(g_game->Spawn( + {.position = at, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = Random()})); + creep->sprite.scale = vector_make(scale, scale); + creep->SetTimeout(frames); + creep->Update(); +} + +// Its demon lost: it rages along a diagonal away from its target, with a tracer of where it goes, healing a quarter. +static void vis_fatty_rage_start(Entity_NPC& npc) +{ + npc.state = NPC_STATE_SPECIAL; + npc.projectileDelay = 0; + npc.PlaySound(SOUND_MOUTH_FULL, RAGE_VOLUME, 2, false, 1); + npc.sprite.Play("RageStart"); + Entity* target = npc.GetPlayerTarget(); + npc.targetPosition = vector_make(target->pos.x - npc.pos.x > 0 ? -RAGE_DIAGONAL : RAGE_DIAGONAL, + target->pos.y - npc.pos.y > 0 ? -RAGE_DIAGONAL : RAGE_DIAGONAL); + float behind = vector_angle(npc.targetPosition) + DEGREES_PER_TURN / 2; + following_effect_spawn(npc, {.offset = vector_make(0, RAGE_TRACER_RISE), + .targetPosition = vector_from_angle(behind), + .color = VIS_RAGE_TRACER_COLOR, + .scale = VIS_RAGE_TRACER_SCALE, + .timeout = RAGE_TRACER_FRAMES}); + if (npc.health < npc.maxHitPoints) + npc.health = std::min(npc.health + npc.maxHitPoints * HEAL_SHARE, npc.maxHitPoints); +} + +// Its first frame: the demon dropped beside it, the cord laid between them and settled, and its extra AI calls. +static void vis_fatty_init(Entity_NPC& npc) +{ + if (npc.subtype == 0) + { + uint32_t seed = npc.dropRNG.Next(); + Vector at = vector_make(random_unit() * DEMON_SPAWN_SPREAD - DEMON_SPAWN_SPREAD / 2 + npc.pos.x, + npc.pos.y + DEMON_SPAWN_DROP); + Entity* demon = g_game->Spawn( + {.position = at, .spawner = &npc, .type = ENTITY_VIS_FATTY, .variant = FETAL_DEMON, .seed = seed}); + npc.child = demon; + demon->parent = &npc; + npc.subtype = 1; + } + npc.state = NPC_STATE_MOVE; + npc.sprite.Play("WalkVert"); + npc.sprite.PlayOverlay("Cord"); + npc.sprite.GetLayer(VIS_CORD_LAYER)->isVisible = false; + if (npc.child) + { + for (int point = 0; point < CORD_POINTS; point++) + { + float along = (float)point / CORD_POINT_SPACING; + npc.vectorDeque1.push_back(vector_add(npc.pos, vector_scale(vector_sub(npc.child->pos, npc.pos), along))); + npc.vectorDeque1.push_back({}); + npc.vectorDeque1.push_back(vector_make(CORD_HANG, 0)); + } + npc.vectorDeque2 = npc.vectorDeque1; + for (int i = 0; i < CORD_SETTLE_STEPS; i++) npc.UpdateCordChain(false); + } + npc.aiCallFlags |= AI_CALL_PRE_UPDATE | AI_CALL_INTERPOLATE | AI_CALL_COLLISION; +} + +// Its walk to its target (or away when feared or shrunk), and the pump once its demon has charged long enough. +static void vis_fatty_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", 0.1f); + if (!npc.HasEntityFlags(VIS_FATTY_DAZED)) + { + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), VIS_FATTY_WALK_SPEED, VIS_FATTY_PATH_MARKER, + DIRECT_PATH_FAR); + Entity_NPC* demon = npc.ChildNPC(); + if (demon && demon->state == NPC_STATE_ATTACK && demon->projectileCooldown > PUMP_CHARGE_FRAMES && + (Random() % PUMP_ODDS == 0 || npc.v1.y > RAGE_FULL)) + { + npc.v1.y = 0; + npc.state = NPC_STATE_ATTACK; + npc.PlaySound(SOUND_ANGRY_GURGLE, 1, 2, false, 1); + npc.AnimWalkFrame("AttackHori", "AttackVert", 0); + } + } + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= VIS_FATTY_FRICTION; + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= VIS_FATTY_FRICTION; + } + if (npc.pathfinder.hasDirectPath && Random() % GRUNT_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, GRUNT_DELAY, false, 1); +} + +// The pump on Shoot: a fart, a pool of creep, the cord swelling and a pulse sent down it, its demon charging longer. +static void vis_fatty_pump(Entity_NPC& npc) +{ + npc.friction *= VIS_FATTY_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = PUMP_FART_RADIUS, .isShowEffect = false}); + Entity* fart = + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_FART, .seed = Random()}); + fart->SetColor(PUMP_FART_COLOR, -1, 255, false, true); + creep_spawn(npc, npc.pos, PUMP_CREEP_SCALE, PUMP_CREEP_FRAMES); + npc.v1.x = PUMP_SWELL; + Entity_NPC* demon = npc.ChildNPC(); + if (demon && demon->state == NPC_STATE_ATTACK && demon->projectileCooldown > 0) + demon->projectileCooldown += PUMP_DEMON_DELAY; + npc.projectileDelay = 1; + } + if (npc.sprite.IsFinished()) npc.state = NPC_STATE_MOVE; +} + +// The rage: once its RageStart ends it charges along its diagonal, breathing a laser at its back (in front of it when +// heading down) and sparks every other frame, bouncing off walls. +static void vis_fatty_rage(Entity_NPC& npc) +{ + if (npc.sprite.IsFinished()) npc.sprite.Play("RageDown"); + if (!npc.sprite.animState.IsLoopingAnimation()) npc.friction *= VIS_FATTY_FRICTION; + else + { + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.friction = RAGE_FRICTION; + npc.mass = npc.config->mass * RAGE_MASS; + npc.AddVelocity(vector_scale(npc.targetPosition, RAGE_PUSH), false); + npc.sprite.Play(npc.targetPosition.y <= 0 ? "RageDown" : "RageUp"); + npc.sprite.isFlipX = npc.targetPosition.x < 0; + float behind = vector_angle(npc.targetPosition) + DEGREES_PER_TURN / 2; + + auto* laser = dynamic_cast(npc.entityRef.get()); + if (!laser || laser->type != ENTITY_LASER) + { + laser = Entity_Laser::ShootAngle({.position = npc.pos, + .posOffset = vector_make(0, RAGE_MOUTH), + .source = &npc, + .angleDegrees = behind, + .timeout = RAGE_LASER_FRAMES, + .variant = RAGE_LASER_VARIANT}); + npc.SetRef_bec(laser); + laser->isSampleLaser = true; + laser->Update(); + } + if (npc.IsFrame(2, 0)) + { + float angle = (random_unit() * RAGE_SPARK_SPREAD + behind - RAGE_SPARK_SPREAD / 2) * DEGREES_TO_RADIANS; + float speed = random_unit() * RAGE_SPARK_SPEED_RANGE + RAGE_SPARK_SPEED_MIN; + Vector velocity = vector_add(vector_make(std::cos(angle) * speed, std::sin(angle) * speed), npc.velocity); + Entity* spark = g_game->Spawn({.position = vector_add(velocity, npc.pos), + .velocity = velocity, + .type = ENTITY_EFFECT, + .variant = EFFECT_HAEMO_TRAIL, + .seed = Random()}); + float scale = random_unit() * RAGE_SPARK_SCALE_RANGE + RAGE_SPARK_SCALE_MIN; + spark->posOffset = vector_make(0, RAGE_MOUTH); + spark->sprite.scale = vector_make(scale, scale); + } + if (laser->angleDegrees != behind) + { + laser->ClearLaserSamples(); + laser->set_aim_angle(behind); + laser->Update(); + } + laser->timeout = RAGE_LASER_FRAMES; + laser->renderDepthOffset = npc.targetPosition.y <= RAGE_LASER_IN_FRONT ? RAGE_LASER_FRONT_DEPTH + : RAGE_LASER_BACK_DEPTH; + } + if (!npc.isCollidesWithGrid) return; + + Vector normal = npc.gridCollisionNormal; + if ((npc.targetPosition.x > 0 && normal.x > VIS_WALL_BOUNCE) || (npc.targetPosition.x < 0 && normal.x < -VIS_WALL_BOUNCE)) + npc.targetPosition.x = -npc.targetPosition.x; + if ((npc.targetPosition.y > 0 && normal.y > VIS_WALL_BOUNCE) || (npc.targetPosition.y < 0 && normal.y < -VIS_WALL_BOUNCE)) + npc.targetPosition.y = -npc.targetPosition.y; + npc.velocity = vector_resized(npc.velocity, vector_length(npc.gridCollisionVelocity)); +} + +// The pulse down the cord: every other tick it moves a point on with a gurgle, leaving a small creep and blood, and a +// larger pool at the demon's end. +static void vis_fatty_pulse(Entity_NPC& npc) +{ + for (int tick = 0; tick < npc_ticks_get(npc); tick++) + { + npc.projectileDelay++; + if (npc.projectileDelay % 2 != 0) continue; + + npc.PlaySound(SOUND_BOSS2_BUBBLES, PULSE_VOLUME, 2, false, 1); + size_t point = (size_t)(npc.projectileDelay / 2); + size_t points = npc.vectorDeque1.size() / CORD_STRIDE; + if (point >= points) + { + npc.projectileDelay = 0; + return; + } + + Vector at = npc.vectorDeque1[point * CORD_STRIDE]; + bool isEnd = point == points - 1; + creep_spawn(npc, at, isEnd ? PULSE_END_CREEP_SCALE : PULSE_CREEP_SCALE, + isEnd ? PULSE_END_CREEP_FRAMES : PULSE_CREEP_FRAMES); + Vector lift = vector_make(0, npc.vectorDeque1[point * CORD_STRIDE + 2].x); + Entity* blood = blood_explosion_spawn(isEnd ? PULSE_END_BLOOD : PULSE_BLOOD, at, lift, COLOR_DEFAULT, {}); + blood->renderDepthOffset = PULSE_BLOOD_DEPTH; + } +} + +// The Vis Fatty's update: rage when its demon is gone, a splat now and then, its state, the cord's swell going down +// and the pulse travelling down it. +static void vis_fatty_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_MOVE && !npc.child) vis_fatty_rage_start(npc); + if (Random() % VIS_SPLAT_ODDS == 0) npc.MakeSplat(random_unit() * VIS_SPLAT_SIZE_RANGE + VIS_SPLAT_SIZE_MIN); + + switch (npc.state) + { + case NPC_STATE_INIT: + vis_fatty_init(npc); + break; + case NPC_STATE_MOVE: + vis_fatty_walk(npc); + break; + case NPC_STATE_ATTACK: + vis_fatty_pump(npc); + break; + case NPC_STATE_SPECIAL: + vis_fatty_rage(npc); + break; + } + if (npc.v1.x > 0 && npc.projectileDelay < 1) npc.v1.x = std::max(npc.v1.x - npc.speedMultiplier * SWELL_DRAIN, 0.0f); + if (npc.child && npc.projectileDelay >= 1) vis_fatty_pulse(npc); +} + +// The Fetal Demon's crawl and, in reach of its Vis Fatty, a charge at where its target is heading. +static void demon_crawl(Entity_NPC& npc) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Walk01"); + if (!npc.parent) + { + npc.sprite.Play("Rage"); + npc.state = NPC_STATE_STOMP; + if (npc.health < npc.maxHitPoints) + npc.health = std::min(npc.health + npc.maxHitPoints * HEAL_SHARE, npc.maxHitPoints); + return; + } + + Vector toward = vector_sub(npc.CalcTargetPosition(0), npc.pos); + Entity* target = npc.GetPlayerTarget(); + npc.velocity = vector_add(npc.velocity, vector_scale(vector_resized(toward, DEMON_CRAWL), npc.speedMultiplier)); + // The original compares this distance against squared reaches, so the demon charges from anywhere. + float distance = vector_length(vector_sub(npc.parent->pos, target->pos)); + if (npc.projectileCooldown > 0 || npc.HasEntityFlags(DEMON_DAZED)) return; + bool isCharging = distance < DEMON_CHARGE_REACH && Random() % DEMON_CHARGE_ODDS == 0; + if (!isCharging && (npc.ParentNPC()->v1.y <= RAGE_FULL || distance >= DEMON_RAGE_REACH || + Random() % DEMON_RAGE_ODDS != 0)) + return; + + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Rage"); + float lead = vector_length(vector_sub(npc.pos, target->pos)) * DEMON_LEAD; + Vector aim = vector_sub(vector_add(target->pos, vector_scale(target->velocity, lead)), npc.pos); + npc.targetPosition = vector_normalized(aim); + npc.projectileCooldown = (int)(Random() % DEMON_CHARGE_RANGE) + DEMON_CHARGE_MIN; + if (std::abs(toward.x) > std::abs(toward.y)) npc.sprite.isFlipX = toward.x < 0; +} + +// Alone, the demon drifts after its target, heavier. +static void demon_wander(Entity_NPC& npc) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Walk02"); + Vector toward = vector_sub(npc.CalcTargetPosition(0), npc.pos); + float drift = npc.speedMultiplier == 1 + ? DEMON_DRIFT + : DEMON_DRIFT / ((npc.speedMultiplier + DEMON_DRIFT) - npc.speedMultiplier * DEMON_DRIFT); + npc.velocity = vector_scale(npc.velocity, drift); + npc_push(npc, vector_scale(vector_normalized(toward), DEMON_LONE_SPEED)); + npc.mass = DEMON_LONE_MASS; + if (std::abs(toward.x) > std::abs(toward.y)) npc.sprite.isFlipX = toward.x < 0; +} + +// The demon's charge: steering toward its target in its last 20 frames, then resting. +static void demon_charge(Entity_NPC& npc) +{ + if (!npc.parent) + { + npc.state = NPC_STATE_STOMP; + return; + } + if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_SHAKEY_KID_ROAR, 1, 2, false, 1); + if (npc.projectileCooldown < 1) + { + npc.sprite.Play("RageEnd"); + npc.state = NPC_STATE_MOVE; + npc.projectileCooldown = (int)(Random() % DEMON_REST_RANGE) + DEMON_REST_MIN; + return; + } + + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Walk02"); + if (npc.projectileCooldown < DEMON_STEER_FRAMES) + { + Vector toward = vector_normalized(vector_sub(npc.CalcTargetPosition(0), npc.parent->pos)); + Vector steer = vector_add(vector_scale(toward, DEMON_STEER * npc.speedMultiplier), npc.targetPosition); + npc.targetPosition = vector_normalized(steer); + } + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, DEMON_CHARGE_SPEED * npc.speedMultiplier)); +} + +// The Fetal Demon's update. +static void demon_update(Entity_NPC& npc) +{ + npc.friction *= VIS_FATTY_FRICTION; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.sprite.Play("Walk01"); + npc.state = NPC_STATE_MOVE; + npc.projectileCooldown = DEMON_START_REST; + break; + case NPC_STATE_MOVE: + demon_crawl(npc); + break; + case NPC_STATE_STOMP: + demon_wander(npc); + break; + case NPC_STATE_ATTACK: + demon_charge(npc); + break; + } + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); +} + +// 004ea3d0 (NpcAI::ENTITY_VIS_FATTY) The Vis Fatty and its Fetal Demon. Before its update the Vis Fatty's rage +// meter drains and its cord snaps once the demon is gone, it lets its own demon through, and before each update and +// interpolation its cord follows both ends. +void npc_vis_fatty_update(Entity_NPC& npc) +{ + if (npc.variant == FETAL_DEMON) return demon_update(npc); + + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE && (npc.isDead || !npc.child) && npc.i1 == 0) cord_snap(npc); + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + npc.v1.y = std::max(npc.pendingDamage + npc.v1.y - npc.speedMultiplier * VIS_RAGE_DRAIN, 0.0f); + if (npc.child) npc.sprite.GetLayer(VIS_CORD_LAYER)->isFlipX = (npc.child->pos.x < npc.pos.x) != npc.sprite.isFlipX; + } + else if (npc.aiCallPhase == AI_PHASE_COLLISION) + { + if (npc.collisionEntity->IsType(ENTITY_VIS_FATTY, FETAL_DEMON, -1)) npc.collisionResult = 0; + return; + } + else if (npc.aiCallPhase != AI_PHASE_INTERPOLATE) return vis_fatty_update(npc); + + if (npc.child) cord_update(npc); +} diff --git a/src/npc_wrinkly_baby.cpp b/src/npc_wrinkly_baby.cpp new file mode 100644 index 0000000..6d74b47 --- /dev/null +++ b/src/npc_wrinkly_baby.cpp @@ -0,0 +1,216 @@ +#include "boss_ai.h" +#include "active_items.h" +#include "entity_player.h" +#include "menu_manager.h" +#include "npc_basement.h" + +// The Wrinkly Baby's states: drifting, the dash along a line at its target, and the double shot. +constexpr int WRINKLY_DASH = NPC_STATE_STOMP; +constexpr int WRINKLY_SHOOT = NPC_STATE_ATTACK; + +constexpr ColorMod WRINKLY_SPLAT_COLOR = {{0.5f, 0.1f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0.1f, 0.1f}}; +constexpr int WRINKLY_REST_MIN = 5; +constexpr uint32_t WRINKLY_REST_RANGE = 10; +constexpr int WRINKLY_SHOT_REST_MIN = 15; +constexpr uint32_t WRINKLY_SHOT_REST_RANGE = 30; +constexpr int WRINKLY_CONTROLLED_REST = 15; + +constexpr float WRINKLY_FRICTION = 0.7f; +constexpr float WRINKLY_DASH_FRICTION = 0.85f; +constexpr float WRINKLY_DRIFT = 0.33f; +constexpr float WRINKLY_CONTROLLED_DRIFT = 0.1f; +constexpr float WRINKLY_KEEP_AWAY = 120; +constexpr float WRINKLY_DASH_REACH = 280; +constexpr float WRINKLY_CONTROLLED_DASH_SQUARED = 100; +constexpr uint32_t WRINKLY_ATTACK_ODDS_MASK = 3; +constexpr float WRINKLY_ATTACK_RANGE = 1000; +constexpr int WRINKLY_ATTACK_FRAMES = 7; +constexpr float WRINKLY_ATTACK_START_FRAME = 3; +constexpr float WRINKLY_DASH_PUSH = 3.75f; +constexpr float WRINKLY_DASH_STOP = 20; +constexpr float WRINKLY_RIGHT_ANGLE = 1.5707964f; + +constexpr float WRINKLY_SHOT_VOLUME = 0.85f; +constexpr float WRINKLY_SHOT_PITCH = 0.9f; +constexpr float WRINKLY_SHOT_SPREAD = 0.6f; +constexpr float WRINKLY_SHOT_SPEED = 8; +constexpr float WRINKLY_SHOT_SPEED_HARD = 10; +constexpr float WRINKLY_SHOT_OFFSET = 4; +constexpr std::string_view WRINKLY_DASHES[] = {"DashHori", "DashUp", "DashHori", "DashDown"}; + +// Back to drifting after an attack, resting first. +static void wrinkly_rest(Entity_NPC& npc, int rest) +{ + npc.i2 = rest; + npc.sprite.Play("Move"); + npc.state = NPC_STATE_MOVE; +} + +// Starts the double shot from its fourth frame. +static void wrinkly_shoot_start(Entity_NPC& npc) +{ + npc.sprite.Play("Attack"); + if (npc.sprite.animState.animData) npc.sprite.animState.SetFrameFloat(WRINKLY_ATTACK_START_FRAME); + npc.state = WRINKLY_SHOOT; +} + +// Drifting: toward its target, kept 120 away, then once rested a dash when 120 to 280 away (a shot when nearer), one +// roll in four. A controlled one dashes at a far aim mark or shoots when its target is in range. +static void wrinkly_drift(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.friction *= WRINKLY_FRICTION; + npc.sprite.Play("Move"); + + Entity* target = npc.GetPlayerTarget(); + Vector goal = npc.CalcTargetPosition(0); + Vector away = vector_sub(npc.pos, goal); + if (vector_length_squared(away) < WRINKLY_KEEP_AWAY * WRINKLY_KEEP_AWAY) + goal = vector_add(goal, vector_resized(away, WRINKLY_KEEP_AWAY)); + if (npc.controllerID != -1) npc_push(npc, vector_scale(npc.GetControllerInput(0), WRINKLY_DRIFT)); + else if (goal.x != npc.pos.x || goal.y != npc.pos.y) + npc_push(npc, vector_scale(vector_normalized(vector_sub(goal, npc.pos)), WRINKLY_DRIFT)); + + float distance = vector_length(vector_sub(npc.pos, target->pos)); + if (npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK) || npc.i2 > 0) return; + + if (npc.controllerID == -1) + { + if (!npc.IsHostileTo(npc.GetPlayerTarget()) || (Random() & WRINKLY_ATTACK_ODDS_MASK) != 0) return; + if (distance >= WRINKLY_DASH_REACH) return; + if (distance >= WRINKLY_KEEP_AWAY) + { + npc.sprite.Play("DashStart"); + npc.state = WRINKLY_DASH; + return; + } + return wrinkly_shoot_start(npc); + } + + if (npc.is_controller_input_idle() && + vector_length_squared(vector_sub(npc.pos, npc.GetAimTargetPosition())) > WRINKLY_CONTROLLED_DASH_SQUARED) + { + npc.sprite.Play("DashStart"); + npc.state = WRINKLY_DASH; + return; + } + if (npc.aimTargetEffect.get() || !npc.IsTargetInAttackRange(WRINKLY_ATTACK_RANGE, WRINKLY_ATTACK_FRAMES, false)) + return; + npc.UpdateControllerMovement(true); + wrinkly_shoot_start(npc); +} + +// Aims the dash at its target (controlled, at its aim mark) and faces along it. +static void wrinkly_dash_aim(Entity_NPC& npc) +{ + npc.targetPosition = npc.GetPlayerTarget()->pos; + if (npc.controllerID != -1) + { + npc.targetPosition = npc.GetAimTargetPosition(); + npc.ClearChild(); + } + npc.v1 = vector_normalized(vector_sub(npc.targetPosition, npc.pos)); + Direction direction = vector_to_direction(npc.v1); + npc.sprite.Play(WRINKLY_DASHES[direction]); + npc.sprite.isFlipX = direction == DIRECTION_LEFT; +} + +// The dash: once DashStart ends it speeds along its line, pulled back onto it, and stops 20 short of the mark to shoot +// (a controlled one with no target in range rests instead). +static void wrinkly_dash(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + const AnimationData* data = npc.sprite.animState.animData; + if (!data || !data->isLooping) + { + npc.friction *= WRINKLY_FRICTION; + if (!data || !npc.sprite.animState.isPlaying) wrinkly_dash_aim(npc); + return; + } + + npc.friction *= WRINKLY_DASH_FRICTION; + Vector pushed = vector_add(npc.velocity, vector_scale(npc.v1, WRINKLY_DASH_PUSH * npc.speedMultiplier)); + float cosine = std::cos(WRINKLY_RIGHT_ANGLE); + float sine = std::sin(WRINKLY_RIGHT_ANGLE); + Vector side = vector_make(npc.v1.x * cosine - npc.v1.y * sine, npc.v1.y * cosine + npc.v1.x * sine); + float drift = vector_dot(vector_sub(npc.pos, npc.targetPosition), side); + npc.velocity = vector_sub(vector_scale(npc.v1, vector_dot(npc.v1, pushed)), vector_scale(side, drift)); + if (vector_dot(vector_sub(npc.targetPosition, npc.pos), npc.v1) >= WRINKLY_DASH_STOP) return; + + npc.entityCollisionClass = ENTCOLL_ALL; + if (npc.controllerID == -1 || npc.IsTargetInAttackRange(WRINKLY_ATTACK_RANGE, WRINKLY_ATTACK_FRAMES, false)) + { + npc.UpdateControllerMovement(true); + npc.state = WRINKLY_SHOOT; + npc.sprite.Play("Attack"); + return; + } + npc.v1 = {}; + npc.targetPosition = {}; + wrinkly_rest(npc, WRINKLY_CONTROLLED_REST); +} + +// The double shot on its Shoot event at its target (controlled, along its input), then a rest. +static void wrinkly_shoot(Entity_NPC& npc) +{ + npc.friction *= WRINKLY_FRICTION; + if (npc.controllerID != -1) npc_push(npc, vector_scale(npc.GetControllerInput(0), WRINKLY_CONTROLLED_DRIFT)); + npc.UpdateControllerMovement(false); + + if (npc.sprite.animState.animData) + { + if (npc.sprite.animState.IsEventTriggered("Shoot")) + { + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) + aim = vector_normalized(npc.controllerMovement); + npc.sprite.isFlipX = aim.x < 0; + npc.PlaySound(SOUND_FLOATY_BABY_ROAR, WRINKLY_SHOT_VOLUME, 2, false, WRINKLY_SHOT_PITCH); + ProjectileParams params; + params.spread = WRINKLY_SHOT_SPREAD; + float speed = game_is_hard_mode() ? WRINKLY_SHOT_SPEED_HARD : WRINKLY_SHOT_SPEED; + npc.FireProjectiles(vector_add(npc.pos, vector_scale(aim, WRINKLY_SHOT_OFFSET)), vector_scale(aim, speed), + PROJECTILES_TWO, params); + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + } + npc.v1 = {}; + npc.targetPosition = {}; + int rest = WRINKLY_CONTROLLED_REST; + if (npc.controllerID == -1) rest = (int)(Random() % WRINKLY_SHOT_REST_RANGE) + WRINKLY_SHOT_REST_MIN; + wrinkly_rest(npc, rest); +} + +// 0054fa80 The Wrinkly Baby (38.3): drifts at a distance from its target, dashes in along a line and fires a double +// shot. A controlled one shows its aim mark while aiming. +void npc_wrinkly_baby_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + npc.splatColor = WRINKLY_SPLAT_COLOR; + npc.i2 = WRINKLY_REST_MIN; + if (npc.controllerID == -1) npc.i2 += (int)(Random() % WRINKLY_REST_RANGE); + return; + case NPC_STATE_MOVE: + wrinkly_drift(npc); + break; + case WRINKLY_DASH: + wrinkly_dash(npc); + break; + case WRINKLY_SHOOT: + wrinkly_shoot(npc); + break; + } + + const AnimationData* data = npc.sprite.animState.animData; + bool isAimable = npc.state == NPC_STATE_MOVE || !data || !data->isLooping; + bool isAiming = npc.aimTargetEffect.get() || + (npc.controllerID != -1 && + input_is_action_pressed(ACTION_ITEM, npc.controllerID, &npc) && + !vector_is_zero(npc.GetControllerInput(0.1f))); + if (isAimable && isAiming) npc.SpawnControlTarget(1, -1); + if (npc.i2 > 0) npc.i2 -= ticks; +} diff --git a/src/player_hud.cpp b/src/player_hud.cpp index 55108f7..75e11fa 100644 --- a/src/player_hud.cpp +++ b/src/player_hud.cpp @@ -11,6 +11,8 @@ #include "menu_special_seeds.h" #include "render_passes.h" #include "seeds.h" +#include "data.h" +#include "stb_image.h" #include #include #include @@ -96,7 +98,6 @@ constexpr float MANTLE_SECOND_X = 6; constexpr float MANTLE_SECOND_RISE = 4; constexpr float MANTLE_SECOND_ALPHA = 0.5f; constexpr int NULL_ITEM_HOLY_CARD = 46; -constexpr int COLLECTIBLE_BLANKET = 535; // The extra lives text: its gap from the hearts, its rise, and the shift beside a shield or in the compact layout. constexpr float LIVES_GAP = 10; @@ -208,7 +209,6 @@ constexpr int SUBCHARGES_PER_CHARGE = 450; constexpr int COLLECTIBLE_JAR_OF_FLIES = 434; constexpr int COLLECTIBLE_MAMA_MEGA = 483; constexpr int COLLECTIBLE_JAR_OF_WISPS = 685; -constexpr int COLLECTIBLE_HOLD = 715; constexpr int JAR_HEARTS_SHOWN = 10; constexpr int JAR_FLIES_SHOWN = 20; constexpr int JAR_FLIES_PER_ROW = 11; @@ -458,6 +458,45 @@ void PlayerHUD::actives_update(bool& isChanged) } } +// The icon of a trinket slot, the Modeling Clay copy's when there is one, and the middle of its drawn pixels. The +// original scans the 32 pixel square oddly: for each column x of row y it tests the red byte of the pixel (x + 1) * y +// counted along the square, and it stores the middle of the rows in x and of the columns in y. Both are kept. +static void trinket_icon_load(PlayerHUDTrinket& trinket) +{ + constexpr int TRINKET_ICON_PIXELS = 32; + constexpr int RGBA = 4; + ItemConfig& items = g_manager->itemConfig; + if (trinket.clayItem < 0) reconstruction_missing("PlayerHUD::Update 00842230: a glitched item's clay icon"); + ItemConfig_Item* item = trinket.clayItem ? items.GetCollectible(trinket.clayItem) : items.GetTrinket(trinket.id); + if (!item) return; + trinket.image = Manager::LoadImage(item->gfxFilename); + if (!trinket.image) return; + + int width = 0; + int height = 0; + int channels = 0; + stbi_uc* pixels = stbi_load(resource_path(trinket.image->path).c_str(), &width, &height, &channels, STBI_rgb_alpha); + std::array square{}; + for (int row = 0; pixels && row < std::min(height, TRINKET_ICON_PIXELS); row++) + std::copy_n(pixels + (size_t)row * width * RGBA, std::min(width, TRINKET_ICON_PIXELS) * RGBA, square.begin() + row * TRINKET_ICON_PIXELS * RGBA); + stbi_image_free(pixels); + + uint32_t minX = TRINKET_ICON_PIXELS; + uint32_t maxX = 0; + uint32_t minY = TRINKET_ICON_PIXELS; + uint32_t maxY = 0; + for (uint32_t y = 0; y < TRINKET_ICON_PIXELS; y++) + for (uint32_t x = 0; x < TRINKET_ICON_PIXELS; x++) + { + if (square[(x + 1) * y * RGBA] == 0) continue; + minX = std::min(minX, x); + maxX = std::max(maxX, x); + minY = std::min(minY, y); + maxY = std::max(maxY, y); + } + trinket.offset = vector_make((float)((maxY - minY) / 2 + minY), (float)((maxX - minX) / 2 + minX)); +} + // The trinket slots of Update: each follows its trinket (the error trinket shows one picked by the room's spawn seed) // and, once it shows Modeling Clay, the item the clay copies, reloading the icon and the offset of its drawn pixels // when either changed. @@ -481,8 +520,7 @@ void PlayerHUD::trinkets_update(bool& isChanged) trinket.id = id; trinket.clayItem = clayItem; - if (id != 0 || clayItem != 0) - reconstruction_missing("PlayerHUD::Update 00842230: a trinket's icon and the offset of its drawn pixels"); + trinket_icon_load(trinket); isChanged = true; g_game->hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); } @@ -1590,12 +1628,6 @@ void PlayerHUD::RenderCraftingTable(Vector at, float tableScale) KAGE::Graphics::manager.shader_default_set(); } -// 0084a3e0 Draws Tainted ???'s poop spell queue. -void PlayerHUD::RenderSpellQueue(Vector, float) -{ - reconstruction_missing("PlayerHUD::RenderSpellQueue 0084a3e0"); -} - // 0084ad40 Draws a versus health bar and returns its size. Vector PlayerHUD::render_deathmatch_health_bar(Vector) { diff --git a/src/pocket_items.h b/src/pocket_items.h new file mode 100644 index 0000000..a73349b --- /dev/null +++ b/src/pocket_items.h @@ -0,0 +1,39 @@ +#pragma once + +#include "classes.h" +#include +#include +#include + +struct Entity_Player; +struct RNG; + +// What a card's or pill's use goes on with after its effect: the item held up, nothing more, or nothing at all. +enum PocketUseEnd +{ + POCKET_END_ANIMATE, + POCKET_END_SKIP_ANIMATION, + POCKET_END_RETURN +}; + +// A card's or pill's use as its effect runs: the player, its generator, the pill's color, its flags and the sound an +// up pill plays. +struct PocketUse +{ + Entity_Player& player; + RNG& rng; + int pillColor = 0; + int sound = SOUND_POWERUP_SPEWER; + uint32_t flags = 0; + bool isAddCostume = true; + bool isCarBattery = false; + bool isDoubled = false; + bool isHorse = false; + bool isPlayAnimation = true; +}; + +void sound_fart_play(int sound); +void pocket_pickup_spawn(PocketUse& use, int variant, int subType); +PocketUseEnd card_effect_run(PocketUse& use, int card); +void pill_effect_run(PocketUse& use, int pillEffect, std::string_view name); +bool teleport_random_room_of_types(Entity_Player& player, std::span roomTypes, bool isPreferUnvisited); diff --git a/src/room.cpp b/src/room.cpp index b89928c..b48feec 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -192,7 +192,6 @@ constexpr int DUST_TIMEOUT_MIN = 30; // that count as it. constexpr int COLLECTIBLE_MEMBER_CARD = 602; constexpr int COLLECTIBLE_VOID = 477; -constexpr int CARD_CRACKED_KEY = 78; constexpr int CARD_SOUL_OF_CAIN = 83; constexpr int SECRET_SHOP_COLUMN = 10; constexpr int EFFECT_SHOP_LADDER = 156; @@ -235,7 +234,6 @@ constexpr float LAVA_AMOUNT = 0.45f; constexpr float COLOR_MODIFIER_RATE = 0.015f; // The collectibles, trinkets, seeds and challenges Room checks. -constexpr int COLLECTIBLE_INFESTATION = 148; constexpr int COLLECTIBLE_THE_STAIRWAY = 586; constexpr int COLLECTIBLE_ISAACS_TOMB = 701; constexpr int COLLECTIBLE_CARD_READING = 660; diff --git a/src/room_clear.cpp b/src/room_clear.cpp index 3358291..0e6d225 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -12,6 +12,7 @@ #include "grid_entity_trap_door.h" #include "item_config.h" #include "item_pool.h" +#include "loot_list.h" #include "lua_engine.h" #include "manager.h" #include "npc_ai.h" @@ -30,16 +31,13 @@ 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_BROKEN_SHOVEL_2 = 551; constexpr int COLLECTIBLE_OPTIONS = 670; constexpr int COLLECTIBLE_SWARM = 693; constexpr int COLLECTIBLE_LITTLE_CHAD = 96; constexpr int COLLECTIBLE_LITTLE_GISH = 99; constexpr int COLLECTIBLE_STEVEN = 50; -constexpr int COLLECTIBLE_LITTLE_STEVEN = 100; constexpr int TRINKET_AAA_BATTERY_CLEAR = 3; constexpr int TRINKET_ISAACS_FORK = 46; -constexpr int TRINKET_LOUSE = 70; constexpr int TRINKET_OLD_CAPACITOR = 143; constexpr int TRINKET_DINGLE_BERRY = 163; constexpr int TRINKET_POLISHED_BONE = 167; @@ -1063,6 +1061,76 @@ static void dark_room_award_spawn(Room& room, ClearAward& award, bool isContinui if (isContinuing && is_void_reachable()) void_portal_spawn(room, award); } +// The Void's bosses: Delirium marks the character's completion, unlocks Delirious and Lil Delirium and leaves a big +// chest (a trophy where the run ends here). Any other boss leaves an item from a random pool of the first 16 or the +// Bomb Bum's, two with There's Options. +constexpr int BOSS_DELIRIUM_ID = 70; +constexpr int ACHIEVEMENT_DELIRIOUS = 338; +constexpr int ACHIEVEMENT_LIL_DELIRIUM = 357; +constexpr uint32_t VOID_POOL_ROLL = 17; + +// An item from one of the pools a Void boss draws from, taken out of the pools. +static int void_item_pick(ClearAward& award) +{ + uint32_t pool = award.rng.RandomInt(VOID_POOL_ROLL); + if (pool == VOID_POOL_ROLL - 1) pool = POOL_BOMB_BUM; + + int item = g_game->itemPool.GetCollectible((ItemPoolType)pool, award.rng.Next(), 0, 0, 0); + g_game->itemPool.RemoveCollectible(item, REMOVE_ANY, REMOVE_APPLY); + return item; +} + +// Spawns a Void boss's item at a spot. +static Entity_Pickup* void_item_spawn(Room& room, ClearAward& award, Vector spot, int item) +{ + reward_spot_clear(room, spot); + auto* pickup = static_cast(g_game->Spawn({.position = spot, + .subType = item, + .type = ENTITY_PICKUP, + .variant = PICKUP_COLLECTIBLE, + .seed = award.rng.Next()})); + pickup->coopDuplicateIndex = 0; + return pickup; +} + +// 007fb250 (part) A Void boss's award. +static void void_award_spawn(Room& room, ClearAward& award, bool isContinuing) +{ + PersistentGameData& data = g_manager->persistentGameData; + PlayerManager& players = g_game->playerManager; + Vector center = vector_make(award.reward.x, award.itemRow); + Vector left = vector_make(award.reward.x - AWARD_ITEM_SPACING, award.reward.y + AWARD_ITEM_DROP); + Vector right = vector_make(award.reward.x + AWARD_ITEM_SPACING, award.reward.y + AWARD_ITEM_DROP); + + if (room.bossId == BOSS_DELIRIUM_ID) + { + PlayerManager::unlock_completion_mark(COMPLETION_DELIRIUM); + data.TryUnlock(ACHIEVEMENT_DELIRIOUS); + data.TryUnlock(ACHIEVEMENT_LIL_DELIRIUM); + data.IncreaseEventCounter(EVENT_COUNTER_DELIRIUM_KILLS, 1); + reward_spot_clear(room, award.reward); + if (!isContinuing) + { + g_game->Spawn( + {.position = award.reward, .type = ENTITY_PICKUP, .variant = PICKUP_TROPHY, .seed = Random()}); + return; + } + g_manager->achievementOverlay.isPopupBlocked = true; + g_game->Spawn( + {.position = award.reward, .type = ENTITY_PICKUP, .variant = PICKUP_BIGCHEST, .seed = award.rng.Next()}); + return; + } + + bool hasOptions = players.AnyoneHasCollectible(COLLECTIBLE_THERES_OPTIONS); + int item = void_item_pick(award); + Entity_Pickup* first = void_item_spawn(room, award, hasOptions ? left : center, item); + + if (!players.AnyoneHasCollectible(COLLECTIBLE_THERES_OPTIONS)) return; + item = void_item_pick(award); + Entity_Pickup* option = void_item_spawn(room, award, right, item); + option->optionsPickupIndex = first->AssignOptionsIndex(); +} + // Mega Satan: the kill counts and marks. Unless the challenge is to beat him, the run ends at once with his ending, or // where it goes on to the Void a big chest and a Void portal come. A Mega Satan challenge's end leaves a trophy. static void mega_satan_award_spawn(Room& room, ClearAward& award, bool isContinuing) @@ -1163,7 +1231,7 @@ static void boss_award_spawn(Room& room, ClearAward& award) else if (room.bossId == BOSS_MEGA_SATAN_ID) mega_satan_award_spawn(room, award, isContinuing); else if (stage == STAGE_SHEOL) sheol_award_spawn(room, award, isContinuing); else if (stage == STAGE_DARK_ROOM) dark_room_award_spawn(room, award, isContinuing); - else reconstruction_missing("Room::SpawnClearAward 007fb250: the Void's bosses' items and Delirium's chest"); + else if (stage == STAGE_VOID) void_award_spawn(room, award, isContinuing); boss_kill_records(stage, isLastBoss); } @@ -1380,9 +1448,46 @@ static void azazels_stump_update(Entity_Player& player) effects.AddEffect(TemporaryEffect(stump), true, 2); } +// Dingle Berry's part of 007a8fd0: a dip per copy, mostly plain, often red or corny, rarely golden, rainbow, black or +// white. +static void dingle_berry_dips_throw(Entity_Player& player) +{ + constexpr int DIP_WEIGHTS[] = {20, 6, 6, 1, 1, 1, 1}; + constexpr RNG DIP_SHIFTS = {0, 5, 9, 7}; + for (int i = player.GetTrinketMultiplier(TRINKET_DINGLE_BERRY); i > 0; i--) + { + WeightedOutcomePicker picker; + for (int dip = 0; dip < (int)std::size(DIP_WEIGHTS); dip++) picker.AddOutcomeWeight(dip, DIP_WEIGHTS[dip]); + RNG rng = DIP_SHIFTS; + rng._seed = player.GetTrinketRNG(TRINKET_DINGLE_BERRY).Next(); + Entity_Familiar::ThrowDip(picker.PickOutcome(rng), player.pos, &player); + } +} + +// Crystal Key's part of 007a8fd0: one clear in three (more often with stronger copies, one in eight in a red room) +// opens a red room door on a free side of the room. +static void crystal_key_door_open(Entity_Player& player) +{ + constexpr int ODDS_BASE = 4; + constexpr int RED_ROOM_ODDS_BASE = 5; + Game& game = *g_game; + int multiplier = player.GetTrinketMultiplier(TRINKET_CRYSTAL_KEY); + bool isRedRoom = game.room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM; + uint32_t odds = (uint32_t)std::max(1, isRedRoom ? (RED_ROOM_ODDS_BASE - multiplier) * 2 : ODDS_BASE - multiplier); + RNG& rng = player.GetTrinketRNG(TRINKET_CRYSTAL_KEY); + if (rng.Next() % odds != 0) return; + + std::vector slots; + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) + if (game.CanSpawnDoorOutline(game.currentRoomIdx, slot)) slots.push_back(slot); + if (slots.empty()) return; + uint32_t pick = rng.Next() % (uint32_t)slots.size(); + game.MakeRedRoomDoor(game.currentRoomIdx, slots[pick]); +} + // 007a8fd0 A cleared room's effects on the player: active charge (none with Old Capacitor or 4.5 Volt), Isaac's // Fork, Louse, rotten hearts' flies, the end of an astral projection, Curse of the Lost, Swarm, Wavy Cap's fading, -// Azazel's Rage and Stump, and the wisps waiting for a clear. +// Azazel's Rage, Crystal Key's red door, Azazel's Stump, and the wisps waiting for a clear. void Entity_Player::TriggerRoomClear() { if (!HasTrinket(TRINKET_OLD_CAPACITOR) && !HasCollectible(COLLECTIBLE_4_5_VOLT)) @@ -1396,12 +1501,10 @@ void Entity_Player::TriggerRoomClear() temporaryEffects.RemoveNullEffect(NULLITEM_WAVY_CAP, 1); if (HasCollectible(COLLECTIBLE_AZAZELS_RAGE)) azazels_rage_charge(*this); - if (HasTrinket(TRINKET_DINGLE_BERRY)) - reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: Dingle Berry's dip"); + if (HasTrinket(TRINKET_DINGLE_BERRY)) dingle_berry_dips_throw(*this); if (HasTrinket(TRINKET_POLISHED_BONE)) reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: Polished Bone's bony"); - if (HasTrinket(TRINKET_CRYSTAL_KEY)) - reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: Crystal Key's red room"); + if (HasTrinket(TRINKET_CRYSTAL_KEY)) crystal_key_door_open(*this); if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_SKIN_WISP) reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: the wisp baby's wisps"); bool isTaintedLazarus = playerType == PLAYER_LAZARUS_B || playerType == PLAYER_LAZARUS2_B; diff --git a/src/room_lighting.cpp b/src/room_lighting.cpp index e50553f..1cbe67e 100644 --- a/src/room_lighting.cpp +++ b/src/room_lighting.cpp @@ -38,7 +38,6 @@ constexpr ColorMod LIGHT_PURPLE = {{0.9f, 0.3f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod LIGHT_WARM = {{1, 0.9f, 0.8f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod LIGHT_AURA = {{0.4f, 0.6f, 1, 0}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr int COLLECTIBLE_SPIRIT_OF_THE_NIGHT = 3; -constexpr int COLLECTIBLE_TELEPATHY_BOOK = 192; constexpr int PLAYER_DARK_JUDAS = 12; // A fireplace's light: how it fades and shrinks as the fire burns down, how far it flickers, how small Coal glows, diff --git a/src/room_render.cpp b/src/room_render.cpp index 79facaf..d9f76b8 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -191,6 +191,7 @@ constexpr float SECRET_SHADOW = 0.33f; constexpr float BASEMENT_SHADOW = 0.6f; constexpr float NIGHT_LIGHT_SHADOW = 0.5f; constexpr float GLAUCOMA_SHADOW = 0.1f; +constexpr float LIGHT_ROOM_REACH = 300; // The items, entities, grid states and rooms the render passes tell apart. constexpr int BABY_SKIN_GLOW = 66; @@ -1572,7 +1573,8 @@ static KColor room_light_color(Room& room, KColor shadow) // 0081e250 How dark the room's shadows are: the Beast's darkness, full in pitch black rooms, the floor's shadow alpha // (lighter on Basement I, full under the Curse of the Darkness), halved by Night Light, raised by Glaucoma, toward // the game's darkness, darker in secret rooms, the mineshaft and the death certificate's floor. Hush's room lightens -// with Hush's health. The Blue Womb's light room (-9) lightens near its center, not reconstructed yet. +// with Hush's health. The Blue Womb's light room (-9) is the darker the nearer its nearest player is to its center, +// fully dark there and light from 300 away. float Room::GetLightingAlpha() { Game& game = *g_game; @@ -1607,9 +1609,14 @@ float Room::GetLightingAlpha() return std::max(1 - entity->health / entity->maxHitPoints, alpha); return alpha; } - if (game.currentRoomIdx == ROOM_IDX_BLUE_WOMB_LIGHT) - reconstruction_missing("Room::GetLightingAlpha 0081e250: the Blue Womb's light room (Game::GetNearestPlayer)"); - return alpha; + if (game.currentRoomIdx != ROOM_IDX_BLUE_WOMB_LIGHT) return alpha; + + Vector center = GetCenterPos(); + Vector nearest = game_nearest_player(center)->pos; + float dx = center.x - nearest.x; + float dy = center.y - nearest.y; + float distance = std::sqrt(dy * dy + dx * dx); + return 1 - std::min(distance, LIGHT_ROOM_REACH) / LIGHT_ROOM_REACH; } // 0080ea80 Draws the room's shadow and light surfaces before the room: the entities' shadows, then (with lighting) the diff --git a/src/room_special.cpp b/src/room_special.cpp index 75dab82..351eaf9 100644 --- a/src/room_special.cpp +++ b/src/room_special.cpp @@ -20,7 +20,6 @@ constexpr int COLLECTIBLE_POUND_OF_FLESH = 672; constexpr int TRINKET_STORE_CREDIT = 13; constexpr int TRINKET_KEEPERS_BARGAIN = 171; constexpr int TRINKET_ADOPTION_PAPERS = 184; -constexpr int CARD_HOLY = 51; constexpr int CARD_SOUL_LILITH = 92; constexpr int ACHIEVEMENT_HOLY_CARD = 293; constexpr int ACHIEVEMENT_HEART_BONE_SHOP = 391; diff --git a/src/room_update.cpp b/src/room_update.cpp index a110cf8..ef0415d 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -163,7 +163,6 @@ constexpr int DOGMA_ANGEL = 2; constexpr int DOGMA_ANGEL_STATE = 10; constexpr int LASER_LOOP_VARIANTS[] = {6, 15}; constexpr int EFFECT_DOGMA_BLACKHOLE = 171; -constexpr int EFFECT_URN_OF_SOULS = 178; constexpr int BLACKHOLE_STATE_OPEN = 1; // How the sources sound: the reach of the enemies' loops, the flies' buzz (Hush's flies quieter, the whole buzz capped), diff --git a/src/sfx_manager.h b/src/sfx_manager.h index 3d5fbbc..b1da1b4 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -45,12 +45,21 @@ enum SoundId : int SOUND_BOSS1_EXPLOSIONS = 28, SOUND_DEATH_REVERSE = 29, SOUND_DEATH_BURST_SMALL = 30, + SOUND_DEATH_CARD = 33, + SOUND_DEVIL_CARD = 34, SOUND_FART = 37, SOUND_FETUS_JUMP = 38, SOUND_FETUS_LAND = 40, SOUND_FIREDEATH_HISS = 43, SOUND_COIN_INSERT = 45, SOUND_FORESTBOSS_STOMPS = 48, + SOUND_SCYTHE_BREAK = 49, + SOUND_PING_PONG = 458, + SOUND_STONE_IMPACT = 487, + SOUND_GFUEL_RICOCHET = 831, + SOUND_MONSTRO_LUNG_BARF = 891, + SOUND_MONSTRO_LUNG_CHARGE = 896, + SOUND_TEAR_BOUNCE = 905, SOUND_GASCAN_POUR = 51, SOUND_HELLBOSS_GROUNDPOUND = 52, SOUND_GLASS_BREAK = 53, @@ -113,6 +122,7 @@ enum SoundId : int SOUND_BOIL_HATCH = 181, SOUND_BOSS2_BUBBLES = 185, SOUND_ERROR_BUZZ = 187, + SOUND_GOLDENKEY = 204, SOUND_GOOATTACH0 = 205, SOUND_SATAN_HAND_LASER = 211, SOUND_HEARTIN = 212, @@ -181,6 +191,8 @@ enum SoundId : int SOUND_LITTLE_HORN_GRUNT_2 = 416, SOUND_THE_STAIN_BURST = 419, SOUND_BONE_SNAP = 462, + SOUND_BONE_DROP = 467, + SOUND_BONE_BOUNCE = 499, SOUND_SHOVEL_DIG = 464, SOUND_GOLD_HEART_DROP = 466, SOUND_CANDLE_LIGHT = 471, @@ -192,18 +204,24 @@ enum SoundId : int SOUND_BATTERYDISCHARGE = 493, SOUND_FREEZE = 496, SOUND_FREEZE_SHATTER = 498, + SOUND_RECALL_FINISH = 584, SOUND_POOP_LASER = 589, + SOUND_EDEN_GLITCH = 595, 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_POOPITEM_THROW = 605, + SOUND_POOPITEM_STORE = 606, + SOUND_POOPITEM_HOLD = 607, SOUND_VAMP_DOUBLE = 614, SOUND_GFUEL_AIR_HORN = 828, SOUND_DARK_BUM_PAYOUT = 853, SOUND_DRSREMOTE_WARNING = 855, SOUND_POOP_THROW = 865, + SOUND_SUMMON_PENTA = 871, SOUND_SUMMON_WAVE = 872, SOUND_PRIDE_ZAP = 903, SOUND_CAGE_DEATH = 918, @@ -280,6 +298,11 @@ enum SoundId : int SOUND_POT_BREAK = 138, SOUND_SWORD_SPIN = 538, SOUND_CUBE_BABY_KICK = 852, + SOUND_RAGMAN_1 = 392, + SOUND_RAGMAN_2 = 393, + SOUND_RAGMAN_3 = 394, + SOUND_RAGMAN_4 = 395, + SOUND_FORSAKEN_LAUGH = 417, SOUND_OCCULAR_RIFT_PORTAL = 1088, SOUND_ROCKET_LAUNCH_SHORT = 585, SOUND_ROCKET_LAUNCH_TINY = 586, @@ -290,9 +313,17 @@ enum SoundId : int SOUND_IMP_WARP_IN = 1079, SOUND_LIGHTBOLT = 172, SOUND_LIGHTBOLT_CHARGE = 173, + SOUND_HOLY_MANTLE = 277, SOUND_HUSH_ROAR = 421, SOUND_HUSH_GROWL = 422, SOUND_HUSH_LOW_ROAR = 423, + SOUND_SISTERS_VIS_SCARE = 960, + SOUND_RAGMEGA_BALL_ATTACK = 981, + SOUND_RAGMEGA_BEAM = 982, + SOUND_RAGMEGA_INHALE = 983, + SOUND_RAGMEGA_EXHALE = 984, + SOUND_RAGMEGA_INVINCIBLE_ON = 985, + SOUND_RAGMEGA_INVINCIBLE_OFF = 986, SOUND_HUSH_CHARGE = 425, SOUND_LAZARUS_FLIP_DEAD = 582, SOUND_LAZARUS_FLIP_ALIVE = 583, @@ -304,8 +335,37 @@ enum SoundId : int SOUND_DARK_ESAU_DEATH_OPEN = 617, SOUND_ABYSS = 834, SOUND_FLIP_POOF = 856, + SOUND_GNAWED_LEAF_STONE = 858, + SOUND_BUTTER_DROP = 901, + SOUND_TICK_BURN = 911, SOUND_VOID_FAIL = 1072, - SOUND_ABYSS_SUCCESS = 1073 + SOUND_ABYSS_SUCCESS = 1073, + SOUND_ULTRA_GREED_SPINNING = 440, + SOUND_MOTHER_SUCTION = 640, + SOUND_ROCKET_BLAST_DEATH = 141, + SOUND_THUMBSUP_AMPLIFIED = 602, + SOUND_THUMBSDOWN_AMPLIFIED = 603, + SOUND_POWERUP_SPEWER_AMPLIFIED = 604, + SOUND_MOM_BOTTLE = 870, + SOUND_SMELTER = 908, + SOUND_MOMS_BRA = 1035, + SOUND_BOOK_SHADOWS_START = 1026, + SOUND_RED_CANDLE = 1036, + SOUND_NOTCHED_AXE = 1057, + SOUND_TELEPATHY_DUMMY = 1059, + SOUND_ITEMRECHARGE = 218, + SOUND_D6_ROLL = 910, + SOUND_ITEM_RAISE = 1017, + SOUND_BIBLE = 1038, + SOUND_RAZOR_BLADE = 1058, + SOUND_DERP = 197, + SOUND_BROWNIE_LAUGH = 420, + SOUND_FLOATING_KNIGHT_GROWL = 1084, + SOUND_KNIGHT_GROWL = 1082, + SOUND_SELFLESS_KNIGHT_GROWL = 1083, + SOUND_FLAMETHROWER_END = 536, + SOUND_FLAMETHROWER_LOOP = 535, + SOUND_FLAMETHROWER_START = 534 }; // Construction, copies and destruction (00a2a990, 00a2aa60, 00a2ab40, 00a2ac90) are the defaults. diff --git a/src/tainted_characters.cpp b/src/tainted_characters.cpp index 0e36eb9..3d98593 100644 --- a/src/tainted_characters.cpp +++ b/src/tainted_characters.cpp @@ -82,13 +82,6 @@ struct AnimaChain int duration = 0; }; -// Lemegeton's wisp config under Book of Virtues, among the extra wisp configs. -constexpr int LEMEGETON_VIRTUES_WISP = 0x10012; -// How many wisps each of the three wisp rings holds, from the innermost. -constexpr std::array WISP_RING_CAPACITY = {6, 8, 12}; -constexpr int WISP_RING_FIRST_LAYER = 7; -constexpr int WISP_PRIORITY_NONE = 9999; - // A locust flies out at a random angle, 6 to 10 pixels a frame, in one of its two flying states. constexpr float LOCUST_TURN = 3.14f * 2; constexpr float LOCUST_SPEED_MIN = 6; @@ -290,49 +283,6 @@ void lemegeton_use(ItemUse& use) sound_play(SOUND_DEVILROOM_DEAL); } -// 005c96f0 Adds an item wisp of a collectible on Lemegeton's ring (or Book of Virtues' Lemegeton ring): a full ring -// passes it on to the next unless the layer is fixed, and a ring still full loses its least important wisp. -Entity_Familiar* Entity_Player::AddItemWisp(int collectibleId, Vector position, bool isAdjustOrbitLayer) -{ - ItemConfig& config = g_manager->itemConfig; - WispEntry* own = config.wisp_config_get(HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) ? LEMEGETON_VIRTUES_WISP - : COLLECTIBLE_LEMEGETON); - int ring = own->layer; - if (ring >= 0) - { - std::array weakest{}; - std::array lowestPriority = {WISP_PRIORITY_NONE, WISP_PRIORITY_NONE, WISP_PRIORITY_NONE}; - std::array counts{}; - for (Entity* entity : g_game->room->GetEntities()->updateEL) - { - auto* wisp = entity && entity->type == ENTITY_FAMILIAR ? static_cast(entity) : nullptr; - bool isWisp = wisp && (wisp->variant == Entity_Familiar::WISP || wisp->variant == Entity_Familiar::ITEM_WISP); - if (!isWisp || wisp->player != this) continue; - - int wispItem = wisp->variant == Entity_Familiar::ITEM_WISP ? wisp->wispCollectibleType : wisp->subtype; - int layer = wisp->orbitLayer - WISP_RING_FIRST_LAYER; - if (layer < 0 || layer >= 3) continue; - int priority = config.wisp_config_get(wispItem)->priority; - if (wisp->variant == Entity_Familiar::WISP || priority < lowestPriority[layer]) - { - lowestPriority[layer] = priority; - weakest[layer] = wisp; - } - counts[layer]++; - } - for (int i = 0; isAdjustOrbitLayer && i < 3 && counts[ring] >= WISP_RING_CAPACITY[ring]; i++) - ring = (ring + 1) % 3; - if (counts[ring] >= WISP_RING_CAPACITY[ring] && weakest[ring]) weakest[ring]->Remove(); - } - - uint32_t seed = GetCollectibleRNG(COLLECTIBLE_LEMEGETON).Next(); - auto* wisp = static_cast( - g_game->Spawn({position, {}, this, collectibleId, ENTITY_FAMILIAR, Entity_Familiar::ITEM_WISP, seed})); - if (isAdjustOrbitLayer && ring >= 0) wisp->AddToOrbit(ring + WISP_RING_FIRST_LAYER); - wisp->Update(); - return wisp; -} - // The Tainted Jacob part of update_effects 00794e50: when Jacob's curse runs down to its last 10 frames, Dark Esau // (again) climbs out of a hole somewhere in the room, held off while Jacob cannot act. void tainted_frame_update(Entity_Player& player) diff --git a/src/weapon.cpp b/src/weapon.cpp index 4ec6835..2871ab5 100644 --- a/src/weapon.cpp +++ b/src/weapon.cpp @@ -4,8 +4,15 @@ #include "weapon_knives.h" #include "weapon_fetus.h" #include "weapon_ludovico.h" +#include "weapon_monstros_lung.h" #include "weapon_rockets.h" +#include "weapon_spirit_sword.h" +#include "weapon_deathmatch.h" +#include "weapon_umbilical_whip.h" +#include "weapon_urn_of_souls.h" +#include "boss_ai.h" #include "entity_familiar.h" +#include "entity_laser.h" #include "entity_player.h" #include "entity_tear.h" #include "game.h" @@ -13,10 +20,10 @@ #include "log.h" #include "manager.h" #include "menu_manager.h" +#include "npc_ai.h" #include #include -constexpr float DEGREES_TO_RADIANS = 0.017453292f; constexpr float EYE_DROPS_FAST_RATE = 0.5833333f; constexpr float EYE_DROPS_SLOW_RATE = 0.41666666f; constexpr float EYE_OFFSET_MIN = 0.3f; @@ -29,8 +36,6 @@ constexpr float INHERIT_SCALE = 0.6f; constexpr float IPECAC_SPEED_MIN = 0.9f; constexpr float IPECAC_SPEED_RANGE = 0.2f; constexpr float PEE_SPREAD = 24; -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 TEAR_SPEED_SPREAD = 0.2f; @@ -47,6 +52,17 @@ constexpr int SEEDED_VARIANT_SPEEDY = 2; constexpr int COLLECTIBLE_EYE_DROPS = 600; constexpr int COLLECTIBLE_KIDNEY_STONE_WEAPON = 440; constexpr int COLLECTIBLE_TECHNOLOGY_2 = 152; +// Technology 2: its laser's damage share, blink, depth (behind the player when aimed up or left), and the odds of +// Mom's Eye's and Loki's Horns' extra lasers, better with luck. +constexpr float TECHNOLOGY_2_DAMAGE = 0.13f; +constexpr int TECHNOLOGY_2_BLINK = 5; +constexpr float TECHNOLOGY_2_BEHIND = -0.5f; +constexpr float TECHNOLOGY_2_DEPTH_BEHIND = -10; +constexpr float TECHNOLOGY_2_DEPTH_FRONT = 3000; +constexpr int MOMS_EYE_LASER_CHANCE = 20; +constexpr float MOMS_EYE_LASER_LUCK = 1.5f; +constexpr int LOKIS_HORNS_LASER_CHANCE = 80; +constexpr float LOKIS_HORNS_LASER_LUCK = 5; constexpr int COLLECTIBLE_ISAACS_TEARS = 323; constexpr int TRINKET_TORN_CARD = 157; constexpr int BABY_SPIN = 8; @@ -69,9 +85,6 @@ enum CostumeLayers 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; } - // A vector turned by an angle in degrees. static Vector vector_rotate(Vector v, float degrees) { @@ -87,25 +100,20 @@ static Vector vector_spread(Vector v, float spreadAngle) return spreadAngle == 0 ? v : vector_rotate(v, (random_unit() - 0.5f) * spreadAngle); } -static Vector vector_scale(Vector v, float scale) { return vector_make(v.x * scale, v.y * scale); } - -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: tears (009f9260), the lasers // (weapon_laser_make), the knife and clubs (weapon_knife_make), Dr. Fetus (weapon_bomb_make), Epic Fetus -// (weapon_rocket_make), Ludovico (weapon_ludovico_make) and C Section (weapon_fetus_make). +// (weapon_rocket_make), Ludovico (weapon_ludovico_make), C Section (weapon_fetus_make), Monstro's Lung, the Spirit +// Sword, the Urn of Souls, the umbilical whip and the versus weapon. A type without a maker makes none. WeaponPtr weapon_create(WeaponType type, Entity* owner) { Weapon* made = type == WEAPON_TEARS ? new Weapon_Tears() : nullptr; for (auto make : {weapon_laser_make, weapon_knife_make, weapon_bomb_make, weapon_rocket_make, weapon_ludovico_make, - weapon_fetus_make}) + weapon_fetus_make, weapon_monstros_lung_make, weapon_spirit_sword_make, + weapon_urn_of_souls_make, weapon_umbilical_whip_make, weapon_deathmatch_make}) if (!made) made = make(type); - if (!made) reconstruction_missing("Isaac::CreateWeapon 009f9020 (Monstro's Lung, the Spirit Sword, the Urn of Souls, " - "the umbilical whip and the versus weapon)"); WeaponPtr weapon(made); - - weapon->Init(type, owner); + if (weapon) weapon->Init(type, owner); return weapon; } @@ -138,16 +146,84 @@ void Weapon::Update(bool isInterpolated) fireDelay -= owner ? owner->speedMultiplier : 1; } -// 009f3540 What every weapon fires alongside its own shots: Technology 2's laser, which is not written yet. Without it -// a laser left over is removed. -void Weapon::Fire(const Vector&, bool, bool) +// 0097e7c0 Whether a laser can hit this frame: not a Tractor Beam, interpolating or dead, and on its first update or +// every other tick. +bool laser_is_hit_frame(Entity_Laser& laser) +{ + if (laser.variant == LASER_TRACTOR_BEAM || laser.isInterpolating || laser.isDead) return false; + return laser.isFirstUpdate || laser.GetIntervalTicks(2, 0) != 0; +} + +// What a weapon does when its Technology 2 laser can hit this frame: Mom's Eye now and then (more with luck) fires a +// short laser backward, and Loki's Horns (rarer) one backward and to both sides. +void Weapon::technology2_extra_lasers(Entity_Player& player, const Vector& aim) +{ + bool isMomsEye = player.HasCollectible(COLLECTIBLE_MOMS_EYE) && + random_below(std::max(MOMS_EYE_LASER_CHANCE - (int)(player.luck * MOMS_EYE_LASER_LUCK), 1)) == 0; + if (!isMomsEye && (!player.HasCollectible(COLLECTIBLE_LOKIS_HORNS) || + random_below(std::max(LOKIS_HORNS_LASER_CHANCE - (int)(player.luck * LOKIS_HORNS_LASER_LUCK), 1)) != 0)) + return; + + auto fire = [&](Vector toward) { + fire_laser({.direction = toward, .position = get_owner_position(), .damageScale = TECHNOLOGY_2_DAMAGE, + .offsetId = LASER_OFFSET_MOMS_EYE, .isOneHit = true})->Update(); + }; + fire(vector_make(-aim.x, -aim.y)); + if (!player.HasCollectible(COLLECTIBLE_LOKIS_HORNS)) return; + fire(vector_make(aim.y, -aim.x)); + fire(vector_make(-aim.y, aim.x)); +} + +// 009f3540 What every weapon fires alongside its own shots: Technology 2's lasting laser from the eye toward the aim +// (snapped to the four directions unless free), weak and never explosive, made on the first frame of shooting (with +// its sound once the room has run a moment) and aimed, placed and tinted after. While it can hit, Mom's Eye and Loki's +// Horns may add lasers. Letting go removes it, unless a room transition is on. The umbilical whip has none. +void Weapon::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) { Entity_Player* player = owner_player(); - if (player && player->HasCollectible(COLLECTIBLE_TECHNOLOGY_2) && weaponType != WEAPON_UMBILICAL_WHIP) - reconstruction_missing("Weapon::Fire 009f3540 (Technology 2)"); + Entity_Laser* laser = static_cast(technology2Laser.get()); + bool isTechnology2 = player && player->HasCollectible(COLLECTIBLE_TECHNOLOGY_2) && weaponType != WEAPON_UMBILICAL_WHIP; + Vector aim = IsAxisAligned() ? vector_cardinal(shootDirection) : vector_normalized(shootDirection); + if (!isTechnology2 || !isShooting || vector_is_zero(aim)) + { + if (isTechnology2 && (g_game->roomTransition.mode != TRANSITION_NONE || isShooting)) return; + if (laser && !laser->isDead) laser->Remove(); + return; + } - Entity* laser = technology2Laser; - if (laser && !laser->isDead) laser->Remove(); + if (!laser) + { + laser = fire_laser({.direction = aim, .position = get_owner_position(), .offsetId = LASER_OFFSET_TECH2}); + laser->isDisableInitSound = true; + if (owner && g_game->room->isInitialized && g_game->room->GetFrameCount() > 1) + { + int sound = SOUND_REDLIGHTNING_ZAP_WEAK; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); + } + laser->timeout = -1; + laser->isDisableFollowParent = false; + laser->tearFlags.reset(TEAR_EXPLOSIVE); + technology2Laser = laser; + laser->damageMultiplier = TECHNOLOGY_2_DAMAGE; + laser->isPlayerParams = true; + laser->Update(); + } + else if (!isInterpolated) + { + laser->set_aim_angle(vector_angle(aim)); + Vector offset = GetOwnerLaserOffset(LASER_OFFSET_TECH2, aim); + laser->posOffset = vector_make(0, offset.y); + laser->parentOffset = vector_make(offset.x, 0); + laser->tearFlags = player->tearFlags; + laser->tearFlags.reset(TEAR_EXPLOSIVE); + laser->SetColor(player->get_laser_color_copy(), -1, TEAR_COLOR_PRIORITY, false, true); + laser->renderDepthOffset = aim.y <= TECHNOLOGY_2_BEHIND || aim.x <= TECHNOLOGY_2_BEHIND ? TECHNOLOGY_2_DEPTH_BEHIND + : TECHNOLOGY_2_DEPTH_FRONT; + } + + if (laser_is_hit_frame(*laser)) technology2_extra_lasers(*player, aim); + SetBlinkTime(TECHNOLOGY_2_BLINK); } // 009f3480 Drops the links and restarts the fire delay, charge and aim. The original also writes two fields nothing @@ -198,7 +274,7 @@ Entity_Player* Weapon::owner_player() bool Weapon::IsAxisAligned() { Entity_Player* player = owner_player(); - return player && is_zero(fixedDirection) && !player->HasCollectible(COLLECTIBLE_ANALOG_STICK) && + return player && vector_is_zero(fixedDirection) && !player->HasCollectible(COLLECTIBLE_ANALOG_STICK) && !player->HasCollectible(COLLECTIBLE_MARKED); } @@ -210,7 +286,7 @@ Vector Weapon::get_aim_direction(const Vector& defaultDirection) if (!player || (modifiers & WEAPON_MOD_FIXED_AIM)) return defaultDirection; bool isMarking = player->HasCollectible(COLLECTIBLE_MARKED) && player->markedTarget; - return !isMarking && is_zero(fixedDirection) ? player->delayed_shoot_direction() : defaultDirection; + return !isMarking && vector_is_zero(fixedDirection) ? player->delayed_shoot_direction() : defaultDirection; } // 009f3bd0 Where the owner stands. @@ -290,14 +366,14 @@ void Weapon::set_head_direction(int headDirection) // crashes in the original: here it carries none. Vector Weapon::get_tear_movement_inheritance(const Vector& shootDirection) { - if (!owner || !is_zero(fixedDirection)) return {}; + if (!owner || !vector_is_zero(fixedDirection)) return {}; if (owner->is_player()) return owner->ToPlayer()->GetTearMovementInheritance(shootDirection, INHERIT_CHECKED); Entity_Player* player = owner_player(); if (!player || (player->HasCollectible(COLLECTIBLE_MARKED) && player->markedTarget)) return {}; Vector inherited = vector_scale(player->velocity, INHERIT_SCALE * 2); - if (is_zero(shootDirection)) return inherited; + if (vector_is_zero(shootDirection)) return inherited; float length = std::sqrt(shootDirection.x * shootDirection.x + shootDirection.y * shootDirection.y); Vector normal = length > 0 ? vector_scale(shootDirection, 1 / length) : shootDirection; @@ -697,17 +773,19 @@ bool Weapon_Tears::CanTriggerCursedEyeTeleport() // 00a0a720 Fires the tears due this frame: one volley per fire delay passed (at most eight), from each eye Eye Drops // gives, alternating eyes, spread by the multi-shot items, with the extra backward, sideways and random shots. Shots // fired late in a frame start further along. Cain's one eye shoots from the right, Technology 2 leaves the right eye -// to its laser. Charged shots (Chocolate Milk, Cursed Eye, Neptunus) and G FUEL! are not written yet. The player field -// getters and the volley wrapper it calls are inlined (009f5830, 009f5850, 009f5870, 009f4230). +// to its laser. A familiar (Incubus, Cain's Other Eye, Twisted Pair) fires its player's volley from itself, with no +// eyes, spread or blink of a player. Charged shots (Chocolate Milk, Cursed Eye, Neptunus) and G FUEL! are not +// written yet. The player field getters and the volley wrapper it calls are inlined (009f5830, 009f5850, 009f5870, +// 009f4230). void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) { Weapon::Fire(shootDirection, isShooting, isInterpolated); - Entity_Player* player = owner && owner->is_player() ? owner->ToPlayer() : nullptr; - if (!player) reconstruction_missing("Weapon_Tears::Fire 00a0a720 (familiars' tears)"); + Entity_Player* shooter = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + Entity_Player* player = owner_player(); if (modifiers & (WEAPON_MOD_CHOCOLATE_MILK | WEAPON_MOD_CURSED_EYE | WEAPON_MOD_NEPTUNUS)) reconstruction_missing("Weapon_Tears::Fire 00a0a720 (charged shots)"); - if (player->get_seeded_variant() != SEEDED_VARIANT_NONE) + if (shooter && shooter->get_seeded_variant() != SEEDED_VARIANT_NONE) reconstruction_missing("Weapon_Tears::Fire 00a0a720 (G FUEL!)"); Vector aim = isShooting ? shootDirection : direction; @@ -717,11 +795,11 @@ void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isIn else if (float length = std::sqrt(aim.x * aim.x + aim.y * aim.y); length > 0) aim = vector_scale(aim, 1 / length); int eyeMode = 0; - if (player->playerType == PLAYER_CAIN || player->playerType == PLAYER_CAIN_B || - player->HasCollectible(COLLECTIBLE_LEAD_PENCIL) || player->HasCollectible(COLLECTIBLE_STAPLER)) + if (shooter && (shooter->playerType == PLAYER_CAIN || shooter->playerType == PLAYER_CAIN_B || + shooter->HasCollectible(COLLECTIBLE_LEAD_PENCIL) || shooter->HasCollectible(COLLECTIBLE_STAPLER))) eyeMode = 1; - else if (player->HasCollectible(COLLECTIBLE_TECHNOLOGY_2)) eyeMode = -1; - int eyeCount = eyeMode == 0 && player->HasCollectible(COLLECTIBLE_EYE_DROPS) ? 2 : 1; + else if (shooter && shooter->HasCollectible(COLLECTIBLE_TECHNOLOGY_2)) eyeMode = -1; + int eyeCount = shooter && eyeMode == 0 && shooter->HasCollectible(COLLECTIBLE_EYE_DROPS) ? 2 : 1; for (int eye = 0; eye < eyeCount; eye++) { @@ -752,40 +830,43 @@ void Weapon_Tears::Fire(const Vector& shootDirection, bool isShooting, bool isIn { Weapon_MultiShotParams params = GetMultiShotParams(); Vector shotDirection = aim; - int threshold = std::max(FIRE_BLINK_MIN, FIRE_BLINK_BASE - (int)(maxFireDelay * FIRE_BLINK_SCALE)); - player->blinkTime = std::max(player->blinkTime, threshold); + SetBlinkTime(std::max(FIRE_BLINK_MIN, FIRE_BLINK_BASE - (int)(maxFireDelay * FIRE_BLINK_SCALE))); TriggerTearEffects(shotDirection, 1); - if (eyeMode != 0) player->tearDisplacement = (int8_t)eyeMode; - else player->tearDisplacement = (int8_t)(eyeCount == 2 ? (eye == 0 ? -1 : 1) : -tear_displacement()); - int eyeSide = tear_displacement(); - if (is_shot_rotated()) shotDirection = vector_rotate(shotDirection, (float)eyeSide * SHOT_ROTATION_STEP); - if (params.numTears > 1 || player->HasCollectible(COLLECTIBLE_POLYPHEMUS) || - player->HasCollectible(COLLECTIBLE_IPECAC)) - eyeSide = 0; - if (player->HasCollectible(COLLECTIBLE_NUMBER_ONE) || - player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_NUMBER_ONE) || - player->HasCollectible(COLLECTIBLE_KIDNEY_STONE_WEAPON)) + int eyeSide = 0; + if (shooter) { - eyeSide = 0; - player->blinkTime = std::max(player->blinkTime, NUMBER_ONE_BLINK); + if (eyeMode != 0) shooter->tearDisplacement = (int8_t)eyeMode; + else shooter->tearDisplacement = (int8_t)(eyeCount == 2 ? (eye == 0 ? -1 : 1) : -tear_displacement()); + eyeSide = tear_displacement(); + if (is_shot_rotated()) shotDirection = vector_rotate(shotDirection, (float)eyeSide * SHOT_ROTATION_DEGREES); + if (params.numTears > 1 || shooter->HasCollectible(COLLECTIBLE_POLYPHEMUS) || + shooter->HasCollectible(COLLECTIBLE_IPECAC)) + eyeSide = 0; + if (shooter->HasCollectible(COLLECTIBLE_NUMBER_ONE) || + shooter->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_NUMBER_ONE) || + shooter->HasCollectible(COLLECTIBLE_KIDNEY_STONE_WEAPON)) + { + eyeSide = 0; + shooter->blinkTime = std::max(shooter->blinkTime, NUMBER_ONE_BLINK); + } } - Vector firePos = player->pos; + Vector firePos = owner ? owner->pos : Vector{}; Vector base = vector_add(vector_scale(shotDirection, SHOT_SPEED_BASE), get_tear_movement_inheritance(shotDirection)); - if (player->HasCollectible(COLLECTIBLE_IPECAC)) + if (player && player->HasCollectible(COLLECTIBLE_IPECAC)) base = vector_scale(base, random_unit() * IPECAC_SPEED_RANGE + IPECAC_SPEED_MIN); float spreadAngle = 0; - if (player->HasCollectible(COLLECTIBLE_EPIPHORA) && player->epiphoraCharge > 0) - spreadAngle = (float)(player->epiphoraCharge / EPIPHORA_FRAMES_PER_STEP) * EPIPHORA_SPREAD / + if (shooter && shooter->HasCollectible(COLLECTIBLE_EPIPHORA) && shooter->epiphoraCharge > 0) + spreadAngle = (float)(shooter->epiphoraCharge / EPIPHORA_FRAMES_PER_STEP) * EPIPHORA_SPREAD / EPIPHORA_SPREAD_DIVISOR; - int pee = player->peeBurstCooldown; - int peeMax = player->maxPeeBurstCooldown; + int pee = shooter ? shooter->peeBurstCooldown : 0; + int peeMax = shooter ? shooter->maxPeeBurstCooldown : 0; if (pee > 0 && peeMax > 0 && pee < peeMax - 1) spreadAngle += (float)pee * PEE_SPREAD / (float)peeMax; - float speed = player->shotSpeed; + float speed = player ? player->shotSpeed : 1; auto extra_fire = [&](Vector velocity) { fire_tear({firePos, vector_spread(vector_scale(velocity, speed), spreadAngle)}, TEAR_FIRE_EXTRA_SHOT, 1, positionStep); diff --git a/src/weapon.h b/src/weapon.h index 814e898..57b34ed 100644 --- a/src/weapon.h +++ b/src/weapon.h @@ -10,6 +10,8 @@ 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; +// How far R U A Wizard and the spinning co-op baby turn shots per eye side. +constexpr float SHOT_ROTATION_DEGREES = 45; // What a player or familiar shoots (Lua's WeaponType). Slot 16 is the deathmatch's. enum WeaponType : int @@ -243,6 +245,7 @@ struct Weapon int marked_target_variant(); int tear_displacement(); bool is_shot_rotated(); + float held_scale(); void SetBlinkTime(int delay); void SetHeadLockTime(int time); void set_head_direction(int headDirection); @@ -262,11 +265,11 @@ struct Weapon 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); + void technology2_extra_lasers(Entity_Player& player, const Vector& aim); Entity_Laser* fire_tech_x_laser(const TechXShot& shot); Entity_Knife* fire_knife(Entity* knifeParent, int knifeVariant, bool isCantOverwrite, float rotationOffset); Entity_Knife* fire_bone_club(Entity* clubParent, int clubVariant, bool isCantOverwrite, float rotationOffset); - Entity_Knife* FireSword(Entity* swordParent, int swordVariant, float rotationOffset, bool isUnknown1, - bool isUnknown2, int unknown3, Entity* unknown4); + Entity_Knife* FireSword(const KnifeShot& shot); }; // Destroys a weapon as Isaac::DestoryWeapon does: its links dropped first, then freed. @@ -296,6 +299,7 @@ struct Weapon_Tears : Weapon }; WeaponPtr weapon_create(WeaponType type, Entity* owner); +bool laser_is_hit_frame(Entity_Laser& laser); Vector weapon_steer_aim(Entity_Player* player, Vector aim); 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); diff --git a/src/weapon_deathmatch.cpp b/src/weapon_deathmatch.cpp new file mode 100644 index 0000000..e553ff3 --- /dev/null +++ b/src/weapon_deathmatch.cpp @@ -0,0 +1,103 @@ +#include "weapon_deathmatch.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "npc_ai.h" +#include +#include + +constexpr float BARF_FIRE_DELAY = 20; +constexpr float BARF_CHARGE_MIN = 0.001f; +constexpr int BARF_BLINK_MIN = 11; +constexpr int BARF_BLINK_BASE = 7; +constexpr float BARF_BLINK_SHARE = -0.45f; +constexpr float BARF_SPEED = 10; +constexpr float BARF_SCATTER_TURN = 6.28f; +constexpr float BARF_SCATTER = 3.5f; +constexpr float BARF_SPEED_MIN = 0.4f; +constexpr float BARF_SPEED_SPREAD = 0.6f; +constexpr float BARF_FALL_ACCEL = 0.8f; +constexpr float BARF_FALL_SPEED_MIN = -1; +constexpr float BARF_FALL_SPEED_SPREAD = 8; +constexpr uint32_t BARF_FUSE_SPREAD = 15; +constexpr int BARF_FUSE_MIN = 15; +constexpr float BARF_DAMAGE = 25; +constexpr float BARF_SIZE_MIN = 0.4f; +constexpr float BARF_SIZE_STEP = 0.2f; +constexpr float BARF_SIZE_SPREAD = 0.15f; +constexpr float HEAD_CHARGE_FRAME_NONE = -1; + +// 009f9080 009f9020's maker for the versus weapon, or none for the other types. +Weapon* weapon_deathmatch_make(WeaponType type) +{ + return type == WEAPON_DEATHMATCH ? new Weapon_Deathmatch() : nullptr; +} + +// 00a036b0 A barf takes one fire delay of charge. +float Weapon_Deathmatch::GetMaxCharge() { return std::max(maxFireDelay, BARF_CHARGE_MIN); } + +// One bomb thrown along the aim, scattered a little, at a random share of the shot speed: a player's falls in an arc +// with a fuse cut by up to 15 frames (at least 15). Each is weak, small and of a random size. +void Weapon_Deathmatch::barf(const Vector& aim) +{ + Entity_Player* player = owner_player(); + UpdateHeadChargeAnimation(COLLECTIBLE_MONSTROS_LUNG, HEAD_CHARGE_SHOOT, aim, HEAD_CHARGE_FRAME_NONE); + float delay = std::max(maxFireDelay, BARF_CHARGE_MIN); + float held = std::min(std::max(GetMaxCharge(), charge), delay); + SetBlinkTime(std::max(BARF_BLINK_MIN, BARF_BLINK_BASE - (int)(held * BARF_BLINK_SHARE))); + + Vector thrown = vector_scale(vector_add(vector_scale(aim, BARF_SPEED), get_tear_movement_inheritance(aim)), + player ? player->shotSpeed : 1); + float angle = random_unit() * BARF_SCATTER_TURN; + float scatter = random_unit() * BARF_SCATTER; + float speed = random_unit() * BARF_SPEED_SPREAD + BARF_SPEED_MIN; + Vector velocity = vector_scale(vector_add(vector_make(std::cos(angle) * scatter, std::sin(angle) * scatter), thrown), + speed); + Entity_Bomb* bomb = fire_bomb(*this, {get_owner_position(), velocity}); + if (player) + { + bomb->fallAcceleration = BARF_FALL_ACCEL; + bomb->fallSpeed = BARF_FALL_SPEED_MIN - random_unit() * BARF_FALL_SPEED_SPREAD; + bomb->explosionCountdown = std::max(bomb->explosionCountdown - (int)(Random() % BARF_FUSE_SPREAD), BARF_FUSE_MIN); + bomb->explosionCountdown2 = bomb->explosionCountdown; + } + + uint32_t step = Random() & 1; + float size = random_unit() * BARF_SIZE_SPREAD + (float)step * BARF_SIZE_STEP + BARF_SIZE_MIN; + bomb->isLoadCostumes = true; + bomb->explosionDamage = BARF_DAMAGE; + bomb->radiusMultiplier *= size; + bomb->scale *= size; +} + +// 00a031b0 Held, the head charges toward the aim (snapped to the four directions unless free); on release a full +// charge barfs, the charge empties and the head's animation ends once played. +void Weapon_Deathmatch::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + maxFireDelay = BARF_FIRE_DELAY; + Weapon::Fire(shootDirection, isShooting, isInterpolated); + if (isInterpolated) return; + + float maxCharge = GetMaxCharge(); + if (isShooting) + { + if (maxCharge <= charge) UpdateHeadChargeAnimation(COLLECTIBLE_MONSTROS_LUNG, HEAD_CHARGE_CHARGED, shootDirection, HEAD_CHARGE_FRAME_NONE); + else + { + charge += owner ? owner->speedMultiplier : 1; + UpdateHeadChargeAnimation(COLLECTIBLE_MONSTROS_LUNG, HEAD_CHARGE_CHARGING, shootDirection, + charge / maxCharge * HEAD_CHARGE_FRAMES); + } + SetBlinkTime(1); + direction = shootDirection; + return; + } + + Vector aim = IsAxisAligned() ? vector_cardinal(direction) : vector_normalized(get_aim_direction(direction)); + if (std::max(maxFireDelay, BARF_CHARGE_MIN) <= charge) barf(aim); + charge = 0; + if (!IsItemAnimFinished(COLLECTIBLE_MONSTROS_LUNG)) return; + if (owner && owner->IsFamiliar()) static_cast(owner)->fireCooldown = 0; + else if (owner && owner->is_player()) owner->ToPlayer()->stop_costume_item_anims(); +} diff --git a/src/weapon_deathmatch.h b/src/weapon_deathmatch.h new file mode 100644 index 0000000..d223b41 --- /dev/null +++ b/src/weapon_deathmatch.h @@ -0,0 +1,16 @@ +#pragma once + +#include "weapon.h" + +// Destruction (009f3260) is the base's. +// The versus mode's bomb barf (in Monstro's Lung's costume): held, it charges over one fire delay (fixed at 20), and +// a release once charged coughs up one small bomb with a short random fuse. +struct Weapon_Deathmatch : Weapon +{ + void Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) override; + float GetMaxCharge() override; + + void barf(const Vector& aim); +}; + +Weapon* weapon_deathmatch_make(WeaponType type); diff --git a/src/weapon_fetus.cpp b/src/weapon_fetus.cpp index 12b5d99..9119dc9 100644 --- a/src/weapon_fetus.cpp +++ b/src/weapon_fetus.cpp @@ -1,7 +1,10 @@ #include "weapon_fetus.h" #include "boss_ai.h" #include "entity_player.h" +#include "entity_effect.h" +#include "entity_familiar.h" #include "entity_tear.h" +#include "game.h" #include "item_config.h" #include "log.h" #include "manager.h" @@ -22,6 +25,17 @@ constexpr float FETUS_BLINK_SHARE = -0.15f; constexpr int FETUS_BLINK_MIN = 11; constexpr float C_SECTION_FRAME_KEEP = -1; +// A thrown fetus: its share of the damage, its range without a player, and its birth's blood (only for a fetus +// thrown fast enough): the puff above it, the droplets' spread and how many follow the drops. +constexpr float FETUS_DAMAGE_SHARE = 0.75f; +constexpr float FETUS_RANGE_DEFAULT = 260; +constexpr float FETUS_BIRTH_SPEED_SQUARED = 0.001f; +constexpr int FETUS_BIRTH_PUFF_SUBTYPE = 2; +constexpr float FETUS_BIRTH_PUFF_LIFT = -15; +constexpr int FETUS_BIRTH_DROPLETS = 4; +constexpr float FETUS_BIRTH_SPREAD = 20; +constexpr int FETUS_DROPLET_SUBTYPE = 99; + // 009f9020's maker for C Section's weapon (009f95d0), or none for the other types. Weapon* weapon_fetus_make(WeaponType type) { @@ -40,10 +54,112 @@ int Weapon_Fetus::GetMarkedTargetVariant() return marked_target_variant(); } -// 009f6e60 -Entity_Tear* fire_fetus_tear(Weapon&, const FetusShot&) +// The weapons a fetus carries by its player's items, in C Section's fetus flags. +struct FetusWeapon { - reconstruction_missing("fire_fetus_tear 009f6e60"); + int collectible = 0; + int flag = 0; +}; + +constexpr std::array FETUS_WEAPONS = {{ + {COLLECTIBLE_DR_FETUS, TEAR_FETUS_BOMBER}, + {COLLECTIBLE_EPIC_FETUS, TEAR_FETUS_BOMBER}, + {COLLECTIBLE_TECHNOLOGY, TEAR_FETUS_TECH}, + {COLLECTIBLE_TECH_X, TEAR_FETUS_TECHX}, + {COLLECTIBLE_BRIMSTONE, TEAR_FETUS_BRIMSTONE}, + {COLLECTIBLE_MOMS_KNIFE, TEAR_FETUS_KNIFE}, +}}; + +// Skins the fetus like its player's body, The Forgotten's bones for a bone fetus. +static void fetus_skin_apply(Entity_Tear& tear, Entity_Player& player) +{ + if (tear.variant != TEAR_FETUS || tear.sprite.layerStates.empty()) return; + int playerType = tear.tearFlags[TEAR_BONE_FLAG] ? PLAYER_THEFORGOTTEN : player.playerType; + const std::string& sheet = tear.sprite.GetLayer(0)->spriteSheetPath; + std::string skinned = costume_path_apply_skin_color(sheet, player.bodyColor, playerType, nullptr, nullptr); + if (skinned == sheet) return; + tear.sprite.ReplaceSpritesheet(0, skinned); + tear.sprite.LoadGraphics(); +} + +// The birth of a thrown fetus: a puff of blood behind it and one or two drops with a few droplets spraying ahead. +static void fetus_birth_splash(Entity_Tear& tear) +{ + Entity* puff = g_game->Spawn({.position = tear.pos, .velocity = tear.velocity, .subType = FETUS_BIRTH_PUFF_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + puff->posOffset = vector_make(0, FETUS_BIRTH_PUFF_LIFT); + puff->Update(); + + int drops = (int)(Random() & 1) + 1; + int count = (int)(Random() & 1) + drops + FETUS_BIRTH_DROPLETS; + for (int i = 0; i < count; i++) + { + float turn = (random_unit() * FETUS_BIRTH_SPREAD - FETUS_BIRTH_SPREAD / 2) * DEGREES_TO_RADIANS; + float share = random_unit(); + Vector v = tear.velocity; + Vector dropVelocity = vector_make((std::cos(turn) * v.x - std::sin(turn) * v.y) * share, + (std::sin(turn) * v.x + std::cos(turn) * v.y) * share); + Entity* drop = g_game->Spawn({.position = vector_add(tear.pos, dropVelocity), .velocity = dropVelocity, + .subType = i < drops ? 0 : FETUS_DROPLET_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, .seed = Random()}); + drop->Update(); + } +} + +// 009f6e60 Throws a fetus (a C Section tear) for the weapon's owner (or a given source): its player's fetus hit +// params at three quarters of the damage, spectral, never held by Marked, the Tractor Beam or a laser, carrying the +// weapons its player's items give, skinned like its player and born in a splash of blood. It updates once and steps +// back a frame. A familiar throws for its player. The original reads a missing player's effects and type. This skips +// them. +Entity_Tear* fire_fetus_tear(Weapon& weapon, const FetusShot& shot) +{ + Entity* owner = shot.source ? shot.source : weapon.owner; + Entity_Player* player = nullptr; + if (owner->is_player()) player = owner->ToPlayer(); + else if (owner->type == ENTITY_FAMILIAR) player = static_cast(owner)->player; + + TearParams params; + if (player) + { + params = player->GetTearHitParams(WEAPON_FETUS, shot.damageMultiplier, (int)(Random() & 1) * 2 - 1, owner); + if (player->HasCollectible(COLLECTIBLE_MARKED)) params.tearFlags.reset(TEAR_WAIT); + } + params.tearFlags.reset(TEAR_TRACTOR_BEAM); + params.tearFlags.reset(TEAR_LASERSHOT); + params.tearFlags.set(TEAR_FETUS_FLAG); + params.tearFlags.set(TEAR_SPECTRAL); + if (player) + { + for (const FetusWeapon& carried : FETUS_WEAPONS) + if (player->HasCollectible(carried.collectible)) params.tearFlags.set(carried.flag); + if (weapon.weaponType == WEAPON_BONE) params.tearFlags.set(TEAR_FETUS_BONE); + if (player->HasCollectible(COLLECTIBLE_SPIRIT_SWORD)) params.tearFlags.set(TEAR_FETUS_SWORD); + } + + uint32_t seed = Random(); + Entity* spawned = g_game->Spawn({.position = vector_add(shot.velocity, shot.position), .velocity = shot.velocity, + .spawner = weapon.owner, .type = ENTITY_TEAR, .variant = params.tearVariant, + .seed = seed}); + Entity_Tear& tear = *spawned->ToTear(); + tear.velocity = vector_scale(tear.velocity, params.speedMultiplier); + tear.SetHeight(params.tearHeight); + tear.SetCollisionDamage(params.tearDamage * FETUS_DAMAGE_SHARE); + tear.SetTearFlags(params.tearFlags); + tear.SetScale(params.tearScale); + tear.SetColor(params.tearColor, -1, TEAR_COLOR_PRIORITY, false, true); + tear.tearRange = player ? player->tearRange : FETUS_RANGE_DEFAULT; + tear.parent = player; + if (shot.fireFlags & TEAR_FIRE_NO_STREAK_END) tear.isCanTriggerStreakEnd = false; + if (player) + { + float glow = dead_eye_glow_get(*player); + if (glow > 0) tear.SetDeadEyeIntensity(glow); + fetus_skin_apply(tear, *player); + } + if (vector_length_squared(shot.velocity) > FETUS_BIRTH_SPEED_SQUARED) fetus_birth_splash(tear); + tear.Update(); + tear.pos = vector_sub(tear.pos, tear.velocity); + return &tear; } // Throws the fetuses of a full charge: the fire delay restarts at a third of the charge (a familiar blinks), the tear diff --git a/src/weapon_knives.cpp b/src/weapon_knives.cpp index 1836c99..3c2cd4d 100644 --- a/src/weapon_knives.cpp +++ b/src/weapon_knives.cpp @@ -315,7 +315,6 @@ constexpr float CLUB_SWING_PITCH_SPREAD = 0.2f; constexpr float CLUB_SWING_PITCH_MIN = 0.5f; constexpr float CLUB_RANDOM_TURN = 360; constexpr float FLYING_OFFSET_SCALE = 0.65f; -constexpr float SHOT_ROTATION_DEGREES = 45; // 009f6af0 Fires a bone club through the owning player (Entity_Player::FireBoneClub 007ae030): spawned by the player // from its position, hanging from a parent at an angle with the player's tear color, flags and damage, raised by the @@ -481,9 +480,9 @@ int Weapon_Bone::club_variant() return KNIFE_BONE_CLUB; } -// How big the clubs are: as big as the player (at least normal), a familiar's smaller, four times under Mega Mush, -// doubled by Polyphemus or half again by Haemolacria. -float Weapon_Bone::club_scale() +// How big the held clubs and swords are: as big as the player (at least normal), a familiar's smaller, four times +// under Mega Mush, doubled by Polyphemus or half again by Haemolacria. Notched Axe keeps the owner's size. +float Weapon::held_scale() { float size = 1; if (owner && owner->is_player()) @@ -697,7 +696,7 @@ void Weapon_Bone::Fire(const Vector& shootDirection, bool isShooting, bool isInt reconstruction_missing("Weapon_Bone::Fire 009fa450 (the clubs with a charging item, Dr. Fetus, Epic Fetus, " "Ludovico or rapid swings)"); - float clubScale = club_scale(); + float clubScale = held_scale(); int variant = club_variant(); float maxCharge = std::max(maxFireDelay, KNIFE_CHARGE_MINIMUM) * CLUB_CHARGE_DELAYS; clubs_hold(variant); diff --git a/src/weapon_knives.h b/src/weapon_knives.h index cd2c774..c49f8e1 100644 --- a/src/weapon_knives.h +++ b/src/weapon_knives.h @@ -74,7 +74,6 @@ struct Weapon_Bone : Weapon void init_club(Entity_Knife& club); int club_variant(); - float club_scale(); void clubs_hold(int variant); Vector shot_direction(const Vector& shootDirection); ClubSwing club_swing_get(); diff --git a/src/weapon_monstros_lung.cpp b/src/weapon_monstros_lung.cpp new file mode 100644 index 0000000..020cd6f --- /dev/null +++ b/src/weapon_monstros_lung.cpp @@ -0,0 +1,234 @@ +#include "weapon_monstros_lung.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "npc_ai.h" +#include "sfx_manager.h" +#include +#include + +// The charge: the fire delay (never quite none), Chocolate Milk's two and a half, and its share by a Marked target's +// distance (a quarter near it, two and a half past 300). +constexpr float LUNG_CHARGE_MIN = 0.001f; +constexpr float LUNG_CHOCOLATE_CHARGE = 2.5f; +constexpr float LUNG_CHOCOLATE_NEAR = 0.25f; +constexpr float LUNG_TARGET_NEAR = 50; +constexpr float LUNG_TARGET_SPAN = 250; +// The release: its blink, the cough's speed and Ipecac's slowing, Chocolate Milk's damage by the charge, and the +// tears a cough throws (fewer with Haemolacria or Dr. Fetus), each lane of the volley adding its share. +constexpr int LUNG_BLINK_BASE = 7; +constexpr float LUNG_BLINK_SHARE = -0.45f; +constexpr int LUNG_BLINK_MIN = 11; +constexpr float LUNG_SHOT_SPEED = 10; +constexpr float LUNG_IPECAC_MIN = 0.7f; +constexpr float LUNG_IPECAC_SPREAD = 0.2f; +constexpr float LUNG_DAMAGE_SHARE_MIN = 0.02f; +constexpr float LUNG_DAMAGE_SHARE_MAX = 2.5f; +constexpr float LUNG_DAMAGE_SCALE = 0.8f; +constexpr int LUNG_TEARS = 12; +constexpr int LUNG_TEARS_HAEMOLACRIA = 7; +constexpr int LUNG_TEARS_FEW = 5; +constexpr float LUNG_TEARS_PER_LANE = 5; +// A cough's tears: their scatter, fall (higher with Ipecac and Haemolacria, lifted by falling tears) and sizes, and +// Dr. Fetus' bombs' throw, fuse and sizes. +constexpr float COUGH_SCATTER = 3.5f; +constexpr float COUGH_LIFT_FALLING = -10; +constexpr float COUGH_FALL_ACCEL = 0.5f; +constexpr float COUGH_FALL_LOW = 5; +constexpr float COUGH_FALL_LOW_SPREAD = 15; +constexpr float COUGH_FALL_HIGH = -5; +constexpr float COUGH_FALL_HIGH_SPREAD = 10; +constexpr float COUGH_SCALE_MIN = 0.9f; +constexpr float COUGH_SCALE_BIG = 0.4f; +constexpr float COUGH_SCALE_SPREAD = 0.05f; +constexpr float COUGH_BOMB_SPEED_MIN = 0.4f; +constexpr float COUGH_BOMB_SPEED_SPREAD = 0.6f; +constexpr float COUGH_BOMB_FALL_ACCEL = 0.8f; +constexpr float COUGH_BOMB_LIFT = -1; +constexpr float COUGH_BOMB_LIFT_SPREAD = 8; +constexpr int COUGH_BOMB_FUSE_SPREAD = 15; +constexpr int COUGH_BOMB_FUSE_MIN = 15; +constexpr float COUGH_BOMB_SCALE_MIN = 0.4f; +constexpr float COUGH_BOMB_SCALE_BIG = 0.2f; +constexpr float COUGH_BOMB_SCALE_SPREAD = 0.15f; +// The target Marked places, and Eye of the Occult's. +constexpr int LUNG_MARKED_TARGET = 30; +constexpr int LUNG_OCCULT_TARGET = 153; + +// 009f9020's maker for Monstro's Lung's weapon, or none for the other types. +Weapon* weapon_monstros_lung_make(WeaponType type) +{ + return type == WEAPON_MONSTROS_LUNGS ? new Weapon_MonstrosLung() : nullptr; +} + +// 00a08c80 The charge a cough takes: the fire delay, two and a half times with Chocolate Milk. +float Weapon_MonstrosLung::GetMaxCharge() +{ + float multiplier = (modifiers & WEAPON_MOD_CHOCOLATE_MILK) ? LUNG_CHOCOLATE_CHARGE : 1; + return std::max(maxFireDelay, LUNG_CHARGE_MIN) * multiplier; +} + +// 00a08cd0 Marked's target, Eye of the Occult's with it, or none without Marked. The original reads a missing +// player's items. This places none. +int Weapon_MonstrosLung::GetMarkedTargetVariant() +{ + Entity_Player* player = owner_player(); + if (!player || !player->HasCollectible(COLLECTIBLE_MARKED)) return 0; + return player->HasCollectible(COLLECTIBLE_EYE_OF_THE_OCCULT) ? LUNG_OCCULT_TARGET : LUNG_MARKED_TARGET; +} + +// 00a08700 Coughs count tears from the owner at a velocity scaled by its player's shot speed, each scattered at +// random, falling as its player's tears do (higher with Ipecac or Haemolacria), a few larger. With Dr. Fetus it +// throws small bombs with short fuses instead. +void Weapon_MonstrosLung::FireBurst(const Vector& velocity, int count, float damageMultiplier) +{ + Entity_Player* player = owner_player(); + Vector from = owner ? owner->pos : Vector{}; + for (int i = 0; i < count; i++) + { + float shotSpeed = player ? player->shotSpeed : 1; + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float scatter = random_unit() * COUGH_SCATTER; + Vector shot = vector_make(std::cos(angle) * scatter + velocity.x * shotSpeed, + std::sin(angle) * scatter + velocity.y * shotSpeed); + + if (player && player->HasCollectible(COLLECTIBLE_DR_FETUS)) + { + shot = vector_scale(shot, random_unit() * COUGH_BOMB_SPEED_SPREAD + COUGH_BOMB_SPEED_MIN); + Entity_Bomb* bomb = fire_bomb(*this, {from, shot}); + bomb->fallAcceleration = COUGH_BOMB_FALL_ACCEL; + bomb->fallSpeed = COUGH_BOMB_LIFT - random_unit() * COUGH_BOMB_LIFT_SPREAD; + int fuse = std::max(bomb->explosionCountdown - (int)(Random() % COUGH_BOMB_FUSE_SPREAD), COUGH_BOMB_FUSE_MIN); + bomb->explosionCountdown = fuse; + bomb->explosionCountdown2 = fuse; + uint32_t big = Random() & 1; + float size = random_unit() * COUGH_BOMB_SCALE_SPREAD + (float)big * COUGH_BOMB_SCALE_BIG + COUGH_BOMB_SCALE_MIN; + bomb->isLoadCostumes = true; + bomb->radiusMultiplier *= size; + bomb->scale *= size; + continue; + } + + Entity_Tear* tear = fire_tear({from, shot}, 0, damageMultiplier, 0); + if (g_game->deathmatchManager.is_active()) + reconstruction_missing("Weapon_MonstrosLung::FireBurst 00a08700 (versus tears)"); + if (player && player->tearFallingAcceleration > 0) + tear->fallingSpeed = random_unit() * COUGH_LIFT_FALLING - tear->fallingSpeed; + else if (player) + { + tear->fallingAccel = player->tearFallingAcceleration + COUGH_FALL_ACCEL; + bool isHigh = player->HasCollectible(COLLECTIBLE_IPECAC) || player->HasCollectible(COLLECTIBLE_HAEMOLACRIA); + float lift = isHigh ? COUGH_FALL_HIGH - random_unit() * COUGH_FALL_HIGH_SPREAD + : COUGH_FALL_LOW - random_unit() * COUGH_FALL_LOW_SPREAD; + tear->fallingSpeed = lift - player->tearFallingSpeed; + } + uint32_t big = Random() & 1; + float size = (float)big * COUGH_SCALE_BIG + COUGH_SCALE_MIN + random_unit() * COUGH_SCALE_SPREAD; + tear->SetScale(size * tear->fScale); + } +} + +// 00a07d50 Monstro's Lung: while shooting the charge grows at the owner's speed (the head shows it), the aim follows +// the shots and the body blinks. A full charge (Chocolate Milk's by a Marked target's distance, Soy Milk's at once) +// coughs: twelve tears per lane of the volley (fewer with Haemolacria or Dr. Fetus, fewer and stronger for a short +// Chocolate Milk charge), the backward, sideways and random ones, and a barf. The charge then resets and the +// costumes settle. +void Weapon_MonstrosLung::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Weapon::Fire(shootDirection, isShooting, isInterpolated); + if (isInterpolated) return; + + Entity_Player* player = owner_player(); + bool isMarked = player && player->HasCollectible(COLLECTIBLE_MARKED); + bool isChocolate = modifiers & WEAPON_MOD_CHOCOLATE_MILK; + bool isInstant = (modifiers & WEAPON_MOD_SOY_MILK) || maxFireDelay <= 0; + float delay = std::max(maxFireDelay, LUNG_CHARGE_MIN); + Vector aim = IsAxisAligned() ? vector_cardinal(direction) : vector_normalized(get_aim_direction(direction)); + Vector target = fixedDirection; + if (isMarked && player->markedTarget) target = player->markedTarget->pos; + bool isTargeted = !vector_is_zero(target); + float maxCharge = GetMaxCharge(); + + bool isReleasing = !isShooting; + if (isShooting && isTargeted) + { + if (isChocolate) + { + float distance = vector_length(vector_sub(target, get_owner_position())); + float t = std::clamp((distance - LUNG_TARGET_NEAR) / LUNG_TARGET_SPAN, 0.0f, 1.0f); + maxCharge = (delay * LUNG_CHOCOLATE_CHARGE - delay * LUNG_CHOCOLATE_NEAR) * t + delay * LUNG_CHOCOLATE_NEAR; + } + isReleasing = maxCharge <= charge; + } + if (isShooting && !isReleasing && isInstant) isReleasing = std::max(maxCharge, LUNG_CHARGE_MIN) <= charge; + if (!isReleasing) + { + if (maxCharge <= charge) UpdateHeadChargeAnimation(COLLECTIBLE_MONSTROS_LUNG, HEAD_CHARGE_CHARGED, shootDirection, -1); + else + { + charge += owner ? owner->speedMultiplier : 1; + UpdateHeadChargeAnimation(COLLECTIBLE_MONSTROS_LUNG, HEAD_CHARGE_CHARGING, shootDirection, + charge / maxCharge * HEAD_CHARGE_FRAMES); + if (maxCharge <= charge) sound_play(SOUND_MONSTRO_LUNG_CHARGE); + } + SetBlinkTime(1); + direction = shootDirection; + return; + } + + float releaseCharge = isChocolate ? std::min(delay, 1.0f) : std::max(delay, LUNG_CHARGE_MIN); + if (releaseCharge <= charge) + { + UpdateHeadChargeAnimation(COLLECTIBLE_MONSTROS_LUNG, HEAD_CHARGE_SHOOT, aim, -1); + float spent = std::min(std::max(maxCharge, charge), releaseCharge); + SetBlinkTime(std::max(LUNG_BLINK_BASE - (int)(spent * LUNG_BLINK_SHARE), LUNG_BLINK_MIN)); + Vector base = vector_add(vector_scale(aim, LUNG_SHOT_SPEED), get_tear_movement_inheritance(aim)); + if (player && player->HasCollectible(COLLECTIBLE_IPECAC)) + base = vector_scale(base, random_unit() * LUNG_IPECAC_SPREAD + LUNG_IPECAC_MIN); + + float damageMultiplier = 1; + if (isChocolate) + damageMultiplier = std::clamp(charge / delay, LUNG_DAMAGE_SHARE_MIN, LUNG_DAMAGE_SHARE_MAX) * LUNG_DAMAGE_SCALE; + Weapon_MultiShotParams params = GetMultiShotParams(); + int count = LUNG_TEARS; + if (player && player->HasCollectible(COLLECTIBLE_HAEMOLACRIA)) + count = player->HasCollectible(COLLECTIBLE_BRIMSTONE) ? LUNG_TEARS_FEW : LUNG_TEARS_HAEMOLACRIA; + if (player && player->HasCollectible(COLLECTIBLE_DR_FETUS)) count = LUNG_TEARS_FEW; + if (damageMultiplier < 1) + { + int full = count; + count = std::max((int)std::ceil((float)full * damageMultiplier), 1); + damageMultiplier *= (float)full / (float)count; + } + TriggerTearEffects(aim, count); + + int perBurst = count + (int)((float)count / LUNG_TEARS_PER_LANE * (float)params.numTears); + for (int i = 0; i < params.numEyesActive; i++) + { + float angle = 0; + if (params.numEyesActive > 1) + angle = lerp_clamped((float)i, 0, (float)params.numEyesActive - 1, -params.multiEyeAngle, + params.multiEyeAngle); + FireBurst(tear_vector_rotate(base, angle), perBurst, damageMultiplier); + } + if (params.isShootingBackwards) FireBurst(vector_make(-base.x, -base.y), perBurst, damageMultiplier); + if (params.isShootingSideways) + { + FireBurst(vector_make(-base.y, base.x), perBurst, damageMultiplier); + FireBurst(vector_make(base.y, -base.x), perBurst, damageMultiplier); + } + for (int i = 0; i < params.numRandomDirTears; i++) + FireBurst(tear_vector_rotate(base, random_unit() * TEAR_FULL_TURN), perBurst, damageMultiplier); + sound_play(SOUND_MONSTRO_LUNG_BARF); + } + + charge = 0; + if (!IsItemAnimFinished(COLLECTIBLE_MONSTROS_LUNG)) return; + if (owner && owner->is_player()) owner->ToPlayer()->stop_costume_item_anims(); + else if (owner && owner->IsFamiliar()) static_cast(owner)->fireCooldown = 0; +} diff --git a/src/weapon_monstros_lung.h b/src/weapon_monstros_lung.h new file mode 100644 index 0000000..2c424cb --- /dev/null +++ b/src/weapon_monstros_lung.h @@ -0,0 +1,17 @@ +#pragma once + +#include "weapon.h" + +// Destruction (009f3260) is the base's. +// Monstro's Lung's weapon: the shots charge the head over the fire delay (Chocolate Milk's two and a half), and a +// release past the charge coughs a burst of tears (or Dr. Fetus' bombs) per lane of the volley, sized by the charge. +struct Weapon_MonstrosLung : Weapon +{ + void Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) override; + float GetMaxCharge() override; + int GetMarkedTargetVariant() override; + + void FireBurst(const Vector& velocity, int count, float damageMultiplier); +}; + +Weapon* weapon_monstros_lung_make(WeaponType type); diff --git a/src/weapon_rockets.cpp b/src/weapon_rockets.cpp index c11b396..d88c918 100644 --- a/src/weapon_rockets.cpp +++ b/src/weapon_rockets.cpp @@ -1,9 +1,11 @@ #include "weapon_rockets.h" +#include "boss_ai.h" #include "entity_bomb.h" #include "entity_effect.h" #include "entity_familiar.h" #include "entity_player.h" #include "entity_projectile.h" +#include "entity_tear.h" #include "game.h" #include "grid_entity.h" #include "log.h" @@ -22,6 +24,9 @@ constexpr float FAMILIAR_TARGET_SCALE = 0.8f; constexpr float RANDOM_TARGET_REACH = 80; constexpr float RANDOM_TARGET_MIN = 10; constexpr float HOMING_TARGET_REACH = 200; +// Strange Attractor pulls things toward the target and its added targets. +constexpr float ROCKET_ATTRACT_RADIUS = 250; +constexpr float ROCKET_ATTRACT_STRENGTH = 10; // The targets' frame: their drag (a Lil Gurdy's milder), the frames each rocket falls behind the last, the warning // before them, the blink, the spin of a random target, and the Marked line's drawn share of its length. @@ -189,7 +194,12 @@ void Weapon_Rockets::Fire(const Vector& shootDirection, bool isShooting, bool is { TearFlags flags = get_owner_tear_flags(); if (flags[TEAR_ATTRACTOR]) - reconstruction_missing("Weapon_Rockets::Fire 00a08d40 (Strange Attractor, Game::AttractEntities)"); + { + entities_attract({.position = aimed->pos, .radius = ROCKET_ATTRACT_RADIUS, .strength = ROCKET_ATTRACT_STRENGTH}); + for (Entity* other : entity_query(ENTITY_EFFECT, EFFECT_TARGET)) + if (other->parent.get() == aimed) + entities_attract({.position = other->pos, .radius = ROCKET_ATTRACT_RADIUS, .strength = ROCKET_ATTRACT_STRENGTH}); + } if (flags[TEAR_HOMING]) { Entity* nearest = nullptr; diff --git a/src/weapon_spirit_sword.cpp b/src/weapon_spirit_sword.cpp new file mode 100644 index 0000000..800af9c --- /dev/null +++ b/src/weapon_spirit_sword.cpp @@ -0,0 +1,224 @@ +#include "weapon_spirit_sword.h" +#include "boss_ai.h" +#include "entity_factory.h" +#include "entity_familiar.h" +#include "entity_knife.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "sfx_manager.h" +#include +#include + +constexpr float SWORD_LIFT = -10; +constexpr float SWORD_CHARGE_DELAYS = 4; +constexpr float SWORD_SWING_DELAY = 1; +constexpr float SWORD_VERSUS_DELAY = 30; +constexpr float SWORD_BEAM_DELAYS = 2; +constexpr float SWORD_BEAM_DELAY_MAX = 60; +constexpr float SWORD_PITCH_MIN = 0.5f; +constexpr float SWORD_SWING_PITCH = 1.1f; +constexpr float SWORD_SWING_PITCH_SPREAD = 0.2f; +constexpr int SWORD_SWING_SOUND = 252; +constexpr float SWORD_SHAKE_DAMAGE = 20; +constexpr float SWORD_SHAKE_SCALE = 1.5f; +constexpr float SWORD_SHAKE_PER_SCALE = 5; +constexpr float SWORD_RANDOM_TURN = 360; +constexpr int SWORD_SPIN_EFFECTS = 6; +constexpr float SWORD_RANGE_SHARE = 0.6f; +constexpr float SWORD_REACH = 300; +constexpr float SWORD_ORBIT_REACH = 100000; +constexpr int SWORD_RESIZE_FRAMES = 2; +constexpr int HELD_SWORD_BEAM_WAIT = 1; + +// 009f92d0 009f9020's maker for the Spirit Sword, or none for the other types. +Weapon* weapon_spirit_sword_make(WeaponType type) +{ + return type == WEAPON_SPIRIT_SWORD ? new Weapon_SpiritSword() : nullptr; +} + +// 009f6c50 Spawns a sword at the owner (a familiar's sword too) hanging from a parent, made like a fresh tear of the +// owning player (the tear side picked at random), turned by its offset. +Entity_Knife* Weapon::FireSword(const KnifeShot& shot) +{ + Entity_Player* player = owner_player(); + Entity_Knife* sword = static_cast(game_spawn({.position = owner ? owner->pos : Vector{}, + .spawner = owner, + .type = ENTITY_KNIFE, + .variant = shot.variant, + .seed = Random()}, + POOL_OVERWRITE)); + sword->parent = shot.parent; + sword->posOffset = vector_make(0, SWORD_LIFT); + if (player) + { + int displacement = (int)(Random() & 1) * 2 - 1; + TearParams params = player->GetTearHitParams(WEAPON_SPIRIT_SWORD, 1, displacement, owner); + sword->SetColor(params.tearColor, -1, TEAR_COLOR_PRIORITY, false, true); + sword->tearFlags = params.tearFlags; + sword->SetCollisionDamage(params.tearDamage); + } + sword->rotationOffset = angle_wrap(shot.rotationOffset); + if (shot.isCantOverwrite) sword->AddEntityFlags(FLAG_DONT_OVERWRITE); + return sword; +} + +// 00a0a6f0 Lets the next press swing. The base's reset does not run. +void Weapon_SpiritSword::Reset() { isSwung = false; } + +// The sword is removed and forgotten (Weapon_Laser::ClearReferences 00a063b0, which swords share). +void Weapon_SpiritSword::ClearReferences() +{ + for (EntityPtr* held : {&technology2Laser, &sword}) + { + if (!*held) continue; + (*held)->Remove(); + *held = nullptr; + } +} + +// 00a0a700 A spin takes four fire delays of charge. +float Weapon_SpiritSword::GetMaxCharge() { return maxFireDelay * SWORD_CHARGE_DELAYS; } + +// A swing: the fire delay restarts (longer in versus), the tear side flips, Anti-Gravity lets its held beams go, the +// old sword gives way to a new one (a beam ready at full health, at most every two fire delays), an extra sword fans +// out for each extra shot, all swing at the size of the owner, the swing sounds (lower for big swords) and a heavy big +// sword shakes the screen. +void Weapon_SpiritSword::swing(const Vector& aim) +{ + Entity_Player* player = owner_player(); + fireDelay = g_game->deathmatchManager.state >= DEATHMATCH_INTRO ? SWORD_VERSUS_DELAY : SWORD_SWING_DELAY; + charge = 0; + isSwung = true; + bool isFull = player && player->soulHearts + player->redHearts >= player->maxHearts; + if (owner && owner->is_player()) owner->ToPlayer()->tearDisplacement = (int8_t)-tear_displacement(); + if (player && player->HasCollectible(COLLECTIBLE_ANTI_GRAVITY)) + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity && entity->type == ENTITY_TEAR && entity->variant == TEAR_SWORD_BEAM && + entity->spawnerEntity == owner && static_cast(entity)->waitFrames > HELD_SWORD_BEAM_WAIT) + static_cast(entity)->waitFrames = HELD_SWORD_BEAM_WAIT; + + bool isBeam = isFull && beamCooldown <= 0; + if (isBeam) beamCooldown = std::min(maxFireDelay * SWORD_BEAM_DELAYS, SWORD_BEAM_DELAY_MAX); + if (sword) sword->Remove(); + + int variant = player && player->HasCollectible(COLLECTIBLE_TECHNOLOGY) ? KNIFE_TECH_SWORD : KNIFE_SPIRIT_SWORD; + float angle = vector_angle(aim); + std::vector swords; + auto fire = [&](Entity* parent, float offset, bool isCantOverwrite) { + Entity_Knife* fired = FireSword({.parent = parent, .rotationOffset = offset, .variant = variant, + .isCantOverwrite = isCantOverwrite}); + fired->rotation = angle; + fired->swingEffects = 1; + fired->swingTick = 0; + swords.push_back(fired); + return fired; + }; + sword = fire(owner, 0, true); + if (isBeam) sword->AddEntityFlags(FLAG_SWORD_BEAM); + + Weapon_MultiShotParams params = GetMultiShotParams(); + if (params.isShootingBackwards) fire(sword, 180, false); + if (params.isShootingSideways) + { + fire(sword, 90, false); + fire(sword, -90, false); + } + for (int i = 0; i < params.numRandomDirTears; i++) fire(sword, random_unit() * SWORD_RANDOM_TURN, false); + + float swordScale = held_scale(); + float size = swordScale; + if (g_game->frameCount - sword->spawnFrame > SWORD_RESIZE_FRAMES) + size = (swordScale - sword->sprite.scale.x) * 0.5f + sword->sprite.scale.x; + for (Entity_Knife* fired : swords) + if (fired->subtype == KNIFE_SUBTYPE_HELD && (fired->parent == sword || fired == sword)) + fired->sprite.scale = vector_make(size, size); + + float heaviest = 0; + for (Entity_Knife* fired : swords) + { + fired->SetAttackAnimation(); + fired->Update(); + heaviest = std::max(fired->collisionDamage, heaviest); + } + + float pitch = std::max(1 / (swordScale * 0.5f + 0.5f), SWORD_PITCH_MIN); + int sound = SWORD_SWING_SOUND; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.frameDelay = 1, .pitch = (random_unit() * SWORD_SWING_PITCH_SPREAD + SWORD_SWING_PITCH) * pitch}); + if (heaviest > SWORD_SHAKE_DAMAGE && swordScale > SWORD_SHAKE_SCALE) + game_shake_screen((int)(swordScale * SWORD_SHAKE_PER_SCALE)); + TriggerTearEffects(aim, 1); +} + +// Holding on after a swing charges the sword, which shows once full. A release once full spins it (one spin per shot +// of the volley), and Mom's Knife throws it as far as the range allows. +void Weapon_SpiritSword::charge_update(const Vector& aim, bool isShooting) +{ + Entity_Knife& held = *static_cast(sword.get()); + float full = maxFireDelay * SWORD_CHARGE_DELAYS; + if (isShooting || charge < full) + { + held.isAttacking = isShooting; + if (!held.isAttacking) charge = 0; + else + { + if (!held.isSwinging) charge = std::min(charge + (owner ? owner->speedMultiplier : 1), full); + held.isSwingCharged = full <= charge; + } + return; + } + + held.SpinAttack(GetMultiShotParams().numTears, 0); + Entity_Player* player = owner_player(); + if (player && player->HasCollectible(COLLECTIBLE_MOMS_KNIFE)) + { + float range = player->tearRange * SWORD_RANGE_SHARE; + held.Shoot(1, std::min(range, held.tearFlags[TEAR_ORBIT] ? SWORD_ORBIT_REACH : SWORD_REACH)); + } + charge = 0; + TriggerTearEffects(aim, SWORD_SPIN_EFFECTS); +} + +// 00a099e0 Swings, charges and spins the sword toward the aim (the last aim, else the head's way), snapped to the four +// directions unless free, turned with the eye under R U A Wizard. A press swings once the fire delay passed and the +// sword is idle. The head turns with the sword (with its hit point while spinning). An idle sword goes away. +void Weapon_SpiritSword::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Weapon::Fire(shootDirection, isShooting, isInterpolated); + Entity_Player* holder = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + if (!isInterpolated && beamCooldown > 0) beamCooldown -= owner ? owner->speedMultiplier : 1; + if (!isShooting) isSwung = false; + + Vector aim = vector_is_zero(shootDirection) ? direction : shootDirection; + if (vector_is_zero(aim) && holder) aim = vector_from_direction(holder->headDirection); + if (IsAxisAligned()) aim = vector_cardinal(aim); + if (holder && is_shot_rotated()) aim = tear_vector_rotate(aim, (float)tear_displacement() * SHOT_ROTATION_DEGREES); + if (isInterpolated) return; + + bool isIdle = !sword || !static_cast(sword.get())->isAttacking; + if (isShooting && fireDelay <= 0 && isIdle) + { + if (sword) sword->Remove(); + if (!isSwung) swing(aim); + } + if (!sword) + { + charge = 0; + return; + } + charge_update(aim, isShooting); + + Entity_Knife& held = *static_cast(sword.get()); + Vector facing = held.sprite.GetAnimation().starts_with("Spin") ? held.GetNullOffset("Hit") + : vector_from_angle(held.rotation); + Direction head = facing.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP; + if (std::fabs(facing.y) < std::fabs(facing.x)) head = facing.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + set_head_direction(head); + SetHeadLockTime(1); + if (!held.isFlying && !held.isSwinging && !held.isAttacking) held.Remove(); +} diff --git a/src/weapon_spirit_sword.h b/src/weapon_spirit_sword.h new file mode 100644 index 0000000..150a605 --- /dev/null +++ b/src/weapon_spirit_sword.h @@ -0,0 +1,26 @@ +#pragma once + +#include "weapon.h" + +// Destruction (009f9930) is the default. +// The Spirit Sword's weapon (Technology's tech sword): a press swings a sword (one more per extra shot of the volley) +// that throws a beam at full health, holding on charges it, and a release once charged spins it (Mom's Knife throws +// it too). +struct Weapon_SpiritSword : Weapon +{ + EntityPtr sword; + float beamCooldown = 0; + bool isSwung = false; + + void Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) override; + void Reset() override; + void ClearReferences() override; + float GetMaxCharge() override; + // 009f3150 The sword is what the weapon fires as. + Entity* GetMainEntity() override { return sword; } + + void swing(const Vector& aim); + void charge_update(const Vector& aim, bool isShooting); +}; + +Weapon* weapon_spirit_sword_make(WeaponType type); diff --git a/src/weapon_umbilical_whip.cpp b/src/weapon_umbilical_whip.cpp new file mode 100644 index 0000000..04e1a22 --- /dev/null +++ b/src/weapon_umbilical_whip.cpp @@ -0,0 +1,79 @@ +#include "weapon_umbilical_whip.h" +#include "boss_ai.h" +#include "entity_factory.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "game.h" +#include "manager.h" +#include "npc_ai.h" +#include "sfx_manager.h" + +constexpr float WHIP_DELAYS = 2; +constexpr int WHIP_BLINK_BASE = 7; +constexpr float WHIP_BLINK_SHARE = -0.45f; +constexpr float WHIP_SPEED = 10; +constexpr float WHIP_INHERIT_SHARE = 0.4f; +constexpr int WHIP_SOUND = 494; +constexpr int WHIP_SOUND_DELAY = 2; +// The whip familiar's state once it is pulled back. +constexpr int WHIP_STATE_RETURN = 1; + +// 009f9170 009f9020's maker for the umbilical whip, or none for the other types. +Weapon* weapon_umbilical_whip_make(WeaponType type) +{ + return type == WEAPON_UMBILICAL_WHIP ? new Weapon_UmbilicalWhip() : nullptr; +} + +// The whip is removed and forgotten (Weapon_Laser::ClearReferences 00a063b0, which the whip shares). +void Weapon_UmbilicalWhip::ClearReferences() +{ + for (EntityPtr* held : {&technology2Laser, &whip}) + { + if (!*held) continue; + (*held)->Remove(); + *held = nullptr; + } +} + +// A crack: two fire delays of rest, the eyes shut, and a whip spawned by the player at the owner, sent along the aim +// (snapped to the four directions unless free) bent a little by the owner's movement. +void Weapon_UmbilicalWhip::crack(const Vector& shootDirection) +{ + fireDelay = maxFireDelay * WHIP_DELAYS; + SetBlinkTime(WHIP_BLINK_BASE - (int)(maxFireDelay * WHIP_BLINK_SHARE)); + Vector aim = IsAxisAligned() ? vector_cardinal(shootDirection) : vector_normalized(shootDirection); + aim = vector_normalized(vector_add(vector_scale(aim, WHIP_SPEED), + vector_scale(get_tear_movement_inheritance(aim), WHIP_INHERIT_SHARE))); + + whip = game_spawn({.position = get_owner_position(), + .spawner = owner_player(), + .type = ENTITY_FAMILIAR, + .variant = Entity_Familiar::UMBILICAL_BABY, + .seed = Random()}, + POOL_OVERWRITE); + whip->ClearEntityFlags(FLAG_APPEAR); + whip->targetPosition = vector_normalized(aim); + whip->Update(); + int sound = WHIP_SOUND; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.frameDelay = WHIP_SOUND_DELAY}); + TriggerTearEffects(aim, 1); +} + +// 00a0e270 Cracks the whip on a press once the fire delay passed (a whip on its way back goes first), pulls it back on +// release, and turns the body toward it. The whip's look (none, hidden or out) is kept for Tainted Lilith's costume. +void Weapon_UmbilicalWhip::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Weapon::Fire(shootDirection, isShooting, isInterpolated); + whipLook = whip ? (whip->isVisible ? 2 : 1) : 0; + if (isShooting && fireDelay < 0) + { + if (isInterpolated) return; + + if (whip && static_cast(whip.get())->state == WHIP_STATE_RETURN) whip->Remove(); + if (!whip) crack(shootDirection); + } + + bodyDirection = whip ? vector_normalized(vector_sub(whip->pos, get_owner_position())) : Vector{}; + if (!isShooting && whip) static_cast(whip.get())->state = WHIP_STATE_RETURN; +} diff --git a/src/weapon_umbilical_whip.h b/src/weapon_umbilical_whip.h new file mode 100644 index 0000000..53fdd4c --- /dev/null +++ b/src/weapon_umbilical_whip.h @@ -0,0 +1,21 @@ +#pragma once + +#include "weapon.h" + +// Destruction (009f9880) is the default. +// Tainted Lilith's weapon: a press cracks her umbilical whip (a Gello familiar) toward the aim, and letting go pulls it +// back. The body turns toward the whip, and whipLook (0 none, 1 hidden, 2 out) poses her Gello costume. +struct Weapon_UmbilicalWhip : Weapon +{ + EntityPtr whip; + int whipLook = 0; + + void Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) override; + void ClearReferences() override; + // 009f3150 The whip is what the weapon fires as. + Entity* GetMainEntity() override { return whip; } + + void crack(const Vector& shootDirection); +}; + +Weapon* weapon_umbilical_whip_make(WeaponType type); diff --git a/src/weapon_urn_of_souls.cpp b/src/weapon_urn_of_souls.cpp new file mode 100644 index 0000000..fb0a7f7 --- /dev/null +++ b/src/weapon_urn_of_souls.cpp @@ -0,0 +1,289 @@ +#include "weapon_urn_of_souls.h" +#include "anm2.h" +#include "entity_effect.h" +#include "entity_factory.h" +#include "entity_familiar.h" +#include "entity_laser.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "game.h" +#include "level.h" +#include "manager.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "sfx_manager.h" +#include +#include + +constexpr float URN_SOUND_VOLUME = 1.6f; +constexpr float URN_LIFT = -15; +constexpr float URN_TILT = 90; +constexpr float URN_LASER_FOLLOW = 0.15f; +constexpr float URN_LASER_AIM = 0.3f; +constexpr float URN_SOUL_FLAMES = 15; +constexpr float URN_CHARGE_FLAMES = 25; +constexpr float URN_RAMP_FRAMES = 90; +constexpr float FLAME_SPEED = 6; +constexpr float FLAME_SPREAD = 16; +constexpr float FLAME_RECOIL = -0.4f; +constexpr float FLAME_START = 2; +constexpr float TWIN_RECOIL_REACH_SQUARED = 6400; +constexpr float FLAME_RANGE = 160; +constexpr int FLAME_SHIELDED_CHANCE = 8; +constexpr float FLAME_DAMAGE_BASE = 2.3f; +constexpr float FLAME_LASER_DAMAGE_BASE = 2.8f; +constexpr float FLAME_LASER_DAMAGE_SCALE = 1.5f; +constexpr float FLAME_DAMAGE_PER_STAGE = 0.3f; +constexpr float FLAME_RAMP_DAMAGE_MIN = 0.8f; +constexpr float FLAME_RAMP_DAMAGE = 0.2f; +constexpr float FLAME_SCALE_MIN = 0.7f; +constexpr float FLAME_RAMP_SCALE = 0.4f; +constexpr float FLAME_FALL_ACCEL = 0.1f; +constexpr int FLAME_LASER_TIMEOUT = 8; +constexpr float FLAME_LASER_ABOVE = -0.5f; +constexpr float FLAME_LASER_DEPTH_BEHIND = -10; +constexpr float FLAME_LASER_DEPTH_FRONT = 3000; +constexpr int URN_SHAKE = 3; +constexpr int URN_BLINK = 4; + +// The urn's states: still rising into the hands below zero, closed, opening, breathing, breathing on, closing. +enum UrnState : int +{ + URN_CLOSED = 0, + URN_OPENING = 1, + URN_OPEN = 2, + URN_REOPENED = 3, + URN_CLOSING = 4, + URN_RISING = -4 +}; + +static bool is_breathing(int state) { return state == URN_OPEN || state == URN_REOPENED; } + +// 009f90f0 009f9020's maker for the Urn of Souls, or none for the other types. +Weapon* weapon_urn_of_souls_make(WeaponType type) +{ + return type == WEAPON_URN_OF_SOULS ? new Weapon_UrnOfSouls() : nullptr; +} + +// 00a0f410 Empties the flames and the ramp. The base's reset does not run. +void Weapon_UrnOfSouls::Reset() +{ + flamesLeft = 0; + intensity = 0; +} + +// 00a0f420 Removes Technology 2's laser and the urn, and stops its sounds. The flame beam stays. +void Weapon_UrnOfSouls::ClearReferences() +{ + for (EntityPtr* held : {&technology2Laser, &urn}) + { + if (!*held) continue; + (*held)->Remove(); + *held = nullptr; + } + g_manager->sfxManager.Stop(SOUND_FLAMETHROWER_START); + g_manager->sfxManager.Stop(SOUND_FLAMETHROWER_LOOP); +} + +// The stage the flames grow with: one more on the alternate path, as 004360f0 counts it. +static int flame_stage() +{ + bool isAltPath = g_game->stageType == STAGETYPE_REPENTANCE || g_game->stageType == STAGETYPE_REPENTANCE_B; + return g_game->stage + (isAltPath ? 1 : 0); +} + +// Where the urn points: the shot, the last aim, else the player's head (a familiar's shot direction). Without an owner +// the original reads nothing safe: it keeps the zero aim. +Vector Weapon_UrnOfSouls::aim_get(const Vector& shootDirection) +{ + Vector aim = vector_is_zero(shootDirection) ? direction : shootDirection; + if (!vector_is_zero(aim)) return vector_normalized(aim); + + if (owner && owner->is_player()) return vector_from_direction(owner->ToPlayer()->headDirection); + if (owner && owner->IsFamiliar()) return vector_from_direction(static_cast(owner)->shootDirection); + return aim; +} + +// A new urn at the owner, rising into its hands, turned upright toward the aim. Its subtype is whether the Book of +// Belial's birthright makes it breathe a beam. +void Weapon_UrnOfSouls::urn_spawn(const Vector& aim, bool isBelial) +{ + uint32_t seed = Random(); + urn = game_spawn({.position = get_owner_position(), + .spawner = owner, + .subType = isBelial, + .type = ENTITY_EFFECT, + .variant = EFFECT_URN_OF_SOULS, + .seed = seed}, + POOL_OVERWRITE); + urn->parent = owner; + static_cast(urn.get())->state = URN_RISING; + urn->posOffset = vector_make(0, URN_LIFT); + float angle = vector_angle(aim); + urn->sprite.rotation = angle > 0 ? angle + URN_TILT : angle - URN_TILT; + urn->Update(); +} + +// A press with souls (or soul charges) and no flames left opens the urn, or keeps it breathing. Each time it breathes +// a soul gives 15 flames, else a soul charge 25, and the Book of Virtues adds a wisp. Out of flames it closes. +void Weapon_UrnOfSouls::urn_open(bool isShooting) +{ + Entity_Effect& held = *static_cast(urn.get()); + Entity_Player* holder = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + if (isShooting && flamesLeft <= 0 && holder && (holder->urnSouls > 0 || holder->effectiveSoulCharge > 0)) + { + if (held.state == URN_REOPENED || held.state == URN_CLOSING) held.state = URN_REOPENED; + else if (held.state == URN_CLOSED) + { + held.state = URN_OPENING; + int sound = SOUND_FLAMETHROWER_START; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = URN_SOUND_VOLUME, .frameDelay = 1}); + } + + if (is_breathing(held.state)) + { + if (holder->urnSouls >= 1) + { + holder->AddUrnSouls((uint32_t)-1); + flamesLeft = URN_SOUL_FLAMES; + } + else if (holder->effectiveSoulCharge > 0) + { + holder->AddSoulCharge(-1); + flamesLeft = URN_CHARGE_FLAMES; + } + if (flamesLeft > 0 && holder->HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) + holder->AddWisp(COLLECTIBLE_URN_OF_SOULS, get_owner_position(), false, false); + } + } + + if (flamesLeft > 0 || !is_breathing(held.state)) return; + + int sound = SOUND_FLAMETHROWER_END; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = URN_SOUND_VOLUME, .frameDelay = 1}); + intensity = 0; + direction = {}; + g_manager->sfxManager.Stop(SOUND_FLAMETHROWER_START); + held.state = URN_CLOSING; +} + +// One flame from the urn's mouth, spread a little and pushing the owner (and a close twin) back: a piercing fire tear +// that sometimes blocks shots, bigger and stronger as the stream grows, or the beam held toward the urn's aim. +void Weapon_UrnOfSouls::flame_fire(const Vector& aim) +{ + Entity_Player* holder = owner && owner->is_player() ? owner->ToPlayer() : nullptr; + float speed = owner ? owner->speedMultiplier : 1; + intensity = std::min(speed / URN_RAMP_FRAMES + intensity, 1.0f); + Vector mouth = vector_from_angle(urn->sprite.rotation); + Vector velocity = vector_scale(mouth, intensity * FLAME_SPEED + FLAME_SPEED); + velocity = tear_vector_rotate(velocity, random_unit() * FLAME_SPREAD - FLAME_SPREAD / 2); + Vector position = vector_add(get_owner_position(), vector_scale(mouth, FLAME_START)); + + Vector recoil = vector_scale(mouth, FLAME_RECOIL * speed); + owner->velocity = vector_add(owner->velocity, vector_scale(recoil, owner->speedMultiplier)); + if (Entity_Player* twin = holder ? holder->twin_get() : nullptr; + twin && vector_length_squared(vector_sub(owner->pos, twin->pos)) < TWIN_RECOIL_REACH_SQUARED) + twin->velocity = vector_add(twin->velocity, vector_scale(recoil, twin->speedMultiplier)); + velocity = vector_add(velocity, get_tear_movement_inheritance(velocity)); + + float growth = intensity * FLAME_RAMP_DAMAGE + FLAME_RAMP_DAMAGE_MIN; + TearFlags shielded; + shielded.set(TEAR_SHIELDED); + if (urn->subtype == 1) + { + float damage = ((float)flame_stage() * FLAME_DAMAGE_PER_STAGE + FLAME_LASER_DAMAGE_BASE) * + FLAME_LASER_DAMAGE_SCALE * growth; + if (!flameLaser) + { + flameLaser = Entity_Laser::ShootAngle({.position = urn->pos, + .posOffset = vector_make(0, URN_LIFT), + .source = urn, + .angleDegrees = vector_angle(mouth), + .timeout = FLAME_LASER_TIMEOUT, + .variant = LASER_THICK_RED}); + flameLaser->spawnerType = ENTITY_PLAYER; + flameLaser->spawnerVariant = 0; + flameLaser->SetCollisionDamage(damage); + static_cast(flameLaser.get())->tearFlags = shielded; + flameLaser->Update(); + } + if (flameLaser) + { + Entity_Laser& laser = *static_cast(flameLaser.get()); + laser.SetCollisionDamage(damage); + laser.tearFlags = shielded; + laser.timeout = FLAME_LASER_TIMEOUT; + laser.set_aim_angle(angle_lerp(laser.angleDegrees, urn->sprite.rotation, URN_LASER_AIM)); + bool isAbove = std::sin(laser.angleDegrees * DEGREES_TO_RADIANS) <= FLAME_LASER_ABOVE; + laser.renderDepthOffset = isAbove ? FLAME_LASER_DEPTH_BEHIND : FLAME_LASER_DEPTH_FRONT; + } + } + else + { + Entity_Tear& flame = *static_cast(game_spawn({.position = position, + .velocity = velocity, + .spawner = holder, + .type = ENTITY_TEAR, + .variant = TEAR_FIRE, + .seed = Random()}, + POOL_OVERWRITE)); + flame.parent = holder; + TearFlags piercing; + piercing.set(TEAR_PIERCING); + flame.SetTearFlags(piercing); + flame.tearRange = FLAME_RANGE; + if (flame.dropRNG.RandomInt(FLAME_SHIELDED_CHANCE) == 0) flame.SetTearFlags(flame.tearFlags | shielded); + flame.mass = 0; + float damage = ((float)flame_stage() * FLAME_DAMAGE_PER_STAGE + FLAME_DAMAGE_BASE) * growth; + float scale = std::max(intensity * FLAME_RAMP_SCALE + FLAME_SCALE_MIN, TEAR_SCALE_MIN); + flame.baseScale = scale; + flame.fScale = scale; + flame.ResetSpriteScale(); + flame.SetCollisionDamage(damage); + flame.fallingAccel = FLAME_FALL_ACCEL; + flame.Update(); + } + + game_shake_screen(URN_SHAKE); + TriggerTearEffects(aim, 1); + flamesLeft -= 1; + direction = aim; +} + +// 00a0e630 Holds the urn toward the aim (a new one when the birthright changes), the beam following its mouth, opens +// and closes it, and breathes a flame each update while open. The eyes stay shut while it breathes. +void Weapon_UrnOfSouls::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) +{ + Weapon::Fire(shootDirection, isShooting, isInterpolated); + Vector aim = aim_get(shootDirection); + bool isBelial = owner && owner->is_player() && owner->ToPlayer()->HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE); + if (urn && urn->subtype != (int)isBelial) urn->Remove(); + if (!urn && !isInterpolated) urn_spawn(aim, isBelial); + if (!urn) return; + + Entity_Effect& held = *static_cast(urn.get()); + held.rotation = vector_angle(aim); + if (flameLaser) + { + Entity_Laser& laser = *static_cast(flameLaser.get()); + laser.pos = urn->pos; + float last = laser.angleDegrees; + float angle = angle_lerp(last, urn->sprite.rotation, URN_LASER_FOLLOW); + laser.startAngleDegrees = angle; + laser.angleDegrees = angle; + laser.lastAngleDegrees = last; + laser.sprite.rotation = angle - URN_TILT; + } + if (isInterpolated) return; + + if (held.state >= 0) + { + urn_open(isShooting); + if (flamesLeft > 0 && is_breathing(held.state)) flame_fire(aim); + } + held.scale = intensity; + if (is_breathing(held.state) || flameLaser) SetBlinkTime(URN_BLINK); +} diff --git a/src/weapon_urn_of_souls.h b/src/weapon_urn_of_souls.h new file mode 100644 index 0000000..1492b35 --- /dev/null +++ b/src/weapon_urn_of_souls.h @@ -0,0 +1,28 @@ +#pragma once + +#include "weapon.h" + +// Destruction (009f97e0) is the default. +// The Urn of Souls' weapon: an urn held toward the aim that, opened while there are souls, breathes a stream of flames +// (a short beam with the Book of Belial's birthright) that grows over three seconds, one soul per 15 flames (or a soul +// charge per 25), and the urn closes once they run out. +struct Weapon_UrnOfSouls : Weapon +{ + EntityPtr flameLaser; + EntityPtr urn; + float flamesLeft = 0; + float intensity = 0; + + void Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) override; + void Reset() override; + void ClearReferences() override; + // 009f3170 The urn is what the weapon fires as. + Entity* GetMainEntity() override { return urn; } + + Vector aim_get(const Vector& shootDirection); + void urn_spawn(const Vector& aim, bool isBelial); + void urn_open(bool isShooting); + void flame_fire(const Vector& aim); +}; + +Weapon* weapon_urn_of_souls_make(WeaponType type);