diff --git a/generated-src/classes.h b/generated-src/classes.h index 7a49eaf..baee98e 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -162,6 +162,7 @@ struct CameraBounds; struct Capsule; struct Card; struct CellSpace; +struct ChainLightning; struct ChallengeParam; struct ChallengeParams; struct ChampionLook; @@ -220,6 +221,7 @@ struct Devolve; struct DreamCatcherPage; struct EffectBehaviour; struct EmoteWheel; +struct EntitiesLive; struct Entity; struct EntityConfig; struct EntityConfig_Baby; @@ -656,6 +658,7 @@ struct VectorRing; struct VentricleRazorPortal; struct VideoPlayer; struct VoidedPassive; +struct WalkAnims; struct WallDetail; struct WallSlot; struct WaterClipInfo; @@ -5799,7 +5802,6 @@ void FUN_004b7070(uint32_t param_1); // 004b7070 uint32_t FUN_004b7090(); // 004b7090 Entity * FUN_004bb230(); // 004bb230 uint32_t FUN_004bc660(); // 004bc660 -Entity * FUN_004bcb30(uint32_t param_1, uint32_t param_2); // 004bcb30 void FUN_004bfd20(); // 004bfd20 void FUN_004c5850(uint8_t *param_1); // 004c5850 void FUN_004c5980(float *param_1, Vector *param_2); // 004c5980 @@ -5845,7 +5847,6 @@ bool FUN_00557bb0(int *param_1); // 00557bb0 void FUN_00565dd0(uint32_t param_1); // 00565dd0 void FUN_00565de0(uint32_t param_1); // 00565de0 void FUN_00568980(char param_1); // 00568980 -void FUN_0056c7c0(); // 0056c7c0 void FUN_0056ff00(uint32_t *param_1, uint32_t param_2, uint32_t param_3); // 0056ff00 bool FUN_0056ff60(uint32_t param_1); // 0056ff60 void FUN_00571170(); // 00571170 @@ -5858,10 +5859,6 @@ void FUN_00579700(); // 00579700 uint32_t FUN_00579760(); // 00579760 void FUN_0057be30(uint32_t param_1); // 0057be30 void FUN_0057be60(uint32_t param_1, uint32_t param_2); // 0057be60 -void FUN_0057be90(int param_1); // 0057be90 -void FUN_0057e3b0(float *param_1); // 0057e3b0 -void rotgut_death_spawn_effects(Entity_NPC *npc); // 00581200 -void FUN_005828b0(); // 005828b0 int FUN_00582a60(); // 00582a60 int FUN_00582a80(); // 00582a80 void FUN_00582aa0(); // 00582aa0 @@ -6356,7 +6353,6 @@ void FUN_007008b0(int *param_1); // 007008b0 void FUN_00703140(); // 00703140 void FUN_00704b50(); // 00704b50 void FUN_007068f0(int param_1); // 007068f0 -Entity * spawn_chain_lightning(Vector *position, BitSet128 tearFlags, Entity *spawner, float damage); // 00707e10 uint32_t FUN_00708350(); // 00708350 void FUN_00708380(); // 00708380 void FUN_00708430(uint32_t param_1, uint32_t param_2, int param_3); // 00708430 @@ -6544,7 +6540,6 @@ 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_007c2e80(); // 007c2e80 -uint8_t FUN_007c7b10(uint32_t param_1, int param_2); // 007c7b10 void FUN_007cb4f0(); // 007cb4f0 void FUN_007cf940(); // 007cf940 long double FUN_007cf9a0(float *param_1, KColor *param_2, uint32_t param_3); // 007cf9a0 @@ -7442,7 +7437,6 @@ uint32_t FUN_00893c70(uint32_t param_1); // 00893c70 void FUN_00893c90(uint32_t param_1, uint32_t param_2); // 00893c90 uint32_t * FUN_00893cf0(uint32_t param_1, uint32_t param_2); // 00893cf0 void FUN_00893d90(); // 00893d90 -void FUN_00893df0(); // 00893df0 void FUN_00893e50(); // 00893e50 void FUN_00893eb0(); // 00893eb0 void FUN_00893f10(); // 00893f10 @@ -8170,7 +8164,6 @@ void FUN_008ba6d0(uint32_t param_1); // 008ba6d0 void FUN_008ba7c0(uint32_t param_1); // 008ba7c0 void FUN_008ba890(uint32_t param_1); // 008ba890 int FUN_008ba900(); // 008ba900 -int FUN_008ba960(); // 008ba960 void FUN_008ba9c0(void *param_1); // 008ba9c0 int FUN_008baa50(); // 008baa50 void FUN_008baab0(void *param_1); // 008baab0 @@ -20746,17 +20739,11 @@ namespace AudioPacketQueue { void destroyAllAudioPackets(); // 00aadc80 } namespace FamiliarAI { -void gb_bug(Entity_Familiar *familiar); // 00618b00 -void variant_53(Entity_Familiar *familiar); // 006196e0 void variant_66(Entity_Familiar *familiar); // 0061c3f0 void lil_haunt(Entity_Familiar *familiar, int unused); // 0061d030 -void bumbo(Entity_Familiar *familiar); // 0062f7f0 void lil_spewer(Entity_Familiar *familiar); // 006384a0 Entity_Knife * sprinkler_spawn_knife(Entity_Familiar *familiar); // 0063b070 -void variant_204(Entity_Familiar *familiar); // 00644780 -int worm_friend(Entity_Familiar *familiar); // 0064bfa0 void star_of_bethlehem(Entity_Familiar *familiar); // 0064d5f0 -void vanishing_twin(Entity_Familiar *familiar); // 00650610 } namespace FamiliarHelper { Entity_Laser * sprinkler_fire_laser(Entity_Familiar *familiar, float angle, float distance); // 0063acf0 @@ -20815,63 +20802,28 @@ void ENTITY_CHIMERA_head_update(Entity_NPC *npc); // 0049cd90 void ENTITY_CHIMERA_body(Entity_NPC *npc); // 0049d130 uint32_t ENTITY_CHIMERA(Entity_NPC *npc); // 0049fa10 void ENTITY_CLOG(Entity_NPC *npc); // 004a12f0 -void ENTITY_COLOSTOMIA(Entity_NPC *npc); // 004a3040 void ENTITY_DOGMA_update_distortion(Entity_NPC *npc); // 004aaef0 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_HORNFEL_DOOR(Entity_NPC *npc); // 004bb9b0 -void ENTITY_HORNY_BOYS(Entity_NPC *npc); // 004bd2a0 void ENTITY_MATRIARCH(Entity_NPC *npc); // 004c59d0 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 -void ENTITY_ROTTEN_GAPER(Entity_NPC *npc); // 004da590 -Entity_Effect * ENTITY_TWITCHY(Entity_NPC *npc); // 004db6a0 -void ENTITY_SPIKEBALL(Entity_NPC *npc); // 004dc490 void ENTITY_UNBORN(Entity_NPC *npc); // 004dca90 -void * ENTITY_GASBAG(Entity_NPC *npc); // 004dd7f0 -void ENTITY_EVIS(Entity_NPC *npc); // 004df3f0 -void ENTITY_GUTTED_FATTY(Entity_NPC *npc); // 004e0dd0 -uint32_t ENTITY_GAPER_L2(Entity_NPC *npc); // 004e2b40 void ENTITY_CHARGER_L2(Entity_NPC *npc); // 004e38c0 -void ENTITY_CANDLER(Entity_NPC *npc); // 004e4970 -uint32_t ENTITY_BISHOP(Entity_NPC *npc); // 004e7ea0 void ENTITY_BALL_AND_CHAIN(Entity_NPC *npc); // 004f4730 -void ENTITY_GYRO(Entity_NPC *npc); // 004ff620 -void ENTITY_BOUNCER(Entity_NPC *npc); // 00501f30 -void ENTITY_STONE_EYE(Entity_NPC *npc); // 00505d00 -void ENTITY_DOPLE(Entity_NPC *npc); // 00525650 -void ENTITY_BLACK_MAW(Entity_NPC *npc); // 0053b2f0 -float ENTITY_TARBOY(Entity_NPC *npc); // 005442a0 -void ENTITY_FISTULOID(Entity_NPC *npc); // 00545f70 -void ENTITY_MR_MINE(Entity_NPC *npc); // 005492c0 void ENTITY_BUTT_SLICKER(Entity_NPC *npc); // 0054d250 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 int ENTITY_WILLO_L2_find_target(Entity_NPC *npc); // 005591c0 void ENTITY_WILLO_L2(Entity_NPC *npc); // 005593c0 uint32_t ENTITY_POLTY(Entity_NPC *npc); // 0055d230 -void ENTITY_BLOATY(Entity_NPC *npc); // 00563da0 void ENTITY_FISSURE(Entity_NPC *npc); // 00564f30 -void ENTITY_MOTHER_worm(Entity_NPC *npc); // 00565e00 -void ENTITY_MOTHER_ball(Entity_NPC *npc); // 00566810 -void ENTITY_MOTHER_ball_burst(Entity_NPC *npc); // 00567d50 -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_CLUTCH(Entity_NPC *npc); // 00573030 void ENTITY_RAGLICH(Entity_NPC *npc); // 005769b0 void ENTITY_RAINMAKER(Entity_NPC *npc); // 00578a70 -void ENTITY_ROTGUT_face(Entity_NPC *npc); // 0057bec0 -void ENTITY_ROTGUT_maggot(Entity_NPC *npc); // 0057e4a0 -void rotgut_fire_projectiles(Entity_NPC *npc); // 00581430 -void ENTITY_ROTGUT(Entity_NPC *npc); // 00581730 void ENTITY_SCOURGE_chain(Entity_NPC *npc); // 00584140 void ENTITY_SCOURGE_main(Entity_NPC *npc); // 005864b0 void ENTITY_SCOURGE_projectile_attack(Entity_NPC *npc); // 00586c40 @@ -20887,11 +20839,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_TURDLET_segments(Entity_NPC *npc); // 0059c5d0 -void ENTITY_TURDLET(Entity_NPC *npc); // 0059c830 -void ENTITY_ULTRA_GREED(Entity_NPC *npc); // 0059edb0 -void ENTITY_ULTRA_COIN(Entity_NPC *npc); // 005a4820 -void ENTITY_ULTRA_DOOR(Entity_NPC *npc); // 005a5b60 void ENTITY_VISAGE(Entity_NPC *npc); // 005a7b20 void ENTITY_VISAGE_mask(Entity_NPC *npc); // 005ab4d0 void ENTITY_VISAGE_chain(Entity_NPC *npc); // 005ad250 diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index e31210a..d4e6b4f 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -177,298 +177,6 @@ LAB_0049f8ee: return; } -// 004a2940 -Vector * NpcHelper::colostomia_pick_target(Entity_NPC *npc, Vector *outTarget, uint8_t *isPlayerPos) -{ - uint64_t qVar1; - Entity *playerTarget; - uint64_t *allocCounter; - int gridWidth; - uint32_t uVar3; - uint32_t uVar4; - int iVar5; - float score; - float dy; - float cellX; - float cellY; - float fVar6; - float fVar7; - float bestY; - EntityList_EL effects; - Entity_NPC *local_720; - uint8_t *local_71c; - Vector *local_718; - int cellCounts [448]; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - int local_8; - Game *game; - int gridWidth; - void *room; - - local_8 = 0xffffffff; - puStack_c = &LAB_00af2fd0; - local_10 = ExceptionList; - local_14 = __security_cookie ^ GHIDRA_UINT((cellCounts + 0x1c4)); - ExceptionList = &local_10; - local_71c = isPlayerPos; - local_718 = outTarget; - local_720 = npc; - memset(cellCounts,0,0x700); - EntityList::QuerySublist(GHIDRA_CAST((GHIDRA_INT(g_game->_room) + 0x1218)),&effects,1000,0x8d,1,0,0); - local_8 = 0; - uVar4 = 0; - if (effects._size != 0) { - room = g_game->_room; - do { - uVar3 = 0; - iVar5 = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(effects)) + 0x4))) + uVar4 * 4)); - fVar6 = *GHIDRA_CAST((iVar5 + 0x33c)); - fVar7 = *GHIDRA_CAST((iVar5 + 0x340)); - do { - iVar5 = GHIDRA_INT((((fVar6 + *GHIDRA_CAST((GHIDRA_INT(&DAT_00c5c5e8) + uVar3))) - 40.0) / 40.0 + 0.5)); - gridWidth = GHIDRA_INT((((fVar7 + *GHIDRA_CAST((GHIDRA_INT(&DAT_00c5c5ec) + uVar3))) - 120.0) / 40.0 + 0.5)); - if ((((-1 < iVar5) && (gridWidth = *GHIDRA_CAST((GHIDRA_CAST(room) + 0xc)), iVar5 < gridWidth)) && - (-1 < gridWidth)) && - ((gridWidth < *GHIDRA_CAST((GHIDRA_CAST(room) + 0x10)) && (iVar5 = gridWidth * gridWidth + iVar5, -1 < iVar5))) - ) { - cellCounts[iVar5] = cellCounts[iVar5] + 1; - } - uVar3 = uVar3 + 8; - } while (uVar3 < 0x48); - uVar4 = uVar4 + 1; - } while (uVar4 < GHIDRA_UINT(effects._size)); - outTarget = local_718; - } - playerTarget = Entity_NPC::GetPlayerTarget(local_720); - game = g_game; - local_718 = GHIDRA_CAST((playerTarget->_pos).x); - local_720 = GHIDRA_CAST((playerTarget->_pos).y); - iVar5 = GHIDRA_INT((((float)local_718 - 40.0) / 40.0 + 0.5)); - gridWidth = GHIDRA_INT((((float)local_720 - 120.0) / 40.0 + 0.5)); - if (((iVar5 < 0) || (gridWidth = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc)), gridWidth <= iVar5)) || - ((gridWidth < 0 || (*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x10)) <= gridWidth)))) { - *local_71c = 1; - } - else { - iVar5 = gridWidth * gridWidth + iVar5; - *local_71c = 1; - if ((-1 < iVar5) && (iVar5 = cellCounts[iVar5], iVar5 != 0)) { - uVar4 = 0; - gridWidth = *GHIDRA_CAST((GHIDRA_CAST(game->_room) + 0xc)); - uVar3 = *GHIDRA_CAST((GHIDRA_CAST(game->_room) + 0x10)) * gridWidth; - fVar6 = (float)((double)iVar5 + __uint_to_double_fixup[-(iVar5 >> 0x1f)]) * 1000.0; - fVar7 = (float)local_718; - bestY = (float)local_720; - if (uVar3 != 0) { - do { - cellY = (float)(GHIDRA_INT(uVar4) / gridWidth) * 40.0 + 120.0; - iVar5 = cellCounts[uVar4] * cellCounts[uVar4]; - cellX = (float)(GHIDRA_INT(uVar4) % gridWidth) * 40.0 + 40.0; - dy = (float)local_720 - cellY; - score = (float)local_718 - cellX; - score = dy * dy + score * score + - (float)((double)iVar5 + __uint_to_double_fixup[-(iVar5 >> 0x1f)]) * 10000.0; - if (score < fVar6) { - fVar6 = score; - fVar7 = cellX; - bestY = cellY; - } - uVar4 = uVar4 + 1; - } while (uVar4 < uVar3); - } - *local_71c = 0; - outTarget->x = fVar7; - outTarget->y = bestY; - if ((*GHIDRA_CAST((GHIDRA_CAST(&(effects)) + 0x0))) != '\0') { - ExceptionList = local_10; - return outTarget; - } - if (g_mainHeap == (void *)0x0) { - allocCounter = &g_allocatedBytesNoHeap; - } - else { - allocCounter = GHIDRA_CAST((GHIDRA_INT(g_mainHeap) + 0x30)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(effects)) + 0x4))) == 0) { - ExceptionList = local_10; - return outTarget; - } - uVar4 = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(effects)) + 0x4))) + -4)); - qVar1 = *allocCounter; - *GHIDRA_CAST(allocCounter) = GHIDRA_UINT(*allocCounter) - uVar4; - *GHIDRA_CAST((GHIDRA_CAST(allocCounter) + 4)) = - *GHIDRA_CAST((GHIDRA_CAST(allocCounter) + 4)) - GHIDRA_UINT((GHIDRA_UINT(qVar1) < uVar4)); - goto LAB_004a2cad; - } - } - outTarget->x = (float)local_718; - outTarget->y = (float)local_720; - if ((*GHIDRA_CAST((GHIDRA_CAST(&(effects)) + 0x0))) != '\0') { - ExceptionList = local_10; - return outTarget; - } - if (g_mainHeap == (void *)0x0) { - allocCounter = &g_allocatedBytesNoHeap; - } - else { - allocCounter = GHIDRA_CAST((GHIDRA_INT(g_mainHeap) + 0x30)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(effects)) + 0x4))) == 0) { - ExceptionList = local_10; - return outTarget; - } - uVar4 = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(effects)) + 0x4))) + -4)); - qVar1 = *allocCounter; - *GHIDRA_CAST(allocCounter) = GHIDRA_UINT(*allocCounter) - uVar4; - *GHIDRA_CAST((GHIDRA_CAST(allocCounter) + 4)) = *GHIDRA_CAST((GHIDRA_CAST(allocCounter) + 4)) - GHIDRA_UINT((GHIDRA_UINT(qVar1) < uVar4)); -LAB_004a2cad: - free((void *)((*GHIDRA_CAST((GHIDRA_CAST(&(effects)) + 0x4))) + -4)); - ExceptionList = local_10; - return outTarget; -} - -// 004a2ce0 -void NpcHelper::colostomia_pick_dive_target(Entity_NPC *npc) -{ - uint8_t bVar1; - void **roomRef; - Vector *candidatePos; - Entity_Player *nearestPlayer; - uint32_t uVar2; - uint8_t *animData; - int iVar4; - uint8_t *pbVar5; - int iVar6; - Entity_NPC *pEVar7; - bool bVar8; - float fVar9; - float fVar10; - Vector freePos; - Vector randomPos; - int *local_24; - int *local_20; - void **roomSlot; - uint32_t attempt; - Entity_NPC *npcLocal; - uint8_t *animData; - uint32_t *childRef; - Vector *diveTarget; - Game *game; - Room *room; - - game = g_game; - diveTarget = &npc->_v1; - diveTarget->x = g_vectorZero.x; - (npc->_v1).y = g_vectorZero.y; - attempt = 0; - roomRef = &game->_room; - npcLocal = npc; - do { - room = *roomRef; - candidatePos = Room::GetRandomPosition(room,&randomPos,0.0); - candidatePos = Room::FindFreePickupSpawnPosition(room,&freePos,candidatePos,0.0,0,0,0); - pEVar7 = npcLocal; - fVar10 = candidatePos->x; - diveTarget->x = fVar10; - fVar9 = candidatePos->y; - (npc->_v1).y = fVar9; - fVar10 = (npcLocal->_pos).x - fVar10; - fVar9 = (npcLocal->_pos).y - fVar9; - local_20 = GHIDRA_CAST(sqrtf(fVar9 * fVar9 + fVar10 * fVar10)); - nearestPlayer = Game::GetNearestPlayer(g_game,diveTarget); - fVar10 = (nearestPlayer->_pos).y - (npc->_v1).y; - fVar9 = (nearestPlayer->_pos).x - diveTarget->x; - local_24 = GHIDRA_CAST(sqrtf(fVar10 * fVar10 + fVar9 * fVar9)); - roomSlot = &g_game->_room; - bVar1 = Room::IsPositionInRoom(*roomSlot,diveTarget,60.0); - if (bVar1 != 0) { - room = *roomSlot; - iVar6 = GHIDRA_INT(((diveTarget->x - 40.0) / 40.0 + 0.5)); - iVar4 = GHIDRA_INT((((npc->_v1).y - 120.0) / 40.0 + 0.5)); - if ((((iVar6 < 0) || (room->_gridWidth <= iVar6)) || (iVar4 < 0)) || - (room->_gridHeight <= iVar4)) { - iVar6 = -1; - } - else { - iVar6 = room->_gridWidth * iVar4 + iVar6; - } - uVar2 = Room::GetGridCollision(room,iVar6); - pEVar7 = npcLocal; - if ((((uVar2 == 0) && (80.0 <= (float)local_20)) && - (((float)local_20 <= 200.0 && (120.0 < (float)local_24)))) && - ((iVar6 = npcLocal->_entityRef, iVar6 == 0 || - (fVar10 = (npc->_v1).y - *GHIDRA_CAST((iVar6 + 0x340)), - fVar9 = diveTarget->x - *GHIDRA_CAST((iVar6 + 0x33c)), - 10000.0 < fVar10 * fVar10 + fVar9 * fVar9)))) break; - } - attempt = attempt + 1; - roomRef = roomSlot; - } while (attempt < 0xf); - childRef = &pEVar7->_entityRef; - if (pEVar7->_entityRef != 0) { - local_20 = GHIDRA_CAST((pEVar7->_entityRef + 0x3bc)); - if (*local_20 != 0) { - local_24 = local_20; - msvc::multiset::erase(&local_24); - } - *local_20 = 0; - if (*childRef != 0) { - local_24 = childRef; - msvc::multiset::erase(&local_24); - } - *childRef = 0; - } - local_20 = GHIDRA_CAST(pEVar7->_child); - if (local_20 != GHIDRA_CAST(0x0)) { - *childRef = local_20; - msvc::multiset::insert(childRef); - if (pEVar7->_child != 0) { - local_24 = &pEVar7->_child; - msvc::multiset::erase(&local_24); - } - pEVar7->_child = 0; - } - animData = (pEVar7->_sprite)._animState._animData; - if (animData != GHIDRA_CAST(0x0)) { - animData = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - animData = *GHIDRA_CAST(animData); - } - pbVar5 = &DAT_00b1d33c; - do { - bVar1 = *animData; - bVar8 = bVar1 < *pbVar5; - if (bVar1 != *pbVar5) { -LAB_004a2fd4: - uVar2 = -GHIDRA_UINT(bVar8) | 1; - goto LAB_004a2fd9; - } - if (bVar1 == 0) break; - bVar1 = animData[1]; - bVar8 = bVar1 < pbVar5[1]; - if (bVar1 != pbVar5[1]) goto LAB_004a2fd4; - animData = animData + 2; - pbVar5 = pbVar5 + 2; - } while (bVar1 != 0); - uVar2 = 0; -LAB_004a2fd9: - if ((uVar2 == 0) && ((animData[0x34] == 0 || ((pEVar7->_sprite)._animState._isPlaying != 0)))) - goto LAB_004a2fed; - } - bVar1 = ANM2::SetAnimation(&pEVar7->_sprite,&DAT_00b1d33c,1); - if (bVar1 != 0) { - AnimationState::Rewind(&(pEVar7->_sprite)._animState); - (pEVar7->_sprite)._animState._isPlaying = 1; - npcLocal->_state = 6; - return; - } -LAB_004a2fed: - pEVar7->_state = 6; - return; -} - // 004b70c0 void NpcHelper::hornfel_spawn_doors() { @@ -2208,675 +1916,6 @@ void NpcHelper::hornfel_room_controller(Entity_Effect *effect) return; } -// 004bc680 -uint8_t NpcHelper::horny_boys_pick_position(Entity_NPC *npc) -{ - Entity_Player *nearestPlayer; - Game *game; - int gridWidth; - int iVar1; - int gridX; - uint32_t gridIndex; - float fVar2; - float dy; - float playerDistSq; - Vector candidatePos; - float candidateY; - float candidateX; - int attemptsLeft; - float bestDistSq; - void *room; - - game = g_game; - bestDistSq = 0.0; - attemptsLeft = 6; - (npc->_targetPosition).x = g_vectorZero.x; - (npc->_targetPosition).y = g_vectorZero.y; - do { - Room::GetRandomPosition(game->_room,&candidatePos,20.0); - room = g_game->_room; - gridX = GHIDRA_INT(((candidatePos.x - 40.0) / 40.0 + 0.5)); - iVar1 = GHIDRA_INT(((candidatePos.y - 120.0) / 40.0 + 0.5)); - if ((((gridX < 0) || (gridWidth = *GHIDRA_CAST((GHIDRA_CAST(room) + 0xc)), gridWidth <= gridX)) || (iVar1 < 0) - ) || (*GHIDRA_CAST((GHIDRA_CAST(room) + 0x10)) <= iVar1)) { - gridWidth = *GHIDRA_CAST((GHIDRA_CAST(room) + 0xc)); - gridIndex = 0xffffffff; - } - else { - gridIndex = gridWidth * iVar1 + gridX; - } - candidatePos.x = (float)(GHIDRA_INT(gridIndex) % gridWidth) * 40.0 + 40.0; - candidatePos.y = (float)(GHIDRA_INT(gridIndex) / gridWidth) * 40.0 + 120.0; - candidateY = candidatePos.y; - candidateX = candidatePos.x; - nearestPlayer = Game::GetNearestPlayer(g_game,&candidatePos); - game = g_game; - fVar2 = candidateX - (nearestPlayer->_pos).x; - dy = candidateY - (nearestPlayer->_pos).y; - playerDistSq = dy * dy + fVar2 * fVar2; - if ((((20.0 <= ABS(fVar2)) && (20.0 <= ABS(dy))) || (160000.0 <= playerDistSq)) && - (((40000.0 <= playerDistSq && - ((0x1bf < gridIndex || (*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + gridIndex * 4 + 0x76c)) < 500)))) && - (fVar2 = (npc->_pos).x - candidateX, dy = (npc->_pos).y - candidateY, - fVar2 = dy * dy + fVar2 * fVar2, bestDistSq < fVar2)))) { - (npc->_targetPosition).x = candidateX; - (npc->_targetPosition).y = candidateY; - bestDistSq = fVar2; - } - attemptsLeft = attemptsLeft + -1; - } while (attemptsLeft != 0); - if (((npc->_targetPosition).x == g_vectorZero.x) && ((npc->_targetPosition).y == g_vectorZero.y)) - { - return 0; - } - return 1; -} - -// 004bc8c0 -Entity * NpcHelper::horny_boys_pull_entity(Entity_NPC *npc, int slot, Vector *targetPos) -{ - int iVar1; - uint32_t uVar2; - uint32_t blockSlot; - Entity *pEVar3; - float fVar4; - float dx; - int *local_c; - float local_8; - uint32_t *parentSlot; - - local_c = GHIDRA_CAST((npc->_entityDeque)._offset); - uVar2 = GHIDRA_UINT((slot + GHIDRA_INT(local_c))) >> 2; - blockSlot = slot + GHIDRA_INT(local_c) & 3; - if (*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + - ((npc->_entityDeque)._mapSize - 1 & uVar2) * 4)) + blockSlot * 4)) == 0) { - return GHIDRA_CAST(0x0); - } - pEVar3 = *(Entity **) - (*GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + ((npc->_entityDeque)._mapSize - 1 & uVar2) * 4 - )) + blockSlot * 4); - if ((pEVar3 == GHIDRA_CAST(0x0)) || (pEVar3->_type != 4)) { - pEVar3 = GHIDRA_CAST(0x0); - } - else { - dx = (npc->_pos).x - targetPos->x; - local_8 = targetPos->y; - fVar4 = (npc->_pos).y - local_8; - targetPos = GHIDRA_CAST(targetPos->x); - fVar4 = sqrtf(fVar4 * fVar4 + dx * dx); - targetPos = GHIDRA_CAST(((float)targetPos - (npc->_pos).x)); - fVar4 = (fVar4 - 100.0) / 200.0; - if (fVar4 <= 0.0) { - fVar4 = 0.0; - } - if (1.0 <= fVar4) { - fVar4 = 1.0; - } - local_c = GHIDRA_CAST((fVar4 * 18.0 + 10.0)); - local_8 = local_8 - (npc->_pos).y; - fVar4 = sqrtf(local_8 * local_8 + (float)targetPos * (float)targetPos); - if (0.0 < fVar4) { - local_8 = (1.0 / fVar4) * local_8; - targetPos = GHIDRA_CAST(((1.0 / fVar4) * (float)targetPos)); - } - targetPos = GHIDRA_CAST(((float)targetPos * (float)local_c)); - parentSlot = &pEVar3->_parent; - local_8 = local_8 * (float)local_c; - if (*parentSlot != 0) { - local_c = parentSlot; - msvc::multiset::erase(&local_c); - } - *parentSlot = npc; - if (npc != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(parentSlot); - } - pEVar3->_entityCollisionClass = 4; - pEVar3->_visible = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(pEVar3[1])) + 0xc)))) = 0xc0800000; - (pEVar3->_posOffset).x = 0.0; - (pEVar3->_posOffset).y = -24.0; - (pEVar3->_pos).x = (npc->_pos).x; - fVar4 = (npc->_pos).y; - *GHIDRA_CAST(&pEVar3->_flags) = GHIDRA_UINT(pEVar3->_flags) & 0xffffffdf; - (pEVar3->_pos).y = fVar4; - *GHIDRA_CAST((GHIDRA_INT(&pEVar3->_flags) + 4)) = *GHIDRA_CAST((GHIDRA_INT(&pEVar3->_flags) + 4)); - iVar1 = *GHIDRA_CAST(pEVar3); - (pEVar3->_velocity).x = (float)targetPos; - (pEVar3->_velocity).y = local_8; - (**(code **)(iVar1 + 0xc))(); - } - uVar2 = slot + (npc->_entityDeque)._offset; - blockSlot = uVar2 & 3; - iVar1 = *GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + - (uVar2 >> 2 & (npc->_entityDeque)._mapSize - 1) * 4)); - parentSlot = GHIDRA_CAST((iVar1 + blockSlot * 4)); - if (*GHIDRA_CAST((iVar1 + blockSlot * 4)) != 0) { - slot = GHIDRA_INT(parentSlot); - msvc::multiset::erase(&slot); - } - *parentSlot = 0; - return pEVar3; -} - -// 004bcc70 -Entity * NpcHelper::horny_boys_spawn_bomb(Entity_NPC *npc, int slot) -{ - uint32_t uVar1; - int iVar2; - RNG rng; - uint8_t *puVar3; - Entity *pEVar4; - uint32_t uVar5; - void *ptr; - uint32_t uVar6; - BitSet128 bombTearFlags0; - uint64_t uStack_3c; - uint32_t *puStack_34; - void *picker; - uint32_t *outcomesEnd; - uint32_t *outcomesCapacity; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - uint32_t *bombSlot; - int *outcomeWeight; - - puStack_20 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - local_14 = 0xffffffff; - puStack_18 = &DAT_00af350d; - local_1c = ExceptionList; - local_24 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 0x10U; - ExceptionList = &local_1c; - uVar5 = slot + (npc->_entityDeque)._offset; - uVar6 = uVar5 >> 2; - uVar5 = uVar5 & 3; - puVar3 = GHIDRA_CAST((GHIDRA_INT(register0x00000010) + -4)); - if (*GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + - ((npc->_entityDeque)._mapSize - 1 & uVar6) * 4)) + uVar5 * 4)) != 0) { - puStack_34 = GHIDRA_CAST((npc->_entityDeque)._offset); - (**(code **)(**GHIDRA_CAST((*GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + - ((npc->_entityDeque)._mapSize - 1 & uVar6) * 4)) + uVar5 * 4)) + - 0x28))(local_24); - puVar3 = puStack_20; - } - puStack_20 = puVar3; - picker = (void *)0x0; - outcomesEnd = GHIDRA_CAST(0x0); - outcomesCapacity = GHIDRA_CAST(0x0); - local_14 = 0; - uStack_3c = (uint64_t)GHIDRA_UINT(uStack_3c); - puStack_34 = GHIDRA_CAST(0x6); - msvc::vector<8byte>::_Emplace_reallocate(0,GHIDRA_INT(&uStack_3c) + 4); - uVar5 = 0; - uVar6 = GHIDRA_INT(outcomesEnd) - GHIDRA_INT(picker) >> 3; - if (uVar6 != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(picker) + uVar5 * 8)) == 8) { - outcomeWeight = GHIDRA_CAST((GHIDRA_INT(picker) + uVar5 * 8 + 4)); - *outcomeWeight = *outcomeWeight + 3; - if (*outcomeWeight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(picker) + uVar5 * 8 + 4)) = 0; - } - goto LAB_004bcda7; - } - uVar5 = uVar5 + 1; - } while (uVar5 < uVar6); - } - uStack_3c = CONCAT44(8,GHIDRA_UINT(uStack_3c)); - puStack_34 = GHIDRA_CAST(0x3); - if (outcomesEnd == outcomesCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesEnd,GHIDRA_INT(&uStack_3c) + 4); - } - else { - *outcomesEnd = 8; - outcomesEnd[1] = 3; - outcomesEnd = outcomesEnd + 2; - } -LAB_004bcda7: - uVar5 = 0; - uVar6 = GHIDRA_INT(outcomesEnd) - GHIDRA_INT(picker) >> 3; - if (uVar6 != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(picker) + uVar5 * 8)) == 0x10) { - outcomeWeight = GHIDRA_CAST((GHIDRA_INT(picker) + uVar5 * 8 + 4)); - *outcomeWeight = *outcomeWeight + 1; - if (*outcomeWeight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(picker) + uVar5 * 8 + 4)) = 0; - } - goto LAB_004bce05; - } - uVar5 = uVar5 + 1; - } while (uVar5 < uVar6); - } - uStack_3c = CONCAT44(0x10,GHIDRA_UINT(uStack_3c)); - puStack_34 = GHIDRA_CAST(0x1); - if (outcomesEnd == outcomesCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(outcomesEnd,GHIDRA_INT(&uStack_3c) + 4); - } - else { - *outcomesEnd = 0x10; - outcomesEnd[1] = 1; - outcomesEnd = outcomesEnd + 2; - } -LAB_004bce05: - uVar5 = Random(); - uStack_3c = 0x900000005; - puStack_34 = GHIDRA_CAST(&DAT_00000007); - rng._shift1 = 5; - rng._seed = uVar5 | 1; - rng._shift2 = 9; - rng._shift3 = 7; - uVar5 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&picker),rng); - bombTearFlags0 = (BitSet128)ZEXT816(0); - if (uVar5 == 8) { - bombTearFlags0 = g_tearFlagBurn; - } - else if (uVar5 == 0x10) { - bombTearFlags0 = g_tearFlagSadBomb; - } - else { - } - uVar6 = Random(); - pEVar4 = Game::Spawn(g_game,4,uVar5,&npc->_pos,&g_vectorZero,GHIDRA_CAST(npc),0,uVar6); - pEVar4->_visible = 0; - pEVar4->_entityCollisionClass = 0; - pEVar4->_entityGridCollisionClass = 0; - if (pEVar4->_parent != 0) { - puStack_34 = &pEVar4->_parent; - msvc::multiset::erase(&puStack_34); - } - pEVar4->_parent = npc; - if (npc != GHIDRA_CAST(0x0)) { - msvc::multiset::insert(&pEVar4->_parent); - } - uVar1 = *GHIDRA_CAST((GHIDRA_INT(&pEVar4->_flags) + 4)); - *GHIDRA_CAST(&pEVar4->_flags) = GHIDRA_UINT(pEVar4->_flags) | 0x20; - *GHIDRA_CAST((GHIDRA_INT(&pEVar4->_flags) + 4)) = uVar1; - iVar2 = *GHIDRA_CAST(pEVar4); - *GHIDRA_CAST((pEVar4 + 1)) = 0x23; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(pEVar4[1])) + 0x4)))) = 0x23; - pEVar4[1]._type = GHIDRA_INT(bombTearFlags0._l); - pEVar4[1]._variant = (*GHIDRA_CAST((GHIDRA_CAST(&(bombTearFlags0._l)) + 0x4))); - pEVar4[1]._subtype = GHIDRA_INT(bombTearFlags0._h); - pEVar4[1]._spawnerType = (*GHIDRA_CAST((GHIDRA_CAST(&(bombTearFlags0._h)) + 0x4))); - pEVar4[1]._sprite._filename._buf[0xb] = '\x01'; - (**(code **)(iVar2 + 0xc))(); - puStack_34 = GHIDRA_CAST((npc->_entityDeque)._offset); - uVar5 = slot + GHIDRA_INT(puStack_34) & 3; - iVar2 = *GHIDRA_CAST((GHIDRA_INT((npc->_entityDeque)._map) + - (GHIDRA_UINT((slot + GHIDRA_INT(puStack_34))) >> 2 & (npc->_entityDeque)._mapSize - 1) * 4)); - bombSlot = GHIDRA_CAST((iVar2 + uVar5 * 4)); - if (*GHIDRA_CAST((iVar2 + uVar5 * 4)) != 0) { - puStack_34 = bombSlot; - msvc::multiset::erase(&puStack_34); - } - *bombSlot = pEVar4; - msvc::multiset::insert(bombSlot); - if (picker != (void *)0x0) { - uVar5 = GHIDRA_INT(outcomesCapacity) - GHIDRA_INT(picker) & 0xfffffff8; - ptr = picker; - if (0xfff < uVar5) { - ptr = *(void **)(GHIDRA_CAST(picker) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(picker) + (-4 - GHIDRA_INT(ptr))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(ptr,uVar5); - } - ExceptionList = local_1c; - return pEVar4; -} - -// 004d8d10 -Entity_NPC * NpcHelper::gaper_l2_spawn_maggot(Vector *origin, float yOffset, Vector *velocity, float fallingSpeed) -{ - void *pvVar1; - code *pcVar2; - uint32_t seed; - Entity_NPC *maggot; - float fVar3; - float fVar4; - float dirY; - uint64_t flags; - uint32_t flagsHigh; - - pvVar1 = g_game->_room; - seed = Random(); - maggot = GHIDRA_CAST(Game)::Spawn(g_game,0x355,0,origin,&g_vectorZero,GHIDRA_CAST(0x0),0,seed); - *GHIDRA_CAST(&maggot->_flags) = GHIDRA_UINT(maggot->_flags) & 0xfffffffb; - flagsHigh = *GHIDRA_CAST((GHIDRA_INT(&maggot->_flags) + 4)); - flags = maggot->_flags; - (maggot->_v1).x = fallingSpeed; - *GHIDRA_CAST((GHIDRA_INT(&maggot->_flags) + 4)) = flagsHigh; - fVar3 = sqrtf(velocity->x * velocity->x + velocity->y * velocity->y); - (maggot->_v1).y = fVar3; - fVar3 = velocity->x; - (maggot->_targetPosition).x = fVar3; - dirY = velocity->y; - (maggot->_targetPosition).y = dirY; - (maggot->_velocity).y = dirY; - (maggot->_velocity).x = fVar3; - maggot->_state = 0x10; - maggot->_i1 = 2; - *GHIDRA_CAST(&maggot->_flags) = GHIDRA_UINT(flags) | 0x4000000; - *GHIDRA_CAST((GHIDRA_INT(&maggot->_flags) + 4)) = flagsHigh; - if (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 8)) == 0x10) { - (maggot->_pos).y = yOffset + (maggot->_pos).y; - (maggot->_velocity).y = fallingSpeed + (maggot->_velocity).y; - } - else { - (maggot->_posOffset).y = yOffset; - } - (**(code **)(*GHIDRA_CAST(maggot) + 0xc))(); - fVar3 = (maggot->_velocity).x; - dirY = (maggot->_velocity).y; - seed = maggot->_initSeed; - fVar4 = sqrtf(fVar3 * fVar3 + dirY * dirY); - if (0.0 < fVar4) { - fVar3 = fVar3 * (1.0 / fVar4); - dirY = dirY * (1.0 / fVar4); - } - (maggot->_pathfinder)._movementTarget.x = fVar3; - (maggot->_pathfinder)._movementTarget.y = dirY; - if (seed == 0) { - KAGE_LogMessage(0x10,GHIDRA_CAST("RNG Seed is zero!\n")); - pcVar2 = (code *)swi(3); - maggot = GHIDRA_CAST((*pcVar2)()); - return maggot; - } - seed = seed >> 5 ^ seed; - seed = seed << 9 ^ seed; - (maggot->_pathfinder)._moveCountdown = (seed >> 7 ^ seed) % 0x1e + 10; - return maggot; -} - -// 004d8f20 -Vector * NpcHelper::adult_leech_heading(Vector *outHeading, Entity *target, Vector npcPos) -{ - uint32_t rngResult; - float fVar1; - float cosAngle; - - rngResult = Random(); - fVar1 = ((float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 - 0.5) * 90.0 * 0.017453292; - cosAngle = cos(fVar1); - outHeading->x = cosAngle; - fVar1 = sin(fVar1); - outHeading->y = fVar1; - rngResult = Random(); - if ((rngResult & 1) == 0) { - outHeading->x = outHeading->x * -1.0; - } - rngResult = Random(); - if ((rngResult & 1) == 0) { - fVar1 = outHeading->y; - cosAngle = (target->_pos).y; - if (((fVar1 < 0.0) && (npcPos.y < cosAngle)) || ((0.0 < fVar1 && (cosAngle < npcPos.y)))) { - outHeading->y = fVar1 * -1.0; - } - } - return outHeading; -} - -// 004db3c0 -void NpcHelper::twitchy_jump_target(Vector *outTarget, Entity_NPC *npc) -{ - Entity *playerTarget; - Vector *resultPos; - uint32_t gridCollision; - int gridRow; - int gridIndex; - float fVar1; - float fVar2; - float fVar3; - Vector scratchVec; - float toTargetX; - float local_c; - float local_8; - Room *room; - - room = g_game->_room; - Entity_NPC::CalcTargetPosition(npc,outTarget,0.0); - playerTarget = Entity_NPC::GetPlayerTarget(npc); - local_8 = (playerTarget->_velocity).y; - fVar2 = (npc->_pos).x - (playerTarget->_pos).x; - local_c = (playerTarget->_velocity).x; - fVar1 = (npc->_pos).y - (playerTarget->_pos).y; - fVar1 = sqrtf(fVar1 * fVar1 + fVar2 * fVar2); - local_c = local_c * 0.1 * fVar1 + outTarget->x; - local_8 = local_8 * 0.1 * fVar1 + outTarget->y; - outTarget->x = local_c; - outTarget->y = local_8; - scratchVec.y = local_8 - (npc->_pos).y; - toTargetX = local_c - (npc->_pos).x; - fVar1 = sqrtf(scratchVec.y * scratchVec.y + toTargetX * toTargetX); - if (fVar1 <= 0.0) { - fVar2 = toTargetX; - fVar1 = scratchVec.y; - } - else { - fVar2 = toTargetX * (1.0 / fVar1); - fVar1 = scratchVec.y * (1.0 / fVar1); - } - outTarget->x = fVar2 * 40.0 + local_c; - outTarget->y = fVar1 * 40.0 + local_8; - resultPos = Room::GetClampedPositionImpl(room,&scratchVec,outTarget,0.0,0.0,0.0,0.0); - local_8 = resultPos->x; - outTarget->x = local_8; - local_c = resultPos->y; - outTarget->y = local_c; - fVar2 = (npc->_pos).x - local_8; - fVar1 = (npc->_pos).y - local_c; - fVar1 = sqrtf(fVar1 * fVar1 + fVar2 * fVar2); - if (fVar1 <= 200.0) { - fVar1 = local_8; - fVar2 = local_c; - } - else { - local_c = local_c - (npc->_pos).y; - local_8 = local_8 - (npc->_pos).x; - fVar1 = sqrtf(local_c * local_c + local_8 * local_8); - if (fVar1 <= 0.0) { - fVar2 = local_8; - fVar3 = local_c; - } - else { - fVar2 = local_8 * (1.0 / fVar1); - fVar3 = local_c * (1.0 / fVar1); - } - fVar1 = fVar2 * 200.0 + (npc->_pos).x; - fVar2 = fVar3 * 200.0 + (npc->_pos).y; - outTarget->x = fVar1; - outTarget->y = fVar2; - } - gridRow = GHIDRA_INT(((fVar2 - 120.0) / 40.0 + 0.5)); - gridIndex = GHIDRA_INT(((fVar1 - 40.0) / 40.0 + 0.5)); - if ((((gridIndex < 0) || (room->_gridWidth <= gridIndex)) || (gridRow < 0)) || - (room->_gridHeight <= gridRow)) { - gridIndex = -1; - } - else { - gridIndex = room->_gridWidth * gridRow + gridIndex; - } - gridCollision = Room::GetGridCollision(room,gridIndex); - if (0 < GHIDRA_INT(gridCollision)) { - resultPos = Room::FindFreeTilePosition(room,&scratchVec,outTarget,64.0); - outTarget->x = resultPos->x; - outTarget->y = resultPos->y; - } - return; -} - -// 004e0930 -void NpcHelper::gutted_fatty_burst_projectiles(Entity *timer) -{ - uint32_t rngResult; - uint32_t rngFraction; - Entity_Projectile *pEVar1; - int projectilesLeft; - float originY; - float dirX; - float randomScale; - Vector local_18; - Vector local_10; - float originX; - float originY; - - projectilesLeft = 2; - originX = (timer->_pos).x; - originY = (timer->_pos).y; - do { - rngResult = Random(); - originY = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - originY = originY + originY; - dirX = cos(originY); - originY = sin(originY); - rngResult = Random(); - rngFraction = Random(); - randomScale = (float)((double)GHIDRA_INT(rngFraction) + - __uint_to_double_fixup[-(GHIDRA_INT(rngFraction) >> 0x1f)]) * 2.3283064e-10; - local_18.y = randomScale * originY * 2.8; - local_18.x = randomScale * dirX * 2.8; - rngFraction = Random(); - randomScale = (float)((double)GHIDRA_INT(rngFraction) + - __uint_to_double_fixup[-(GHIDRA_INT(rngFraction) >> 0x1f)]) * 2.3283064e-10; - local_10.x = dirX * 5.0 * randomScale + originX; - local_10.y = originY * 5.0 * randomScale + originY; - pEVar1 = (Entity_Projectile *) - Game::SpawnEx(g_game,9,0,&local_10,&local_18,GHIDRA_CAST(0x0),0,rngResult,0); - pEVar1->_spawnerType = 0x33f; - rngResult = Random(); - pEVar1->_fallingAccel = 2.0; - pEVar1->_scale = - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 1.4; - rngResult = Random(); - pEVar1->_fallingSpeed = - -15.0 - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 * 60.0; - rngResult = Random(); - pEVar1->_height = - -23.0 - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 * 15.0; - Entity_Projectile::apply_spawn_flags - (pEVar1,*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(timer[1])) + 0x40)))), - *GHIDRA_CAST((timer[1]._sprite._animDefaultName._buf + 8)),timer->_flags,GHIDRA_CAST(0x0)); - (**(code **)(*GHIDRA_CAST(pEVar1) + 0xc))(); - projectilesLeft = projectilesLeft + -1; - } while (projectilesLeft != 0); - projectilesLeft = 2; - do { - rngResult = Random(); - originY = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - originY = originY + originY; - dirX = cos(originY); - originY = sin(originY); - rngResult = Random(); - rngFraction = Random(); - randomScale = (float)((double)GHIDRA_INT(rngFraction) + - __uint_to_double_fixup[-(GHIDRA_INT(rngFraction) >> 0x1f)]) * 2.3283064e-10; - local_10.y = randomScale * originY * 2.8; - local_10.x = randomScale * dirX * 2.8; - rngFraction = Random(); - randomScale = (float)((double)GHIDRA_INT(rngFraction) + - __uint_to_double_fixup[-(GHIDRA_INT(rngFraction) >> 0x1f)]) * 2.3283064e-10; - local_18.x = dirX * 5.0 * randomScale + originX; - local_18.y = originY * 5.0 * randomScale + originY; - pEVar1 = (Entity_Projectile *) - Game::SpawnEx(g_game,9,0,&local_18,&local_10,GHIDRA_CAST(0x0),0,rngResult,0); - pEVar1->_spawnerType = 0x33f; - rngResult = Random(); - pEVar1->_fallingAccel = 2.0; - pEVar1->_scale = - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 1.4; - rngResult = Random(); - pEVar1->_fallingSpeed = - -15.0 - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 * 60.0; - rngResult = Random(); - pEVar1->_height = - -23.0 - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 * 1000.0; - Entity_Projectile::apply_spawn_flags - (pEVar1,*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(timer[1])) + 0x40)))), - *GHIDRA_CAST((timer[1]._sprite._animDefaultName._buf + 8)),timer->_flags,GHIDRA_CAST(0x0)); - (**(code **)(*GHIDRA_CAST(pEVar1) + 0xc))(); - projectilesLeft = projectilesLeft + -1; - } while (projectilesLeft != 0); - return; -} - -// 004e4870 -uint8_t NpcHelper::candler_is_free_cell(Vector *position) -{ - uint32_t uVar1; - int gridY; - int gridY; - Room *room; - - room = g_game->_room; - gridY = GHIDRA_INT(((position->x - 40.0) / 40.0 + 0.5)); - gridY = GHIDRA_INT(((position->y - 120.0) / 40.0 + 0.5)); - if ((((gridY < 0) || (room->_gridWidth <= gridY)) || (gridY < 0)) || (room->_gridHeight <= gridY)) - { - gridY = -1; - } - else { - gridY = room->_gridWidth * gridY + gridY; - } - uVar1 = Room::GetGridCollision(room,gridY); - if (((((uVar1 == 0) && (gridY = GHIDRA_INT(((position->x - 40.0) / 40.0 + 0.5)), -1 < gridY)) && - ((gridY < room->_gridWidth && - ((gridY = GHIDRA_INT(((position->y - 120.0) / 40.0 + 0.5)), -1 < gridY && - (gridY < room->_gridHeight)))))) && (gridY = room->_gridWidth * gridY + gridY, -1 < gridY)) - && (((0x1bf < gridY || (room->_gridEntities[gridY] == (void *)0x0)) || - (*GHIDRA_CAST((GHIDRA_INT(room->_gridEntities[gridY]) + 4)) != 0x17)))) { - return 1; - } - return 0; -} - -// 00501e10 -void NpcHelper::bouncer_death_gib(Entity_Effect *timer) -{ - uint32_t rngResult; - Entity *pEVar1; - float sinAngle; - Vector local_20; - float local_18; - float velocityX; - Vector gibVelocity; - - rngResult = Random(); - local_20.x = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_20.x = local_20.x + local_20.x; - rngResult = Random(); - local_18 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 12.0; - velocityX = cos(local_20.x); - velocityX = velocityX * local_18; - gibVelocity.x = velocityX; - sinAngle = sin(local_20.x); - local_18 = sinAngle * local_18; - gibVelocity.y = local_18; - rngResult = Random(); - local_20.x = (timer->_pos).x; - local_20.y = (timer->_pos).y; - pEVar1 = Game::SpawnEx(g_game,1000,2,&local_20,&gibVelocity,GHIDRA_CAST(0x0),3,rngResult,0); - (pEVar1->_sprite)._offset.x = velocityX + 0.0; - (pEVar1->_sprite)._offset.y = local_18 - 26.0; - return; -} - // 00528ec0 void NpcHelper::migraine_timer_spawn(Entity *timer) { @@ -3412,43 +2451,6 @@ LAB_00529ca4: } while( true ); } -// 005441e0 -uint8_t NpcHelper::tarboy_is_creep_near(Entity_NPC *npc, Vector *position) -{ - int iVar1; - uint32_t i; - int *entityIt; - float deltaY; - float deltaX; - uint32_t entityCount; - bool isFriendly; - - if ((npc == GHIDRA_CAST(0x0)) || ((npc->_flags & 0x20000000) == 0)) { - isFriendly = false; - } - else { - isFriendly = true; - } - i = 0; - entityCount = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x1264)); - if (entityCount != 0) { - entityIt = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x125c)); - do { - iVar1 = *entityIt; - if ((*GHIDRA_CAST((iVar1 + 0x28)) == 1000) && - (((*GHIDRA_CAST((iVar1 + 0x2c)) == 0x1a || ((isFriendly && (*GHIDRA_CAST((iVar1 + 0x2c)) == 0x2d)))) && - (deltaX = position->x - *GHIDRA_CAST((iVar1 + 0x33c)), - deltaY = position->y - *GHIDRA_CAST((iVar1 + 0x340)), - deltaX * deltaX + deltaY * deltaY < 676.0)))) { - return 1; - } - i = i + 1; - entityIt = entityIt + 1; - } while (i < entityCount); - } - return 0; -} - // 0055d070 uint8_t NpcHelper::polty_target_set(int gridIndex) { @@ -3554,351 +2556,6 @@ void NpcHelper::mother_set_collision_class(Entity_NPC *npc, int collisionClass) return; } -// 00568cc0 -void NpcHelper::mother_spawn_parts() -{ - uint32_t uVar1; - uint32_t uVar2; - Entity *pEVar3; - Entity_NPC *npc; - Entity *part2; - Entity *in_ECX; - uint32_t blockSlot; - uint32_t *childRef; - float offsetY; - Vector part3Pos; - Vector part2Pos; - Vector part1Pos; - Entity_NPC *local_24; - float local_20; - Entity_NPC *local_1c; - int *local_18; - Entity *local_14; - int dequeBlock; - uint64_t flags; - - part1Pos.x = DAT_00c33d3c + (in_ECX->_pos).x; - part1Pos.y = DAT_00c33d40 + (in_ECX->_pos).y; - npc = GHIDRA_CAST(Game)::Spawn(g_game,0x390,0,&part1Pos,&g_vectorZero,in_ECX,1,in_ECX->_initSeed) - ; - offsetY = (in_ECX->_posOffset).y - DAT_00c33d40; - (npc->_posOffset).x = (in_ECX->_posOffset).x - DAT_00c33d3c; - (npc->_posOffset).y = offsetY; - local_24 = npc; - mother_set_collision_class(npc,0); - uVar1 = *GHIDRA_CAST((GHIDRA_INT(&npc->_flags) + 4)); - npc->_isInvicible = 1; - *GHIDRA_CAST(&npc->_flags) = GHIDRA_UINT(npc->_flags) & 0xfffffffb | 0x80100011; - *GHIDRA_CAST((GHIDRA_INT(&npc->_flags) + 4)) = uVar1; - Entity::SetVisibleFlag(GHIDRA_CAST(npc),0); - if (npc->_parent != 0) { - local_14 = GHIDRA_CAST(&npc->_parent); - msvc::multiset::erase(&local_14); - } - npc->_parent = in_ECX; - msvc::multiset::insert(&npc->_parent); - (**(code **)(*GHIDRA_CAST(npc) + 0xc))(); - part2Pos.x = DAT_00c33d44 + (in_ECX->_pos).x; - part2Pos.y = DAT_00c33d48 + (in_ECX->_pos).y; - part2 = Game::Spawn(g_game,0x390,0,&part2Pos,&g_vectorZero,in_ECX,2,in_ECX->_initSeed); - local_20 = -g_vectorOne.x; - local_1c = GHIDRA_CAST(-g_vectorOne.y); - local_14 = part2; - Entity::SetSize(part2,70.0,(Vector)(CONCAT44(g_vectorOne.y,g_vectorOne.x) ^ 0x8000000080000000),-1 - ); - offsetY = (in_ECX->_posOffset).y - DAT_00c33d48; - (part2->_posOffset).x = (in_ECX->_posOffset).x - DAT_00c33d44; - (part2->_posOffset).y = offsetY; - if (part2->_parent != 0) { - local_18 = &part2->_parent; - msvc::multiset::erase(&local_18); - } - part2->_parent = in_ECX; - msvc::multiset::insert(&part2->_parent); - flags = part2->_flags; - *GHIDRA_CAST((GHIDRA_INT(&part2->_flags) + 4)) = *GHIDRA_CAST((GHIDRA_INT(&part2->_flags) + 4)); - *GHIDRA_CAST(&part2->_flags) = GHIDRA_UINT(flags) & 0xfffffffb | 0x80000000; - (**(code **)(*GHIDRA_CAST(part2) + 0xc))(); - part3Pos.x = DAT_00c33d4c + (in_ECX->_pos).x; - part3Pos.y = DAT_00c33d50 + (in_ECX->_pos).y; - part2 = Game::Spawn(g_game,0x390,0,&part3Pos,&g_vectorZero,in_ECX,3,in_ECX->_initSeed); - local_20 = -g_vectorOne.x; - local_1c = GHIDRA_CAST(-g_vectorOne.y); - Entity::SetSize(part2,70.0,(Vector)(CONCAT44(g_vectorOne.y,g_vectorOne.x) ^ 0x8000000080000000),-1 - ); - offsetY = (in_ECX->_posOffset).y - DAT_00c33d50; - (part2->_posOffset).x = (in_ECX->_posOffset).x - DAT_00c33d4c; - (part2->_posOffset).y = offsetY; - if (part2->_parent != 0) { - local_18 = &part2->_parent; - msvc::multiset::erase(&local_18); - } - part2->_parent = in_ECX; - msvc::multiset::insert(&part2->_parent); - flags = part2->_flags; - *GHIDRA_CAST((GHIDRA_INT(&part2->_flags) + 4)) = *GHIDRA_CAST((GHIDRA_INT(&part2->_flags) + 4)); - *GHIDRA_CAST(&part2->_flags) = GHIDRA_UINT(flags) & 0xfffffffb | 0x80000000; - (**(code **)(*GHIDRA_CAST(part2) + 0xc))(); - local_18 = GHIDRA_CAST(0x0); - msvc::deque::resize(3,&local_18); - uVar2 = in_ECX[2]._dropRNG._seed; - blockSlot = uVar2 & 3; - dequeBlock = *GHIDRA_CAST((in_ECX[2]._minecart + (uVar2 >> 2 & in_ECX[2]._hitEffect - 1) * 4)); - local_1c = GHIDRA_CAST((dequeBlock + blockSlot * 4)); - if (*GHIDRA_CAST((dequeBlock + blockSlot * 4)) != 0) { - local_18 = GHIDRA_CAST(local_1c); - msvc::multiset::erase(&local_18); - } - *GHIDRA_CAST(local_1c) = local_24; - msvc::multiset::insert(local_1c); - uVar2 = in_ECX[2]._dropRNG._seed + 1; - blockSlot = uVar2 & 3; - dequeBlock = *GHIDRA_CAST((in_ECX[2]._minecart + (uVar2 >> 2 & in_ECX[2]._hitEffect - 1) * 4)); - local_1c = GHIDRA_CAST((dequeBlock + blockSlot * 4)); - if (*GHIDRA_CAST((dequeBlock + blockSlot * 4)) != 0) { - local_24 = local_1c; - msvc::multiset::erase(&local_24); - } - *GHIDRA_CAST(local_1c) = local_14; - msvc::multiset::insert(local_1c); - uVar2 = in_ECX[2]._dropRNG._seed + 2; - blockSlot = uVar2 & 3; - dequeBlock = *GHIDRA_CAST((in_ECX[2]._minecart + (uVar2 >> 2 & in_ECX[2]._hitEffect - 1) * 4)); - local_1c = GHIDRA_CAST((dequeBlock + blockSlot * 4)); - if (*GHIDRA_CAST((dequeBlock + blockSlot * 4)) != 0) { - local_24 = local_1c; - msvc::multiset::erase(&local_24); - } - *GHIDRA_CAST(local_1c) = part2; - msvc::multiset::insert(local_1c); - local_1c = GHIDRA_CAST(&in_ECX->_child); - if (in_ECX->_child != 0) { - local_24 = local_1c; - msvc::multiset::erase(&local_24); - } - pEVar3 = local_14; - *GHIDRA_CAST(local_1c) = local_14; - msvc::multiset::insert(local_1c); - childRef = &pEVar3->_child; - if (pEVar3->_child != 0) { - local_24 = GHIDRA_CAST(childRef); - msvc::multiset::erase(&local_24); - } - *childRef = part2; - msvc::multiset::insert(childRef); - return; -} - -// 0056c800 -void NpcHelper::mother_2_slam_burst(float *param_1) -{ - uint32_t rngResult; - Entity *spawnedEffect; - uint32_t uVar1; - int in_ECX; - int iVar2; - int iVar3; - float fVar4; - Vector local_3c; - Vector local_34; - Vector slamPos; - float local_24; - float local_20; - float local_1c; - float local_18; - float backDirX; - Manager *manager; - - Room::GetClampedPositionImpl - (g_game->_room,&slamPos,GHIDRA_CAST((in_ECX + 0x33c)),10.0,10.0,10.0,10.0); - manager = g_manager; - local_18 = 1.079e-43; - seed_fart_sound_override(GHIDRA_CAST(&local_18)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_18),1.0,2,0,1.0,0.0); - Game::ShakeScreen(g_game,0xc); - rngResult = Random(); - spawnedEffect = Game::Spawn(g_game,1000,2,&slamPos,&g_vectorZero,GHIDRA_CAST(0x0),4,rngResult); - rngResult = Random(); - (spawnedEffect->_sprite)._rotation = - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 360.0; - rngResult = Random(); - (spawnedEffect->_posOffset).x = 0.0; - (spawnedEffect->_posOffset).y = - -10.0 - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 20.0; - (**(code **)(*GHIDRA_CAST(spawnedEffect) + 0x3c))(&g_colorGreenSplat,0xffffffff,0xff,0,1); - (**(code **)(*GHIDRA_CAST(spawnedEffect) + 0xc))(); - local_18 = param_1[1]; - backDirX = *param_1; - fVar4 = sqrtf(local_18 * local_18 + backDirX * backDirX); - if (0.0 < fVar4) { - local_18 = local_18 * (1.0 / fVar4); - backDirX = backDirX * (1.0 / fVar4); - } - backDirX = -backDirX; - local_18 = -local_18; - iVar2 = 0xc; - do { - iVar3 = iVar2; - rngResult = Random(); - local_20 = ((float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 - 0.5) * 90.0 * 0.017453292; - local_1c = cos(local_20); - fVar4 = sin(local_20); - local_20 = local_18 * local_1c + backDirX * fVar4; - local_1c = backDirX * local_1c - local_18 * fVar4; - rngResult = Random(); - local_24 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 10.0 + 20.0; - rngResult = Random(); - fVar4 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10; - local_3c.y = fVar4 * local_20 * 5.0 + slamPos.y; - local_3c.x = fVar4 * local_1c * 5.0 + slamPos.x; - rngResult = Random(); - local_34.x = local_24 * local_1c; - local_34.y = local_24 * local_20; - spawnedEffect = Game::Spawn(g_game,1000,4,&local_3c,&local_34,GHIDRA_CAST(0x0),0,rngResult); - (**(code **)(*GHIDRA_CAST(spawnedEffect) + 0xc))(); - iVar2 = iVar3 + -1; - } while (iVar2 != 0); - iVar3 = iVar3 + 0xb; - do { - rngResult = Random(); - local_24 = ((float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) - * 2.3283064e-10 - 0.5) * 90.0 * 0.017453292; - local_20 = cos(local_24); - fVar4 = sin(local_24); - local_1c = local_18 * local_20 + backDirX * fVar4; - local_20 = backDirX * local_20 - local_18 * fVar4; - rngResult = Random(); - local_24 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 25.0 + 5.0; - rngResult = Random(); - fVar4 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10; - local_34.y = fVar4 * local_1c * 5.0 + slamPos.y; - local_34.x = fVar4 * local_20 * 5.0 + slamPos.x; - rngResult = Random(); - uVar1 = Random(); - if (uVar1 % 5 == 0) { - uVar1 = 0; - } - else { - uVar1 = Random(); - uVar1 = (~uVar1 & 1) + 3; - } - local_3c.x = local_24 * local_20; - local_3c.y = local_24 * local_1c; - spawnedEffect = Game::Spawn(g_game,1000,2,&local_34,&local_3c,GHIDRA_CAST(0x0),uVar1,rngResult); - rngResult = Random(); - (spawnedEffect->_posOffset).x = 0.0; - (spawnedEffect->_posOffset).y = -10.0; - iVar2 = *GHIDRA_CAST(spawnedEffect); - (spawnedEffect->_sprite)._rotation = - (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 360.0; - (**(code **)(iVar2 + 0x3c))(&g_colorGreenSplat,0xffffffff,0xff,0,1); - (**(code **)(*GHIDRA_CAST(spawnedEffect) + 0xc))(); - iVar3 = iVar3 + -1; - } while (iVar3 != 0); - return; -} - -// 0056fcf0 -void NpcHelper::mother_render(Entity_NPC *npc, Vector *offset) -{ - ColorMod *pCVar1; - ColorMod *pCVar2; - uint64_t uVar3; - float fVar4; - float fVar5; - float fVar6; - float fVar7; - float fVar8; - float fVar9; - float fVar10; - float fVar11; - float fVar12; - float fVar13; - Entity_NPC *colorTarget; - int layerId; - float pixelScale; - double dVar14; - double dVar15; - uint32_t local_6c [26]; - float offsetY; - - if (npc->_variant == 0) { - pixelScale = g_displayPixelRatio * g_screenPointScale; - dVar14 = floor((double)(((((npc->_posOffset).x + (npc->_pos).x) - 60.0) * 0.65 + - (g_screenWidth - 338.0) * 0.5) * pixelScale + 0.5)); - dVar15 = floor((double)(((((npc->_pos).y + (npc->_posOffset).y) - 140.0) * 0.65 + - (g_screenHeight - 182.0) * 0.5) * pixelScale + 0.5)); - offsetY = offset->y; - (npc->_renderPosition).x = (float)dVar14 / pixelScale + offset->x; - (npc->_renderPosition).y = (float)dVar15 / pixelScale + offsetY; - layerId = npc->_subtype; - if ((layerId == 0) || - (colorTarget = GHIDRA_CAST(npc->_parent), GHIDRA_CAST(npc->_parent) == GHIDRA_CAST(0x0))) - { - colorTarget = npc; - } - pixelScale = (colorTarget->_sprite)._color._tint[0]; - fVar4 = (colorTarget->_sprite)._color._tint[1]; - fVar5 = (colorTarget->_sprite)._color._tint[2]; - fVar6 = (colorTarget->_sprite)._color._tint[3]; - offsetY = (colorTarget->_sprite)._color._offset[2]; - pCVar1 = &(colorTarget->_sprite)._color; - pCVar2 = &(npc->_sprite)._color; - fVar7 = (colorTarget->_sprite)._color._colorize[0]; - fVar8 = (colorTarget->_sprite)._color._colorize[1]; - fVar9 = (colorTarget->_sprite)._color._colorize[2]; - fVar10 = (colorTarget->_sprite)._color._colorize[3]; - uVar3 = *GHIDRA_CAST((colorTarget->_sprite)._color._offset); - if (pCVar1 != pCVar2) { - fVar11 = (npc->_sprite)._color._tint[1]; - fVar12 = (npc->_sprite)._color._tint[2]; - fVar13 = (npc->_sprite)._color._tint[3]; - pCVar1->_tint[0] = pCVar2->_tint[0]; - (colorTarget->_sprite)._color._tint[1] = fVar11; - (colorTarget->_sprite)._color._tint[2] = fVar12; - (colorTarget->_sprite)._color._tint[3] = fVar13; - fVar11 = (npc->_sprite)._color._colorize[1]; - fVar12 = (npc->_sprite)._color._colorize[2]; - fVar13 = (npc->_sprite)._color._colorize[3]; - (colorTarget->_sprite)._color._colorize[0] = (npc->_sprite)._color._colorize[0]; - (colorTarget->_sprite)._color._colorize[1] = fVar11; - (colorTarget->_sprite)._color._colorize[2] = fVar12; - (colorTarget->_sprite)._color._colorize[3] = fVar13; - *GHIDRA_CAST((colorTarget->_sprite)._color._offset) = - *GHIDRA_CAST((npc->_sprite)._color._offset); - (colorTarget->_sprite)._color._offset[2] = (npc->_sprite)._color._offset[2]; - layerId = npc->_subtype; - } - (GHIDRA_CAST((GHIDRA_CAST(&colorTarget->_sprite))))->Sprite::RenderLayer(layerId,&npc->_renderPosition,&g_vectorZero, - &g_vectorZero); - if (pCVar1 != GHIDRA_CAST(local_6c)) { - pCVar1->_tint[0] = pixelScale; - (colorTarget->_sprite)._color._tint[1] = fVar4; - (colorTarget->_sprite)._color._tint[2] = fVar5; - (colorTarget->_sprite)._color._tint[3] = fVar6; - (colorTarget->_sprite)._color._colorize[0] = fVar7; - (colorTarget->_sprite)._color._colorize[1] = fVar8; - (colorTarget->_sprite)._color._colorize[2] = fVar9; - (colorTarget->_sprite)._color._colorize[3] = fVar10; - *GHIDRA_CAST((colorTarget->_sprite)._color._offset) = uVar3; - (colorTarget->_sprite)._color._offset[2] = offsetY; - return; - } - } - else { - Entity::Render(GHIDRA_CAST(npc),offset); - } - return; -} - // 00572a70 Entity * NpcHelper::clutch_find_farthest_orbital(Entity_NPC *clutch, int unused) { @@ -5926,399 +4583,6 @@ void NpcHelper::beast_soul_render(Entity_NPC *npc, Vector *offset) return; } -// 0059e2a0 -void NpcHelper::UltraGreed_Heal(Entity_NPC *npc, int amount) -{ - int healStacks; - float newHealth; - float fVar1; - uint32_t healColor; - uint32_t uStack_30; - uint32_t uStack_2c; - uint32_t uStack_28; - uint32_t local_24; - uint32_t uStack_20; - uint32_t uStack_1c; - uint32_t uStack_18; - float flashIntensity; - float local_10; - float local_c; - uint32_t local_8; - - local_8 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 4U; - npc->_i2 = npc->_i2 + amount; - healStacks = npc->_i2; - if (0x19 < healStacks) { - healStacks = 0x19; - } - npc->_i2 = healStacks; - fVar1 = npc->_maxHitPoints; - newHealth = fVar1 * 0.00125 * (float)amount + npc->_health; - npc->_health = newHealth; - if (fVar1 < newHealth) { - npc->_health = fVar1; - } - fVar1 = (float)amount / 3.0; - healStacks = amount * 4; - if (0xf < healStacks) { - healStacks = 0xf; - } - flashIntensity = 1.0; - if (fVar1 <= 1.0) { - flashIntensity = fVar1; - } - healColor = 0x3f800000; - uStack_30 = 0x3f800000; - uStack_2c = 0x3f800000; - uStack_28 = 0x3f800000; - local_24 = 0; - uStack_20 = 0; - uStack_1c = 0; - uStack_18 = 0; - local_10 = flashIntensity * 0.84; - local_c = flashIntensity * 0.0; - (**(code **)(*GHIDRA_CAST(npc) + 0x3c))(&healColor,healStacks,0xff,1,1); - return; -} - -// 0059e630 -Entity_NPC * NpcHelper::UltraDoor_Opposite(Entity_NPC *door, EntityList_EL doors) -{ - uint32_t uVar1; - Entity_NPC *oppositeDoor; - uint64_t *heapAllocatedBytes; - int oppositeSlot; - uint32_t entityIdx; - int oppositeSlots [9]; - void *local_10; - uint8_t *puStack_c; - int local_8; - uint64_t oldAllocatedBytes; - - puStack_c = &LAB_00af57bd; - local_10 = ExceptionList; - uVar1 = __security_cookie ^ GHIDRA_UINT((oppositeSlots + 0xc)); - ExceptionList = &local_10; - local_8 = 0; - oppositeSlots[8] = uVar1; - if (door != GHIDRA_CAST(0x0)) { - oppositeSlot = -1; - oppositeSlots[0] = 2; - oppositeSlots[1] = 3; - oppositeSlots[2] = 0; - oppositeSlots[3] = 1; - oppositeSlots[4] = 6; - oppositeSlots[5] = 7; - oppositeSlots[6] = 4; - oppositeSlots[7] = 5; - if (GHIDRA_UINT(door->_i1) < 8) { - oppositeSlot = oppositeSlots[door->_i1]; - } - entityIdx = 0; - if (doors._size != 0) { - do { - oppositeDoor = (Entity_NPC *) - __RTDynamicCast(*GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(doors)) + 0x4))) + entityIdx * 4)),0, - &IsaacRepentancePlus::Entity::RTTI_Type_Descriptor, - &IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0, - uVar1); - if ((oppositeDoor != GHIDRA_CAST(0x0)) && (oppositeDoor->_i1 == oppositeSlot)) - goto LAB_0059e6d2; - entityIdx = entityIdx + 1; - } while (entityIdx < GHIDRA_UINT(doors._size)); - } - } - oppositeDoor = GHIDRA_CAST(0x0); -LAB_0059e6d2: - if ((*GHIDRA_CAST((GHIDRA_CAST(&(doors)) + 0x0))) == '\0') { - if (g_mainHeap == (void *)0x0) { - heapAllocatedBytes = &g_allocatedBytesNoHeap; - } - else { - heapAllocatedBytes = GHIDRA_CAST((GHIDRA_INT(g_mainHeap) + 0x30)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(doors)) + 0x4))) != 0) { - uVar1 = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(doors)) + 0x4))) + -4)); - oldAllocatedBytes = *heapAllocatedBytes; - *GHIDRA_CAST(heapAllocatedBytes) = GHIDRA_UINT(*heapAllocatedBytes) - uVar1; - *GHIDRA_CAST((GHIDRA_CAST(heapAllocatedBytes) + 4)) = - *GHIDRA_CAST((GHIDRA_CAST(heapAllocatedBytes) + 4)) - GHIDRA_UINT((GHIDRA_UINT(oldAllocatedBytes) < uVar1)); - free((void *)((*GHIDRA_CAST((GHIDRA_CAST(&(doors)) + 0x4))) + -4)); - } - } - ExceptionList = local_10; - return oppositeDoor; -} - -// 0059e730 -void NpcHelper::UltraGreed_Smash(Entity_NPC *npc, Vector position) -{ - int iVar1; - RNG rng; - EntityList_EL doors; - EntityList_EL doors_00; - EntityList_EL doors_01; - uint64_t qVar2; - uint32_t uVar3; - Entity_NPC *oppositeDoor; - Entity_NPC *randomDoor; - uint32_t outcomeCount; - Game *game; - uint64_t *allocCounter; - uint32_t uVar4; - EntityList_EL ultraDoors; - void *picker; - uint32_t *pickerEnd; - uint32_t *pickerCapacity; - Entity_NPC *boss; - uint32_t pickSeed; - uint64_t uStack_8c; - Entity_NPC *pEStack_84; - float local_80; - ColorMod particleColor; - ColorMod explosionColor; - uint32_t local_24; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - float local_14; - Manager *manager; - int *outcomeWeight; - void *room; - - puStack_20 = GHIDRA_CAST((&explosionColor)[1]._offset); - local_14 = -NAN; - puStack_18 = &LAB_00af580b; - local_1c = ExceptionList; - local_24 = __security_cookie ^ GHIDRA_UINT(((&explosionColor)[1]._colorize + 1)); - ExceptionList = &local_1c; - boss = npc; - Entity_NPC::CreateGoldParticles(npc,0x1e); - manager = g_manager; - local_80 = 1.93379e-43; - seed_fart_sound_override(GHIDRA_CAST(&local_80)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_80),1.0,2,0,1.0,0.0); - uVar3 = Random(); - manager = g_manager; - local_80 = 6.72623e-44; - pEStack_84 = (Entity_NPC *) - ((float)((double)GHIDRA_INT(uVar3) + __uint_to_double_fixup[-(GHIDRA_INT(uVar3) >> 0x1f)]) * - 2.3283064e-10 * 0.2 + 0.9); - seed_fart_sound_override(GHIDRA_CAST(&local_80)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_80),1.0,2,0,(float)pEStack_84,0.0); - game = g_game; - pEStack_84 = GHIDRA_CAST(position.x); - room = g_game->_room; - local_80 = position.y; - *GHIDRA_CAST((GHIDRA_CAST(room) + 0x70fc)) = *GHIDRA_CAST((GHIDRA_CAST(room) + 0x70fc)) + 1; - uVar3 = *GHIDRA_CAST((GHIDRA_CAST(room) + 0x70fc)) & 0x80000001; - if (GHIDRA_INT(uVar3) < 0) { - uVar3 = (uVar3 - 1 | 0xfffffffe) + 1; - } - if (1 < uVar3) { - KAGE_LogMessage(0x10,GHIDRA_CAST("Shockwave id is too large!")); - game = g_game; - } - randomDoor = boss; - iVar1 = uVar3 + 0x407; - *GHIDRA_CAST((GHIDRA_CAST(room) + iVar1 * 0x1c)) = pEStack_84; - *GHIDRA_CAST((GHIDRA_CAST(room) + iVar1 * 0x1c + 4)) = local_80; - *GHIDRA_CAST((GHIDRA_CAST(room) + iVar1 * 0x1c + 8)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(room) + iVar1 * 0x1c + 0xc)) = 0x3ccccccd; - *GHIDRA_CAST((GHIDRA_CAST(room) + iVar1 * 0x1c + 0x10)) = 0x3ccccccd; - *GHIDRA_CAST((GHIDRA_CAST(room) + iVar1 * 0x1c + 0x14)) = 0; - *GHIDRA_CAST((GHIDRA_CAST(room) + iVar1 * 0x1c + 0x18)) = 0x19; - explosionColor._offset[0] = 0.5; - explosionColor._offset[1] = 0.25; - explosionColor._colorize[0] = 0.0; - explosionColor._colorize[1] = 0.0; - explosionColor._colorize[2] = 0.0; - explosionColor._colorize[3] = 0.0; - explosionColor._offset[2] = 0.0; - explosionColor._tint[0] = 1.0; - explosionColor._tint[1] = 1.0; - explosionColor._tint[2] = 1.0; - explosionColor._tint[3] = 1.0; - Game::BombExplosionEffects - (game,&position,60.0,(BitSet128)ZEXT816(0),&explosionColor,GHIDRA_CAST(boss),1.8,1,4,0); - particleColor._tint[0] = 1.0; - particleColor._tint[1] = 1.0; - particleColor._tint[2] = 1.0; - particleColor._tint[3] = 1.0; - particleColor._offset[0] = 0.0; - particleColor._colorize[0] = 0.0; - particleColor._colorize[1] = 0.0; - particleColor._colorize[2] = 0.0; - particleColor._colorize[3] = 0.0; - particleColor._offset[1] = 0.0; - particleColor._offset[2] = 0.0; - Game::SpawnParticles(g_game,&position,0x5f,0xf,5.0,&particleColor,100000.0,0); - EntityList::QuerySublist(GHIDRA_CAST((GHIDRA_INT(g_game->_room) + 0x1218)),&ultraDoors,0x126,-1,-1,1,0); - local_14 = 0.0; - if ((randomDoor->_state == 700) || (randomDoor->_state == 0x10)) { - picker = (void *)0x0; - pickerEnd = GHIDRA_CAST(0x0); - pickerCapacity = GHIDRA_CAST(0x0); - local_14 = 1.4013e-45; - uStack_8c = uStack_8c & 0xffffffff; - pEStack_84 = GHIDRA_CAST(0x64); - msvc::vector<8byte>::_Emplace_reallocate(0,GHIDRA_INT(&uStack_8c) + 4); - uVar3 = 0; - outcomeCount = GHIDRA_INT(pickerEnd) - GHIDRA_INT(picker) >> 3; - if (outcomeCount != 0) { - do { - if (*GHIDRA_CAST((GHIDRA_CAST(picker) + uVar3 * 8)) == 1) { - outcomeWeight = GHIDRA_CAST((GHIDRA_INT(picker) + uVar3 * 8 + 4)); - *outcomeWeight = *outcomeWeight + 0x46; - if (*outcomeWeight < 0) { - *GHIDRA_CAST((GHIDRA_CAST(picker) + uVar3 * 8 + 4)) = 0; - } - goto LAB_0059eaaa; - } - uVar3 = uVar3 + 1; - } while (uVar3 < outcomeCount); - } - uStack_8c = CONCAT44(1,(uint32_t)uStack_8c); - pEStack_84 = GHIDRA_CAST(0x46); - if (pickerEnd == pickerCapacity) { - msvc::vector<8byte>::_Emplace_reallocate(pickerEnd,GHIDRA_INT(&uStack_8c) + 4); - } - else { - *pickerEnd = 1; - pickerEnd[1] = 0x46; - pickerEnd = pickerEnd + 2; - } -LAB_0059eaaa: - pickSeed = Random(); - pickSeed = pickSeed | 1; - uStack_8c = 0x900000005; - pEStack_84 = GHIDRA_CAST(&DAT_00000007); - rng._shift1 = 5; - rng._seed = pickSeed; - rng._shift2 = 9; - rng._shift3 = 7; - uVar3 = WeightedOutcomePicker::PickOutcome(GHIDRA_CAST(&picker),rng); - if ((uVar3 == 0) || (boss->_state == 0x10)) { - Game::ShakeScreen(g_game,0xd); - if ((float)ultraDoors._size != 0.0) { - uVar3 = Random(); - local_80 = (float)(uVar3 % GHIDRA_UINT(ultraDoors._size) + 1); - if (0 < GHIDRA_INT(local_80)) { - do { - uVar3 = Random(); - uVar4 = 0; - randomDoor = (Entity_NPC *) - __RTDynamicCast(*(uint32_t *) - ((*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x4))) + (uVar3 % GHIDRA_UINT(ultraDoors._size)) * 4), - 0,&IsaacRepentancePlus::Entity::RTTI_Type_Descriptor, - &IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0); - (*GHIDRA_CAST((GHIDRA_CAST(&(doors_00)) + 0x1))) = (int3)(GHIDRA_UINT(uVar4) >> 8); - (*GHIDRA_CAST((GHIDRA_CAST(&(doors_00)) + 0x0))) = 1; - (*GHIDRA_CAST((GHIDRA_CAST(&(doors_00)) + 0x4))) = (*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x4))); - doors_00._capacity = ultraDoors._capacity; - doors_00._size = ultraDoors._size; - oppositeDoor = UltraDoor_Opposite(randomDoor,doors_00); - if ((randomDoor != GHIDRA_CAST(0x0)) && (randomDoor->_state == 3)) { - randomDoor->_state = 8; - } - if ((oppositeDoor != GHIDRA_CAST(0x0)) && (oppositeDoor->_state == 3)) { - oppositeDoor->_state = 9; - } - local_80 = (float)(GHIDRA_INT(local_80) + -1); - } while (local_80 != 0.0); - } - } - } - else if ((uVar3 == 1) && (Game::ShakeScreen(g_game,0x12), (float)ultraDoors._size != 0.0)) { - local_80 = (float)ultraDoors._size; - do { - if ((float)ultraDoors._size == 0.0) { - uVar3 = 0; - } - else { - uVar3 = Random(); - uVar3 = uVar3 % GHIDRA_UINT(ultraDoors._size); - } - uVar4 = 0; - randomDoor = (Entity_NPC *) - __RTDynamicCast(*GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x4))) + uVar3 * 4)),0, - &IsaacRepentancePlus::Entity::RTTI_Type_Descriptor, - &IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0); - (*GHIDRA_CAST((GHIDRA_CAST(&(doors)) + 0x1))) = (int3)(GHIDRA_UINT(uVar4) >> 8); - (*GHIDRA_CAST((GHIDRA_CAST(&(doors)) + 0x0))) = 1; - (*GHIDRA_CAST((GHIDRA_CAST(&(doors)) + 0x4))) = (*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x4))); - doors._capacity = ultraDoors._capacity; - doors._size = ultraDoors._size; - oppositeDoor = UltraDoor_Opposite(randomDoor,doors); - if ((randomDoor != GHIDRA_CAST(0x0)) && (randomDoor->_state == 3)) { - randomDoor->_state = 8; - } - if ((oppositeDoor != GHIDRA_CAST(0x0)) && (oppositeDoor->_state == 3)) { - oppositeDoor->_state = 9; - } - local_80 = (float)(GHIDRA_INT(local_80) - 1); - } while (local_80 != 0.0); - local_80 = 0.0; - } - local_14 = (float)(GHIDRA_UINT(local_14) & 0xffffff00); - if (picker != (void *)0x0) { - uVar3 = (GHIDRA_INT(pickerCapacity) - GHIDRA_INT(picker) >> 3) * 8; - room = picker; - if (0xfff < uVar3) { - room = *(void **)(GHIDRA_CAST(picker) + -4); - uVar3 = uVar3 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(picker) + (-4 - GHIDRA_INT(room))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(room,uVar3); - } - } - if ((boss->_state == 0x2c6) && (Game::ShakeScreen(g_game,10), (float)ultraDoors._size != 0.0)) { - uVar3 = Random(); - uVar4 = 0; - randomDoor = (Entity_NPC *) - __RTDynamicCast(*(uint32_t *) - ((*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x4))) + (uVar3 % GHIDRA_UINT(ultraDoors._size)) * 4),0, - &IsaacRepentancePlus::Entity::RTTI_Type_Descriptor, - &IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0); - (*GHIDRA_CAST((GHIDRA_CAST(&(doors_01)) + 0x1))) = (int3)(GHIDRA_UINT(uVar4) >> 8); - (*GHIDRA_CAST((GHIDRA_CAST(&(doors_01)) + 0x0))) = 1; - (*GHIDRA_CAST((GHIDRA_CAST(&(doors_01)) + 0x4))) = (*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x4))); - doors_01._capacity = ultraDoors._capacity; - doors_01._size = ultraDoors._size; - pEStack_84 = randomDoor; - oppositeDoor = UltraDoor_Opposite(randomDoor,doors_01); - if (randomDoor != GHIDRA_CAST(0x0)) { - randomDoor->_state = 8; - randomDoor->_stateFrame = 0; - } - if (oppositeDoor != GHIDRA_CAST(0x0)) { - oppositeDoor->_state = 9; - oppositeDoor->_stateFrame = 0; - } - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x0))) == '\0') { - if (g_mainHeap == (void *)0x0) { - allocCounter = &g_allocatedBytesNoHeap; - } - else { - allocCounter = GHIDRA_CAST((GHIDRA_INT(g_mainHeap) + 0x30)); - } - if ((*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x4))) != 0) { - uVar3 = *GHIDRA_CAST(((*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x4))) + -4)); - qVar2 = *allocCounter; - *GHIDRA_CAST(allocCounter) = GHIDRA_UINT(*allocCounter) - uVar3; - *GHIDRA_CAST((GHIDRA_CAST(allocCounter) + 4)) = - *GHIDRA_CAST((GHIDRA_CAST(allocCounter) + 4)) - GHIDRA_UINT((GHIDRA_UINT(qVar2) < uVar3)); - free((void *)((*GHIDRA_CAST((GHIDRA_CAST(&(ultraDoors)) + 0x4))) + -4)); - } - } - ExceptionList = local_1c; - return; -} - // 005a7010 void NpcHelper::visage_spawn_particles(Vector *position, Vector *direction) { @@ -7036,302 +5300,3 @@ LAB_005adfbb: (npc->_velocity).y = g_vectorZero.y; return 1; } - -// 006d0ec0 -void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) -{ - uint8_t bVar1; - EntityRef *damageSource; - uint8_t *curAnimName; - uint32_t uVar2; - LayerState *layer; - int iVar3; - uint8_t *wantedAnimName; - char *wantedAnimNameStr; - float *damageEvent; - bool isLess; - float fVar4; - float fVar5; - EntityRef damageSourceRef; - float local_10; - float local_c; - char isIgnoreDamage; - uint8_t *animData; - uint32_t damageEventsBegin; - uint64_t flags; - Manager *manager; - ANM2 *sprite; - - if ((npc->_variant == 0xc) || (npc->_variant == 0xd)) { - isIgnoreDamage = '\x01'; - } - else { - isIgnoreDamage = '\0'; - if ((0.2 < *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x7240))) && - (bVar1 = Entity::IsFrame(GHIDRA_CAST(npc),5,npc->_index), bVar1 != 0)) { - damageSource = EntityRef::EntityRef(&damageSourceRef); - (**(code **)(*GHIDRA_CAST(npc) + 0x20))(0x3f800000,0,0,damageSource,0x1e); - } - } - iVar3 = npc->_state; - if (iVar3 != 0) { - if (iVar3 != 3) { - if (iVar3 == 0x10) { - fVar4 = npc->_health - 1.0; - if (fVar4 <= 0.01) { - fVar4 = 0.01; - } - npc->_health = fVar4; - if (((npc->_sprite)._animState._animData == (void *)0x0) || - ((npc->_sprite)._animState._isPlaying == 0)) { - (**(code **)(*GHIDRA_CAST(npc) + 0x28))(); - } - } - goto LAB_006d1556; - } - sprite = &npc->_sprite; - if (((npc->_sprite)._animState._animData == (void *)0x0) || - ((npc->_sprite)._animState._isPlaying == 0)) { - animData = (npc->_sprite)._animState._animData; - if (animData != GHIDRA_CAST(0x0)) { - curAnimName = animData; - if (0xf < *GHIDRA_CAST((animData + 0x14))) { - curAnimName = *GHIDRA_CAST(animData); - } - wantedAnimName = s_Idle; - do { - bVar1 = *curAnimName; - isLess = bVar1 < *wantedAnimName; - if (bVar1 != *wantedAnimName) { -LAB_006d0fd0: - uVar2 = -GHIDRA_UINT(isLess) | 1; - goto LAB_006d0fd5; - } - if (bVar1 == 0) break; - bVar1 = curAnimName[1]; - isLess = bVar1 < wantedAnimName[1]; - if (bVar1 != wantedAnimName[1]) goto LAB_006d0fd0; - curAnimName = curAnimName + 2; - wantedAnimName = wantedAnimName + 2; - } while (bVar1 != 0); - uVar2 = 0; -LAB_006d0fd5: - if ((uVar2 == 0) && ((animData[0x34] == 0 || ((npc->_sprite)._animState._isPlaying != 0)))) - goto LAB_006d1001; - } - bVar1 = ANM2::SetAnimation(sprite,s_Idle,1); - if (bVar1 != 0) { - AnimationState::Rewind(&(npc->_sprite)._animState); - (npc->_sprite)._animState._isPlaying = 1; - } - } -LAB_006d1001: - fVar4 = (npc->_targetPosition).x; - if ((fVar4 == g_vectorZero.x) && ((npc->_targetPosition).y == g_vectorZero.y)) { - if (npc->_spawnerType != 0x3b7) { - fVar4 = npc->_friction * 0.95; - goto LAB_006d107e; - } - } - else { - fVar5 = (npc->_pos).x; - (npc->_velocity).y = (npc->_targetPosition).y - (npc->_pos).y; - (npc->_velocity).x = fVar4 - fVar5; - fVar4 = npc->_friction * 0.6; -LAB_006d107e: - npc->_friction = fVar4; - } - if (npc->_variant == 0xc) { - fVar4 = npc->_speedMultiplier + (npc->_v1).x; - (npc->_v1).x = fVar4; - if (90.0 < fVar4) { - fVar5 = npc->_health - 1.0; - (npc->_v1).x = fVar4 - 90.0; - if (fVar5 <= 1.0) { - fVar5 = 1.0; - } - npc->_health = fVar5; - local_c = (fVar5 * 0.9) / npc->_maxHitPoints + 0.1; - local_10 = local_c * g_vectorOne.y; - local_c = local_c * g_vectorOne.x; - layer = ANM2::GetLayer(sprite,GHIDRA_CAST(0x0)); - (layer->_size).x = local_c; - (layer->_size).y = local_10; - if (npc->_health <= 1.5 && npc->_health != 1.5) goto LAB_006d114a; - } - } - else if (npc->_variant != 0xd) { - iVar3 = 300; - if (npc->_entityGridCollisionClass != 0) { - iVar3 = 0xb4; - } - if (iVar3 < g_game->_frameCount - npc->_spawnFrame) { -LAB_006d114a: - npc->_state = 0x10; - npc->_entityCollisionClass = 0; - npc->_entityGridCollisionClass = 0; - ANM2::Play(sprite,GHIDRA_CAST("Disappear"),0); - goto LAB_006d1556; - } - } - if (((npc->_spawnerType == 0x3b7) && - (iVar3 = Entity::GetIntervalTicks(GHIDRA_CAST(npc),30.0,0.0), iVar3 != 0)) && - (uVar2 = Random(), (uVar2 & 3) == 0)) { - damageSource = EntityRef::EntityRef(&damageSourceRef); - (**(code **)(*GHIDRA_CAST(npc) + 0x20))(0x3f800000,0x20000,0,damageSource,0x1e); - } - if (npc->_pendingDamage <= 0.0) goto LAB_006d1556; - if ((npc->_pendingDamageFlags & 4) == 0) { - if (isIgnoreDamage == '\0') { - damageEvent = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((npc)) + 0x8)))); - if (damageEvent == *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((npc)) + 0xc))))) { - fVar4 = npc->_health; - } - else { - do { - if (10.0 < *damageEvent) { - uVar2 = Random(); - if (uVar2 % 3 == 0) { - fVar4 = 3.0; - } - else { - fVar4 = 2.0; - } -LAB_006d1299: - fVar4 = npc->_health - fVar4; - npc->_health = fVar4; - } - else { - if (0.0 < *damageEvent) { - uVar2 = Random(); - if (uVar2 % 3 == 0) { - fVar4 = 2.0; - } - else { - fVar4 = 1.0; - } - goto LAB_006d1299; - } - fVar4 = npc->_health; - } - damageEvent = damageEvent + 0xe; - } while (damageEvent != *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((npc)) + 0xc))))); - } - if (fVar4 < 1.0) goto LAB_006d12d6; - } - } - else { -LAB_006d12d6: - npc->_health = 1.0; - } - local_10 = (npc->_health * 0.9) / npc->_maxHitPoints + 0.1; - local_c = local_10 * g_vectorOne.y; - local_10 = local_10 * g_vectorOne.x; - layer = ANM2::GetLayer(&npc->_sprite,GHIDRA_CAST(0x0)); - (layer->_size).x = local_10; - (layer->_size).y = local_c; - if (1.5 < npc->_health || npc->_health == 1.5) goto LAB_006d1556; - npc->_state = 0x10; - npc->_entityCollisionClass = 0; - npc->_entityGridCollisionClass = 0; - animData = (npc->_sprite)._animState._animData; - if (animData == GHIDRA_CAST(0x0)) { -LAB_006d13b6: - bVar1 = ANM2::SetAnimation(&npc->_sprite,GHIDRA_CAST("Disappear"),1); - if (bVar1 != 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 = "Disappear"; - do { - bVar1 = *curAnimName; - isLess = bVar1 < (uint8_t)*wantedAnimNameStr; - if (bVar1 != *wantedAnimNameStr) { -LAB_006d13a3: - uVar2 = -GHIDRA_UINT(isLess) | 1; - goto LAB_006d13a8; - } - if (bVar1 == 0) break; - bVar1 = curAnimName[1]; - isLess = bVar1 < (uint8_t)wantedAnimNameStr[1]; - if (bVar1 != wantedAnimNameStr[1]) goto LAB_006d13a3; - curAnimName = curAnimName + 2; - wantedAnimNameStr = wantedAnimNameStr + 2; - } while (bVar1 != 0); - uVar2 = 0; -LAB_006d13a8: - if ((uVar2 != 0) || ((animData[0x34] != 0 && ((npc->_sprite)._animState._isPlaying == 0)))) - goto LAB_006d13b6; - } - manager = g_manager; - if ((npc->_pendingDamageFlags & 0x20000) == 0) { - local_c = 3.65739e-43; - seed_fart_sound_override(GHIDRA_CAST(&local_c)); - (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_c),0.85,2,0,1.0,0.0); - } - goto LAB_006d1556; - } - fVar4 = npc->_health; - flags = npc->_flags; - *GHIDRA_CAST((GHIDRA_INT(&npc->_flags) + 4)) = *GHIDRA_CAST((GHIDRA_INT(&npc->_flags) + 4)); - *GHIDRA_CAST(&npc->_flags) = GHIDRA_UINT(flags) & 0xfffffffb | 0x42050011; - local_10 = (fVar4 * 0.9) / npc->_maxHitPoints + 0.1; - local_c = local_10 * g_vectorOne.y; - local_10 = local_10 * g_vectorOne.x; - layer = ANM2::GetLayer(&npc->_sprite,GHIDRA_CAST(0x0)); - (layer->_size).x = local_10; - (layer->_size).y = local_c; - animData = (npc->_sprite)._animState._animData; - if (animData == GHIDRA_CAST(0x0)) { -LAB_006d14f6: - bVar1 = ANM2::SetAnimation(&npc->_sprite,GHIDRA_CAST("Appear"),1); - if (bVar1 != 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 = "Appear"; - do { - bVar1 = *curAnimName; - isLess = bVar1 < (uint8_t)*wantedAnimNameStr; - if (bVar1 != *wantedAnimNameStr) { -LAB_006d14e0: - uVar2 = -GHIDRA_UINT(isLess) | 1; - goto LAB_006d14e5; - } - if (bVar1 == 0) break; - bVar1 = curAnimName[1]; - isLess = bVar1 < (uint8_t)wantedAnimNameStr[1]; - if (bVar1 != wantedAnimNameStr[1]) goto LAB_006d14e0; - curAnimName = curAnimName + 2; - wantedAnimNameStr = wantedAnimNameStr + 2; - } while (bVar1 != 0); - uVar2 = 0; -LAB_006d14e5: - if ((uVar2 != 0) || ((animData[0x34] != 0 && ((npc->_sprite)._animState._isPlaying == 0)))) - goto LAB_006d14f6; - } - npc->_state = 3; - if (((npc->_targetPosition).x != g_vectorZero.x) || ((npc->_targetPosition).y != g_vectorZero.y)) - { - npc->_entityGridCollisionClass = 0; - } -LAB_006d1556: - damageEventsBegin = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((npc)) + 0x8)))); - npc->_pendingDamage = 0.0; - *GHIDRA_CAST(&npc->_pendingDamageFlags) = 0; - *GHIDRA_CAST((GHIDRA_INT(&npc->_pendingDamageFlags) + 4)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((npc)) + 0xc)))) = damageEventsBegin; - return; -} diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index b5e7c60..cf78851 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -9213,8 +9213,6 @@ 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"); } -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::hornfel_spawn_doors() { generated_stub("NpcHelper::hornfel_spawn_doors 004b70c0"); } void NpcHelper::hornfel_remove_doors() { generated_stub("NpcHelper::hornfel_remove_doors 004b78f0"); } void NpcHelper::hornfel_charge(Entity_NPC *npc) { generated_stub("NpcHelper::hornfel_charge 004b7e30"); } @@ -9229,24 +9227,11 @@ int NpcHelper::hornfel_next_rail_index(Entity_NPC *npc) { generated_stub("NpcHel void NpcHelper::hornfel_set_anim(Entity_NPC *npc, int stateFrame) { generated_stub("NpcHelper::hornfel_set_anim 004bb830"); } uint8_t NpcHelper::hornfel_claim_target(Entity_NPC *npc, Entity *target) { generated_stub("NpcHelper::hornfel_claim_target 004bb920"); } void NpcHelper::hornfel_room_controller(Entity_Effect *effect) { generated_stub("NpcHelper::hornfel_room_controller 004bc460"); } -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"); } -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"); } -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"); } 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"); } uint8_t NpcHelper::polty_is_pot_cell(Entity_NPC *npc, int gridIndex) { generated_stub("NpcHelper::polty_is_pot_cell 0055d180"); } void NpcHelper::mother_set_collision_class(Entity_NPC *npc, int collisionClass) { generated_stub("NpcHelper::mother_set_collision_class 005688c0"); } -void NpcHelper::mother_spawn_parts() { generated_stub("NpcHelper::mother_spawn_parts 00568cc0"); } -void NpcHelper::mother_2_slam_burst(float *param_1) { generated_stub("NpcHelper::mother_2_slam_burst 0056c800"); } -void NpcHelper::mother_render(Entity_NPC *npc, Vector *offset) { generated_stub("NpcHelper::mother_render 0056fcf0"); } Entity * NpcHelper::clutch_find_farthest_orbital(Entity_NPC *clutch, int unused) { generated_stub("NpcHelper::clutch_find_farthest_orbital 00572a70"); } void NpcHelper::clutch_spawn_fire(Entity_NPC *npc, Entity *target) { generated_stub("NpcHelper::clutch_spawn_fire 00572cc0"); } void NpcHelper::clutch_render(Entity_NPC *npc, Vector *offset) { generated_stub("NpcHelper::clutch_render 00575a10"); } @@ -9262,8 +9247,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"); } -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"); } void NpcHelper::visage_spawn_chain(Entity_NPC *npc) { generated_stub("NpcHelper::visage_spawn_chain 005a7310"); } int NpcHelper::visage_plasma_cap() { generated_stub("NpcHelper::visage_plasma_cap 005a7510"); } @@ -9272,7 +9255,6 @@ void NpcHelper::visage_pick_target_position(Entity_NPC *npc) { generated_stub("N void NpcHelper::visage_start_charge(Entity_NPC *npc) { generated_stub("NpcHelper::visage_start_charge 005ab180"); } void NpcHelper::visage_chain_solve(Entity_NPC *npc, uint8_t isInterpolate) { generated_stub("NpcHelper::visage_chain_solve 005acd30"); } uint8_t NpcHelper::visage_handle_collision(Entity_NPC *npc, Entity *collider, int unused) { generated_stub("NpcHelper::visage_handle_collision 005add40"); } -void NpcHelper::fireplace_moveable_update(Entity_NPC *npc) { generated_stub("NpcHelper::fireplace_moveable_update 006d0ec0"); } void OnlineChat::render(Vector *position, uint8_t isInputLine, uint8_t isCursorVisible, float alpha) { generated_stub("OnlineChat::render 0091d2b0"); } void OnlineChat::destructor() { generated_stub("OnlineChat::destructor 0091db20"); } void OnlineChat::render_all(Vector *pos, uint8_t isFocused) { generated_stub("OnlineChat::render_all 0091e650"); } @@ -9886,7 +9868,6 @@ uint32_t NpcAI::ENTITY_CHIMERA(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ void FUN_004a11b0() { generated_stub("FUN_004a11b0 004a11b0"); } void NpcAI::ENTITY_CLOG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CLOG 004a12f0"); } int FUN_004a2920() { generated_stub("FUN_004a2920 004a2920"); } -void NpcAI::ENTITY_COLOSTOMIA(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_COLOSTOMIA 004a3040"); } void FUN_004aaaa0(void *param_1, int param_2) { generated_stub("FUN_004aaaa0 004aaaa0"); } void FUN_004aaaf0(uint32_t *param_1, uint32_t *param_2, uint32_t *param_3) { generated_stub("FUN_004aaaf0 004aaaf0"); } uint32_t * FUN_004aac80(uint32_t *param_1) { generated_stub("FUN_004aac80 004aac80"); } @@ -9923,8 +9904,6 @@ uint32_t FUN_004b7090() { generated_stub("FUN_004b7090 004b7090"); } Entity * FUN_004bb230() { generated_stub("FUN_004bb230 004bb230"); } void NpcAI::ENTITY_HORNFEL_DOOR(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HORNFEL_DOOR 004bb9b0"); } 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 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"); } @@ -9950,23 +9929,12 @@ void FUN_004d7450(void *param_1, int param_2) { generated_stub("FUN_004d7450 004 void Catch_All_004d7683() { generated_stub("Catch_All_004d7683 004d7683"); } void FUN_004d76c0() { generated_stub("FUN_004d76c0 004d76c0"); } bool FUN_004d7760() { generated_stub("FUN_004d7760 004d7760"); } -void NpcAI::ENTITY_SMALL_MAGGOT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SMALL_MAGGOT 004d77b0"); } -void NpcAI::ENTITY_ADULT_LEECH(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ADULT_LEECH 004d9000"); } -void NpcAI::ENTITY_ROTTEN_GAPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ROTTEN_GAPER 004da590"); } -Entity_Effect * NpcAI::ENTITY_TWITCHY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_TWITCHY 004db6a0"); } -void NpcAI::ENTITY_SPIKEBALL(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SPIKEBALL 004dc490"); } void NpcAI::ENTITY_UNBORN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_UNBORN 004dca90"); } -void * NpcAI::ENTITY_GASBAG(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GASBAG 004dd7f0"); } -void NpcAI::ENTITY_EVIS(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EVIS 004df3f0"); } -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"); } void FUN_004e46b0() { generated_stub("FUN_004e46b0 004e46b0"); } void FUN_004e46c0() { generated_stub("FUN_004e46c0 004e46c0"); } bool FUN_004e47b0() { generated_stub("FUN_004e47b0 004e47b0"); } int FUN_004e4840() { generated_stub("FUN_004e4840 004e4840"); } -void NpcAI::ENTITY_CANDLER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CANDLER 004e4970"); } -uint32_t NpcAI::ENTITY_BISHOP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BISHOP 004e7ea0"); } void NpcAI::ENTITY_BALL_AND_CHAIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BALL_AND_CHAIN 004f4730"); } void FUN_004f8390() { generated_stub("FUN_004f8390 004f8390"); } void FUN_004f8460(int *param_1, int *param_2) { generated_stub("FUN_004f8460 004f8460"); } @@ -9974,45 +9942,26 @@ uint8_t str_ne(std_string *a, uint8_t *b) { generated_stub("str_ne 004f84a0"); } void rng_pair_init(void *self) { generated_stub("rng_pair_init 004f88a0"); } uint32_t FUN_004f88e0() { generated_stub("FUN_004f88e0 004f88e0"); } uint32_t FUN_004f8930() { generated_stub("FUN_004f8930 004f8930"); } -void NpcAI::ENTITY_GYRO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GYRO 004ff620"); } -void NpcAI::ENTITY_BOUNCER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BOUNCER 00501f30"); } void pow_wrapper() { generated_stub("pow_wrapper 00505b40"); } void set_byte_0x101(void *self, uint8_t value) { generated_stub("set_byte_0x101 00505b50"); } 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"); } long double FUN_00515290(Vector *param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00515290 00515290"); } -void NpcAI::ENTITY_DOPLE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DOPLE 00525650"); } -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_MR_MINE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MR_MINE 005492c0"); } int FUN_0054d1b0(int param_1) { generated_stub("FUN_0054d1b0 0054d1b0"); } void NpcAI::ENTITY_BUTT_SLICKER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BUTT_SLICKER 0054d250"); } void NpcAI::ENTITY_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_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"); } 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"); } uint32_t NpcAI::ENTITY_POLTY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_POLTY 0055d230"); } -void NpcAI::ENTITY_BLOATY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BLOATY 00563da0"); } void NpcAI::ENTITY_FISSURE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FISSURE 00564f30"); } void FUN_00565dd0(uint32_t param_1) { generated_stub("FUN_00565dd0 00565dd0"); } void FUN_00565de0(uint32_t param_1) { generated_stub("FUN_00565de0 00565de0"); } -void NpcAI::ENTITY_MOTHER_worm(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOTHER_worm 00565e00"); } -void NpcAI::ENTITY_MOTHER_ball(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOTHER_ball 00566810"); } -void NpcAI::ENTITY_MOTHER_ball_burst(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOTHER_ball_burst 00567d50"); } void FUN_00568980(char param_1) { generated_stub("FUN_00568980 00568980"); } -void NpcAI::ENTITY_MOTHER_start_transition(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOTHER_start_transition 00568a90"); } -void NpcAI::ENTITY_MOTHER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOTHER 00569170"); } -void FUN_0056c7c0() { generated_stub("FUN_0056c7c0 0056c7c0"); } -void NpcAI::ENTITY_MOTHER_2(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOTHER_2 0056cd60"); } void FUN_0056ff00(uint32_t *param_1, uint32_t param_2, uint32_t param_3) { generated_stub("FUN_0056ff00 0056ff00"); } 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"); } @@ -10029,14 +9978,6 @@ void FUN_00579700() { generated_stub("FUN_00579700 00579700"); } uint32_t FUN_00579760() { generated_stub("FUN_00579760 00579760"); } 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"); } -void NpcAI::ENTITY_ROTGUT_face(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ROTGUT_face 0057bec0"); } -void FUN_0057e3b0(float *param_1) { generated_stub("FUN_0057e3b0 0057e3b0"); } -void NpcAI::ENTITY_ROTGUT_maggot(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ROTGUT_maggot 0057e4a0"); } -void rotgut_death_spawn_effects(Entity_NPC *npc) { generated_stub("rotgut_death_spawn_effects 00581200"); } -void NpcAI::rotgut_fire_projectiles(Entity_NPC *npc) { generated_stub("NpcAI::rotgut_fire_projectiles 00581430"); } -void NpcAI::ENTITY_ROTGUT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ROTGUT 00581730"); } -void FUN_005828b0() { generated_stub("FUN_005828b0 005828b0"); } int FUN_00582a60() { generated_stub("FUN_00582a60 00582a60"); } int FUN_00582a80() { generated_stub("FUN_00582a80 00582a80"); } void FUN_00582aa0() { generated_stub("FUN_00582aa0 00582aa0"); } @@ -10067,11 +10008,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_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"); } -void NpcAI::ENTITY_ULTRA_COIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ULTRA_COIN 005a4820"); } -void NpcAI::ENTITY_ULTRA_DOOR(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ULTRA_DOOR 005a5b60"); } void FUN_005a6fb0() { generated_stub("FUN_005a6fb0 005a6fb0"); } uint8_t FUN_005a7570() { generated_stub("FUN_005a7570 005a7570"); } void NpcAI::ENTITY_VISAGE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_VISAGE 005a7b20"); } @@ -10257,12 +10193,9 @@ uint32_t FUN_0060d1e0() { generated_stub("FUN_0060d1e0 0060d1e0"); } void FUN_0060d1f0(uint32_t param_1) { generated_stub("FUN_0060d1f0 0060d1f0"); } void FUN_0060d400() { generated_stub("FUN_0060d400 0060d400"); } uint32_t FUN_0060dae0() { generated_stub("FUN_0060dae0 0060dae0"); } -void FamiliarAI::gb_bug(Entity_Familiar *familiar) { generated_stub("FamiliarAI::gb_bug 00618b00"); } -void FamiliarAI::variant_53(Entity_Familiar *familiar) { generated_stub("FamiliarAI::variant_53 006196e0"); } void FamiliarAI::variant_66(Entity_Familiar *familiar) { generated_stub("FamiliarAI::variant_66 0061c3f0"); } void FamiliarAI::lil_haunt(Entity_Familiar *familiar, int unused) { generated_stub("FamiliarAI::lil_haunt 0061d030"); } void FUN_0062e0e0(int param_1) { generated_stub("FUN_0062e0e0 0062e0e0"); } -void FamiliarAI::bumbo(Entity_Familiar *familiar) { generated_stub("FamiliarAI::bumbo 0062f7f0"); } void FUN_00631a00(float *param_1, uint32_t param_2, float *param_3) { generated_stub("FUN_00631a00 00631a00"); } void FamiliarAI::lil_spewer(Entity_Familiar *familiar) { generated_stub("FamiliarAI::lil_spewer 006384a0"); } void FUN_00638e20() { generated_stub("FUN_00638e20 00638e20"); } @@ -10274,15 +10207,12 @@ void FUN_0063c060(int param_1) { generated_stub("FUN_0063c060 0063c060"); } void FamiliarHelper::fly_head_pathfind_move(Entity_Familiar *familiar) { generated_stub("FamiliarHelper::fly_head_pathfind_move 0063d570"); } void FUN_0063e180() { generated_stub("FUN_0063e180 0063e180"); } void FUN_006431b0() { generated_stub("FUN_006431b0 006431b0"); } -void FamiliarAI::variant_204(Entity_Familiar *familiar) { generated_stub("FamiliarAI::variant_204 00644780"); } void FUN_0064b6a0() { generated_stub("FUN_0064b6a0 0064b6a0"); } -int FamiliarAI::worm_friend(Entity_Familiar *familiar) { generated_stub("FamiliarAI::worm_friend 0064bfa0"); } int FUN_0064ccf0() { generated_stub("FUN_0064ccf0 0064ccf0"); } int level_get_room_neighbors(uint32_t roomIndex, uint32_t *outNeighbors) { generated_stub("level_get_room_neighbors 0064cd30"); } int star_of_bethlehem_get_target_room() { generated_stub("star_of_bethlehem_get_target_room 0064d370"); } void FUN_0064d570(uint32_t param_1) { generated_stub("FUN_0064d570 0064d570"); } void FamiliarAI::star_of_bethlehem(Entity_Familiar *familiar) { generated_stub("FamiliarAI::star_of_bethlehem 0064d5f0"); } -void FamiliarAI::vanishing_twin(Entity_Familiar *familiar) { generated_stub("FamiliarAI::vanishing_twin 00650610"); } int apply_forgotten_lullaby(void *self, int fireDelay) { generated_stub("apply_forgotten_lullaby 00651810"); } int FUN_006518d0(uint32_t param_1) { generated_stub("FUN_006518d0 006518d0"); } void * set_iterator_post_increment(void *self, void *outIterator, int unused) { generated_stub("set_iterator_post_increment 006518f0"); } @@ -10573,7 +10503,6 @@ void FUN_007008b0(int *param_1) { generated_stub("FUN_007008b0 007008b0"); } void FUN_00703140() { generated_stub("FUN_00703140 00703140"); } void FUN_00704b50() { generated_stub("FUN_00704b50 00704b50"); } void FUN_007068f0(int param_1) { generated_stub("FUN_007068f0 007068f0"); } -Entity * spawn_chain_lightning(Vector *position, BitSet128 tearFlags, Entity *spawner, float damage) { generated_stub("spawn_chain_lightning 00707e10"); } uint32_t FUN_00708350() { generated_stub("FUN_00708350 00708350"); } void FUN_00708380() { generated_stub("FUN_00708380 00708380"); } void FUN_00708430(uint32_t param_1, uint32_t param_2, int param_3) { generated_stub("FUN_00708430 00708430"); } @@ -10761,7 +10690,6 @@ 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_007c2e80() { generated_stub("FUN_007c2e80 007c2e80"); } -uint8_t FUN_007c7b10(uint32_t param_1, int param_2) { generated_stub("FUN_007c7b10 007c7b10"); } void FUN_007cb4f0() { generated_stub("FUN_007cb4f0 007cb4f0"); } 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"); } @@ -11667,7 +11595,6 @@ uint32_t FUN_00893c70(uint32_t param_1) { generated_stub("FUN_00893c70 00893c70" void FUN_00893c90(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_00893c90 00893c90"); } uint32_t * FUN_00893cf0(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_00893cf0 00893cf0"); } void FUN_00893d90() { generated_stub("FUN_00893d90 00893d90"); } -void FUN_00893df0() { generated_stub("FUN_00893df0 00893df0"); } void FUN_00893e50() { generated_stub("FUN_00893e50 00893e50"); } void FUN_00893eb0() { generated_stub("FUN_00893eb0 00893eb0"); } void FUN_00893f10() { generated_stub("FUN_00893f10 00893f10"); } @@ -12395,7 +12322,6 @@ void FUN_008ba6d0(uint32_t param_1) { generated_stub("FUN_008ba6d0 008ba6d0"); } void FUN_008ba7c0(uint32_t param_1) { generated_stub("FUN_008ba7c0 008ba7c0"); } void FUN_008ba890(uint32_t param_1) { generated_stub("FUN_008ba890 008ba890"); } int FUN_008ba900() { generated_stub("FUN_008ba900 008ba900"); } -int FUN_008ba960() { generated_stub("FUN_008ba960 008ba960"); } void FUN_008ba9c0(void *param_1) { generated_stub("FUN_008ba9c0 008ba9c0"); } int FUN_008baa50() { generated_stub("FUN_008baa50 008baa50"); } void FUN_008baab0(void *param_1) { generated_stub("FUN_008baab0 008baab0"); } diff --git a/src/ambush.cpp b/src/ambush.cpp index 214799e..d152aa7 100644 --- a/src/ambush.cpp +++ b/src/ambush.cpp @@ -24,13 +24,12 @@ // A wave's difficulty by wave (one later on Hard), the room subtypes of normal and boss waves, how often a wave is // drawn again (the special rooms' stage the second time) before none is called, and the Death Certificate's -// dimension, whose waves come from Home. A layout entry of type 999 is an effect. +// dimension, whose waves come from Home. constexpr std::array AMBUSH_WAVE_DIFFICULTY = {1, 5, 10, 15}; constexpr int WAVE_SUBTYPE_NORMAL = 10; constexpr int WAVE_SUBTYPE_BOSS = 11; constexpr int AMBUSH_WAVE_TRIES = 10; constexpr int AMBUSH_HOME_DIMENSION = 2; -constexpr uint32_t WAVE_ENTRY_EFFECT = 999; // A challenge's three waves (two for bosses), 30 frames between them, and Door Stop's multiplier that keeps the // entrance open. diff --git a/src/ambush.h b/src/ambush.h index e938419..f2eaff2 100644 --- a/src/ambush.h +++ b/src/ambush.h @@ -3,6 +3,9 @@ #include "classes.h" #include +// A wave's layout entry of this type is an effect. +constexpr uint32_t WAVE_ENTRY_EFFECT = 999; + // A boss a Boss Rush spawn slot holds (ambush.xml): its type and variant, and the segments of a segmented boss. struct BossRushEntry { diff --git a/src/anm2.cpp b/src/anm2.cpp index da488cd..bde5393 100644 --- a/src/anm2.cpp +++ b/src/anm2.cpp @@ -337,7 +337,7 @@ static AnimationFrame frame_read(object source, const std::vector file_parse(const std::string& path) array list; std::string redirected = g_manager ? g_manager->modManager.TryRedirectPath(path) : path; - if (parser.load(resource_path(redirected)).get(document) || document["anm2ed"].error()) + if (parser.load(resource_path(redirected)).get(document)) { log_print(LOG_INFO, "ERROR Could not open %s\n", path.c_str()); return nullptr; } - if (!document["spritesheets"].get(list)) + if (!document["sheets"].get(list)) for (element entry : list) { object fields; @@ -534,7 +534,7 @@ static std::shared_ptr file_parse(const std::string& path) if (file->eventNames.size() > ANM2_EVENT_LIMIT) log_print(LOG_ASSERT, "%s: invalid Event ID %d\n", path.c_str(), ANM2_EVENT_LIMIT); - file->defaultAnimation = text_get(document, "defaultAnimation"); + file->defaultAnimation = text_get(document, "default"); object animations; if (!document["animations"].get(animations)) animations_read(animations, parse, *file); return file; diff --git a/src/backdrop.cpp b/src/backdrop.cpp index 583b4f0..6f9201f 100644 --- a/src/backdrop.cpp +++ b/src/backdrop.cpp @@ -121,7 +121,6 @@ constexpr float ICON_WIDTH = 8; constexpr int GLYPH_JITTER = 3; constexpr int JACOB_ESAU_SPLIT_CONTROLS = 1; constexpr int ASCENT_START_ROOM = 84; -constexpr uint32_t ASCENT_STAGE_LAST = 6; // The control icons the start room shows, a row to each of the controls picture's nulls: moving, shooting, then the // bomb, item, card, drop and card buttons, and shooting again. @@ -802,7 +801,7 @@ static bool is_controls_room() Game& game = *g_game; int startRoom = game.startingRoomIdx; - if (game.stage - 1 < ASCENT_STAGE_LAST && (game.gameStateFlags & 1ull << GAME_STATE_BACKWARDS_PATH)) + if (game.stage - 1 < ASCENT_LAST_STAGE && (game.gameStateFlags & 1ull << GAME_STATE_BACKWARDS_PATH)) startRoom = ASCENT_START_ROOM; return game.stage == STAGE_BASEMENT_I && game.stageType != STAGETYPE_REPENTANCE && game.stageType != STAGETYPE_REPENTANCE_B && startRoom == game.currentRoomIdx; diff --git a/src/beast_arena.cpp b/src/beast_arena.cpp index 85ad859..82e0c24 100644 --- a/src/beast_arena.cpp +++ b/src/beast_arena.cpp @@ -7,8 +7,6 @@ constexpr int BACKGROUND_LAYER_COUNT = 15; constexpr int BACKGROUND_GLOW_LAYER = 8; constexpr int BACKGROUND_ADDITIVE_LAYER = 13; constexpr int BACKGROUND_MULTIPLY_LAYER = 14; -constexpr unsigned int WRAP_REPEAT = 0; -constexpr unsigned int WRAP_CLAMP = 1; constexpr float BACKGROUND_PARALLAX = 0.1f; // The background's layer blending: plain alpha, the glow over what is behind it, added light, and a darkening multiply. @@ -65,7 +63,7 @@ void BeastArena::update() scroll += scrollSpeed; scrollRendered = scroll; - for (Entity* entity : g_game->room->entityList.updateEL) + for (Entity* entity : entities_live(g_game->room->entityList.updateEL)) { if (entity->type == ENTITY_PLAYER) { diff --git a/src/bomb_explosion.cpp b/src/bomb_explosion.cpp index 4d5326a..e920a01 100644 --- a/src/bomb_explosion.cpp +++ b/src/bomb_explosion.cpp @@ -1,17 +1,27 @@ #include "entity_bomb.h" #include "boss_ai.h" +#include "deathmatch_manager.h" #include "entity_combat.h" #include "entity_effect.h" +#include "entity_knife.h" +#include "entity_laser.h" +#include "entity_pickup.h" #include "entity_player.h" +#include "entity_projectile.h" #include "entity_save_state.h" #include "entity_tear.h" +#include "fx_layers.h" #include "game.h" +#include "grid_entity.h" #include "grid_entity_lock.h" #include "log.h" #include "npc_ai.h" +#include "npc_basement.h" +#include "npc_fireplace.h" #include "room.h" #include "room_descriptor.h" #include "room_grid.h" +#include "sfx_manager.h" #include #include #include @@ -24,6 +34,19 @@ constexpr float RADIUS_MEDIUM = 90; constexpr float RADIUS_LARGE = 105; constexpr float DAMAGE_MEDIUM = 140; constexpr float DAMAGE_LARGE = 175; +constexpr float RADIUS_GIGA = 130; + +// A giga bomb's blast hits three more times two frames apart, at a third of its damage. +constexpr int GIGA_AFTERSHOCK_DELAY = 2; +constexpr int GIGA_AFTERSHOCKS = 3; +constexpr float GIGA_AFTERSHOCK_DAMAGE = 0.33f; + +// Bomber Boy's cross: the four sides 50 apart, two out along each, a quarter weaker and smaller (to 0.45 in the +// Bomberman versus mode). +constexpr std::array, 4> CROSS_SIDES = {{{-50, 0}, {50, 0}, {0, -50}, {0, 50}}}; +constexpr int CROSS_DISTANCES = 2; +constexpr float CROSS_SCALE = 0.75f; +constexpr float CROSS_SCALE_VERSUS = 0.45f; // Safety Scissors shrink the explosions no player set off: by a quarter for two, by half for more. constexpr float SCISSORS_DOUBLE_SCALE = 0.75f; @@ -53,13 +76,100 @@ constexpr float RAY_DENSITY = 8; constexpr float RAY_STEP = 20; // The entities and effects an explosion treats apart. -constexpr int CHALLENGE_BLUE_BOMBER = 23; constexpr int CARPET_BLOWN = 1000; constexpr std::array EFFECTS_BLOWN_AWAY = {21, 33, 63, 64, 158, 159}; constexpr int BOMB_EXPLOSION_EFFECT = 1; constexpr int SPECIAL_DAILY_FIREWORKS = 12; constexpr size_t SAVED_EFFECTS_MAX = 128; +// Butt Bombs heal poop enemies by a quarter, and hurt and confuse the rest for two seconds. +constexpr float BUTT_HEAL = 0.25f; +constexpr float BUTT_DAMAGE = 10; +constexpr int BUTT_CONFUSION = 60; + +// Sad Bombs fire ten shots (an enemy's eight projectiles), each 25 stronger and a third larger, Technology lasers a +// little above the floor. +constexpr int SAD_SHOTS = 10; +constexpr int SAD_ENEMY_SHOTS = 8; +constexpr float SAD_ENEMY_SPEED = 10; +constexpr float SAD_TEAR_SPEED = 10; +constexpr float SAD_TEAR_SCALE = 1.355f; +constexpr float SAD_EXTRA_DAMAGE = 25; +constexpr float SAD_LASER_LIFT = -8; + +// The Mysterious Liquid's creep: off the walls, a twentieth of the blast's reach wide. +constexpr float LIQUID_WALL_MARGIN = 15; +constexpr float LIQUID_SCALE_PER_RADIUS = 0.05f; + +// Hot Bombs' flame: its damage (less in a versus match) and five to seven seconds of burning. +constexpr float HOT_FLAME_DAMAGE = 23; +constexpr float HOT_FLAME_DAMAGE_VERSUS = 18; +constexpr int HOT_FLAME_FRAMES = 300; +constexpr int HOT_FLAME_EXTRA_FRAMES = 120; + +// Glitter Bombs: a pickup unless a roll of a hundred stays under 36 plus the bomb pickups this floor, its speed, and +// a 15 in 100 chance of charming an enemy for five seconds. +constexpr int GLITTER_PICKUP_ODDS = 36; +constexpr float GLITTER_PICKUP_SPEED = 3; +constexpr uint32_t GLITTER_CHARM_CHANCE = 15; +constexpr int GLITTER_CHARM_FRAMES = 150; + +// The creep splashes of Sticky and Blood Bombs: how many, how far the outer ones land and how large they are, the +// creep's life and look, and the size from which the burst is the big one. +constexpr int SPLASHES = 6; +constexpr float SPLASH_DISTANCE_MIN = 40; +constexpr float SPLASH_DISTANCE_RANGE = 70; +constexpr float SPLASH_SIZE_MIN = 0.2f; +constexpr float SPLASH_SIZE_RANGE = 0.5f; +constexpr int SPLASH_CREEP_FRAMES = 450; +constexpr float SPLASH_CREEP_SCALE = 3; +constexpr float SPLASH_BIG = 0.6f; + +// Scatter Bombs' poison cloud: five seconds, a sixtieth of the reach wide, and its damage. +constexpr int POISON_CLOUD_FRAMES = 150; +constexpr float POISON_CLOUD_RADIUS = 60; +constexpr float POISON_CLOUD_DAMAGE = 5; + +// Brimstone Bombs' cross: four beams for a second, their damage, the red blast's life and a brimstone bomb's shake. +constexpr int BRIMSTONE_BEAMS = 4; +constexpr int BRIMSTONE_BEAM_FRAMES = 30; +constexpr float BRIMSTONE_BEAM_DAMAGE = 8; +constexpr int BRIMSTONE_BLAST_FRAMES = 40; +constexpr int BRIMSTONE_SHAKE = 12; + +// Giga Bombs: the shake, flash and fart, the dust ring, the rings of pits, the chips and rocks each pit throws, and +// the fart heard after. +constexpr int GIGA_SHAKE = 20; +constexpr int GIGA_BLOOM_FRAMES = 6; +constexpr float GIGA_FART_RADIUS = 200; +constexpr int GIGA_DUSTS = 15; +constexpr float GIGA_DUST_SPEED_MIN = 15; +constexpr float GIGA_DUST_SPEED_RANGE = 5; +constexpr float GIGA_DUST_FLATTEN = 0.85f; +constexpr float GIGA_DUST_SPIN_MIN = 2; +constexpr float GIGA_DUST_SPIN_RANGE = 10; +constexpr float GIGA_DUST_SCALE_RANGE = 0.6f; +constexpr int GIGA_DUST_FRAMES = 40; +constexpr ColorMod GIGA_DUST_COLOR = {{0.45f, 0.45f, 0.46f, 0.75f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int GIGA_RINGS = 2; +constexpr int GIGA_CHIPS = 5; +constexpr int GIGA_CHIP_SUBTYPE = 0x20000; +constexpr float GIGA_CHIP_SPREAD = 60; +constexpr float GIGA_CHIP_SPEED_MIN = 6; +constexpr float GIGA_CHIP_SPEED_RANGE = 6; +constexpr float GIGA_CHIP_SCATTER = 20; +constexpr float GIGA_CHIP_RISE_MIN = 5; +constexpr float GIGA_CHIP_RISE_RANGE = 20; +constexpr int GIGA_ROCKS = 2; +constexpr float GIGA_ROCK_SCATTER = 25; +constexpr float GIGA_ROCK_SPEED_MIN = 12; +constexpr float GIGA_ROCK_SPEED_RANGE = 3; +constexpr float GIGA_ROCK_SCALE_MIN = 0.7f; +constexpr float GIGA_ROCK_SCALE_RANGE = 0.1f; +constexpr float GIGA_ROCK_DAMAGE = 15; +constexpr int GIGA_FART_DELAY = 30; +constexpr float GIGA_FART_VOLUME = 1.1f; + // The colors poison, butt and brimstone bombs tint the explosion with. constexpr ColorMod POISON_COLOR = {{0.4f, 0.97f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod BUTT_COLOR = {{0.4431373f, 0.2901961f, 0.06666667f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; @@ -146,12 +256,18 @@ static void explosion_entity_hurt(Explosion& explosion, Entity& entity, const Te return; } } - if (flags[TEAR_CROSS_BOMB]) reconstruction_missing("Game::BombDamage 006ff2a0: Bomber Boy's shared damage"); + // Bomber Boy's cross shares its damage: each hit the entity already took from the bomb this frame halves it. + float damage = explosion.damage; + if (flags[TEAR_CROSS_BOMB]) + { + auto isSameBomb = [&](const DamageEvent& hit) { return hit.source.entity == explosion.source; }; + damage /= (float)(1 << (std::ranges::count_if(entity.damageEvents, isSameBomb) & 31)); + } TearFlags effects = flags; effects.reset(TEAR_EXPLOSIVE); explosion.damageFlags |= tear_damage_flags_get(effects, explosion.source); - entity.TakeDamage(explosion.damage, explosion.damageFlags, EntityRef(explosion.source), HIT_COUNTDOWN); + entity.TakeDamage(damage, explosion.damageFlags, EntityRef(explosion.source), HIT_COUNTDOWN); Entity* source = explosion.source; bool isTearEffecting = flags.any() && source && !Entity::is_enemy_type(source->spawnerType); @@ -263,17 +379,429 @@ void explosion_damage(Explosion explosion) explosion_grid_break(explosion); } -// 007009a0 The tear effects an explosion spreads (Butt, Sad, Hot, Glitter, Sticky Bombs' eggs, Bob's Curse, Blood, -// Brimstone and Giga Bombs, the Mysterious Liquid). A plain explosion has none. +// The poop enemies a butt bomb heals by a quarter of their health instead of hurting. +static bool is_poop_healed(Entity& entity) +{ + int type = entity.type; + return type == ENTITY_BROWNIE || type == ENTITY_DINGLE || type == ENTITY_CLOG || + (type == ENTITY_GURGLING && entity.variant == GURGLING_TURDLING); +} + +// Whether a bomb's tear effect reaches an entity: a solid, live, mortal enemy (a player in a versus match) that can +// be targeted (the Blood Puppy and Dark Esau always can). +static bool is_bomb_reachable(Entity& entity) +{ + if (!Entity::is_enemy_type(entity.type) || entity.isInvincible || entity.isDead) return false; + if (entity.entityCollisionClass == ENTCOLL_NONE || entity.entityCollisionClass == ENTCOLL_PLAYERONLY) return false; + return !entity.HasEntityFlags(FLAG_NO_TARGET) || entity.type == ENTITY_BLOOD_PUPPY || entity.type == ENTITY_DARK_ESAU; +} + +// Butt bombs: every enemy in the room but the bomb's own spawners takes a hit and is confused, the poop enemies heal +// instead (unless a rocket, a fetus or the Beans challenge set it off), and poop clouds spread over the screen. +static void butt_bomb_spread(const Explosion& explosion) +{ + Entity* source = explosion.source; + bool isFetus = source && source->type == ENTITY_BOMB && static_cast(source)->isFetus; + bool isRocket = source && source->type == ENTITY_EFFECT && source->variant == EFFECT_ROCKET; + bool isHealing = !isRocket && !isFetus && g_game->challenge != CHALLENGE_BEANS; + for (Entity* entity : entities_live(g_game->room->GetEntities()->updateEL)) + { + if (isHealing && is_poop_healed(*entity)) + { + entity->health = std::min(entity->maxHitPoints * BUTT_HEAL + entity->health, entity->maxHitPoints); + continue; + } + if (!is_bomb_reachable(*entity) || (source && source->IsDescendantOf(entity))) continue; + + entity->TakeDamage(explosion.radiusMultiplier * BUTT_DAMAGE, 0, EntityRef(source), HIT_COUNTDOWN); + entity->AddConfusion(EntityRef(source), BUTT_CONFUSION, false); + } + g_game->room->fxLayers.AddPoopFx(COLOR_DEFAULT); +} + +// A Sad Bomb's tear from its player (with the player's tear effects) or a plain one, a third larger and 25 stronger, +// in blood with Blood Bombs. +static void sad_tear_fire(const Explosion& explosion, Entity_Player* player, Vector velocity) +{ + Entity_Tear* tear; + if (player) tear = player->FireTear({.position = explosion.position, .velocity = velocity}, TEAR_FIRE_NO_EVIL_EYE | TEAR_FIRE_EXTRA_SHOT, nullptr, 1); + else + { + uint32_t seed = Random(); + tear = static_cast(g_game->Spawn({.position = explosion.position, .velocity = velocity, .spawner = explosion.source, + .type = ENTITY_TEAR, .seed = seed})); + } + int blood = tear_variant_blood(tear->variant); + if (explosion.tearFlags[TEAR_BLOOD_BOMB] && blood != tear->variant) tear->ChangeVariant(blood); + + float multiplier = explosion.radiusMultiplier; + tear->SetScale(tear->fScale * SAD_TEAR_SCALE * multiplier); + tear->SetCollisionDamage((tear->collisionDamage + SAD_EXTRA_DAMAGE) * multiplier); + tear->targetPosition = explosion.position; +} + +// Sad Bombs: ten shots in a ring at a random turn, of whatever the bomb's player fires (Brimstone beams, knives, +// Technology lasers or tears). An enemy's bomb throws eight shots of its spawner's instead. +static void sad_bomb_spread(const Explosion& explosion) +{ + Entity* source = explosion.source; + float multiplier = explosion.radiusMultiplier; + Vector position = explosion.position; + if (source && source->spawnerType >= ENTITY_FIRST_ENEMY && source->spawnerType <= ENTITY_LAST_ENEMY) + { + for (int i = 0; i < SAD_ENEMY_SHOTS; i++) + { + uint32_t seed = Random(); + Vector velocity = vector_scale(vector_from_angle(i * FULL_TURN_DEGREES / SAD_ENEMY_SHOTS), SAD_ENEMY_SPEED); + g_game->Spawn({.position = position, .velocity = velocity, .spawner = source->spawnerEntity, + .type = ENTITY_PROJECTILE, .seed = seed}); + } + return; + } + + Entity* root = source ? source->GetLastSpawner() : nullptr; + Entity_Player* player = root && root->type == ENTITY_PLAYER ? root->ToPlayer() : nullptr; + float speed = (player ? player->shotSpeed : 1) * SAD_TEAR_SPEED; + float turn = random_unit() * FULL_TURN_DEGREES; + auto has = [&](int item, int weapon) { return player && (player->HasCollectible(item) || player->weaponTypes[weapon]); }; + bool isBrimstone = has(COLLECTIBLE_BRIMSTONE, WEAPON_BRIMSTONE); + bool isKnife = !isBrimstone && has(COLLECTIBLE_MOMS_KNIFE, WEAPON_KNIFE); + bool isLaser = !isBrimstone && !isKnife && (has(COLLECTIBLE_TECHNOLOGY, WEAPON_LASER) || has(COLLECTIBLE_TECH_X, WEAPON_TECH_X)); + for (int i = 0; i < SAD_SHOTS; i++) + { + float angle = i * FULL_TURN_DEGREES / SAD_SHOTS + turn; + if (isBrimstone) + { + // The original turns the ring by its random angle times a full turn, which is as random. + Entity_Laser* beam = player->FireBrimstone(vector_from_angle(((float)i / SAD_SHOTS + turn) * FULL_TURN_DEGREES), nullptr, 1); + beam->SetCollisionDamage(multiplier * beam->collisionDamage); + beam->pos = position; + beam->isDisableFollowParent = true; + beam->Update(); + } + else if (isKnife) + { + Entity_Knife* knife = player->FireKnife({.parent = player, .subType = KNIFE_SUBTYPE_PATH}); + knife->pos = position; + knife->rotation = angle_wrapped(angle); + knife->SetCollisionDamage((knife->collisionDamage + SAD_EXTRA_DAMAGE) * multiplier); + knife->parent = player; + knife->InitHomingPath(vector_from_angle(knife->rotation), player, 0); + knife->Update(); + } + else if (isLaser) + { + Entity_Laser* laser = player->FireTechLaser({.direction = vector_from_angle(angle), .position = position, + .offsetId = LASER_OFFSET_NONE, .isLeftEye = true, .isOneHit = true}); + laser->pos = position; + laser->posOffset = vector_make(0, SAD_LASER_LIFT); + laser->isDisableFollowParent = true; + laser->SetCollisionDamage((laser->collisionDamage + SAD_EXTRA_DAMAGE) * multiplier); + laser->Update(); + } + else sad_tear_fire(explosion, player, vector_scale(vector_from_angle(angle), speed)); + } +} + +// The Mysterious Liquid: green creep as wide as the blast, kept off the walls. +static void liquid_creep_spread(const Explosion& explosion) +{ + Vector position = g_game->room->GetClampedPosition(explosion.position, LIQUID_WALL_MARGIN); + uint32_t seed = Random(); + Entity* spawner = explosion.source ? explosion.source->spawnerEntity.get() : nullptr; + Entity* creep = g_game->Spawn({.position = position, .spawner = spawner, .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_GREEN, .seed = seed}); + float scale = explosion.radius * LIQUID_SCALE_PER_RADIUS; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); +} + +// Hot Bombs: a player's bomb leaves a burning flame for five to seven seconds, an enemy's a moving fire. +static void hot_bomb_burn(const Explosion& explosion) +{ + Entity* source = explosion.source; + bool isPlayers = !source || source->type == ENTITY_PLAYER || source->spawnerType == ENTITY_PLAYER || + source->type == ENTITY_FAMILIAR || source->spawnerType == ENTITY_FAMILIAR; + if (!isPlayers) + { + Entity* fire = g_game->Spawn({.position = explosion.position, .spawner = source, .type = ENTITY_FIREPLACE, + .variant = FIRE_MOVEABLE, .seed = Random()}); + fire->targetPosition = explosion.position; + return fire->Update(); + } + + auto* flame = static_cast(g_game->Spawn({.position = explosion.position, .spawner = source, + .type = ENTITY_EFFECT, .variant = EFFECT_RED_CANDLE_FLAME, + .seed = Random()})); + flame->scale = explosion.radiusMultiplier; + flame->SetCollisionDamage(g_game->deathmatchManager.is_active() ? HOT_FLAME_DAMAGE_VERSUS : HOT_FLAME_DAMAGE); + flame->SetTimeout((int)(Random() % HOT_FLAME_EXTRA_FRAMES) + HOT_FLAME_FRAMES); +} + +// Glitter Bombs: a random pickup (fewer the more bombs dropped some this floor), and a chance to charm an enemy: the +// first uncharmed one, or else the last charmed one again. +static void glitter_bomb_sparkle(const Explosion& explosion) +{ + Game& game = *g_game; + Entity* source = explosion.source; + if ((int)(Random() % 100) > game.bombPickupsSpawned + GLITTER_PICKUP_ODDS) + { + uint32_t seed = source ? source->dropRNG.Next() : Random(); + int filter = game.IsGreedMode() ? RANDOM_NO_COINS : RANDOM_NO_CHESTS_A; + Vector velocity = vector_scale(random_direction(), GLITTER_PICKUP_SPEED); + game.Spawn({.position = explosion.position, .velocity = velocity, .spawner = source, .subType = filter, + .type = ENTITY_PICKUP, .variant = PICKUP_NULL, .seed = seed}); + game.bombPickupsSpawned++; + } + if (Random() % 100 >= GLITTER_CHARM_CHANCE) return; + + Entity* charmed = nullptr; + for (Entity* entity : game.room->GetEntities()->updateEL) + { + if (!is_bomb_reachable(*entity)) continue; + charmed = entity; + if (!entity->HasEntityFlags(FLAG_CHARM)) break; + } + if (charmed) charmed->AddCharmed(EntityRef(), GLITTER_CHARM_FRAMES, false, false); +} + +// Sticky Bombs' eggs and Blood Bombs' blood: six splashes of creep (one in the middle, five around it, smaller), each +// with a burst of white or blood. +static void creep_splash_spread(const Explosion& explosion, int creepVariant, Entity* spawner) +{ + float multiplier = explosion.radiusMultiplier; + bool isWhite = creepVariant == EFFECT_PLAYER_CREEP_WHITE; + for (int i = 0; i < SPLASHES; i++) + { + Vector position = explosion.position; + float size = 1; + if (i > 0) + { + Vector direction = random_direction(); + float distance = random_unit() * SPLASH_DISTANCE_RANGE + SPLASH_DISTANCE_MIN; + position = vector_add(position, vector_scale(direction, distance * multiplier)); + size = random_unit() * SPLASH_SIZE_RANGE + SPLASH_SIZE_MIN; + } + size *= multiplier; + + auto* creep = static_cast(g_game->Spawn({.position = position, .spawner = spawner, .type = ENTITY_EFFECT, + .variant = creepVariant, .seed = Random()})); + creep->SetTimeout(SPLASH_CREEP_FRAMES); + creep->sprite.scale = vector_make(size * SPLASH_CREEP_SCALE, size * SPLASH_CREEP_SCALE); + creep->Update(); + + float burstSize = size < SPLASH_BIG ? size + size : size; + int burstKind = size >= SPLASH_BIG ? BLOOD_EXPLOSION_SPLASH_BIG : BLOOD_EXPLOSION_BURST; + auto* burst = static_cast(g_game->Spawn({.position = position, .subType = burstKind, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()})); + burst->rotation = random_unit() * FULL_TURN_DEGREES; + burst->sprite.scale = vector_make(burstSize, burstSize); + if (isWhite) burst->SetColor(SOLID_WHITE, -1, COLOR_PRIORITY_DEFAULT, false, true); + burst->Update(); + } +} + +// Scatter Bombs' poison (from a bomb, a rocket or Bob's Head): a cloud of poison gas as wide as the blast. +static void poison_cloud_spread(const Explosion& explosion) +{ + Entity* source = explosion.source; + bool isCarrier = source->type == ENTITY_BOMB || (source->type == ENTITY_EFFECT && source->variant == EFFECT_ROCKET) || + (source->type == ENTITY_TEAR && source->variant == TEAR_BOBS_HEAD); + if (!isCarrier) return; + + auto* cloud = static_cast(g_game->Spawn({.position = explosion.position, .spawner = source->GetLastSpawner(), + .type = ENTITY_EFFECT, .variant = EFFECT_SMOKE_CLOUD, .seed = Random()})); + cloud->SetTimeout(POISON_CLOUD_FRAMES); + float scale = explosion.radius * explosion.radiusMultiplier / POISON_CLOUD_RADIUS; + cloud->sprite.scale = vector_make(scale, scale); + cloud->SetCollisionDamage(POISON_CLOUD_DAMAGE); + cloud->Update(); +} + +// Brimstone Bombs (and a brimstone bomb itself, which shakes the screen): a red blast and a cross of four beams that +// count as shot by the bomb's first spawner, stronger with a player's. +static void brimstone_cross_spread(const Explosion& explosion) +{ + Entity* source = explosion.source; + Entity* root = source ? source->GetLastSpawner() : nullptr; + bool isPlayers = root && root->type == ENTITY_PLAYER; + int spawnerType = isPlayers ? ENTITY_PLAYER : root ? root->spawnerType : 0; + int spawnerVariant = isPlayers ? root->variant : root ? root->spawnerVariant : 0; + + // The original reads the source's type here even when there is none, and crashes. + if (source && source->type == ENTITY_BOMB && source->variant == BOMB_BRIMSTONE) game_shake_screen(BRIMSTONE_SHAKE); + auto* blast = static_cast(g_game->Spawn({.position = explosion.position, .spawner = source, .type = ENTITY_EFFECT, + .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()})); + blast->SetColor(BRIMSTONE_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + blast->SetTimeout(BRIMSTONE_BLAST_FRAMES); + + Entity_Laser* first = nullptr; + for (int i = 0; i < BRIMSTONE_BEAMS; i++) + { + Entity_Laser* beam = Entity_Laser::ShootAngle({.position = explosion.position, .source = blast, + .angleDegrees = i * RIGHT_ANGLE_DEGREES, .timeout = BRIMSTONE_BEAM_FRAMES, + .variant = LASER_THICK_RED}); + beam->spawnerEntity = root; + beam->spawnerType = spawnerType; + beam->spawnerVariant = spawnerVariant; + beam->scale = explosion.radiusMultiplier; + beam->ResetSpriteScale(); + beam->parentLaser = first; + beam->SetCollisionDamage(isPlayers ? explosion.radiusMultiplier * BRIMSTONE_BEAM_DAMAGE : BRIMSTONE_BEAM_DAMAGE); + beam->Update(); + if (!first) first = beam; + } +} + +// A giga pit's debris: five rock chips flung away from the blast, and two rocks shot outward, a player's as tears. +static void giga_pit_debris(const Explosion& explosion, Vector pit) +{ + Entity* source = explosion.source; + Vector away = vector_normalized(vector_sub(pit, explosion.position)); + for (int i = 0; i < GIGA_CHIPS; i++) + { + uint32_t seed = Random(); + float turn = random_unit() * GIGA_CHIP_SPREAD - GIGA_CHIP_SPREAD / 2; + float speed = random_unit() * GIGA_CHIP_SPEED_RANGE + GIGA_CHIP_SPEED_MIN; + Vector velocity = vector_scale(vector_rotated(away, turn), speed); + Vector direction = random_direction(); + Vector position = vector_add(pit, vector_scale(direction, random_unit() * GIGA_CHIP_SCATTER)); + auto* chip = static_cast(g_game->Spawn({.position = position, .velocity = velocity, .subType = GIGA_CHIP_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_ROCK_PARTICLE, .seed = seed})); + chip->fallingSpeed = -GIGA_CHIP_RISE_MIN - random_unit() * GIGA_CHIP_RISE_RANGE; + } + + bool isPlayers = source && (source->type == ENTITY_PLAYER || source->spawnerType == ENTITY_PLAYER); + // The original reads the spawner of a missing source and crashes. Here the rocks have none. + Entity* spawner = source ? source->spawnerEntity.get() : nullptr; + for (int i = 0; i < GIGA_ROCKS; i++) + { + Vector direction = random_direction(); + Vector position = vector_add(pit, vector_scale(direction, random_unit() * GIGA_ROCK_SCATTER)); + float speed = random_unit() * GIGA_ROCK_SPEED_RANGE + GIGA_ROCK_SPEED_MIN; + Vector velocity = vector_resized(vector_sub(position, explosion.position), speed); + uint32_t seed = Random(); + EntitySpawn rock = {.position = position, .velocity = velocity, .spawner = spawner, .seed = seed}; + rock.type = isPlayers ? ENTITY_TEAR : ENTITY_PROJECTILE; + rock.variant = isPlayers ? (int)TEAR_ROCK : (int)PROJECTILE_ROCK; + Entity* shot = g_game->Spawn(rock); + float scale = random_unit() * GIGA_ROCK_SCALE_RANGE + GIGA_ROCK_SCALE_MIN; + if (isPlayers) + { + static_cast(shot)->SetScale(scale); + shot->SetCollisionDamage(GIGA_ROCK_DAMAGE); + } + else static_cast(shot)->scale = scale; + shot->Update(); + } +} + +// Opens a pit in a cell a giga bomb tears up. Whether it is a pit now. +static bool giga_pit_open(int gridIndex) +{ + Room& room = *g_game->room; + room.SpawnGridEntity(gridIndex, GRID_PIT, 0, Random(), 0); + GridEntity* pit = gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + if (!pit || pit->type != GRID_PIT) return false; + + pit->PostInit(); + return true; +} + +// The fart a giga bomb's debris makes half a second later. +static void giga_fart_play(Entity_Effect*) +{ + effect_sound_play(SOUND_EXPLOSION_DEBRIS, {.volume = GIGA_FART_VOLUME}); +} + +// Giga Bombs: a big shake and flash, a fart that knocks everything away, a ring of dust and a big poof, then the floor +// caves in: a pit under the blast and two diamond rings of pits around it, each breaking what stood there and +// throwing debris. +static void giga_bomb_crater(const Explosion& explosion) +{ + Game& game = *g_game; + Entity* source = explosion.source; + game_shake_screen(GIGA_SHAKE); + game.bloomDuration = GIGA_BLOOM_FRAMES; + game.bloomTimer = GIGA_BLOOM_FRAMES; + game.bloomStrength = 1; + game_butter_bean_fart({.position = explosion.position, .source = source, .radius = GIGA_FART_RADIUS, .isShowEffect = false}); + + for (int i = 0; i < GIGA_DUSTS; i++) + { + float angle = ((random_unit() + (float)i) - HALF) * FULL_TURN_DEGREES / GIGA_DUSTS; + float speed = random_unit() * GIGA_DUST_SPEED_RANGE + GIGA_DUST_SPEED_MIN; + Vector direction = vector_from_angle(angle); + Vector velocity = vector_make(direction.x * speed, direction.y * speed * GIGA_DUST_FLATTEN); + auto* dust = static_cast(game.Spawn({.position = explosion.position, .velocity = velocity, .type = ENTITY_EFFECT, + .variant = EFFECT_DUST_CLOUD, .seed = Random()})); + float spin = Random() & 1 ? 1 : -1; + dust->rotation = (random_unit() * GIGA_DUST_SPIN_RANGE + GIGA_DUST_SPIN_MIN) * spin; + float scale = random_unit() * GIGA_DUST_SCALE_RANGE + 1; + dust->sprite.scale = vector_make(scale, scale); + dust->SetTimeout((int)(Random() % GIGA_DUST_FRAMES) + GIGA_DUST_FRAMES); + dust->SetColor(GIGA_DUST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + Entity* poof = game.Spawn({.position = explosion.position, .spawner = source, .subType = 1, .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, .seed = Random()}); + poof->sprite.scale = vector_make(2, 2); + poof->sprite.isFlipX = (Random() & 1) == 0; + poof->Update(); + + Room& room = *game.room; + int center = room.GetGridIndex(explosion.position); + if (room.CanSpawnObstacleAtPosition(center, false)) giga_pit_open(center); + + int centerX = center % room.gridWidth; + int centerY = center / room.gridWidth; + for (int ring = 1; ring <= GIGA_RINGS; ring++) + { + int dx = -1; + int dy = 0; + for (int side = 0; side < 4; side++) + { + int x = centerX + dx * ring; + int y = centerY + dy * ring; + for (int step = 0; step < ring; step++, x -= dy + dx, y += dx - dy) + { + bool isInside = x >= 0 && x < room.gridWidth && y >= 0 && y < room.gridHeight; + int gridIndex = isInside ? y * room.gridWidth + x : -1; + if (!room.CanSpawnObstacleAtPosition(gridIndex, false)) continue; + + GridEntity* grid = isInside ? room.gridEntities[gridIndex] : nullptr; + if (grid && grid->collisionClass != COLLISION_NONE) grid->Destroy(true, EntityRef(source)); + if (giga_pit_open(gridIndex)) giga_pit_debris(explosion, room.GetGridPosition(gridIndex)); + } + int turned = dx; + dx = -dy; + dy = turned; + } + } + Entity_Effect::CreateTimer(reinterpret_cast(&giga_fart_play), GIGA_FART_DELAY, 0, false); +} + +// 007009a0 The tear effects an explosion spreads, in order: Butt, Sad, the Mysterious Liquid, Hot, Glitter, Sticky +// Bombs' eggs, Scatter Bombs' poison, Blood, Brimstone and Giga Bombs. void explosion_tear_flag_effects(const Explosion& explosion) { - constexpr std::array SPREAD_FLAGS = {TEAR_BUTT_BOMB, TEAR_SAD_BOMB, TEAR_MYSTERIOUS_LIQUID_CREEP, TEAR_BURN, - TEAR_GLITTER_BOMB, TEAR_EGG_FLAG, TEAR_POISON, TEAR_BLOOD_BOMB, - TEAR_BRIMSTONE_BOMB, TEAR_GIGA_BOMB}; + const TearFlags& flags = explosion.tearFlags; Entity* source = explosion.source; + if (flags[TEAR_BUTT_BOMB]) butt_bomb_spread(explosion); + if (flags[TEAR_SAD_BOMB]) sad_bomb_spread(explosion); + if (flags[TEAR_MYSTERIOUS_LIQUID_CREEP]) liquid_creep_spread(explosion); + if (flags[TEAR_BURN]) hot_bomb_burn(explosion); + if (flags[TEAR_GLITTER_BOMB]) glitter_bomb_sparkle(explosion); + if (flags[TEAR_EGG_FLAG]) creep_splash_spread(explosion, EFFECT_PLAYER_CREEP_WHITE, nullptr); + if (flags[TEAR_POISON] && source) poison_cloud_spread(explosion); + if (flags[TEAR_BLOOD_BOMB]) + { + Entity* player = source; + while (player && player->type != ENTITY_PLAYER) player = player->spawnerEntity; + creep_splash_spread(explosion, EFFECT_PLAYER_CREEP_RED, g_game->deathmatchManager.is_active() ? player : nullptr); + } bool isBrimstoneBomb = source && source->type == ENTITY_BOMB && source->variant == BOMB_BRIMSTONE; - bool isSpread = std::ranges::any_of(SPREAD_FLAGS, [&](int bit) { return explosion.tearFlags[bit]; }); - if (isSpread || isBrimstoneBomb) reconstruction_missing("Game::BombTearflagEffects 007009a0: the bombs' tear effects"); + if (isBrimstoneBomb || flags[TEAR_BRIMSTONE_BOMB]) brimstone_cross_spread(explosion); + if (flags[TEAR_GIGA_BOMB]) giga_bomb_crater(explosion); } // 008207a0 Digs Mom's Shovel up when a bomb goes off in the first floor's start room while its quest is on. @@ -286,18 +814,70 @@ void shovel_quest_dig() reconstruction_missing("Room 008207a0: Mom's Shovel dug up by a bomb"); } -// 00700060, 00700061 An explosion as a bomb makes it: its damage and reach (larger for a stronger one), a crater (smaller -// under Safety Scissors), the blast itself in the bomb's color (or the poison, butt or brimstone bomb's), and the tear +// FUN_007008b0 A giga bomb's aftershock: while its bomb is there, the blast hits again with the bomb's tear effects. +static void giga_aftershock_hit(Entity_Effect* timer) +{ + Entity* bomb = timer->parent; + if (!bomb) return timer->Remove(); + + Explosion hit = {.position = timer->pos, + .source = bomb, + .damageFlags = (uint64_t)timer->varData[1] << 32 | timer->varData[0], + .damage = timer->collisionDamage, + .radius = timer->scale, + .isDamageSource = timer->varData[3] != 0, + .isLineCheck = timer->varData[2] != 0}; + if (bomb->type == ENTITY_BOMB) hit.tearFlags = static_cast(bomb)->tearFlags; + explosion_damage(hit); +} + +// Bomber Boy's cross: two explosions out along each of the four sides, a quarter weaker and smaller (smaller still in +// Bomberman versus), carrying the tear effects but the bomb kinds' own. Those past the room's walls go off nowhere. +static void cross_bomb_spread(const Explosion& explosion) +{ + Explosion arm = explosion; + for (int bit : {TEAR_BRIMSTONE_BOMB, TEAR_GLITTER_BOMB, TEAR_SAD_BOMB, TEAR_BUTT_BOMB, TEAR_CROSS_BOMB}) arm.tearFlags.reset(bit); + arm.damageFlags = DAMAGE_EXPLOSION; + arm.isDamageSource = false; + arm.isLineCheck = true; + DeathmatchManager& versus = g_game->deathmatchManager; + bool isBomberman = versus.is_active() && dynamic_cast(versus.type.get()); + float scale = isBomberman ? CROSS_SCALE_VERSUS : CROSS_SCALE; + arm.radiusMultiplier = scale * explosion.radiusMultiplier; + + for (int distance = 1; distance <= CROSS_DISTANCES; distance++) + for (auto [x, y] : CROSS_SIDES) + { + arm.position = vector_add(explosion.position, vector_scale(vector_make(x, y), explosion.radiusMultiplier * distance)); + Vector inside = g_game->room->GetClampedPositionImpl(arm.position, 0, 0, 0, 0); + if (inside.x == arm.position.x && inside.y == arm.position.y) explosion_effects(arm); + } +} + +// 00700060, 00700061 An explosion as a bomb makes it: its damage and reach (larger for a stronger one, largest for a +// giga bomb, which hits three more times), a crater (smaller under Safety Scissors), the blast itself in the bomb's +// color (or the poison, butt or brimstone bomb's, twice as large for a giga bomb), Bomber Boy's cross and the tear // effects it spreads. void explosion_effects(const Explosion& explosion) { Entity* source = explosion.source; - if (source && explosion.tearFlags[TEAR_GIGA_BOMB]) - reconstruction_missing("Game::BombExplosionEffects 00700061: the giga explosion's wave"); - if (explosion.tearFlags[TEAR_CROSS_BOMB]) - reconstruction_missing("Game::BombExplosionEffects 00700061: Bomber Boy's cross of explosions"); - + const TearFlags& flags = explosion.tearFlags; float radius = explosion.damage >= DAMAGE_LARGE ? RADIUS_LARGE : explosion.damage > DAMAGE_MEDIUM ? RADIUS_MEDIUM : RADIUS_SMALL; + if (source && flags[TEAR_GIGA_BOMB]) + { + radius = RADIUS_GIGA; + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&giga_aftershock_hit), GIGA_AFTERSHOCK_DELAY, + GIGA_AFTERSHOCKS, false); + timer->pos = explosion.position; + timer->SetCollisionDamage(explosion.damage * GIGA_AFTERSHOCK_DAMAGE); + timer->varData = {(uint32_t)explosion.damageFlags, (uint32_t)(explosion.damageFlags >> 32), explosion.isLineCheck, + explosion.isDamageSource}; + timer->scale = explosion.radiusMultiplier * RADIUS_GIGA; + timer->parent = source; + } + + Explosion damaged = explosion; + if (flags[TEAR_CROSS_BOMB]) damaged.damage *= CROSS_SCALE; float craterScale = radius / RADIUS_SMALL * explosion.radiusMultiplier; if (is_scissored(source)) { @@ -305,7 +885,6 @@ void explosion_effects(const Explosion& explosion) if (scissors == 2) craterScale *= SCISSORS_DOUBLE_SCALE; else if (scissors > 2) craterScale *= SCISSORS_MORE_SCALE; } - Explosion damaged = explosion; damaged.radius = radius * explosion.radiusMultiplier; explosion_damage(damaged); bomb_crater_spawn(explosion.position, nullptr, craterScale); @@ -315,11 +894,12 @@ void explosion_effects(const Explosion& explosion) blast->SetColor(explosion.color, -1, 255, false, true); const float* tint = explosion.color._tint; bool isWhite = tint[0] == 1 && tint[1] == 1 && tint[2] == 1 && tint[3] == 1; - if (explosion.tearFlags[TEAR_POISON] && isWhite) blast->SetColor(POISON_COLOR, -1, 255, false, true); - if (explosion.tearFlags[TEAR_BUTT_BOMB]) blast->SetColor(BUTT_COLOR, -1, 255, false, true); + if (flags[TEAR_POISON] && isWhite) blast->SetColor(POISON_COLOR, -1, 255, false, true); + if (flags[TEAR_BUTT_BOMB]) blast->SetColor(BUTT_COLOR, -1, 255, false, true); blast->sprite.scale = vector_make(craterScale, craterScale); if (source && source->type == ENTITY_BOMB && source->variant == BOMB_BRIMSTONE) blast->SetColor(BRIMSTONE_COLOR, -1, 255, false, true); + else if (flags[TEAR_GIGA_BOMB]) blast->sprite.scale = vector_make(explosion.radiusMultiplier * 2, explosion.radiusMultiplier * 2); bool isFetusBomb = source && source->type == ENTITY_BOMB && static_cast(source)->isFetus; if (g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_FIREWORKS && isFetusBomb) @@ -329,6 +909,7 @@ void explosion_effects(const Explosion& explosion) fireworks->isDead = true; fireworks->Update(); } + if (flags[TEAR_CROSS_BOMB]) cross_bomb_spread(damaged); explosion_tear_flag_effects(damaged); shovel_quest_dig(); } diff --git a/src/boss_baby_plum.cpp b/src/boss_baby_plum.cpp index 3d8b741..00171bf 100644 --- a/src/boss_baby_plum.cpp +++ b/src/boss_baby_plum.cpp @@ -66,12 +66,6 @@ constexpr float LEAVE_SPEED = 0.75f; constexpr float LEAVE_FRICTION = 0.98f; constexpr float ROOM_MIDDLE = 0.5f; -// A random fraction scaled into a range starting at a minimum. -static float random_between(float minimum, float spread) -{ - return random_unit() * spread + minimum; -} - // Idling, it circles its target on the grid. A boss room's Baby Plum left alone for 900 frames leaves, and after // a short wait it now and then picks one of its three attacks. static void plum_idle(Entity_NPC& npc) diff --git a/src/boss_colostomia.cpp b/src/boss_colostomia.cpp new file mode 100644 index 0000000..7467ca2 --- /dev/null +++ b/src/boss_colostomia.cpp @@ -0,0 +1,803 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "loot_list.h" +#include "npc_basement.h" +#include "room_grid.h" +#include +#include + +// Colostomia's states: idle, surfaced, its dive, its charge, its butt bomb spits, its fart and its pop into its second +// phase below 40% health. +constexpr int COLO_IDLE = NPC_STATE_IDLE; +constexpr int COLO_SURFACED = NPC_STATE_MOVE; +constexpr int COLO_DIVE = NPC_STATE_JUMP; +constexpr int COLO_CHARGE = NPC_STATE_ATTACK; +constexpr int COLO_SPIT = NPC_STATE_ATTACK2; +constexpr int COLO_SPIT_SURFACED = NPC_STATE_ATTACK3; +constexpr int COLO_FART = NPC_STATE_ATTACK4; +constexpr int COLO_POP = NPC_STATE_SPECIAL; + +constexpr ColorMod COLO_SPLAT_COLOR = {{1, 1, 1, 1}, {3.7f, 2.7f, 1.5f, 1}, {0, 0, 0}}; +constexpr ColorMod COLO_POOF_COLOR = {{0.62f, 0.6f, 0.42f, 0.6f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float COLO_FRICTION = 0.65f; +constexpr float COLO_CHARGE_FRICTION = 0.95f; +constexpr float COLO_POP_HEALTH = 0.4f; +constexpr RNG COLO_PICK_RNG = {0, 5, 9, 7}; +constexpr float COLO_AIM_LEAD = 0.1f; + +// Its moves from the surface: a dive and fart (more likely with few clouds about, never twice running and not with 14 +// clouds), a bomb spit, or a dive elsewhere. +enum ColostomiaMove +{ + COLO_MOVE_FART, + COLO_MOVE_SPIT, + COLO_MOVE_DIVE +}; +constexpr size_t COLO_CLOUD_LIMIT = 14; +constexpr size_t COLO_CLOUDS_FEW = 4; +constexpr int COLO_FART_WEIGHT = 1; +constexpr int COLO_FART_FEW_WEIGHT = 3; +constexpr int COLO_SPIT_WEIGHT = 2; +constexpr int COLO_DIVE_WEIGHT = 1; + +// Its targets: the cell nearest the target player among those the fewest clouds cover (each cloud covers its cell and +// the eight about it), and a dive spot 80 to 200 away, over 120 from the players and 100 from its last puddle. +static const std::array COLO_CLOUD_COVER = { + vector_make(0, 0), vector_make(-40, 0), vector_make(40, 0), vector_make(0, -40), vector_make(0, 40), + vector_make(-28, -28), vector_make(28, -28), vector_make(-28, 28), vector_make(28, 28)}; +constexpr float COLO_CELL_SCORE = 1000; +constexpr float COLO_CLOUD_SCORE = 10000; +constexpr int COLO_DIVE_TRIES = 15; +constexpr float COLO_DIVE_MARGIN = 60; +constexpr float COLO_DIVE_NEAR = 80; +constexpr float COLO_DIVE_FAR = 200; +constexpr float COLO_DIVE_PLAYER_GAP = 120; +constexpr float COLO_DIVE_PUDDLE_GAP_SQUARED = 10000; + +// The dive: a leap toward its spot, landing in a ring of puke and its puddle, surfacing after 20 to 49 frames. +constexpr float COLO_LEAP_PULL = 0.011f; +constexpr float COLO_LEAP_FRICTION = 0.5f; +constexpr float COLO_LANDING_SPEED = 10; +constexpr uint32_t COLO_SURFACE_WAIT_RANGE = 30; +constexpr int COLO_SURFACE_WAIT = 20; + +// The charge along an axis, steering toward its target, splashing and farting as it goes, until it hits a wall or +// stalls. +constexpr float COLO_CHARGE_MASS = 5; +constexpr float COLO_STEER = 0.002f; +constexpr float COLO_STEER_MAX = 0.2f; +constexpr float COLO_CHARGE_PUSH = 2; +constexpr float COLO_SPLASH_EVERY = 4; +constexpr float COLO_SPLASH_TRAIL = 0.1f; +constexpr float COLO_SPLASH_SPREAD = 2; +constexpr float COLO_SPLASH_SCALE = 0.8f; +constexpr float COLO_SPLASH_SCALE_RANGE = 0.2f; +constexpr float COLO_SPLASH_FLAT = 0.8f; +constexpr uint32_t COLO_DROPS_RANGE = 6; +constexpr uint32_t COLO_DROPS = 8; +constexpr float COLO_DROP_REACH_X = 60; +constexpr float COLO_DROP_REACH_Y = 40; +constexpr float COLO_DROP_SPEED = 3; +constexpr float COLO_DROP_SPEED_RANGE = 5; +constexpr int COLO_DROP_SUBTYPE = 1; +constexpr float COLO_DROP_FALL = 1.5f; +constexpr float COLO_DROP_RISE = -4; +constexpr float COLO_DROP_RISE_RANGE = 8; +constexpr float COLO_STALL_SPEED = 6; +constexpr float COLO_STALL_LIMIT = 10; +constexpr float COLO_STALL_DECAY = 0.2f; +constexpr float COLO_FART_DISTANCE = 60; +constexpr float COLO_FART_VOLUME = 0.5f; +constexpr float COLO_FART_SPEED = 10; +constexpr float COLO_FART_DRIFT = 0.2f; +constexpr float COLO_TRAIL_FALL = -0.093f; +constexpr float COLO_TRAIL_RISE = -2; +constexpr float COLO_TRAIL_SLOWING = 0.96f; +constexpr float COLO_TRAIL_ANGLE = 110; +constexpr float COLO_TRAIL_SPEED = 6; +constexpr float COLO_TRAIL_SPEED_RANGE = 2; +constexpr float COLO_WALL_HIT = 0.5f; +constexpr int COLO_WALL_SHAKE = 6; +constexpr uint32_t COLO_SPIT_ODDS = 5; +constexpr uint32_t COLO_SPIT_CLOUDS = 8; + +// The butt bombs: lobbed from its side at the target's lead, turning at most 65 degrees from its facing, at a speed +// up to 18, or two from the surface 20 degrees apart. +constexpr float COLO_BOMB_SIDE = 15; +constexpr float COLO_BOMB_TURN = 65; +constexpr float COLO_BOMB_SPEED = 0.08f; +constexpr float COLO_BOMB_SPEED_MAX = 18; +constexpr float COLO_BOMB_FALL = -6; +constexpr float COLO_BOMB_HEIGHT = -50; +constexpr int COLO_BOMB_FUSE = 36; +constexpr int COLO_BOMB_SHORT_FUSE = 30; +constexpr int COLO_SPIT_POOF = 3; +constexpr uint32_t COLO_SPIT_REST_RANGE = 20; +constexpr int COLO_SPIT_REST = 40; +constexpr float COLO_CLOUD_ALPHA = 0.5f; +constexpr float COLO_CLOUD_SCALE = 0.7f; +constexpr float COLO_CLOUD_SIDE = 10; +constexpr float COLO_CLOUD_HEIGHT = -20; +constexpr float COLO_PAIR_AIM = 0.05f; +constexpr float COLO_PAIR_SPEED = 20; +constexpr float COLO_PAIR_ANGLE = 20; +constexpr float COLO_PAIR_SPREAD = 5; + +// The fart: eight clouds, a ring at 14 to 22, and 6 to 15 frames on the surface or a spit when the clouds are many. +constexpr int COLO_FART_CLOUDS = 8; +constexpr float COLO_FART_STEP = 45; +constexpr float COLO_FART_JITTER = 20; +constexpr float COLO_FART_CLOUD_SPEED = 14; +constexpr float COLO_FART_CLOUD_RANGE = 8; +constexpr int COLO_CLOUD_SUBTYPE = 1; +constexpr uint32_t COLO_FART_SURFACE_ODDS = 3; +constexpr size_t COLO_FART_SPIT_CLOUDS = 11; +constexpr uint32_t COLO_FART_REST_RANGE = 10; +constexpr int COLO_FART_REST = 6; + +// The pop: kept 40 and 80 inside the walls, six clouds at 13 to 19, and every cloud of its own fading in 30 frames. +constexpr float COLO_POP_MARGIN = 40; +constexpr float COLO_POP_MARGIN_WIDE = 80; +constexpr float COLO_POP_PULL = 0.6f; +constexpr float COLO_POP_FRICTION = 0.4f; +constexpr int COLO_POP_CLOUDS = 6; +constexpr float COLO_POP_STEP = 60; +constexpr float COLO_POP_CLOUD_SPEED = 13; +constexpr float COLO_POP_CLOUD_RANGE = 6; +constexpr int COLO_CLOUD_FADE = 30; + +// Its drips while diving or popping, and the water browning as it dies. +constexpr float COLO_DRIP_EVERY = 2; +constexpr float COLO_DRIP_SPREAD = 6; +constexpr float COLO_DRIP_DEPTH = -10; +constexpr KColor COLO_WATER_COLOR = kcolor_rgba(0.455f, 0.296f, 0.127f, 0.7f); +constexpr KColor COLO_WATER_MULTIPLIER = kcolor_rgba(1, 0.8f, 0.7f, 1); +constexpr int COLO_WATER_FADE = 90; + +// Whether a hit is an explosion of its own clouds or bombs, which it ignores. +static bool colostomia_hit_is_own(const DamageEvent& hit) +{ + if (!(hit.damageFlags & DAMAGE_EXPLOSION) || hit.source.IsFriendly()) return false; + bool isCloud = hit.source.type == ENTITY_EFFECT && hit.source.variant == EFFECT_SMOKE_CLOUD; + return isCloud || hit.source.spawnerType == ENTITY_COLOSTOMIA; +} + +// Where the target player stands in its lead, a tenth of its velocity per unit of distance ahead. +static Vector colostomia_lead_get(Entity_NPC& npc, Vector from) +{ + Entity* target = npc.GetPlayerTarget(); + float distance = vector_length(vector_sub(from, target->pos)); + return vector_add(target->pos, vector_scale(target->velocity, distance * COLO_AIM_LEAD)); +} + +// 004a2940 Its charge's target: the cell nearest the target player that the fewest clouds cover, or the player when +// it stands clear of them (isPlayer). +static Vector colostomia_pick_target(Entity_NPC& npc, bool& isPlayer) +{ + Room& room = *g_game->room; + std::array clouds{}; + for (Entity* cloud : entity_query(ENTITY_EFFECT, EFFECT_SMOKE_CLOUD)) + for (Vector cover : COLO_CLOUD_COVER) + { + int index = room.GetGridIndex(vector_add(cloud->pos, cover)); + if (index >= 0) clouds[index]++; + } + + Vector player = npc.GetPlayerTarget()->pos; + int playerCell = room.GetGridIndex(player); + isPlayer = true; + if (playerCell < 0 || clouds[playerCell] == 0) return player; + + float best = (float)clouds[playerCell] * COLO_CELL_SCORE; + Vector spot = player; + for (int i = 0; i < room.gridHeight * room.gridWidth; i++) + { + Vector cell = room.GetGridPosition(i); + float score = + vector_length_squared(vector_sub(player, cell)) + (float)(clouds[i] * clouds[i]) * COLO_CLOUD_SCORE; + if (score >= best) continue; + best = score; + spot = cell; + } + isPlayer = false; + return spot; +} + +// 004a2ce0 Picks a dive spot (v1) in the open, its last puddle let go and the current one kept to keep away from, and +// dives. +static void colostomia_pick_dive_target(Entity_NPC& npc) +{ + Room& room = *g_game->room; + npc.v1 = {}; + for (int i = 0; i < COLO_DIVE_TRIES; i++) + { + npc.v1 = room_free_pickup_position_find({.position = room.GetRandomPosition(0)}); + float fromNpc = vector_length(vector_sub(npc.pos, npc.v1)); + float fromPlayer = vector_length(vector_sub(game_nearest_player(npc.v1)->pos, npc.v1)); + if (!room.IsPositionInRoom(npc.v1, COLO_DIVE_MARGIN)) continue; + if (room.GetGridCollision(room.GetGridIndex(npc.v1)) != COLLISION_NONE) continue; + if (fromNpc < COLO_DIVE_NEAR || fromNpc > COLO_DIVE_FAR || fromPlayer <= COLO_DIVE_PLAYER_GAP) continue; + Entity* lastPuddle = npc.entityRef.get(); + if (!lastPuddle || vector_length_squared(vector_sub(npc.v1, lastPuddle->pos)) > COLO_DIVE_PUDDLE_GAP_SQUARED) + break; + } + + if (npc.entityRef) + { + npc.entityRef->parent = nullptr; + npc.entityRef = nullptr; + } + if (npc.child) + { + npc.entityRef = npc.child.get(); + npc.child = nullptr; + } + npc.sprite.Play("Dive"); + npc.state = COLO_DIVE; +} + +// A smoke cloud it lets out, lasting until it fades on its own. +static void colostomia_cloud_spawn(Entity_NPC& npc, Vector velocity) +{ + auto* cloud = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = velocity, + .spawner = &npc, + .subType = COLO_CLOUD_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = Random()})); + cloud->timeout = -1; + cloud->lifespan = -1; + cloud->Update(); +} + +// A ring of clouds: count of them a step apart, jittered, at a speed and range. +static void colostomia_cloud_ring(Entity_NPC& npc, int count, float step, float speed, float range) +{ + for (int i = 0; i < count; i++) + { + float angle = random_unit() * COLO_FART_JITTER - COLO_FART_JITTER * HALF + (float)i * step; + float cloudSpeed = random_unit() * range + speed; + colostomia_cloud_spawn(npc, vector_scale(vector_from_angle(angle), cloudSpeed)); + } +} + +// Its own clouds fade out in 30 frames. +static void colostomia_clouds_fade(Entity_NPC& npc) +{ + for (Entity* entity : entity_query(ENTITY_EFFECT, EFFECT_SMOKE_CLOUD)) + { + auto* cloud = static_cast(entity); + if (cloud->spawnerEntity.get() != &npc) continue; + cloud->timeout = COLO_CLOUD_FADE; + cloud->lifespan = COLO_CLOUD_FADE; + } +} + +// A butt bomb lobbed from a place. +static void colostomia_bomb_throw(Entity_NPC& npc, Vector position, Vector velocity, uint32_t seed, int fuse) +{ + auto* bomb = static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_BOMB, + .variant = BOMB_BUTT, + .seed = seed})); + bomb->fallSpeed = COLO_BOMB_FALL; + bomb->posOffset = vector_make(0, COLO_BOMB_HEIGHT); + bomb->SetExplosionCountdown(fuse); + bomb->entityCollisionClass = ENTCOLL_NONE; +} + +// Its puddle, left where it lands as its child. +static void colostomia_puddle_spawn(Entity_NPC& npc) +{ + Entity* puddle = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_COLOSTOMIA_PUDDLE, + .seed = Random()}); + puddle->parent = &npc; + puddle->Update(); + npc.child = puddle; +} + +// A landing: a ring of eight puke shots. +static void colostomia_landing_shots(Entity_NPC& npc) +{ + ProjectileParams params; + params.variant = PROJECTILE_PUKE; + npc.FireProjectiles(npc.pos, vector_make(COLO_LANDING_SPEED, 0), PROJECTILES_EIGHT, params); +} + +// Idle: a charge at its target, or a bomb spit when it was told to. +static void colostomia_idle_update(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + npc.sprite.Play("Idle"); + if (npc.projectileCooldown >= 1) return; + + if (npc.i2 == 0) + { + bool isPlayer = false; + npc.targetPosition = colostomia_pick_target(npc, isPlayer); + Vector toward = vector_sub(npc.targetPosition, npc.pos); + npc.i1 = vector_to_direction(vector_make(toward.x + toward.x, toward.y)); + if (isPlayer) npc.targetPosition = {}; + if (npc.i1 == DIRECTION_UP) npc.sprite.Play("ChargeStartUp"); + else npc.sprite.Play(npc.i1 == DIRECTION_DOWN ? "ChargeStartDown" : "ChargeStartHori"); + npc.state = COLO_CHARGE; + } + else + { + npc.sprite.Play("Attack"); + npc.sprite.isFlipX = npc.pos.x < colostomia_lead_get(npc, npc.pos).x; + npc.state = COLO_SPIT; + } + npc.i2 = 0; +} + +// Surfaced: its next move once its wait runs out. +static void colostomia_surfaced_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) npc.entityCollisionClass = ENTCOLL_ALL; + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Idle2"); + if (npc.projectileCooldown >= 1) return; + + npc.entityCollisionClass = ENTCOLL_ALL; + size_t clouds = entity_query(ENTITY_EFFECT, EFFECT_SMOKE_CLOUD).size(); + WeightedOutcomePicker picker; + if (npc.i1 == 0 && clouds < COLO_CLOUD_LIMIT) + picker.AddOutcomeWeight(COLO_MOVE_FART, clouds < COLO_CLOUDS_FEW ? COLO_FART_FEW_WEIGHT : COLO_FART_WEIGHT); + picker.AddOutcomeWeight(COLO_MOVE_SPIT, COLO_SPIT_WEIGHT); + picker.AddOutcomeWeight(COLO_MOVE_DIVE, COLO_DIVE_WEIGHT); + RNG rng = COLO_PICK_RNG; + rng._seed = Random() | 1; + + switch (picker.PickOutcome(rng)) + { + case COLO_MOVE_FART: + npc.sprite.Play("GoUnder"); + npc.state = COLO_FART; + npc.i1 = 1; + break; + case COLO_MOVE_SPIT: + npc.sprite.Play("Attack2"); + npc.sprite.isFlipX = colostomia_lead_get(npc, npc.pos).x < npc.pos.x; + npc.state = COLO_SPIT_SURFACED; + break; + case COLO_MOVE_DIVE: + colostomia_pick_dive_target(npc); + npc.sprite.Play("GoUnder"); + break; + } +} + +// The dive: under, a leap toward its spot, and a landing with its puke ring and puddle. +static void colostomia_dive_update(Entity_NPC& npc) +{ + if (npc.sprite.GetAnimation() == "GoUnder") + { + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Dive"); + return; + } + if (npc.sprite.IsEventTriggered("Jump")) + { + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + npc.targetPosition = {}; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.v2.x = 0; + } + if (npc.sprite.WasEventTriggered("Jump") && !npc.sprite.WasEventTriggered("Land")) + { + npc.friction *= COLO_LEAP_FRICTION; + npc.v2.x = std::clamp(npc.speedMultiplier * COLO_LEAP_PULL + npc.v2.x, 0.0f, 1.0f); + npc.velocity = vector_scale(vector_sub(npc.v1, npc.pos), npc.v2.x / npc.friction); + } + if (npc.sprite.IsEventTriggered("Land")) + { + npc.PlaySound(SOUND_MEATHEADSHOOT, 1, 2, false, 1); + npc.MakeBloodPoofAtPos(npc.splatColor, 1); + colostomia_landing_shots(npc); + npc.targetPosition = npc.pos; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.entityCollisionClass = ENTCOLL_ALL; + if (!npc.child) colostomia_puddle_spawn(npc); + } + if (npc.sprite.IsPlaying()) return; + + npc.sprite.Play("Surface"); + npc.state = COLO_SURFACED; + npc.projectileCooldown = (int)(Random() % COLO_SURFACE_WAIT_RANGE) + COLO_SURFACE_WAIT; + npc.i1 = 0; +} + +// The charge's splash every four frames: a blood splash and a scatter of drops. +static void colostomia_charge_splash(Entity_NPC& npc) +{ + Vector trail = vector_scale(npc.velocity, COLO_SPLASH_TRAIL); + Vector spread = random_direction(); + spread = vector_add(vector_scale(spread, random_unit() * COLO_SPLASH_SPREAD), trail); + Entity* splash = blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH, npc.pos, {}, npc.splatColor, spread); + float size = random_unit() * COLO_SPLASH_SCALE_RANGE + COLO_SPLASH_SCALE; + splash->sprite.scale = vector_make(size, size * COLO_SPLASH_FLAT); + + for (uint32_t drops = Random() % COLO_DROPS_RANGE + COLO_DROPS; drops != 0; drops--) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector reach = vector_make(std::cos(angle) * COLO_DROP_REACH_X, std::sin(angle) * COLO_DROP_REACH_Y); + float speed = random_unit() * COLO_DROP_SPEED_RANGE + COLO_DROP_SPEED; + Vector velocity = vector_scale(reach, speed / COLO_DROP_REACH_X); + auto* drop = static_cast(g_game->Spawn({.position = vector_add(reach, npc.pos), + .velocity = velocity, + .subType = COLO_DROP_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_WATER_SPLASH, + .seed = Random()})); + drop->sprite.scale = vector_scale(drop->sprite.scale, 2); + drop->fallingAcceleration = COLO_DROP_FALL; + drop->fallingSpeed = COLO_DROP_RISE - random_unit() * COLO_DROP_RISE_RANGE; + drop->Update(); + } +} + +// Every 60 of the charge's distance: a cloud let out behind and two puke shots to the sides. +static void colostomia_charge_fart(Entity_NPC& npc) +{ + npc.v1.x = 0; + npc.PlaySound(SOUND_FART, COLO_FART_VOLUME, 2, false, 1); + Vector drift = random_direction(); + drift = vector_add(vector_scale(drift, random_unit() * COLO_FART_SPEED), npc.velocity); + auto* cloud = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(drift, COLO_FART_DRIFT), + .spawner = &npc, + .subType = COLO_CLOUD_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = Random()})); + cloud->timeout = -1; + cloud->lifespan = -1; + cloud->Update(); + + ProjectileParams params; + params.fallingAccelModifier = COLO_TRAIL_FALL; + params.bulletFlags = PROJECTILE_ACCELERATE_EX; + params.acceleration = COLO_TRAIL_SLOWING; + params.variant = PROJECTILE_PUKE; + params.fallingSpeedModifier = random_unit() * COLO_TRAIL_RISE; + for (float side : {COLO_TRAIL_ANGLE, -COLO_TRAIL_ANGLE}) + { + Vector direction = vector_normalized(vector_rotated(npc.velocity, side)); + float speed = random_unit() * COLO_TRAIL_SPEED_RANGE + COLO_TRAIL_SPEED; + npc.FireProjectiles(npc.pos, vector_scale(direction, speed), PROJECTILES_SINGLE, params); + } +} + +// The charge underway: steering toward its target, splashing, farting every 60 it covers, and stalling into a wall +// hit when it slows. +static void colostomia_charge_move(Entity_NPC& npc, Vector direction, float& frictionScale) +{ + frictionScale = COLO_CHARGE_FRICTION; + Vector side = vector_rotated(direction, RIGHT_ANGLE_DEGREES); + Vector aim = vector_is_zero(npc.targetPosition) ? npc.GetPlayerTarget()->pos : npc.targetPosition; + float steer = std::clamp(vector_dot(vector_sub(aim, npc.pos), side) * COLO_STEER, -COLO_STEER_MAX, COLO_STEER_MAX); + Vector push = vector_add(vector_scale(side, steer), direction); + npc.velocity = vector_add(vector_scale(push, COLO_CHARGE_PUSH * npc.speedMultiplier), npc.velocity); + if (npc.GetIntervalTicks(COLO_SPLASH_EVERY, 0)) colostomia_charge_splash(npc); + + float moved = vector_length(vector_sub(npc.pos, npc.v2)); + npc.v1.x += moved; + npc.v2 = npc.pos; + if (moved < npc.speedMultiplier * COLO_STALL_SPEED) npc.v1.y += npc.speedMultiplier; + if (npc.v1.y > COLO_STALL_LIMIT) + { + npc.isCollidesWithGrid = true; + npc.gridCollisionVelocity = npc.velocity; + npc.gridCollisionNormal = npc.velocity; + } + npc.v1.y -= npc.speedMultiplier * COLO_STALL_DECAY; + if (npc.v1.x > COLO_FART_DISTANCE) colostomia_charge_fart(npc); +} + +// The charge: its start toward an axis, the run, and the end against a wall, after which it spits bombs when the +// clouds are many. +static void colostomia_charge_update(Entity_NPC& npc, float& frictionScale) +{ + if (npc.i1 < 0) + { + if (npc.sprite.IsEventTriggered("Shoot")) npc.sprite.isFlipX = false; + if (npc.sprite.IsPlaying()) return; + npc.state = COLO_IDLE; + uint32_t odds = Random(); + size_t clouds = entity_query(ENTITY_EFFECT, EFFECT_SMOKE_CLOUD).size(); + npc.projectileCooldown = 1; + if (odds % COLO_SPIT_ODDS + COLO_SPIT_CLOUDS <= clouds) npc.i2 = 1; + return; + } + + Vector direction = vector_from_direction(npc.i1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.sprite.isFlipX = npc.i1 == DIRECTION_LEFT; + npc.PlaySound(SOUND_FART_GURG, 1, 2, false, 1); + npc.PlaySound(SOUND_BOSS2_DIVE, 1, 2, false, 1); + npc.v2 = npc.pos; + npc.v1 = {}; + npc.mass = npc.config->mass * COLO_CHARGE_MASS; + } + if (npc.sprite.WasEventTriggered("Shoot") || npc.sprite.animState.IsLoopingAnimation()) + colostomia_charge_move(npc, direction, frictionScale); + if (!npc.sprite.IsPlaying()) + { + if (npc.i1 == DIRECTION_UP) npc.sprite.Play("ChargeLoopUp"); + else npc.sprite.Play(npc.i1 == DIRECTION_DOWN ? "ChargeLoopDown" : "ChargeLoopHori"); + } + + if (!npc.isCollidesWithGrid || vector_dot(direction, npc.gridCollisionNormal) <= COLO_WALL_HIT) return; + npc.mass = npc.config->mass; + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, 1); + game_shake_screen(COLO_WALL_SHAKE); + if (npc.i1 == DIRECTION_UP) npc.sprite.Play("ChargeEndUp"); + else npc.sprite.Play(npc.i1 == DIRECTION_DOWN ? "ChargeEndDown" : "ChargeEndHori"); + npc.sprite.isFlipX = npc.i1 == DIRECTION_LEFT; + npc.i1 = -1; +} + +// The bomb spit: a poof and a butt bomb lobbed from its side at the target's lead. +static void colostomia_spit_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_HEARTOUT, 1, 2, false, 1); + Entity* poof = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = COLO_SPIT_POOF, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, + .seed = Random()}); + poof->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->sprite.isFlipX = (Random() & 1) == 0; + poof->Update(); + + bool isRight = npc.sprite.isFlipX; + Vector from = vector_make(npc.pos.x + (isRight ? COLO_BOMB_SIDE : -COLO_BOMB_SIDE), npc.pos.y); + Vector lead = colostomia_lead_get(npc, npc.pos); + float aim = vector_angle(vector_sub(lead, from)); + float speed = std::min(vector_length(vector_sub(npc.pos, lead)) * COLO_BOMB_SPEED, COLO_BOMB_SPEED_MAX); + float angle = angle_approach(isRight ? 0 : HALF_TURN_DEGREES, aim, COLO_BOMB_TURN); + uint32_t seed = Random(); + colostomia_bomb_throw(npc, from, vector_scale(vector_from_angle(angle), speed), seed, COLO_BOMB_FUSE); + } + if (npc.sprite.IsEventTriggered("Land")) npc.sprite.isFlipX = false; + if (npc.sprite.IsPlaying()) return; + + npc.state = COLO_IDLE; + npc.projectileCooldown = (int)(Random() % COLO_SPIT_REST_RANGE) + COLO_SPIT_REST; +} + +// The surfaced spit: a cloud and two bombs at the target's lead, 20 degrees apart, then a dive. +static void colostomia_spit_surfaced_update(Entity_NPC& npc) +{ + if (npc.sprite.GetAnimation() == "Surface") + { + if (npc.sprite.IsPlaying()) return; + npc.sprite.Play("Attack2"); + npc.sprite.isFlipX = colostomia_lead_get(npc, npc.pos).x < npc.pos.x; + return; + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_BOSS_LITE_GURGLE, 1, 2, false, 1); + ColorMod color = npc.splatColor; + color._tint[3] = COLO_CLOUD_ALPHA; + Entity_Effect* cloud = npc.MakeBloodCloud(npc.pos, color, COLO_CLOUD_SCALE); + cloud->posOffset = vector_make(npc.sprite.isFlipX ? -COLO_CLOUD_SIDE : COLO_CLOUD_SIDE, COLO_CLOUD_HEIGHT); + Vector aim = vector_scale(vector_sub(colostomia_lead_get(npc, npc.pos), npc.pos), COLO_PAIR_AIM); + if (vector_length(aim) > COLO_PAIR_SPEED) aim = vector_resized(aim, COLO_PAIR_SPEED); + for (int side : {-1, 1}) + { + uint32_t seed = Random(); + Vector velocity = vector_rotated(aim, (float)side * COLO_PAIR_ANGLE); + Vector from = vector_add(vector_scale(random_direction(), COLO_PAIR_SPREAD), npc.pos); + colostomia_bomb_throw(npc, from, velocity, seed, side < 0 ? COLO_BOMB_SHORT_FUSE : COLO_BOMB_FUSE); + } + } + if (!npc.sprite.IsPlaying()) colostomia_pick_dive_target(npc); +} + +// The fart: under, a ring of eight clouds, then up to spit or to wait. +static void colostomia_fart_update(Entity_NPC& npc) +{ + if (npc.sprite.GetAnimation() == "GoUnder") + { + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Attack3"); + return; + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_FART, 1, 2, false, 1); + npc.MakeGroundPoofAtSelf(COLO_POOF_COLOR, 1); + colostomia_cloud_ring(npc, COLO_FART_CLOUDS, COLO_FART_STEP, COLO_FART_CLOUD_SPEED, COLO_FART_CLOUD_RANGE); + } + if (npc.sprite.IsPlaying()) return; + + bool isSpit = Random() % COLO_FART_SURFACE_ODDS != 0 || + entity_query(ENTITY_EFFECT, EFFECT_SMOKE_CLOUD).size() > COLO_FART_SPIT_CLOUDS; + npc.sprite.Play("Surface"); + if (isSpit) + { + npc.state = COLO_SPIT_SURFACED; + return; + } + npc.state = COLO_SURFACED; + npc.projectileCooldown = (int)(Random() % COLO_FART_REST_RANGE) + COLO_FART_REST; +} + +// The pop: pulled off the walls, a burst of six clouds as its own fade, its puddle, and a landing ring. +static void colostomia_pop_update(Entity_NPC& npc) +{ + if (vector_is_zero(npc.targetPosition)) + { + Vector inside = g_game->room->GetClampedPositionImpl(npc.pos, COLO_POP_MARGIN, COLO_POP_MARGIN_WIDE, + COLO_POP_MARGIN, COLO_POP_MARGIN_WIDE); + npc.velocity = vector_scale(vector_sub(inside, npc.pos), COLO_POP_PULL); + npc.friction *= COLO_POP_FRICTION; + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.targetPosition = npc.pos; + npc.PlaySound(SOUND_PLOP, 1, 2, false, 1); + npc.PlaySound(SOUND_DEATH_BURST_LARGE, 1, 2, false, 1); + npc.MakeGroundPoof(npc.pos, COLO_POOF_COLOR, 1); + colostomia_clouds_fade(npc); + colostomia_cloud_ring(npc, COLO_POP_CLOUDS, COLO_POP_STEP, COLO_POP_CLOUD_SPEED, COLO_POP_CLOUD_RANGE); + } + if (npc.sprite.WasEventTriggered("Shoot") && !npc.child) colostomia_puddle_spawn(npc); + if (npc.sprite.IsEventTriggered("Land")) + { + npc.PlaySound(SOUND_MEATHEADSHOOT, 1, 2, false, 1); + npc.MakeBloodPoof(npc.pos, npc.splatColor, 1); + colostomia_landing_shots(npc); + } + if (npc.sprite.IsPlaying()) return; + + npc.sprite.Play("Surface"); + npc.state = COLO_SURFACED; + npc.projectileCooldown = (int)(Random() % COLO_FART_REST_RANGE) + COLO_FART_REST; + npc.i1 = 0; +} + +// Its drips while diving or popping: a haemo trail from its EffectGuide null every other frame. +static void colostomia_drip(Entity_NPC& npc) +{ + if (!npc.GetIntervalTicks(COLO_DRIP_EVERY, 0)) return; + Vector guide = npc.GetNullOffset("EffectGuide"); + if (vector_is_zero(guide)) return; + + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float reach = random_unit(); + Vector drift = vector_make(std::cos(angle) * reach, std::sin(angle) * reach); + Vector position = vector_make(guide.x + drift.x * COLO_DRIP_SPREAD + npc.pos.x, npc.pos.y); + Entity* drip = g_game->Spawn({.position = position, + .velocity = drift, + .type = ENTITY_EFFECT, + .variant = EFFECT_HAEMO_TRAIL, + .seed = Random()}); + drip->posOffset = vector_make(0, guide.y + drift.y * COLO_DRIP_SPREAD); + drip->renderDepthOffset = COLO_DRIP_DEPTH; + drip->sprite.color = npc.splatColor; + drip->Update(); +} + +// Dying, the room's water browns over 90 frames, from where its fade stood (or the floor's water when none ran). +static void colostomia_water_brown() +{ + Room& room = *g_game->room; + if (room.waterLerpColorDuration < 0) + { + room.waterColor = room.fxLayers.fxParams.waterColor; + room.waterColorMultiplier = room.fxLayers.fxParams.waterColorMultiplier; + } + else + { + float t = 1; + if (room.waterLerpColorDuration != 0) + t = std::clamp(1 - (float)room.waterLerpColorCountdown / (float)room.waterLerpColorDuration, 0.0f, 1.0f); + for (auto [from, to] : {std::pair{&room.waterColor, &room.waterLerpTargetColor}, + std::pair{&room.waterColorMultiplier, &room.waterLerpTargetColorMult}}) + { + from->_red += (to->_red - from->_red) * t; + from->_green += (to->_green - from->_green) * t; + from->_blue += (to->_blue - from->_blue) * t; + from->_alpha += (to->_alpha - from->_alpha) * t; + } + } + room.waterLerpTargetColor = COLO_WATER_COLOR; + room.waterLerpTargetColorMult = COLO_WATER_MULTIPLIER; + room.waterLerpColorDuration = COLO_WATER_FADE; + room.waterLerpColorCountdown = COLO_WATER_FADE; +} + +// Its explosions' hits are taken back, and below 40% health it pops into its second phase. +static void colostomia_damage_update(Entity_NPC& npc) +{ + if (npc.pendingDamage > 0) + { + npc.pendingDamage = 0; + for (DamageEvent& hit : npc.damageEvents) + { + if (colostomia_hit_is_own(hit)) hit.damage = 0; + npc.pendingDamage += hit.damage; + } + } + + bool isBusy = npc.state == COLO_POP || npc.state == COLO_SURFACED || npc.state == COLO_DIVE || + npc.state == COLO_SPIT_SURFACED || npc.state == COLO_FART; + if (npc.health >= npc.maxHitPoints * COLO_POP_HEALTH || isBusy) return; + npc.state = COLO_POP; + npc.RemoveStatusEffects(); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.sprite.Play("Pop"); + npc.targetPosition = {}; +} + +// 004a3040 Colostomia: charges trailing clouds and puke, butt bombs, dives that leave puddles and farts, popping +// into a burrowing second phase. It ignores its own explosions, and its death browns the water. +void boss_colostomia_update(Entity_NPC& npc) +{ + float frictionScale = COLO_FRICTION; + colostomia_damage_update(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = COLO_IDLE; + npc.splatColor = COLO_SPLAT_COLOR; + npc.i1 = -1; + npc.i2 = 1; + npc.entityCollisionClass = ENTCOLL_NONE; + break; + case COLO_IDLE: + colostomia_idle_update(npc); + break; + case COLO_SURFACED: + colostomia_surfaced_update(npc); + break; + case COLO_DIVE: + colostomia_dive_update(npc); + break; + case COLO_CHARGE: + colostomia_charge_update(npc, frictionScale); + break; + case COLO_SPIT: + colostomia_spit_update(npc); + break; + case COLO_SPIT_SURFACED: + colostomia_spit_surfaced_update(npc); + break; + case COLO_FART: + colostomia_fart_update(npc); + break; + case COLO_POP: + colostomia_pop_update(npc); + break; + } + + if (npc.state == COLO_POP || npc.state == COLO_DIVE) colostomia_drip(npc); + bool isHeld = npc.state == COLO_POP || npc.state == COLO_SURFACED || npc.state == COLO_DIVE || + npc.state == COLO_SPIT_SURFACED || npc.state == COLO_FART; + if (isHeld && !vector_is_zero(npc.targetPosition)) npc.velocity = vector_sub(npc.targetPosition, npc.pos); + npc.friction *= frictionScale; + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + if (!npc.isDead) return; + + colostomia_water_brown(); + colostomia_clouds_fade(npc); +} diff --git a/src/boss_death.cpp b/src/boss_death.cpp index 5455234..c3e92ce 100644 --- a/src/boss_death.cpp +++ b/src/boss_death.cpp @@ -70,9 +70,6 @@ constexpr int ACHIEVEMENT_GEHENNA = 414; constexpr int ACHIEVEMENT_BRIMSTONE_BOMBS = 546; constexpr int EVENT_BABY_PLUM_KILLS = 493; -constexpr int MUSIC_JINGLE_BOSS_OVER = 83; -constexpr int MUSIC_JINGLE_BOSS_OVER2 = 97; -constexpr int MUSIC_JINGLE_BOSS_OVER3 = 42; constexpr int MUSIC_JINGLE_MINIBOSS_OVER = 92; constexpr int GAME_STATE_PERFECTION_SPAWNED = 45; @@ -125,6 +122,10 @@ constexpr float GFUEL_EARLY_FRAMES = 10; constexpr int GFUEL_DELAYED_COUNT = 2; constexpr uint32_t GFUEL_SEED_MASK = 0xfffff; constexpr uint32_t GFUEL_BABY_PLUM_SEED = 0xdedbb; +constexpr int GFUEL_DELAYED_SUBTYPE = 11; +constexpr std::string_view GFUEL_DELAYED_ANM2 = "gfx/promo/gfuel/effects/explosion_delayed.anm2"; +constexpr float GFUEL_DELAYED_SCALE = 1.5f; +constexpr float GFUEL_DEATH_BIG_SCALE = 2; // The blood explosion sizes a death's Explosion event bursts in, by the dying boss's size and shadow. constexpr int EXPLOSION_SMALL = 1; @@ -744,8 +745,9 @@ static void pile_chunks_spawn(Entity_NPC& npc, const NullFrame& bloodGuide) // Part of 006c4b30: a death animation with a blood guide bleeds along it (update_blood_guide_gibs), and its Explosion // event bursts the boss: a blood explosion at the guide sized to it (with a large one for a boss with large gibs, but -// Pin's tail), Mom's Heart's shots and The Pile's chunks, its shadow gone and its gibs thrown. G-Fuel's explosions -// are not reconstructed yet. +// Pin's tail), Mom's Heart's shots and The Pile's chunks, its shadow gone and its gibs thrown. With G-Fuel the blood +// is G-Fuel explosions instead, and past two (or for Baby Plum's G-Fuel seed) half the bosses blow a delayed one ten +// frames ahead that takes the place of the blood. void npc_blood_guide_update(Entity_NPC& npc, const NullFrame& bloodGuide) { npc.update_blood_guide_gibs(bloodGuide); @@ -760,15 +762,28 @@ void npc_blood_guide_update(Entity_NPC& npc, const NullFrame& bloodGuide) float next = (float)npc.sprite.animState.NextEventTrigger("Explosion"); float step = npc.sprite.playbackSpeed * npc.speedMultiplier; if (frame + GFUEL_EARLY_FRAMES <= next && next < frame + step + GFUEL_EARLY_FRAMES) - reconstruction_missing("Entity_NPC::Update 006c4b30: G-Fuel's delayed explosion"); + { + Entity* delayed = g_game->Spawn({.position = npc.pos, .subType = GFUEL_DELAYED_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, .seed = Random()}); + ANM2& sprite = delayed->sprite; + sprite.Load(GFUEL_DELAYED_ANM2, GRAPHICS_LOAD); + sprite.Play(sprite.GetDefaultAnimationName(), PLAY_UNFORCED); + sprite.isFlipX = random_below(2) == 0; + sprite.scale = vector_make(GFUEL_DELAYED_SCALE, GFUEL_DELAYED_SCALE); + delayed->Update(); + npc.AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + } } if (!npc.sprite.IsEventTriggered("Explosion")) return; - if (!npc.HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) + bool isLarge = npc.IsBoss() && (npc.config->gibFlags & GIB_FLAG_LARGE) && (npc.type != ENTITY_PIN || !npc.parent); + if (!npc.HasEntityFlags(FLAG_NO_BLOOD_SPLASH) && g_game->playerManager.GetGFuelCount() > 0) + { + gfuel_explosion_spawn(npc.pos, 1); + if (isLarge) gfuel_explosion_spawn(npc.pos, GFUEL_DEATH_BIG_SCALE); + } + else if (!npc.HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) { - if (g_game->playerManager.GetGFuelCount() > 0) - reconstruction_missing("Entity_NPC::Update 006c4b30: G-Fuel's death explosions"); - Entity* explosion = g_game->Spawn({.position = npc.pos, .subType = explosion_size_get(npc), .type = ENTITY_EFFECT, @@ -776,7 +791,7 @@ void npc_blood_guide_update(Entity_NPC& npc, const NullFrame& bloodGuide) .seed = Random()}); explosion->sprite.offset = bloodGuide.pos; explosion->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); - if (npc.IsBoss() && (npc.config->gibFlags & GIB_FLAG_LARGE) && (npc.type != ENTITY_PIN || !npc.parent)) + if (isLarge) { Entity* large = g_game->Spawn({.position = npc.pos, .spawner = &npc, diff --git a/src/boss_final.h b/src/boss_final.h new file mode 100644 index 0000000..719e9d2 --- /dev/null +++ b/src/boss_final.h @@ -0,0 +1,33 @@ +#pragma once + +#include "entity_npc.h" + +// Mother's forms (912), by variant: her two phases, the Dead Isaacs she raises, her worms and her balls. +enum MotherVariant +{ + MOTHER_PHASE_ONE = 0, + MOTHER_PHASE_TWO = 10, + MOTHER_DEAD_ISAAC = 20, + MOTHER_WORM = 30, + MOTHER_ORB = 100 +}; + +// The parts of Mother's first phase, by subtype: the body that runs the fight, her head and her two arms. +enum MotherPart +{ + MOTHER_PART_BODY, + MOTHER_PART_HEAD, + MOTHER_PART_LEFT_ARM, + MOTHER_PART_RIGHT_ARM +}; + +// Mother's balls by subtype: the big one she throws, and the medium and small ones it bursts into. +enum MotherOrbSize +{ + MOTHER_ORB_BIG, + MOTHER_ORB_MEDIUM, + MOTHER_ORB_SMALL +}; + +void boss_mother_update(Entity_NPC& npc); +void mother_render(Entity_NPC& npc, const Vector& offset); diff --git a/src/boss_gemini.cpp b/src/boss_gemini.cpp index 1ffdc5c..7523f5e 100644 --- a/src/boss_gemini.cpp +++ b/src/boss_gemini.cpp @@ -34,7 +34,6 @@ constexpr float WALK_THRESHOLD = 0.1f; constexpr float SPEED = 1.4f; constexpr float OVUM_SPEED = 1.6f; constexpr float PATH_SPEED_SCALE = 0.83f; -constexpr int PATH_MARKER = 900; constexpr int RAGE_ODDS = 60; constexpr int OVUM_RAGE_MASK = 3; constexpr float RAGE_ACCELERATION = 0.04f; @@ -163,7 +162,7 @@ static void twin_init(Entity_NPC& npc) // Walks after its target along the grid at a speed. static void twin_walk(Entity_NPC& npc, float speed) { - npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), speed * PATH_SPEED_SCALE, PATH_MARKER, DIRECT_PATH_FAR); + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), speed * PATH_SPEED_SCALE, GRID_PATH_FREED, DIRECT_PATH_FAR); } // Shows the idle head over the walk from its first frame. diff --git a/src/boss_horny_boys.cpp b/src/boss_horny_boys.cpp new file mode 100644 index 0000000..9b10830 --- /dev/null +++ b/src/boss_horny_boys.cpp @@ -0,0 +1,612 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "entity_tear.h" +#include "loot_list.h" +#include +#include + +// The Horny Boys' states: idle, teleporting up and down, their poof out and back, the juggle, the Loki dance and the +// fly summon. +constexpr int HORNY_IDLE = NPC_STATE_IDLE; +constexpr int HORNY_TELEPORT_UP = NPC_STATE_JUMP; +constexpr int HORNY_POOF_BACK = NPC_STATE_STOMP; +constexpr int HORNY_TELEPORT_DOWN = NPC_STATE_ATTACK; +constexpr int HORNY_POOF = NPC_STATE_ATTACK2; +constexpr int HORNY_JUGGLE = NPC_STATE_ATTACK3; +constexpr int HORNY_DANCE = NPC_STATE_ATTACK4; +constexpr int HORNY_SUMMON = NPC_STATE_SUMMON; + +// They keep three bombs (entityDeque) behind hidden layers 3 to 5, and take no damage from explosions but their +// players', their own kind's lasers or fire jets. +constexpr size_t HORNY_BOMBS = 3; +constexpr std::array HORNY_HIDDEN_LAYERS = {3, 4, 5}; +constexpr int HORNY_IDLE_FRAMES = 60; +constexpr int HORNY_MOVES = 4; +constexpr float HORNY_LOW_HEALTH = 0.33f; +constexpr float HORNY_FRICTION = 0.8f; +constexpr float HORNY_SLOW_FRICTION = 0.7f; + +// Their moves, in turn: the fly summon, the juggle, the dance, and a teleport or poof chain. +enum HornyMove +{ + HORNY_MOVE_SUMMON, + HORNY_MOVE_JUGGLE, + HORNY_MOVE_DANCE, + HORNY_MOVE_VANISH +}; +constexpr int HORNY_POOFS = 5; +constexpr int HORNY_TELEPORTS = 3; +constexpr int HORNY_LOW_EXTRA = 2; + +// Their bombs: a plain one most often, a hot one or a sad blood one, all lit for 35, thrown at 10 to 28 by the +// distance (100 to 300). A teleport leaves a brimstone bomb lit for 25, a poof a sad blood bomb about to go off. +constexpr int HORNY_PLAIN_WEIGHT = 6; +constexpr int HORNY_HOT_WEIGHT = 3; +constexpr int HORNY_SAD_WEIGHT = 1; +constexpr RNG HORNY_PICK_RNG = {0, 5, 9, 7}; +constexpr int HORNY_BOMB_FUSE = 35; +constexpr int HORNY_TELEPORT_FUSE = 25; +constexpr int HORNY_POOF_FUSE = 2; +constexpr float HORNY_THROW_NEAR = 100; +constexpr float HORNY_THROW_SPAN = 200; +constexpr float HORNY_THROW_SPEED = 10; +constexpr float HORNY_THROW_SPEED_RANGE = 18; +constexpr float HORNY_THROW_FALL = -4; +constexpr float HORNY_THROW_HEIGHT = -24; +constexpr float HORNY_POOF_DROP = 5; +constexpr float HORNY_DEATH_SPREAD = 10; +constexpr float HORNY_TELEPORT_FRAME = 20; + +// A teleport spot: of six random cells the farthest from them, 200 from the nearest player and not straight in line +// with it closer than 400, on a free path. +constexpr int HORNY_SPOT_TRIES = 6; +constexpr float HORNY_SPOT_MARGIN = 20; +constexpr float HORNY_SPOT_LINE = 20; +constexpr float HORNY_SPOT_FAR_SQUARED = 160000; +constexpr float HORNY_SPOT_NEAR_SQUARED = 40000; +constexpr int HORNY_SPOT_PATH = 500; + +// The juggle: bombs taken up on its second and third throws, and three thrown 60 and 30 degrees off the target and +// at it, in the order 1, 2, 0. +constexpr float HORNY_JUGGLE_DRIFT = 0.55f; +constexpr int HORNY_JUGGLE_THROWS = 3; +constexpr int HORNY_THROW_FIRST = 4; +constexpr float HORNY_THROW_TURN = 30; +constexpr std::array HORNY_THROW_ORDER = {1, 2, 0}; +constexpr std::array HORNY_JUGGLES = {"Juggle0", "Juggle1", "Juggle2"}; + +// The dance: kept 80 inside the walls, a pattern of shots on each beat and three fire wave lobs on each cough. +constexpr float HORNY_DANCE_MARGIN = 80; +constexpr float HORNY_DANCE_PULL = 0.01f; +constexpr float HORNY_DANCE_SPEED = 3; +constexpr std::array HORNY_DANCES = {"LokiDance2", "LokiDance3", "LokiDance4", "LokiDance5"}; +constexpr float HORNY_DANCE_FALL = -0.05f; +constexpr float HORNY_DIAGONAL = 7.071068f; +constexpr ColorMod HORNY_LOB_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 0.3f, 0}}; +constexpr float HORNY_LOB_SCALE = 2; +constexpr float HORNY_LOB_SPEED = 10; +constexpr int HORNY_LOBS = 3; +constexpr float HORNY_LOB_SLOWING = 0.2f; +constexpr float HORNY_LOB_FALL = -0.6f; +constexpr float HORNY_LOB_FALL_STEP = -0.12f; +constexpr float HORNY_LOB_RISE_SHARE = 0.7f; +constexpr float HORNY_LOB_RISE = -3; +constexpr float HORNY_LOB_RISE_STEP = -5; +constexpr float HORNY_AIM_LEAD = 0.1f; + +// The summon: a Boom Fly 50 below with three fly bombs about it, 120 degrees apart. +constexpr float HORNY_FLY_DROP = 50; +constexpr int HORNY_FLY_BOMBS = 3; +constexpr float HORNY_FLY_BOMB_STEP = 120; +constexpr float HORNY_FLY_BOMB_REACH = 10; +constexpr int HORNY_FLY_BOMB_VARIANT = 1; + +// The bomb in a slot (entityDeque), if any. +static EntityPtr& horny_bomb_slot(Entity_NPC& npc, size_t slot) +{ + return npc.entityDeque[slot]; +} + +// Explosions from other than a player, their own kind's lasers and fire jets do them no harm. +static bool horny_hit_is_ignored(Entity_NPC& npc, const DamageEvent& hit) +{ + const EntityRef& source = hit.source; + if (source.flags & (ENTITY_REF_CHARMED | ENTITY_REF_FRIENDLY)) return false; + bool isForeignBlast = + (hit.damageFlags & DAMAGE_EXPLOSION) && source.spawnerType != ENTITY_PLAYER && source.type != ENTITY_PLAYER; + bool isOwnLaser = (hit.damageFlags & DAMAGE_LASER) && source.type == npc.type; + bool isFireJet = + source.type == ENTITY_EFFECT && source.variant == EFFECT_FIRE_JET && source.spawnerType != ENTITY_PLAYER; + return isForeignBlast || isOwnLaser || isFireJet; +} + +// 004bcb30 A hidden bomb of a variant held in its first slot, replacing the one there. +static Entity_Bomb* horny_bomb_hold(Entity_NPC& npc, int variant) +{ + if (horny_bomb_slot(npc, 0)) horny_bomb_slot(npc, 0)->Remove(); + auto* bomb = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_BOMB, .variant = variant, .seed = Random()})); + bomb->isVisible = false; + bomb->entityCollisionClass = ENTCOLL_NONE; + bomb->entityGridCollisionClass = GRIDCOLL_NONE; + bomb->parent = &npc; + bomb->AddEntityFlags(FLAG_FREEZE); + horny_bomb_slot(npc, 0) = bomb; + return bomb; +} + +// 004bcc70 A hidden lit bomb in a slot, plain, hot or sad blood, replacing the one there. +static void horny_bomb_spawn(Entity_NPC& npc, size_t slot) +{ + if (horny_bomb_slot(npc, slot)) horny_bomb_slot(npc, slot)->Remove(); + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(BOMB_NORMAL, HORNY_PLAIN_WEIGHT); + picker.AddOutcomeWeight(BOMB_HOT, HORNY_HOT_WEIGHT); + picker.AddOutcomeWeight(BOMB_SAD_BLOOD, HORNY_SAD_WEIGHT); + RNG rng = HORNY_PICK_RNG; + rng._seed = Random() | 1; + int variant = picker.PickOutcome(rng); + TearFlags flags; + if (variant == BOMB_HOT) flags.set(TEAR_BURN); + else if (variant == BOMB_SAD_BLOOD) flags.set(TEAR_SAD_BOMB); + + auto* bomb = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_BOMB, .variant = variant, .seed = Random()})); + bomb->isVisible = false; + bomb->entityCollisionClass = ENTCOLL_NONE; + bomb->entityGridCollisionClass = GRIDCOLL_NONE; + bomb->parent = &npc; + bomb->AddEntityFlags(FLAG_FREEZE); + bomb->SetExplosionCountdown(HORNY_BOMB_FUSE); + bomb->tearFlags = flags; + bomb->isLoadCostumes = true; + bomb->Update(); + horny_bomb_slot(npc, slot) = bomb; +} + +// 004bc8c0 Throws the bomb in a slot at a spot, faster the farther it is, and empties the slot. The bomb thrown, if +// the slot held one. +static Entity_Bomb* horny_bomb_throw(Entity_NPC& npc, size_t slot, Vector spot) +{ + Entity* held = horny_bomb_slot(npc, slot).get(); + if (!held) return nullptr; + auto* bomb = held->type == ENTITY_BOMB ? static_cast(held) : nullptr; + if (bomb) + { + float reach = + std::clamp((vector_length(vector_sub(npc.pos, spot)) - HORNY_THROW_NEAR) / HORNY_THROW_SPAN, 0.0f, 1.0f); + Vector velocity = vector_scale(vector_normalized(vector_sub(spot, npc.pos)), + reach * HORNY_THROW_SPEED_RANGE + HORNY_THROW_SPEED); + bomb->parent = &npc; + bomb->entityCollisionClass = ENTCOLL_ALL; + bomb->isVisible = true; + bomb->fallSpeed = HORNY_THROW_FALL; + bomb->posOffset = vector_make(0, HORNY_THROW_HEIGHT); + bomb->pos = npc.pos; + bomb->ClearEntityFlags(FLAG_FREEZE); + bomb->velocity = velocity; + bomb->Update(); + } + horny_bomb_slot(npc, slot) = nullptr; + return bomb; +} + +// 004bc680 Picks a teleport spot (targetPosition). Whether one was found. +static bool horny_spot_pick(Entity_NPC& npc) +{ + Room& room = *g_game->room; + float best = 0; + npc.targetPosition = {}; + for (int i = 0; i < HORNY_SPOT_TRIES; i++) + { + int cell = room.GetGridIndex(room.GetRandomPosition(HORNY_SPOT_MARGIN)); + Vector spot = room.GetGridPosition(cell); + Vector fromPlayer = vector_sub(spot, game_nearest_player(spot)->pos); + float playerSquared = vector_length_squared(fromPlayer); + bool isOffLine = std::abs(fromPlayer.x) >= HORNY_SPOT_LINE && std::abs(fromPlayer.y) >= HORNY_SPOT_LINE; + if (!isOffLine && playerSquared < HORNY_SPOT_FAR_SQUARED) continue; + if (playerSquared < HORNY_SPOT_NEAR_SQUARED) continue; + if ((uint32_t)cell < ROOM_GRID_CELLS && room.gridPaths[cell] >= HORNY_SPOT_PATH) continue; + float fromSelf = vector_length_squared(vector_sub(npc.pos, spot)); + if (fromSelf <= best) continue; + npc.targetPosition = spot; + best = fromSelf; + } + return !vector_is_zero(npc.targetPosition); +} + +// Back to idle after a chain of moves. +static void horny_idle_return(Entity_NPC& npc) +{ + npc.sprite.Play("Idle"); + npc.state = HORNY_IDLE; + npc.stateFrame = 0; + npc.i1 = 0; +} + +// A poof where they vanish or appear. +static void horny_poof(Entity_NPC& npc) +{ + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()})->Update(); +} + +// Idle: wandering a second, then the next move in turn. +static void horny_idle_update(Entity_NPC& npc) +{ + npc.friction *= HORNY_FRICTION; + npc.pathfinder.MoveRandomlyBoss(STATUS_OBEYED); + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Idle"); + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame < HORNY_IDLE_FRAMES) return; + + bool isLow = npc.health < npc.maxHitPoints * HORNY_LOW_HEALTH; + switch (npc.i2) + { + case HORNY_MOVE_SUMMON: + npc.state = HORNY_SUMMON; + npc.sprite.Play("SpawnFly"); + npc.stateFrame = 0; + break; + case HORNY_MOVE_JUGGLE: + npc.state = HORNY_JUGGLE; + npc.sprite.Play("JuggleStart"); + npc.stateFrame = 0; + horny_bomb_spawn(npc, 0); + npc.i1 = 0; + break; + case HORNY_MOVE_DANCE: + npc.state = HORNY_DANCE; + npc.sprite.Play("LokiDance"); + npc.i1 = 0; + npc.stateFrame = 0; + break; + case HORNY_MOVE_VANISH: + if ((Random() & 1) == 0) + { + npc.state = HORNY_POOF; + npc.sprite.Play("BombPoof"); + npc.i1 = HORNY_POOFS + (isLow ? HORNY_LOW_EXTRA : 0); + } + else + { + npc.state = HORNY_TELEPORT_UP; + npc.sprite.Play("TeleportUp"); + npc.i1 = HORNY_TELEPORTS + (isLow ? HORNY_LOW_EXTRA : 0); + } + npc.stateFrame = 0; + break; + } + npc.i2 = (npc.i2 + 1) % HORNY_MOVES; +} + +// The teleport: up and gone, down at a far spot with a brimstone bomb thrown at the target, as many times as set. +static void horny_teleport_update(Entity_NPC& npc) +{ + npc.friction *= HORNY_SLOW_FRICTION; + if (npc.state == HORNY_TELEPORT_UP) + { + if (npc.sprite.IsEventTriggered("Sound")) + { + npc.shadowSize = 0; + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (npc.sprite.IsPlaying() || !horny_spot_pick(npc)) return; + npc.pos = npc.targetPosition; + npc.sprite.Play("TeleportDown"); + horny_bomb_hold(npc, BOMB_BRIMSTONE)->SetExplosionCountdown(HORNY_TELEPORT_FUSE); + npc.state = HORNY_TELEPORT_DOWN; + return; + } + + if (npc.sprite.IsEventTriggered("Sound")) + { + npc.shadowSize = npc.config->shadowSize; + npc.entityCollisionClass = ENTCOLL_ALL; + } + if (npc.sprite.IsEventTriggered("Shoot")) horny_bomb_throw(npc, 0, npc.GetPlayerTarget()->pos); + if (npc.sprite.IsPlaying()) return; + if (--npc.i1 <= 0) return horny_idle_return(npc); + npc.sprite.Play("TeleportUp"); + npc.sprite.SetFrame(HORNY_TELEPORT_FRAME); + npc.state = HORNY_TELEPORT_UP; + npc.stateFrame = 0; +} + +// The poof: a sad blood bomb dropped where they vanish, and back elsewhere, as many times as set. +static void horny_poof_update(Entity_NPC& npc) +{ + npc.friction *= HORNY_SLOW_FRICTION; + if (npc.state == HORNY_POOF_BACK) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.shadowSize = npc.config->shadowSize; + npc.entityCollisionClass = ENTCOLL_ALL; + } + if (npc.sprite.IsPlaying()) return; + if (--npc.i1 <= 0) return horny_idle_return(npc); + npc.sprite.Play("BombPoof"); + npc.state = HORNY_POOF; + npc.stateFrame = 0; + return; + } + + if (npc.sprite.IsEventTriggered("Sound")) + { + Entity_Bomb* bomb = horny_bomb_hold(npc, BOMB_SAD_BLOOD); + bomb->SetExplosionCountdown(HORNY_POOF_FUSE); + bomb->isLoadCostumes = true; + bomb->tearFlags.reset(); + bomb->tearFlags.set(TEAR_SAD_BOMB); + } + // The original writes the dropped bomb's fall without checking it threw one. + if (npc.sprite.IsEventTriggered("Shoot")) + if (Entity_Bomb* bomb = horny_bomb_throw(npc, 0, npc.pos)) bomb->fallSpeed = HORNY_POOF_DROP; + if (npc.entityCollisionClass != ENTCOLL_NONE && !npc.sprite.animState.GetNullFrame("OverlayFrame")) + { + npc.shadowSize = 0; + npc.entityCollisionClass = ENTCOLL_NONE; + horny_poof(npc); + } + if (npc.sprite.IsPlaying() || !horny_spot_pick(npc)) return; + npc.pos = npc.targetPosition; + npc.sprite.Play("BombPoofBack"); + npc.state = HORNY_POOF_BACK; + horny_poof(npc); +} + +// The juggle: drifting diagonally, taking up bombs on the second and third juggles and throwing all three about the +// target. +static void horny_juggle_update(Entity_NPC& npc) +{ + npc.friction *= HORNY_FRICTION; + Vector drift = vector_make(npc.velocity.x < 0 ? -HORNY_JUGGLE_DRIFT : HORNY_JUGGLE_DRIFT, + npc.velocity.y < 0 ? -HORNY_JUGGLE_DRIFT : HORNY_JUGGLE_DRIFT); + npc_push(npc, drift); + + if (npc.sprite.IsEventTriggered("Shoot")) + { + bool isPickup = npc.i1 == 1 || npc.i1 == 2; + if (isPickup && !horny_bomb_slot(npc, (size_t)npc.i1)) horny_bomb_spawn(npc, (size_t)npc.i1); + else if (npc.i1 >= HORNY_THROW_FIRST) + { + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + float turn = (float)(npc.i1 - HORNY_THROW_FIRST - 1) * HORNY_THROW_TURN - HORNY_THROW_TURN; + Vector spot = vector_add(vector_rotated(toward, turn), npc.pos); + Entity_Bomb* bomb = horny_bomb_throw(npc, (size_t)HORNY_THROW_ORDER[npc.i1 - HORNY_THROW_FIRST], spot); + if (bomb) bomb->pos = vector_make(npc.GetNullOffset("BombGuide").x + npc.pos.x, npc.pos.y); + npc.PlaySound(SOUND_CUTE_GRUNT, 1, 2, false, 1); + npc.i1++; + } + } + if (npc.sprite.IsPlaying()) return; + if (npc.i1 < HORNY_JUGGLE_THROWS) + { + npc.sprite.Play(HORNY_JUGGLES[npc.i1++]); + npc.PlaySound(SOUND_SCAMPER, 1, 2, false, 1); + } + else if (npc.i1 == HORNY_JUGGLE_THROWS) + { + npc.sprite.Play("JuggleThrow"); + npc.i1++; + } + else horny_idle_return(npc); +} + +// One beat of the dance: the shot pattern its count calls for, and a splash. +static void horny_dance_beat(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_CUTE_GRUNT, 1, 2, false, 1); + ProjectileParams params; + params.fallingAccelModifier = HORNY_DANCE_FALL; + auto fire = [&](float x, float y, ProjectilesMode mode) { + npc.FireProjectiles(npc.pos, vector_make(x, y), mode, params); + }; + switch (npc.stateFrame) + { + case 0: + case 2: + case 17: + case 19: + fire(10, 0, PROJECTILES_PLUS); + break; + case 1: + case 8: + case 18: + fire(10, 0, PROJECTILES_CROSS); + break; + case 3: + case 11: + fire(10, 0, PROJECTILES_EIGHT); + break; + case 4: + case 15: + params.circleAngle = PI_F / 12; + fire(10, 12, PROJECTILES_RING); + break; + case 5: + params.circleAngle = 0; + fire(8, 8, PROJECTILES_RING); + params.circleAngle = PI_F / 20; + fire(10, 8, PROJECTILES_RING); + params.circleAngle = -PI_F / 20; + fire(10, 8, PROJECTILES_RING); + break; + case 6: + case 7: + params.bulletFlags = npc.stateFrame == 6 ? PROJECTILE_CURVE_LEFT : PROJECTILE_CURVE_RIGHT; + params.circleAngle = 0; + fire(8, 10, PROJECTILES_RING); + break; + case 9: + fire(10, 0, PROJECTILES_THREE_WIDE); + fire(-10, 0, PROJECTILES_THREE_WIDE); + fire(0, 10, PROJECTILES_THREE_WIDE); + fire(0, -10, PROJECTILES_THREE_WIDE); + break; + case 10: + case 12: + { + ProjectilesMode mode = npc.stateFrame == 10 ? PROJECTILES_THREE_WIDE : PROJECTILES_FIVE; + fire(HORNY_DIAGONAL, HORNY_DIAGONAL, mode); + fire(-HORNY_DIAGONAL, HORNY_DIAGONAL, mode); + fire(HORNY_DIAGONAL, -HORNY_DIAGONAL, mode); + fire(-HORNY_DIAGONAL, -HORNY_DIAGONAL, mode); + break; + } + case 13: + params.circleAngle = 0; + fire(6, 10, PROJECTILES_RING); + break; + case 14: + fire(8, 0, PROJECTILES_EIGHT); + break; + case 16: + params.circleAngle = 0; + fire(8, 12, PROJECTILES_RING); + break; + } + blood_explosion_spawn(BLOOD_EXPLOSION_BURST, npc.pos, {}, COLOR_DEFAULT, {})->sprite.rotation = + random_unit() * FULL_TURN_DEGREES; + npc.stateFrame++; +} + +// The dance's cough: three fire wave lobs at the target's lead, each shorter and higher. +static void horny_dance_cough(Entity_NPC& npc) +{ + npc.PlaySound(SOUND_WHEEZY_COUGH, 1, 2, false, 1); + ProjectileParams params; + params.bulletFlags |= PROJECTILE_FIRE_WAVE; + params.scale = HORNY_LOB_SCALE; + params.color = HORNY_LOB_COLOR; + Entity* target = npc.GetPlayerTarget(); + float distance = vector_length(vector_sub(npc.pos, target->pos)); + Vector lead = vector_add(target->pos, vector_scale(target->velocity, HORNY_AIM_LEAD * distance)); + for (int i = 0; i < HORNY_LOBS; i++) + { + Entity_Projectile* lob = npc.FireBossProjectiles(1, lead, HORNY_LOB_SPEED, params); + lob->scale = HORNY_LOB_SCALE; + lob->velocity = vector_scale(lob->velocity, 1 - (float)i * HORNY_LOB_SLOWING); + lob->fallingAccel = lob->fallingAccel + HORNY_LOB_FALL + (float)i * HORNY_LOB_FALL_STEP; + lob->fallingSpeed = lob->fallingSpeed * HORNY_LOB_RISE_SHARE + HORNY_LOB_RISE + (float)i * HORNY_LOB_RISE_STEP; + } +} + +// The Loki dance: drawn off the walls, four dances of beats and coughs. +static void horny_dance_update(Entity_NPC& npc) +{ + npc.friction *= HORNY_SLOW_FRICTION; + Vector inside = g_game->room->GetClampedPositionImpl(npc.pos, HORNY_DANCE_MARGIN, HORNY_DANCE_MARGIN, + HORNY_DANCE_MARGIN, HORNY_DANCE_MARGIN); + Vector pull = vector_scale(vector_sub(inside, npc.pos), HORNY_DANCE_PULL); + if (vector_length_squared(pull) > HORNY_DANCE_SPEED * HORNY_DANCE_SPEED) + pull = vector_resized(pull, HORNY_DANCE_SPEED); + npc.velocity = vector_add(vector_scale(pull, npc.speedMultiplier), npc.velocity); + if (!npc.sprite.IsPlaying()) + { + if (npc.i1 < (int)HORNY_DANCES.size()) npc.sprite.Play(HORNY_DANCES[npc.i1++]); + else horny_idle_return(npc); + } + if (npc.sprite.IsEventTriggered("Shoot")) horny_dance_beat(npc); + if (npc.sprite.IsEventTriggered("Sound")) horny_dance_cough(npc); +} + +// The summon: a Boom Fly with three fly bombs circling it. +static void horny_summon_update(Entity_NPC& npc) +{ + npc.friction *= HORNY_SLOW_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_SUMMONSOUND, 1, 2, false, 1); + Vector spot = vector_make(npc.pos.x, npc.pos.y + HORNY_FLY_DROP); + Entity* fly = g_game->Spawn({.position = spot, .spawner = &npc, .type = ENTITY_BOOMFLY, .seed = Random()}); + fly->entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + fly->Update(); + for (int i = 0; i < HORNY_FLY_BOMBS; i++) + { + float angle = (float)i * HORNY_FLY_BOMB_STEP; + uint32_t seed = Random(); + Vector position = vector_add(vector_scale(vector_from_angle(angle), HORNY_FLY_BOMB_REACH), spot); + auto* bomb = static_cast(g_game->Spawn({.position = position, + .spawner = &npc, + .type = ENTITY_FLY_BOMB, + .variant = HORNY_FLY_BOMB_VARIANT, + .seed = seed})); + bomb->parent = fly; + bomb->ClearEntityFlags(FLAG_APPEAR); + bomb->v1.x = angle; + bomb->entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + bomb->Update(); + } + } + if (npc.sprite.IsPlaying()) return; + npc.stateFrame = 0; + npc.state = HORNY_IDLE; + npc.sprite.Play("Idle"); +} + +// Before its update, the hits it ignores are taken back. +static void horny_damage_filter(Entity_NPC& npc) +{ + for (DamageEvent& hit : npc.damageEvents) + { + if (!horny_hit_is_ignored(npc, hit)) continue; + npc.pendingDamage -= hit.damage; + hit.damage = 0; + } + npc.pendingDamage = std::max(npc.pendingDamage, 0.0f); +} + +// 004bd2a0 The Horny Boys: teleports and poofs leaving bombs, a juggle of three bombs, the Loki dance and a Boom Fly +// with fly bombs, in turn. Killed, they throw what bombs they hold. +void boss_horny_boys_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return horny_damage_filter(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = HORNY_IDLE; + npc.ClearDequeRefs(); + npc.entityDeque.resize(HORNY_BOMBS); + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.stateFrame = 0; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + for (int layer : HORNY_HIDDEN_LAYERS) npc.sprite.GetLayer(layer)->isVisible = false; + break; + case HORNY_IDLE: + horny_idle_update(npc); + break; + case HORNY_TELEPORT_UP: + case HORNY_TELEPORT_DOWN: + horny_teleport_update(npc); + break; + case HORNY_POOF: + case HORNY_POOF_BACK: + horny_poof_update(npc); + break; + case HORNY_JUGGLE: + horny_juggle_update(npc); + break; + case HORNY_DANCE: + horny_dance_update(npc); + break; + case HORNY_SUMMON: + horny_summon_update(npc); + break; + } + if (!npc.isDead) return; + + for (size_t slot = 0; slot < HORNY_BOMBS; slot++) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector spot = vector_make(std::cos(angle) * HORNY_DEATH_SPREAD + npc.pos.x, + std::sin(angle) * HORNY_DEATH_SPREAD + npc.pos.y); + horny_bomb_throw(npc, slot, spot); + } +} diff --git a/src/boss_intro.cpp b/src/boss_intro.cpp index 6431d50..f0d81ea 100644 --- a/src/boss_intro.cpp +++ b/src/boss_intro.cpp @@ -33,6 +33,7 @@ constexpr int LAYER_OVERLAY = 11; constexpr int LAYER_PLAYER_PORTRAIT_ALT = 12; constexpr int LAYER_BOSS_SHADOW = 13; constexpr int LAYER_SECOND_BOSS_SHADOW = 14; +constexpr int LAYER_MOTHER_PORTRAIT = 24; constexpr unsigned int DOGMA_OVERLAY_FLAGS = 0x60; constexpr std::array PLAYER_LAYERS_HIDDEN = {5, 12, 15, 18, 21, 16, 19, 22, 17, 20, 23}; @@ -240,8 +241,7 @@ void RoomTransition::StartBossIntro(uint32_t bossId1, uint32_t bossId2) versus.GetLayer(LAYER_BOSS_SPOT)->isVisible = bossId1 != BOSS_MEGA_SATAN; } if (bossId1 == BOSS_MOTHER) - reconstruction_missing("RoomTransition::StartBossIntro 0082f1c0: Mother's " - "layer 24 (FUN_0069d250)"); + versus.ReplaceSpritesheet(LAYER_MOTHER_PORTRAIT, boss_portrait_get(boss_config_get(bossId1))); versus.LoadGraphics(); if (isDogma) for (int layer : {LAYER_BACKGROUND, LAYER_BOSS_SHADOW, LAYER_SECOND_BOSS_SHADOW}) diff --git a/src/boss_min_min.cpp b/src/boss_min_min.cpp index c8c97e6..325495a 100644 --- a/src/boss_min_min.cpp +++ b/src/boss_min_min.cpp @@ -771,7 +771,7 @@ static void min_min_turn_check(Entity_NPC& npc) // 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) + for (Entity* entity : entities_live(g_game->room->entityList.updateEL)) { Entity* parent = entity->parent.get(); if (parent != &npc && (!parent || parent->parent.get() != &npc)) continue; diff --git a/src/boss_mother.cpp b/src/boss_mother.cpp new file mode 100644 index 0000000..d770b50 --- /dev/null +++ b/src/boss_mother.cpp @@ -0,0 +1,2501 @@ +#include "boss_final.h" +#include "boss_ai.h" +#include "capsule.h" +#include "entity_config.h" +#include "entity_combat.h" +#include "entity_effect.h" +#include "entity_effect_combat.h" +#include "entity_familiar.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "grid_entity.h" +#include "grid_entity_trap_door.h" +#include "manager.h" +#include "npc_alt.h" +#include "npc_basement.h" +#include "player_manager.h" +#include "room_grid.h" +#include + +static void mother_orb_burst(Entity_NPC& npc); + +// Mother's first phase: her states, the shared bounds she works within, and her parts' places about her body. +constexpr int MOTHER_IDLE = NPC_STATE_IDLE; +constexpr int MOTHER_STUNNED = NPC_STATE_SUICIDE; +constexpr int MOTHER_KNIFE = NPC_STATE_ATTACK; +constexpr int MOTHER_POUND = NPC_STATE_ATTACK2; +constexpr int MOTHER_WRIST = NPC_STATE_ATTACK3; +constexpr int MOTHER_SCRAPE = NPC_STATE_ATTACK4; +constexpr int MOTHER_CRUSH = NPC_STATE_ATTACK5; +constexpr int MOTHER_SUMMON = NPC_STATE_SUMMON; +constexpr int MOTHER_TRANSITION = NPC_STATE_SPECIAL; +constexpr int MOTHER_FISTULA = NPC_STATE_DEATH + 1; + +constexpr float MOTHER_WALL_DEPTH = 40; +constexpr float MOTHER_RISE = 80; +constexpr int MOTHER_RENDER_Z = 8000; +constexpr float MOTHER_PLAYER_START = 120; +constexpr float MOTHER_WALL_X = 80; +constexpr float MOTHER_CAMERA_DEPTH = 0.43f; +static const Vector MOTHER_SHOT_DROP = vector_make(0, 60); +constexpr std::string_view MOTHER_WALL_ANM2 = "gfx/backdrop/07x_corpse_bottomwall.anm2"; +constexpr std::array MOTHER_WALL_SHADE_BLEND = {0, 0, 2, 1, 1}; +static const std::array MOTHER_PART_OFFSETS = {vector_make(0, 0), vector_make(0, -40), vector_make(-180, 10), + vector_make(180, 10)}; +constexpr float MOTHER_ARM_SIZE = 70; +constexpr uint64_t MOTHER_PART_FLAGS = + FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_BOSSDEATH_TRIGGERED | FLAG_DONT_COUNT_BOSS_HP; +constexpr uint64_t MOTHER_SUMMON_FLAGS = MOTHER_PART_FLAGS | FLAG_HIDE_HP_BAR | FLAG_NO_PLAYER_CONTROL; + +// Her rests: 50 frames after most attacks, 90 after a wrist attack, and her summons once every 1620 frames from 1140. +constexpr int MOTHER_REST = 50; +constexpr int MOTHER_WRIST_REST = 90; +constexpr int MOTHER_SUMMON_EVERY = 1620; +constexpr int MOTHER_SUMMON_FIRST = 1140; +constexpr uint32_t MOTHER_FISTULA_ODDS = 6; +constexpr int MOTHER_FISTULA_AFTER = 2; +constexpr uint32_t MOTHER_WRIST_ODDS = 3; +constexpr int MOTHER_FEW_ENEMIES = 4; +constexpr int MOTHER_MANY_ENEMIES = 15; + +// The ball she bats back: a scrape for one rolling slower than 3, a pound for one faster, swung when it would pass 13 +// (15 when fast) frames ahead of a line 80 below her, or 140 higher once it is heavy. +constexpr float BALL_SLOW_SPEED = 3; +constexpr float BALL_SWING_AHEAD = 13; +constexpr float BALL_SWING_AHEAD_FAST = 15; +constexpr float BALL_SWING_LINE = 80; +constexpr float BALL_SWING_RAISE = 140; +constexpr float BALL_HEAVY = 6; +constexpr float BALL_POUND_PULL = 10; +constexpr float BALL_BAT_SPEED = 16; +constexpr float BALL_BAT_LINE = 150; +constexpr float BALL_BAT_SPEEDUP = 0.15f; +constexpr float BALL_BAT_TOP_SPEED = 3; +constexpr float BALL_HIT_LINE = 100; +constexpr float BALL_THROW_SPEED = 16; +constexpr float BALL_THROW_PUSH = 2; + +// The pound: a fan of 13 at 80 degrees from her fist toward the room's middle, maggots on the odd ones and shots on the +// even ones. +constexpr int POUND_FAN_HALF = 6; +constexpr float POUND_FAN_DEGREES = 80; +constexpr float POUND_MAGGOT_SPEED = 3; +constexpr float POUND_MAGGOT_SPEED_RANGE = 6; +constexpr float POUND_MAGGOT_HEIGHT = -15; +constexpr float POUND_MAGGOT_RISE = -8; +constexpr float POUND_SHOT_SPEED = 14; +constexpr float POUND_SHOT_FALL = -0.04f; +constexpr float POUND_SHOT_SCALE = 1.4f; +constexpr int POUND_SHAKE = 12; +constexpr float MOTHER_SHOCKWAVE_AMPLITUDE = 0.04f; +constexpr float MOTHER_SHOCKWAVE_SPEED = 0.025f; +constexpr int SHOCKWAVE_DURATION = 13; + +// The knife thrown from her hand, falling at 15. +static const Vector KNIFE_VELOCITY = vector_make(0, 15); +constexpr int MOTHER_KNIFE_SHAKE = 8; +constexpr float KNIFE_SLIDE_VOLUME = 1.2f; +constexpr float KNIFE_SLIDE_PITCH = 0.8f; + +// The wrist: eight worms fanned from 30 to 150 degrees, each weaving 8 frames longer, and the blood of the burst. +constexpr int WRIST_WORMS = 8; +constexpr float WRIST_FAN_FIRST = 30; +constexpr float WRIST_FAN_SPAN = 120; +constexpr float WRIST_WORM_REACH = 4; +constexpr float WRIST_WORM_SPEED = 6; +constexpr float WRIST_WORM_SPEED_RANGE = 4; +constexpr int WRIST_WORM_WEAVE = 15; +constexpr int WRIST_WORM_WEAVE_STEP = 8; +constexpr float WRIST_WORM_SCALE = 0.7f; +constexpr float WRIST_WORM_SCALE_RANGE = 0.2f; +static const Vector WRIST_BLOOD_OFFSET = vector_make(0, -20); +static const Vector WRIST_GIB_VELOCITY = vector_make(0, 6); +constexpr int WRIST_GIBS = 6; +constexpr float GIB_SPREAD = 40; +constexpr float WRIST_GIB_SPEED = 2.5f; +constexpr uint32_t GIB_BLOOD_AND_BONE = 5; +constexpr uint32_t GIB_BLOOD = 1; + +// The scrape hurts what its null touches: players and familiars by 2, others by 100, all pushed away at 10. +constexpr int SCRAPE_SHAKE = 8; +constexpr float SCRAPE_PUSH = 10; +constexpr float SCRAPE_PLAYER_DAMAGE = 2; +constexpr float SCRAPE_DAMAGE = 100; +constexpr int MOTHER_HIT_COUNTDOWN = 30; +constexpr float SCRAPE_ISAAC_REACH = 140; + +// The crush: her hands sweep down 20 a frame from the Shoot, killing the Dead Isaacs above the sweep every other frame, +// each spitting its head, and she rests once 45 frames are past. +constexpr float CRUSH_SPEED = 20; +constexpr float CRUSH_HEAD_HEIGHT = 8; +constexpr float CRUSH_HEAD_FALL = -3; +constexpr float CRUSH_HEAD_FALL_RANGE = 10; +constexpr float CRUSH_HEAD_FALL_STEP = 3; +constexpr float CRUSH_HEAD_ACCEL = 1.5f; +constexpr int CRUSH_FRAMES = 45; + +// The summon: the laser holds 120 frames, rumbling the floor; the Dead Isaacs rise every 20 frames, half a frame +// sooner each, down to 6, until 35 are up. +constexpr int MOTHER_SUMMON_FRAMES = 120; +constexpr int SUMMON_SHAKE = 4; +constexpr float SUMMON_DUST_MARGIN = 20; +constexpr float SUMMON_DUST_DEPTH = 40; +constexpr float MOTHER_PARTICLE_SPEED = 6; +constexpr uint32_t SUMMON_SPLAT_ODDS = 3; +constexpr float ISAAC_RISE_FIRST = 30; +constexpr float ISAAC_RISE_EVERY = 20; +constexpr float ISAAC_RISE_SOONER = 0.5f; +constexpr float ISAAC_RISE_FASTEST = 6; +constexpr int ISAAC_RISE_TRIES = 10; +constexpr int ISAAC_RISE_LAST = 34; +constexpr int GRID_PATH_FREE = 101; +constexpr float ISAAC_RISE_STOP = 40; + +// The transition: the head and an arm burst, the laser fires down, then the walls fall row by row as she becomes her +// second phase 60 below and charges down at 16. +constexpr int TRANSITION_GIBS = 9; +constexpr float TRANSITION_LASER_DROP = 10; +constexpr float TRANSITION_LASER_ANGLE = 90; +constexpr int TRANSITION_LASER_TIMEOUT = 47; +constexpr int TRANSITION_LASER_VARIANT = 6; +constexpr ColorMod TRANSITION_LASER_COLOR = {{1, 1, 1, 1}, {2, 2.2f, 1, 1}, {0, 0, 0}}; +constexpr float TRANSITION_LASER_DEPTH = 1000; +constexpr float TRANSITION_HEAD_DEPTH = 100; +static const Vector TRANSITION_CHARGE = vector_make(0, 16); +static const Vector TRANSITION_OFFSET = vector_make(0, 60); +static const Vector MOTHER_CAMERA_LEAD = vector_make(0, 100); +constexpr float WALL_SPLAT_SCALE = 2; +constexpr int WALL_GIBS = 2; +constexpr float MOTHER_WALL_STEP = 40; +constexpr float MOTHER_WALL_SPLAT_REACH = 40; + +// The transition from death: blood runs from the walls, and the parts are kept alive while the second phase comes. +constexpr int TRANSITION_BLOOD_FRAMES = 20; +constexpr int TRANSITION_BLOOD_COUNT = 6; +constexpr float TRANSITION_HEALTH = 1e-05f; + +// Her second phase: states, the charge's push and edges, its spray spots and the jump's landing. +constexpr int MOTHER2_IDLE = NPC_STATE_IDLE; +constexpr int MOTHER2_CHARGE = NPC_STATE_JUMP; +constexpr int MOTHER2_LAND = NPC_STATE_STOMP; +constexpr int MOTHER2_SPIN = NPC_STATE_ATTACK; +constexpr int MOTHER2_SWIPE = NPC_STATE_ATTACK2; +constexpr int MOTHER2_SUCK = NPC_STATE_ATTACK3; +constexpr int MOTHER2_SPIT = NPC_STATE_ATTACK4; +constexpr int MOTHER2_JUMP = NPC_STATE_ATTACK5; +constexpr int MOTHER2_ARRIVE = NPC_STATE_SPECIAL; + +constexpr uint32_t MOTHER2_ATTACK_ODDS = 15; +constexpr int MOTHER2_ATTACK_LATE = -60; +constexpr int MOTHER2_LONG_REST = 240; +constexpr int MOTHER2_SHORT_REST = 90; +constexpr float MOTHER2_PATH_SPEED = 0.2f; +constexpr int MOTHER2_PATH_MARKER = 900; + +constexpr float MOTHER_CHARGE_FRICTION = 0.85f; +constexpr float MOTHER_CHARGE_STEER = 0.8f; +constexpr float MOTHER_CHARGE_PUSH = 4.5f; +constexpr int CHARGE_SHAKE = 3; +constexpr float MOTHER_CHARGE_FADE = 0.005f; +constexpr float CHARGE_BOUNCE = 0.95f; +constexpr float MOTHER_CHARGE_EDGE = 20; +constexpr float CHARGE_OUT = 400; +constexpr float CHARGE_RETURN = 90; +constexpr float CHARGE_RETURN_SPEED = -8; +constexpr float CHARGE_SPLAT_REACH = 20; +constexpr float CHARGE_SPLAT_SPREAD = 0.06f; +constexpr float CHARGE_SPLAT_SPEED = 3; +constexpr float CHARGE_SPLAT_RISE = -5; +constexpr float CHARGE_SPLAT_RISE_RANGE = 10; +constexpr uint32_t CHARGE_DUST_ODDS = 6; +constexpr int CHARGE_DUST = 2; +static const std::array CHARGE_SPOTS = {vector_make(-100, 100), vector_make(-50, 114), vector_make(0, 120), + vector_make(50, 114), vector_make(100, 100)}; +constexpr int SPLAT_BIG = 4; +constexpr int SPLAT_MEDIUM = 2; + +constexpr int LAND_SHAKE = 18; +constexpr float LAND_POOF_SCALE = 2; +constexpr int LAND_POOF_SUBTYPE = 3; +constexpr int LAND_CRACKS = 16; +constexpr float LAND_CRACK_REACH = 80; +constexpr int LAND_CRACK_SUBTYPE = 2; +constexpr float LAND_CRACK_WIDE = 6; +constexpr float LAND_CRACK_NARROW = 4; + +// The spin: 210 frames of gore and three arms of shots every 4 frames turning 0.132 turns a frame, four of 4 a frame +// apart, or every 12th three slower of 2.8 that change later. +constexpr float SPIN_FRICTION = 0.7f; +constexpr int MOTHER_SPIN_FRAMES = 209; +constexpr int SPIN_GORE_EVERY = 3; +constexpr float SPIN_GORE_SPEED = 3; +constexpr float SPIN_SPLAT_REACH = 70; +constexpr float SPIN_SPLAT_SPEED = 4; +constexpr float SPIN_SPLAT_SPEED_RANGE = 8; +static const Vector SPIN_SPLAT_OFFSET = vector_make(0, -50); +constexpr float SPLAT_DEPTH = 10; +constexpr int SPIN_SHOT_EVERY = 4; +constexpr int SPIN_WIGGLE_EVERY = 8; +constexpr int SPIN_SLOW_EVERY = 12; +constexpr ColorMod SPIN_SHOT_COLOR = {{1, 1, 1, 1}, {4, 3.5f, 3.2f, 1}, {0, 0, 0}}; +constexpr float SPIN_SHOT_FALL = -0.095f; +constexpr int SPIN_SHOT_CHANGE = 10; +constexpr int SPIN_SHOT_CHANGE_SLOW = 40; +constexpr float SPIN_SHOT_ACCEL = 1.03f; +constexpr float SPIN_SHOT_ACCEL_SLOW = 1.05f; +constexpr float SPIN_SHOT_SCALE = 0.7f; +constexpr float SPIN_SHOT_SCALE_RANGE = 0.2f; +constexpr float SPIN_SHOT_SCALE_SLOW = 0.7f; +constexpr float SPIN_SHOT_SCALE_LAST = 0.6f; +constexpr float SPIN_SHOT_SCALE_STEP = 1.25f; +constexpr int SPIN_SHOT_WIGGLE = 30; +constexpr float SPIN_SHOT_SPEED = 4; +constexpr float SPIN_SHOT_SPEED_SLOW = 2.8f; +constexpr float SPIN_SHOTS = 4; +constexpr float SPIN_SHOTS_SLOW = 3; +constexpr int SPIN_ARMS = 3; +constexpr float SPIN_ARM_STEP = 120; +constexpr float MOTHER_SPIN_TURN = 0.132f; +constexpr float SPIN_ARM_REACH = 60; +constexpr float SPIN_WAVE = 3; +constexpr float SPIN_WAVE_PERIOD = 30; +constexpr float SPIN_ADVANCE = 1.5f; +constexpr float SPIN_VOLUME_STEP = 0.15f; + +// The swipes: five of them, tracers lining a wall 80 apart, 20 outside it. +constexpr std::array SWIPE_ANIMATIONS = {"SwipeLeft", "SwipeUp", "SwipeRight", "SwipeDown"}; +constexpr float SWIPE_FRICTION = 0.7f; +constexpr int SWIPES = 5; +constexpr float TRACER_SPACING = 80; +constexpr float TRACER_OUTSIDE = 20; +constexpr int TRACER_WARN = 2; +constexpr int TRACER_RUSH = 3; +constexpr float SWIPE_BLOOD_SPEED = 2; +constexpr float SWIPE_BLOOD_SPEED_RANGE = 3; +constexpr float SWIPE_GIB_REACH = 40; +constexpr float SWIPE_GIB_SPEED = 4; +constexpr float SWIPE_GIB_SPEED_RANGE = 4; +constexpr int SWIPE_GIBS = 3; +constexpr float SWIPE_LUNGE = 10; +constexpr int SWIPE_SHAKE = 7; + +// The suction: drifting to the room's middle, she draws in what lies within a narrow cone ahead, swallowing it +// within 20, raising attract effects every 3 frames and rubble falling in from 31 to 119, for 180 frames. +constexpr float SUCK_FRICTION = 0.6f; +constexpr float SUCK_DRIFT = 0.01f; +constexpr float SUCK_DRIFT_MAX = 0.8f; +constexpr float SUCK_TURN = 2; +constexpr int SUCK_SHAKE = 4; +constexpr float SUCK_CONE = 0.9f; +constexpr float SUCK_PULL = 2; +constexpr float SUCK_PULL_FALLOFF = 0.0001f; +constexpr float SUCK_PLAYER_PULL = 1.4f; +constexpr float SUCK_PLAYER_PULL_MAX = 0.8f; +constexpr float SUCK_TEAR_PULL = 0.7f; +constexpr float SUCK_PUSH = 0.2f; +constexpr float SUCK_SWALLOW_SQUARED = 400; +constexpr int SUCK_EFFECT_EVERY = 3; +constexpr float SUCK_EFFECT_REACH = 800; +static const Vector SUCK_EFFECT_OFFSET = vector_make(0, -24); +constexpr ColorMod SUCK_EFFECT_COLOR = {{0.5f, 0.6f, 0.3f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float SUCK_EFFECT_SPREAD = 60; +constexpr int SUCK_RUBBLE_FIRST = 31; +constexpr int SUCK_RUBBLE_LAST = 119; +constexpr int SUCK_FRAMES = 179; +constexpr float SUCK_RUBBLE_SPREAD = 40; +constexpr float SUCK_RUBBLE_NEAR = 280; +constexpr float SUCK_RUBBLE_RANGE = 400; +constexpr float SUCK_RUBBLE_MARGIN = 10; +constexpr int SUCK_RUBBLE_FADE = 30; +constexpr float SUCK_RUBBLE_DEPTH = 120; +constexpr float SUCK_RUBBLE_FALL = -0.05f; +constexpr float SUCK_RUBBLE_HOMING = 0.3f; +constexpr float SUCK_RUBBLE_FRICTION = 0.88f; +constexpr float SUCK_VOLUME_STEP = 0.0667f; + +// The spit: one broccoli shot at 14 and a recoil of 15. +constexpr float MOTHER_SPIT_FRICTION = 0.7f; +static const Vector SPIT_CLOUD_OFFSET = vector_make(0, -15); +constexpr float MOTHER_SPIT_HEIGHT = -23; +constexpr float SPIT_FALL = -0.08f; +constexpr float MOTHER_SPIT_SPEED = 14; +constexpr float SPIT_HOMING = 0.5f; +constexpr int SPIT_SUBTYPE = 106; +constexpr ColorMod SPIT_BLOOD_COLOR = {{1, 1, 1, 1}, {2, 4, 1, 1}, {0, 0, 0}}; +static const Vector SPIT_BLOOD_OFFSET = vector_make(0, -20); +constexpr float MOTHER_SPIT_RECOIL = 15; + +// The jump: she leaps off screen, comes back 90 above the room on the player's side 140 in from a wall, and charges. +constexpr float MOTHER_JUMP_FRICTION = 0.6f; +constexpr float JUMP_SOUND_VOLUME = 3; +constexpr int JUMP_AWAY = 30; +constexpr int JUMP_FRAMES = 60; +constexpr float JUMP_ABOVE = 90; +constexpr float JUMP_INSET = 140; +static const Vector JUMP_CHARGE = vector_make(0, 8); +constexpr float JUMP_WIDEN = 1.18f; +constexpr float ARRIVE_FRICTION = 0.9f; +constexpr int ARRIVE_FRAMES = 30; + +// The burst of a slam: 12 rocks and 12 green splats thrown back within 45 degrees. +constexpr float SLAM_MARGIN = 10; +constexpr int MOTHER_SLAM_BURST_SHAKE = 12; +constexpr float SLAM_SPLAT_RISE = -10; +constexpr float SLAM_SPLAT_RISE_RANGE = 20; +constexpr int SLAM_PIECES = 12; +constexpr float SLAM_SPREAD = 90; +constexpr float SLAM_ROCK_SPEED = 20; +constexpr float SLAM_ROCK_SPEED_RANGE = 10; +constexpr float SLAM_SPLAT_SPEED = 5; +constexpr float SLAM_SPLAT_SPEED_RANGE = 25; +constexpr float MOTHER_SLAM_REACH = 5; +constexpr uint32_t SLAM_SMALL_SPLAT_ODDS = 5; + +// Her worms: six to eight segments of tinted shots that weave for their timer, then home in for 30 frames, up to 14. +constexpr int WORM_SEGMENTS_MIN = 6; +constexpr uint32_t WORM_SEGMENTS_RANGE = 3; +constexpr uint64_t WORM_SEGMENT_FLAGS = PROJECTILE_NO_WALL_COLLIDE; +constexpr float WORM_SEGMENT_FALL = -0.098f; +constexpr float WORM_HEAD_SCALE = 0.6f; +constexpr float WORM_SEGMENT_SCALE = 1.7f; +constexpr float WORM_SEGMENT_TAPER = 0.1f; +constexpr float WORM_SCALE_RANGE = 0.2f; +constexpr int WORM_DELAY_FLOOR = -100; +constexpr float WORM_WEAVE_RAMP = 15; +constexpr float WORM_JITTER = 2; +constexpr float WORM_WEAVE_SPEED = 0.1f; +constexpr float WORM_WEAVE_DEGREES = 60; +constexpr float WORM_WEAVE_SLOWDOWN = 0.88f; +constexpr float WORM_WEAVE_RANGE = 0.120000005f; +constexpr float WORM_MIN_SPEED = 5; +constexpr float WORM_HOME_RAMP = -30; +constexpr int WORM_HOME_FRAMES = -30; +constexpr float WORM_SPEEDUP = 0.100000024f; +constexpr float WORM_MAX_SPEED = 14; +constexpr int WORM_LEAVE_FRAMES = -60; +constexpr float WORM_ROOM_MARGIN = -10; +constexpr size_t WORM_TRAIL = 64; +constexpr float WORM_LINK = 10; + +// Her balls: the big one darkens for 6 frames as it comes, rolls with a sickly pulse and bounces off walls (a ring of +// shots off the floor); the smaller ones last their timer and trail blood. +constexpr ColorMod ORB_DARK = {{0.03f, 0.03f, 0.03f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int ORB_DARK_FRAMES = 6; +constexpr float ORB_BIG_RISE = -35; +constexpr float ORB_MEDIUM_RISE = -18; +constexpr float ORB_SMALL_RISE = -12; +constexpr float ORB_START_SCALE = 0.8f; +constexpr float ORB_COLLISION_SCALE = 0.3f; +constexpr int ORB_MEDIUM_TIMER = 3000; +constexpr int ORB_SMALL_TIMER = 30; +constexpr float MOTHER_ORB_DEPTH = 60; +constexpr float ORB_PUSH = 10; +constexpr float ORB_ENEMY_DAMAGE = 40; +constexpr float ORB_SPIN = 1.5f; +constexpr float ORB_SPIN_MAX = 32; +constexpr float ORB_GROWTH = 0.04f; +constexpr float ORB_FRICTION = 0.85f; +constexpr float ORB_PULSE_SPEED = 2; +constexpr float ORB_PULSE_FAST = 6; +constexpr float ORB_PULSE_PERIOD = 30; +constexpr float ORB_PULSE_ROLL = 2; +constexpr float ORB_PULSE_RED = 0.25f; +constexpr float ORB_PULSE_GREEN = 0.2f; +constexpr float ORB_PULSE_BLUE = 0.3f; +constexpr float ORB_GLOW_RED = 0.35f; +constexpr float ORB_GLOW_GREEN = 0.5f; +constexpr float ORB_GLOW_BLUE = 0.25f; +constexpr float ORB_STEER = 3; +constexpr float ORB_STEER_LIMIT = 0.2f; +constexpr float ORB_FLOOR_NORMAL = 0.8f; +constexpr float ORB_MIN_TILT = 0.3f; +constexpr int ORB_FLOOR_SHAKE = 8; +constexpr int ORB_WALL_SHAKE = 4; +constexpr float ORB_BOUNCE_VOLUME = 0.8f; +static const Vector ORB_RING_BIG = vector_make(8, 6); +static const Vector ORB_RING_SMALL = vector_make(6, 6); +constexpr float ORB_RING_FALL = -0.08f; +constexpr float ORB_RING_BIG_SCALE = 2; +constexpr float ORB_RING_SMALL_SCALE = 1.5f; +constexpr float ORB_SMALL_SLOWDOWN = 0.3f; +constexpr float ORB_SMALL_SLOWDOWN_FRAMES = 60; +constexpr ColorMod ORB_TRAIL_COLOR = {{0, 0, 0, 0.87f}, {0, 0, 0, 0}, {0.5493272f, 0.6969627f, 0.45951557f}}; +constexpr float ORB_TRAIL_DEPTH = -50; +constexpr float ORB_TRAIL_BIG_REACH = 30; +constexpr float ORB_TRAIL_BIG_SCALE = 2; +constexpr float ORB_TRAIL_BIG_PLAYBACK = 0.5f; +constexpr float ORB_TRAIL_MEDIUM_REACH = 13; +constexpr float ORB_TRAIL_MEDIUM_SCALE = 1.2f; +constexpr float ORB_TRAIL_MEDIUM_PLAYBACK = 0.7f; +constexpr float ORB_TRAIL_SMALL_REACH = 8; + +// The burst: eight medium balls (six small from a medium) out along clear lines, and the hurt it deals Mother when she +// broke it. +constexpr int ORB_BIG_PIECES = 8; +constexpr float ORB_BIG_PIECE_STEP = 45; +constexpr float ORB_BIG_PIECE_REACH = 160; +constexpr int ORB_MEDIUM_PIECES = 6; +constexpr float ORB_MEDIUM_PIECE_STEP = 60; +constexpr float ORB_MEDIUM_PIECE_REACH = 120; +constexpr float ORB_PIECE_SPLAT_REACH = 4; +constexpr float ORB_PIECE_SPLAT_SPEED = 3; +constexpr float ORB_PIECE_REACH = 6; +constexpr float ORB_PIECE_SPEED = 10; +constexpr float ORB_MOTHER_SPREAD = 1.5f; +constexpr float ORB_BIG_MOTHER_DAMAGE = 400; +constexpr float ORB_MEDIUM_MOTHER_DAMAGE = 60; +constexpr float ORB_SMALL_MOTHER_DAMAGE = 30; +constexpr int ORB_SMALL_HELD = 4; +constexpr int ORB_MEDIUM_HELD_MIN = 8; +constexpr uint32_t ORB_MEDIUM_HELD_RANGE = 6; +constexpr int ORB_BIG_GIBS = 10; +constexpr float ORB_GIB_SPEED = 3; +constexpr int ORB_BIG_SHAKE = 18; +constexpr int ORB_MEDIUM_SHAKE = 10; +constexpr float ORB_MAGGOT_HEIGHT = -15; +constexpr float ORB_MAGGOT_RISE = -8; +constexpr float ORB_MAGGOT_RISE_RANGE = 4; + +// Sets a sprite's scale on both axes. +static void sprite_scale_set(Entity& entity, float scale) +{ + entity.sprite.scale = vector_make(scale, scale); +} + +// An effect of a variant and subtype from a seed. +static Entity* effect_spawn_at(int variant, int subType, Vector position, Vector velocity, Entity* spawner, + uint32_t seed) +{ + return g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = spawner, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = variant, + .seed = seed}); +} + +// One of Mother's forms from a seed. +static Entity_NPC* mother_spawn(int variant, int subType, Vector position, Vector velocity, Entity* spawner, + uint32_t seed) +{ + return static_cast(g_game->Spawn({.position = position, + .velocity = velocity, + .spawner = spawner, + .subType = subType, + .type = ENTITY_MOTHER, + .variant = variant, + .seed = seed})); +} + +// Tints an entity for good, shared with what it spawns. +static void tint_set(Entity& entity, const ColorMod& color) +{ + entity.SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// A rock particle that bounces, flung once from a spot. +static void dust_spawn(Vector position, int count, int subType) +{ + game_particles_spawn({.position = position, + .speed = MOTHER_PARTICLE_SPEED, + .count = count, + .subType = subType, + .variant = EFFECT_ROCK_PARTICLE}); +} + +// Whether the line from a spot along a reach crosses no wall, walking the grid cell by cell. +static bool room_line_is_clear(Vector from, Vector reach) +{ + constexpr float CELL_HALF = GRID_CELL_SIZE * HALF; + + Room& room = *g_game->room; + Vector delta = vector_sub(vector_add(reach, from), from); + int column = (int)((from.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF); + int row = (int)((from.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF); + int stepX = delta.x > 0 ? 1 : -1; + int stepY = delta.y > 0 ? 1 : -1; + float t = 0; + Vector at = from; + if (vector_is_zero(delta)) return false; + + while (t < 1) + { + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + uint32_t collision = room.GetGridCollision(isInside ? row * room.gridWidth + column : -1); + if (collision == COLLISION_WALL || collision == COLLISION_WALL_EXCEPT_PLAYER) break; + + float edgeX = (float)column * GRID_CELL_SIZE + GRID_ORIGIN_X + CELL_HALF * (float)stepX; + float edgeY = (float)row * GRID_CELL_SIZE + GRID_ORIGIN_Y + CELL_HALF * (float)stepY; + float toX = delta.x == 0 ? INFINITY : (edgeX - at.x) / delta.x; + float toY = delta.y == 0 ? INFINITY : (edgeY - at.y) / delta.y; + if (toY <= toX) row += stepY; + else column += stepX; + t += std::min(toX, toY); + at = vector_add(vector_scale(delta, t), from); + } + return t >= 1; +} + +// Sets Mother's collision class, and her arms' along with her body's. +static void mother_collision_set(Entity_NPC& npc, int collisionClass) +{ + npc.entityCollisionClass = collisionClass; + if (npc.subtype != MOTHER_PART_BODY) return; + + for (int part : {1, 2}) + if (npc.entityDeque[part]) npc.entityDeque[part]->entityCollisionClass = collisionClass; +} + +// Stops every shot in the room, popping it, and with isEnemiesKilled also kills the door shutting enemies other than +// Dark Esau and Mother's own pieces but her phases. +enum MotherSweep +{ + SWEEP_SHOTS, + SWEEP_ENEMIES +}; + +static void mother_sweep(Entity_NPC& npc, MotherSweep sweep) +{ + EntityList_EL& entities = g_game->room->entityList.updateEL; + + for (size_t i = 0; i < entities.size(); i++) + { + Entity* entity = entities[i]; + if (entity->type == ENTITY_PROJECTILE) + { + static_cast(entity)->projectileFlags = 0; + entity->isDead = true; + continue; + } + + bool isDoorEnemy = Entity::is_enemy_type(entity->type) && entity->CanShutDoors() && + entity->type != ENTITY_DARK_ESAU && !entity->HasEntityFlags(FLAG_FRIENDLY); + bool isMotherPiece = + entity->type == ENTITY_MOTHER && entity->variant != MOTHER_PHASE_ONE && entity->variant != MOTHER_PHASE_TWO; + if (sweep != SWEEP_ENEMIES || !(isDoorEnemy || isMotherPiece)) continue; + + entity->AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + entity->Kill(EntityRef(&npc)); + } +} + +// Keeps a dying piece alive through the transition: invincible, still and untargeted at a sliver of health. +static void mother_hold_alive(Entity& entity) +{ + entity.damageEvents.clear(); + entity.pendingDamage = 0; + entity.pendingDamageFlags = 0; + entity.isDead = false; + entity.entityCollisionClass = ENTCOLL_NONE; + entity.health = TRANSITION_HEALTH; + entity.isInvincible = true; + entity.RemoveStatusEffects(); + entity.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); +} + +// 00568a90 Her first phase dies into her second: the room slows, she plays Transition, and she and her parts hold. +static void mother_transition_start(Entity_NPC& npc) +{ + mother_sweep(npc, SWEEP_ENEMIES); + g_game->room->bloodFromWallsDuration = TRANSITION_BLOOD_FRAMES; + g_game->room->bloodFromWallsCount = TRANSITION_BLOOD_COUNT; + npc_anim_loop(npc.sprite, "Transition"); + + for (EntityPtr& part : npc.entityDeque) + { + if (!part || !Entity::is_enemy_type(part->type)) continue; + mother_hold_alive(*part); + static_cast(part.get())->state = MOTHER_TRANSITION; + } + mother_hold_alive(npc); + npc.state = MOTHER_TRANSITION; + npc.i1 = 0; + npc_sound_play(SOUND_MOTHER_DEATH1, 1, 2, 1); +} + +// 00568cc0 Spawns her head and arms about her body, kept in its deque, the head as its child and an arm as the head's. +static void mother_parts_spawn(Entity_NPC& npc) +{ + std::array parts{}; + + for (int part = MOTHER_PART_HEAD; part <= MOTHER_PART_RIGHT_ARM; part++) + { + Vector offset = MOTHER_PART_OFFSETS[part]; + auto* piece = static_cast(g_game->Spawn({.position = vector_add(npc.pos, offset), + .spawner = &npc, + .subType = part, + .type = ENTITY_MOTHER, + .variant = MOTHER_PHASE_ONE, + .seed = npc.initSeed})); + if (part == MOTHER_PART_HEAD) + { + piece->posOffset = vector_sub(npc.posOffset, offset); + mother_collision_set(*piece, ENTCOLL_NONE); + piece->isInvincible = true; + piece->ClearEntityFlags(FLAG_APPEAR); + piece->AddEntityFlags(MOTHER_PART_FLAGS); + piece->isCanShutDoors = false; + } + else + { + piece->SetSize(MOTHER_ARM_SIZE, vector_make(-1, -1), -1); + piece->posOffset = vector_sub(npc.posOffset, offset); + piece->ClearEntityFlags(FLAG_APPEAR); + piece->AddEntityFlags(FLAG_DONT_COUNT_BOSS_HP); + } + piece->parent = &npc; + piece->Update(); + parts[part - 1] = piece; + } + + npc.entityDeque.resize(parts.size()); + for (size_t i = 0; i < parts.size(); i++) npc.entityDeque[i] = parts[i]; + npc.child = parts[1]; + parts[1]->child = parts[2]; +} + +// One of the two pieces of the bottom wall in front of her: the floor's shade multiplied under it, or the wall itself. +enum WallPiece +{ + WALL_SHADE, + WALL_FRONT +}; + +static void mother_wall_spawn(Vector position, WallPiece piece) +{ + Entity* wall = effect_spawn_at(EFFECT_BACKDROP_DECORATION, 0, position, {}, nullptr, Random()); + ANM2& sprite = wall->sprite; + sprite.Load(MOTHER_WALL_ANM2, GRAPHICS_LOAD); + + if (piece == WALL_SHADE) + for (size_t layer = 1; layer < sprite.layerStates.size(); layer++) + sprite.GetLayer((int)layer)->isVisible = false; + else sprite.GetLayer(0)->isVisible = false; + if (sprite.SetAnimation("Idle", SWITCH_KEEP_FRAME) && sprite.animState.animData) sprite.animState.SetFrameFloat(0); + if (sprite.animState.animData) sprite.animState.isPlaying = false; + if (piece == WALL_SHADE) sprite.GetLayer(0)->blendMode = MOTHER_WALL_SHADE_BLEND; + wall->sortingLayer = piece == WALL_SHADE ? SORTING_BACKGROUND : SORTING_DOOR; +} + +// Her first frame as the body: up in the top wall, the doors gone, the players and familiars at the bottom, her parts +// and the wall in front. +static void mother_body_init(Entity_NPC& npc, float innerTop) +{ + Room& room = *g_game->room; + + npc.pos = vector_make(Room::GetCenterPos().x, innerTop); + npc.posOffset.y = MOTHER_RISE; + npc.renderZOffset = MOTHER_RENDER_Z; + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) room.RemoveDoor(slot); + room.descriptor->allowedDoors = 0; + + Vector start = + vector_make((room.bottomRightPos.x + room.topLeftPos.x) * HALF, room.bottomRightPos.y - MOTHER_PLAYER_START); + for (Entity_Player* player : g_game->playerManager.playerList) + player->Teleport(PlayerManager::get_player_start_position(player, start), false, false); + for (Entity* entity : room.entityList.updateEL) + if (entity && entity->type == ENTITY_FAMILIAR) + entity->pos = static_cast(entity)->GetFollowTargetPosition(FOLLOW_EXACT); + + mother_parts_spawn(npc); + Vector wall = vector_make(room.topLeftPos.x - MOTHER_WALL_X, room.bottomRightPos.y); + mother_wall_spawn(wall, WALL_SHADE); + mother_wall_spawn(wall, WALL_FRONT); + npc.i2 = 0; + npc_sound_play(SOUND_MOTHER_APPEAR1, 1, 2, 1); +} + +// Where her fist lands: her ShootPos null, 60 down. +static Vector mother_fist_get(Entity_NPC& npc, std::string_view null = "ShootPos") +{ + return vector_add(vector_add(npc.pos, npc.GetNullOffset(null)), MOTHER_SHOT_DROP); +} + +// A fist landing: blood and a ripple through the floor. +static void mother_fist_land(Entity_NPC& npc, Vector position) +{ + npc.MakeBloodPoof(position, npc.splatColor, 1); + shockwave_make(position, MOTHER_SHOCKWAVE_AMPLITUDE, MOTHER_SHOCKWAVE_SPEED, SHOCKWAVE_DURATION); +} + +// Her idle: with no ball out, crushes the risen Isaacs, attacks or summons; with Isaacs risen, scrapes them; with a +// ball out, swings at it as it comes. +static void mother_idle_update(Entity_NPC& npc, int ticks, float middle) +{ + if (npc.sprite.IsFinished()) npc.sprite.Play("Idle"); + if (npc.stateFrame > 0) npc.stateFrame -= ticks; + + Entity* ball = npc.entityRef; + if (ball) + { + float ballMass = ball->config->mass; + float ahead = BALL_SWING_AHEAD; + float line = npc.pos.y + BALL_SWING_LINE; + bool isFast = false; + if (ball->mass >= ballMass + BALL_HEAVY) line -= BALL_SWING_RAISE; + else if (ball->mass == ballMass && vector_length(ball->targetPosition) >= BALL_SLOW_SPEED) + { + ahead = BALL_SWING_AHEAD_FAST; + isFast = true; + } + + float lead = ball->speedMultiplier / npc.speedMultiplier * ahead; + float landX = ball->velocity.x * lead + ball->pos.x; + if (ball->velocity.y >= 0 || ball->velocity.y * lead + ball->pos.y >= line) return; + + bool isRight = middle <= landX; + if (isFast) + { + npc.sprite.Play(isRight ? "GroundPound" : "GroundPound2", PLAY_FORCED); + npc.state = MOTHER_POUND; + npc_sound_play(npc.sprite.IsPlaying("GroundPound") ? SOUND_MOTHER_FISTPOUND1 : SOUND_MOTHER_FISTPOUND2, 1, + 2, 1); + return; + } + npc.sprite.Play(isRight ? "ScrapeAttack" : "ScrapeAttack2", PLAY_FORCED); + npc.state = MOTHER_SCRAPE; + npc_sound_play(SOUND_MOTHER_FISTPOUND1 + (int)(Random() % 3), 1, 2, 1); + return; + } + + if (npc.i2 == -1) + { + if (!npc.sprite.animState.IsLoopingAnimation()) return; + npc.i2 = 0; + npc_sound_play(SOUND_MOTHER_FISTPOUND3, 1, 2, 1); + npc.sprite.Play("GroundPound3"); + npc.state = MOTHER_CRUSH; + npc.stateFrame = 0; + return; + } + + if (npc.i2 >= 1) + { + if (!npc.sprite.animState.IsLoopingAnimation()) return; + int left = 0; + int right = 0; + for (Entity* isaac : entity_query(ENTITY_MOTHER, MOTHER_DEAD_ISAAC)) + { + if (isaac->pos.y >= npc.pos.y + SCRAPE_ISAAC_REACH) continue; + if (npc.pos.x <= isaac->pos.x) right++; + else left++; + } + if (left <= 0 && right <= 0) return; + npc.sprite.Play(left <= right ? "ScrapeAttack" : "ScrapeAttack2"); + npc.state = MOTHER_SCRAPE; + npc.projectileCooldown = 1 - npc.projectileCooldown; + return; + } + + if (npc.stateFrame >= 1) return; + if (npc.updateTime >= (float)(npc.i1 * MOTHER_SUMMON_EVERY + MOTHER_SUMMON_FIRST)) + { + npc.state = MOTHER_SUMMON; + npc.i1++; + npc.sprite.Play("SummonBegin"); + npc.stateFrame = 0; + npc.i2 = 0; + return; + } + + int enemies = npc.GetAliveEnemyCount(); + if (Random() % MOTHER_FISTULA_ODDS == 0 && npc.championTimer > MOTHER_FISTULA_AFTER) + { + npc.state = MOTHER_FISTULA; + npc.sprite.Play("Shoot1"); + npc_sound_play(SOUND_MOTHER_FISTULA, 1, 2, 1); + npc.championTimer = -1; + } + else if (Random() % MOTHER_WRIST_ODDS == 0) + { + npc.state = MOTHER_WRIST; + npc.sprite.Play(Random() & 1 ? "WristAttackLeft" : "WristAttackRight"); + npc_sound_play(SOUND_MOTHER_HAND_BOIL_START, 1, 2, 1); + } + else if (random_below((enemies < MOTHER_FEW_ENEMIES) + 2) == 0 && enemies < MOTHER_MANY_ENEMIES) + { + npc.state = MOTHER_POUND; + npc.sprite.Play(Random() & 1 ? "GroundPound" : "GroundPound2"); + npc_sound_play(npc.sprite.IsPlaying("GroundPound") ? SOUND_MOTHER_FISTPOUND1 : SOUND_MOTHER_FISTPOUND2, 1, 2, + 1); + } + else + { + npc.state = MOTHER_KNIFE; + npc.sprite.Play(Random() & 1 ? "ThrowKnife" : "ThrowKnife2"); + } + npc.championTimer++; + npc.stateFrame = 0; +} + +// Back to her idle after an attack, resting a while. +static void mother_rest(Entity_NPC& npc, int rest) +{ + npc.state = MOTHER_IDLE; + npc.stateFrame = rest; +} + +// The knife: a big knife thrown down from her hand. +static void mother_knife_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Sound")) + { + npc_sound_play(SOUND_MOTHER_KNIFE_START, 1, 2, 1); + npc_sound_play(SOUND_KNIFE_PULL, 1, 2, 1); + game_shake_screen(MOTHER_KNIFE_SHAKE); + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_MOTHER_KNIFE_THROW, 1, 2, 1); + npc_sound_play(SOUND_SHELLGAME, KNIFE_SLIDE_VOLUME, 2, KNIFE_SLIDE_PITCH); + npc_sound_play(SOUND_FART_GURG, 1, 2, 1); + Entity* knife = effect_spawn_at(EFFECT_BIG_KNIFE, 0, mother_fist_get(npc), KNIFE_VELOCITY, &npc, Random()); + knife->parent = &npc; + knife->Update(); + } +} + +// The pound: with her ball near, pulls it toward her fist and smashes it; else a fan of maggots and shots. +static void mother_pound_update(Entity_NPC& npc) +{ + Entity* ball = npc.entityRef; + if (ball) + { + Vector toFist = + vector_sub(vector_add(vector_add(npc.GetNullOffset("ShootPos"), npc.pos), {0, BALL_SWING_LINE}), ball->pos); + Vector pulled = vector_add(ball->targetPosition, vector_resized(toFist, BALL_POUND_PULL)); + ball->targetPosition = vector_resized(pulled, vector_length(ball->targetPosition)); + } + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, 1); + game_shake_screen(POUND_SHAKE); + Vector fist = mother_fist_get(npc); + ball = npc.entityRef; + if (!ball) + { + Vector aim = vector_normalized(vector_sub(Room::GetCenterPos(), fist)); + for (int i = -POUND_FAN_HALF; i <= POUND_FAN_HALF; i++) + { + Vector direction = vector_rotated(aim, (float)i * POUND_FAN_DEGREES / POUND_FAN_HALF); + Vector velocity = vector_scale(direction, random_between(POUND_MAGGOT_SPEED, POUND_MAGGOT_SPEED_RANGE)); + if (i & 1) + { + small_maggot_spawn(vector_add(fist, velocity), POUND_MAGGOT_HEIGHT, velocity, POUND_MAGGOT_RISE); + continue; + } + Vector shot = vector_scale(direction, POUND_SHOT_SPEED); + ProjectileParams params; + params.fallingAccelModifier = POUND_SHOT_FALL; + params.scale = POUND_SHOT_SCALE; + npc.fire_projectiles(vector_add(shot, fist), shot, PROJECTILES_SINGLE, params)->subtype = 1; + } + } + else + { + ball->AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + ball->Kill(EntityRef(&npc)); + if (ball->IsType(ENTITY_MOTHER, MOTHER_ORB, -1)) mother_orb_burst(*static_cast(ball)); + mother_sweep(npc, SWEEP_SHOTS); + } + mother_fist_land(npc, fist); +} + +// The wrist: it swells and bursts into eight worms fanned below, with blood and gibs. +static void mother_wrist_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Sound")) npc_sound_play(SOUND_MOTHER_WRIST_SWELL, 1, 2, 1); + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + Vector wrist = mother_fist_get(npc); + for (int i = 0; i < WRIST_WORMS; i++) + { + float spread = std::clamp((float)i / (WRIST_WORMS - 1), 0.0f, 1.0f); + Vector direction = vector_from_angle(spread * WRIST_FAN_SPAN + WRIST_FAN_FIRST); + uint32_t seed = Random(); + Vector velocity = vector_scale(direction, random_between(WRIST_WORM_SPEED, WRIST_WORM_SPEED_RANGE)); + Vector position = vector_add(wrist, vector_scale(direction, WRIST_WORM_REACH)); + Entity_NPC* worm = mother_spawn(MOTHER_WORM, 0, position, velocity, &npc, seed); + worm->target = npc.GetPlayerTarget(); + worm->projectileDelay = WRIST_WORM_WEAVE + WRIST_WORM_WEAVE_STEP * i; + worm->SetScale(random_between(WRIST_WORM_SCALE, WRIST_WORM_SCALE_RANGE)); + worm->Update(); + Vector spray = vector_scale(direction, random_between(WRIST_WORM_SPEED, WRIST_WORM_SPEED_RANGE)); + blood_explosion_spawn(3, position, WRIST_BLOOD_OFFSET, npc.splatColor, spray); + } + gibs_spawn({.color = npc.splatColor, + .position = wrist, + .velocity = WRIST_GIB_VELOCITY, + .spawner = &npc, + .speed = WRIST_GIB_SPEED, + .spread = GIB_SPREAD, + .amount = WRIST_GIBS, + .gibFlags = GIB_BLOOD_AND_BONE}); + npc_sound_play(SOUND_MOTHER_WRIST_EXPLODE, 1, 2, 1); + npc_sound_play(Random() & 1 ? SOUND_MOTHER_GRUNT5 : SOUND_MOTHER_GRUNT7, 1, 2, 1); +} + +// The scrape: her hand sweeps along the floor, hurting and pushing away what it touches, and batting her ball back at +// the player. +static void mother_scrape_update(Entity_NPC& npc) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + game_shake_screen(SCRAPE_SHAKE); + Capsule hand; + npc.GetNullCapsule(hand, "ShootPos"); + if (hand.radius > 0) + { + hand.center = vector_add(hand.center, npc.posOffset); + hand.end = vector_add(hand.end, npc.posOffset); + hand.start = vector_add(hand.start, npc.posOffset); + for (Entity* other : entity_query_radius(hand.center, hand.halfLength + hand.radius, QUERY_ALL)) + { + if (other == &npc || other->entityCollisionClass == ENTCOLL_NONE || + other->entityGridCollisionClass == GRIDCOLL_BULLET || other->IsType(ENTITY_MOTHER, MOTHER_ORB, -1)) + continue; + + if (Capsule::Collide(hand, other->GetCollisionCapsule({}))) + { + other->velocity = vector_add( + other->velocity, vector_scale(vector_normalized(vector_sub(other->pos, npc.pos)), SCRAPE_PUSH)); + float damage = other->is_player() || other->IsFamiliar() ? SCRAPE_PLAYER_DAMAGE : SCRAPE_DAMAGE; + other->TakeDamage(damage, 0, EntityRef(&npc), MOTHER_HIT_COUNTDOWN); + } + if (other->IsType(ENTITY_MOTHER, MOTHER_DEAD_ISAAC, -1)) npc_sound_play(SOUND_MOTHER_ISAAC_HIT, 1, 2, 1); + } + } + + Entity* ball = npc.entityRef; + if (ball && ball->pos.y < npc.pos.y + BALL_BAT_LINE) + { + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, ball->pos)); + npc_sound_play(SOUND_MEATY_DEATHS, 1, 2, 1); + ball->velocity = vector_resized(aim, BALL_BAT_SPEED); + ball->targetPosition = + vector_resized(aim, std::min(vector_length(ball->targetPosition) + BALL_BAT_SPEEDUP, BALL_BAT_TOP_SPEED)); + if (ball->mass == ball->config->mass) ball->target = npc.GetPlayerTarget(); + } + mother_rest(npc, MOTHER_REST); +} + +// The crush: both hands slam the floor and sweep down, crushing the Dead Isaacs above the sweep into flying heads. +static void mother_crush_update(Entity_NPC& npc, int ticks, float innerTop) +{ + if (npc.sprite.IsEventTriggered("Skip")) + { + npc.targetPosition.y = innerTop; + mother_collision_set(npc, ENTCOLL_ALL); + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.v1 = vector_make(npc.pos.y, 0); + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, 2, 1); + game_shake_screen(POUND_SHAKE); + mother_fist_land(npc, mother_fist_get(npc)); + mother_fist_land(npc, mother_fist_get(npc, "ShootPos2")); + } + + if (npc.sprite.WasEventTriggered("Shoot") || npc.sprite.animState.IsLoopingAnimation()) + { + npc.v1.x += npc.speedMultiplier * CRUSH_SPEED; + if (npc.GetIntervalTicks(2, 0)) + for (Entity* isaac : entity_query(ENTITY_MOTHER, MOTHER_DEAD_ISAAC)) + { + if (!Entity::is_enemy_type(isaac->type) || isaac->pos.y >= npc.v1.x) continue; + + effect_spawn_at(EFFECT_ROCK_EXPLOSION, 0, isaac->pos, {}, &npc, Random())->Update(); + isaac->AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + isaac->Kill(EntityRef(&npc)); + ProjectileParams params; + params.fallingAccelModifier = CRUSH_HEAD_ACCEL; + params.heightModifier -= random_unit() * CRUSH_HEAD_HEIGHT; + params.variant = PROJECTILE_HEAD; + params.fallingSpeedModifier = CRUSH_HEAD_FALL - random_unit() * CRUSH_HEAD_FALL_RANGE - npc.v1.y; + npc.FireProjectiles(isaac->pos, {}, PROJECTILES_SINGLE, params); + npc.v1.y += CRUSH_HEAD_FALL_STEP; + } + } + + if (npc.sprite.IsFinished()) npc.sprite.Play("Idle"); + npc.stateFrame += ticks; + if (npc.sprite.animState.IsLoopingAnimation() && npc.stateFrame > CRUSH_FRAMES) mother_rest(npc, MOTHER_REST); +} + +// The bounds Mother works within: the room's edges, the line below the top wall she sits on and the line inside it she +// retreats to. +struct MotherBounds +{ + float left = 0; + float right = 0; + float top = 0; + float bottom = 0; + float innerTop = 0; + float wallTop = 0; +}; + +// The summon: her laser holds 120 frames under a rumbling floor, starting the Dead Isaacs' rise. +static void mother_summon_update(Entity_NPC& npc, int ticks, const MotherBounds& bounds) +{ + bool isFinished = npc.sprite.IsFinished(); + if (npc.stateFrame < 0) + { + if (!isFinished) return; + npc.sprite.Play("Idle"); + return mother_rest(npc, MOTHER_REST); + } + + if (isFinished) npc.sprite.Play("LaserAttackLoop"); + if (npc.sprite.IsEventTriggered("Skip")) + { + npc.targetPosition.y = bounds.wallTop; + mother_collision_set(npc, ENTCOLL_NONE); + } + if (npc.sprite.IsEventTriggered("Sound")) npc_sound_play(SOUND_MOTHER_SUMMON_ISAACS_START, 1, 2, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.i2 = 1; + npc.projectileCooldown = (int)(Random() & 1); + npc.v1.x = ISAAC_RISE_FIRST; + } + if (npc.sprite.WasEventTriggered("Shoot") || npc.sprite.animState.IsLoopingAnimation()) + { + game_shake_screen(SUMMON_SHAKE); + if (npc.GetIntervalTicks(2, 0)) + { + float left = bounds.left + SUMMON_DUST_MARGIN; + Vector dust; + dust.x = (bounds.right - SUMMON_DUST_MARGIN - left) * random_unit() + left; + dust.y = random_unit() * SUMMON_DUST_DEPTH + (bounds.bottom - SUMMON_DUST_MARGIN); + dust_spawn(dust, 1, ROCK_PARTICLE_BOUNCY); + if (Random() % SUMMON_SPLAT_ODDS == 0) blood_explosion_spawn(2, dust, {}, COLOR_GREEN_SPLAT, {}); + } + } + npc.stateFrame += ticks; + if (npc.stateFrame <= MOTHER_SUMMON_FRAMES) return; + npc.sprite.Play("LaserAttackEnd"); + npc.state = MOTHER_IDLE; + npc.stateFrame = -1; +} + +// The fistula: she spits out her ball, rolling at the player. +static void mother_fistula_update(Entity_NPC& npc) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + Entity* player = npc.GetPlayerTarget(); + Vector toPlayer = vector_sub(player->pos, npc.pos); + Vector aim = toPlayer; + float down = toPlayer.y; + float distance = vector_length(toPlayer); + if (down < distance * HALF) aim.y = distance * HALF - down + toPlayer.y; + npc_sound_play(SOUND_HEARTOUT, 1, 2, 1); + npc.MakeBloodCloud(npc.pos, npc.splatColor, 1); + uint32_t seed = Random(); + Entity_NPC* ball = + mother_spawn(MOTHER_ORB, MOTHER_ORB_BIG, npc.pos, vector_resized(aim, BALL_THROW_SPEED), &npc, seed); + ball->targetPosition = vector_resized(aim, BALL_THROW_PUSH); + ball->parent = &npc; + npc.SetRef_bec(ball); + ball->target = npc.GetPlayerTarget(); + ball->Update(); + mother_rest(npc, MOTHER_REST); +} + +// One row of the walls falls: the top row still standing loses its run of wall from the left, with blood and gore, +// and the bottom wall's pieces slide down a cell. +static void mother_wall_row_fall(Entity_NPC& npc) +{ + Room& room = *g_game->room; + + for (int row = 1; row < room.gridHeight - 1; row++) + { + bool isFallen = false; + for (int column = 1; column < room.gridWidth - 1; column++) + { + int index = room.gridWidth * row + column; + GridEntity* wall = room.gridEntities[index]; + if (!wall || wall->type != GRID_WALL) break; + + Vector spot = vector_make((float)(index % room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_X, + (float)(index / room.gridWidth) * GRID_CELL_SIZE + GRID_ORIGIN_Y); + dust_spawn(spot, 1, 0); + if (Random() % SUMMON_SPLAT_ODDS == 0) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float reach = random_unit() * MOTHER_WALL_SPLAT_REACH; + Vector splat = vector_make(std::cos(angle) * reach + spot.x, spot.y + std::sin(angle) * reach); + blood_explosion_spawn(2, splat, {}, COLOR_GREEN_SPLAT, {}); + } + Entity* blood = effect_spawn_at(EFFECT_BLOOD_SPLAT, 0, spot, {}, &npc, Random()); + sprite_scale_set(*blood, random_unit() + WALL_SPLAT_SCALE); + tint_set(*blood, npc.splatColor); + blood->Update(); + gibs_spawn({.color = npc.splatColor, + .position = spot, + .spread = GIB_SPREAD, + .amount = WALL_GIBS, + .gibFlags = GIB_BLOOD}); + if ((uint32_t)index < ROOM_GRID_CELLS && room.gridEntities[index] && wall->type != GRID_DECORATION) + { + room.gridPaths[index] = GRID_PATH_FREED; + room.gridEntities[index] = nullptr; + delete wall; + } + isFallen = true; + } + if (!isFallen) continue; + + npc_sound_play(SOUND_MEATY_DEATHS, 1, 2, 1); + for (Entity* piece : entity_query(ENTITY_EFFECT, EFFECT_BACKDROP_DECORATION)) + if (row == room.gridHeight - 1) piece->Remove(); + else piece->pos.y += MOTHER_WALL_STEP; + room.update_bounds(false); + return; + } +} + +// The transition: her head and arms burst one by one, her laser fires down, and at the last burst she becomes her +// second phase, charging down out of the wall while the walls fall. +static void mother_transition_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + int burst = npc.i1; + if (burst == 0 || burst == 1 || burst == 3) + { + for (int arm : {1, 2}) + { + if (!npc.entityDeque[arm]) continue; + npc.entityDeque[arm]->Remove(); + npc.entityDeque[arm] = nullptr; + break; + } + Vector gore = vector_add(vector_add(npc.pos, npc.posOffset), npc.GetNullOffset("ShootPos")); + gibs_spawn({.color = npc.splatColor, + .position = gore, + .spawner = &npc, + .spread = GIB_SPREAD, + .amount = TRANSITION_GIBS, + .gibFlags = npc.config->gibFlags}); + blood_explosion_spawn(4, gore, {}, npc.splatColor, {}); + npc_sound_play(SOUND_ROCKET_BLAST_DEATH, 1, 2, 1); + } + if (burst == 2) + { + Vector source = vector_add(vector_add(npc.pos, npc.posOffset), npc.GetNullOffset("ShootPos")); + source.y += TRANSITION_LASER_DROP; + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = source, + .posOffset = vector_make(0, -TRANSITION_LASER_DROP), + .source = &npc, + .angleDegrees = TRANSITION_LASER_ANGLE, + .timeout = TRANSITION_LASER_TIMEOUT, + .variant = TRANSITION_LASER_VARIANT}); + tint_set(*laser, TRANSITION_LASER_COLOR); + laser->renderDepthOffset = TRANSITION_LASER_DEPTH; + npc.MakeBloodCloud(source, npc.splatColor, 1); + } + if (burst == 3) + { + npc.MakeBloodCloud(npc.pos, npc.splatColor, 1); + if (Entity* head = npc.entityDeque[0]) + { + head->parent = nullptr; + head->sprite.Play(npc.sprite.GetAnimation()); + head->sprite.SetFrame((float)npc.sprite.GetFrame()); + head->targetPosition = vector_add(npc.targetPosition, MOTHER_PART_OFFSETS[MOTHER_PART_HEAD]); + head->renderDepthOffset = TRANSITION_HEAD_DEPTH; + } + npc.Morph(ENTITY_MOTHER, MOTHER_PHASE_TWO, 0, -1); + npc.entityDeque[0] = nullptr; + npc.sprite.Play("ChargeLoop"); + npc.ClearEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.state = MOTHER_TRANSITION; + npc.i1 = 0; + npc.i2 = 0; + npc.health = npc.maxHitPoints; + npc.velocity = TRANSITION_CHARGE; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.isInvincible = false; + npc.posOffset = TRANSITION_OFFSET; + g_game->room->camera->SetFocusPosition(vector_add(npc.pos, MOTHER_CAMERA_LEAD)); + return; + } + npc.i1 = burst + 1; + } + + if (npc.i1 == 3 && npc.IsFrame(2, 0)) mother_wall_row_fall(npc); + if (npc.sprite.IsEventTriggered("Sound")) npc_sound_play(SOUND_HEARTIN, 1, 2, 1); +} + +// The Dead Isaacs rise from below the floor, one sooner each time, until 35 are up and she is ready to crush them. +static void mother_isaacs_rise(Entity_NPC& npc, int ticks, const MotherBounds& bounds) +{ + Room& room = *g_game->room; + + for (int tick = 0; tick < ticks; tick++) + { + npc.v1.x += 1; + if (npc.v1.x < std::max(ISAAC_RISE_EVERY - (float)npc.i2 * ISAAC_RISE_SOONER, ISAAC_RISE_FASTEST)) continue; + + float left = bounds.left + SUMMON_DUST_MARGIN; + float span = bounds.right - SUMMON_DUST_MARGIN - left; + float y = bounds.bottom + ISAAC_RISE_STOP; + int row = (int)((y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF); + Vector spot; + for (int tries = ISAAC_RISE_TRIES;;) + { + spot = vector_make(random_unit() * span + left, y); + int column = (int)((spot.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF); + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) break; + uint32_t index = (uint32_t)(row * room.gridWidth + column); + if (index >= ROOM_GRID_CELLS || room.gridPaths[index] < GRID_PATH_FREE || --tries < 1) break; + } + room_path_raise_at(spot, GRID_PATH_FREED); + npc_sound_play(SOUND_MOTHER_ISAAC_RISE, 1, 2, 1); + Entity_NPC* isaac = mother_spawn(MOTHER_DEAD_ISAAC, 0, spot, {}, &npc, Random()); + isaac->targetPosition = vector_make(spot.x, npc.size + npc.pos.y - ISAAC_RISE_STOP); + isaac->Update(); + npc.i2++; + npc.v1.x = 0; + } + if (npc.i2 <= ISAAC_RISE_LAST) return; + npc.i2 = -1; + npc_sound_play(SOUND_MOTHER_SUMMON_ISAACS_END, 1, 2, 1); +} + +// Her body darkens as she retreats into the top wall. +static void mother_shade_update(Entity_NPC& npc, const MotherBounds& bounds) +{ + float depth = 0; + if (npc.targetPosition.y == bounds.wallTop) + depth = lerp_range(npc.pos.y, {.inMin = bounds.innerTop, .inMax = bounds.wallTop}) + 0; + float shade = 1 - depth * HALF; + for (LayerState& layer : npc.sprite.layerStates) + { + layer.color = {{shade, shade, shade, 1}, + {1, 1, 1, -depth}, + {layer.color._offset[0], layer.color._offset[1], layer.color._offset[2]}}; + } +} + +// Her own ball hurled back at her stuns her, bursting it against her. +static void mother_ball_hit(Entity_NPC& npc) +{ + Entity* ball = npc.entityRef; + if (!ball || ball->mass < ball->config->mass + BALL_HEAVY || ball->velocity.y >= 0 || + ball->pos.y >= npc.pos.y + BALL_HIT_LINE) + return; + + if (ball->IsType(ENTITY_MOTHER, MOTHER_ORB, -1)) + { + auto* orb = static_cast(ball); + orb->SetRef_bec(&npc); + if (!orb->isDead) mother_orb_burst(*orb); + } + ball->Kill(EntityRef(&npc)); + if (npc.state == MOTHER_TRANSITION) return; + npc.sprite.Play("Stunned"); + npc.state = MOTHER_STUNNED; +} + +// Each part follows its place about the body, and the body its target, at half speed while out of reach. +static void mother_follow(Entity_NPC& npc) +{ + Entity* parent = npc.parent; + Vector target = npc.targetPosition; + if (parent) + target = + vector_add(parent->targetPosition, MOTHER_PART_OFFSETS[std::min(npc.subtype, (int)MOTHER_PART_RIGHT_ARM)]); + npc.velocity = vector_sub(target, npc.pos); + int collisionClass = parent ? parent->entityCollisionClass : npc.entityCollisionClass; + if (collisionClass == ENTCOLL_NONE) npc.velocity = vector_scale(npc.velocity, HALF); +} + +// The pre-update: the body starts her transition when killed, the arms share their health with her and kill her with +// them, the camera holds on her, and she ignores the hurt her own kind deals. +static void mother_pre_update(Entity_NPC& npc, const MotherBounds& bounds) +{ + if (npc.subtype == MOTHER_PART_BODY) + { + if (npc.isDead) mother_transition_start(npc); + } + else if (npc.subtype != MOTHER_PART_HEAD) + { + auto* body = static_cast(npc.parent.get()); + if (!body) npc.Kill(EntityRef()); + else + { + if (body->health > npc.health) body->health = npc.health; + else npc.health = body->health; + if (npc.isDead) + { + body->Kill(EntityRef()); + mother_transition_start(*body); + } + } + } + + if (npc.subtype == MOTHER_PART_BODY) + g_game->room->camera->SetFocusPosition(vector_make( + (bounds.right + bounds.left) * HALF, (bounds.bottom - bounds.top) * MOTHER_CAMERA_DEPTH + bounds.top)); + if (npc.pendingDamage <= 0) return; + + npc.pendingDamage = 0; + for (DamageEvent& event : npc.damageEvents) + { + bool isOwnKind = event.source.type == npc.type || event.source.spawnerType == npc.type; + if (isOwnKind && event.source.IsFriendly() == npc.IsFriendly()) event.damage = 0; + npc.pendingDamage += event.damage; + } +} + +// 00569170 Mother's first phase (912.0): the body in the top wall throws knives, pounds, bursts her wrists into worms, +// spits her ball and raises Dead Isaacs to crush, and her head and arms follow it about. +static void boss_mother_phase_one_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + MotherBounds bounds{.left = room.topLeftPos.x, + .right = room.bottomRightPos.x, + .top = room.topLeftPos.y, + .bottom = room.bottomRightPos.y, + .innerTop = room.topLeftPos.y + MOTHER_WALL_DEPTH, + .wallTop = room.topLeftPos.y - MOTHER_WALL_DEPTH}; + int ticks = npc_ticks_get(npc); + + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return mother_pre_update(npc, bounds); + + if (npc.state == NPC_STATE_INIT) + { + npc.splatColor = COLOR_GREEN_SPLAT; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + if (npc.subtype == MOTHER_PART_BODY) mother_body_init(npc, bounds.innerTop); + npc.targetPosition = npc.pos; + npc.state = MOTHER_IDLE; + return mother_follow(npc); + } + if (npc.subtype != MOTHER_PART_BODY) return mother_follow(npc); + + switch (npc.state) + { + case MOTHER_IDLE: + mother_idle_update(npc, ticks, (bounds.right + bounds.left) * HALF); + break; + case MOTHER_STUNNED: + if (!npc.sprite.IsFinished()) break; + npc.sprite.Play("Idle"); + npc.state = MOTHER_IDLE; + break; + case MOTHER_KNIFE: + case MOTHER_POUND: + if (npc.state == MOTHER_KNIFE) mother_knife_update(npc); + else mother_pound_update(npc); + if (!npc.sprite.IsFinished()) break; + npc.sprite.Play("Idle"); + mother_rest(npc, MOTHER_REST); + break; + case MOTHER_WRIST: + mother_wrist_update(npc); + if (!npc.sprite.IsFinished()) break; + npc.sprite.Play("Idle"); + mother_rest(npc, MOTHER_WRIST_REST); + break; + case MOTHER_SCRAPE: + mother_scrape_update(npc); + break; + case MOTHER_CRUSH: + mother_crush_update(npc, ticks, bounds.innerTop); + break; + case MOTHER_SUMMON: + mother_summon_update(npc, ticks, bounds); + break; + case MOTHER_TRANSITION: + mother_transition_update(npc); + if (npc.variant == MOTHER_PHASE_TWO) return; + break; + case MOTHER_FISTULA: + mother_fistula_update(npc); + break; + } + + if (npc.i2 > 0) mother_isaacs_rise(npc, ticks, bounds); + mother_shade_update(npc, bounds); + mother_ball_hit(npc); + mother_follow(npc); +} + +// 0056c800 A slam of her second phase against the room's edge: a green splat and a burst of rocks and splats thrown +// back against her heading. +static void mother_slam_burst(Entity_NPC& npc, Vector heading) +{ + Vector spot = g_game->room->GetClampedPositionImpl(npc.pos, SLAM_MARGIN, SLAM_MARGIN, SLAM_MARGIN, SLAM_MARGIN); + npc_sound_play(SOUND_MEATY_DEATHS, 1, 2, 1); + game_shake_screen(MOTHER_SLAM_BURST_SHAKE); + Entity* splat = effect_spawn_at(EFFECT_BLOOD_EXPLOSION, SPLAT_BIG, spot, {}, nullptr, Random()); + splat->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + splat->posOffset = vector_make(0, SLAM_SPLAT_RISE - random_unit() * SLAM_SPLAT_RISE_RANGE); + tint_set(*splat, COLOR_GREEN_SPLAT); + splat->Update(); + + Vector back = vector_scale(vector_normalized(heading), -1); + for (int i = 0; i < SLAM_PIECES; i++) + { + Vector direction = vector_rotated(back, (random_unit() - HALF) * SLAM_SPREAD); + float speed = random_between(SLAM_ROCK_SPEED, SLAM_ROCK_SPEED_RANGE); + Vector position = vector_add(vector_scale(direction, random_unit() * MOTHER_SLAM_REACH), spot); + effect_spawn_at(EFFECT_ROCK_PARTICLE, 0, position, vector_scale(direction, speed), nullptr, Random())->Update(); + } + for (int i = 0; i < SLAM_PIECES; i++) + { + Vector direction = vector_rotated(back, (random_unit() - HALF) * SLAM_SPREAD); + float speed = random_between(SLAM_SPLAT_SPEED, SLAM_SPLAT_SPEED_RANGE); + Vector position = vector_add(vector_scale(direction, random_unit() * MOTHER_SLAM_REACH), spot); + uint32_t seed = Random(); + int size = Random() % SLAM_SMALL_SPLAT_ODDS == 0 ? 0 : (Random() & 1) ? 3 : SPLAT_BIG; + Entity* piece = + effect_spawn_at(EFFECT_BLOOD_EXPLOSION, size, position, vector_scale(direction, speed), nullptr, seed); + piece->posOffset = vector_make(0, SLAM_SPLAT_RISE); + piece->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + tint_set(*piece, COLOR_GREEN_SPLAT); + piece->Update(); + } +} + +// The charge: she rushes down (or up) through the room, fading past its edges, leaving gore, slamming at its edges, +// coming back up the other side, and landing from above in the middle once she has passed the top. +static void mother_charge_update(Entity_NPC& npc, const MotherBounds& bounds) +{ + npc.friction *= MOTHER_CHARGE_FRICTION; + float steer = timescale_factor(MOTHER_CHARGE_STEER, npc.speedMultiplier); + npc.velocity.y += npc.speedMultiplier * npc.targetPosition.y * MOTHER_CHARGE_PUSH; + npc.velocity.x += (npc.targetPosition.x - npc.pos.x - npc.velocity.x) * (1 - steer); + game_shake_screen(CHARGE_SHAKE); + float outside = std::max({npc.pos.y - bounds.bottom, bounds.top - npc.pos.y, 0.0f}); + float alpha = std::max(1 - outside * MOTHER_CHARGE_FADE, 0.0f); + for (LayerState& layer : npc.sprite.layerStates) layer.color._tint[3] = alpha; + + if (npc.IsFrame(2, 0)) + for (size_t i = 0; i < CHARGE_SPOTS.size(); i++) + { + Vector spot = CHARGE_SPOTS[i]; + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float reach = random_unit() * CHARGE_SPLAT_REACH; + Vector position = vector_make(std::cos(angle) * reach + npc.pos.x + spot.x, + std::sin(angle) * reach + spot.y * npc.targetPosition.y + npc.pos.y); + if (i == 0 || i == CHARGE_SPOTS.size() - 1) + { + Vector velocity = vector_make(spot.x * CHARGE_SPLAT_SPREAD, npc.targetPosition.y * CHARGE_SPLAT_SPEED); + Entity* splat = + effect_spawn_at(EFFECT_BLOOD_EXPLOSION, SPLAT_BIG, position, velocity, nullptr, Random()); + splat->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + splat->posOffset = vector_make(0, CHARGE_SPLAT_RISE - random_unit() * CHARGE_SPLAT_RISE_RANGE); + tint_set(*splat, COLOR_GREEN_SPLAT); + splat->Update(); + } + if (Random() % CHARGE_DUST_ODDS == 0) dust_spawn(position, CHARGE_DUST, ROCK_PARTICLE_BOUNCY); + } + + float heading = npc.targetPosition.y; + if (std::abs(heading) == 1) + { + bool isPast = + heading > 0 ? npc.pos.y + MOTHER_CHARGE_EDGE > bounds.bottom : bounds.top > npc.pos.y - MOTHER_CHARGE_EDGE; + if (isPast) + { + npc_sound_play(SOUND_MAGGOT_ENTER_GROUND, 1, 2, 1); + npc.targetPosition.y *= CHARGE_BOUNCE; + mother_slam_burst(npc, npc.velocity); + heading = npc.targetPosition.y; + } + } + + if (heading > 0 && npc.pos.y > bounds.bottom + CHARGE_OUT) + { + npc.sprite.Play("ChargeUpLoop"); + npc.targetPosition.y = -1; + float x = bounds.right - npc.targetPosition.x + bounds.left; + npc.pos = vector_make(x, bounds.bottom + CHARGE_RETURN); + npc.targetPosition.x = x; + npc.velocity = vector_make(0, CHARGE_RETURN_SPEED); + npc_sound_play(SOUND_MAGGOT_BURST_OUT, 1, 2, 1); + npc_sound_play(SOUND_MOTHER_CHARGE2, 1, 2, 1); + mother_slam_burst(npc, npc.velocity); + return; + } + if (heading >= 0 || npc.pos.y >= bounds.top - CHARGE_OUT) return; + + npc.pos = Room::GetCenterPos(); + npc.targetPosition = npc.pos; + npc.sprite.Play("JumpDown"); + npc_sound_play(SOUND_MOTHER_LAUGH, 1, 2, 1); + npc.state = MOTHER2_LAND; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + for (LayerState& layer : npc.sprite.layerStates) layer.color._tint[3] = 1; + npc.SetSize(npc.config->collisionRadius, npc.config->collisionRadiusMulti, npc.config->gridCollisionPoints); +} + +// The landing: she drops into the middle, cracking the floor in a ring of 16 cracks. +static void mother_land_update(Entity_NPC& npc) +{ + npc.friction *= MOTHER_CHARGE_FRICTION; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc_sound_play(SOUND_MOTHER_LAND_SMASH, 1, 2, 1); + npc_sound_play(SOUND_MOTHER_MISC, 1, 2, 1); + game_shake_screen(LAND_SHAKE); + Entity* poof = effect_spawn_at(EFFECT_POOF02, LAND_POOF_SUBTYPE, npc.pos, {}, &npc, Random()); + sprite_scale_set(*poof, LAND_POOF_SCALE); + tint_set(*poof, npc.splatColor); + poof->sprite.isFlipX = !(Random() & 1); + poof->Update(); + + for (int i = 0; i < LAND_CRACKS; i++) + { + Vector direction = vector_from_angle((float)i * FULL_TURN_DEGREES / LAND_CRACKS); + uint32_t seed = Random(); + Vector position = vector_add(vector_scale(direction, LAND_CRACK_REACH), npc.pos); + auto* crack = static_cast( + effect_spawn_at(EFFECT_CRACKWAVE, LAND_CRACK_SUBTYPE, position, {}, &npc, seed)); + crack->parent = &npc; + crack->rotation = vector_angle(direction); + if (i % 2 == 0) crack->AddEntityFlags(FLAG_SPAWN_STICKY_SPIDERS); + crack->minRadius = i % 2 == 0 ? LAND_CRACK_WIDE : LAND_CRACK_NARROW; + crack->maxRadius = crack->minRadius; + crack->Update(); + } + } + if (npc.sprite.animState.animData && npc.sprite.animState.isPlaying) return; + npc.state = NPC_STATE_INIT; + npc.stateFrame = 0; +} + +// Three arms of shots out from her spin, each a wave of four (three slower) growing as they go. +static void mother_spin_shots(Entity_NPC& npc) +{ + ProjectileParams spin; + spin.color = SPIN_SHOT_COLOR; + spin.scale = random_between(SPIN_SHOT_SCALE, SPIN_SHOT_SCALE_RANGE); + spin.changeFlags |= PROJECTILE_ACCELERATE | PROJECTILE_WIGGLE; + spin.fallingAccelModifier = SPIN_SHOT_FALL; + spin.isFallingKept = true; + spin.bulletFlags = PROJECTILE_WIGGLE | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT; + spin.changeTimeout = SPIN_SHOT_CHANGE; + spin.acceleration = SPIN_SHOT_ACCEL; + if (npc.stateFrame % SPIN_WIGGLE_EVERY == 0) spin.wiggleFrameOffset = SPIN_SHOT_WIGGLE; + float speed = SPIN_SHOT_SPEED; + float shots = SPIN_SHOTS; + if (npc.stateFrame % SPIN_SLOW_EVERY == 0) + { + speed = SPIN_SHOT_SPEED_SLOW; + spin.scale *= SPIN_SHOT_SCALE_SLOW; + spin.changeTimeout = SPIN_SHOT_CHANGE_SLOW; + shots = SPIN_SHOTS_SLOW; + spin.acceleration = SPIN_SHOT_ACCEL_SLOW; + } + + for (int arm = 0; arm < SPIN_ARMS; arm++) + { + Vector direction = vector_from_angle((float)npc.stateFrame * FULL_TURN_DEGREES * MOTHER_SPIN_TURN + + (float)arm * SPIN_ARM_STEP); + ProjectileParams params = spin; + Vector position = vector_add(vector_scale(direction, SPIN_ARM_REACH), npc.pos); + Vector velocity = vector_scale(direction, speed); + for (int i = 0; (float)i < shots; i++) + { + if ((float)i == shots - 1) params.scale *= SPIN_SHOT_SCALE_LAST; + npc.FireProjectiles(position, velocity, PROJECTILES_SINGLE, params); + params.wiggleFrameOffset += 2; + params.changeTimeout -= 1; + float wave = std::cos((float)params.wiggleFrameOffset * 2 * PI_F * 2 / SPIN_WAVE_PERIOD); + position.x += wave * direction.y * SPIN_WAVE + velocity.x * SPIN_ADVANCE; + position.y += -direction.x * wave * SPIN_WAVE + velocity.y * SPIN_ADVANCE; + params.scale *= SPIN_SHOT_SCALE_STEP; + } + } +} + +// The spin: from its Shoot on, gore flies every 3 frames and arms of shots every 4, for 210 frames. +static void mother_spin_update(Entity_NPC& npc, int ticks) +{ + AnimationState& anim = npc.sprite.animState; + npc.friction = SPIN_FRICTION; + if (!anim.animData || !anim.isPlaying) + { + g_manager->sfxManager.SetAmbientSound(SOUND_ULTRA_GREED_SPINNING, 1, 1); + npc.sprite.Play("SpinLoop"); + } + bool isShooting = anim.animData && (anim.WasEventTriggered("Shoot") || anim.animData->isLooping); + if (!isShooting) return; + + for (int tick = 0; tick < ticks; tick++) + { + npc.stateFrame++; + if (npc.stateFrame % SPIN_GORE_EVERY == 0) + { + gibs_spawn({.color = npc.splatColor, + .position = npc.pos, + .spawner = &npc, + .speed = SPIN_GORE_SPEED, + .spread = GIB_SPREAD, + .amount = 1, + .gibFlags = (Random() & 1) ? 4u : GIB_BLOOD}); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector direction = vector_make(std::cos(angle), std::sin(angle)); + Vector velocity = vector_scale(direction, random_between(SPIN_SPLAT_SPEED, SPIN_SPLAT_SPEED_RANGE)); + Vector position = vector_add(vector_scale(direction, SPIN_SPLAT_REACH), npc.pos); + Entity* splat = + effect_spawn_at(EFFECT_BLOOD_EXPLOSION, SPLAT_MEDIUM, position, velocity, nullptr, Random()); + tint_set(*splat, npc.splatColor); + splat->sprite.offset = SPIN_SPLAT_OFFSET; + splat->renderDepthOffset = SPLAT_DEPTH; + } + if (npc.stateFrame % SPIN_SHOT_EVERY == 0) mother_spin_shots(npc); + if (npc.stateFrame <= MOTHER_SPIN_FRAMES) continue; + + npc.sprite.Play("SpinEnd"); + npc.stateFrame = 0; + npc.state = MOTHER2_IDLE; + return; + } +} + +// Lines a wall with tracers aimed across the room, 80 apart from the target's offset, 20 outside the wall. +static void mother_tracers_line(Entity_NPC& npc, Vector start, Vector along, float end, Vector aim) +{ + for (Vector spot = start; vector_dot(spot, along) < end; + spot = vector_add(spot, vector_scale(along, TRACER_SPACING))) + { + Entity* tracer = effect_spawn_at(EFFECT_MOTHER_TRACER, 0, spot, {}, &npc, Random()); + tracer->parent = &npc; + tracer->targetPosition = aim; + tracer->Update(); + } +} + +// The swipes: five in turn, each lining a wall with tracers that warn, then rush across the room with her swipe. +static void mother_swipe_update(Entity_NPC& npc, const MotherBounds& bounds) +{ + npc.friction *= SWIPE_FRICTION; + if (npc.stateFrame == 0) + { + npc.stateFrame = 1; + npc.sprite.Play(SWIPE_ANIMATIONS[npc.i2], PLAY_FORCED); + Vector target = npc.CalcTargetPosition(0); + if (npc.i2 == 0 || npc.i2 == 2) + { + float x = npc.i2 == 0 ? bounds.right + TRACER_OUTSIDE : bounds.left - TRACER_OUTSIDE; + float y = std::fmod(target.y - bounds.top, TRACER_SPACING) + bounds.top; + mother_tracers_line(npc, vector_make(x, y), vector_make(0, 1), bounds.bottom, + vector_make(npc.i2 == 0 ? -1 : 1, 0)); + } + else + { + float y = npc.i2 == 1 ? bounds.bottom + TRACER_OUTSIDE : bounds.top - TRACER_OUTSIDE; + float x = std::fmod(target.x - bounds.left, TRACER_SPACING) + bounds.left; + mother_tracers_line(npc, vector_make(x, y), vector_make(1, 0), bounds.right, + vector_make(0, npc.i2 == 1 ? -1 : 1)); + } + } + + AnimationState& anim = npc.sprite.animState; + if (anim.animData) + { + if (anim.IsEventTriggered("Sound")) npc_sound_play(SOUND_MOTHER_FISTPOUND1 + (int)(Random() % 3), 1, 2, 1); + if (anim.animData && anim.IsEventTriggered("Warn")) + for (Entity* tracer : entity_query(ENTITY_EFFECT, EFFECT_MOTHER_TRACER)) + { + auto* effect = static_cast(tracer); + if (effect->parent == &npc && effect->state < TRACER_WARN) effect->state = TRACER_WARN; + } + if (anim.animData && anim.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_DEATH_BURST_SMALL, 1, 2, 1); + for (Entity* tracer : entity_query(ENTITY_EFFECT, EFFECT_MOTHER_TRACER)) + { + auto* effect = static_cast(tracer); + if (effect->parent != &npc || effect->state >= TRACER_RUSH) continue; + + if (npc.i1 == SWIPES - 1) mother_sweep(npc, SWEEP_SHOTS); + effect->state = TRACER_RUSH; + Vector spray = + vector_scale(effect->targetPosition, random_between(SWIPE_BLOOD_SPEED, SWIPE_BLOOD_SPEED_RANGE)); + blood_explosion_spawn(2, effect->pos, effect->posOffset, npc.splatColor, spray); + Vector gibVelocity = + vector_scale(effect->targetPosition, random_between(SWIPE_GIB_SPEED, SWIPE_GIB_SPEED_RANGE)); + gibs_spawn({.color = npc.splatColor, + .position = vector_add(vector_scale(effect->targetPosition, SWIPE_GIB_REACH), effect->pos), + .velocity = gibVelocity, + .spread = GIB_SPREAD, + .amount = SWIPE_GIBS, + .gibFlags = GIB_BLOOD}); + } + npc.velocity = vector_add(npc.velocity, + vector_scale(vector_from_direction(npc.i2), SWIPE_LUNGE * npc.speedMultiplier)); + game_shake_screen(SWIPE_SHAKE); + } + if (anim.animData && anim.isPlaying) return; + } + + npc.i1++; + int next = 0; + if (npc.i1 < SWIPES) next = (npc.i1 == SWIPES - 1 ? npc.i2 + 2 : npc.i2 + 1 + ((Random() & 1) ? 0 : 2)) & 3; + else + { + npc.sprite.Play("Idle"); + npc.state = MOTHER2_IDLE; + npc.i1 = 0; + } + npc.i2 = next; + npc.stateFrame = 0; +} + +// The suction's pull on one entity in the cone ahead: players pulled less and by their mass, tears less, and anything +// within 20 swallowed (enemies but bosses killed, tears removed). +static void mother_suck_pull(Entity_NPC& npc, Entity& other, Vector aim) +{ + if (vector_dot(aim, vector_normalized(vector_sub(other.pos, npc.pos))) < SUCK_CONE) return; + + Vector back = vector_sub(npc.pos, other.pos); + float pull = SUCK_PULL / (vector_length_squared(back) * SUCK_PULL_FALLOFF + 1); + if (other.is_player()) pull = std::min(pull * SUCK_PLAYER_PULL, SUCK_PLAYER_PULL_MAX) / std::min(other.mass, 1.0f); + else if (other.IsTear()) pull *= SUCK_TEAR_PULL; + if (other.friction != 0) + other.velocity = + vector_add(other.velocity, vector_scale(vector_normalized(back), + pull * SUCK_PUSH * other.speedMultiplier / other.friction)); + if (vector_length_squared(vector_sub(npc.pos, other.pos)) >= SUCK_SWALLOW_SQUARED) return; + + if (Entity::is_enemy_type(other.type) && !other.IsBoss()) other.Kill(EntityRef(&npc)); + else if (other.IsTear()) other.Remove(); +} + +// Rubble the suction draws in from afar: a shot that falls toward her, fading in from outside the room or with a +// splat and dust inside it. +static void mother_suck_rubble(Entity_NPC& npc) +{ + float angle = random_unit() * SUCK_RUBBLE_SPREAD + (npc.v1.x - SUCK_RUBBLE_SPREAD * HALF); + float reach = random_between(SUCK_RUBBLE_NEAR, SUCK_RUBBLE_RANGE); + Vector position = vector_add(vector_scale(vector_from_angle(angle), reach), npc.pos); + auto* shot = static_cast( + g_game->Spawn({.position = position, .spawner = &npc, .type = ENTITY_PROJECTILE, .seed = Random()})); + ColorMod color = Random() & 1 ? SHOT_COLOR_SICK_PALE : SHOT_COLOR_SICK; + tint_set(*shot, color); + + uint64_t flags = PROJECTILE_HIT_ENEMIES; + if (!g_game->room->IsPositionInRoom(position, SUCK_RUBBLE_MARGIN)) + { + color._tint[3] = 0; + shot->SetColor(color, SUCK_RUBBLE_FADE, COLOR_PRIORITY_DEFAULT, true, true); + flags |= PROJECTILE_NO_WALL_COLLIDE; + } + else + { + dust_spawn(position, 1, ROCK_PARTICLE_BOUNCY); + Entity* splat = effect_spawn_at(EFFECT_BLOOD_EXPLOSION, SPLAT_MEDIUM, position, {}, nullptr, Random()); + tint_set(*splat, COLOR_GREEN_SPLAT); + splat->sprite.offset = {}; + splat->renderDepthOffset = SPLAT_DEPTH; + } + shot->projectileFlags = flags | PROJECTILE_ACCELERATE_TO_POSITION; + shot->parent = &npc; + shot->renderDepthOffset = SUCK_RUBBLE_DEPTH; + shot->targetPosition = npc.pos; + shot->fallingAccel = SUCK_RUBBLE_FALL; + shot->homingStrength = SUCK_RUBBLE_HOMING; + shot->friction = SUCK_RUBBLE_FRICTION; + shot->scale = ((float)std::min(Random() % 3 + 5, 13u) - 3) / 3; +} + +// The suction: she turns her open mouth toward the player while drifting to the middle, drawing in what lies ahead. +static void mother_suck_update(Entity_NPC& npc, int ticks) +{ + npc.friction *= SUCK_FRICTION; + bool isFinished = npc.sprite.IsFinished(); + if (npc.stateFrame < 0) + { + if (!isFinished) return; + Vector toPlayer = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + std::string_view begin = "ShootBegin"; + if (std::abs(toPlayer.x) > std::abs(toPlayer.y)) begin = toPlayer.x >= 0 ? "ShootRightBegin" : "ShootLeftBegin"; + npc.sprite.Play(begin); + npc.state = MOTHER2_SPIT; + npc.stateFrame = 0; + return; + } + + if (isFinished) npc.sprite.Play("ShootLoop"); + if (npc.sprite.IsEventTriggered("Shoot")) g_manager->sfxManager.SetAmbientSound(SOUND_MOTHER_SUCTION, 1, 1); + if (!npc.sprite.WasEventTriggered("Shoot") && !npc.sprite.animState.IsLoopingAnimation()) return; + + Vector drift = vector_scale(vector_sub(Room::GetCenterPos(), npc.pos), SUCK_DRIFT); + if (vector_length(drift) > SUCK_DRIFT_MAX) drift = vector_resized(drift, SUCK_DRIFT_MAX); + npc.velocity = vector_add(npc.velocity, vector_scale(drift, npc.speedMultiplier)); + float turn = npc.speedMultiplier * SUCK_TURN; + npc.v1.x = angle_approach(npc.v1.x, vector_angle(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)), turn); + Vector aim = vector_from_angle(npc.v1.x); + game_shake_screen(SUCK_SHAKE); + + EntityList_EL& entities = g_game->room->entityList.updateEL; + for (size_t i = 0; i < entities.size(); i++) + { + Entity* other = entities[i]; + if (other != &npc && (other->IsActiveEnemy(DEAD_EXCLUDED) || other->is_player() || other->IsTear())) + mother_suck_pull(npc, *other, aim); + } + + for (int tick = 0; tick < ticks; tick++) + { + npc.stateFrame++; + if (npc.stateFrame % SUCK_EFFECT_EVERY == 0) + { + Vector far = vector_add(vector_scale(aim, SUCK_EFFECT_REACH), npc.pos); + Entity* inward = effect_spawn_at(EFFECT_BIG_ATTRACT, 0, far, {}, nullptr, Random()); + inward->posOffset = SUCK_EFFECT_OFFSET; + inward->targetPosition = npc.pos; + tint_set(*inward, SUCK_EFFECT_COLOR); + inward->Update(); + Entity* mouth = effect_spawn_at(EFFECT_BIG_ATTRACT, 1, npc.pos, {}, nullptr, Random()); + mouth->posOffset = SUCK_EFFECT_OFFSET; + mouth->sprite.rotation = random_unit() * SUCK_EFFECT_SPREAD + (npc.v1.x - SUCK_EFFECT_SPREAD * HALF); + tint_set(*mouth, SUCK_EFFECT_COLOR); + mouth->Update(); + } + bool isRubbleTime = npc.stateFrame >= SUCK_RUBBLE_FIRST && npc.stateFrame <= SUCK_RUBBLE_LAST; + if (isRubbleTime && npc.stateFrame % SUCK_EFFECT_EVERY != 0) continue; + if (isRubbleTime) mother_suck_rubble(npc); + if (npc.stateFrame <= SUCK_FRAMES) continue; + npc.stateFrame = -1; + npc.sprite.Play("ShootEnd"); + } +} + +// The spit: one broccoli shot at the player with a recoil. Its end leaves the animation to finish on its own. +static void mother_spit_update(Entity_NPC& npc) +{ + npc.friction *= MOTHER_SPIT_FRICTION; + if (npc.stateFrame != 0) return; + + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_MOTHER_SHOOT, 1, 2, 1); + Vector aim = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.MakeBloodCloud(npc.pos, npc.splatColor, 1)->posOffset = SPIT_CLOUD_OFFSET; + ProjectileParams params; + params.color = COLOR_GREEN_SPLAT; + params.bulletFlags = PROJECTILE_BROCCOLI; + Entity_Projectile* shot = npc.FireBossProjectiles(1, {}, 0, params); + shot->height = MOTHER_SPIT_HEIGHT; + shot->fallingAccel = SPIT_FALL; + shot->velocity = vector_scale(aim, MOTHER_SPIT_SPEED); + shot->fallingSpeed = 0; + shot->homingStrength = SPIT_HOMING; + shot->subtype = SPIT_SUBTYPE; + shot->scale = 1; + blood_explosion_spawn(4, npc.pos, SPIT_BLOOD_OFFSET, SPIT_BLOOD_COLOR, {}); + npc.velocity = vector_add(npc.velocity, vector_scale(aim, -MOTHER_SPIT_RECOIL)); + } + if (!npc.sprite.IsFinished()) return; + npc.state = MOTHER2_IDLE; + npc.i1 = 0; + npc.i2 = 0; + npc.stateFrame = 0; +} + +// The jump: she leaps out of the room, comes back above it on the player's side and charges down. +static void mother_jump_update(Entity_NPC& npc, int ticks, const MotherBounds& bounds) +{ + npc.friction *= MOTHER_JUMP_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc_sound_play(SOUND_MEAT_JUMPS, JUMP_SOUND_VOLUME, 2, 1); + } + if (!npc.sprite.IsFinished()) return; + + npc.stateFrame += ticks; + if (npc.stateFrame > JUMP_AWAY && vector_is_zero(npc.targetPosition)) + { + float middle = (bounds.right + bounds.left) * HALF; + float x = middle <= npc.GetPlayerTarget()->pos.x ? bounds.right - JUMP_INSET : bounds.left + JUMP_INSET; + npc.pos = vector_make(x, bounds.top - JUMP_ABOVE); + npc.targetPosition = vector_make(x, 1); + mother_slam_burst(npc, vector_make(0, -1)); + } + if (npc.stateFrame <= JUMP_FRAMES) return; + + npc.sprite.Play("ChargeLoop"); + npc.velocity = JUMP_CHARGE; + npc_sound_play(SOUND_MAGGOT_BURST_OUT, 1, 2, 1); + npc_sound_play(SOUND_MOTHER_CHARGE1, 1, 2, 1); + npc.entityCollisionClass = ENTCOLL_ALL; + npc.state = MOTHER2_CHARGE; + mother_slam_burst(npc, npc.velocity); + Vector widened = vector_make(npc.config->collisionRadiusMulti.x * JUMP_WIDEN, npc.config->collisionRadiusMulti.y); + npc.SetSize(npc.config->collisionRadius, widened, npc.config->gridCollisionPoints); +} + +// Her idle: she walks after the player and picks an attack once her rest is out, one in 15 a frame, or at once after +// a minute. +static void mother2_idle_update(Entity_NPC& npc, int ticks) +{ + if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) npc.sprite.Play("Idle"); + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), MOTHER2_PATH_SPEED, MOTHER2_PATH_MARKER, DIRECT_PATH_FAR); + npc.projectileCooldown -= ticks; + if (npc.projectileCooldown >= 1 || + (Random() % MOTHER2_ATTACK_ODDS != 0 && npc.projectileCooldown >= MOTHER2_ATTACK_LATE)) + return; + + switch (Random() & 3) + { + case 0: + npc.state = MOTHER2_JUMP; + npc_sound_play(SOUND_MOTHER_ANGER_SHAKE, 1, 2, 1); + npc.sprite.Play("JumpUp"); + npc.stateFrame = 0; + npc.i1 = 0; + npc.projectileCooldown = MOTHER2_LONG_REST; + npc.targetPosition = {}; + break; + case 1: + npc.state = MOTHER2_SUCK; + npc.sprite.Play("ShootBegin"); + npc.stateFrame = 0; + npc.projectileCooldown = MOTHER2_LONG_REST; + npc.v1.x = vector_angle(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + break; + case 2: + npc.state = MOTHER2_SWIPE; + npc_sound_play(SOUND_MOTHER_WALL_SHOT_START, 1, 2, 1); + npc.i1 = 0; + npc.i2 = (int)(Random() & 3); + npc.stateFrame = 0; + npc.projectileCooldown = MOTHER2_SHORT_REST; + break; + default: + npc_sound_play(SOUND_MOTHER_SPIN_START, 1, 2, 1); + npc.sprite.Play("SpinBegin"); + npc.state = MOTHER2_SPIN; + npc.stateFrame = 0; + npc.projectileCooldown = MOTHER2_SHORT_REST; + break; + } +} + +// Fades out one of her looping sounds once its attack is over, and stops it when she dies. +static void mother_loop_fade(Entity_NPC& npc, int sound, int state, float step) +{ + SFXManager& sfx = g_manager->sfxManager; + if (!sfx.IsPlaying(sound)) return; + if (npc.isDead) sfx.Stop(sound); + else if (npc.state != state) sfx.SetAmbientSound(sound, sfx.GetAmbientSoundVolume(sound) - step, 1); +} + +// 0056cd60 Mother's second phase (912.10): out of the wall, she charges through the room, spins, swipes, sucks the +// room in and spits, and melts as she dies. +static void boss_mother_phase_two_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + MotherBounds bounds{.left = room.topLeftPos.x, + .right = room.bottomRightPos.x, + .top = room.topLeftPos.y, + .bottom = room.bottomRightPos.y}; + int ticks = npc_ticks_get(npc); + AnimationState& anim = npc.sprite.animState; + + if (anim.animData && anim.isPlaying && anim.animData->name == "Death") + { + if (anim.IsEventTriggered("Sound")) npc_sound_play(SOUND_MOTHER_DEATH2, 1, 2, 1); + else if (anim.animData && anim.IsEventTriggered("Shoot")) npc_sound_play(SOUND_MOTHER_DEATH_MELT, 1, 2, 1); + } + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.i1 = 0; + npc.i2 = 0; + npc.stateFrame = 0; + npc.projectileDelay = 0; + npc.projectileCooldown = 0; + npc.state = MOTHER2_IDLE; + break; + case MOTHER2_IDLE: + mother2_idle_update(npc, ticks); + break; + case MOTHER2_CHARGE: + mother_charge_update(npc, bounds); + break; + case MOTHER2_LAND: + mother_land_update(npc); + break; + case MOTHER2_SPIN: + mother_spin_update(npc, ticks); + break; + case MOTHER2_SWIPE: + mother_swipe_update(npc, bounds); + break; + case MOTHER2_SUCK: + mother_suck_update(npc, ticks); + break; + case MOTHER2_SPIT: + mother_spit_update(npc); + break; + case MOTHER2_JUMP: + mother_jump_update(npc, ticks, bounds); + break; + case MOTHER2_ARRIVE: + room.camera->SetFocusPosition(vector_add(npc.pos, MOTHER_CAMERA_LEAD)); + npc.friction = ARRIVE_FRICTION; + if (npc.stateFrame == 0) npc_sound_play(SOUND_MOTHER_APPEAR2, 1, 2, 1); + npc.stateFrame += ticks; + if (npc.stateFrame > ARRIVE_FRAMES) npc.sprite.Play("ChargeEnd"); + if (!npc.sprite.IsFinished()) break; + // 0056c7c0 Clears her counters. + npc.i1 = 0; + npc.i2 = 0; + npc.stateFrame = 0; + npc.projectileDelay = 0; + npc.projectileCooldown = 0; + npc.state = MOTHER2_IDLE; + break; + } + + mother_loop_fade(npc, SOUND_MOTHER_SUCTION, MOTHER2_SUCK, SUCK_VOLUME_STEP); + mother_loop_fade(npc, SOUND_ULTRA_GREED_SPINNING, MOTHER2_SPIN, SPIN_VOLUME_STEP); +} + +// The segments still out of a worm's deque. +static int worm_segments_count(Entity_NPC& npc) +{ + return (int)std::count_if(npc.entityDeque.begin(), npc.entityDeque.end(), + [](const EntityPtr& segment) { return segment && segment->type == ENTITY_PROJECTILE; }); +} + +// A worm's first frame: an unseen head trailed by six to eight tinted shots, shrinking from the second on. +static void mother_worm_init(Entity_NPC& npc) +{ + npc.AddEntityFlags(MOTHER_SUMMON_FLAGS); + npc.isInvincible = true; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.state = NPC_STATE_IDLE; + npc.isVisible = false; + int segments = (int)(Random() % WORM_SEGMENTS_RANGE) + WORM_SEGMENTS_MIN; + npc.ClearDequeRefs(); + npc.entityDeque.resize(segments); + + for (int i = 0; i < segments; i++) + { + auto* segment = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = npc.spawnerEntity, .type = ENTITY_PROJECTILE, .seed = Random()})); + segment->parent = npc.spawnerEntity; + tint_set(*segment, SPIN_SHOT_COLOR); + segment->projectileFlags = WORM_SEGMENT_FLAGS; + segment->fallingAccel = WORM_SEGMENT_FALL; + float scale = random_unit() * WORM_SCALE_RANGE; + scale += i == 0 ? WORM_HEAD_SCALE : WORM_SEGMENT_SCALE - (float)i * WORM_SEGMENT_TAPER; + segment->scale = scale * npc.scale; + npc.entityDeque[i] = segment; + } +} + +// A worm weaves for its timer, then homes in on its target for 30 frames, and leaves once out of the room for long. +static void mother_worm_steer(Entity_NPC& npc) +{ + Entity* mother = npc.spawnerEntity; + if (!mother || mother->isDead) return npc.Remove(); + + int delay = npc.projectileDelay; + float speed = vector_length(npc.velocity); + if (delay > 0) + { + float ramp = std::clamp((float)delay / WORM_WEAVE_RAMP, 0.0f, 1.0f); + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float jitter = random_unit(); + Vector heading = vector_normalized(npc.velocity); + Vector weave = vector_rotated(heading, std::cos(npc.updateTime * WORM_WEAVE_SPEED) * WORM_WEAVE_DEGREES); + Vector velocity = vector_add(vector_add(npc.velocity, vector_make(std::cos(angle) * WORM_JITTER * jitter, + std::sin(angle) * WORM_JITTER * jitter)), + weave); + float target = (ramp * WORM_WEAVE_RANGE + WORM_WEAVE_SLOWDOWN) * speed; + npc.velocity = velocity; + if (vector_length(velocity) > 0) npc.velocity = vector_resized(velocity, std::max(target, WORM_MIN_SPEED)); + return; + } + + float ramp = std::clamp((float)delay / WORM_HOME_RAMP, 0.0f, 1.0f); + if (npc.target && delay > WORM_HOME_FRAMES) + npc.velocity = vector_add(npc.velocity, vector_resized(vector_sub(npc.target->pos, npc.pos), 1)); + float target = std::min((ramp * WORM_SPEEDUP + 1) * speed, WORM_MAX_SPEED); + if (vector_length(npc.velocity) > 0) npc.velocity = vector_resized(npc.velocity, target); + if (npc.projectileDelay <= WORM_LEAVE_FRAMES && !g_game->room->IsPositionInRoom(npc.pos, WORM_ROOM_MARGIN)) + npc.Remove(); +} + +// 00565e00 Mother's worm (912.30): an unseen head that weaves, then homes in, its segments of shots trailing it along +// its path 10 apart, popping when it goes. +static void mother_worm_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) return mother_worm_init(npc); + if (worm_segments_count(npc) == 0) return npc.Remove(); + + if (npc.projectileDelay > WORM_DELAY_FLOOR) npc.projectileDelay -= npc_ticks_get(npc); + mother_worm_steer(npc); + + if (npc.isDead) + { + for (EntityPtr& segment : npc.entityDeque) + if (segment && segment->type == ENTITY_PROJECTILE) + { + static_cast(segment.get())->projectileFlags = 0; + segment->isDead = true; + } + return; + } + + std::deque& trail = npc.vectorDeque1; + trail.push_front(npc.pos); + if (trail.size() > WORM_TRAIL) trail.resize(WORM_TRAIL); + Vector link = npc.pos; + size_t next = trail.size() > 1 ? 1 : 0; + for (EntityPtr& segment : npc.entityDeque) + { + if (!segment || segment->type != ENTITY_PROJECTILE) continue; + segment->velocity = vector_sub(link, segment->pos); + float left = npc.scale * WORM_LINK; + while (next != trail.size() && left > 0) + { + Vector step = vector_sub(trail[next], link); + float length = vector_length(step); + if (left < length) + { + step = vector_resized(step, left); + left = 0; + } + else + { + left -= length; + next++; + } + link = vector_add(link, step); + } + } +} + +// A ball's touch: it pushes players and some familiars away at 10 and hurts them by its collision damage, and the big +// one hurts the vulnerable enemies but bosses by 40. +static void mother_orb_collide(Entity_NPC& npc) +{ + Entity* other = npc.collisionEntity; + bool isPushedFamiliar = + other->IsFamiliar() && + (other->variant == Entity_Familiar::ISAACS_HEART || other->variant == Entity_Familiar::PUNCHING_BAG || + other->variant == Entity_Familiar::LOST_SOUL || other->variant == Entity_Familiar::MILK); + if (other->is_player() || isPushedFamiliar) + { + Vector away = vector_sub(other->pos, npc.pos); + if (vector_length(away) > 0) away = vector_resized(away, ORB_PUSH); + other->velocity = vector_add(other->velocity, vector_scale(away, other->speedMultiplier)); + other->TakeDamage(npc.collisionDamage, 0, EntityRef(&npc), MOTHER_HIT_COUNTDOWN); + npc.collisionResult = 0; + return; + } + if (other->IsFamiliar() || !Entity::is_enemy_type(other->type) || npc.subtype != MOTHER_ORB_BIG) return; + + if (other->IsVulnerableEnemy(nullptr) && !other->IsBoss()) + other->TakeDamage(ORB_ENEMY_DAMAGE, 0, EntityRef(&npc), MOTHER_HIT_COUNTDOWN); + npc.collisionResult = 0; +} + +// A ball's first frame: the big one darkens in, small at first and with a tight hitbox, the others time out. +static void mother_orb_init(Entity_NPC& npc) +{ + npc.AddEntityFlags(MOTHER_SUMMON_FLAGS); + npc.isInvincible = true; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.aiCallFlags = AI_CALL_COLLISION; + npc.state = NPC_STATE_IDLE; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.renderDepthOffset = MOTHER_ORB_DEPTH; + npc.v1.x = random_unit() * FULL_TURN_DEGREES; + npc.splatColor = COLOR_GREEN_SPLAT; + + switch (npc.subtype) + { + case MOTHER_ORB_BIG: + npc.sprite.Play("Idle"); + npc.posOffset.y = ORB_BIG_RISE; + npc.SetColor(ORB_DARK, ORB_DARK_FRAMES, COLOR_PRIORITY_DEFAULT, true, true); + sprite_scale_set(npc, ORB_START_SCALE); + for (Vector& point : npc.collisionPoints) point = vector_scale(point, ORB_COLLISION_SCALE); + break; + case MOTHER_ORB_MEDIUM: + npc.sprite.Play("Idle2"); + npc.posOffset.y = ORB_MEDIUM_RISE; + npc.stateFrame = ORB_MEDIUM_TIMER; + break; + case MOTHER_ORB_SMALL: + npc.sprite.Play("Idle3"); + npc.posOffset.y = ORB_SMALL_RISE; + npc.sprite.isFlipX = !(Random() & 1); + npc.stateFrame = ORB_SMALL_TIMER; + break; + } +} + +// A ball rolls: its layer turns with its speed. +static void mother_orb_roll(Entity_NPC& npc) +{ + float spin = std::min(vector_length(npc.velocity) * ORB_SPIN, ORB_SPIN_MAX); + npc.v1.x = normalize_angle_degrees(spin * npc.speedMultiplier + npc.v1.x); + npc.sprite.GetLayer(0)->rotation = npc.v1.x; +} + +// The blood a ball trails every other frame. +struct OrbTrail +{ + float reach = 0; + float scale = 1; + float playback = 1; +}; + +static void mother_orb_trail(Entity_NPC& npc, const OrbTrail& look) +{ + uint32_t seed = Random(); + Vector velocity = vector_scale(npc.velocity, HALF); + Vector direction = random_direction(); + Vector position = vector_add(vector_scale(direction, look.reach * random_unit()), npc.pos); + Entity* trail = effect_spawn_at(EFFECT_HAEMO_TRAIL, 0, position, velocity, &npc, seed); + trail->posOffset = npc.posOffset; + tint_set(*trail, ORB_TRAIL_COLOR); + sprite_scale_set(*trail, look.scale); + trail->sprite.playbackSpeed = look.playback; + trail->renderDepthOffset = ORB_TRAIL_DEPTH; + trail->Update(); +} + +// The smaller balls roll until their timer runs out or they hit a wall, then burst, trailing blood while loose. +static void mother_orb_small_update(Entity_NPC& npc) +{ + if (npc.subtype == MOTHER_ORB_SMALL) + npc.friction *= 1 - std::clamp(npc.updateTime / ORB_SMALL_SLOWDOWN_FRAMES, 0.0f, 1.0f) * ORB_SMALL_SLOWDOWN; + mother_orb_roll(npc); + npc.stateFrame -= npc_ticks_get(npc); + if ((npc.isCollidesWithGrid || npc.stateFrame < 1) && !npc.isDead) + { + npc.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + npc.Kill(EntityRef()); + mother_orb_burst(npc); + } + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + if (!npc.GetIntervalTicks(2, 0) || npc.entityRef) return; + + if (npc.subtype == MOTHER_ORB_MEDIUM) + mother_orb_trail(npc, {ORB_TRAIL_MEDIUM_REACH, ORB_TRAIL_MEDIUM_SCALE, ORB_TRAIL_MEDIUM_PLAYBACK}); + else mother_orb_trail(npc, {ORB_TRAIL_SMALL_REACH}); +} + +// The big ball bounces off a wall: shots ring off the floor (a shake for a side wall), and it heads away from it. +static void mother_orb_bounce(Entity_NPC& npc) +{ + bool isFloor = npc.gridCollisionNormal.y > 0 && std::abs(npc.gridCollisionNormal.x) < ORB_FLOOR_NORMAL; + if (isFloor) + { + game_shake_screen(ORB_FLOOR_SHAKE); + npc_sound_play(SOUND_DEATH_BURST_LARGE, ORB_BOUNCE_VOLUME, 2, 1); + ProjectileParams params; + params.fallingAccelModifier = ORB_RING_FALL; + params.isFallingKept = true; + params.scale = ORB_RING_BIG_SCALE; + params.color = SHOT_COLOR_SICK; + params.circleAngle = 0; + npc.FireProjectiles(npc.pos, ORB_RING_BIG, PROJECTILES_RING, params); + params.color = SHOT_COLOR_SICK_PALE; + params.scale = ORB_RING_SMALL_SCALE; + npc.FireProjectiles(npc.pos, ORB_RING_SMALL, PROJECTILES_RING, params); + } + else + { + game_shake_screen(ORB_WALL_SHAKE); + npc_sound_play(SOUND_DEATH_BURST_SMALL, ORB_BOUNCE_VOLUME, 2, 1); + } + + Vector& push = npc.targetPosition; + float strength = vector_length(push); + Vector normal = npc.gridCollisionNormal; + push = vector_normalized(vector_sub(push, vector_scale(normal, 2 * vector_dot(normal, push)))); + if (std::abs(push.y) < ORB_MIN_TILT) + { + push.y = push.y <= 0 ? -ORB_MIN_TILT : ORB_MIN_TILT; + push = vector_normalized(push); + } + push = vector_resized(push, strength); + npc.velocity = vector_resized(push, vector_length(npc.gridCollisionVelocity)); + npc.mass = npc.config->mass; +} + +// 00566810 Mother's ball (912.100): the big one rolls with a sickly pulse under its push, steering after the player +// (or back up to Mother once batted) and bouncing off the walls; the smaller ones burst when their timer runs out. +static void mother_orb_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_COLLISION) return mother_orb_collide(npc); + if (npc.state == NPC_STATE_INIT) return mother_orb_init(npc); + if (npc.isDead) return; + if (npc.subtype != MOTHER_ORB_BIG) return mother_orb_small_update(npc); + + float rush = std::clamp(vector_length(npc.targetPosition) - ORB_PULSE_ROLL, 0.0f, 1.0f) + 0; + float period = rush * ORB_PULSE_FAST + 1; + if (rush == 1) period += period; + float wave = std::sin(npc.updateTime * ORB_PULSE_SPEED * PI_F / (period * ORB_PULSE_PERIOD)); + float glow = (wave + 1) * HALF * rush; + npc.sprite.GetLayer(0)->color = { + {1 - glow * ORB_PULSE_RED, 1 - glow * ORB_PULSE_GREEN, 1 - glow * ORB_PULSE_BLUE, 1}, + {0, 0, 0, 0}, + {glow * ORB_GLOW_RED, glow * ORB_GLOW_GREEN, glow * ORB_GLOW_BLUE}}; + sprite_scale_set(npc, std::min(npc.speedMultiplier * ORB_GROWTH + npc.sprite.scale.x, 1.0f)); + mother_orb_roll(npc); + npc.friction *= ORB_FRICTION; + npc.velocity = vector_add(npc.velocity, vector_scale(npc.targetPosition, npc.speedMultiplier)); + if (npc.GetIntervalTicks(2, 0)) + mother_orb_trail(npc, {ORB_TRAIL_BIG_REACH, ORB_TRAIL_BIG_SCALE, ORB_TRAIL_BIG_PLAYBACK}); + + if (npc.target && npc.mass > npc.config->mass) + { + Entity* toward = npc.targetPosition.y <= 0 ? npc.parent.get() : npc.GetPlayerTarget(); + if (toward) + { + Vector aim = vector_normalized(vector_sub(toward->pos, npc.pos)); + bool isSteered = npc.targetPosition.y <= 0 ? aim.y < -ORB_STEER_LIMIT : aim.y > ORB_STEER_LIMIT; + if (isSteered) + { + Vector steered = vector_add(npc.targetPosition, vector_scale(aim, ORB_STEER * npc.speedMultiplier)); + npc.targetPosition = vector_resized(steered, vector_length(npc.targetPosition)); + } + } + } + if (npc.isCollidesWithGrid && !npc.isDead) mother_orb_bounce(npc); +} + +// One piece of a burst: a splat and a smaller ball flung out along a clear line, held as long as Mother broke it. +static void mother_orb_piece(Entity_NPC& npc, Vector direction, int size) +{ + Vector splatVelocity = vector_scale(direction, random_between(ORB_PIECE_SPLAT_SPEED, ORB_PIECE_SPLAT_SPEED)); + Entity* splat = effect_spawn_at(EFFECT_BLOOD_EXPLOSION, SPLAT_BIG, + vector_add(vector_scale(direction, ORB_PIECE_SPLAT_REACH), npc.pos), splatVelocity, + nullptr, Random()); + tint_set(*splat, npc.splatColor); + splat->sprite.offset = npc.posOffset; + splat->renderDepthOffset = SPLAT_DEPTH; + + uint32_t seed = Random(); + Entity_NPC* piece = mother_spawn(MOTHER_ORB, size, vector_add(vector_scale(direction, ORB_PIECE_REACH), npc.pos), + vector_scale(direction, ORB_PIECE_SPEED), npc.spawnerEntity, seed); + piece->targetPosition = direction; + piece->entityRef = npc.entityRef; + piece->Update(); + if (!piece->entityRef) return; + piece->stateFrame = + size == MOTHER_ORB_SMALL ? ORB_SMALL_HELD : (int)(Random() % ORB_MEDIUM_HELD_RANGE) + ORB_MEDIUM_HELD_MIN; +} + +// 00567d50 A ball bursts: the big one into eight medium ones (wider apart when Mother broke it, hurting her by 400), +// a medium one into six small ones or, broken by Mother, a splash hurting her by 60, and a small one into a maggot or +// 30 of hurt to Mother. +static void mother_orb_burst(Entity_NPC& npc) +{ + Entity* mother = npc.entityRef; + if (npc.subtype == MOTHER_ORB_SMALL) + { + if (mother) mother->TakeDamage(ORB_SMALL_MOTHER_DAMAGE, 0, EntityRef(), MOTHER_HIT_COUNTDOWN); + else + small_maggot_spawn(npc.pos, ORB_MAGGOT_HEIGHT, {}, ORB_MAGGOT_RISE - random_unit() * ORB_MAGGOT_RISE_RANGE); + return; + } + + if (npc.subtype == MOTHER_ORB_MEDIUM) + { + if (mother) + { + if (mother->entityCollisionClass != ENTCOLL_NONE) + mother->TakeDamage(ORB_MEDIUM_MOTHER_DAMAGE, 0, EntityRef(), MOTHER_HIT_COUNTDOWN); + npc_sound_play(SOUND_DEATH_BURST_LARGE, 1, 2, 1); + blood_explosion_spawn(4, npc.pos, npc.posOffset, npc.splatColor, vector_scale(npc.velocity, HALF)); + game_shake_screen(ORB_MEDIUM_SHAKE); + return; + } + for (int i = 0; i < ORB_MEDIUM_PIECES; i++) + { + Vector direction = vector_rotated(vector_make(0, 1), (float)i * ORB_MEDIUM_PIECE_STEP); + if (room_line_is_clear(npc.pos, vector_scale(direction, ORB_MEDIUM_PIECE_REACH))) + mother_orb_piece(npc, direction, MOTHER_ORB_SMALL); + } + return; + } + + float spread = 1; + if (mother) + { + if (mother->entityCollisionClass != ENTCOLL_NONE) + mother->TakeDamage(ORB_BIG_MOTHER_DAMAGE, 0, EntityRef(), MOTHER_HIT_COUNTDOWN); + spread = ORB_MOTHER_SPREAD; + } + for (int i = 0; i < ORB_BIG_PIECES; i++) + { + Vector direction = vector_rotated(vector_make(0, 1), (float)i * ORB_BIG_PIECE_STEP); + direction.x *= spread; + if (room_line_is_clear(npc.pos, vector_scale(direction, ORB_BIG_PIECE_REACH))) + mother_orb_piece(npc, direction, MOTHER_ORB_MEDIUM); + } + gibs_spawn({.color = npc.splatColor, + .position = npc.pos, + .spawner = &npc, + .speed = ORB_GIB_SPEED, + .spread = GIB_SPREAD, + .amount = ORB_BIG_GIBS, + .gibFlags = npc.config->gibFlags}); + npc_sound_play(SOUND_DEATH_BURST_LARGE, 1, 2, 1); + game_shake_screen(ORB_BIG_SHAKE); +} + +// Mother's forms by variant: her phases, the Dead Isaacs (which walk as rotten gapers), her worms and her balls. +void boss_mother_update(Entity_NPC& npc) +{ + switch (npc.variant) + { + case MOTHER_PHASE_ONE: + return boss_mother_phase_one_update(npc); + case MOTHER_PHASE_TWO: + return boss_mother_phase_two_update(npc); + case MOTHER_DEAD_ISAAC: + return npc_rotten_gaper_update(npc); + case MOTHER_WORM: + return mother_worm_update(npc); + case MOTHER_ORB: + return mother_orb_update(npc); + } +} + +// 0056fcf0 Her first phase draws in the wall's space, snapped to the screen's pixels, each part as its layer of the +// body's sprite in its own color. Her other forms draw as entities do. +void mother_render(Entity_NPC& npc, const Vector& offset) +{ + if (npc.variant != MOTHER_PHASE_ONE) return npc.Entity::Render(offset); + + npc.renderPosition = vector_add(render_position_get(vector_add(npc.posOffset, npc.pos), RENDER_SNAPPED), offset); + Entity_NPC* body = &npc; + if (npc.subtype != MOTHER_PART_BODY && npc.parent) body = static_cast(npc.parent.get()); + ColorMod kept = body->sprite.color; + body->sprite.color = npc.sprite.color; + body->sprite.RenderLayer(npc.subtype, {.position = npc.renderPosition}); + body->sprite.color = kept; +} diff --git a/src/boss_pool.h b/src/boss_pool.h index a57f91a..8f7369a 100644 --- a/src/boss_pool.h +++ b/src/boss_pool.h @@ -18,6 +18,7 @@ constexpr int BOSS_SATAN = 24; constexpr int BOSS_ISAAC = 39; constexpr int BOSS_BLUE_BABY = 40; constexpr int BOSS_MEGA_SATAN = 55; +constexpr int BOSS_ULTRA_GREED = 62; constexpr int BOSS_MOTHER = 88; constexpr int BOSS_MOM_MAUSOLEUM = 89; constexpr int BOSS_DOGMA = 99; diff --git a/src/boss_repentance.h b/src/boss_repentance.h new file mode 100644 index 0000000..ab3d213 --- /dev/null +++ b/src/boss_repentance.h @@ -0,0 +1,22 @@ +#pragma once + +#include "entity_npc.h" + +// Rotgut's forms, by variant: the face in the wall, the maggot in its first dungeon and the heart in its second. +enum RotgutVariant +{ + ROTGUT_FACE, + ROTGUT_MAGGOT, + ROTGUT_HEART +}; + +// The Repentance enemies' and bosses' AIs the dispatcher (npc_ai_update) runs by type. +void boss_colostomia_update(Entity_NPC& npc); +void boss_horny_boys_update(Entity_NPC& npc); +void boss_rotgut_update(Entity_NPC& npc); +void npc_adult_leech_update(Entity_NPC& npc); +void npc_spikeball_update(Entity_NPC& npc); +void npc_gasbag_update(Entity_NPC& npc); +void npc_generic_prop_update(Entity_NPC& npc); +void boss_turdlet_update(Entity_NPC& npc); +void rotgut_death_spawn_effects(Entity_NPC& npc); diff --git a/src/boss_rotgut.cpp b/src/boss_rotgut.cpp new file mode 100644 index 0000000..8137aac --- /dev/null +++ b/src/boss_rotgut.cpp @@ -0,0 +1,1449 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_laser.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "grid_entity.h" +#include "loot_list.h" +#include "npc_basement.h" +#include "room_transition.h" +#include + +// Rotgut's states: idle, its three attacks (the face's spirals, rubble and munch, the maggot's butt attacks), the +// maggot's two head attacks, its suck, the heart's retreat and summon, and the face's fall into the dungeon. +constexpr int ROTGUT_IDLE = NPC_STATE_IDLE; +constexpr int ROTGUT_RETRACTED = NPC_STATE_MOVE; +constexpr int ROTGUT_SUCK = NPC_STATE_STOMP; +constexpr int ROTGUT_ATTACK = NPC_STATE_ATTACK; +constexpr int ROTGUT_ATTACK2 = NPC_STATE_ATTACK2; +constexpr int ROTGUT_ATTACK3 = NPC_STATE_ATTACK3; +constexpr int ROTGUT_HEAD_LASER = NPC_STATE_ATTACK4; +constexpr int ROTGUT_HEAD_SPRAY = NPC_STATE_ATTACK5; +constexpr int ROTGUT_SUMMON = NPC_STATE_SUMMON; +constexpr int ROTGUT_TRANSITION = NPC_STATE_SPECIAL; + +constexpr float ROTGUT_FRICTION = 0.6f; +constexpr RNG ROTGUT_PICK_RNG = {0, 5, 9, 7}; +constexpr float ROTGUT_MOUTH_DROP = 10; +constexpr float ROTGUT_HEART_MOUTH = 20; +constexpr float ROTGUT_SHOT_SPEED = 6; +constexpr float ROTGUT_SHOT_FALL = -0.12f; + +// The face: an attack one in 20 frames after 45, its spirals (eight every 14 frames, turning on alternate volleys), +// crosses and waves for 180 frames, its rubble rain for 90 and its munch's three bites. +constexpr int FACE_REST = 45; +constexpr uint32_t FACE_ATTACK_ODDS = 20; +constexpr int FACE_SPIRAL_EVERY = 14; +constexpr int FACE_SPIRAL_SWAP = 28; +constexpr int FACE_SPIRAL_SHOTS = 8; +constexpr float FACE_SPIRAL_STEP = 45; +constexpr float FACE_SPIRAL_CURVE = 0.006f; +constexpr int FACE_WAVE_EVERY = 3; +constexpr float FACE_CROSS_SWAY = 45; +constexpr float FACE_CROSS_SPIN = 6; +constexpr int FACE_CROSS_SHOTS = 4; +constexpr float FACE_WAVE_TURN = 8; +constexpr float FACE_WAVE_BIG_SCALE = 1.5f; +constexpr float FACE_WAVE_BIG_SPEED = 8; +constexpr int FACE_SHOTS_FRAMES = 180; +constexpr int FACE_RUBBLE_FRAMES = 90; +constexpr int FACE_RUBBLE_COOLDOWN = 240; + +// The rubble: a pick among puke, bones, small maggots and meat thrown at random spots, and a splash of rotten blood. +enum FaceRubble +{ + RUBBLE_PUKE, + RUBBLE_BONE, + RUBBLE_MAGGOT, + RUBBLE_MEAT +}; +constexpr int RUBBLE_PUKE_WEIGHT = 65; +constexpr int RUBBLE_BONE_WEIGHT = 20; +constexpr int RUBBLE_MAGGOT_WEIGHT = 10; +constexpr int RUBBLE_MEAT_WEIGHT = 5; +constexpr float RUBBLE_MOUTH_RISE = 4; +constexpr float RUBBLE_MARGIN = 10; +constexpr float RUBBLE_AIM = 0.024f; +constexpr float RUBBLE_HEIGHT_RANGE = -8; +constexpr float RUBBLE_FALL_SPEED = -60; +constexpr float RUBBLE_FALL_ACCEL = 2; +constexpr float RUBBLE_PUKE_SCALE = 2; +constexpr float RUBBLE_MAGGOT_HEIGHT = -60; +constexpr float RUBBLE_MAGGOT_RISE = -20; +constexpr float RUBBLE_SPLASH_SPREAD = 30; +constexpr float RUBBLE_SPLASH_SPEED = 8; +constexpr float RUBBLE_SPLASH_SPEED_RANGE = 10; +constexpr float RUBBLE_SPLASH_WOBBLE = 4; +constexpr float RUBBLE_SPLASH_HEIGHT = -14; +constexpr float RUBBLE_SPLASH_RISE = 26; +constexpr float RUBBLE_SPLASH_RISE_RANGE = 16; +constexpr int RUBBLE_SPLASH_DEPTH = 500; +constexpr float RUBBLE_SPLASH_SCALE = 0.8f; +constexpr float RUBBLE_SPLASH_SCALE_RANGE = 0.4f; +constexpr uint32_t RUBBLE_GIB_MASK = 7; +constexpr uint32_t RUBBLE_GIB_PLAIN_ODDS = 5; +constexpr float RUBBLE_GIB_REACH = 12; +constexpr float RUBBLE_GIB_SPEED = 5; +constexpr float RUBBLE_GIB_HEIGHT = -60; +constexpr int RUBBLE_SHAKE = 4; + +// The munch: a ring of 18 then of 9, then 22 slowing shots, or 20 pairs of fans to the sides. +constexpr float MUNCH_RING_SPEED = 5; +constexpr float MUNCH_RING_SHOTS = 18; +constexpr float MUNCH_SMALL_RING_SPEED = 10; +constexpr float MUNCH_SMALL_RING_SHOTS = 9; +constexpr int MUNCH_SPRAY_SHOTS = 22; +constexpr float MUNCH_SPRAY_REACH = 5; +constexpr float MUNCH_SPRAY_SPEED = 15; +constexpr float MUNCH_SPRAY_HEIGHT = -22; +constexpr float MUNCH_SPRAY_HEIGHT_RANGE = 8; +constexpr float MUNCH_SPRAY_FALL = -0.06f; +constexpr float MUNCH_SPRAY_FALL_RANGE = 0.030000005f; +constexpr float MUNCH_SPRAY_SCALE = 0.6f; +constexpr float MUNCH_SPRAY_SCALE_RANGE = 1.1999999f; +constexpr float MUNCH_SPRAY_BIG = 1.2f; +constexpr float MUNCH_SPRAY_SLOWDOWN = 0.9f; +constexpr int MUNCH_FAN_PAIRS = 20; +constexpr float MUNCH_FAN_SPREAD = 30; +constexpr float MUNCH_FAN_SPEED = 20; +constexpr float MUNCH_FAN_RISE = -4; +constexpr float MUNCH_FAN_FALL = 0.2f; +constexpr float MUNCH_FAN_SCALE = 0.8f; +constexpr float MUNCH_FAN_SCALE_RANGE = 0.7f; +constexpr float MUNCH_SPLASH_HEIGHT = -54; +constexpr float MUNCH_SPLASH_HEIGHT_RANGE = 16; +constexpr int MUNCH_BITE_FRAME = 15; +constexpr int MUNCH_REWIND_FRAME = 4; +constexpr int MUNCH_BITES = 2; +constexpr int MUNCH_SHAKE = 8; + +// The fall: once killed, it sucks in everything for 20 frames after a player falls in, pulling up to eight times as +// hard after 90 frames, and the players drop into its first dungeon. +constexpr int FALL_FRAMES = 19; +constexpr int FALL_SWIRL_EVERY = 6; +constexpr int FALL_SPARK_EVERY = 3; +constexpr int FALL_PULL_DELAY = 90; +constexpr float FALL_PULL_RAMP = 30; +constexpr float FALL_PULL_MAX = 8; +constexpr float FALL_PULL_STRENGTH = 2; +constexpr float FALL_PULL_FALLOFF = 0.0001f; +constexpr float FALL_PLAYER_PULL = 1.4f; +constexpr float FALL_PLAYER_PULL_MAX = 0.8f; +constexpr float FALL_TEAR_PULL = 0.7f; +constexpr float FALL_REACH_SQUARED = 400; +constexpr float FALL_PIT_PULL = 0.5f; +constexpr float FALL_HEALTH = 0.001f; +constexpr int FALL_DEPTH = -500; +constexpr float FALL_SPLASH_HEIGHT = -4; +constexpr int FALL_RETURN_INDEX_MIN = -20; +constexpr int FALL_RETURN_INDEX_MAX = 168; + +// The maggot: an attack one in 30 frames after 15, its head attacks more likely with the target below it, its suck, its +// spray of 15 volleys, its 20 frames of wiggling shots and its fart. +constexpr float MAGGOT_HEIGHT = 36; +constexpr int MAGGOT_REST = 15; +constexpr uint32_t MAGGOT_ATTACK_ODDS = 30; +constexpr uint32_t MAGGOT_PICK_ODDS = 3; +constexpr float MAGGOT_TARGET_HIGH = 80; +constexpr float MAGGOT_DETAIL_DEPTH = 100; +constexpr std::string_view MAGGOT_DETAIL_ANM2 = "gfx/1000.006_rotgut detail.anm2"; +constexpr float MAGGOT_SUCK_GULP = 0.5f; +constexpr float MAGGOT_SUCK_BLOW = -2; +constexpr float MAGGOT_SUCK_FALLOFF = 1e-05f; +constexpr float MAGGOT_SHOT_PULL = 0.4f; +constexpr int MAGGOT_SUCK_SHAKE = 20; +constexpr int MAGGOT_SPRAY_FRAMES = 29; +constexpr int MAGGOT_SPRAY_SHOTS = 3; +constexpr float MAGGOT_SPRAY_FALL = 0.72f; +constexpr float MAGGOT_SPRAY_SPEED = -10; +constexpr float MAGGOT_SPRAY_SPEED_RANGE = 11; +constexpr float MAGGOT_SPRAY_ANGLE = 10; +constexpr float MAGGOT_SPRAY_ANGLE_RANGE = 15; +constexpr uint32_t MAGGOT_SPAWN_ODDS = 6; +constexpr float MAGGOT_TOSS_RISE = -4; +constexpr float MAGGOT_TOSS_RANGE = 4; +constexpr float MAGGOT_TOSS_SPEED = -6; +constexpr float MAGGOT_FLY_SPEED = -10; +constexpr float MAGGOT_FLY_SPEED_RANGE = 10; +constexpr float MAGGOT_FLY_ANGLE = 30; +constexpr float MAGGOT_DRIP_ANGLE = 10; +constexpr float MAGGOT_DRIP_SPEED = -6; +constexpr float MAGGOT_DRIP_SCALE = 0.32000002f; +constexpr int MAGGOT_BLOOD_DEPTH = 2000; +constexpr float MAGGOT_BOMB_SCALE = 2; +constexpr float MAGGOT_BOMB_SPEED = -10; +constexpr float MAGGOT_BOMB_SPEED_RANGE = 6; +constexpr float MAGGOT_BOMB_ANGLE = 30; +constexpr float MAGGOT_BOMB_SPLASH = 0.2f; +constexpr ColorMod MAGGOT_BOMB_COLOR = {{1, 1, 1, 1}, {0.4f, 2, 0.5f, 1}, {0, 0, 0}}; +constexpr ColorMod MAGGOT_BOMB_SPLASH_COLOR = {{1, 1, 1, 1}, {0.2f, 1.2f, 0, 1}, {0, 0, 0}}; +constexpr int MAGGOT_WIGGLE_FRAMES = 21; +constexpr int MAGGOT_WIGGLE_EVERY = 4; +constexpr float MAGGOT_WIGGLE_DROP = 8; +constexpr float MAGGOT_WIGGLE_TARGET = -8; +constexpr float MAGGOT_WIGGLE_FALL = -0.1f; +constexpr float MAGGOT_WIGGLE_SLOWING = 16; +constexpr float MAGGOT_WIGGLE_SPEED = 1.5f; +constexpr float MAGGOT_WIGGLE_SPEED_DROP = 1.3f; +constexpr float MAGGOT_WIGGLE_PUSH = -2; +constexpr float MAGGOT_WIGGLE_RISE = 6; +constexpr float MAGGOT_WIGGLE_RISE_RANGE = 9; +constexpr int MAGGOT_FART_FRAMES = 5; +constexpr float MAGGOT_FART_REACH = 100; +constexpr float MAGGOT_FART_DAMAGE = 15; +constexpr float MAGGOT_FART_THRESHOLD = 50; +constexpr float MAGGOT_FART_RADIUS = 80; +constexpr int MAGGOT_FART_SHOTS = 4; +constexpr float MAGGOT_FART_SPEED_HIGH = -16; +constexpr float MAGGOT_FART_ANGLE = 25; +constexpr float MAGGOT_FART_ANGLE_RANGE = 15; +constexpr float MAGGOT_FART_ANGLE_HIGH = 30; +constexpr float MAGGOT_FART_ANGLE_HIGH_RANGE = 25; +constexpr int MAGGOT_CLOUDS = 2; +constexpr float MAGGOT_CLOUD_STEP = 0.25f; +constexpr float MAGGOT_CLOUD_SPAN = 6; +constexpr float MAGGOT_CLOUD_SPEED = 90; +constexpr float MAGGOT_CLOUD_WOBBLE = 6; +constexpr float MAGGOT_CLOUD_TILT = 5; +constexpr float MAGGOT_CLOUD_TILT_RANGE = 25; +constexpr float MAGGOT_CLOUD_SHRINK = 0.25f; +constexpr int MAGGOT_CLOUD_FRAMES = 150; +constexpr float MAGGOT_FART_SPLASH_SPEED = -2; +constexpr int MAGGOT_FART_SHAKE = 10; +constexpr float MAGGOT_LASER_ANGLE = 180; +constexpr int MAGGOT_LASER_FRAMES = 30; +constexpr float MAGGOT_LASER_DROP = 12; + +// The heart: an attack one in 60 frames after 30, firing a fan at each beat (or raining fire for its summon's ten +// beats), its spit, and its retreat with leeches crossing the room. +constexpr float HEART_HEIGHT = 10; +constexpr int HEART_REST = 29; +constexpr uint32_t HEART_ATTACK_ODDS = 60; +constexpr int HEART_SPIT_WEIGHT = 10; +constexpr int HEART_MOVE_WEIGHT = 5; +constexpr int HEART_BEAT_SHAKE = 6; +constexpr float HEART_HALF_HEALTH = 0.5f; +constexpr int HEART_RAIN_BEATS = 10; +constexpr int HEART_RAIN_SHOTS = 3; +constexpr float HEART_RAIN_MARGIN = 20; +constexpr float HEART_RAIN_FALL = 0.48f; +constexpr int HEART_RAIN_TIMEOUT = 30; +constexpr float HEART_RAIN_SCALE = 1.6f; +constexpr float HEART_RAIN_SPEED = 4; +constexpr int HEART_RAIN_FADE = 15; +constexpr int HEART_RAIN_DEPTH = 2000; +constexpr float HEART_SUMMON_PITCH = 0.6f; +constexpr int HEART_SUMMON_SHAKE = 4; +constexpr int HEART_FAN_SHOTS = 12; +constexpr float HEART_FAN_SPREAD = 30; +constexpr float HEART_FAN_FALL = -0.1f; +constexpr float HEART_FAN_LOW = -20; +constexpr float HEART_FAN_HIGH = 200; +constexpr float HEART_FAN_SPEED = 7; +constexpr int HEART_SPIT_SHAKE = 10; +constexpr float HEART_SPIT_FALL = 0.75f; +constexpr float HEART_SPIT_SCALE = 2.2f; +constexpr float HEART_SPIT_SPEED = 5; +constexpr float HEART_SPIT_SPLASH = 1.2f; +constexpr float HEART_SPIT_SPLASH_RANGE = 0.4f; +constexpr int HEART_LEECH_FIRST = 29; +constexpr uint32_t HEART_LEECH_WAVES = 61; +constexpr int HEART_LEECH_EVERY = 15; +constexpr int HEART_BIG_LEECH_FRAME = 120; +constexpr uint32_t HEART_BIG_LEECH_ODDS = 3; +constexpr float HEART_LEECH_OUTSIDE = 80; +constexpr float HEART_BIG_LEECH_OUTSIDE = 120; +constexpr float HEART_LEECH_MARGIN = 40; +constexpr float HEART_LEECH_SPEED = 1.55f; +constexpr float HEART_LEECH_PITCH = 0.95f; +constexpr float HEART_LEECH_PITCH_RANGE = 0.1f; +constexpr int HEART_RETRACT_FRAMES = 150; +constexpr int HEART_COMEBACK_WAIT = -90; +constexpr int HEART_DEATH_SHAKE = 50; +constexpr uint32_t HEART_DEATH_SPLAT_DELAY = 15; +constexpr uint32_t HEART_DEATH_SPLATS = 10; +constexpr int HEART_DEATH_SPLAT_DEPTH = 5000; +constexpr float HEART_DEATH_PITCH = 0.9f; +constexpr float HEART_DEATH_PITCH_RANGE = 0.2f; + +// The heart's attacks and the face's. +enum RotgutMove +{ + ROTGUT_MOVE_FIRST, + ROTGUT_MOVE_SECOND, + ROTGUT_MOVE_THIRD +}; + +// The maggot's death opens a way up through the three cells above column 14 of row 7, one after another. +constexpr int ROTGUT_WALL_COLUMN = 14; +constexpr int ROTGUT_WALL_ROW = 7; +constexpr int ROTGUT_WALL_CELLS = 3; +constexpr uint32_t ROTGUT_WALL_BREAK_DELAY = 1; +constexpr uint32_t ROTGUT_WALL_BREAK_STEP = 5; +constexpr int ROTGUT_WALL_ROCKS = 4; +constexpr int ROTGUT_WALL_ROCK_SUBTYPE = 34; +constexpr float ROTGUT_WALL_ROCK_SPEED = 10; +constexpr float ROTGUT_WALL_ROCK_REACH = 20; +constexpr float ROTGUT_WALL_SPLAT_SCALE = 1.3f; +constexpr float ROTGUT_WALL_SPLAT_SCALE_RANGE = 0.6f; +constexpr int ROTGUT_WALL_SPLAT_DEPTH = 5000; + +// The pitch Rotgut's leeches cry at: higher for a tiny champion, lower for a giant. +static float rotgut_pitch_get(Entity_NPC& npc, float pitch) +{ + if (npc.championColorIdx == CHAMPION_TINY) return pitch + HALF; + return npc.championColorIdx == CHAMPION_GIANT ? pitch * HALF : pitch; +} + +// 0057e430 One shot from a place at a velocity, falling and sized as the params say. +static Entity_Projectile* rotgut_projectile_fire(Entity_NPC& npc, Vector position, Vector velocity, + const ProjectileParams& params) +{ + Entity_Projectile* shot = npc.FireBossProjectiles(1, {}, 0, params); + shot->fallingSpeed = params.fallingSpeedModifier; + shot->fallingAccel = params.fallingAccelModifier; + shot->scale = params.scale; + shot->pos = position; + shot->velocity = velocity; + return shot; +} + +// 0057e3b0 Where its mouth shoots from: its ShootPos null. +static Vector rotgut_shoot_position(Entity_NPC& npc) +{ + return vector_add(vector_add(npc.pos, npc.posOffset), npc.GetNullOffset("ShootPos")); +} + +// A shot size of five to seven thirds less one, as the maggot draws them. +static float rotgut_shot_scale() +{ + uint32_t size = std::min(Random() % 3 + 5, 13u); + return ((float)size - 3) / 3; +} + +// A splash of blood scaled at random, drawn in front. +static void rotgut_splash(Entity* splash, float least, float range, int depth) +{ + float size = random_between(least, range); + splash->renderZOffset = depth; + splash->sprite.scale = vector_make(size, size); +} + +// 00581430 A fan of twelve shots from the heart's mouth, aimed about the target, keeping those that point down. +static void rotgut_fire_projectiles(Entity_NPC& npc) +{ + Vector mouth = + vector_make(npc.pos.x, npc.pos.y + (npc.state != ROTGUT_RETRACTED ? ROTGUT_HEART_MOUTH : -ROTGUT_HEART_MOUTH)); + float aim = vector_angle(vector_sub(npc.GetPlayerTarget()->pos, mouth)); + aim += random_unit() * HEART_FAN_SPREAD - HEART_FAN_SPREAD * HALF; + ProjectileParams params; + params.color = SHOT_COLOR_SICK; + params.fallingAccelModifier = HEART_FAN_FALL; + + for (int i = 0; i < HEART_FAN_SHOTS; i++) + { + float angle = normalize_angle_degrees((float)i / HEART_FAN_SHOTS * FULL_TURN_DEGREES + aim); + if (angle >= HEART_FAN_LOW && angle <= HEART_FAN_HIGH) + rotgut_projectile_fire(npc, mouth, vector_scale(vector_from_angle(angle), HEART_FAN_SPEED), params); + } +} + +// A pick among Rotgut's moves, the first always there. +static int rotgut_move_pick(WeightedOutcomePicker& picker) +{ + RNG rng = ROTGUT_PICK_RNG; + rng._seed = Random() | 1; + return picker.PickOutcome(rng); +} + +// One of the face's volleys at a delay: eight curving spiral shots, four swaying crosses, or two waves of a small and +// a big shot. +static void face_volley(Entity_NPC& npc, Vector mouth, int delay) +{ + if (npc.i1 == 0 && delay % FACE_SPIRAL_EVERY == 0) + { + bool isLeft = delay % FACE_SPIRAL_SWAP == 0; + float angle = isLeft ? (float)delay : (float)-delay; + for (int i = 0; i < FACE_SPIRAL_SHOTS; i++) + { + angle += isLeft ? FACE_SPIRAL_STEP : -FACE_SPIRAL_STEP; + ProjectileParams params; + params.fallingAccelModifier += ROTGUT_SHOT_FALL; + params.color = isLeft ? SHOT_COLOR_SICK : SHOT_COLOR_SICK_PALE; + params.bulletFlags = (isLeft ? PROJECTILE_CURVE_LEFT : PROJECTILE_CURVE_RIGHT) | PROJECTILE_HIT_ENEMIES; + params.curvingStrength = FACE_SPIRAL_CURVE; + npc.FireProjectiles(mouth, vector_scale(vector_from_angle(angle), ROTGUT_SHOT_SPEED), PROJECTILES_SINGLE, + params); + } + } + else if (npc.i1 == 1 && delay % FACE_WAVE_EVERY == 0) + { + float angle = std::sin((float)delay * FACE_CROSS_SPIN) * FACE_CROSS_SWAY; + for (int i = 0; i < FACE_CROSS_SHOTS; i++) + { + angle += RIGHT_ANGLE_DEGREES; + ProjectileParams params; + params.fallingAccelModifier += ROTGUT_SHOT_FALL; + params.bulletFlags = PROJECTILE_SINE_VELOCITY | PROJECTILE_HIT_ENEMIES; + params.color = SHOT_COLOR_SICK; + npc.FireProjectiles(mouth, vector_scale(vector_from_angle(angle), ROTGUT_SHOT_SPEED), PROJECTILES_SINGLE, + params); + } + } + else if (npc.i1 == 2 && delay % FACE_WAVE_EVERY == 0) + { + float angle = (float)delay * FACE_WAVE_TURN; + float mirrored = HALF_TURN_DEGREES - angle; + ProjectileParams params; + params.fallingAccelModifier += ROTGUT_SHOT_FALL; + params.bulletFlags = PROJECTILE_HIT_ENEMIES; + params.color = SHOT_COLOR_SICK; + params.targetPosition = mouth; + npc.FireProjectiles(mouth, vector_scale(vector_from_angle(angle), ROTGUT_SHOT_SPEED), PROJECTILES_SINGLE, + params); + npc.FireProjectiles(mouth, vector_scale(vector_from_angle(mirrored), ROTGUT_SHOT_SPEED), PROJECTILES_SINGLE, + params); + params.scale = FACE_WAVE_BIG_SCALE; + params.color = SHOT_COLOR_SICK_PALE; + npc.FireProjectiles(mouth, vector_scale(vector_from_angle(angle), FACE_WAVE_BIG_SPEED), PROJECTILES_SINGLE, + params); + npc.FireProjectiles(mouth, vector_scale(vector_from_angle(mirrored), FACE_WAVE_BIG_SPEED), PROJECTILES_SINGLE, + params); + } +} + +// The face's first attack: its shots begin on the Shoot event and run 180 frames. +static void face_shots_update(Entity_NPC& npc, int ticks) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Attack1Loop"); + if (npc.sprite.IsEventTriggered("Sound1")) npc.PlaySound(SOUND_MONSTER_GRUNT_4, 1, 2, false, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.projectileDelay = 0; + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, 2, false, 1); + } + if (npc.projectileDelay < 0) return; + + Vector mouth = vector_make(npc.pos.x, npc.pos.y + ROTGUT_MOUTH_DROP); + for (int tick = 0; tick < ticks && npc.state == ROTGUT_ATTACK; tick++) + { + face_volley(npc, mouth, npc.projectileDelay); + if (npc.projectileDelay >= FACE_SHOTS_FRAMES) + { + npc.sprite.Play("Attack1End"); + npc.state = ROTGUT_IDLE; + } + npc.projectileDelay++; + } +} + +// A blood gib thrown from about the face, plain one in five, else rotten. +static void face_gib_throw(Entity_NPC& npc) +{ + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector direction = vector_make(std::cos(angle), std::sin(angle)); + float reach = random_unit(); + Vector position = vector_add(npc.pos, vector_scale(direction, reach * RUBBLE_GIB_REACH)); + Vector velocity = vector_scale(direction, RUBBLE_GIB_SPEED); + + Entity* gib = nullptr; + if (Random() % RUBBLE_GIB_PLAIN_ODDS == 0) + { + uint32_t seed = Random(); + int subType = (int)(Random() & 1) + 1; + gib = g_game->Spawn({.position = position, + .velocity = velocity, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, + .seed = seed}); + } + else + { + gib = g_game->Spawn({.position = position, + .velocity = velocity, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, + .seed = Random()}); + gib->sprite.color = SHOT_COLOR_ROTTEN; + } + gib->posOffset = vector_make(0, RUBBLE_GIB_HEIGHT); + gib->Update(); +} + +// One piece of the face's rubble: thrown at a random spot as puke, a bone, a small maggot or meat, with a rotten +// splash and now and then a gib. +static void face_rubble_throw(Entity_NPC& npc) +{ + Vector mouth = vector_make(npc.pos.x, npc.pos.y - RUBBLE_MOUTH_RISE); + Vector aim = vector_scale(vector_sub(g_game->room->GetRandomPosition(RUBBLE_MARGIN), mouth), RUBBLE_AIM); + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(RUBBLE_PUKE, RUBBLE_PUKE_WEIGHT); + picker.AddOutcomeWeight(RUBBLE_BONE, RUBBLE_BONE_WEIGHT); + picker.AddOutcomeWeight(RUBBLE_MAGGOT, RUBBLE_MAGGOT_WEIGHT); + picker.AddOutcomeWeight(RUBBLE_MEAT, RUBBLE_MEAT_WEIGHT); + ProjectileParams params; + params.heightModifier = random_unit() * RUBBLE_HEIGHT_RANGE; + params.fallingSpeedModifier = RUBBLE_FALL_SPEED; + params.fallingAccelModifier = RUBBLE_FALL_ACCEL; + + switch (rotgut_move_pick(picker)) + { + case RUBBLE_PUKE: + params.scale = RUBBLE_PUKE_SCALE; + params.variant = PROJECTILE_PUKE; + npc.FireProjectiles(npc.pos, aim, PROJECTILES_SINGLE, params); + break; + case RUBBLE_BONE: + params.variant = PROJECTILE_BONE; + npc.FireProjectiles(npc.pos, aim, PROJECTILES_SINGLE, params); + break; + case RUBBLE_MAGGOT: + small_maggot_spawn(npc.pos, RUBBLE_MAGGOT_HEIGHT, aim, RUBBLE_MAGGOT_RISE); + break; + case RUBBLE_MEAT: + params.variant = PROJECTILE_MEAT; + npc.FireProjectiles(npc.pos, aim, PROJECTILES_SINGLE, params); + break; + } + + Vector spray = vector_rotated(vector_make(0, -1), (random_unit() - HALF) * RUBBLE_SPLASH_SPREAD); + Vector velocity = vector_scale(spray, random_between(RUBBLE_SPLASH_SPEED, RUBBLE_SPLASH_SPEED_RANGE)); + float rise = std::clamp((float)npc.projectileDelay / FACE_RUBBLE_FRAMES, 0.0f, 1.0f); + float lift = random_unit(); + float wobble = random_unit() * RANDOM_HALF_TURN; + wobble += wobble; + Vector offset = vector_make(std::cos(wobble) * RUBBLE_SPLASH_WOBBLE, + RUBBLE_SPLASH_HEIGHT - rise * RUBBLE_SPLASH_RISE - lift * RUBBLE_SPLASH_RISE_RANGE + + std::sin(wobble) * RUBBLE_SPLASH_WOBBLE); + Entity* splash = blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH_BIG, npc.pos, offset, SHOT_COLOR_ROTTEN, velocity); + rotgut_splash(splash, RUBBLE_SPLASH_SCALE, RUBBLE_SPLASH_SCALE_RANGE, RUBBLE_SPLASH_DEPTH); + + if ((Random() & RUBBLE_GIB_MASK) == 0) face_gib_throw(npc); + game_shake_screen(RUBBLE_SHAKE); +} + +// The face's second attack: rubble thrown every other frame for 90 frames from the Shoot event. +static void face_rubble_update(Entity_NPC& npc, int ticks) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Attack2Loop"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_HEARTOUT, 1, 2, false, 1); + npc.PlaySound(SOUND_MEGA_PUKE, 1, 10, false, 0.9f); + npc.projectileDelay = 0; + } + if (npc.sprite.IsEventTriggered("Sound1")) npc.PlaySound(SOUND_ANGRY_GURGLE, 1, 10, false, HEART_SUMMON_PITCH); + if (npc.sprite.IsEventTriggered("Sound2")) npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + if (npc.projectileDelay < 0) return; + + for (int tick = 0; tick < ticks; tick++) + { + if ((npc.projectileDelay & 1) == 0) face_rubble_throw(npc); + if (npc.projectileDelay >= FACE_RUBBLE_FRAMES) + { + npc.projectileCooldown = FACE_RUBBLE_COOLDOWN; + npc.sprite.Play("Attack2End"); + npc.state = ROTGUT_IDLE; + return; + } + npc.projectileDelay++; + } +} + +// The munch's last bite: 22 shots spat about that slow down as they go. +static void face_munch_spray(Entity_NPC& npc) +{ + for (int i = 0; i < MUNCH_SPRAY_SHOTS; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + Vector direction = vector_make(std::cos(angle), std::sin(angle)); + float speed = random_unit() * MUNCH_SPRAY_SPEED; + Vector position = vector_add(npc.pos, vector_scale(direction, MUNCH_SPRAY_REACH)); + auto* shot = static_cast(g_game->Spawn({.position = position, + .velocity = vector_scale(direction, speed), + .spawner = &npc, + .type = ENTITY_PROJECTILE, + .seed = Random()})); + shot->height = MUNCH_SPRAY_HEIGHT - random_unit() * MUNCH_SPRAY_HEIGHT_RANGE; + shot->fallingSpeed = 0; + shot->fallingAccel = MUNCH_SPRAY_FALL - random_unit() * MUNCH_SPRAY_FALL_RANGE; + shot->scale = random_between(MUNCH_SPRAY_SCALE, MUNCH_SPRAY_SCALE_RANGE); + shot->projectileFlags = PROJECTILE_ACCELERATE_EX; + shot->acceleration = MUNCH_SPRAY_SLOWDOWN; + shot->SetColor(shot->scale <= MUNCH_SPRAY_BIG ? SHOT_COLOR_SICK : SHOT_COLOR_SICK_PALE, -1, + COLOR_PRIORITY_DEFAULT, false, true); + if (npc.HasEntityFlags(FLAG_SLOW)) shot->projectileFlags |= PROJECTILE_SLOWED; + } +} + +// The munch's fans: 20 pairs of shots thrown out to both sides. +static void face_munch_fans(Entity_NPC& npc, Vector mouth) +{ + ProjectileParams params; + params.fallingAccelModifier = MUNCH_FAN_FALL; + for (int i = 0; i < MUNCH_FAN_PAIRS; i++) + for (float side : {0.0f, HALF_TURN_DEGREES}) + { + float angle = random_unit() * MUNCH_FAN_SPREAD + side - MUNCH_FAN_SPREAD * HALF; + float speed = random_unit() * MUNCH_FAN_SPEED; + Vector velocity = vector_scale(vector_from_angle(angle), speed); + params.fallingSpeedModifier = random_unit() * MUNCH_FAN_RISE; + params.scale = random_between(MUNCH_FAN_SCALE, MUNCH_FAN_SCALE_RANGE); + npc.FireProjectiles(mouth, velocity, PROJECTILES_SINGLE, params); + } +} + +// The face's munch: on each bite a ring, a smaller ring and a spray, or the fans, with a green splash. It bites again +// twice by rewinding. +static void face_munch_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + game_shake_screen(MUNCH_SHAKE); + Vector mouth = vector_make(npc.pos.x, npc.pos.y + ROTGUT_MOUTH_DROP); + npc.PlaySound(SOUND_SMB_LARGE_CHEWS_4, 1, 2, false, 1); + npc.PlaySound(SOUND_HEARTOUT, 1, 2, false, 1); + npc.projectileDelay = 0; + ProjectileParams params; + params.fallingAccelModifier = ROTGUT_SHOT_FALL; + if (npc.i1 != 0) face_munch_fans(npc, mouth); + else if (npc.stateFrame == 0) + { + params.color = SHOT_COLOR_SICK; + params.scale = FACE_WAVE_BIG_SCALE; + npc.FireProjectiles(mouth, vector_make(MUNCH_RING_SPEED, MUNCH_RING_SHOTS), PROJECTILES_RING, params); + } + else if (npc.stateFrame == 1) + npc.FireProjectiles(mouth, vector_make(MUNCH_SMALL_RING_SPEED, MUNCH_SMALL_RING_SHOTS), PROJECTILES_RING, + params); + else if (npc.stateFrame == 2) face_munch_spray(npc); + + Vector offset = vector_make(0, MUNCH_SPLASH_HEIGHT - random_unit() * MUNCH_SPLASH_HEIGHT_RANGE); + blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH_BIG, npc.pos, offset, COLOR_GREEN_SPLAT, {})->renderZOffset = + RUBBLE_SPLASH_DEPTH; + } + + if (npc.sprite.GetFrame() == MUNCH_BITE_FRAME && npc.i1 == 0 && npc.stateFrame < MUNCH_BITES) + { + npc.stateFrame++; + npc.sprite.SetFrame((float)MUNCH_REWIND_FRAME); + } + if (npc.sprite.IsPlaying()) return; + npc.state = ROTGUT_IDLE; + npc.stateFrame = MUNCH_BITE_FRAME; +} + +// The fall's pull on one entity: drawn toward the mouth, players harder up to a limit and tears less, and swallowed +// within 20: a shot or tear removed, a player dropping in, any other enemy (not a boss) killed. +static void face_fall_pull(Entity_NPC& npc, Entity& entity, float pull) +{ + if (entity.type == ENTITY_PLAYER && entity.pitfallState != 0) + { + entity.velocity = vector_scale(vector_sub(npc.pos, entity.pos), FALL_PIT_PULL); + return; + } + + Vector toward = vector_sub(npc.pos, entity.pos); + float strength = FALL_PULL_STRENGTH / (vector_length_squared(toward) * FALL_PULL_FALLOFF + 1); + Vector direction = vector_normalized(toward); + if (entity.type == ENTITY_PLAYER) + strength = std::min(strength * FALL_PLAYER_PULL, FALL_PLAYER_PULL_MAX) / std::min(entity.mass, 1.0f); + else if (entity.type == ENTITY_TEAR) strength *= FALL_TEAR_PULL; + npc_push(entity, vector_scale(direction, strength * pull)); + if (vector_length_squared(vector_sub(npc.pos, entity.pos)) >= FALL_REACH_SQUARED) return; + + bool isVersusPlayer = g_game->deathmatchManager.is_active() && entity.type == ENTITY_PLAYER; + bool isNpc = entity.type >= 10 && entity.type <= 999; + if (isVersusPlayer || (isNpc && !entity.IsBoss())) + { + entity.Kill(EntityRef(&npc)); + return; + } + if (entity.type == ENTITY_TEAR || entity.type == ENTITY_PROJECTILE) + { + entity.Remove(); + return; + } + auto& player = static_cast(entity); + if (entity.type != ENTITY_PLAYER || player.variant != 0 || player.isDead || player.pitfallState != 0) return; + player.PlayExtraAnimation("FallIn"); + player.isControlsEnabled = false; + player.entityCollisionClass = ENTCOLL_NONE; + player.pitfallState = PITFALL_GONE; + player.pitfallTimer = 0; + npc.stateFrame = std::max(npc.stateFrame, 0); +} + +// The face's fall: swirls rising out of the hole and everything pulled in, then the players dropped into the first +// dungeon 20 frames after one fell. +static void face_fall_update(Entity_NPC& npc, int ticks) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play("TransitionLoop"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_GRROOWL, 1, 2, false, 1); + npc.projectileDelay = 0; + } + if (npc.stateFrame >= 0) + { + npc.stateFrame += ticks; + if (npc.stateFrame > FALL_FRAMES) + { + Game& game = *g_game; + game.enterDoor = -1; + game.dungeonReturnPosition = npc.pos; + // 0057be90 The dungeon's return room, held between -20 and 168. + game.dungeonReturnRoomIndex = std::clamp(game.currentRoomIdx, FALL_RETURN_INDEX_MIN, FALL_RETURN_INDEX_MAX); + game.StartRoomTransition({.animation = TRANSITION_PIXELATION, .roomIndex = ROOM_ROTGUT_DUNGEON1_IDX}); + } + } + if (npc.projectileDelay < 0) return; + + for (int tick = 0; tick < ticks; tick++) + { + for (int subType : {0, 1}) + { + int every = subType == 0 ? FALL_SWIRL_EVERY : FALL_SPARK_EVERY; + if (npc.projectileDelay % every != 0) continue; + g_game + ->Spawn({.position = npc.pos, + .subType = subType, + .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_ATTRACT, + .seed = Random()}) + ->Update(); + } + npc.projectileDelay++; + } + float pull = 1; + if (npc.projectileDelay > FALL_PULL_DELAY) + pull = std::min((float)(npc.projectileDelay - FALL_PULL_DELAY) / FALL_PULL_RAMP + 1, FALL_PULL_MAX); + + EntityList& list = g_game->room->entityList; + for (size_t i = 0; i < list.updateEL.size(); i++) + { + Entity* entity = list.updateEL[i]; + bool isPulled = entity->IsActiveEnemy(DEAD_EXCLUDED) || entity->type == ENTITY_PLAYER || + entity->type == ENTITY_TEAR || entity->type == ENTITY_PROJECTILE; + if (entity != &npc && isPulled) face_fall_pull(npc, *entity, pull); + } +} + +// The face's idle: an attack one in 20 frames after 45, its rubble only once cooled down. +static void face_idle_update(Entity_NPC& npc) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Idle"); + if (++npc.stateFrame <= FACE_REST || Random() % FACE_ATTACK_ODDS != 0) return; + + npc.stateFrame = 0; + npc.projectileDelay = -1; + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(ROTGUT_MOVE_FIRST, 1); + if (npc.projectileCooldown < 1) picker.AddOutcomeWeight(ROTGUT_MOVE_SECOND, 1); + picker.AddOutcomeWeight(ROTGUT_MOVE_THIRD, 1); + switch (rotgut_move_pick(picker)) + { + case ROTGUT_MOVE_FIRST: + npc.sprite.Play("Attack1Begin"); + npc.state = ROTGUT_ATTACK; + npc.i1 = (int)(Random() % 3); + break; + case ROTGUT_MOVE_SECOND: + npc.sprite.Play("Attack2Begin"); + npc.state = ROTGUT_ATTACK2; + npc.i1 = 0; + break; + case ROTGUT_MOVE_THIRD: + npc.sprite.Play("Munch"); + npc.state = ROTGUT_ATTACK3; + npc.i1 = (int)(Random() & 1); + break; + } +} + +// Killed, the face falls back into the wall instead of dying and starts sucking. +static void face_fall_start(Entity_NPC& npc) +{ + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.state = ROTGUT_TRANSITION; + npc.isDead = false; + npc.health = FALL_HEALTH; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.isInvincible = true; + npc.projectileDelay = -1; + npc.stateFrame = -1; + npc.renderZOffset = FALL_DEPTH; + npc.PlaySound(SOUND_MONSTER_GRUNT_4, 1, 2, false, 1); + npc.sprite.Play("Transition"); + npc.PlaySound(SOUND_DEATH_BURST_LARGE, 1, 2, false, 1); + blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH_BIG, npc.pos, vector_make(0, FALL_SPLASH_HEIGHT), COLOR_GREEN_SPLAT, + {}) + ->renderZOffset = RUBBLE_SPLASH_DEPTH; + npc.BloodExplode(); +} + +// 0057bec0 Rotgut's face in the wall: spirals, rubble and munching, and once killed the suck that drops the players +// into its dungeon. Gone at once when its dungeon is already cleared. +static void rotgut_face_update(Entity_NPC& npc) +{ + bool isCleared = g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_ROTGUT_CLEARED; + npc.friction = ROTGUT_FRICTION; + int ticks = npc_ticks_get(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + g_game->init_rotgut_dungeon_room(); + npc.state = ROTGUT_IDLE; + npc.sprite.Play("Idle"); + npc.targetPosition = npc.pos; + npc.splatColor = COLOR_GREEN_SPLAT; + if (!isCleared) break; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.Kill(EntityRef()); + return; + case ROTGUT_IDLE: + face_idle_update(npc); + break; + case ROTGUT_ATTACK: + face_shots_update(npc, ticks); + break; + case ROTGUT_ATTACK2: + face_rubble_update(npc, ticks); + break; + case ROTGUT_ATTACK3: + face_munch_update(npc); + break; + case ROTGUT_TRANSITION: + face_fall_update(npc, ticks); + break; + } + + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.projectileCooldown > 0) npc.projectileCooldown = std::max(npc.projectileCooldown - ticks, 0); + if (!isCleared && (npc.isDead || npc.health <= 0)) face_fall_start(npc); +} + +// The maggot's suck or blow on everything about it but fireplaces: players harder up to a limit, tears and shots less. +static void maggot_suck(Entity_NPC& npc, float push) +{ + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity == &npc) continue; + bool isVersusPlayer = g_game->deathmatchManager.is_active() && entity->type == ENTITY_PLAYER; + bool isNpc = entity->type >= 10 && entity->type <= 999 && entity->type != ENTITY_FIREPLACE; + bool isPlayer = isVersusPlayer || entity->type == ENTITY_PLAYER; + if (!isNpc && !isPlayer && entity->type != ENTITY_TEAR && entity->type != ENTITY_PROJECTILE) continue; + + Vector toward = vector_sub(npc.pos, entity->pos); + float strength = FALL_PULL_STRENGTH / (vector_length_squared(toward) * MAGGOT_SUCK_FALLOFF + 1); + Vector direction = vector_normalized(toward); + if (isPlayer) + strength = std::min(strength * FALL_PLAYER_PULL, FALL_PLAYER_PULL_MAX) / std::min(entity->mass, 1.0f); + else if (entity->type == ENTITY_TEAR) strength *= FALL_TEAR_PULL; + else if (entity->type == ENTITY_PROJECTILE) strength *= MAGGOT_SHOT_PULL; + npc_push(*entity, vector_scale(direction, strength * push)); + } +} + +// One volley of the maggot's head spray: three shots up and back, a small maggot or a fly now and then, and a drip. +static void maggot_spray_volley(Entity_NPC& npc) +{ + Vector mouth = rotgut_shoot_position(npc); + for (int i = 0; i < MAGGOT_SPRAY_SHOTS; i++) + { + ProjectileParams params; + params.fallingAccelModifier = MAGGOT_SPRAY_FALL; + params.scale = rotgut_shot_scale(); + float speed = MAGGOT_SPRAY_SPEED - random_unit() * MAGGOT_SPRAY_SPEED_RANGE; + float angle = random_between(MAGGOT_SPRAY_ANGLE, MAGGOT_SPRAY_ANGLE_RANGE); + rotgut_projectile_fire(npc, mouth, vector_rotated(vector_make(speed, 0), angle), params); + } + + if (Random() % MAGGOT_SPAWN_ODDS == 0) + { + float rise = MAGGOT_TOSS_RISE - random_unit() * MAGGOT_TOSS_RANGE; + float speed = MAGGOT_TOSS_SPEED - random_unit() * MAGGOT_TOSS_RANGE; + small_maggot_spawn(mouth, 0, vector_make(speed, 0), rise); + } + else if (Random() % MAGGOT_SPAWN_ODDS == 0) + { + uint32_t seed = Random(); + float speed = MAGGOT_FLY_SPEED - random_unit() * MAGGOT_FLY_SPEED_RANGE; + Vector velocity = vector_rotated(vector_make(speed, 0), random_unit() * MAGGOT_FLY_ANGLE); + g_game->Spawn({.position = mouth, .velocity = velocity, .type = ENTITY_ATTACKFLY, .seed = seed}) + ->ClearEntityFlags(FLAG_APPEAR); + } + + Vector drip = + vector_rotated(vector_make(MAGGOT_DRIP_SPEED, 0), random_unit() * MAGGOT_DRIP_ANGLE - MAGGOT_DRIP_ANGLE * HALF); + drip = vector_scale(drip, random_unit()); + rotgut_splash(blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH, mouth, {}, COLOR_DEFAULT, drip), 0, MAGGOT_DRIP_SCALE, + MAGGOT_BLOOD_DEPTH); +} + +// The maggot's head attack 3: a gulp that pulls everything in, then a roar blowing it away and 15 volleys of spray. +static void maggot_suck_update(Entity_NPC& npc, int ticks) +{ + float push = 0; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.projectileCooldown = 0; + npc.PlaySound(SOUND_BOSS_GURGLE_ROAR, 1, 2, false, 1); + game_shake_screen(MAGGOT_SUCK_SHAKE); + push = MAGGOT_SUCK_BLOW; + } + if (npc.sprite.IsEventTriggered("Sound")) npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + if (npc.projectileCooldown < 0) + { + game_shake_screen(RUBBLE_SHAKE); + push = MAGGOT_SUCK_GULP; + } + if (push != 0) maggot_suck(npc, push); + + for (int tick = 0; tick < ticks && (uint32_t)npc.projectileCooldown <= MAGGOT_SPRAY_FRAMES; tick++) + { + if ((npc.projectileCooldown & 1) == 0) maggot_spray_volley(npc); + npc.projectileCooldown++; + } +} + +// The maggot's butt attack 1: one big exploding shot that splits, lobbed back over it. +static void maggot_bomb_update(Entity_NPC& npc) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) return; + npc.PlaySound(SOUND_FART, 1, 2, false, 1); + npc.PlaySound(SOUND_HEARTOUT, 0.8f, 2, false, 1); + ProjectileParams params; + params.color = MAGGOT_BOMB_COLOR; + params.bulletFlags = PROJECTILE_EXPLODE | PROJECTILE_BURSTSPLIT; + params.scale = MAGGOT_BOMB_SCALE; + params.fallingSpeedModifier = 0; + params.fallingAccelModifier = MAGGOT_SPRAY_FALL; + float speed = MAGGOT_BOMB_SPEED - random_unit() * MAGGOT_BOMB_SPEED_RANGE; + Vector mouth = rotgut_shoot_position(npc); + Vector velocity = vector_rotated(vector_make(speed, 0), MAGGOT_BOMB_ANGLE); + rotgut_projectile_fire(npc, mouth, velocity, params); + Entity* splash = blood_explosion_spawn(BLOOD_EXPLOSION_BURST, mouth, {}, MAGGOT_BOMB_SPLASH_COLOR, + vector_scale(velocity, MAGGOT_BOMB_SPLASH)); + rotgut_splash(splash, RUBBLE_SPLASH_SCALE, RUBBLE_SPLASH_SCALE_RANGE, MAGGOT_BLOOD_DEPTH); +} + +// The maggot's butt attack 2 and head attack 2: wiggling shots every four frames for 20 frames, slowing as they go, +// the butt's paler and lifted toward a target high above it. +static void maggot_wiggle_update(Entity_NPC& npc, bool isTargetHigh, int ticks) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_SPIDER_SPIT_ROAR, 1, 2, false, 1); + npc.projectileCooldown = 0; + } + bool isButt = npc.state == ROTGUT_ATTACK2; + for (int tick = 0; tick < ticks && npc.projectileCooldown >= 0; tick++, npc.projectileCooldown++) + { + if (npc.projectileCooldown >= MAGGOT_WIGGLE_FRAMES || npc.projectileCooldown % MAGGOT_WIGGLE_EVERY != 0) + continue; + + ProjectileParams params; + params.bulletFlags = PROJECTILE_NO_WALL_COLLIDE | PROJECTILE_WIGGLE_ROTGUT; + params.targetPosition = vector_make(MAGGOT_WIGGLE_TARGET, 0); + if (isButt) params.color = SHOT_COLOR_SICK_PALE; + params.fallingAccelModifier = MAGGOT_WIGGLE_FALL; + params.scale = rotgut_shot_scale(); + Vector mouth = vector_add(rotgut_shoot_position(npc), vector_make(0, MAGGOT_WIGGLE_DROP)); + float slowing = std::clamp((float)npc.projectileCooldown / MAGGOT_WIGGLE_SLOWING, 0.0f, 1.0f); + float speed = MAGGOT_WIGGLE_SPEED - slowing * MAGGOT_WIGGLE_SPEED_DROP; + Vector velocity = vector_make(speed * MAGGOT_WIGGLE_PUSH, speed * 0); + if (isButt && isTargetHigh) velocity.y += MAGGOT_WIGGLE_RISE + random_unit() * MAGGOT_WIGGLE_RISE_RANGE; + rotgut_projectile_fire(npc, mouth, velocity, params); + Entity* splash = + blood_explosion_spawn(BLOOD_EXPLOSION_BURST, mouth, {}, isButt ? COLOR_GREEN_SPLAT : COLOR_DEFAULT, + vector_scale(velocity, MAGGOT_BOMB_SPLASH)); + rotgut_splash(splash, RUBBLE_SPLASH_SCALE, RUBBLE_SPLASH_SCALE_RANGE, MAGGOT_BLOOD_DEPTH); + } +} + +// One frame of the maggot's fart: on its first a poison cloud that knocks everything back, then four shots and two +// smoke clouds thrown up and back, and a splash. +static void maggot_fart_volley(Entity_NPC& npc, bool isTargetHigh) +{ + Vector mouth = rotgut_shoot_position(npc); + if (npc.projectileCooldown == 0) + { + game_fart({.position = npc.pos, .source = &npc}); + game_butter_bean_fart( + {.position = npc.pos, .source = &npc, .radius = MAGGOT_FART_REACH, .isShowEffect = false}); + TearFlags poison; + poison.set(TEAR_POISON); + damage_radius({.tearFlags = poison, + .position = npc.pos, + .source = &npc, + .damage = MAGGOT_FART_DAMAGE, + .playerDamageThreshold = MAGGOT_FART_THRESHOLD, + .radius = MAGGOT_FART_RADIUS}); + } + + for (int i = 0; i < MAGGOT_FART_SHOTS; i++) + { + ProjectileParams params; + params.color = SHOT_COLOR_SICK; + params.fallingAccelModifier = MAGGOT_SPRAY_FALL; + params.scale = rotgut_shot_scale(); + float range = random_unit(); + Vector from = rotgut_shoot_position(npc); + float speed = (isTargetHigh ? MAGGOT_FART_SPEED_HIGH : MAGGOT_BOMB_SPEED) - range * MAGGOT_BOMB_SPEED_RANGE; + float angle = isTargetHigh ? random_between(MAGGOT_FART_ANGLE_HIGH, MAGGOT_FART_ANGLE_HIGH_RANGE) + : random_between(MAGGOT_FART_ANGLE, MAGGOT_FART_ANGLE_RANGE); + rotgut_projectile_fire(npc, from, vector_rotated(vector_make(speed, 0), angle), params); + } + + for (int i = 0; i < MAGGOT_CLOUDS; i++) + { + float speed = + MAGGOT_BOMB_SPEED - + (((float)i * MAGGOT_CLOUD_STEP + (float)npc.projectileCooldown) / MAGGOT_CLOUD_SPAN) * MAGGOT_CLOUD_SPEED; + Vector velocity = + vector_rotated(vector_make(speed, 0), random_unit() * MAGGOT_CLOUD_WOBBLE - MAGGOT_CLOUD_WOBBLE * HALF); + if (isTargetHigh) + velocity = vector_rotated(velocity, random_between(MAGGOT_CLOUD_TILT, MAGGOT_CLOUD_TILT_RANGE)); + auto* cloud = static_cast(g_game->Spawn({.position = mouth, + .velocity = velocity, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = Random()})); + float size = 1 - random_unit() * MAGGOT_CLOUD_SHRINK; + cloud->timeout = MAGGOT_CLOUD_FRAMES; + cloud->sprite.scale = vector_make(size, size); + cloud->lifespan = MAGGOT_CLOUD_FRAMES; + cloud->Update(); + } + + Entity* splash = blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH, mouth, {}, COLOR_GREEN_SPLAT, + vector_make(MAGGOT_FART_SPLASH_SPEED, 0)); + rotgut_splash(splash, 0, MAGGOT_DRIP_SCALE, MAGGOT_BLOOD_DEPTH); +} + +// The maggot's butt attack 3: a fart of six frames. +static void maggot_fart_update(Entity_NPC& npc, bool isTargetHigh, int ticks) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_FART, 1, 2, false, 1); + game_shake_screen(MAGGOT_FART_SHAKE); + npc.projectileCooldown = 0; + } + for (int tick = 0; tick < ticks && (uint32_t)npc.projectileCooldown <= MAGGOT_FART_FRAMES; tick++) + { + maggot_fart_volley(npc, isTargetHigh); + npc.projectileCooldown++; + } +} + +// The maggot's idle: an attack one in 30 frames after 15, a head attack more often with its target below it. +static void maggot_idle_update(Entity_NPC& npc) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Idle"); + if (++npc.stateFrame <= MAGGOT_REST || Random() % MAGGOT_ATTACK_ODDS != 0) return; + + float targetY = npc.GetPlayerTarget()->pos.y; + bool isHead = npc.pos.y < targetY && Random() % MAGGOT_PICK_ODDS != 0; + if (!isHead) isHead = (npc.pos.y <= targetY || Random() % MAGGOT_PICK_ODDS == 0) && (Random() & 1) == 0; + int attack = (int)(Random() % MAGGOT_PICK_ODDS) + (isHead ? 3 : 0); + npc.projectileCooldown = -1; + npc.stateFrame = 0; + + static constexpr std::array ANIMS = {"ButtAttack1", "ButtAttack2", "ButtAttack3", + "HeadAttack1", "HeadAttack2", "HeadAttack3"}; + static constexpr std::array STATES = {ROTGUT_ATTACK, ROTGUT_ATTACK2, ROTGUT_ATTACK3, + ROTGUT_HEAD_LASER, ROTGUT_HEAD_SPRAY, ROTGUT_SUCK}; + npc.state = STATES[attack]; + npc.sprite.Play(ANIMS[attack]); + if (npc.state == ROTGUT_SUCK) npc.PlaySound(SOUND_MOUTH_FULL, 1, 20, false, 0.75f); +} + +// The maggot's start: its detail drawn over the dungeon's wall as its child. +static void maggot_init(Entity_NPC& npc) +{ + npc.splatColor = COLOR_GREEN_SPLAT; + npc.state = ROTGUT_IDLE; + npc.sprite.Play("Idle"); + npc.posOffset.y = MAGGOT_HEIGHT; + npc.targetPosition = npc.pos; + npc.stateFrame = 0; + uint32_t seed = Random(); + Entity* detail = g_game->Spawn({.position = vector_make(npc.pos.x, npc.pos.y + MAGGOT_HEIGHT), + .type = ENTITY_EFFECT, + .variant = EFFECT_DEVIL, + .seed = seed}); + detail->sprite.Load(MAGGOT_DETAIL_ANM2, GRAPHICS_LOAD); + detail->sprite.Play("Detail"); + detail->AddEntityFlags(FLAG_DONT_OVERWRITE); + detail->renderDepthOffset = MAGGOT_DETAIL_DEPTH; + npc.child = detail; + detail->Update(); +} + +// Whether the shot is the boss's own, which its death takes with it. +static bool rotgut_shot_is_own(Entity_NPC& npc, Entity* entity) +{ + return entity && entity->type == ENTITY_PROJECTILE && entity->parent.get() == &npc; +} + +// 0057e4a0 Rotgut's maggot in its first dungeon: butt attacks (a splitting bomb, wiggling shots, a fart) and head +// attacks (a laser, wiggling shots, a suck and spray). Its death takes its wiggling shots with it. +static void rotgut_maggot_update(Entity_NPC& npc) +{ + npc.friction = ROTGUT_FRICTION; + int ticks = npc_ticks_get(npc); + Entity* target = npc.GetPlayerTarget(); + bool isTargetHigh = + target->entityGridCollisionClass != GRIDCOLL_GROUND && target->pos.y < npc.pos.y - MAGGOT_TARGET_HIGH; + bool isAttack = true; + + switch (npc.state) + { + case NPC_STATE_INIT: + maggot_init(npc); + isAttack = false; + break; + case ROTGUT_IDLE: + maggot_idle_update(npc); + isAttack = false; + break; + case ROTGUT_SUCK: + maggot_suck_update(npc, ticks); + break; + case ROTGUT_ATTACK: + maggot_bomb_update(npc); + break; + case ROTGUT_ATTACK2: + case ROTGUT_HEAD_SPRAY: + maggot_wiggle_update(npc, isTargetHigh, ticks); + break; + case ROTGUT_ATTACK3: + maggot_fart_update(npc, isTargetHigh, ticks); + break; + case ROTGUT_HEAD_LASER: + if (npc.sprite.IsEventTriggered("Shoot")) + Entity_Laser::ShootAngle( + {.position = vector_add(rotgut_shoot_position(npc), vector_make(0, MAGGOT_LASER_DROP)), + .posOffset = vector_make(0, -MAGGOT_LASER_DROP), + .source = &npc, + .angleDegrees = MAGGOT_LASER_ANGLE, + .timeout = MAGGOT_LASER_FRAMES, + .variant = LASER_THICK_RED}); + break; + default: + isAttack = false; + break; + } + if (isAttack && !npc.sprite.IsPlaying()) npc.state = ROTGUT_IDLE; + + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (!npc.isDead) return; + for (Entity* entity : g_game->room->entityList.updateEL) + { + auto* shot = static_cast(entity); + if (!rotgut_shot_is_own(npc, entity) || !(shot->projectileFlags & PROJECTILE_WIGGLE_ROTGUT)) continue; + shot->projectileFlags &= ~PROJECTILE_WIGGLE_ROTGUT; + shot->isDead = true; + } +} + +// 00580360 One cell of the maggot's way out: its block swapped for open air, the cells about it set up again, and a +// green splat and four rocks where the wall above breaks. +static void rotgut_wall_break(Entity_Effect* timer) +{ + Room& room = *g_game->room; + int column = (int)((timer->pos.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + HALF); + int row = (int)((timer->pos.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + HALF); + int index = room.GetGridIndexByTile(column, row); + if (index < 0) return; + + room.RemoveGridEntityImmediate(index, 0, DECORATION_KEPT); + room.SpawnGridEntity(index, GRID_GRAVITY, 0, Random(), 0); + for (int cell : {index, room.GetGridIndexByTile(column, row + 1)}) + { + GridEntity* grid = cell >= 0 ? room.GetGridEntity(cell) : nullptr; + if (grid) grid->PostInit(); + } + int above = room.GetGridIndexByTile(column, row - 1); + GridEntity* aboveGrid = above >= 0 ? room.GetGridEntity(above) : nullptr; + if (aboveGrid) aboveGrid->PostInit(); + + Vector spot = room.GetGridPosition(above); + Entity* splat = g_game->Spawn({.position = spot, + .subType = BLOOD_EXPLOSION_SPLASH_BIG, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + splat->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + float size = random_between(ROTGUT_WALL_SPLAT_SCALE, ROTGUT_WALL_SPLAT_SCALE_RANGE); + splat->sprite.scale = vector_make(size, size); + splat->sprite.color = COLOR_GREEN_SPLAT; + splat->renderZOffset = ROTGUT_WALL_SPLAT_DEPTH; + + for (int i = 0; i < ROTGUT_WALL_ROCKS; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float speed = random_unit(); + Vector velocity = vector_make(std::cos(angle) * speed * ROTGUT_WALL_ROCK_SPEED, + std::sin(angle) * speed * ROTGUT_WALL_ROCK_SPEED); + float reach = random_unit(); + Vector position = vector_add(spot, vector_scale(vector_normalized(velocity), reach * ROTGUT_WALL_ROCK_REACH)); + g_game + ->Spawn({.position = position, + .velocity = velocity, + .subType = ROTGUT_WALL_ROCK_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_ROCK_PARTICLE, + .seed = Random()}) + ->Update(); + } + npc_sound_play(SOUND_MEATY_DEATHS, 1, 2, 1); +} + +// 00581200 The maggot's death: the way up opens a cell at a time (rows 7, 6 and 5 of column 14, five frames apart) and +// its detail goes. A room too small breaks the corner cell instead. +void rotgut_death_spawn_effects(Entity_NPC& npc) +{ + Room& room = *g_game->room; + for (int i = 0; i < ROTGUT_WALL_CELLS; i++) + { + Entity_Effect* timer = + Entity_Effect::CreateTimer(reinterpret_cast(&rotgut_wall_break), + ROTGUT_WALL_BREAK_DELAY + ROTGUT_WALL_BREAK_STEP * (uint32_t)i, 0, false); + timer->pos = room.GetGridPosition(room.GetGridIndexByTile(ROTGUT_WALL_COLUMN, ROTGUT_WALL_ROW - i)); + } + if (npc.child) npc.child->Remove(); +} + +// One heart's beat: a shake and a fan of shots, or during its summon a rain of fire from the top wall. +static void heart_beat(Entity_NPC& npc, bool isBelowHalf) +{ + game_shake_screen(HEART_BEAT_SHAKE); + npc.PlaySound(isBelowHalf ? SOUND_HEARTBEAT_FASTER : SOUND_HEARTBEAT, 1, 2, false, 1); + if (npc.projectileDelay < 1) return rotgut_fire_projectiles(npc); + + npc.projectileDelay--; + Room& room = *g_game->room; + float left = room.topLeftPos.x + HEART_RAIN_MARGIN; + float width = room.bottomRightPos.x - HEART_RAIN_MARGIN - left; + ProjectileParams params; + params.color = SHOT_COLOR_FIERY; + params.fallingAccelModifier = HEART_RAIN_FALL; + params.bulletFlags = PROJECTILE_NO_WALL_COLLIDE | PROJECTILE_BURST | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT; + params.changeFlags = PROJECTILE_BURST; + params.changeTimeout = HEART_RAIN_TIMEOUT; + for (int i = 0; i < HEART_RAIN_SHOTS; i++) + { + params.scale = HEART_RAIN_SCALE; + float x = random_unit() * width + left; + float speed = random_unit() * HEART_RAIN_SPEED; + Entity_Projectile* shot = + rotgut_projectile_fire(npc, vector_make(x, room.topLeftPos.y), vector_make(0, speed), params); + ColorMod faded = shot->color; + faded._tint[3] = 0; + shot->SetColor(faded, HEART_RAIN_FADE, 1, true, true); + shot->renderZOffset = HEART_RAIN_DEPTH; + } +} + +// The heart's idle: beating (faster below half health), and an attack one in 60 frames after 30. +static void heart_idle_update(Entity_NPC& npc, bool isBelowHalf, int ticks) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play(isBelowHalf ? "HeartbeatFast" : "Heartbeat"); + if (npc.sprite.IsEventTriggered("Shoot")) heart_beat(npc, isBelowHalf); + npc.stateFrame += ticks; + if (npc.i1 < 0) npc.i1 += ticks; + if (npc.stateFrame <= HEART_REST || Random() % HEART_ATTACK_ODDS != 0) return; + + npc.stateFrame = 0; + npc.projectileCooldown = -1; + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(ROTGUT_MOVE_FIRST, HEART_SPIT_WEIGHT); + if (npc.projectileDelay < 1) + { + picker.AddOutcomeWeight(ROTGUT_MOVE_SECOND, HEART_MOVE_WEIGHT); + if (npc.i1 >= 0) picker.AddOutcomeWeight(ROTGUT_MOVE_THIRD, HEART_MOVE_WEIGHT); + } + switch (rotgut_move_pick(picker)) + { + case ROTGUT_MOVE_FIRST: + npc.sprite.Play("SpitDown"); + npc.state = ROTGUT_ATTACK; + break; + case ROTGUT_MOVE_SECOND: + npc.sprite.Play("Summon"); + npc.state = ROTGUT_SUMMON; + npc.PlaySound(SOUND_ANGRY_GURGLE, 1, 10, false, HEART_SUMMON_PITCH); + npc.projectileDelay = HEART_RAIN_BEATS; + break; + case ROTGUT_MOVE_THIRD: + npc.sprite.Play("Retract"); + npc.state = ROTGUT_RETRACTED; + npc.i1 = (int)(Random() & 1); + break; + } +} + +// A leech crossing the room from beyond a side wall, at a height, small or big. +static void heart_leech_send(Entity_NPC& npc, Vector position, bool isBig) +{ + int type = isBig ? ENTITY_ADULT_LEECH : ENTITY_LEECH; + auto* leech = static_cast( + g_game->Spawn({.position = position, .spawner = &npc, .type = type, .seed = Random()})); + leech->ClearEntityFlags(FLAG_APPEAR); + leech->Update(); + leech->state = NPC_STATE_SUICIDE; + leech->entityGridCollisionClass = GRIDCOLL_NONE; + float direction = npc.i1 == 0 ? 1.0f : -1.0f; + leech->targetPosition = vector_make(isBig ? direction : direction * HEART_LEECH_SPEED, 0); + leech->sprite.Play(isBig ? "MoveHori" : "Hori"); + leech->sprite.isFlipX = npc.i1 != 0; + float pitch = rotgut_pitch_get(npc, random_unit() * HEART_LEECH_PITCH_RANGE + HEART_LEECH_PITCH); + npc_sound_play(isBig ? SOUND_BIG_LEECH : SOUND_LEECH, 1, 2, pitch); +} + +// The heart's retreat: hidden for 150 frames while leeches cross from one side (five every 15 frames, a big one one in +// three), beating out fans, then it comes back down. +static void heart_retracted_update(Entity_NPC& npc, int ticks) +{ + if (!npc.sprite.IsPlaying()) + { + npc.sprite.Play("HeartbeatRetracted"); + npc.projectileCooldown = std::max(npc.projectileCooldown, 0); + } + if (npc.sprite.IsEventTriggered("Sound")) + { + npc.PlaySound(SOUND_HEARTIN, 1, 2, false, 1); + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + game_shake_screen(HEART_BEAT_SHAKE); + npc.PlaySound(SOUND_HEARTBEAT, 1, 2, false, 1); + rotgut_fire_projectiles(npc); + } + + Room& room = *g_game->room; + for (int tick = 0; tick < ticks && npc.projectileCooldown >= 0; tick++) + { + int frame = npc.projectileCooldown++; + uint32_t wave = (uint32_t)(frame - HEART_LEECH_FIRST); + bool isLeft = npc.i1 == 0; + if (wave < HEART_LEECH_WAVES && wave % HEART_LEECH_EVERY == 0) + { + float x = isLeft ? room.topLeftPos.x - HEART_LEECH_OUTSIDE : room.bottomRightPos.x + HEART_LEECH_OUTSIDE; + float y = 0; + if ((Random() & 1) == 0) y = npc.GetPlayerTarget()->pos.y; + else + { + float top = room.topLeftPos.y + HEART_LEECH_MARGIN; + y = (room.bottomRightPos.y - HEART_LEECH_MARGIN - top) * random_unit() + top; + } + heart_leech_send(npc, vector_make(x, y), false); + } + else if (npc.projectileCooldown == HEART_BIG_LEECH_FRAME && Random() % HEART_BIG_LEECH_ODDS == 0) + { + float x = + isLeft ? room.topLeftPos.x - HEART_BIG_LEECH_OUTSIDE : room.bottomRightPos.x + HEART_BIG_LEECH_OUTSIDE; + heart_leech_send(npc, vector_make(x, npc.GetPlayerTarget()->pos.y), true); + } + if (npc.projectileCooldown <= HEART_RETRACT_FRAMES) continue; + + npc.entityCollisionClass = ENTCOLL_ALL; + npc.sprite.Play("ComeDown"); + npc.state = ROTGUT_IDLE; + npc_sound_play(SOUND_HEARTOUT, 1, 2, rotgut_pitch_get(npc, 1)); + npc.i1 = HEART_COMEBACK_WAIT; + } +} + +// The heart's spit: one big splitting shot down with a splash. +static void heart_spit_update(Entity_NPC& npc) +{ + if (!npc.sprite.IsEventTriggered("Shoot")) return; + game_shake_screen(HEART_SPIT_SHAKE); + npc.PlaySound(SOUND_HEARTOUT, 1, 2, false, 1); + ProjectileParams params; + params.fallingAccelModifier = HEART_SPIT_FALL; + params.bulletFlags = PROJECTILE_BURSTSPLIT; + params.scale = HEART_SPIT_SCALE; + Vector mouth = vector_make(npc.pos.x, npc.pos.y + ROTGUT_HEART_MOUTH); + rotgut_projectile_fire(npc, mouth, vector_make(0, HEART_SPIT_SPEED), params); + Entity* splash = blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH_BIG, mouth, {}, COLOR_DEFAULT, {}); + splash->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + rotgut_splash(splash, HEART_SPIT_SPLASH, HEART_SPIT_SPLASH_RANGE, MAGGOT_BLOOD_DEPTH); +} + +// 005828b0 One of the heart's death splats: green blood bursting somewhere in the room. +static void heart_death_splat(Entity_Effect*) +{ + Vector spot = g_game->room->GetRandomPosition(0); + Entity* splat = blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH_BIG, spot, {}, COLOR_GREEN_SPLAT, {}); + splat->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + rotgut_splash(splat, HEART_SPIT_SPLASH, HEART_SPIT_SPLASH_RANGE, HEART_DEATH_SPLAT_DEPTH); + npc_sound_play(SOUND_ROCKET_BLAST_DEATH, 1, 2, random_between(HEART_DEATH_PITCH, HEART_DEATH_PITCH_RANGE)); +} + +// 00581730 Rotgut's heart in its second dungeon: fans of shots at each beat, a spit, a rain of fire and a retreat with +// leeches crossing the room. Its death clears its bursting shots and bursts green blood about the room. +static void rotgut_heart_update(Entity_NPC& npc) +{ + npc.friction = ROTGUT_FRICTION; + bool isBelowHalf = npc.health / npc.maxHitPoints < HEART_HALF_HEALTH; + int ticks = npc_ticks_get(npc); + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.splatColor = COLOR_GREEN_SPLAT; + npc.state = ROTGUT_IDLE; + npc.sprite.Play("Heartbeat"); + npc.posOffset.y = HEART_HEIGHT; + npc.targetPosition = npc.pos; + break; + case ROTGUT_IDLE: + heart_idle_update(npc, isBelowHalf, ticks); + break; + case ROTGUT_RETRACTED: + heart_retracted_update(npc, ticks); + break; + case ROTGUT_ATTACK: + heart_spit_update(npc); + if (!npc.sprite.IsPlaying()) npc.state = ROTGUT_IDLE; + break; + case ROTGUT_SUMMON: + if ((npc.sprite.GetFrame() & 1) == 0) game_shake_screen(HEART_SUMMON_SHAKE); + if (!npc.sprite.IsPlaying()) npc.state = ROTGUT_IDLE; + break; + } + + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (!npc.isDead) return; + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (!rotgut_shot_is_own(npc, entity)) continue; + static_cast(entity)->projectileFlags &= ~(PROJECTILE_BURST | PROJECTILE_BURSTSPLIT); + entity->isDead = true; + } + game_shake_screen(HEART_DEATH_SHAKE); + Entity_Effect::CreateTimer(reinterpret_cast(&heart_death_splat), HEART_DEATH_SPLAT_DELAY, HEART_DEATH_SPLATS, + false); +} + +// Rotgut (type 911) by variant: its face, its maggot and its heart. +void boss_rotgut_update(Entity_NPC& npc) +{ + if (npc.variant == ROTGUT_HEART) return rotgut_heart_update(npc); + if (npc.variant == ROTGUT_MAGGOT) return rotgut_maggot_update(npc); + rotgut_face_update(npc); +} diff --git a/src/boss_turdlet.cpp b/src/boss_turdlet.cpp new file mode 100644 index 0000000..ef179f1 --- /dev/null +++ b/src/boss_turdlet.cpp @@ -0,0 +1,476 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_laser.h" +#include +#include + +// Turdlet's states: walking, charging, its charge's wind-up and its split. +constexpr int TURDLET_WALK = NPC_STATE_MOVE; +constexpr int TURDLET_CHARGE = NPC_STATE_JUMP; +constexpr int TURDLET_WIND_UP = NPC_STATE_ATTACK; +constexpr int TURDLET_SPLIT = NPC_STATE_SPECIAL; + +// The chain: segments within 42 join up behind each other, sharing their health (a hit takes them all down to the +// lowest, as damage that ignores invincibility, for 30 frames), following 24 apart at up to 20. +constexpr float TURDLET_JOIN_REACH = 42; +constexpr uint64_t TURDLET_SHARED_DAMAGE = DAMAGE_INVINCIBLE; +constexpr int TURDLET_SHARED_COUNTDOWN = 30; +constexpr float TURDLET_SEGMENT_GAP = 24; +constexpr float TURDLET_SEGMENT_SPEED = 20; +constexpr float TURDLET_FRICTION = 0.85f; +constexpr float TURDLET_CHARGE_FRICTION = 0.98f; +constexpr float TURDLET_START_HEALTH = 0.9f; + +// The walk: the head circles its target 120 to 160 degrees off, the circle widening and turning faster the longer +// it walks (from 120, over 150), and it charges one in five frames once near it after 270. +constexpr float TURDLET_WALK_SETTLE = 120; +constexpr float TURDLET_WALK_SETTLE_SPAN = 80; +constexpr float TURDLET_WALK_WIDEN_SPAN = 150; +constexpr float TURDLET_ORBIT_ANGLE = 120; +constexpr float TURDLET_ORBIT_WIDEN = 40; +constexpr float TURDLET_TURN = 5; +constexpr float TURDLET_TURN_WIDEN = 20; +constexpr float TURDLET_HEAD_SPEED = 1.2f; +constexpr float TURDLET_BODY_SPEED = 1; +constexpr float TURDLET_CHARGE_REACH_SQUARED = 900; +constexpr float TURDLET_CHARGE_AFTER = 270; +constexpr uint32_t TURDLET_CHARGE_ODDS = 5; +constexpr int TURDLET_CHARGE_RIPPLE = 2; + +// The charge: the whole chain at 12 toward the target, carried around its middle, slowing over 60 to 150 and ending +// below 3 after 150. +constexpr float TURDLET_CHARGE_SPEED = 12; +constexpr float TURDLET_FOLLOW_PULL = 0.5f; +constexpr float TURDLET_CHARGE_FADE_START = 60; +constexpr float TURDLET_CHARGE_FADE_SPAN = 90; +constexpr float TURDLET_CHARGE_PUSH = 10; +constexpr int TURDLET_SHORT_CHAIN = 4; +constexpr float TURDLET_SHORT_BOOST = 1.35f; +constexpr float TURDLET_PUSH_MIN = 0.5f; +constexpr float TURDLET_PUSH_SHARE = 0.2f; +constexpr float TURDLET_SPIN = 6; +constexpr float TURDLET_SPIN_STEP = 0.5f; +constexpr float TURDLET_SPIN_SHARE = 0.05f; +constexpr float TURDLET_CHARGE_END = 150; +constexpr float TURDLET_CHARGE_END_SPEED = 3; + +// The split: below a tenth of its health per pair of segments it splits in two, each half healed by a tenth. +constexpr int TURDLET_SPLIT_MIN = 3; +constexpr float TURDLET_SPLIT_HEALTH = 0.1f; +constexpr float TURDLET_SPLIT_WALK = -120; + +// Its trail: a splat one in eight frames, sized 0.2 to 0.7, and slippery creep every eight ticks, 0.75 to 1 wide. +constexpr uint32_t TURDLET_SPLAT_MASK = 7; +constexpr float TURDLET_SPLAT_SIZE = 0.2f; +constexpr float TURDLET_SPLAT_SIZE_RANGE = 0.5f; +constexpr float TURDLET_CREEP_EVERY = -0.125f; +constexpr float TURDLET_CREEP_SIZE = 0.75f; +constexpr float TURDLET_CREEP_SIZE_RANGE = 0.25f; + +// The head's sprite turns in twelve steps of 30 degrees, three frames each. +constexpr float TURDLET_HEAD_STEP = 30; +constexpr int TURDLET_HEAD_STEPS = 12; +constexpr int TURDLET_HEAD_FRAMES = 3; +constexpr float TURDLET_BOUNCE_FRAME_SCALE = 255; + +// The chain from a segment back toward its tail. +static int turdlet_chain_length(Entity_NPC& npc) +{ + int count = 0; + for (Entity* segment = &npc; segment; segment = segment->child.get()) count++; + return count; +} + +// 0059c5d0 Its look from its overlay's Bounce null: the head turned toward its heading (v1.x), a body segment by its +// place in the chain, each layer moved, scaled and turned with the bounce. +static void turdlet_segments_update(Entity_NPC& npc) +{ + if (!npc.sprite.overlayAnimState.animData) return; + const NullFrame* bounce = npc.sprite.overlayAnimState.GetNullFrame("Bounce"); + if (!bounce) + { + for (LayerState& layer : npc.sprite.layerStates) + { + layer.pos = {}; + layer.size = vector_make(1, 1); + layer.rotation = 0; + } + return; + } + + if (!npc.parent) + { + float heading = normalize_angle_degrees(npc.v1.x); + int step = (int)((heading + FULL_TURN_DEGREES) / TURDLET_HEAD_STEP + HALF) % TURDLET_HEAD_STEPS; + npc.sprite.SetFrame("HeadRotate", + step * TURDLET_HEAD_FRAMES + (int)(bounce->color._tint[0] * TURDLET_BOUNCE_FRAME_SCALE)); + } + else + { + int depth = -1; + for (Entity* ancestor = npc.parent.get(); ancestor; ancestor = ancestor->parent.get()) depth++; + npc.sprite.SetFrame("BodySegments", depth); + } + + for (LayerState& layer : npc.sprite.layerStates) + { + layer.pos = bounce->pos; + layer.size = bounce->scale; + layer.rotation = bounce->rotation; + } +} + +// Before its update, every segment behind it takes the damage down to the lowest health among them. +static void turdlet_health_share(Entity_NPC& npc) +{ + float lowest = npc.health - npc.pendingDamage; + for (Entity* segment = &npc; segment; segment = segment->child.get()) + lowest = std::min(lowest, segment->health - segment->pendingDamage); + for (Entity* segment = &npc; segment; segment = segment->child.get()) + { + float health = segment->health - segment->pendingDamage; + if (health > lowest) + segment->TakeDamage(health - lowest, TURDLET_SHARED_DAMAGE, EntityRef(&npc), TURDLET_SHARED_COUNTDOWN); + } +} + +// Its start: it joins the free tail of a segment within 42, records its place in its parent's trail, and a head +// numbers its chain's group. +static void turdlet_init(Entity_NPC& npc) +{ + std::vector others = entity_query(npc.type, npc.variant); + for (auto other = others.rbegin(); other != others.rend(); other++) + { + if (*other == &npc || (*other)->parent.get() == &npc || (*other)->child) continue; + if (vector_length(vector_sub(npc.pos, (*other)->pos)) >= TURDLET_JOIN_REACH) continue; + bool isLoop = false; + for (Entity* link = *other; link && !isLoop; link = link->parent.get()) + { + isLoop = link == &npc; + if (link->parent.get() == *other) break; + } + if (!isLoop) npc.parent = *other; + } + if (npc.parent) npc.parent->child = &npc; + + npc.v1.x = random_unit() * FULL_TURN_DEGREES; + npc.sprite.PlayOverlay("HeadWalkOverlay"); + npc.state = TURDLET_WALK; + npc.splatColor = POOP_SPLAT_COLOR; + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + npc.v2.y = npc.maxHitPoints * TURDLET_START_HEALTH; + if (npc.parent) static_cast(npc.parent.get())->vectorDeque1.push_back(npc.pos); + if (!npc.parent) + for (Entity_NPC* segment = &npc; segment; segment = segment->ChildNPC()) segment->groupIdx = npc.index; + for (auto* segment = static_cast(npc.GetLastParent()); segment; segment = segment->ChildNPC()) + turdlet_segments_update(*segment); +} + +// The head's walk: circling its target, turning toward the side of the circle nearer its heading. +static void turdlet_head_walk(Entity_NPC& npc) +{ + if (npc.isCollidesWithGrid) npc.v1.x = vector_angle(npc.velocity); + Vector target = npc.CalcTargetPosition(0); + if (npc.v2.x >= TURDLET_WALK_SETTLE) + { + float settle = std::clamp((npc.v2.x - TURDLET_WALK_SETTLE) / TURDLET_WALK_SETTLE_SPAN, 0.0f, 1.0f); + npc.targetPosition = + vector_add(vector_scale(vector_sub(target, npc.targetPosition), 1 - settle), npc.targetPosition); + } + else npc.targetPosition = target; + + float widen = std::clamp((npc.v2.x - TURDLET_WALK_SETTLE) / TURDLET_WALK_WIDEN_SPAN, 0.0f, 1.0f); + float orbit = widen * TURDLET_ORBIT_WIDEN + TURDLET_ORBIT_ANGLE; + float away = vector_angle(vector_sub(npc.pos, npc.targetPosition)); + float left = away - orbit; + float right = away + orbit; + float goal = + std::abs(angle_difference(left, npc.v1.x)) <= std::abs(angle_difference(right, npc.v1.x)) ? left : right; + npc.v1.x = angle_approach(npc.v1.x, goal, npc.speedMultiplier * (widen * TURDLET_TURN_WIDEN + TURDLET_TURN)); + npc.v1.y = TURDLET_HEAD_SPEED; + npc.friction *= TURDLET_FRICTION; + npc_push(npc, vector_scale(vector_from_angle(npc.v1.x), TURDLET_HEAD_SPEED)); + + bool isNear = vector_length_squared(vector_sub(npc.targetPosition, npc.pos)) < TURDLET_CHARGE_REACH_SQUARED; + if (isNear && npc.v2.x > TURDLET_CHARGE_AFTER && Random() % TURDLET_CHARGE_ODDS == 0) + { + npc.state = TURDLET_WIND_UP; + npc.sprite.PlayOverlay("HeadChargeOverlay"); + npc.ChildNPC()->i1 = TURDLET_CHARGE_RIPPLE; + } + npc.v2.x = (random_unit() + 1) * npc.speedMultiplier + npc.v2.x; +} + +// A body segment's walk: its charge overlay passed down the chain a frame or two after its parent's. +static void turdlet_body_walk(Entity_NPC& npc) +{ + npc.v1.y = TURDLET_BODY_SPEED; + npc.friction *= TURDLET_FRICTION; + if (npc.i1 <= 0) return; + npc.i1 -= npc_ticks_get(npc); + if (npc.i1 >= 0) return; + npc.sprite.PlayOverlay("HeadChargeOverlay"); + if (npc.child) npc.ChildNPC()->i1 = TURDLET_CHARGE_RIPPLE; +} + +// The wind-up: once the head's overlay ends it roars and the whole chain charges from its middle at the target. +static void turdlet_wind_up(Entity_NPC& npc) +{ + npc.friction *= TURDLET_FRICTION; + if (npc.parent || npc.sprite.IsOverlayPlaying()) return; + + npc.PlaySound(SOUND_CHILD_ANGRY_ROAR, 1, 2, false, 1); + Vector middle{}; + int count = 0; + for (Entity* segment = &npc; segment; segment = segment->child.get(), count++) + middle = vector_add(middle, segment->pos); + middle = vector_scale(middle, 1 / (float)count); + Vector velocity = vector_resized(vector_sub(npc.CalcTargetPosition(0), middle), TURDLET_CHARGE_SPEED); + for (Entity_NPC* segment = &npc; segment; segment = segment->ChildNPC()) + { + segment->sprite.PlayOverlay("HeadChargeLoopOverlay"); + segment->state = TURDLET_CHARGE; + segment->velocity = velocity; + segment->v2.x = 0; + } +} + +// A segment's place in the charging chain: kept 24 behind its neighbour (or midway between two), and the head turned +// away from its child. +static void turdlet_charge_follow(Entity_NPC& npc) +{ + Entity* parent = npc.parent.get(); + Entity* child = npc.child.get(); + if (parent && child) + { + Vector middle = vector_scale(vector_add(vector_add(parent->prevPosition, parent->prevVelocity), + vector_add(child->prevPosition, child->prevVelocity)), + HALF); + npc.velocity = vector_add( + vector_scale(vector_sub(vector_sub(middle, npc.pos), npc.velocity), TURDLET_FOLLOW_PULL), npc.velocity); + return; + } + Entity* neighbour = parent ? parent : child; + if (!neighbour) return; + if (!parent) npc.v1.x = vector_angle(vector_sub(npc.pos, child->pos)); + Vector anchor = vector_add(neighbour->prevPosition, neighbour->prevVelocity); + Vector offset = + vector_resized(vector_sub(vector_add(npc.prevPosition, npc.prevVelocity), anchor), TURDLET_SEGMENT_GAP); + Vector spot = vector_add(anchor, offset); + npc.velocity = vector_add(vector_scale(vector_sub(vector_sub(spot, npc.pos), npc.velocity), TURDLET_FOLLOW_PULL), + npc.velocity); +} + +// The chain's shared motion while charging: its mean push kept up and its spin about its middle, both fading as the +// charge goes on. The chain's mean speed. +static float turdlet_charge_carry(Entity_NPC& npc) +{ + Entity* head = npc.GetLastParent(); + Vector middle{}; + int count = 0; + for (Entity* segment = head; segment; segment = segment->child.get(), count++) + middle = vector_add(middle, segment->prevPosition); + middle = vector_scale(middle, 1 / (float)count); + + Vector push{}; + float spin = 0; + for (Entity* segment = head; segment; segment = segment->child.get()) + { + push = vector_add(push, segment->prevVelocity); + Vector arm = vector_sub(segment->prevPosition, middle); + if (vector_length(arm) < 1) continue; + spin += vector_dot(vector_rotated(vector_normalized(arm), RIGHT_ANGLE_DEGREES), segment->prevVelocity); + } + spin /= (float)count; + push = vector_scale(push, 1 / (float)count); + + float fade = 1 - std::clamp((npc.v2.x - TURDLET_CHARGE_FADE_START) / TURDLET_CHARGE_FADE_SPAN, 0.0f, 1.0f); + float pushMax = fade * TURDLET_CHARGE_PUSH; + if (count < TURDLET_SHORT_CHAIN) pushMax *= TURDLET_SHORT_BOOST; + float speed = vector_length(push); + if (pushMax > TURDLET_PUSH_MIN && speed < pushMax) + { + if (speed > 0) push = vector_scale(push, (pushMax - speed) * TURDLET_PUSH_SHARE / speed); + npc.velocity = vector_add(vector_scale(push, npc.speedMultiplier), npc.velocity); + } + + float spinMax = fade * fade * TURDLET_SPIN; + if (spinMax > TURDLET_SPIN_STEP && std::abs(spin) < spinMax) + { + float turn = std::clamp((spin <= 0 ? -spinMax : spinMax) - spin, -TURDLET_SPIN_STEP, TURDLET_SPIN_STEP); + Vector arm = vector_rotated(vector_sub(npc.prevPosition, middle), RIGHT_ANGLE_DEGREES); + npc.velocity = vector_add(vector_scale(arm, turn * TURDLET_SPIN_SHARE * npc.speedMultiplier), npc.velocity); + } + return speed; +} + +// Each segment's trail rebuilt toward its parent: its parent's trail starts at it. +static void turdlet_trails_restart(Entity_NPC& npc) +{ + for (Entity* segment = npc.child.get(); segment; segment = segment->child.get()) + static_cast(segment->parent.get())->vectorDeque1.push_front(segment->pos); +} + +// The charge: walls it meets shared down the chain, and once slow after 150 the head ends it for all. Whether the +// update goes on to its end. +static bool turdlet_charge(Entity_NPC& npc) +{ + npc.friction *= TURDLET_CHARGE_FRICTION; + npc.v2.x += npc.speedMultiplier; + if (npc.isCollidesWithGrid) + { + Vector bump = vector_sub(npc.velocity, npc.gridCollisionVelocity); + for (Entity* segment = npc.GetLastParent(); segment; segment = segment->child.get()) + { + if (segment->isCollidesWithGrid) continue; + segment->isCollidesWithGrid = npc.isCollidesWithGrid; + segment->gridCollisionVelocity = npc.gridCollisionVelocity; + segment->gridCollisionNormal = npc.gridCollisionNormal; + segment->velocity = vector_add(vector_scale(bump, segment->speedMultiplier), segment->velocity); + } + } + turdlet_charge_follow(npc); + float speed = turdlet_charge_carry(npc); + if (npc.parent) return false; + if (npc.v2.x <= TURDLET_CHARGE_END || speed >= TURDLET_CHARGE_END_SPEED) return true; + + for (Entity_NPC* segment = &npc; segment; segment = segment->ChildNPC()) + segment->sprite.PlayOverlay("HeadChargeEndOverlay"); + if (npc.sprite.IsOverlayPlaying()) return true; + for (Entity_NPC* segment = &npc; segment; segment = segment->ChildNPC()) + { + segment->sprite.PlayOverlay("HeadWalkOverlay"); + segment->state = TURDLET_WALK; + segment->v2.x = 0; + segment->vectorDeque1.clear(); + } + turdlet_trails_restart(npc); + return true; +} + +// The split's end: the chain healed by a tenth and walking again, broken at its middle (the middle segment dropped +// from an odd chain), with a burst of blood. Whether the update goes on to its end. +static bool turdlet_split(Entity_NPC& npc) +{ + npc.friction *= TURDLET_FRICTION; + segment_follow(npc, SEGMENT_FOLLOW, TURDLET_SEGMENT_GAP, TURDLET_SEGMENT_SPEED); + if (npc.sprite.IsPlaying()) return true; + if (npc.parent) return false; + + float health = std::min(npc.maxHitPoints * TURDLET_SPLIT_HEALTH + npc.health, npc.maxHitPoints); + int count = 0; + for (Entity_NPC* segment = &npc; segment; segment = segment->ChildNPC(), count++) + { + segment->health = health; + segment->sprite.PlayOverlay("HeadWalkOverlay"); + segment->state = TURDLET_WALK; + segment->ClearEntityFlags(FLAG_NO_STATUS_EFFECTS); + segment->entityCollisionClass = ENTCOLL_ALL; + segment->isInvincible = false; + segment->v2.x = random_unit() * TURDLET_SPLIT_WALK; + } + + int half = count / 2; + Entity* middle = &npc; + for (int i = 0; i < half && middle; i++) middle = middle->child.get(); + Vector burst = middle->pos; + Entity* before = middle->parent.get(); + if (half * 2 < count) + { + before->child = nullptr; + middle->child->parent = nullptr; + middle->Remove(); + } + else + { + burst = vector_scale(vector_add(burst, before->pos), HALF); + before->child = nullptr; + middle->parent = nullptr; + } + // The original moves the middle segment (not the head) to the burst for the head's blood explosion, then leaves it + // where the head stands. + Vector headPos = npc.pos; + middle->pos = burst; + npc.BloodExplode(); + middle->pos = headPos; + return true; +} + +// A head with more than three segments splits instead of dying, and below a tenth of its health per pair of +// segments: every segment plays its death. +static void turdlet_split_check(Entity_NPC& npc) +{ + int count = turdlet_chain_length(npc); + float threshold = (float)(count / 2) * TURDLET_SPLIT_HEALTH * npc.maxHitPoints; + if (count <= TURDLET_SPLIT_MIN || (!npc.isDead && npc.health >= threshold)) return; + + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + npc.isDead = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.state = TURDLET_SPLIT; + npc.isInvincible = true; + for (Entity_NPC* segment = &npc; segment; segment = segment->ChildNPC()) + { + segment->isDead = false; + segment->entityCollisionClass = ENTCOLL_NONE; + segment->state = TURDLET_SPLIT; + segment->sprite.overlayAnimState.SetAnimationData(nullptr); + segment->sprite.Play(segment->parent ? "DeathBody00" : "DeathHead"); + segment->v2 = {}; + segment->vectorDeque1.clear(); + } + turdlet_trails_restart(npc); +} + +// Its trail: brown splats and slippery creep every eight ticks. +static void turdlet_trail(Entity_NPC& npc) +{ + if ((Random() & TURDLET_SPLAT_MASK) == 0) + npc.MakeSplat(random_unit() * TURDLET_SPLAT_SIZE_RANGE + TURDLET_SPLAT_SIZE) + ->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + + bool isTick = (int)(npc.prevUpdateTime * TURDLET_CREEP_EVERY) != (int)(npc.updateTime * TURDLET_CREEP_EVERY); + if (npc.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused() || !isTick) return; + Entity* creep = g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_SLIPPERY_BROWN, + .seed = Random()}); + float size = random_unit() * TURDLET_CREEP_SIZE_RANGE + TURDLET_CREEP_SIZE; + creep->sprite.scale = vector_make(size, size); + creep->Update(); +} + +// 0059c830 Turdlet: segments that join into a chain sharing its health, the head circling its target and charging +// with the whole chain, splitting in two instead of dying while it is long. A lone segment dies. +void boss_turdlet_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) return turdlet_health_share(npc); + if (npc.state == NPC_STATE_INIT) return turdlet_init(npc); + if (!npc.parent && !npc.child) return npc.Kill(EntityRef()); + + bool isEnd = true; + switch (npc.state) + { + case TURDLET_WALK: + if (npc.parent) turdlet_body_walk(npc); + else turdlet_head_walk(npc); + segment_follow(npc, SEGMENT_FOLLOW, TURDLET_SEGMENT_GAP, TURDLET_SEGMENT_SPEED); + break; + case TURDLET_WIND_UP: + turdlet_wind_up(npc); + segment_follow(npc, SEGMENT_FOLLOW, TURDLET_SEGMENT_GAP, TURDLET_SEGMENT_SPEED); + break; + case TURDLET_CHARGE: + isEnd = turdlet_charge(npc); + break; + case TURDLET_SPLIT: + isEnd = turdlet_split(npc); + break; + } + if (isEnd && !npc.parent) turdlet_split_check(npc); + + turdlet_trail(npc); + turdlet_segments_update(npc); +} diff --git a/src/console_commands.cpp b/src/console_commands.cpp index 2d90c7e..8949700 100644 --- a/src/console_commands.cpp +++ b/src/console_commands.cpp @@ -953,7 +953,7 @@ static void addplayer_run(ConsoleCommand& command) static void reloadfx_run(ConsoleCommand&) { - reconstruction_missing("Room::reload_backdrop 007f2070"); + g_game->room->reload_backdrop(); } // reloadwisps: reloads wisps.xml and locusts.xml and inits the room's wisps and locusts again. diff --git a/src/cutscene.cpp b/src/cutscene.cpp index c45bda1..df2e6d4 100644 --- a/src/cutscene.cpp +++ b/src/cutscene.cpp @@ -37,8 +37,6 @@ constexpr float VIDEO_VOLUME_SCALE = 3; constexpr float VIDEO_SUBTITLE_SCALE = 2; constexpr float POPUP_BUTTON_HIDDEN_OFFSET = 96; constexpr uint32_t FRAMES_PER_SECOND = 30; -constexpr uint32_t MS_PER_SECOND = 1000; -constexpr uint64_t NS_PER_MS = 1000000; constexpr int TIMING_DRIFT_LIMIT = 3; // Without a part, the screen is laid out for this canvas, as is a temporary part. diff --git a/src/cutscene.h b/src/cutscene.h index 5b82918..5b15dd9 100644 --- a/src/cutscene.h +++ b/src/cutscene.h @@ -13,6 +13,7 @@ // The cutscenes cutscenes.xml can fill, by id. Id 0 is no cutscene. constexpr int CUTSCENE_ENTRY_COUNT = 27; +constexpr int CUTSCENE_CREDITS = 2; constexpr int SUBTITLE_LINE_LIMIT = 4; constexpr int NO_PART = -1; diff --git a/src/entity.cpp b/src/entity.cpp index d2f6662..85286bf 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -75,10 +75,6 @@ constexpr int HIT_FLASH_MIN = 1; constexpr int HIT_FLASH_MAX = 6; constexpr float POSITION_LIMIT = 10000; // The debug flags PostRender draws for: entity positions, collision shapes and grid collision points. -constexpr uint32_t DEBUG_ENTITY_POSITIONS = 1 << 0; -constexpr uint32_t DEBUG_HITSPHERES = 1 << 5; -constexpr uint32_t DEBUG_DAMAGE_VALUES = 1 << 6; -constexpr uint32_t DEBUG_GRID_COLLISION = 1 << 12; // The flags an EntityRef's status flags come from, and those CopyStatusEffects hands a segment. constexpr uint64_t SHARED_STATUS_FLAGS = FLAG_FREEZE | FLAG_POISON | FLAG_SLOW | FLAG_CHARM | FLAG_CONFUSION | diff --git a/src/entity.h b/src/entity.h index e4305bc..cc48209 100644 --- a/src/entity.h +++ b/src/entity.h @@ -174,6 +174,7 @@ enum EntityType : int ENTITY_BLACK_GLOBIN = 278, ENTITY_BLACK_GLOBIN_HEAD = 279, ENTITY_BLACK_GLOBIN_BODY = 280, + ENTITY_SWARM = 281, ENTITY_BONE_KNIGHT = 283, ENTITY_RED_GHOST = 285, ENTITY_FLESH_DEATHS_HEAD = 286, @@ -182,16 +183,22 @@ enum EntityType : int ENTITY_MEATBALL = 290, ENTITY_PITFALL = 291, ENTITY_MOVABLE_TNT = 292, + ENTITY_ULTRA_COIN = 293, + ENTITY_ULTRA_DOOR = 294, ENTITY_CORN_MINE = 295, ENTITY_HUSH_FLY = 296, ENTITY_HUSH_GAPER = 297, ENTITY_HUSH_BOIL = 298, + ENTITY_GREED_GAPER = 299, ENTITY_POISON_MIND = 301, ENTITY_STONEY = 302, ENTITY_BLISTER = 303, ENTITY_THE_THING = 304, ENTITY_PORTAL = 306, + ENTITY_TARBOY = 307, + ENTITY_FISTULOID = 308, ENTITY_LEPER = 310, + ENTITY_MR_MINE = 311, ENTITY_STAIN = 401, ENTITY_BROWNIE = 402, ENTITY_FORSAKEN = 403, @@ -237,13 +244,17 @@ enum EntityType : int ENTITY_WHIPPER = 834, ENTITY_REVENANT = 841, ENTITY_PON = 840, + ENTITY_SPIKEBALL = 852, ENTITY_SMALL_MAGGOT = 853, + ENTITY_ADULT_LEECH = 854, + ENTITY_GASBAG = 856, ENTITY_PUSTULE = 861, ENTITY_CYST = 862, ENTITY_MORNINGSTAR = 863, ENTITY_MOCKULUS = 864, ENTITY_EVIS = 865, ENTITY_DARK_ESAU = 866, + ENTITY_ARMYFLY = 868, ENTITY_SIREN_HELPER = 966, ENTITY_DRIP = 870, ENTITY_SPLURT = 871, @@ -403,6 +414,7 @@ enum DamageFlag : uint64_t DAMAGE_SPAWN_FLY = 1ull << 14, DAMAGE_POISON_BURN = 1ull << 15, DAMAGE_CURSED_DOOR = 1ull << 16, + DAMAGE_TIMER = 1ull << 17, DAMAGE_IV_BAG = 1ull << 18, DAMAGE_PITFALL = 1ull << 19, DAMAGE_CHEST = 1ull << 20, @@ -419,6 +431,7 @@ enum DamageFlag : uint64_t DAMAGE_SPAWN_CARD = 1ull << 31, DAMAGE_SPAWN_RUNE = 1ull << 32, DAMAGE_CHAMPION_REWARD = 1ull << 33, + DAMAGE_IGNORED = 1ull << 34, DAMAGE_THROUGH_COOLDOWN = 1ull << 35 }; diff --git a/src/entity_bomb.cpp b/src/entity_bomb.cpp index 5efc91c..3c59459 100644 --- a/src/entity_bomb.cpp +++ b/src/entity_bomb.cpp @@ -5,6 +5,7 @@ #include "entity_familiar.h" #include "entity_knife.h" #include "entity_laser.h" +#include "entity_pickup.h" #include "entity_player.h" #include "entity_tear.h" #include "game.h" @@ -17,6 +18,8 @@ #include "npc_ai.h" #include "npc_basement.h" #include "room.h" +#include "entity_npc.h" +#include "room_grid.h" #include "sfx_manager.h" #include #include @@ -94,8 +97,6 @@ constexpr size_t ANM2_EXTENSION_SIZE = 5; // The items and entities a bomb asks about (Lua's names). constexpr int TRINKET_BLASTING_CAP = 73; -constexpr int PICKUP_BOMB = 40; -constexpr int PICKUP_BOMBCHEST = 51; constexpr int POOF01_EFFECT = 15; constexpr int VISAGE_MASK_VARIANT = 10; @@ -141,6 +142,53 @@ constexpr float ROCKET_SMOKE_SCALE = 0.4f; constexpr float ROCKET_SMOKE_DEPTH = -18; constexpr ColorMod ROCKET_SMOKE_COLOR = {{1, 1, 1, 0.3f}, {}, {}}; +// Hot Bombs' burn: an enemy's damage, and how near a player has to be to an enemy's bomb. +constexpr float HOT_ENEMY_DAMAGE = 16; +constexpr float HOT_PLAYER_MARGIN = 1.5f; + +// Bobby-Bomb: how far ahead it looks and how wide, how often it may pick, and its pull toward its target. +constexpr float BOBBY_LOOKAHEAD = 5; +constexpr float BOBBY_REACH = 150; +constexpr int BOBBY_SEEK_PERIOD = 5; +constexpr float BOBBY_PULL = 1.33f; + +// Bob's Bladder's creep: every seventh frame, its damage (5 in a versus match, else a third of the bomb's past 30, at +// least 6), size, color, and the golden trinket's growth. +constexpr int BLADDER_PERIOD = 7; +constexpr float BLADDER_DAMAGE_VERSUS = 5; +constexpr float BLADDER_DAMAGE_MIN = 6; +constexpr float BLADDER_DAMAGE_BASE = 30; +constexpr float BLADDER_SCALE_MIN = 0.3f; +constexpr float BLADDER_SCALE_RANGE = 0.6f; +constexpr ColorMod BLADDER_CREEP_COLOR = {{0, 1, 1, 1}, {0, 0, 0, 0}, {0, 0.39215687f, 0}}; +constexpr float BLADDER_GOLDEN_GROW = 1.5f; + +// Sticky Bombs slow what they stick to. +constexpr float STICKY_HOLD = 0.9f; + +// Scatter Bombs' bomblets: four or five, their speed and spread, reach, rise (a rocket's higher and falling back) and +// fuse. +constexpr int SCATTER_BOMBLETS = 4; +constexpr float SCATTER_SPEED_MIN = 3; +constexpr float SCATTER_SPEED_RANGE = 7; +constexpr float SCATTER_SPREAD = 15; +constexpr float SCATTER_RADIUS = 0.65f; +constexpr float SCATTER_ROCKET_FALL = 1.3f; +constexpr float SCATTER_RISE_MIN = 3; +constexpr float SCATTER_RISE_RANGE = 5; +constexpr float SCATTER_ROCKET_RISE_RANGE = 10; +constexpr uint32_t SCATTER_FUSE_RANGE = 14; +constexpr int SCATTER_FUSE_MIN = 10; + +// Ghost Bombs: the seed's shifts, the size from which the ghost is a hungry soul, its wail and life. +constexpr std::array GHOST_RNG_SHIFTS = {2, 7, 25}; +constexpr float GHOST_BOMB_BIG_SCALE = 0.75f; +constexpr float GHOST_VOLUME = 0.7f; +constexpr float GHOST_PITCH_MIN = 2; +constexpr float GHOST_PITCH_RANGE = 0.4f; +constexpr int GHOST_FRAMES = 360; +constexpr int GHOST_FETUS_FRAMES = 180; + // The running number each player bomb takes on its first frame (the original's 00c7ec64). static int g_bombIndexCounter = 0; @@ -150,6 +198,138 @@ static void flag_check(const Entity_Bomb& bomb, int bit, const char* what) if (bomb.tearFlags[bit]) reconstruction_missing(what); } +// Hot Bombs burn what they touch: a player's bomb the vulnerable enemies it overlaps, anyone else's the players beside +// it. +static void hot_bomb_burn(Entity_Bomb& bomb) +{ + auto isTouching = [&](Entity& other, float margin) + { + float reach = other.size + bomb.size + margin; + return vector_length_squared(vector_sub(other.pos, bomb.pos)) < reach * reach; + }; + if (bomb.spawnerType == ENTITY_PLAYER) + { + for (Entity* enemy : entity_query_radius(bomb.pos, bomb.size, QUERY_ENEMIES)) + if (enemy->IsVulnerableEnemy(nullptr) && isTouching(*enemy, 0)) + enemy->TakeDamage(HOT_ENEMY_DAMAGE, DAMAGE_FIRE, EntityRef(&bomb), HIT_COUNTDOWN); + return; + } + for (Entity_Player* player : g_game->playerManager.playerList) + if (player && isTouching(*player, HOT_PLAYER_MARGIN)) player->TakeDamage(1, DAMAGE_FIRE, EntityRef(&bomb), HIT_COUNTDOWN); +} + +// Bobby-Bomb: now and then the bomb picks a vulnerable enemy in sight ahead of it, then drifts toward it (a rocket +// steers itself instead). +static void bobby_bomb_home(Entity_Bomb& bomb) +{ + if (Entity* target = bomb.target) + { + if (!bomb.IsRocket() && (Random() & 1) == 0) + bomb.velocity = vector_sub(bomb.velocity, vector_scale(vector_normalized(vector_sub(bomb.pos, target->pos)), BOBBY_PULL)); + return; + } + Vector ahead = vector_add(bomb.pos, vector_scale(bomb.velocity, BOBBY_LOOKAHEAD)); + for (Entity* enemy : entity_query_radius(ahead, BOBBY_REACH, QUERY_ENEMIES)) + { + bool isPrey = enemy->IsVulnerableEnemy(nullptr) && (!bomb.spawnerEntity || !bomb.spawnerEntity->IsDescendantOf(enemy)) && + !enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET); + if (isPrey && (Random() & 1) && bomb.IsFrame(BOBBY_SEEK_PERIOD, (int)bomb.index) && + room_check_line(bomb.pos, enemy->pos, LINE_MODE_CELL, 0)) + bomb.target = enemy; + } +} + +// Bob's Bladder: every seventh frame a lit bomb leaves a puddle of green creep, stronger with a stronger bomb, larger +// (and from three, longer lasting) with a golden or doubled trinket. +static void bladder_creep_drop(Entity_Bomb& bomb) +{ + float damage = g_game->deathmatchManager.is_active() ? BLADDER_DAMAGE_VERSUS + : std::max(BLADDER_DAMAGE_MIN, (bomb.explosionDamage - BLADDER_DAMAGE_BASE) / 3); + auto* creep = static_cast(g_game->Spawn({.position = bomb.pos, .spawner = bomb.spawnerEntity, .type = ENTITY_EFFECT, + .variant = EFFECT_PLAYER_CREEP_RED, .seed = Random()})); + float scale = random_unit() * BLADDER_SCALE_RANGE + BLADDER_SCALE_MIN; + creep->sprite.scale = vector_make(scale, scale); + creep->SetColor(BLADDER_CREEP_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + creep->SetCollisionDamage(damage); + Entity* owner = bomb.spawnerEntity; + int multiplier = owner && owner->type == ENTITY_PLAYER ? owner->ToPlayer()->GetTrinketMultiplier(TRINKET_BOBS_BLADDER) : 0; + if (multiplier > 1) + { + float grow = multiplier > 2 ? 2 : BLADDER_GOLDEN_GROW; + if (multiplier > 2) creep->SetTimeout((int)((float)creep->timeout * BLADDER_GOLDEN_GROW)); + creep->sprite.scale = vector_scale(creep->sprite.scale, grow); + } + creep->spawnerType = bomb.spawnerType; + creep->spawnerVariant = bomb.spawnerVariant; + creep->Update(); +} + +// Scatter Bombs: four or five half-size bomblets flung around, carrying the bomb's effects but this one, with a short +// random fuse. A player's are plain bombs whatever the bomb was. +static void scatter_bomblets_throw(Entity_Bomb& bomb, Entity_Player* spawner) +{ + int count = (int)(Random() & 1) + SCATTER_BOMBLETS; + for (int i = 0; i < count; i++) + { + Vector direction = random_direction(); + uint32_t seed = Random(); + float speed = random_unit() * SCATTER_SPEED_RANGE + SCATTER_SPEED_MIN; + float distance = random_unit() * SCATTER_SPREAD; + auto* bomblet = static_cast(g_game->Spawn({.position = vector_add(bomb.pos, vector_scale(direction, distance)), + .velocity = vector_scale(direction, speed), + .spawner = bomb.spawnerEntity, + .type = bomb.type, + .variant = spawner ? (int)BOMB_NORMAL : bomb.variant, + .seed = seed})); + bomblet->isFetus = bomb.isFetus; + bomblet->spawnerType = bomb.spawnerType; + bomblet->spawnerVariant = bomb.spawnerVariant; + bomblet->tearFlags = bomb.tearFlags; + bomblet->tearFlags.reset(TEAR_SCATTER_BOMB); + bomblet->isLoadCostumes = true; + bomblet->scale = bomb.scale * HALF; + bomblet->explosionDamage = bomb.explosionDamage * HALF; + bomblet->radiusMultiplier = bomb.radiusMultiplier * SCATTER_RADIUS; + bomblet->SetSize(bomblet->size * HALF, vector_make(-1, -1), -1); + bool isRocket = bomblet->IsRocket(); + if (isRocket) bomblet->fallAcceleration = SCATTER_ROCKET_FALL; + bomblet->fallSpeed = -SCATTER_RISE_MIN - random_unit() * (isRocket ? SCATTER_ROCKET_RISE_RANGE : SCATTER_RISE_RANGE); + bomblet->posOffset = vector_make(0, -SCATTER_RISE_MIN); + int fuse = (int)bomblet->dropRNG.RandomInt(SCATTER_FUSE_RANGE) + SCATTER_FUSE_MIN; + bomblet->AddEntityFlags(FLAG_NO_KNOCKBACK | FLAG_NO_REWARD); + bomblet->explosionCountdown = fuse; + bomblet->explosionCountdown2 = fuse; + } +} + +// Ghost Bombs: a bomb's ghost rises where it blew, a wailing hungry soul for a full-size bomb (lasting six seconds, +// three for a Dr. Fetus bomb, as strong and large as the bomb), else a small purgatory ghost already risen. +static void ghost_bomb_release(Entity_Bomb& bomb, Entity_Player* spawner) +{ + RNG rng = {bomb.initSeed, GHOST_RNG_SHIFTS[0], GHOST_RNG_SHIFTS[1], GHOST_RNG_SHIFTS[2]}; + Entity* ghost; + float scale = bomb.scale * 2; + if (bomb.scale > GHOST_BOMB_BIG_SCALE) + { + float pitch = random_unit() * GHOST_PITCH_RANGE + GHOST_PITCH_MIN; + effect_sound_play(SOUND_FLOATY_BABY_ROAR, {.volume = GHOST_VOLUME, .pitch = pitch}); + ghost = g_game->Spawn({.position = bomb.pos, .spawner = spawner, .subType = 1, .type = ENTITY_EFFECT, + .variant = EFFECT_HUNGRY_SOUL, .seed = rng.Next()}); + static_cast(ghost)->SetTimeout(bomb.isFetus ? GHOST_FETUS_FRAMES : GHOST_FRAMES); + ghost->SetCollisionDamage(ghost->collisionDamage * bomb.scale); + ghost->SetSize(ghost->size * bomb.scale, vector_make(-1, -1), -1); + scale = bomb.scale; + } + else + { + ghost = g_game->Spawn({.position = bomb.pos, .spawner = spawner, .subType = 1, .type = ENTITY_EFFECT, + .variant = EFFECT_PURGATORY, .seed = rng.Next()}); + if (const AnimationData* data = ghost->sprite.animState.animData) ghost->sprite.animState.AdvancePosition(data->length - 1); + } + ghost->sprite.scale = vector_make(scale, scale); + ghost->Update(); +} + // The sound a bomb lands with. struct LandSound { @@ -358,22 +538,22 @@ void Entity_Bomb::Update() pulse_update(spawner); float shownAngle = fetus_flight_update(); - flag_check(*this, TEAR_BURN, "Entity_Bomb::Update 006a24d0: Hot Bombs' burn"); + if (tearFlags[TEAR_BURN]) hot_bomb_burn(*this); flag_check(*this, TEAR_OCCULT, "Entity_Bomb::Update 006a24d0: the Occult's steering"); if (IsRocket()) rocket_thrust_update(); Entity::Update(); if (IsRocket() && tearFlags[TEAR_BOOMERANG] && parent) rocket_boomerang_update(); if (spawnerType == ENTITY_PLAYER) { - flag_check(*this, TEAR_HOMING, "Entity_Bomb::Update 006a24d0: Bobby-Bomb's homing"); - flag_check(*this, TEAR_CREEP_TRAIL, "Entity_Bomb::Update 006a24d0: Bob's Bladder's creep"); + if (tearFlags[TEAR_HOMING]) bobby_bomb_home(*this); + if (!isDead && tearFlags[TEAR_CREEP_TRAIL] && IsFrame(BLADDER_PERIOD, 0)) bladder_creep_drop(*this); } if (!IsRocket() && (posOffset.y >= 0 || !isFetus)) { velocity = vector_scale(velocity, SLIDE_FRICTION); if (vector_length_squared(velocity) < 1) velocity = vector_scale(velocity, SLIDE_STOP); } - flag_check(*this, TEAR_STICKY, "Entity_Bomb::Update 006a24d0: Sticky Bombs' hold"); + if (tearFlags[TEAR_STICKY] && stickyTarget) stickyTarget->velocity = vector_scale(stickyTarget->velocity, STICKY_HOLD); if (fuse_update(spawner)) late_update(shownAngle); } @@ -428,8 +608,8 @@ void Entity_Bomb::explode(Entity_Player* spawner) .damageFlags = isFetus ? DAMAGE_EXPLOSION : DAMAGE_EXPLOSION | DAMAGE_IGNORE_ARMOR, .damage = explosionDamage, .radiusMultiplier = radiusMultiplier}); - flag_check(*this, TEAR_SCATTER_BOMB, "Entity_Bomb::Update 006a24d0: Scatter Bombs' bomblets"); - flag_check(*this, TEAR_GHOST_BOMB, "Entity_Bomb::Update 006a24d0: Ghost Bombs' ghost"); + if (tearFlags[TEAR_SCATTER_BOMB]) scatter_bomblets_throw(*this, spawner); + if (tearFlags[TEAR_GHOST_BOMB]) ghost_bomb_release(*this, spawner); isDead = true; if (pitfallState == 0) sprite.Play("Explode"); @@ -439,7 +619,7 @@ void Entity_Bomb::explode(Entity_Player* spawner) flag_check(*this, TEAR_SPLIT, "Entity_Bomb::Update 006a24d0: Dr. Fetus' split bombs"); flag_check(*this, TEAR_QUADSPLIT, "Entity_Bomb::Update 006a24d0: Dr. Fetus' quad split bombs"); } - else flag_check(*this, TEAR_STICKY, "Entity_Bomb::Update 006a24d0: Sticky Bombs' spiders"); + else if (tearFlags[TEAR_STICKY] && stickyTarget) stickyTarget->AddEntityFlags(FLAG_SPAWN_STICKY_SPIDERS); if (!isFetus && variant != BOMB_THROWABLE && spawner && spawner->HasTrinket(TRINKET_BLASTING_CAP)) { RNG& rng = spawner->GetTrinketRNG(TRINKET_BLASTING_CAP); diff --git a/src/entity_combat.cpp b/src/entity_combat.cpp index 9c14d4d..250840a 100644 --- a/src/entity_combat.cpp +++ b/src/entity_combat.cpp @@ -1,4 +1,5 @@ #include "entity_combat.h" +#include "boss_ai.h" #include "entity_bomb.h" #include "entity_config.h" #include "entity_effect.h" @@ -81,7 +82,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_BISHOP_HIT = 501; constexpr int SOUND_CHAIN_BREAK = 504; constexpr int BISHOP_HIT_DELAY = 10; constexpr float SOUND_LARGE_VOLUME = 1.25f; @@ -226,16 +226,16 @@ static bool is_static_obstacle(Entity& entity) STATIC_OBSTACLE_TYPES.end(); } -// 004e7d10 The Bishop nearest a position whose charm matches, in the room's update order. A frozen one does not count, -// a confused, feared or shrunk one half the time. +// 004e7d10 (find_nearest_enemy) The Bishop nearest a position whose charm matches, among the queryable ones in the +// room's update order. A frozen one does not count, a confused, feared or shrunk one half the time. Entity* bishop_nearest_find(const Vector& position, bool isCharmed) { Entity* nearest = nullptr; float nearestDistance = 1e6f; - for (Entity* entity : g_game->room->entityList.updateEL) + for (Entity* entity : entity_query(ENTITY_BISHOP, -1)) { - if (entity->type != ENTITY_BISHOP || entity->HasEntityFlags(FLAG_FREEZE)) continue; + if (entity->HasEntityFlags(FLAG_FREEZE)) continue; bool isDistracted = entity->HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK); if ((isDistracted && (Random() & 1)) || entity->HasEntityFlags(FLAG_CHARM) != isCharmed) continue; diff --git a/src/entity_config.cpp b/src/entity_config.cpp index 91653f7..d34080b 100644 --- a/src/entity_config.cpp +++ b/src/entity_config.cpp @@ -1,6 +1,7 @@ #include "entity_config.h" #include "data.h" #include "entity.h" +#include "entity_player.h" #include "manager.h" #include "texture_cache.h" #include @@ -15,7 +16,6 @@ constexpr char STRING_KEY_PREFIX = '#'; constexpr float SHADOW_SIZE_SCALE = 100; // Eden, whose children list the hairstyles it rolls, and the point boss portrait pivots are measured back from. -constexpr int PLAYER_EDEN = 9; constexpr float BOSS_PORTRAIT_ORIGIN_X = 96; constexpr float BOSS_PORTRAIT_ORIGIN_Y = 132; diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index 4537fee..bbdf0a5 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -164,6 +164,13 @@ TearFlags effect_tear_flags(const Entity_Effect& effect) return flags; } +void effect_tear_flags_set(Entity_Effect& effect, const TearFlags& flags) +{ + effect.varData = {}; + for (size_t bit = 0; bit < flags.size(); bit++) + if (flags[bit]) effect.varData[bit / 32] |= 1u << (bit % 32); +} + // BlendMode::SetMode on a layer. static void layer_blend_set(LayerState& layer, KAGE::Graphics::BlendType type) { diff --git a/src/entity_effect.h b/src/entity_effect.h index a678224..96f658a 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -50,6 +50,27 @@ constexpr int PULLING_PURPLE = 0; constexpr int PULLING_GREY = 1; constexpr int PULLING_RED = 2; +// A blood explosion's subtypes the shots and bosses splash with: a burst, a splash and a big splash. +constexpr int BLOOD_EXPLOSION_BURST = 2; +constexpr int BLOOD_EXPLOSION_SPLASH = 3; +constexpr int BLOOD_EXPLOSION_SPLASH_BIG = 4; + +// Poof02's lava splashes, small and large. +constexpr int POOF02_LAVA_SPLASH = 66; +constexpr int POOF02_LAVA_SPLASH_LARGE = 67; + +// The halos' subtypes several files spawn (EFFECT_HALO). +enum HaloSubtype +{ + HALO_CURSE = 3, + HALO_STATIC = 4, + HALO_TELEKINESIS = 1, + HALO_SALVATION = 6, + HALO_STATIC_PRERENDERED = 7, + HALO_DARK_ARTS = 8, + HALO_BREATH_OF_LIFE = 9 +}; + // The effect variants several files name (Lua's EffectVariant). enum EffectVariant : int { @@ -139,6 +160,7 @@ enum EffectVariant : int EFFECT_PLAYER_CREEP_BLACKPOWDER = 92, EFFECT_PENTAGRAM_BLACKPOWDER = 93, EFFECT_CREEP_SLIPPERY_BROWN = 94, + EFFECT_GOLD_PARTICLE = 95, EFFECT_HUSH_LASER = 96, EFFECT_WATER_SPLASH = 99, EFFECT_HUSH_ASHES = 100, @@ -369,8 +391,20 @@ void effect_sound_play(int sound, SoundPlay play = {}); // carrying their twin. bool is_player_free(Entity_Player& player); -// The tear flags an effect carries in its variant data. +// The tear flags an effect carries in its variant data, and laying them there. TearFlags effect_tear_flags(const Entity_Effect& effect); +void effect_tear_flags_set(Entity_Effect& effect, const TearFlags& flags); + +// A chain lightning to start (spawn_chain_lightning's arguments): where, its damage and tear flags, from whom. +struct ChainLightning +{ + TearFlags tearFlags{}; + Vector position{}; + Entity* spawner = nullptr; + float damage = 0; +}; + +Entity_Effect* chain_lightning_spawn(const ChainLightning& chain); // FUN_0060dae0: whether the Siren may charm a familiar. struct Entity_Familiar; diff --git a/src/entity_effect_blast.cpp b/src/entity_effect_blast.cpp index 5c0b321..b5e1205 100644 --- a/src/entity_effect_blast.cpp +++ b/src/entity_effect_blast.cpp @@ -375,7 +375,7 @@ static void mega_blast_update(Entity_Effect& blast) float tickDamage = std::max(blast.collisionDamage / share, 1.0f); float reachSquared = blast.scale * blast.scale; - for (Entity* entity : g_game->room->entityList.updateEL) + for (Entity* entity : entities_live(g_game->room->entityList.updateEL)) { if (entity == blast.spawnerEntity.get()) continue; if (vector_length_squared(vector_sub(entity->pos, blast.targetPosition)) <= reachSquared) diff --git a/src/entity_effect_combat.cpp b/src/entity_effect_combat.cpp index d2657ad..636d96a 100644 --- a/src/entity_effect_combat.cpp +++ b/src/entity_effect_combat.cpp @@ -115,7 +115,7 @@ enum ParticleState : int // whether it shows the alternate rubble and bounces. Subtype 1 makes the other particles bounce, mostly. constexpr int ROCK_PARTICLE_BACKDROP_MASK = 0xffff; constexpr int ROCK_PARTICLE_ALT = 0x10000; -constexpr int ROCK_PARTICLE_BOUNCY = 0x20000; + constexpr int PARTICLE_BOUNCY = 1; constexpr int PARTICLE_STILL_ODDS = 40; @@ -193,8 +193,6 @@ constexpr float RIPPLE_SMALL_GROWTH = 1.33333f; constexpr int POOF_RENDER_Z = 8000; constexpr int POOF01_GFUEL = 11; constexpr int POOF01_REPEATING = 100; -constexpr int POOF02_LAVA_SPLASH = 66; -constexpr int POOF02_LAVA_SPLASH_LARGE = 67; constexpr uint32_t LAVA_SPLASH_SHIFT = 4; constexpr int GFUEL_SHAKE = 40; constexpr float GFUEL_PITCH_MIN = 0.9f; diff --git a/src/entity_effect_combat.h b/src/entity_effect_combat.h index a1fd2f7..84cb17d 100644 --- a/src/entity_effect_combat.h +++ b/src/entity_effect_combat.h @@ -6,6 +6,9 @@ // splashes, and the poofs pickups and items leave. Entity_Effect's Init and Update hand these variants here. // Render draws them all with its shared draw. +// A rock particle subtype bit that makes it bounce along the floor. +constexpr int ROCK_PARTICLE_BOUNCY = 0x20000; + // Game::SpawnParticles' height that leaves the particles their own. constexpr float PARTICLE_HEIGHT_KEPT = 100000; diff --git a/src/entity_effect_items.cpp b/src/entity_effect_items.cpp index 283edd0..c2b1cc0 100644 --- a/src/entity_effect_items.cpp +++ b/src/entity_effect_items.cpp @@ -1288,16 +1288,6 @@ static void redemption_update(Entity_Effect& sign) // prerendered, 8 Dark Arts, 9 Breath of Life) follow what they belong to, under it. The static ones touch what is near // for nothing every frame, Telekinesis' pushes enemies within 80 away on its Push event, Salvation's grows with its // scale. -enum HaloSubtype -{ - HALO_CURSE = 3, - HALO_STATIC = 4, - HALO_TELEKINESIS = 1, - HALO_SALVATION = 6, - HALO_STATIC_PRERENDERED = 7, - HALO_DARK_ARTS = 8, - HALO_BREATH_OF_LIFE = 9 -}; constexpr int HALO_RENDER_Z = -1000; constexpr unsigned int HALO_PRERENDERED_FLAG = 1u << 8; constexpr float HALO_PUSH_RANGE = 80; diff --git a/src/entity_effect_mother.cpp b/src/entity_effect_mother.cpp index c70653c..f191348 100644 --- a/src/entity_effect_mother.cpp +++ b/src/entity_effect_mother.cpp @@ -36,7 +36,6 @@ constexpr float MOTHER_TRACER_SHOT_SCALE_MIN = 0.4f; constexpr float MOTHER_TRACER_SHOT_SCALE_SPAN = 0.7f; constexpr float MOTHER_TRACER_SHOT_ACCEL = -0.007f; constexpr float MOTHER_TRACER_ROOM_MARGIN = -80; -constexpr ColorMod FIERY_SHOT_COLOR = {{1, 1, 1, 1}, {3.5f, 2.5f, 1, 1}, {0, 0, 0}}; constexpr std::array MOTHER_TRACER_MOVES = {"MoveLeft", "MoveUp", "MoveRight", "MoveDown"}; // Mother's tracer's states: just spawned, fading in, pulsing, rushing. @@ -93,7 +92,7 @@ static void mother_tracer_shot(Entity_Effect& tracer) .type = ENTITY_PROJECTILE, .seed = seed})); shot->parent = tracer.parent; - shot->SetColor(FIERY_SHOT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + shot->SetColor(SHOT_COLOR_FIERY, -1, COLOR_PRIORITY_DEFAULT, false, true); shot->scale = random_unit() * MOTHER_TRACER_SHOT_SCALE_SPAN + MOTHER_TRACER_SHOT_SCALE_MIN; shot->fallingAccel = MOTHER_TRACER_SHOT_ACCEL; shot->fallingSpeed = random_unit() * -1; @@ -326,7 +325,6 @@ constexpr int KNIFE_PRIORITY = 255; constexpr uint64_t KNIFE_SHOT_FLAGS = PROJECTILE_HIT_ENEMIES | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT | PROJECTILE_ACCELERATE_EX; constexpr uint64_t KNIFE_SHOT_CHANGED_FLAGS = PROJECTILE_HIT_ENEMIES | PROJECTILE_DECELERATE; -constexpr ColorMod KNIFE_SHOT_COLOR = color_make({1, 1, 1, 1}, {1.5f, 2, 1, 1}); // The wall burst: rubble and gore within 5 thrown back within 45 degrees, then nine fans of shots across 160. constexpr float KNIFE_WALL_PROBE = 30; @@ -348,7 +346,6 @@ constexpr float KNIFE_FAN_SPEED_MIN = 5; constexpr float KNIFE_FAN_SPEED_MAX = 20; constexpr float KNIFE_FAN_FALL = -0.08f; constexpr float KNIFE_FADE = 0.1f; -constexpr ColorMod KNIFE_FAN_COLOR = color_make({1, 1, 1, 1}, {2.7f, 3, 2, 1}); // A shot the knife throws for its spawner. static Entity_Projectile* knife_shot_spawn(Entity_Effect& knife, Vector position, Vector velocity, uint32_t seed) @@ -435,7 +432,7 @@ static void knife_trail_step(Entity_Effect& knife, Vector at, Vector direction) shot->acceleration = KNIFE_SHOT_ACCELERATION; shot->changeFlags = KNIFE_SHOT_CHANGED_FLAGS; shot->changeTimeout = KNIFE_SHOT_CHANGE_FRAMES; - knife_shot_finish(*shot, KNIFE_SHOT_FALL, KNIFE_SHOT_COLOR); + knife_shot_finish(*shot, KNIFE_SHOT_FALL, SHOT_COLOR_SICK); } damage_radius({.position = knife.pos, .source = knife.spawnerEntity, @@ -491,7 +488,7 @@ static void knife_wall_burst(Entity_Effect& knife, Room& room) float speed = std::lerp(KNIFE_FAN_SPEED_MIN, KNIFE_FAN_SPEED_MAX, random_unit()); Entity_Projectile* shot = knife_shot_spawn(knife, at, vector_scale(direction, speed), shotSeed); shot->projectileFlags = PROJECTILE_HIT_ENEMIES; - knife_shot_finish(*shot, KNIFE_FAN_FALL, KNIFE_FAN_COLOR); + knife_shot_finish(*shot, KNIFE_FAN_FALL, SHOT_COLOR_SICK_PALE); } } } diff --git a/src/entity_effect_shots.cpp b/src/entity_effect_shots.cpp index 4206549..c962237 100644 --- a/src/entity_effect_shots.cpp +++ b/src/entity_effect_shots.cpp @@ -527,6 +527,12 @@ static void shield_update(Entity_Effect& shield) // rehit) 100 farther. In water, enemies on the ground are 200 farther in reach and count as much nearer. Each jump // fires a thin spectral laser along it carrying its status tear flags, and its first one fires even with no enemy. constexpr float CHAIN_LIGHTNING_REACH = 130; +constexpr float CHAIN_REACH_9_VOLT = 185; +constexpr float CHAIN_REACH_TRINKET = 20; +constexpr int CHAIN_JUMPS = 4; +constexpr int CHAIN_JUMPS_BATTERY = 6; +constexpr int CHAIN_JUMPS_EXTRA = 2; +constexpr float CHAIN_CAR_BATTERY = 1.5f; constexpr float CHAIN_BASE_DAMAGE = 3.5f; constexpr float CHAIN_WET = 0.1f; constexpr float CHAIN_WET_REACH = 200; @@ -657,6 +663,46 @@ static void chain_lightning_update(Entity_Effect& chain) if (chain.maxRadius <= 0) chain.Remove(); } +// 00707e10 (spawn_chain_lightning) Starts a chain lightning (Jacob's Ladder, 120 Volt) at a position. A player's reaches +// farther with 9 Volt, the Watch Battery and the Hairpin, jumps more often with The Battery, Jumper Cables, Charged +// Baby and the AAA Battery, hits harder with Car Battery and Sharp Plug, and may hit an enemy again with the Battery +// Pack or the Old Capacitor. +Entity_Effect* chain_lightning_spawn(const ChainLightning& chain) +{ + float reach = CHAIN_LIGHTNING_REACH; + float multiplier = 1; + int jumps = CHAIN_JUMPS; + bool isRehitting = false; + Entity* owner = chain.spawner ? chain.spawner->GetLastSpawner() : nullptr; + if (owner && owner->type == ENTITY_PLAYER) + { + Entity_Player& player = *owner->ToPlayer(); + if (player.HasCollectible(COLLECTIBLE_9_VOLT)) reach = CHAIN_REACH_9_VOLT; + if (player.HasCollectible(COLLECTIBLE_BATTERY)) jumps = CHAIN_JUMPS_BATTERY; + if (player.HasCollectible(COLLECTIBLE_JUMPER_CABLES)) jumps += CHAIN_JUMPS_EXTRA; + if (player.HasCollectible(COLLECTIBLE_CHARGED_BABY)) jumps += CHAIN_JUMPS_EXTRA; + isRehitting = player.HasCollectible(COLLECTIBLE_BATTERY_PACK); + if (player.HasCollectible(COLLECTIBLE_CAR_BATTERY)) multiplier = CHAIN_CAR_BATTERY; + if (player.HasCollectible(COLLECTIBLE_SHARP_PLUG)) multiplier += HALF; + if (player.HasTrinket(TRINKET_AAA_BATTERY)) jumps++; + if (player.HasTrinket(TRINKET_WATCH_BATTERY)) reach += CHAIN_REACH_TRINKET; + if (player.HasTrinket(TRINKET_HAIRPIN)) reach += CHAIN_REACH_TRINKET; + if (player.HasTrinket(TRINKET_OLD_CAPACITOR)) isRehitting = true; + } + + auto* lightning = static_cast(g_game->Spawn({.position = chain.position, .spawner = chain.spawner, + .type = ENTITY_EFFECT, .variant = EFFECT_CHAIN_LIGHTNING, + .seed = Random()})); + lightning->SetCollisionDamage(multiplier * chain.damage); + lightning->minRadius = reach; + lightning->maxRadius = (float)jumps; + if (isRehitting) lightning->AddEntityFlags(FLAG_SPAWN_STICKY_SPIDERS); + lightning->baseDamage = lightning->collisionDamage; + lightning->baseScale = 1; + effect_tear_flags_set(*lightning, chain.tearFlags); + return lightning; +} + constexpr auto SHOT_EFFECT_BEHAVIOURS = std::to_array({ {EFFECT_EVIL_EYE, nullptr, effect_finishing, nullptr}, {EFFECT_BRIMSTONE_SWIRL, swirl_init, effect_finishing, nullptr}, diff --git a/src/entity_effect_vortex.cpp b/src/entity_effect_vortex.cpp index cb0929f..0872795 100644 --- a/src/entity_effect_vortex.cpp +++ b/src/entity_effect_vortex.cpp @@ -263,7 +263,7 @@ static void black_hole_update(Entity_Effect& hole) float scale = std::sin((float)g_game->frameCount * BLACK_HOLE_PULSE_SPEED) * BLACK_HOLE_PULSE + BLACK_HOLE_SCALE; hole.sprite.scale = vector_make(scale, scale); black_hole_spin(hole); - for (Entity* entity : g_game->room->entityList.updateEL) black_hole_pull(hole, *entity); + for (Entity* entity : entities_live(g_game->room->entityList.updateEL)) black_hole_pull(hole, *entity); black_hole_rocks_break(hole); } @@ -382,7 +382,7 @@ static void rift_update(Entity_Effect& rift) float reach = rift.sprite.scale.x * RIFT_REACH; float strength = std::min(rift.sprite.scale.x, 1.0f); - for (Entity* entity : g_game->room->entityList.updateEL) + for (Entity* entity : entities_live(g_game->room->entityList.updateEL)) { if (!is_rift_pulled(*entity, player) || entity == &rift) continue; if (vector_is_zero(vector_sub(entity->pos, rift.pos)) || entity->friction == 0) continue; diff --git a/src/entity_factory.cpp b/src/entity_factory.cpp index ed1202e..101985a 100644 --- a/src/entity_factory.cpp +++ b/src/entity_factory.cpp @@ -24,7 +24,6 @@ #include #include -constexpr uint64_t NS_PER_MS = 1000000; // The seed of a pedestal's Flip item comes from its own with this shift. constexpr uint32_t FLIP_SEED_SHIFT_INDEX = 39; @@ -36,16 +35,12 @@ constexpr int SPAWN_STATUS_FRAMES = 90; constexpr int ENTITY_HORF = 12; constexpr int ENTITY_FLAMINGHOPPER = 54; constexpr int ENTITY_WALKINGBOIL = 88; -constexpr int ENTITY_GREED_GAPER = 299; constexpr int ENTITY_MUSHROOM = 300; constexpr int ENTITY_SUB_HORF = 812; constexpr int EFFECT_CRAWLSPACE_LADDER = 192; -constexpr int CARD_SPECIAL_CHANCE = 25; -constexpr int CARD_RUNE_CHANCE = 10; constexpr int PICKUP_RANDOM_CARD = 301; -constexpr int SLOT_DONATION = 8; constexpr int SLOT_CLOSET_TAINTED = 14; constexpr int SHOPKEEPER_SPECIAL = 3; constexpr int SHOPKEEPER_SECRET_SPECIAL = 4; @@ -106,7 +101,6 @@ enum EntryType : int ENTRY_QUEST_DOOR = 970 }; -// The poop variants a layout's poop can turn into (Lua's PoopVariant). // The achievements a layout entry waits for. enum EntryAchievement : int { @@ -125,7 +119,6 @@ enum EntryAchievement : int ACHIEVEMENT_HEART_BONE = 391, ACHIEVEMENT_HEART_ROTTEN = 411, ACHIEVEMENT_TAINTED_CLOSET = 434, - ACHIEVEMENT_MEGA_CHEST = 601, ACHIEVEMENT_GRAB_BAG_BLACK = 604, ACHIEVEMENT_POOP_CHARMING = 605, ACHIEVEMENT_CRANE_GAME = 607, @@ -1071,7 +1064,7 @@ bool room_entry_spawn(Room& room, RoomEntry entry, const RoomEntrySpawn& spawn) } if (room.roomType == ROOM_SHOP && room.descriptor->gridIndex < 0 && entry.type == ENTITY_SLOT) - return entry.variant != SLOT_DONATION && entity_entry_spawn(room, entry, spawn, rng); + return entry.variant != SLOT_DONATION_MACHINE && entity_entry_spawn(room, entry, spawn, rng); if (entry_is_plain_rock(room, entry.type, gridIndex) && room.roomType != ROOM_DUNGEON) { diff --git a/src/entity_familiar.cpp b/src/entity_familiar.cpp index 1abcef5..b1cf036 100644 --- a/src/entity_familiar.cpp +++ b/src/entity_familiar.cpp @@ -39,7 +39,7 @@ 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[] = {62, 122, 228, 233, 236, 238}; +constexpr int UNWRITTEN_INIT_VARIANTS[] = {228, 236}; // 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}; @@ -500,6 +500,10 @@ void Entity_Familiar::variant_init(int initSubtype) sprite.Play(LEPROSY_ANIMS[subtype]); break; case BONE_ORBITAL: bone_orbital_init(*this); break; + case LIL_HARBINGERS: + subtype = (int)dropRNG.RandomInt(HARBINGER_KINDS); + init_lil_harbinger_sprite(); + break; case MY_SHADOW: my_shadow_init(*this); break; @@ -534,6 +538,8 @@ void Entity_Familiar::variant_finish() break; case BLOOD_PUPPY: state = 0; break; case UMBILICAL_BABY: umbilical_baby_init(*this); break; + case BLOOD_BABY: blood_clot_init(*this); break; + case WORM_FRIEND: worm_friend_init(*this); break; } if ((variant == CENSER || variant == SUCCUBUS) && sprite.layerStates.size() > 1) sprite.GetLayer(1)->bitflags = 1; } @@ -936,8 +942,23 @@ void Entity_Familiar::variant_update() case TINYTOMA: case TINYTOMA_2: return tinytoma_update(*this); case BOT_FLY: return bot_fly_update(*this); + case PSY_FLY: return psy_fly_update(*this); + case BIRD_CAGE: return ai_bird_cage(); + case WORM_FRIEND: return worm_friend_update(*this); + case DECAP_ATTACK: return decap_head_update(*this); case LIL_DUMPY: return lil_dumpy_update(*this); case BOILED_BABY: return boiled_baby_update(*this); + case BLOOD_BABY: return ai_blood_clot(false); + case ISAACS_HEART: return isaacs_heart_update(*this); + case YO_LISTEN: return ai_variant_111(); + case GB_BUG: return gb_bug_update(*this); + case ROBO_BABY_2: return robo_baby_2_update(*this); + case SWORN_PROTECTOR: return sworn_protector_update(*this); + case LIL_GURDY: return ai_lil_gurdy(); + case LIL_HARBINGERS: return ai_lil_harbingers(); + case BUMBO: return bumbo_update(*this); + case DAMOCLES: return ai_shadow_intruder_damocles(false); + case VANISHING_TWIN: return vanishing_twin_update(*this); case FRUITY_PLUM: return fruity_plum_update(*this); default: reconstruction_missing("Entity_Familiar::Update 0061da10 (this familiar's behaviour)"); @@ -1005,8 +1026,8 @@ void Entity_Familiar::update_tail() // Lil Brimstone charges, Gello moves on, and the other variants that act on interpolation stop the game. void Entity_Familiar::Interpolate() { - if (variant == DAMOCLES || variant == BLOOD_BABY) - reconstruction_missing("Entity_Familiar::Interpolate 00624a80 (this familiar's interpolation)"); + if (variant == DAMOCLES) ai_shadow_intruder_damocles(true); + if (variant == BLOOD_BABY) return blood_clot_interpolate(*this); if (variant == LIL_BRIMSTONE) ai_incubus_shot(); if (variant == INCUBUS) update_weapon(true); if (variant == UMBILICAL_BABY) ai_umbilical_baby(true); diff --git a/src/entity_familiar.h b/src/entity_familiar.h index 81ac4a1..176f290 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -59,6 +59,22 @@ constexpr std::array WISP_RING_CAPACITY = {6, 8, 12}; constexpr int LEMEGETON_VIRTUES_WISP = 0x10012; constexpr int WISP_PRIORITY_NONE = 9999; +// The kind of clot (Lua's ClotSubType): the heart Sumptorium turned into it, or Lil Clot's. +enum ClotKind : int +{ + CLOT_RED, + CLOT_SOUL, + CLOT_BLACK, + CLOT_ETERNAL, + CLOT_GOLD, + CLOT_BONE, + CLOT_ROTTEN, + CLOT_LIL +}; + +// How many kinds of Lil Harbinger there are. +constexpr int HARBINGER_KINDS = 5; + // The formation slot of a familiar outside any. constexpr uint8_t FORMATION_NONE = 0xff; @@ -515,6 +531,7 @@ void isaacs_body_init(Entity_Familiar& body); void isaacs_body_update(Entity_Familiar& body); bool isaacs_body_render(Entity_Familiar& body, const Vector& offset); void detached_head_update(Entity_Familiar& head); +void decap_head_update(Entity_Familiar& head); void detached_head_render(Entity_Familiar& head, const Vector& offset); // The variant behaviours of Update written as their own functions (familiar_update.cpp). @@ -545,8 +562,25 @@ void tinytoma_update(Entity_Familiar& tinytoma); bool tinytoma_touch(Entity_Familiar& tinytoma, Entity& enemy, float damageMultiplier); bool tinytoma_death(Entity_Familiar& tinytoma); void bot_fly_update(Entity_Familiar& fly); +void psy_fly_update(Entity_Familiar& fly); +bool psy_fly_touch(Entity_Familiar& fly, Entity& collider); +void worm_friend_init(Entity_Familiar& worm); +void worm_friend_update(Entity_Familiar& worm); +void vanishing_twin_update(Entity_Familiar& twin); void lil_dumpy_update(Entity_Familiar& dumpy); +// The Rebirth and Afterbirth familiars written as their own functions (familiar_afterbirth.cpp). +void isaacs_heart_update(Entity_Familiar& heart); +void gb_bug_update(Entity_Familiar& bug); +void robo_baby_2_update(Entity_Familiar& robo); +void sworn_protector_update(Entity_Familiar& protector); +void lil_gurdy_bounce(Entity_Familiar& gurdy, Entity& enemy); + +// Sumptorium's and Lil Clot's clots (familiar_clot.cpp). +void blood_clot_init(Entity_Familiar& clot); +void blood_clot_interpolate(Entity_Familiar& clot); +void blood_clot_death(Entity_Familiar& clot); + // The Abyss locusts (familiar_locust.cpp). struct LocustConfig; LocustConfig& familiar_locust_config(Entity_Familiar& familiar); @@ -570,5 +604,6 @@ void familiar_check(Entity_Player& player, const FamiliarCount& familiars); void familiars_evaluate(Entity_Player& player); int familiar_lullaby_delay(Entity_Familiar& familiar, int fireDelay); bool bum_pickup_collect(Entity_Familiar& bum, Entity_Pickup& pickup); +void bumbo_update(Entity_Familiar& bumbo); void blue_spider_update(Entity_Familiar& spider); Entity_Familiar* spawn_blue_spider(const Vector& position, Entity* spawner, Vector target); diff --git a/src/entity_knife.cpp b/src/entity_knife.cpp index 124bb39..7716522 100644 --- a/src/entity_knife.cpp +++ b/src/entity_knife.cpp @@ -250,7 +250,8 @@ static Vector knife_path_point(const BezierPoint& start, const BezierPoint& end, b0 * start.point.y + b1 * start.handleOut.y + b2 * end.handleIn.y + b3 * end.point.y); } -// Whether the knife's holder still has the weapon the knife belongs to. Abyss's knife locust is not reconstructed yet. +// Whether the knife's holder still has the weapon the knife belongs to: Abyss's knife locust while it holds its +// blade, another familiar while its player has the weapon. static bool is_owner_armed(Entity* owner, WeaponType weaponType) { if (owner->is_player()) return owner->ToPlayer()->HasWeaponType(weaponType); @@ -258,7 +259,10 @@ static bool is_owner_armed(Entity* owner, WeaponType weaponType) Entity_Familiar& familiar = *static_cast(owner); if (familiar.variant == Entity_Familiar::ABYSS_LOCUST && weaponType == WEAPON_KNIFE) - reconstruction_missing("Entity_Knife::Update 00961b00 (Abyss's knife locust)"); + { + auto* locust = dynamic_cast(familiar.extraData.get()); + if (locust && locust->knife) return true; + } return familiar.player && familiar.player->HasWeaponType(weaponType); } diff --git a/src/entity_knife_hits.cpp b/src/entity_knife_hits.cpp index 7c44d5f..d806808 100644 --- a/src/entity_knife_hits.cpp +++ b/src/entity_knife_hits.cpp @@ -1,6 +1,7 @@ #include "boss_ai.h" #include "capsule.h" #include "entity_bomb.h" +#include "entity_effect.h" #include "entity_effect_combat.h" #include "entity_familiar.h" #include "entity_knife.h" @@ -853,7 +854,7 @@ void Entity_Knife::UpdateSwingHits() // 0096ae70 What a knife's hit sets off: a held club's Ipecac blast, Haemolacria's burst or the Parasite's four shards; // a thrown knife's Cricket's Body split (once a throw) or Ipecac blast (once a throw, bigger with the charge). Mom's -// Knife (and the scythe) set off the rest only one hit in four: Cricket's Body's and Compound Fracture's bone shards, +// Knife (and the scythe) set off the rest only one hit in four: Cricket's Body's and Compound Fracture's bone shards, Jacob's Ladder, // Rift, and Sticky, Booger and Spore tears stuck in a living enemy. void Entity_Knife::apply_hit_effects(const KnifeHit& hit) { @@ -1048,7 +1049,12 @@ void Entity_Knife::apply_hit_effects(const KnifeHit& hit) } if (tearFlags[TEAR_JACOBS]) - reconstruction_missing("Entity_Knife::apply_hit_effects 0096ae70 (Jacob's Ladder, spawn_chain_lightning 00707e10)"); + { + Entity_Effect* chain = chain_lightning_spawn( + {.tearFlags = tearFlags, .position = hitPosition, .spawner = spawnerEntity, .damage = hit.damage * HALF}); + chain->hitList = hitList; + chain->Update(); + } if (tearFlags[TEAR_RIFT] && g_game->room->IsPositionInRoom(hitPosition, RIFT_MARGIN)) { diff --git a/src/entity_laser_render.cpp b/src/entity_laser_render.cpp index 43ced35..e72b54d 100644 --- a/src/entity_laser_render.cpp +++ b/src/entity_laser_render.cpp @@ -274,8 +274,7 @@ bool Entity_Laser::RenderShadowLayer(const Vector& offset) // 0097eb50 The debug display of the laser's hit area (debug flag 6) is not reconstructed yet. void Entity_Laser::PostRender() { - constexpr uint32_t DEBUG_HIT_AREA = 1 << 5; - if ((g_game->debugFlags & DEBUG_HIT_AREA) && size > 0 && entityCollisionClass != ENTCOLL_NONE && + if ((g_game->debugFlags & DEBUG_HITSPHERES) && size > 0 && entityCollisionClass != ENTCOLL_NONE && sampleMode != SAMPLE_UNDECIDED) reconstruction_missing("Entity_Laser::PostRender 0097eb50: the hit area's debug lines"); } diff --git a/src/entity_list.cpp b/src/entity_list.cpp index 204c297..6656c18 100644 --- a/src/entity_list.cpp +++ b/src/entity_list.cpp @@ -646,7 +646,7 @@ void EntityList::rebuild_sublists() partitions[PARTITION_ENEMY_TARGETS].collide(enemies); twins_push_apart(); - for (Entity* entity : updateEL) + for (Entity* entity : entities_live(updateEL)) { if (entity->type == ENTITY_LASER) continue; if (entity->type == ENTITY_PLAYER) entity->PlayerCollideWithGrid(GRID_COLLISION_APPLY); diff --git a/src/entity_list.h b/src/entity_list.h index 517fc7f..1bc3290 100644 --- a/src/entity_list.h +++ b/src/entity_list.h @@ -56,6 +56,36 @@ struct EntityList_EL : std::vector Entity* Get(uint32_t index); }; +// A list walked by index with its size read at every step, as the original's loops walk its arrays: what a step +// spawns (appended to the list) is visited too, and a list that grows or empties under the walk cannot break it. +// Loops whose bodies can spawn walk the update list this way. +struct EntitiesLive +{ + struct Step + { + const std::vector* list = nullptr; + size_t index = 0; + + Entity* operator*() const { return (*list)[index]; } + Step& operator++() + { + index++; + return *this; + } + bool operator!=(const Step&) const { return index < list->size(); } + }; + + const std::vector& list; + + Step begin() const { return {&list, 0}; } + Step end() const { return {&list, 0}; } +}; + +inline EntitiesLive entities_live(const std::vector& list) +{ + return {list}; +} + struct EntityList; // What one frame's updates counted, which EntityList::Update applies once every update ran. diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index e697bcf..8582e8a 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -1,4 +1,5 @@ #include "entity_npc.h" +#include "boss_repentance.h" #include "active_items.h" #include "boss_ai.h" #include "boss_death.h" @@ -11,6 +12,7 @@ #include "entity_pickup.h" #include "entity_player.h" #include "entity_projectile.h" +#include "entity_text.h" #include "data.h" #include "game.h" #include "grid_entity.h" @@ -43,6 +45,11 @@ constexpr int ENTITY_NO_DECOY_TYPE = 213; constexpr uint32_t DOPLE_PICK_SHIFT = 11; constexpr int ENTITY_UNREACHABLE_EXEMPT = 886; constexpr int ENTITY_DAMAGE_NUMBERS_TYPE = 964; +constexpr float DAMAGE_NUMBER_MAX = 9999; +constexpr float DAMAGE_NUMBER_MIN = 0.1f; +constexpr float DAMAGE_NUMBER_PRECISION = 10; +constexpr float DAMAGE_NUMBER_RISE = 20; +constexpr float DAMAGE_NUMBER_SPEED = -3; // G-Fuel's explosions: past 1.5 the big one, which shakes the screen for 40 frames, else one of two small ones for // 20, their sound pitched 0.9 to 1.1. @@ -94,7 +101,6 @@ constexpr int ENTITY_FORWARD_DOWN_A = 262; constexpr int ENTITY_FORWARD_DOWN_B = 263; constexpr int DEATH_NO_BURST_FIRST = 74; constexpr int DEATH_NO_BURST_LAST = 76; -constexpr int CHALLENGE_KILL_CHARGE = 33; constexpr std::string_view BIG_HORN_SPLASH_EVENT = "Poof"; constexpr std::string_view DIRT_LAYER = "dirt"; constexpr std::string_view HOLE_LAYER = "Hole"; @@ -204,8 +210,6 @@ 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; -constexpr int CHALLENGE_SLOW = 22; constexpr int ACHIEVEMENT_BOSS_COLORS = 3; constexpr int ACHIEVEMENT_MORE_BOSS_COLORS = 33; constexpr int ACHIEVEMENT_REDIRECTS = 348; @@ -213,7 +217,6 @@ constexpr uint32_t ROOM_CONFIG_FLAG_NO_CHAMPIONS = 1 << 2; constexpr int GRID_CELL = 40; constexpr float GRID_TOP = 120; constexpr int SHIELD_FRAMES_DEFAULT = 120; -constexpr uint32_t DEBUG_QUICK_KILL = 1 << 9; constexpr int BOSS_ID_NONE_EXCLUDED_FIRST = 46; constexpr int BOSS_ID_NONE_EXCLUDED_LAST = 52; constexpr int BOSS_ID_EXCLUDED = 38; @@ -732,14 +735,14 @@ void Entity_NPC::boss_color_roll() RoomDescriptor* descriptor = game.room->descriptor; RNG rng = {descriptor ? descriptor->spawnSeed : 0, 1, 11, 16}; if (rng.RandomFloat() < boss_color_chance_get()) subtype = (int)rng.RandomInt(colors) + 1; - if (config->id == ENTITY_MOM && subtype == 2 && game.challenge == CHALLENGE_BEANS) subtype = 0; + if (config->id == ENTITY_MOM && subtype == 2 && game.challenge == CHALLENGE_GUARDIAN) subtype = 0; } if (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B) { if (config->id == ENTITY_MOM) subtype = 3; else if (config->id == ENTITY_MOMS_HEART) subtype = 1; } - if (subtype == 0 || subtype > colors) return; + if (subtype == 0 || (uint32_t)subtype > (uint32_t)colors) return; EntityConfig_BossColor color = config->bossColors[subtype - 1]; bosscoloridx = subtype - 1; @@ -928,6 +931,24 @@ void Entity_NPC::SetBossColorIdx(int bossColorIdx, int) constexpr ColorMod FRIENDLY_COLOR = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, -0.5f}, {0.1f, 0.1f, 0.1f}}; constexpr ColorMod FROZEN_COLOR = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, 0.5f}, {0.3f, 0.5f, 0.8f}}; +// An iced enemy's frozen statue: its weight, health and grid collision points, the cold flash it appears with, the +// mist it trails when shoved (and the creep it leaves now and then), the wall margin it breaks at, and its ten shards. +constexpr float STATUE_HEALTH = 10; +constexpr int STATUE_GRID_POINTS = 8; +constexpr ColorMod STATUE_FLASH = {{0.8f, 0.8f, 0.8f, 1}, {1, 1, 1, 0.5f}, {0.8f, 1, 1.2f}}; +constexpr int STATUE_FLASH_FRAMES = 6; +constexpr float STATUE_TRAIL_SCALE_MIN = 0.2f; +constexpr float STATUE_MIST_DRAG = 0.14f; +constexpr float STATUE_MIST_SPIN_MIN = 2; +constexpr float STATUE_MIST_SPIN_RANGE = 10; +constexpr uint32_t STATUE_MIST_FRAMES = 15; +constexpr ColorMod STATUE_MIST_COLOR = {{1, 1, 1, 0.4f}, {0, 0, 0, 0}, {0.8f, 0.9f, 1}}; +constexpr float STATUE_WALL_MARGIN = 4; +constexpr int STATUE_SHARDS = 10; +constexpr float STATUE_SHARD_SPEED = 16; +constexpr float STATUE_SHARD_DAMAGE = 7; +constexpr float STATUE_SHARD_FALL = 0.2f; + // The enemy a "random enemy" spawn (type 306) turns into on each stage, on Normal and on Hard. struct StageEnemy { @@ -1203,7 +1224,7 @@ void Entity_NPC::status_overlay_update() TemporaryEffects& roomEffects = g_game->room->temporaryEffects; bool isTimeSlowed = roomEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) || roomEffects.HasCollectibleEffect(COLLECTIBLE_HOURGLASS_ID) || - (g_game->challenge != CHALLENGE_SLOW && g_game->room->brokenWatchState == BROKEN_WATCH_SLOW); + (g_game->challenge != CHALLENGE_SPEED && g_game->room->brokenWatchState == BROKEN_WATCH_SLOW); bool isTimeImmune = (flags & (FLAG_FRIENDLY | FLAG_NO_STATUS_EFFECTS)) && type != ENTITY_DEATHS_HEAD; std::string_view animation; @@ -1808,8 +1829,7 @@ void Entity_NPC::Update() hitList.clear(); type_update(); - if (isDead && !isDeadBefore && !IsBoss() && !config->isBoss && HasEntityFlags(FLAG_ICE)) - reconstruction_missing("Entity_NPC::Update 006c4b30: an iced enemy turning into a statue"); + if (isDead && !isDeadBefore && !IsBoss() && !config->isBoss && HasEntityFlags(FLAG_ICE)) ice_statue_make(); if (!isDead && state != NPC_STATE_DEATH) { ClearEntityFlags(FLAG_EXTRA_GORE); @@ -1877,7 +1897,7 @@ float Entity_NPC::compute_speed_multiplier() if (!IsFriendly()) { if (room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) || - (g_game->challenge != CHALLENGE_SLOW && room.brokenWatchState == BROKEN_WATCH_SLOW)) + (g_game->challenge != CHALLENGE_SPEED && room.brokenWatchState == BROKEN_WATCH_SLOW)) speed *= SPEED_HALF; else if (TemporaryEffect* hourglass = room.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_HOURGLASS_ID)) speed *= 1 - std::clamp((float)hourglass->cooldown / SLOW_TIMESCALE_EFFECT_FRAMES, 0.0f, 1.0f) * SPEED_HALF; @@ -1925,7 +1945,7 @@ bool Entity_NPC::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& if (attacker && attacker->type != ENTITY_PLAYER) attacker = attacker->spawnerEntity; Entity_Player* player = attacker && attacker->type == ENTITY_PLAYER ? static_cast(attacker) : game_nearest_player(pos); - if (damageFlags & DAMAGE_SPAWN_FLY) reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: the hit's blue fly"); + if (damageFlags & DAMAGE_SPAWN_FLY) player->AddBlueFlies(1, player->pos, this); if (!player->proceduralItems.empty()) reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: the attacker's on-hit procedural items"); return isHurt; @@ -2459,11 +2479,24 @@ void Entity_NPC::spawn_damage_numbers() if (!isShown || !isVisible || sprite.color._tint[3] <= 0 || health <= 0) return; if (GetStatusEffectTarget() != this || isInvincible) return; - auto isDealt = [](const DamageEvent& event) { - return event.damage > 0; - }; - if (std::ranges::any_of(damageEvents, isDealt)) - reconstruction_missing("Entity_NPC::spawn_damage_numbers 006d7010: the damage text"); + for (DamageEvent& event : damageEvents) + { + if (event.damage <= 0) continue; + + EntitySpawn spawn; + spawn.seed = Random(); + spawn.velocity = vector_make(0, DAMAGE_NUMBER_SPEED - random_unit() * 2); + spawn.position = vector_make(pos.x, pos.y - DAMAGE_NUMBER_RISE); + spawn.type = ENTITY_TEXT; + spawn.variant = TEXT_DAMAGE; + + Entity* number = g_game->Spawn(spawn); + float shown = std::min(std::floor(event.damage * DAMAGE_NUMBER_PRECISION + HALF) / DAMAGE_NUMBER_PRECISION, + DAMAGE_NUMBER_MAX); + number->targetPosition = vector_make(shown > 0 ? shown : DAMAGE_NUMBER_MIN, maxHitPoints); + number->parent = this; + number->Update(); + } } // 006d7230 A shielded boss's shield: the damage of its last frames (shieldFrames) averaged per second, and past @@ -2567,7 +2600,7 @@ void Entity_NPC::kill_items_trigger() } } - bool isFriendlyKill = IsFriendly() && g_game->challenge == CHALLENGE_KILL_CHARGE && + bool isFriendlyKill = IsFriendly() && g_game->challenge == CHALLENGE_POKEY_MANS && players.FirstCollectibleOwner(COLLECTIBLE_FRIEND_BALL, LAZARUS_SHARE_CHECK) && (spawnerType == ENTITY_PLAYER || spawnerType == ENTITY_FAMILIAR) && spawnerEntity && spawnerEntity->type == ENTITY_PLAYER; @@ -2637,8 +2670,7 @@ void Entity_NPC::trigger_kill_item_effects() { if (isBoss) g_game->room->TriggerBossDeath(*this); else if (isChampion) champion_drop(); - if (type == ENTITY_ROTGUT && variant == 1) - reconstruction_missing("rotgut_death_spawn_effects 00581200: Rotgut's death"); + if (type == ENTITY_ROTGUT && variant == ROTGUT_MAGGOT) rotgut_death_spawn_effects(*this); if (HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) sticky_spiders_spawn(); if (!HasEntityFlags(FLAG_NO_REWARD)) kill_rewards_spawn(); @@ -2832,22 +2864,12 @@ void Entity_NPC::Hornfel_UpdateFrame() reconstruction_missing("Entity_NPC::Hornfel_UpdateFrame 004bb0e0"); } -// 0059e390 -void Entity_NPC::CreateBling() -{ - reconstruction_missing("Entity_NPC::CreateBling 0059e390"); -} - -// 0059e4c0 -void Entity_NPC::CreateGoldParticles(uint32_t) -{ - reconstruction_missing("Entity_NPC::CreateGoldParticles 0059e4c0"); -} - -// 006be760 +// 006be760 Kills it with no source into its own death animation (Flush! and Lua's KillUnique). void Entity_NPC::KillUnique() { - reconstruction_missing("Entity_NPC::KillUnique 006be760"); + Kill(EntityRef()); + state = NPC_STATE_UNIQUE_DEATH; + stateFrame = 0; } // A thrown spider: a free landing spot within 100 when none is given, a Strider instead over Downpour's and Dross's @@ -2890,10 +2912,108 @@ Entity_NPC* Entity_NPC::ThrowSpider(const Vector& position, Entity* spawner, Vec return spider; } -// 006ca930 +// Part of 006c4b30: an enemy killed while iced does not die. Its killers are rewarded as for a death, then it stands +// as a frozen statue (ENTITY_FROZEN_ENEMY, keeping its type in its state frame): inside the room, heavy, harmless, +// untargetable and alone (every pointer to it dropped), flashing cold. A Blood Puppy's familiar holds on to it. +void Entity_NPC::ice_statue_make() +{ + trigger_death_rewards(); + for (Entity_Player* player : g_game->playerManager.playerList) player->trigger_npc_death(this); + toxic_shock_creep_spawn(); + for (EntityPtr* referrer : referrers) referrer->forget(); + referrers.clear(); + + sprite.Stop(); + sprite.StopOverlay(); + RemoveStatusEffects(); + statusEffectSprite.Reset(); + SetCollisionDamage(0); + entityCollisionClass = ENTCOLL_ALL; + if (entityGridCollisionClass < GRIDCOLL_WALLS || entityGridCollisionClass == GRIDCOLL_PITSONLY) + entityGridCollisionClass = GRIDCOLL_WALLS; + pos = g_game->room->GetClampedPosition(pos, 0); + if (config->gridCollisionPoints < 1) SetSize(size, sizeMulti, STATUE_GRID_POINTS); + + mass = STATUE_MASS; + isDead = false; + isCanShutDoors = false; + isBoss = false; + isInvincible = true; + AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | FLAG_ICE_FROZEN); + health = STATUE_HEALTH; + maxHitPoints = STATUE_HEALTH; + if (type == ENTITY_BLOOD_PUPPY && parent && parent->IsFamiliar()) static_cast(parent.get())->linkedEntity = this; + spawnerType = 0; + spawnerVariant = 0; + spawnerEntity = nullptr; + parent = nullptr; + child = nullptr; + target = nullptr; + + stateFrame = type; + type = ENTITY_FROZEN_ENEMY; + ResetColor(); + SetColor(STATUE_FLASH, STATUE_FLASH_FRAMES, 1, true, true); +} + +// 006ca930 A frozen statue's frame: it slows, and each hit it took chips one of its ten points (an explosion or a +// crush breaks it at once). Shoved, it slides with a trail of cold mist and breaks on the first wall. Broken, it gives +// its kill's item effects and bursts into ten ice shards that slow, stronger the deeper the floor. void Entity_NPC::update_frozen() { - reconstruction_missing("Entity_NPC::update_frozen 006ca930"); + friction *= HALF; + for (const DamageEvent& hit : damageEvents) + { + if (isDead) break; + if (hit.damageFlags & (DAMAGE_EXPLOSION | DAMAGE_CRUSH) || --health <= 0) Kill(EntityRef()); + } + damageEvents.clear(); + pendingDamage = 0; + pendingDamageFlags = 0; + Entity::Update(); + + if (HasEntityFlags(FLAG_KNOCKED_BACK)) + { + if ((Random() & 1) == 0) + { + Entity* creep = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL, + .seed = Random()}); + float scale = random_unit() * HALF + STATUE_TRAIL_SCALE_MIN; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); + } + auto* mist = static_cast(g_game->Spawn({.position = pos, .velocity = vector_scale(velocity, STATUE_MIST_DRAG), + .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, .seed = Random()})); + mist->rotation = random_unit() * STATUE_MIST_SPIN_RANGE + STATUE_MIST_SPIN_MIN; + mist->SetTimeout((int)(Random() % STATUE_MIST_FRAMES) + STATUE_MIST_FRAMES); + mist->posOffset = posOffset; + mist->sprite.GetLayer(0)->color = STATUE_MIST_COLOR; + if (isCollidesWithGrid) + { + pos = g_game->room->GetClampedPositionImpl(vector_sub(pos, gridCollisionVelocity), STATUE_WALL_MARGIN, STATUE_WALL_MARGIN, + STATUE_WALL_MARGIN, STATUE_WALL_MARGIN); + Kill(EntityRef()); + } + } + if (!isDead) return; + + trigger_kill_item_effects(); + float damage = (float)g_game->stage + STATUE_SHARD_DAMAGE; + float turn = random_unit() * FULL_TURN_DEGREES; + TearFlags flags; + flags.set(TEAR_ICE_FLAG); + flags.set(TEAR_SLOW); + for (int i = 0; i < STATUE_SHARDS; i++) + { + Vector velocity = vector_scale(vector_from_angle(i * FULL_TURN_DEGREES / STATUE_SHARDS + turn), STATUE_SHARD_SPEED); + auto* shard = static_cast(g_game->Spawn({.position = pos, .velocity = velocity, .type = ENTITY_TEAR, + .variant = TEAR_ICE, .seed = Random()})); + shard->SetCollisionDamage(damage); + shard->SetTearFlags(flags); + shard->fallingAccel = STATUE_SHARD_FALL; + shard->spawnerType = ENTITY_PLAYER; + shard->Update(); + } } // 006d0c60 diff --git a/src/entity_npc.h b/src/entity_npc.h index 7469453..98b3ea6 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -302,6 +302,7 @@ struct Entity_NPC : Entity void type_update(); void forced_target_update(); void update_frozen(); + void ice_statue_make(); void update_physics(); void apply_velocity(char isInterpolated); void update_move_direction_anim(); diff --git a/src/entity_npc_render.cpp b/src/entity_npc_render.cpp index cd78541..95b06e0 100644 --- a/src/entity_npc_render.cpp +++ b/src/entity_npc_render.cpp @@ -1,4 +1,5 @@ #include "entity_npc.h" +#include "boss_final.h" #include "beam_renderer.h" #include "entity_config.h" #include "entity_player.h" @@ -15,7 +16,6 @@ #include constexpr float NPC_SCREEN_SCALE = 0.65f; -constexpr int NPC_DEBUG_HEALTH_FLAG = 1 << 6; constexpr int SPAWN_BAR_DELAY = 2; constexpr float HEALTH_BAR_DROP = 10; @@ -41,7 +41,6 @@ constexpr float HEALTH_BAR_SATURATION_GREY = 0.8f; // pile's statue, the Shell and Dogma's body. constexpr int WORMWOOD = 3; constexpr int BIG_BONY_BONE = 10; -constexpr int FESTERING_GUTS = 20; constexpr int SHELL = 3; constexpr int SCOURGE_CHAIN = 10; constexpr int RIDDEN_MINECART = 10; @@ -286,7 +285,7 @@ static void npc_body_render(Entity_NPC& npc, const Vector& offset) if (npc.variant != SCOURGE_CHAIN) return npc.Entity::Render(offset); return scourge_chain_render(npc, offset); case ENTITY_MOTHER: - return reconstruction_missing("NpcHelper::mother_render 0056fcf0"); + return mother_render(npc, offset); case ENTITY_HORNY_BOYS: return horny_boys_render(npc, offset); case ENTITY_CLUTCH: @@ -458,7 +457,7 @@ void Entity_NPC::Render(const Vector& offset) Vector at = vector_make(sprite.scale.y * 12 + renderPosition.x, renderPosition.y - sprite.scale.y * 35); chargeBarSprite.Render(SpriteDraw{at, {}, {}}); } - if (HasEntityFlags(FLAG_PERSISTENT | FLAG_DELIRIUM_FORM) && (g_game->debugFlags & NPC_DEBUG_HEALTH_FLAG)) + if (HasEntityFlags(FLAG_PERSISTENT | FLAG_DELIRIUM_FORM) && (g_game->debugFlags & DEBUG_DAMAGE_VALUES)) reconstruction_missing("Entity_NPC::Render 006d2e50: the debug health text"); } diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index 164ef73..69e8e15 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -12,6 +12,7 @@ #include "lua_engine.h" #include "manager.h" #include "menu_options.h" +#include "npc_depths.h" #include "persistent_game_data.h" #include "platform.h" #include "room.h" @@ -47,6 +48,7 @@ enum BombSubType : int }; // The items, trinkets, characters, challenges, seeds and unlocks the pickups ask about. +constexpr int BLOOD_CHARGE_CAP = 99; constexpr int COLLECTIBLE_MAGNETO = 53; constexpr int COLLECTIBLE_HUMBLEING_BUNDLE = 203; constexpr int COLLECTIBLE_BOGO_BOMBS = 250; @@ -85,7 +87,6 @@ constexpr int ACHIEVEMENT_SCARED_HEART = 328; constexpr int ACHIEVEMENT_CHARGED_KEY = 333; constexpr int ACHIEVEMENT_BONE_HEART = 391; constexpr int ACHIEVEMENT_ROTTEN_HEART = 411; -constexpr int ACHIEVEMENT_MEGA_CHEST = 601; constexpr int ACHIEVEMENT_BLACK_SACK = 604; constexpr int ACHIEVEMENT_GOLDEN_PENNY = 613; constexpr int ACHIEVEMENT_GOLDEN_BATTERY = 615; @@ -114,7 +115,6 @@ constexpr std::initializer_list SAVED_EFFECTS = {74, 76, 39, 116, 120, 192} constexpr int BOMB_VARIANT_TROLL = 3; constexpr int BOMB_VARIANT_SUPERTROLL = 4; constexpr int BOMB_VARIANT_GOLDENTROLL = 18; -constexpr int POOF02_LAVA_SPLASH = 66; constexpr int WISP_HEALED_BY_HEARTS = 296; // The sounds pickups play. @@ -127,19 +127,13 @@ constexpr int SOUND_FETUS_FEET = 201; constexpr int SOUND_NICKELDROP = 231; constexpr int SOUND_NICKELPICKUP = 232; constexpr int SOUND_PENNYDROP = 233; -constexpr int SOUND_PENNYPICKUP = 234; -constexpr int SOUND_BONE_HEART = 461; constexpr int SOUND_SHOVEL_DROP = 463; -constexpr int SOUND_GOLD_HEART = 465; -constexpr int SOUND_UNHOLY = 468; constexpr int SOUND_GOLDENBOMB = 470; -constexpr int SOUND_ROTTEN_HEART = 497; constexpr int SOUND_BUTTER_LAND = 902; constexpr float KEY_PICKUP_VOLUME = 0.85f; constexpr float STICKY_NICKEL_VOLUME = 0.5f; constexpr float POOP_PITCH_MIN = 0.9f; constexpr float POOP_PITCH_RANGE = 0.3f; -constexpr int PILL_GOLD = 14; constexpr int CARD_PLAYING_FLAG = 0x8000; // The card pickup subtypes that sound like objects, not paper, when collected. constexpr std::initializer_list CARD_OBJECT_SUBTYPES = {3, 4, 6, 7, 13, 15}; @@ -153,9 +147,6 @@ constexpr int WEIGHT_POCKET = 4; constexpr int WEIGHT_BATTERY = 2; constexpr int WEIGHT_RARE = 1; constexpr int KEY_WEIGHT_NORMAL = 49; -constexpr int RANDOM_NO_COINS = 3; -constexpr int RANDOM_NO_CHESTS_A = 1; -constexpr int RANDOM_NO_CHESTS_B = 4; constexpr float RIB_OF_GREED_ROLL = 0.1f; constexpr float WATCH_BATTERY_ROLL = 0.2f; constexpr int DAEMONS_TAIL_KEEP_ODDS = 5; @@ -218,8 +209,6 @@ constexpr int ODDS_MICRO_BATTERY = 3; constexpr int ODDS_MEGA_BATTERY = 100; constexpr int ODDS_GOLDEN_BATTERY = 120; constexpr int MEGA_CHEST_ROLL = 4; -constexpr int CARD_SPECIAL_CHANCE = 25; -constexpr int CARD_RUNE_CHANCE = 10; constexpr int CARD_SUIT_CHANCE = 10; // Pickup motion and timing. @@ -1530,13 +1519,38 @@ static bool throwable_bomb_lift(Entity_Pickup& pickup, Entity_Player& player) return true; } +// Part of 006e8ae0: a bed sends the players to sleep once, when one of them could use red hearts. Mom's bed always +// does, reviving the co-op ghosts, and at Home it brings the nightmare. +static void bed_touch(Entity_Pickup& bed, Entity_Player& player) +{ + constexpr int BED_MOM = 10; + + if (bed.isTouched) return; + bool isMomsBed = bed.subtype == BED_MOM; + bool isUsed = isMomsBed; + for (Entity_Player* other : g_game->playerManager.playerList) + { + if (isUsed) break; + HealthType health = other->GetHealthType(); + int hearts = health == HEALTH_SOUL || health == HEALTH_NO_HEALTH ? other->maxHearts + : other->maxHearts + other->boneHearts * 2; + isUsed = hearts < 1 || !other->HasFullHearts(); + } + if (!isUsed) return; + + if (isMomsBed) g_game->playerManager.revive_player_ghosts(); + bed.isTouched = true; + bed.target = &player; + bool isHome = g_game->stage == STAGE_HOME && g_game->stageType == STAGETYPE_ORIGINAL; + g_game->itemOverlay.Show(isMomsBed && isHome ? GIANTBOOK_SLEEP_NIGHTMARE : GIANTBOOK_SLEEP, 0, nullptr); +} + // 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). Taking an -// item, opening a chest or a sack starts a challenge room's fight. The bed, -// familiars that collect and the rarer items and trinkets that change what a pickup gives are not -// reconstructed yet. +// item, opening a chest or a sack starts a challenge room's fight, and a bed sends the players to sleep. Familiars +// that collect and the rarer items and trinkets that change what a pickup gives are not reconstructed yet. bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) { if (variant == PICKUP_COLLECTIBLE && (megaChestCollectible[0] || megaChestCollectible[1])) @@ -1584,7 +1598,7 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) (collider->type == ENTITY_ULTRA_GREED || collider->type == ENTITY_BUMBINO) && variant == PICKUP_COIN; auto* eater = static_cast(collider); bool isEaten = - (isBum && bum_pickup_collect(*eater, *this)) || + (isGreed && greed_coin_collect(*this, collider)) || (isBum && bum_pickup_collect(*eater, *this)) || (isEater && !eater->is_following() && (familiar == Entity_Familiar::LIL_PORTAL ? (eater->AddCoins(1), true) : eater->abyss_locust_eat())); if (isEaten) @@ -1595,8 +1609,6 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) collect_finish(nullptr); return true; } - if (isGreed) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Ultra Greed or Bumbino collecting it"); return g_game->room->roomType == ROOM_DUNGEON || collider->type == ENTITY_BOMB || price != 0; } @@ -1697,8 +1709,9 @@ bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) case PICKUP_THROWABLEBOMB: isPickedUp = throwable_bomb_lift(*this, *player); break; - default: - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the bed"); + case PICKUP_BED: + bed_touch(*this, *player); + break; } Room& room = *g_game->room; @@ -1845,8 +1858,11 @@ bool Entity_Pickup::heart_collect(Entity_Player& player) player.AddImmaculateConceptionCounter(2); return true; case HEART_ROTTEN: - if (player.playerType == PLAYER_BETHANY_B) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Tainted Bethany's blood"); + if (player.playerType == PLAYER_BETHANY_B && player.CanPickRedHearts()) + { + player.AddHearts(std::min(1, BLOOD_CHARGE_CAP - player.effectiveBloodCharge), false, false); + return true; + } if (!player.CanPickRottenHearts()) return false; player.AddRottenHearts(2, false); player.AddImmaculateConceptionCounter(2); @@ -1860,7 +1876,12 @@ bool Entity_Pickup::heart_collect(Entity_Player& player) bool isPickedUp = false; if (isMaggysBow) amount *= 2; if (player.playerType == PLAYER_BETHANY_B && player.CanPickRedHearts()) - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Tainted Bethany's blood"); + { + int taken = std::min(amount, BLOOD_CHARGE_CAP - player.effectiveBloodCharge); + player.AddHearts(taken, false, false); + amount -= taken; + isPickedUp = true; + } for (Entity_Player* other : g_game->playerManager.playerList) { @@ -1982,7 +2003,7 @@ void Entity_Pickup::PlayDropSound() sound = subtype == BOMB_GOLDEN ? SOUND_GOLD_HEART_DROP : SOUND_FETUS_LAND; break; case PICKUP_PILL: - sound = (subtype & PILL_COLOR_MASK) == PILL_GOLD ? SOUND_GOLD_HEART_DROP : SOUND_FETUS_JUMP; + sound = (subtype & PILL_COLOR_MASK) == PILL_COLOR_GOLD ? SOUND_GOLD_HEART_DROP : SOUND_FETUS_JUMP; break; case PICKUP_GRAB_BAG: sound = SOUND_FETUS_JUMP; @@ -2240,10 +2261,13 @@ void Entity_Pickup::SetForceBlind(uint8_t setBlind) if (variant == PICKUP_COLLECTIBLE && subtype != 0 && isWasBlind != isForceBlind) UpdateSprite(false); } -// 006e3020 +// 006e3020 A penny still on the first frame of its appearing plays the fast appearance instead. void Entity_Pickup::AppearFast() { - reconstruction_missing("Entity_Pickup::AppearFast 006e3020"); + bool isPenny = variant == PICKUP_COIN && subtype == COIN_PENNY; + + if (isPenny && sprite.IsPlaying() && sprite.GetAnimation() == "Appear" && sprite.GetFrame() == 0) + sprite.Play("AppearFast"); } // 006ee3f0 Whether Jera or Diplopia may copy the pickup: a living one that can be rerolled, no pedestal, trinket, @@ -2255,6 +2279,7 @@ bool Entity_Pickup::CanJeraDuplicate() return CanReroll() && (!IsChest(variant) || subtype != 0); } + // 006eed30 Gives the pickup an options index of its own, past every other pickup's and at least 3. int Entity_Pickup::AssignOptionsIndex() { diff --git a/src/entity_pickup.h b/src/entity_pickup.h index 78d4b79..04af4cc 100644 --- a/src/entity_pickup.h +++ b/src/entity_pickup.h @@ -41,6 +41,11 @@ enum PickupVariant : int PICKUP_MOMSCHEST = 390 }; +// The filters a random pickup's subtype (PICKUP_NULL) sets: no chests (A, or B without trinkets either) or no coins. +constexpr int RANDOM_NO_CHESTS_A = 1; +constexpr int RANDOM_NO_COINS = 3; +constexpr int RANDOM_NO_CHESTS_B = 4; + // The most items a glitched pedestal cycles through. constexpr int CYCLE_COLLECTIBLE_LIMIT = 8; diff --git a/src/entity_pickup_shop.cpp b/src/entity_pickup_shop.cpp index 35ad5ce..d037a69 100644 --- a/src/entity_pickup_shop.cpp +++ b/src/entity_pickup_shop.cpp @@ -368,7 +368,7 @@ void Entity_Pickup::other_deals_take() Game& game = *g_game; bool isDarkRoomStart = !game.IsGreedMode() && game.stage == STAGE_DARK_ROOM && game.startingRoomIdx == game.currentRoomIdx; - for (Entity* entity : game.room->entityList.updateEL) + for (Entity* entity : entities_live(game.room->entityList.updateEL)) { if (entity->type != ENTITY_PICKUP || entity == this) continue; Entity_Pickup& other = *static_cast(entity); diff --git a/src/entity_player.cpp b/src/entity_player.cpp index 0828e09..13bb851 100644 --- a/src/entity_player.cpp +++ b/src/entity_player.cpp @@ -1,4 +1,5 @@ #include "entity_player.h" +#include "entity_pickup.h" #include "entity_player_characters.h" #include "data.h" #include "entity_effect.h" @@ -27,7 +28,6 @@ constexpr float PLAYER_START_TEAR_RANGE = 260; constexpr float ROCK_BOTTOM_LUCK_UNSET = -9999; constexpr int COSTUME_RESERVE = 32; constexpr int MAX_PEE_BURST_COOLDOWN = 30; -constexpr int MONKEY_PAW_USES = 3; constexpr int PLAYER_RENDER_Z_OFFSET = 5; constexpr int TONSIL_COUNTER_MIN = 6; constexpr int TONSIL_COUNTER_RANGE = 7; @@ -49,7 +49,6 @@ constexpr uint32_t COLLECTIBLE_RNG_SHIFT = 6; constexpr uint32_t TRINKET_RNG_SHIFT = 7; constexpr uint32_t PILL_RNG_SHIFT = 8; constexpr uint32_t CARD_RNG_SHIFT = 9; -constexpr uint32_t ITEM_RNG_SHIFT = 35; constexpr uint32_t PRE_LEVEL_RNG_SHIFT = 2; constexpr uint32_t FLOOR_RNG_SHIFT = 12; constexpr uint32_t JACOBS_CURSE_RNG_SHIFT = 66; @@ -64,7 +63,6 @@ constexpr int JACOBS_CURSE_MIN_FRAMES = 610; constexpr int ASCENT_HOME_STAGE = 6; constexpr int CAINS_EYE_CHANCE = 25; constexpr int CANTRIPPED_CARDS = 3; -constexpr int CARD_SPECIAL_CHANCE = 25; constexpr int CARD_START_RUNE_CHANCE = 10; constexpr int COLOR_PRIORITY_TOP = 255; constexpr int DAILY_CHRISTMAS = 19; @@ -74,8 +72,6 @@ constexpr int GIANTBOOK_EMPTY_HEART = 41; constexpr int LOCUST_SUBTYPE_START = 25; constexpr int PEE_ALPHA = 180; constexpr int PEE_OFFSET = 244; -constexpr int PICKUP_GRAB_BAG = 69; -constexpr int PICKUP_HEART = 10; constexpr float PICKUP_SPAWN_RADIUS = 40; constexpr int POCKET_ACTIVE_SLOT = 2; // A removed player lets go of what it holds at a tenth of its speed. @@ -113,7 +109,7 @@ static ColorMod color_from_bytes(int tintRed, int tintGreen, int tintBlue, int t static int card_roll(uint32_t seed, int runeChance, bool isPlaying) { int card = ItemPool::GetCardEx((int)seed, CARD_SPECIAL_CHANCE, runeChance, runeChance, true); - RNG rng = rng_make(seed, ITEM_RNG_SHIFT); + RNG rng = rng_make(seed, DEFAULT_SHIFT_INDEX); return lua_engine_get().GetCard({.rng = &rng, .card = card, .isPlaying = isPlaying, .isRunes = isPlaying}); } @@ -140,7 +136,7 @@ static void item_rngs_fill(std::vector& rngs, size_t count, uint32_t seed, { RNG stepper = rng_make(seed, shiftIndex); - for (size_t i = 0; i < count; i++) rngs.push_back(rng_make(stepper.Next(), ITEM_RNG_SHIFT)); + for (size_t i = 0; i < count; i++) rngs.push_back(rng_make(stepper.Next(), DEFAULT_SHIFT_INDEX)); } // 00753da0 Makes an empty player, its members at their defaults. @@ -1521,6 +1517,7 @@ void Entity_Player::release_weapons_and_effects(bool isRemoveEntities) } link_release(azazelsRageLaser, isRemoveEntities); link_release(dadsRingAura, isRemoveEntities); + link_release(telekinesisHalo, isRemoveEntities); link_release(breathOfLifeEffect, isRemoveEntities); link_release(isaacsHeart, isRemoveEntities); link_release(trinityShield, isRemoveEntities); diff --git a/src/entity_player.h b/src/entity_player.h index fe9c236..6bce712 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -43,6 +43,20 @@ constexpr uint8_t WILD_CARD_PILL = 0; constexpr uint8_t WILD_CARD_CARD = 1; constexpr uint8_t WILD_CARD_ACTIVE = 2; +// Which consumables ConsumableCountChanged and SyncConsumables copy between players. +enum ConsumableMask : uint32_t +{ + CONSUMABLE_COINS = 0x1, + CONSUMABLE_KEYS = 0x2, + CONSUMABLE_BOMBS = 0x4, + CONSUMABLE_GOLDEN_KEY = 0x8, + CONSUMABLE_GOLDEN_BOMB = 0x10, + CONSUMABLE_SOUL_CHARGE = 0x20, + CONSUMABLE_GIGA_BOMBS = 0x40, + CONSUMABLE_POOP_MANA = 0x80, + CONSUMABLE_BLOOD_CHARGE = 0x100 +}; + // The characters, by their ids in players.xml (Lua's PlayerType). enum PlayerType : int { @@ -122,6 +136,20 @@ enum BabySubType : int BABY_BASIC = 71 }; +// Suplex!'s states (suplexState): the dash, the aim with an enemy grabbed (a super leap's aim), the leap up and down. +enum SuplexState +{ + SUPLEX_NONE, + SUPLEX_DASHING, + SUPLEX_AIMING, + SUPLEX_LEAPING, + SUPLEX_LANDING, + SUPLEX_SUPER_AIMING +}; + +// The hits Monkey Paw answers before it is spent. +constexpr int MONKEY_PAW_USES = 3; + // How a character's health is counted (REPENTOGON's HealthType). enum HealthType : int { @@ -331,6 +359,7 @@ enum PlayerItemId : int COLLECTIBLE_MOMS_PURSE = 139, COLLECTIBLE_BOBS_CURSE = 140, COLLECTIBLE_SCAPULAR = 142, + COLLECTIBLE_BUM_FRIEND = 144, COLLECTIBLE_NOTCHED_AXE = 147, COLLECTIBLE_INFESTATION = 148, COLLECTIBLE_IPECAC = 149, @@ -425,6 +454,7 @@ enum PlayerItemId : int COLLECTIBLE_THE_WIZ = 358, COLLECTIBLE_INCUBUS = 360, COLLECTIBLE_SWORN_PROTECTOR = 363, + COLLECTIBLE_CHARGED_BABY = 372, COLLECTIBLE_EPIPHORA = 368, COLLECTIBLE_CURSE_OF_THE_TOWER = 371, COLLECTIBLE_DEAD_EYE = 373, @@ -433,6 +463,7 @@ enum PlayerItemId : int COLLECTIBLE_RESTOCK = 376, COLLECTIBLE_BURSTING_SACK = 377, COLLECTIBLE_PAY_TO_PLAY = 380, + COLLECTIBLE_KEY_BUM = 388, COLLECTIBLE_SERAPHIM = 390, COLLECTIBLE_EMPTY_VESSEL = 409, COLLECTIBLE_ZODIAC = 392, @@ -706,6 +737,7 @@ enum PlayerItemId : int TRINKET_MECONIUM = 91, TRINKET_USED_DIAPER = 93, TRINKET_STORE_KEY = 83, + TRINKET_GOLDEN_HORSE_SHOE = 82, TRINKET_FISH_TAIL = 94, TRINKET_OUROBOROS_WORM = 96, TRINKET_TONSIL = 97, @@ -722,7 +754,9 @@ enum PlayerItemId : int TRINKET_EXTENSION_CORD = 125, TRINKET_BROKEN_PADLOCK = 136, TRINKET_FORGOTTEN_LULLABY = 141, + TRINKET_MYOSOTIS = 137, TRINKET_BETHS_FAITH = 142, + TRINKET_OLD_CAPACITOR = 143, TRINKET_PERFECTION = 145, TRINKET_FRIENDSHIP_NECKLACE = 148, TRINKET_BLUE_KEY = 150, @@ -821,6 +855,8 @@ enum PlayerItemId : int NULLITEM_JUDAS_BIRTHRIGHT = 123, NULLITEM_JUDAS_BIRTHRIGHT_TIMED = 124, NULLITEM_JUDAS_BIRTHRIGHT_PERMANENT = 130, + NULLITEM_AZAZELS_RAGE_1 = 96, + NULLITEM_AZAZELS_RAGE_4 = 99, NULLITEM_ESAU_JR = 100, NULLITEM_SPIRIT_SHACKLES_DISABLED = 102, NULLITEM_FORGOTTEN_BOMB = 106, @@ -987,7 +1023,9 @@ enum PlayerAchievement : int // The challenges the player's code tells apart (Lua's Challenge). enum PlayerChallenge : int { + CHALLENGE_BEANS = 13, CHALLENGE_SPEED = 22, + CHALLENGE_BLUE_BOMBER = 23, CHALLENGE_PAY_TO_PLAY = 24, CHALLENGE_HAVE_A_HEART = 25, CHALLENGE_PRIDE_DAY = 28, @@ -1454,6 +1492,7 @@ public: EntityPtr monstranceAura; EntityPtr redemptionEffect; EntityPtr salvationEffect; + EntityPtr telekinesisHalo; EntityPtr tetheredEffect; EntityPtr tractorBeam; EntityPtr trinityShield; diff --git a/src/entity_player_actives.cpp b/src/entity_player_actives.cpp index 0593b85..c2ae1ad 100644 --- a/src/entity_player_actives.cpp +++ b/src/entity_player_actives.cpp @@ -8,12 +8,15 @@ #include "room_grid.h" #include "active_items.h" #include "boss_ai.h" +#include "capsule.h" #include "entity_bomb.h" +#include "entity_effect.h" #include "entity_pickup.h" #include "entity_tear.h" #include "game.h" #include "grid_entity_door.h" #include "grid_entity_poop.h" +#include "grid_entity_trap_door.h" #include "hud.h" #include "kage_input.h" #include "key_configs.h" @@ -23,6 +26,7 @@ #include "manager.h" #include "menu_manager.h" #include "npc_basement.h" +#include "npc_fireplace.h" #include "room.h" #include "room_special.h" #include "tainted_characters.h" @@ -35,6 +39,10 @@ constexpr int ACHIEVEMENT_HALO = 27; constexpr int ACTIVE_PICKUP_HOLD_FRAMES = 30; constexpr int BATTERY_CHARGE = 6; constexpr int BATTERY_MICRO_CHARGE = 2; +constexpr float BLUE_CANDLE_DAMAGE = 6; +constexpr int BLUE_CANDLE_FRAMES = 60; +constexpr float CANDLE_THROW_BOOST = 1.4f; +constexpr float CANDLE_THROW_SPEED = 10; constexpr int CHARGE_FLASH_MAX = 12; constexpr int EVENT_BATTERIES_COLLECTED = 195; constexpr int GLOWING_HOUR_GLASS_LIT_USES = 3; @@ -45,13 +53,13 @@ constexpr int INPUT_RAW_ACTION = 33; constexpr int MECONIUM_CHANCES[] = {33, 66, 100}; constexpr int MIDAS_POOP_CHANCE = 34; constexpr int MR_BOOM_SOUND_DELAY = 4; +constexpr float RED_CANDLE_DAMAGE = 4; constexpr int NINE_VOLT_RECHARGE_FRAMES = 450; constexpr int NECROMANCER_FORM_ITEMS = 3; constexpr int OVERLAY_DELAY = 3; constexpr int PERCENT = 100; constexpr int REVELATIONS_SOUL_HEARTS = 2; constexpr int REVELATIONS_STATE_FLAG = 7; -constexpr int SUPLEX_AIMING = 2; constexpr int TAMMY_TEAR_COUNT = 10; constexpr int TIMED_RECHARGE_STEP = 1; constexpr int UNUSED_COLLECTIBLES[] = {43, 61, 235}; @@ -667,10 +675,9 @@ void Entity_Player::trigger_book_of_belial_passive(int, int) // the item's pickup and the item is still owned. The original crashes on an item missing from the config. void Entity_Player::TryRemoveCollectibleCostume(int collectibleId, bool) { - constexpr int SHOOP_DA_WHOOP = 49; if (collectibleId == 0 || - (temporaryEffects.HasCollectibleEffect(collectibleId) && collectibleId != SHOOP_DA_WHOOP)) + (temporaryEffects.HasCollectibleEffect(collectibleId) && collectibleId != COLLECTIBLE_SHOOP_DA_WHOOP)) return; ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(collectibleId); @@ -700,6 +707,62 @@ void Entity_Player::ShootCandle(Vector) else ShootBlueCandle(direction); } +// A candle flame the player throws: its effect variant and its damage in tears. +struct CandleFlame +{ + int variant = 0; + float damageFactor = 0; +}; + +// Throws a candle flame the given way with the tears' push, dealing its share of the tear damage scaled by melee +// damage, sized like a tear and faded for a remote online player. The original fades by an unset value in versus, +// which here leaves the flame as it is. +static Entity_Effect* candle_flame_throw(Entity_Player& player, Vector direction, const CandleFlame& candle) +{ + TearParams params = player.GetTearHitParams(WEAPON_TEARS, 1, (int)(Random() & 1) * 2 - 1, nullptr); + Vector push = player.GetTearMovementInheritance(direction, INHERIT_CHECKED); + EntitySpawn spawn; + spawn.velocity = vector_scale(vector_add(vector_scale(direction, CANDLE_THROW_SPEED), push), CANDLE_THROW_BOOST); + spawn.position = player.pos; + spawn.spawner = &player; + spawn.seed = Random(); + spawn.type = ENTITY_EFFECT; + spawn.variant = candle.variant; + + auto* flame = static_cast(g_game->Spawn(spawn)); + flame->SetCollisionDamage(params.tearDamage * candle.damageFactor * player.meleeDamage / player.damage); + if (candle.variant == EFFECT_BLUE_FLAME) + { + flame->timeout = BLUE_CANDLE_FRAMES; + flame->lifespan = BLUE_CANDLE_FRAMES; + flame->entityGridCollisionClass = GRIDCOLL_NONE; + } + flame->sprite.scale = vector_make(params.tearScale, params.tearScale); + + NetplayManager& netplay = g_manager->netplayManager; + if (netplay.is_online() && !netplay.IsIdxLocalPlayer(player.controllerIndex) && + !g_game->deathmatchManager.is_active()) + { + ColorMod faded = flame->sprite.color; + faded._tint[3] *= tear_remote_opacity_get(); + flame->SetColor(faded, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + flame->Update(); + return flame; +} + +// 007c9130 Throws Bird's Eye's red flame. +Entity* Entity_Player::ShootRedCandle(Vector direction) +{ + return candle_flame_throw(*this, direction, {EFFECT_RED_CANDLE_FLAME, RED_CANDLE_DAMAGE}); +} + +// 007c9350 Throws Ghost Pepper's blue flame, which burns out after two seconds. +Entity* Entity_Player::ShootBlueCandle(Vector direction) +{ + return candle_flame_throw(*this, direction, {EFFECT_BLUE_FLAME, BLUE_CANDLE_DAMAGE}); +} + // Bible: kills Mom or Mom's Heart (earning Halo), or Satan kills the player. Flight comes from the room effect. static void bible_use(ItemUse& use) { @@ -1537,6 +1600,18 @@ UseResult Entity_Player::UseActiveItem(const ActiveUse& request) return use.result; } +// Wavy Cap's recharge a frame: quicker the fewer of its uses (and its lingering trips) are on, (n + 1) * n for the +// n of ten left. +static int wavy_cap_recharge_step(Entity_Player& player) +{ + constexpr int WAVY_CAP_USES = 10; + TemporaryEffects& effects = player.temporaryEffects; + int trips = effects.isDisabled ? 0 : effects.GetNullEffectNum(NULLITEM_WAVY_CAP_1); + TemporaryEffect* uses = effects.isDisabled ? nullptr : effects.GetCollectibleEffect(COLLECTIBLE_WAVY_CAP); + int left = std::max(0, WAVY_CAP_USES - (uses ? uses->count : 0) - trips); + return (left + 1) * left; +} + // The first slot's frame for every slot: recharge cooldowns count down, a timed item fills a charge a frame and beeps // when full, 9 Volt refills an empty one-charge item after a while in a room with enemies, and 4.5 Volt turns a whole // partial charge into a charge (the original's partial charge is a float, which only 4.5 Volt's damage fills). @@ -1556,10 +1631,7 @@ static void timed_items_recharge(Entity_Player& player) ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(active.item); if (item && item->chargeType == CHARGE_TIMED) { - if (active.item == COLLECTIBLE_WAVY_CAP) - reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Wavy Cap's recharge)"); - - int step = TIMED_RECHARGE_STEP; + int step = active.item == COLLECTIBLE_WAVY_CAP ? wavy_cap_recharge_step(player) : TIMED_RECHARGE_STEP; if (active.charge < maxCharge) { int added = std::min(maxCharge - active.charge, step); @@ -1572,7 +1644,15 @@ static void timed_items_recharge(Entity_Player& player) } } if (player.HasCollectible(COLLECTIBLE_BATTERY) && active.batteryCharge < maxCharge && step > 0) - reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (a timed item's battery)"); + { + active.batteryCharge += std::min(step, maxCharge - active.batteryCharge); + if (active.batteryCharge >= maxCharge) + { + g_game->hud.FlashChargeBar(&player, slot); + sound_play(SOUND_BATTERYCHARGE); + battery_effect_spawn(player); + } + } } bool isNineVoltCounting = player.HasCollectible(COLLECTIBLE_9_VOLT) && minCharge == 1 && @@ -1678,20 +1758,284 @@ static void sharp_plug_pay(Entity_Player& player, int slot, ItemConfig_Item& con } } -// Uses a slot's item from the item button: only when charged and payable, else Sharp Plug may pay health for it. A -// zero-charge item waits out its room effect. The use discharges the slot or removes the item as it asks, and Car -// Battery uses it again. -static void active_slot_use(Entity_Player& player, int slot, int itemStateBefore) +// The item button for a slot this frame: held and pressed, a press Panic Button made, the use a held item asks for +// (Breath of Life tapped full, Spin to Win held), and a held Spin to Win let go. +struct ItemButton +{ + bool isHeldUse = false; + bool isPanic = false; + bool isPressed = false; + bool isReleased = false; + bool isTriggered = false; +}; + +// The way an entity moves in a frame, as the collision capsules look ahead. +static Vector frame_step(Entity& entity) +{ + return vector_scale(entity.velocity, entity.speedMultiplier * entity.friction); +} + +// Panic Button: with the first slot's item usable and the player open to a hit, an enemy, a damaging enemy shot or +// tear (a player in a versus match) about to touch it next frame presses the item button. +static bool is_panic_pressed(Entity_Player& player) +{ + constexpr float PANIC_REACH = 150; + bool isVersus = g_game->deathmatchManager.is_active(); + bool isOpen = is_active_usable(player, player.activeItems[ACTIVE_SLOT_PRIMARY].item, ACTIVE_SLOT_PRIMARY) && + player.entityCollisionClass != ENTCOLL_NONE && player.itemState == 0 && player.damageCooldown < 2 && + !player.HasInvincibility(0, EntityRef()); + if (!isOpen) return false; + + Capsule body = player.GetCollisionCapsule(frame_step(player)); + uint32_t partitions = QUERY_PROJECTILES | QUERY_ENEMIES | (isVersus ? QUERY_TEARS : 0); + Vector next = vector_add(player.pos, frame_step(player)); + for (Entity* entity : entity_query_radius(next, player.size + PANIC_REACH, partitions)) + { + if (entity->isDead || entity->entityCollisionClass == ENTCOLL_NONE) continue; + bool isRival = isVersus && entity->type == ENTITY_PLAYER; + bool isEnemy = (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENTITY_LAST_ENEMY) || + entity->type == ENTITY_PROJECTILE || entity->type == ENTITY_TEAR; + bool isWhiteFire = entity->type == ENTITY_FIREPLACE && entity->variant == FIRE_WHITE; + if ((!isRival && (!isEnemy || isWhiteFire)) || entity->HasEntityFlags(FLAG_FRIENDLY)) continue; + + bool isHarmful = entity->collisionDamage > 0; + if (!isRival && entity->type == ENTITY_PROJECTILE) + isHarmful = !(static_cast(entity)->projectileFlags & PROJECTILE_CANT_HIT_PLAYER); + if (isHarmful && Capsule::Collide(body, entity->GetCollisionCapsule(frame_step(*entity)))) return true; + } + return false; +} + +// Breath of Life held down: each frame drains four charges (the battery's first) with a tick at each quarter, and +// running dry makes the player unhurtable under its halo while it stays held. +static void breath_of_life_drain(Entity_Player& player, int slot) +{ + constexpr int DRAIN = 4; + constexpr int QUARTERS = 4; + constexpr float TICK_PITCH_TOP = 1.6f; + constexpr float TICK_PITCH_STEP = 0.2f; + constexpr int TICK_FRAME_DELAY = 1; + constexpr float HALO_RISE = -15; + constexpr ColorMod BELIAL_HALO = {{1, 1, 1, 1}, {1, 0.05f, 0.06f, 1}, {0, -0.2f, -0.2f}}; + ActiveItemDesc& active = player.activeItems[slot]; + TemporaryEffects& effects = player.temporaryEffects; + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || effects.HasCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE)) + return; + + int quarter = player.GetActiveMaxCharge(slot) / QUARTERS; + int& drained = active.batteryCharge >= 1 ? active.batteryCharge : active.charge; + int before = drained; + player.AddActiveCharge(-std::min(drained, DRAIN), slot, false, false, false); + if (drained >= 1) + { + // The original divides by a zero quarter on an item under four charges. Here no tick plays. + if (quarter <= 0 || drained / quarter >= before / quarter) return; + int sound = SOUND_TOOTH_AND_NAIL_TICK; + seed_fart_sound_override(&sound); + float pitch = std::clamp(TICK_PITCH_TOP - (float)(drained / quarter) * TICK_PITCH_STEP, 1.0f, TICK_PITCH_TOP); + g_manager->sfxManager.Play(sound, {.frameDelay = TICK_FRAME_DELAY, .pitch = pitch}); + return; + } + + effects.AddCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE, false, 2); + sound_play(SOUND_TOOTH_AND_NAIL); + if (player.breathOfLifeEffect) player.breathOfLifeEffect->Remove(); + Entity* halo = g_game->Spawn({.position = player.pos, .velocity = player.velocity, .spawner = &player, + .subType = HALO_BREATH_OF_LIFE, .type = ENTITY_EFFECT, .variant = EFFECT_HALO, + .seed = Random()}); + player.breathOfLifeEffect = halo; + halo->posOffset = vector_make(0, HALO_RISE); + halo->parent = &player; + halo->sprite.Play("Appear"); + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + halo->SetColor(BELIAL_HALO, -1, COLOR_PRIORITY_DEFAULT, false, true); + halo->Update(); +} + +// Breath of Life: held after a tap it drains, let go it is spent (with a thumbs down when it never ran dry, the +// unhurtable spell ended otherwise), and tapped when full it is used at once. +static void breath_of_life_control(Entity_Player& player, int slot, ItemButton& button) +{ + constexpr int HELD_COOLDOWN = 11; + constexpr int LET_GO_COOLDOWN = 9; + ActiveItemDesc& active = player.activeItems[slot]; + TemporaryEffects& effects = player.temporaryEffects; + bool isControlled = player.AreControlsEnabled(); + bool isMoving = g_game->roomTransition.mode != TRANSITION_NONE; + bool isHeld = active.timeRechargeCooldown > LET_GO_COOLDOWN; + bool isTapped = button.isTriggered; + button.isTriggered = false; + + if (isControlled && !isMoving && isHeld && (button.isPressed || isTapped)) + { + breath_of_life_drain(player, slot); + active.timeRechargeCooldown = HELD_COOLDOWN; + return; + } + if (isControlled && !isMoving && isTapped) + { + int maxCharge = player.GetActiveMaxCharge(slot); + if (active.charge < maxCharge) return; + button.isHeldUse = true; + if (active.batteryCharge < maxCharge) active.batteryCharge = 0; + active.timeRechargeCooldown = HELD_COOLDOWN; + return; + } + if (!isHeld || isMoving || (isControlled && button.isPressed)) return; + + if (!effects.HasCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE)) + { + sound_play(SOUND_THUMBS_DOWN); + player.DischargeActiveItem(slot, false); + } + else + { + effects.RemoveCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE, -1); + if (active.charge == 0) player.DischargeActiveItem(slot, false); + } + active.timeRechargeCooldown = LET_GO_COOLDOWN; +} + +// Spin to Win: held it asks to start spinning, and while it spins it holds its recharge, ends when let go or drained, +// and with the Book of Virtues throws off a short lived wisp every sixth frame. +static void spin_to_win_control(Entity_Player& player, int slot, ItemButton& button) +{ + constexpr int SPIN_COOLDOWN = 15; + constexpr int WISP_PERIOD = 6; + ActiveItemDesc& active = player.activeItems[slot]; + bool isControlled = player.AreControlsEnabled(); + bool isSpinning = player.temporaryEffects.HasNullEffect(NULLITEM_SPIN_TO_WIN); + if (!isSpinning) button.isHeldUse = isControlled && button.isPressed; + else + { + active.timeRechargeCooldown = SPIN_COOLDOWN; + bool isLetGo = g_game->roomTransition.mode == TRANSITION_NONE && (!isControlled || !button.isPressed); + button.isReleased = isLetGo || active.charge < 1; + } + + bool isWisping = player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES) && isSpinning && !button.isReleased; + if (!isWisping || !player.IsFrame(WISP_PERIOD, 0)) return; + Entity_Familiar* wisp = player.AddWisp(COLLECTIBLE_SPIN_TO_WIN, player.pos, false, true); + if (!wisp) return; + wisp->ClearEntityFlags(FLAG_APPEAR); + wisp->isNotCountedAsFollower = true; + wisp->Update(); +} + +// Spin to Win starts spinning with at least 16 charges: the player's familiars are thrown wide, their orbits five +// past their size. +static void spin_to_win_start(Entity_Player& player) +{ + constexpr float ORBIT_WIDEN = 5; + TemporaryEffect spin(g_manager->itemConfig.GetNullItem(NULLITEM_SPIN_TO_WIN)); + spin.cooldown = -1; + player.temporaryEffects.AddEffect(spin, false, 1); + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity->type != ENTITY_FAMILIAR || static_cast(entity)->player != &player) continue; + auto& familiar = *static_cast(entity); + familiar.AddEntityFlags(FLAG_CONFUSION); + if (familiar.orbitLayer >= 0) familiar.size = familiar.config->collisionRadius + ORBIT_WIDEN; + } + player.EvaluateItems(); +} + +// Spin to Win let go: the spin ends, and the M trinket spends a drained item. +static void spin_to_win_let_go(Entity_Player& player, int slot) +{ + player.temporaryEffects.RemoveNullEffect(NULLITEM_SPIN_TO_WIN, 1); + if (player.activeItems[slot].charge == 0 && player.HasTrinket(TRINKET_M)) player.DischargeActiveItem(slot, false); +} + +// Mine Crafter without a charge sets off its barrels already standing a frame. True when one went off. +static bool mine_crafter_detonate(Entity_Player& player) +{ + constexpr int MINE_CRAFTER_TNT = 1; + constexpr float MINE_CRAFTER_DAMAGE = 100; + constexpr int DETONATE_COUNTDOWN = 30; + bool isDetonated = false; + for (Entity* entity : entity_query(ENTITY_MOVABLE_TNT, -1)) + { + if (entity->subtype != MINE_CRAFTER_TNT || entity->health <= 1) continue; + if (g_game->frameCount - entity->spawnFrame <= 1) continue; + entity->TakeDamage(MINE_CRAFTER_DAMAGE, DAMAGE_EXPLOSION, EntityRef(&player), DETONATE_COUNTDOWN); + isDetonated = true; + } + return isDetonated; +} + +// Decap Attack: the player's thrown heads come back. True when it has heads out, which keeps the item from a use. +static bool decap_attack_recall(Entity_Player& player) +{ + bool isRecalled = false; + for (Entity* entity : entity_query(ENTITY_FAMILIAR, Entity_Familiar::DECAP_ATTACK)) + { + auto& head = *static_cast(entity); + if (head.subtype != 0 || head.player != &player) continue; + if (head.state == 0) head.state = 1; + isRecalled = true; + } + return isRecalled; +} + +// April's Fool: the first slot's press uses a random active (never Plan C or Death Certificate) instead, with its +// costume. An item state it starts discharges the slot when the second slot's state stayed the same. +static UseResult aprils_fool_use(Entity_Player& player, int slot) +{ + bool isSecondHeld = slot == ACTIVE_SLOT_PRIMARY && player.activeItems[ACTIVE_SLOT_SECONDARY].item != 0; + std::vector actives; + for (const std::unique_ptr& item : g_manager->itemConfig.collectibles) + if (item && item->type == ITEM_ACTIVE && item->id != COLLECTIBLE_PLAN_C && item->id != COLLECTIBLE_DEATH_CERTIFICATE) + actives.push_back(item->id); + int pick = actives[random_below((int)actives.size())]; + + if (player.itemState != 0 && pick != player.itemState) player.ResetItemState(); + player.wildCardItem = pick; + player.wildCardItemType = WILD_CARD_ACTIVE; + player.wildCardVarData = 0; + UseResult result = player.UseActiveItem({.item = pick, .flags = USE_NOCOSTUME}); + player.AddCostume(g_manager->itemConfig.GetCollectible(pick), true); + if (player.itemState != 0 && isSecondHeld == (player.activeItems[ACTIVE_SLOT_SECONDARY].item != 0)) + player.DischargeActiveItem(ACTIVE_SLOT_PRIMARY, false); + return result; +} + +// A use Panic Button made spends the item only one time in ten with two copies, one in five with three or more. +static bool is_panic_discharge_kept(Entity_Player& player) +{ + constexpr int TWO_COPY_ODDS = 10; + constexpr int MORE_COPY_ODDS = 5; + int copies = player.GetTrinketMultiplier(TRINKET_PANIC_BUTTON); + if (copies < 2) return false; + return player.GetTrinketRNG(TRINKET_PANIC_BUTTON).RandomInt(copies == 2 ? TWO_COPY_ODDS : MORE_COPY_ODDS) != 0; +} + +// Uses a slot's item from the item button: only when charged and payable, else Mine Crafter's barrels go off or Sharp +// Plug may pay health for it. A held use (Spin to Win's spin, a full Breath of Life) skips that. A zero-charge item +// waits out its room effect. The use discharges the slot or removes the item as it asks, and Car Battery uses it +// again. +static void active_slot_use(Entity_Player& player, int slot, int itemStateBefore, const ItemButton& button) { constexpr uint32_t CAR_BATTERY_FLAGS = USE_NOANIM | USE_CARBATTERY | USE_ALLOWWISPSPAWN | USE_CUSTOMVARDATA; + constexpr int SPIN_TO_WIN_START_CHARGE = 16; int item = player.activeItems[slot].item; ItemConfig_Item* config = g_manager->itemConfig.GetCollectible(item); int maxCharge = player.GetActiveMaxCharge(slot); + int charge = player.activeItems[slot].charge; + if (item == COLLECTIBLE_SPIN_TO_WIN && button.isHeldUse && charge >= SPIN_TO_WIN_START_CHARGE) + return spin_to_win_start(player); + if (button.isHeldUse && charge == maxCharge) + { + if (player.HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) return; + player.UseActiveItem({.item = item, .flags = USE_NOANIM | USE_OWNED, .slot = slot}); + player.AddActiveCharge(-1, ACTIVE_SLOT_PRIMARY, false, false, false); + if (player.HasTrinket(TRINKET_BROKEN_REMOTE) && slot == ACTIVE_SLOT_PRIMARY) player.isBrokenRemotePending = true; + return; + } if (!is_active_usable(player, item, slot)) { - if (item == COLLECTIBLE_MINE_CRAFTER) - reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Mine Crafter's barrels)"); + if (item == COLLECTIBLE_MINE_CRAFTER && mine_crafter_detonate(player)) return; if (player.HasCollectible(COLLECTIBLE_SHARP_PLUG) && player.itemState == 0 && config && config->discharge_get() != DISCHARGE_HELD) sharp_plug_pay(player, slot, *config); @@ -1701,29 +2045,33 @@ static void active_slot_use(Entity_Player& player, int slot, int itemStateBefore use_overlay_show(player, item, slot); int varData = player.activeItems[slot].varData; - if (g_game->challenge == CHALLENGE_APRILS_FOOL && slot == ACTIVE_SLOT_PRIMARY) - reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (April's Fool's random actives)"); - if (player.itemState != 0 && item != player.itemState) player.ResetItemState(); - player.wildCardItemType = WILD_CARD_ACTIVE; - player.wildCardItem = item; - player.wildCardVarData = varData; - UseResult result = player.UseActiveItem({.item = item, .flags = USE_OWNED, .slot = slot}); + UseResult result; + if (g_game->challenge == CHALLENGE_APRILS_FOOL && slot == ACTIVE_SLOT_PRIMARY) result = aprils_fool_use(player, slot); + else + { + if (player.itemState != 0 && item != player.itemState) player.ResetItemState(); + player.wildCardItemType = WILD_CARD_ACTIVE; + player.wildCardItem = item; + player.wildCardVarData = varData; + result = player.UseActiveItem({.item = item, .flags = USE_OWNED, .slot = slot}); + } int used = player.activeItems[slot].item; bool isCarBatteryUse = player.HasCollectible(COLLECTIBLE_CAR_BATTERY) && player.itemState == 0 && itemStateBefore == 0 && !result.isRemove && used != 0 && maxCharge > 0 && used != COLLECTIBLE_MOVING_BOX && used != COLLECTIBLE_MR_ME; if (isCarBatteryUse) player.UseActiveItem({.item = used, .flags = CAR_BATTERY_FLAGS, .varData = varData}); - if (result.isDischarge) player.DischargeActiveItem(slot, result.isRemove); + bool isKept = button.isPanic && result.isDischarge && is_panic_discharge_kept(player); + if (result.isDischarge && !isKept) player.DischargeActiveItem(slot, result.isRemove); if (result.isRemove) player.RemoveCollectible(player.activeItems[slot].item, false, slot, true); if (player.HasTrinket(TRINKET_BROKEN_REMOTE) && slot == ACTIVE_SLOT_PRIMARY) player.isBrokenRemotePending = true; } -// The item button pressed for a slot: Notched Axe goes back in hand, a charged item is used. An item state the press -// did not change is put away after. -static void active_trigger(Entity_Player& player, int slot) +// The item button pressed (or a held item's use) for a slot: Notched Axe goes back in hand, Anima Sola's chain and +// Decap Attack's heads are called back, or the slot's item is used. An item state the press did not change is put +// away after. +static void active_trigger(Entity_Player& player, int slot, const ItemButton& button) { - constexpr int SHOOP_DA_WHOOP = 49; constexpr int UNHIDDEN_STATES[] = {0, COLLECTIBLE_PONY, COLLECTIBLE_WHITE_PONY, COLLECTIBLE_BOOMERANG}; int itemStateBefore = player.itemState; @@ -1734,57 +2082,285 @@ static void active_trigger(Entity_Player& player, int slot) player.temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_NOTCHED_AXE, -1); player.AnimateCollectible(COLLECTIBLE_NOTCHED_AXE, "HideItem", "PlayerPickupSparkle"); } - else if (item == COLLECTIBLE_DECAP_ATTACK) - reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Decap Attack's recall)"); - else if (item != 0 && !(item == COLLECTIBLE_ANIMA_SOLA && anima_chain_recall(player))) - active_slot_use(player, slot, itemStateBefore); + else if (item != 0 && !(item == COLLECTIBLE_ANIMA_SOLA && anima_chain_recall(player)) && + !(item == COLLECTIBLE_DECAP_ATTACK && decap_attack_recall(player))) + active_slot_use(player, slot, itemStateBefore, button); if (player.itemState == 0 || player.itemState != itemStateBefore || player.itemStateCooldown >= 1) return; - int costumeItem = player.itemState == SHOOP_DA_WHOOP ? SHOOP_DA_WHOOP : player.activeItems[slot].item; + int costumeItem = player.itemState == COLLECTIBLE_SHOOP_DA_WHOOP ? COLLECTIBLE_SHOOP_DA_WHOOP : player.activeItems[slot].item; player.TryRemoveCollectibleCostume(costumeItem, false); player.ResetItemState(); if (std::ranges::find(UNHIDDEN_STATES, itemStateBefore) == std::end(UNHIDDEN_STATES)) player.AnimateCollectible(itemStateBefore, "HideItem", "PlayerPickupSparkle"); } +// Suplex!'s item hold after its end, as the actives' cooldown after a use. +constexpr int SUPLEX_END_COOLDOWN = 5; + +// Suplex!'s grab put down: with nothing held the dash just ends, else the player leaps up from where it stands +// towards its marked target (or straight up), and its Suplex wisps are spent. +static void suplex_leap(Entity_Player& player) +{ + if (!player.heldEntity) + { + player.cacheFlags |= CACHE_FLYING; + player.suplexState = 0; + player.entityCollisionClass = ENTCOLL_ALL; + player.EvaluateItems(); + player.blinkTime = 1; + player.itemStateCooldown = SUPLEX_END_COOLDOWN; + player.PlayExtraAnimation("HideItem"); + return; + } + + Entity* target = player.markedTarget.get(); + player.suplexTargetPos = target ? target->pos : player.pos; + player.suplexLandPos = player.pos; + player.PlayExtraAnimation(player.suplexState == SUPLEX_SUPER_AIMING ? "SuperLeapUp" : "LeapUp"); + player.suplexState = SUPLEX_LEAPING; + sound_play(SOUND_SUPLEX_JUMP); + if (!player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) return; + for (Entity* entity : entity_query(ENTITY_FAMILIAR, Entity_Familiar::WISP)) + if (entity->subtype == COLLECTIBLE_SUPLEX && static_cast(entity)->player == &player) + entity->Kill(EntityRef()); +} + +// The super leap's landing: a mega blast, a doubled crater, fifteen dust clouds thrown around and a doubled poof. +static void suplex_super_landing(Entity_Player& player) +{ + constexpr int SLAM_DUST_CLOUDS = 15; + constexpr float SLAM_DUST_SPREAD = 360; + constexpr float SLAM_DUST_SPEED_RANGE = 5; + constexpr float SLAM_DUST_SPEED_MIN = 15; + constexpr float SLAM_DUST_FLATTEN = 0.85f; + constexpr float SLAM_DUST_SPIN_RANGE = 10; + constexpr float SLAM_DUST_SPIN_MIN = 2; + constexpr float SLAM_DUST_SCALE_RANGE = 0.6f; + constexpr uint32_t SLAM_DUST_LIFE_RANGE = 40; + constexpr ColorMod SLAM_DUST_COLOR = {{0.45f, 0.45f, 0.46f, 0.75f}, {0, 0, 0, 0}, {0, 0, 0}}; + constexpr float DOUBLE = 2; + Vector at = player.pos; + + auto* blast = static_cast(g_game->Spawn({.position = at, .spawner = &player, .type = ENTITY_EFFECT, + .variant = EFFECT_MAMA_MEGA_EXPLOSION, .seed = Random()})); + blast->targetPosition = at; + blast->Update(); + Entity* crater = g_game->Spawn({.position = at, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_CRATER, .seed = Random()}); + crater->sprite.scale = vector_make(DOUBLE, DOUBLE); + crater->Update(); + for (int i = 0; i < SLAM_DUST_CLOUDS; i++) + { + float angle = ((float)i + random_unit() - HALF) * SLAM_DUST_SPREAD / SLAM_DUST_CLOUDS * DEGREES_TO_RADIANS; + float speed = random_unit() * SLAM_DUST_SPEED_RANGE + SLAM_DUST_SPEED_MIN; + Vector velocity = vector_make(std::cos(angle) * speed, speed * std::sin(angle) * SLAM_DUST_FLATTEN); + auto* dust = static_cast(g_game->Spawn({.position = at, .velocity = velocity, + .type = ENTITY_EFFECT, .variant = EFFECT_DUST_CLOUD, + .seed = Random()})); + float spin = (Random() & 1) ? 1 : -1; + dust->rotation = (random_unit() * SLAM_DUST_SPIN_RANGE + SLAM_DUST_SPIN_MIN) * spin; + float scale = random_unit() * SLAM_DUST_SCALE_RANGE + 1; + dust->sprite.scale = vector_make(scale, scale); + dust->SetTimeout((int)(Random() % SLAM_DUST_LIFE_RANGE + SLAM_DUST_LIFE_RANGE)); + dust->SetColor(SLAM_DUST_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + Entity* poof = g_game->Spawn({.position = at, .spawner = &player, .subType = 1, .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, .seed = Random()}); + poof->sprite.scale = vector_make(DOUBLE, DOUBLE); + poof->sprite.isFlipX = (Random() & 1) == 0; + poof->Update(); +} + +// Suplex!'s landing on the leap's Poof: the slam's sound and look (a shake, a shockwave and its ring, or the super +// leap's blast with six times the damage over twice the reach), the grabbed enemy crushed (a held bomb goes off), the +// slam's crush around, and three Suplex wisps. A landing spot open and reachable from the take-off is kept. +static void suplex_slam(Entity_Player& player) +{ + constexpr float SLAM_DAMAGE_SCALE = 50; + constexpr float SLAM_DAMAGE_MIN = 40; + constexpr float SLAM_VERSUS_DAMAGE = 25; + constexpr float SLAM_RADIUS_SCALE = 25; + constexpr float SLAM_RADIUS_MIN = 20; + constexpr float SUPER_DAMAGE = 6; + constexpr float SUPER_RADIUS = 2; + constexpr int SLAM_SHAKE_FRAMES = 14; + constexpr float SHOCK_AMPLITUDE = 0.04f; + constexpr float SHOCK_SPEED = 0.025f; + constexpr int SHOCK_DURATION = 13; + constexpr float RING_SCALE = 40; + constexpr float RING_BASE = 50; + constexpr float RING_MIN = 70; + constexpr float SLAM_RING_SPEED = 9; + constexpr int SLAM_CRUSH_COUNTDOWN = 30; + constexpr int SUPLEX_WISPS = 3; + float scale = player.playerSpriteScale.x; + float damage = g_game->deathmatchManager.is_active() ? SLAM_VERSUS_DAMAGE : std::max(scale * SLAM_DAMAGE_SCALE, SLAM_DAMAGE_MIN); + float radius = std::max(scale * SLAM_RADIUS_SCALE, SLAM_RADIUS_MIN); + sound_play(SOUND_SUPLEX_LAND); + + if (player.sprite.animState.GetAnimation() != "SuperLeapDown") + { + game_shake_screen(SLAM_SHAKE_FRAMES); + sound_play(SOUND_HELLBOSS_GROUNDPOUND); + shockwave_make(player.pos, SHOCK_AMPLITUDE, SHOCK_SPEED, SHOCK_DURATION); + float ringRadius = std::max(scale * RING_SCALE + RING_BASE, RING_MIN); + auto* ring = static_cast(g_game->Spawn({.position = player.pos, .spawner = &player, + .type = ENTITY_EFFECT, .variant = EFFECT_SHOCKWAVE, + .seed = Random()})); + ring->parent = &player; + ring->SetRadii(player.size, ringRadius); + ring->SetTimeout((int)(ringRadius / SLAM_RING_SPEED)); + } + else + { + damage *= SUPER_DAMAGE; + radius *= SUPER_RADIUS; + sound_play(SOUND_HELLBOSS_GROUNDPOUND); + suplex_super_landing(player); + } + + if (Entity* held = player.heldEntity) + { + held->TakeDamage(damage, DAMAGE_CRUSH, EntityRef(&player), SLAM_CRUSH_COUNTDOWN); + if (held->type == ENTITY_BOMB) + { + static_cast(held)->explosionCountdown = 0; + static_cast(held)->explosionCountdown2 = 0; + held->Update(); + } + } + explosion_damage({.position = player.pos, .source = &player, .damageFlags = DAMAGE_CRUSH, .damage = damage, + .radius = radius, .isLineCheck = false}); + + Room& room = *g_game->room; + uint32_t ground = room.GetGridCollision(room.GetGridIndex(player.pos)); + if (ground == GRIDCOLL_NONE || (player.canFly && ground < GRIDCOLL_WALLS)) + { + PathFinder path(&player); + if (path.HasPathToPos(player.suplexLandPos, false)) player.suplexLandPos = player.pos; + } + if (!player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) return; + for (int i = 0; i < SUPLEX_WISPS; i++) + if (Entity_Familiar* wisp = player.AddWisp(COLLECTIBLE_SUPLEX, player.pos, false, true)) + wisp->targetPosition = player.pos; +} + +// 007d4390 Suplex!'s frame: the player cannot be touched while it leaps (nor blocked by the grid once up), a held +// bomb waits, the aim runs out into the leap (or ends the dash), the leap lands at its target, and the landing slams +// on its Poof, throws the grab on its Hit, draws back to the landing spot and then ends, briefly unhurtable. +void Entity_Player::update_suplex() +{ + constexpr int BOMB_HOLD_COUNTDOWN = 10; + constexpr int SUPLEX_END_INVINCIBILITY = 15; + constexpr float LAND_PULL = 0.3f; + int state = suplexState; + if (state > SUPLEX_DASHING) entityCollisionClass = ENTCOLL_NONE; + if (state > SUPLEX_AIMING) entityGridCollisionClass = GRIDCOLL_NONE; + + bool isGrabbing = state == SUPLEX_AIMING || state == SUPLEX_LEAPING || state == SUPLEX_LANDING; + if (heldEntity && heldEntity->type == ENTITY_BOMB && isGrabbing) + { + auto& bomb = *static_cast(heldEntity); + if (bomb.explosionCountdown < 2) + { + bomb.explosionCountdown = BOMB_HOLD_COUNTDOWN; + bomb.explosionCountdown2 = BOMB_HOLD_COUNTDOWN; + } + } + if (suplexAimCountdown > 0) + { + suplexAimCountdown -= ((int)updateTime - (int)prevUpdateTime) * 2; + if (state == SUPLEX_SUPER_AIMING || (suplexAimCountdown < 1 && state == SUPLEX_AIMING)) + { + suplexAimCountdown = 0; + suplex_leap(*this); + } + else if (suplexAimCountdown < 1) + { + suplexAimCountdown = 0; + if (state == SUPLEX_DASHING) + { + cacheFlags |= CACHE_FLYING; + suplexState = 0; + entityCollisionClass = ENTCOLL_ALL; + EvaluateItems(); + } + } + } + + AnimationState& anim = sprite.animState; + if (suplexState == SUPLEX_LEAPING) + { + if (anim.animData && anim.isPlaying) return; + suplexState = SUPLEX_LANDING; + Teleport(suplexTargetPos, false, false); + if (heldEntity) heldEntity->pos = suplexTargetPos; + PlayExtraAnimation(anim.GetAnimation() == "SuperLeapUp" ? "SuperLeapDown" : "LeapDown"); + return; + } + if (suplexState != SUPLEX_LANDING) return; + + if (anim.animData) + { + if (anim.IsEventTriggered("Poof")) suplex_slam(*this); + if (anim.IsEventTriggered("Hit")) ThrowHeldEntity({}); + if (anim.WasEventTriggered("Hit")) velocity = vector_scale(vector_sub(suplexLandPos, pos), LAND_PULL); + if (anim.isPlaying) return; + } + suplexState = 0; + blinkTime = 1; + itemStateCooldown = SUPLEX_END_COOLDOWN; + entityCollisionClass = ENTCOLL_ALL; + damageCooldown = std::max(damageCooldown, SUPLEX_END_INVINCIBILITY); + cacheFlags |= CACHE_FLYING; + EvaluateItems(); +} + // 00791a40 Reads the item button for an active slot (the first from the frame, the pocket ones from the pocket button): -// Suplex's aim, the items held down, the timed recharges, and a press that uses the slot's item. The bulb trinkets -// reread the stats when the first slot's charge changed. A pending forced use the original keeps is never set. +// Suplex's aim, Panic Button's press, the items held down, the timed recharges, and a press that uses the slot's +// item. The bulb trinkets reread the stats when the first slot's charge changed. A pending forced use the original +// keeps is never set. void Entity_Player::ControlActiveItem(int slot) { if (variant == PLAYER_VARIANT_COOP_BABY || isCoopGhost || IsHologram() || playerType == PLAYER_THESOUL_B) return; ButtonAction action = slot != ACTIVE_SLOT_PRIMARY ? ACTION_PILL_CARD : twin_button_action(*this, TWIN_BUTTON_ITEM); - bool isPressed = input_is_action_pressed(action, controllerIndex, this); - bool isTriggered = input_is_action_triggered(action, controllerIndex, this); + ItemButton button = {.isPressed = input_is_action_pressed(action, controllerIndex, this), + .isTriggered = input_is_action_triggered(action, controllerIndex, this)}; if (is_twin_button_blocked(*this, TWIN_BUTTON_ITEM) || HasEntityFlags(FLAG_FEAR) || hasCurseMistEffect || isCoopGhost) { - isPressed = false; - isTriggered = false; + button.isPressed = false; + button.isTriggered = false; } if (itemStateCooldown != 0 && itemState != 0) return; int chargeBefore = GetTotalActiveCharge(slot); if (itemState == COLLECTIBLE_SUPLEX || suplexState != 0) { - if (suplexState == SUPLEX_AIMING && isTriggered && suplexAimCountdown >= 2) suplexAimCountdown = 1; + if (suplexState == SUPLEX_AIMING && button.isTriggered && suplexAimCountdown >= 2) suplexAimCountdown = 1; return; } bool isInterpolating = HasEntityFlags(FLAG_INTERPOLATION_UPDATE); int item = activeItems[slot].item; - if (slot == ACTIVE_SLOT_PRIMARY && !isPressed && !isInterpolating && HasTrinket(TRINKET_PANIC_BUTTON) && item != 0) - reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Panic Button)"); - if (item == COLLECTIBLE_BREATH_OF_LIFE || item == COLLECTIBLE_SPIN_TO_WIN) - reconstruction_missing("Entity_Player::ControlActiveItem 00791a40 (Breath of Life and Spin to Win held down)"); - if (item == COLLECTIBLE_BAG_OF_CRAFTING && slot == ACTIVE_SLOT_POCKET && !isInterpolating) + bool isPanicChecked = slot == ACTIVE_SLOT_PRIMARY && !button.isPressed && !isInterpolating && + HasTrinket(TRINKET_PANIC_BUTTON) && item != 0; + if (isPanicChecked && is_panic_pressed(*this)) { - if (itemState == COLLECTIBLE_BAG_OF_CRAFTING && AreControlsEnabled() && isPressed && bagOfCraftingOutput != 0) + button.isPanic = true; + button.isPressed = true; + button.isTriggered = true; + } + if (item == COLLECTIBLE_BREATH_OF_LIFE) breath_of_life_control(*this, slot, button); + else if (item == COLLECTIBLE_SPIN_TO_WIN) spin_to_win_control(*this, slot, button); + else if (item == COLLECTIBLE_BAG_OF_CRAFTING && slot == ACTIVE_SLOT_POCKET && !isInterpolating) + { + if (itemState == COLLECTIBLE_BAG_OF_CRAFTING && AreControlsEnabled() && button.isPressed && bagOfCraftingOutput != 0) bag_of_crafting_craft(*this); else bagOfCraftingHoldFrames = 0; } if (slot == ACTIVE_SLOT_PRIMARY && !isInterpolating) timed_items_recharge(*this); - if (AreControlsEnabled() && isTriggered) active_trigger(*this, slot); + if (AreControlsEnabled() && (button.isTriggered || button.isHeldUse)) active_trigger(*this, slot, button); + if (button.isReleased) spin_to_win_let_go(*this, slot); if (slot == ACTIVE_SLOT_PRIMARY) bulbs_update(*this, chargeBefore, slot); } diff --git a/src/entity_player_actives_rebirth.cpp b/src/entity_player_actives_rebirth.cpp index d4ffef4..36b5f35 100644 --- a/src/entity_player_actives_rebirth.cpp +++ b/src/entity_player_actives_rebirth.cpp @@ -1103,7 +1103,7 @@ static void converter_use(ItemUse& use) sound_play(SOUND_CONVERTER); } // FUN_0067d9b0 The blood look of a tear variant (Judas' Birthright's tears), or the same one when it has none. -static int tear_variant_blood(int variant) +int tear_variant_blood(int variant) { switch (variant) { diff --git a/src/entity_player_actives_repentance.cpp b/src/entity_player_actives_repentance.cpp index fcc5213..0a7dbf2 100644 --- a/src/entity_player_actives_repentance.cpp +++ b/src/entity_player_actives_repentance.cpp @@ -529,18 +529,6 @@ static void urn_of_souls_use(ItemUse& use) use.isAddEffect = false; } -// The kind of clot a heart turns into (Lua's ClotSubType), by the heart Sumptorium takes. -enum ClotKind : int -{ - CLOT_RED, - CLOT_SOUL, - CLOT_BLACK, - CLOT_ETERNAL, - CLOT_GOLD, - CLOT_BONE, - CLOT_ROTTEN -}; - // The heart SpawnClot takes from the soul side: a bone heart, the last soul heart (all of them at no health), or a // black heart's half, and the clot it makes. static ClotKind clot_soul_take(Entity_Player& player, bool isFromItem) diff --git a/src/entity_player_bombs.cpp b/src/entity_player_bombs.cpp index 83cae8d..f4f94f1 100644 --- a/src/entity_player_bombs.cpp +++ b/src/entity_player_bombs.cpp @@ -47,8 +47,6 @@ constexpr float ROCKET_FAN_REACH = 80; constexpr int SHORT_FUSE = 22; constexpr std::array SHORT_FUSE_DAMAGE = {15.000001f, 30.000002f, 50}; constexpr int BOMBS_MAX = 99; -constexpr int CONSUMABLE_BOMBS = 1 << 2; -constexpr int CONSUMABLE_GIGA_BOMBS = 1 << 6; constexpr int SOUND_GLITTER_FUSE = 867; constexpr int PLACE_SOUND_DELAY = 4; diff --git a/src/entity_player_cards.cpp b/src/entity_player_cards.cpp index 370b532..6470a1d 100644 --- a/src/entity_player_cards.cpp +++ b/src/entity_player_cards.cpp @@ -410,7 +410,7 @@ static PocketUseEnd sun_use(PocketUse& use) { float damage = (use.isDoubled ? 2 : 1) * SUN_DAMAGE; - for (Entity* entity : g_game->room->GetEntities()->updateEL) + for (Entity* entity : entities_live(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(); @@ -1087,7 +1087,7 @@ static PocketUseEnd black_rune_use(PocketUse& use) card_poof_spawn(vector_add(player.pos, vector_make(0, BLACK_RUNE_POOF_DROP)), nullptr); } - for (Entity* entity : g_game->room->GetEntities()->updateEL) + for (Entity* entity : entities_live(g_game->room->GetEntities()->updateEL)) { auto* pickup = entity->type == ENTITY_PICKUP ? static_cast(entity) : nullptr; if (!pickup || pickup->IsShopItem() || pickup->isDead || !pickup->CanReroll()) continue; diff --git a/src/entity_player_characters.cpp b/src/entity_player_characters.cpp index 26653e3..136b039 100644 --- a/src/entity_player_characters.cpp +++ b/src/entity_player_characters.cpp @@ -23,7 +23,6 @@ constexpr int CHARGE_STORE_MAX = 99; constexpr int SOUL_CHARGE_CONSUMABLE = 0x20; constexpr int BLOOD_CHARGE_CONSUMABLE = 0x100; -constexpr int BLOOD_CLOT_SUBTYPE_SPENT = 7; constexpr int WHORE_OF_BABYLON_RED_HEARTS = 1; constexpr int EVE_WHORE_OF_BABYLON_RED_HEARTS = 2; constexpr int DEATHMATCH_WHORE_RED_HEARTS = 16; diff --git a/src/entity_player_characters.h b/src/entity_player_characters.h index 66ae580..89a0d44 100644 --- a/src/entity_player_characters.h +++ b/src/entity_player_characters.h @@ -4,6 +4,7 @@ #include constexpr int GIANTBOOK_WHORE_OF_BABYLON = 3; +constexpr int BLOOD_CLOT_SUBTYPE_SPENT = 7; // Tainted ???'s poop spells, as the queue and the HUD's frames hold them (REPENTOGON's PoopSpellType). enum PoopSpell : char diff --git a/src/entity_player_collectibles.cpp b/src/entity_player_collectibles.cpp index c6d2e38..7884e90 100644 --- a/src/entity_player_collectibles.cpp +++ b/src/entity_player_collectibles.cpp @@ -1,8 +1,10 @@ #include "entity_player.h" #include "entity_player_passives.h" #include "active_items.h" +#include "boss_ai.h" #include "entity_config.h" #include "entity_effect.h" +#include "entity_familiar.h" #include "entity_pickup.h" #include "game.h" #include "hud.h" @@ -276,13 +278,32 @@ static void collectible_effect_end(Entity_Player& player, int collectibleId) } } +// Spin to Win's spin over: its costume comes off, the player's familiars come back to their own orbits, and its +// wisps go out. +static void spin_to_win_end(Entity_Player& player, ItemConfig_Item* spin) +{ + player.RemoveCostume(spin); + for (Entity* entity : g_game->room->entityList.updateEL) + { + if (entity->type != ENTITY_FAMILIAR || static_cast(entity)->player != &player) continue; + entity->ClearEntityFlags(FLAG_CONFUSION); + entity->size = entity->config->collisionRadius; + } + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) + for (Entity* wisp : entity_query(ENTITY_FAMILIAR, Entity_Familiar::WISP)) + if (wisp->subtype == COLLECTIBLE_SPIN_TO_WIN && static_cast(wisp)->player == &player) + wisp->Kill(EntityRef()); + player.EvaluateItems(); +} + // 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, 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. +// costume comes off (Spin to Win's spin ends). A trinket's effect takes its costume off (Faded Polaroid's fading +// colour too). The other 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}; + constexpr int NULL_EFFECTS_WITH_ENDS[] = {62, 63, 66, 67, 70, 71, 101}; + if (item->type == ITEM_NULL && item->id == NULLITEM_SPIN_TO_WIN) return spin_to_win_end(*this, item); 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) diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp index 969b4b5..de46953 100644 --- a/src/entity_player_damage.cpp +++ b/src/entity_player_damage.cpp @@ -1,6 +1,9 @@ +#include "boss_ai.h" #include "entity_bomb.h" +#include "entity_combat.h" #include "entity_effect_combat.h" #include "entity_familiar.h" +#include "entity_laser.h" #include "entity_pickup.h" #include "entity_npc.h" #include "entity_player.h" @@ -9,12 +12,14 @@ #include "entity_player_trinkets.h" #include "entity_tear.h" #include "game.h" +#include "grid_entity_trap_door.h" #include "level.h" #include "log.h" #include "lua_engine.h" #include "manager.h" #include "npc_ai.h" #include "npc_basement.h" +#include "persistent_game_data.h" #include "room.h" #include "room_grid.h" #include @@ -42,7 +47,6 @@ constexpr int WHITE_FIRE_VARIANT = 4; constexpr int EFFECT_SELF_DAMAGE = 19; constexpr int EFFECT_POISON_CLOUD = 123; constexpr int ITEM_STATE_HOLD_STILL = 47; -constexpr int ENEMY_TYPE_LAST = 999; constexpr int BABY_GHOST = 59; constexpr int BABY_HALO = 24; constexpr int BABY_SHIELD = 11; @@ -63,8 +67,6 @@ constexpr int SOUND_BOSS_DELAY_RANDOM = 130; constexpr int SOUND_BOSS_DELAY_MIN = 50; constexpr int SOUND_FRAME_DELAY = 2; -constexpr uint64_t DAMAGE_INVINCIBLE_IGNORED = 1ull << 13; -constexpr uint64_t DAMAGE_IGNORED = 1ull << 34; // Tainted Jacob turned ghost by Dark Esau cannot be hurt for 90 frames. constexpr int JACOB_GHOST_COOLDOWN = 90; constexpr uint64_t DAMAGE_NO_HURT_EFFECTS = 0x100d0400; @@ -75,8 +77,6 @@ constexpr int LAST_DAMAGE_STAGE_MAX = 13; constexpr int HURT_FRAMES_PER_HEART = 60; constexpr int HURT_HEARTS_MAX = 2; constexpr int HIT_COOLDOWN = 4; -constexpr uint32_t DEBUG_INFINITE_HP = 1 << 2; -constexpr uint32_t DEBUG_DAMAGE_VALUES = 1 << 6; constexpr uint32_t STAGE_FULL_HEART_DAMAGE = 7; constexpr int MASSIVE_DAMAGE = 24; constexpr int EVIL_CHARM_GRACE_FRAMES = 30; @@ -131,7 +131,7 @@ constexpr float GNAWED_LEAF_MASS = 1000; constexpr int BREATH_OF_LIFE_WINDOW = 5; // Whether a hit passes the player by: its own self damage, friendly sources, another's Dark Esau, a dead player, -// Isaac's Heart, Evil Charm's hazards, and a co-op baby still appearing. +// Isaac's Heart, Evil Charm's hazards, a co-op baby still appearing, and a Visage chain whose end holds the player. static bool is_damage_ignored(Entity_Player& player, const EntityRef& source, uint64_t damageFlags) { Game& game = *g_game; @@ -156,27 +156,57 @@ static bool is_damage_ignored(Entity_Player& player, const EntityRef& source, ui bool isAppearing = player.sprite.IsPlaying("Appear") || player.sprite.IsPlaying("Glitch"); if ((player.variant == PLAYER_VARIANT_COOP_BABY || player.isCoopGhost) && isAppearing) return true; - if (source.type == ENTITY_VISAGE && source.variant == VISAGE_CHAIN && entity) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a Visage chain)"); - return false; + if (source.type != ENTITY_VISAGE || source.variant != VISAGE_CHAIN || !entity) return false; + Entity* link = entity; + while (link->child && link->child->type == ENTITY_VISAGE && link->child->variant == VISAGE_CHAIN) link = link->child.get(); + return link->target.get() == &player; } -// Whether a Bishop the player charmed stands in the room to take the hit (find_nearest_enemy 004e7d10). -static bool is_bishop_present() +// A charmed Bishop takes the hit for the player: it is hurt instead and its shield flashes on the player. Whether a +// Bishop took it. +static bool bishop_shield_block(Entity_Player& player) { - return std::ranges::any_of(g_game->room->entityList.updateEL, [](Entity* entity) - { return entity->type == ENTITY_BISHOP && entity->HasEntityFlags(FLAG_CHARM); }); + constexpr float BISHOP_HIT_DAMAGE = 3.5f; + constexpr int BISHOP_HIT_COUNTDOWN = 15; + constexpr int BISHOP_SOUND_DELAY = 10; + constexpr float BISHOP_SHIELD_RISE = -24; + Entity* bishop = bishop_nearest_find(player.pos, true); + if (!bishop) return false; + + bishop->TakeDamage(BISHOP_HIT_DAMAGE, DAMAGE_COUNTDOWN, EntityRef(), BISHOP_HIT_COUNTDOWN); + int sound = SOUND_BISHOP_HIT; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.frameDelay = BISHOP_SOUND_DELAY}); + if (player.hitEffect) player.hitEffect->Remove(); + auto* shield = static_cast(g_game->Spawn({.position = player.pos, .spawner = bishop, + .type = ENTITY_EFFECT, .variant = EFFECT_BISHOP_SHIELD, + .seed = Random()})); + shield->parent = bishop; + shield->target = &player; + shield->parentOffset = vector_make(0, BISHOP_SHIELD_RISE); + shield->posOffset = vector_make(player.posOffset.x, player.posOffset.y + BISHOP_SHIELD_RISE); + shield->Update(); + player.hitEffect = shield; + return true; } -// Whether a wisp of the player's could take the hit (FUN_007c7b10). -static bool is_wisp_shield_present(Entity_Player& player) +// (007c7b10) Dull Razor's wisps shield the player: for each live one, one hit in five (not a fake or red heart one) +// is taken by the wisp, which dies, and the player stays unhurtable for a moment. Whether a wisp took it. +static bool wisp_shield_block(Entity_Player& player, uint64_t damageFlags) { - return std::ranges::any_of(g_game->room->entityList.updateEL, [&](Entity* entity) + constexpr int SHIELD_ODDS = 5; + constexpr int SHIELD_COOLDOWN = 15; + for (Entity* entity : entity_query(ENTITY_FAMILIAR, Entity_Familiar::WISP)) { - return !entity->isDead && entity->IsFamiliar() && entity->variant == Entity_Familiar::WISP && - entity->subtype == COLLECTIBLE_DULL_RAZOR && - static_cast(entity)->player == &player; - }); + auto& wisp = *static_cast(entity); + bool isShield = !wisp.isDead && wisp.player == &player && wisp.subtype == COLLECTIBLE_DULL_RAZOR && + !(damageFlags & (DAMAGE_FAKE | DAMAGE_RED_HEARTS)); + if (!isShield || Random() % SHIELD_ODDS != 0) continue; + player.damageCooldown = std::max(player.damageCooldown, SHIELD_COOLDOWN); + wisp.Kill(EntityRef()); + return true; + } + return false; } // Plays one of the player's sounds at a volume and pitch, unless the seeds swap it for a fart. @@ -230,7 +260,7 @@ static bool jelly_belly_bounce(Entity_Player& player, const EntityRef& source, u { if (!player.HasCollectible(COLLECTIBLE_JELLY_BELLY) || (damageFlags & (DAMAGE_NO_MODIFIERS | DAMAGE_FAKE))) return false; Entity* hitter = source.entity; - bool isLiving = hitter && ((source.type >= ENTITY_FIRST_ENEMY && source.type <= ENEMY_TYPE_LAST) || + bool isLiving = hitter && ((source.type >= ENTITY_FIRST_ENEMY && source.type <= ENTITY_LAST_ENEMY) || source.type == ENTITY_PROJECTILE || source.type == ENTITY_PLAYER); if (random_below(JELLY_BELLY_ODDS) != 0 || !isLiving) return false; @@ -292,14 +322,13 @@ static void walnut_crack(Entity_Player& player) // The items that answer a hit before it lands, in the original's order: Pyromaniac heals from explosions and shrugs // off fire, Host Hat guards explosions and sometimes fires back at shots, Dr. Fetus and the bone with Ipecac ignore // their own blasts, Hot Bombs fire, the bomb baby explosions, Jelly Belly bounces, Metal Plate returns shots and Cone -// Head shrugs off a fifth of the hits, after Walnut cracks. Whether the hit is stopped. A charmed Bishop's shield -// stops the game. +// Head shrugs off a fifth of the hits, after a charmed Bishop's shield and Walnut's crack. Whether the hit is stopped. static bool damage_reactions_check(Entity_Player& player, const EntityRef& source, uint64_t damageFlags) { bool isExplosion = damageFlags & DAMAGE_EXPLOSION; bool isFire = damageFlags & DAMAGE_FIRE; - if (is_bishop_present()) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a charmed Bishop's shield)"); + if (bishop_shield_block(player)) return true; if (player.HasTrinket(TRINKET_WALNUT) && isExplosion) walnut_crack(player); if (player.HasCollectible(COLLECTIBLE_PYROMANIAC) && isFire) return true; if (player.HasCollectible(COLLECTIBLE_PYROMANIAC) && isExplosion) @@ -683,6 +712,134 @@ static bool is_siren_charm_fresh(const EntityRef& source) return frames >= 1 && frames <= SIREN_CHARM_SPARE_FRAMES; } +// A hit that spawns a fly gives one blue fly to the player behind the hit (its source or the source's spawner), else +// to the player nearest the one hit. The fly goes after the player hit. +static void hit_fly_spawn(Entity_Player& player, const EntityRef& source) +{ + Entity* owner = source.entity; + if (owner && !owner->is_player()) owner = owner->spawnerEntity.get(); + if (!owner || !owner->is_player()) owner = game_nearest_player(player.pos); + static_cast(owner)->AddBlueFlies(1, owner->pos, &player); +} + +// Greed and the coin thieves (all hits in Pay to Play) knock a coin out of the player, then one to three more fly +// out as pennies. +static void coins_drop(Entity_Player& player) +{ + constexpr int COIN_DROP_RANGE = 3; + constexpr float COIN_DROP_SPEED_RANGE = 5; + constexpr float COIN_DROP_SPEED_MIN = 2; + player.AddCoins(-1); + int dropped = std::min(random_below(COIN_DROP_RANGE) + 1, player.numCoins); + for (int i = 0; i < dropped; i++) + { + uint32_t seed = Random(); + Vector direction = random_direction(); + Vector velocity = vector_scale(direction, random_unit() * COIN_DROP_SPEED_RANGE + COIN_DROP_SPEED_MIN); + g_game->Spawn({.position = player.pos, .velocity = velocity, .spawner = &player, .subType = COIN_PENNY, + .type = ENTITY_PICKUP, .variant = PICKUP_COIN, .seed = seed}); + } + player.AddCoins(-dropped); +} + +// The co-op babies that answer a hit: the fart baby farts (or only blows), the bomb baby explodes and the book baby +// rolls the room with the D6. +static void coop_baby_hit(Entity_Player& player) +{ + constexpr float BABY_FART_RADIUS = 85; + constexpr float BABY_BEAN_RADIUS = 120; + constexpr float BABY_BOMB_DAMAGE = 40; + constexpr float BABY_BOMB_RADIUS = 60; + switch (player.babySkin) + { + case BABY_FART: + { + bool isBlowOnly = random_below(2) != 0; + if (!isBlowOnly) game_fart({.position = player.pos, .source = &player, .radius = BABY_FART_RADIUS}); + game_butter_bean_fart({.position = player.pos, .source = &player, .radius = BABY_BEAN_RADIUS, + .isShowEffect = isBlowOnly, .isSuperKnockback = false}); + break; + } + case BABY_BOMB: + explosion_damage({.position = player.pos, .source = &player, .damage = BABY_BOMB_DAMAGE, + .radius = BABY_BOMB_RADIUS}); + g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, + .seed = Random()})->Update(); + break; + case BABY_BOOK: + player.UseActiveItem({.item = COLLECTIBLE_D6, .flags = USE_NOANIM}); + break; + } +} + +// Marbles: a hit holding a trinket swallows it one time in ten (always in Pica Run), as by the Smelter. +static void marbles_swallow(Entity_Player& player) +{ + constexpr int MARBLES_ODDS = 10; + bool isRolled = player.GetCollectibleRNG(COLLECTIBLE_MARBLES).RandomInt(MARBLES_ODDS) == 0; + if (!isRolled && g_game->challenge != CHALLENGE_PICA_RUN) return; + + player.FlushQueueItem(); + player.UseActiveItem({.item = COLLECTIBLE_SMELTER, .flags = USE_NOANIM}); + sound_play(SOUND_VAMP_GULP); +} + +// Heartbreak: a killing hit breaks a heart container (one for coin health, else two) and sets off the Necronomicon. +// True when a heart is left to save the player with. +static bool heartbreak_break(Entity_Player& player) +{ + player.AddBrokenHearts(player.GetHealthType() == HEALTH_COIN ? 1 : 2); + player.UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM | USE_ALLOWNONMAIN}); + sound_play(SOUND_BLACK_POOF); + return player.GetHeartLimit(false) >= 1; +} + +// Monkey Paw: a black heart per copy near the player on its last heart, three times before the paw is spent. +static void monkey_paw_grant(Entity_Player& player) +{ + for (int i = player.GetTrinketMultiplier(TRINKET_MONKEY_PAW); i > 0; i--) + { + uint32_t seed = Random(); + Vector spot = room_free_pickup_position_find({.position = player.pos, .step = PICKUP_SPOT_STEP}); + g_game->Spawn({.position = spot, .spawner = &player, .subType = HEART_BLACK, .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, .seed = seed}); + } + if (--player.monkeyPawCounter >= 1) return; + player.TryRemoveTrinket(TRINKET_MONKEY_PAW); + player.monkeyPawCounter = MONKEY_PAW_USES; +} + +// Astral Projection's start: the room pauses, the body stays behind as a ghost corpse and the spirit goes on for 150 +// frames, with a bloom, a white flash fading back to the room's colours, a shockwave and a heartbeat. +static void astral_projection_start(Entity_Player& player) +{ + constexpr int ASTRAL_PAUSE = 60; + constexpr int ASTRAL_ROOM_FRAMES = 150; + constexpr int ASTRAL_BLOOM = 10; + constexpr float ASTRAL_FLASH_RATE = 0.015f; + constexpr float ASTRAL_FADE_RATE = 0.008f; + constexpr float ASTRAL_SHOCK_AMPLITUDE = 0.05f; + constexpr float ASTRAL_SHOCK_SPEED = 0.07f; + constexpr int ASTRAL_SHOCK_DURATION = 12; + constexpr ColorModState ASTRAL_FLASH = {1, 1, 1, 1, 0, 1}; + Game& game = *g_game; + Room& room = *game.room; + room.SetPauseTimer(ASTRAL_PAUSE); + player.spawn_ghost_corpse(); + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_ASTRAL_PROJECTION, true, 1); + TemporaryEffect roomEffect(g_manager->itemConfig.GetCollectible(COLLECTIBLE_ASTRAL_PROJECTION)); + roomEffect.cooldown = ASTRAL_ROOM_FRAMES; + room.temporaryEffects.AddEffect(roomEffect, true, 1); + game.bloomDuration = ASTRAL_BLOOM; + game.bloomTimer = ASTRAL_BLOOM; + game.bloomStrength = 1; + game.SetColorModifier(ASTRAL_FLASH, false, ASTRAL_FLASH_RATE); + game.SetColorModifier(room.get_color_modifier(), true, ASTRAL_FADE_RATE); + shockwave_make(player.pos, ASTRAL_SHOCK_AMPLITUDE, ASTRAL_SHOCK_SPEED, ASTRAL_SHOCK_DURATION); + sound_play(SOUND_HEARTBEAT); + player.damageCooldown += damage_cooldown_scale(ASTRAL_PAUSE); +} + // 007729d0 The player takes a hit: the hit is ignored or turned by many items, then costs its hearts, plays the hurt // grunt and the Hit animation, starts the invincibility frames, and kills the player out of hearts. True when it hurt. bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown) @@ -696,12 +853,16 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR return twin->TakeDamage(damage, damageFlags, source, damageCountdown); } if (is_siren_charm_fresh(source)) return false; - if (is_wisp_shield_present(*this)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (wisp shields)"); + if (wisp_shield_block(*this, damageFlags)) return false; if (source.type == ENTITY_FIREPLACE && source.variant == WHITE_FIRE_VARIANT) { bool isGhost = playerType == PLAYER_THELOST || playerType == PLAYER_THELOST_B || playerType == PLAYER_THESOUL_B; if (isGhost || HasInstantDeathCurse() || isDead) return false; - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (white fire's lost curse)"); + spawn_ghost_corpse(); + if (!temporaryEffects.HasNullEffect(NULLITEM_LOST_CURSE)) game.playerManager.add_lost_curse(NULLITEM_LOST_CURSE); + sound_play(SOUND_FIREDEATH_HISS); + // The controllers' rumble is not wired here. + return true; } if (IsHologram() || is_damage_ignored(*this, source, damageFlags)) return false; if (damage_reactions_check(*this, source, damageFlags)) return false; @@ -727,7 +888,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR int amount = damage_amount_get(*this, damage, damageFlags, source); bool isFake = damageFlags & DAMAGE_FAKE; if (isFake) amount = 0; - if (damageFlags & DAMAGE_SPAWN_FLY) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a fly for the hit)"); + if (damageFlags & DAMAGE_SPAWN_FLY) hit_fly_spawn(*this, source); bool isInvincibleNow = HasInvincibility(damageFlags, source); bool isPenalized = !(damageFlags & DAMAGE_UNPENALIZED); @@ -776,7 +937,7 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR roomDamageTaken += amount; if (playerType != PLAYER_MAGDALENE_B || !is_maggy_draining(*this)) totalDamageTaken += amount; } - if (source.type >= ENTITY_FIRST_ENEMY && source.type <= ENEMY_TYPE_LAST) + if (source.type >= ENTITY_FIRST_ENEMY && source.type <= ENTITY_LAST_ENEMY) bestiary_count_add(g_manager->persistentGameData.bestiary.hits, source.type, source.variant); if (game.debugFlags & DEBUG_DAMAGE_VALUES) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (spawn_debug_damage_text)"); @@ -786,12 +947,10 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR bool isThief = is_listed(COIN_THIEF_TYPES, source.type) || source.spawnerType == ULTRA_GREED || source.spawnerType == ULTRA_GREED_DOOR || (source.type == ENTITY_PROJECTILE && is_listed(COIN_SHOOTER_TYPES, source.spawnerType)); - if ((isThief || game.challenge == CHALLENGE_PAY_TO_PLAY) && numCoins > 0) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (dropping coins to Greed)"); - if (variant == PLAYER_VARIANT_COOP_BABY && (babySkin == BABY_FART || babySkin == BABY_BOMB || babySkin == BABY_BOOK)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the co-op babies that answer hits)"); - if (HasCollectible(COLLECTIBLE_MARBLES) && (trinkets[0] != 0 || queuedItem.item)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Marbles)"); + if ((isThief || game.challenge == CHALLENGE_PAY_TO_PLAY) && numCoins > 0) coins_drop(*this); + if (variant == PLAYER_VARIANT_COOP_BABY) coop_baby_hit(*this); + bool isTrinketQueued = queuedItem.item && queuedItem.item->type == ITEM_TRINKET; + if (HasCollectible(COLLECTIBLE_MARBLES) && (trinkets[0] != 0 || isTrinketQueued)) marbles_swallow(*this); float pitch = get_voice_pitch(); int grunt = SOUND_ISAAC_HURT_GRUNT; @@ -828,8 +987,8 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR if ((redHearts < 1 && soulHearts < 1 && boneHearts < 1) || isInstantDeath) { - if (HasCollectible(COLLECTIBLE_HEARTBREAK)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Heartbreak)"); - if (damageFlags & DAMAGE_NOKILL) TryPreventDeath(); + bool isHeartbreakSaved = HasCollectible(COLLECTIBLE_HEARTBREAK) && heartbreak_break(*this); + if (isHeartbreakSaved || (damageFlags & DAMAGE_NOKILL)) TryPreventDeath(); else { if (isInstantDeath) @@ -865,13 +1024,12 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR { last_heart_items_trigger(*this, damageFlags); bool isLastHeart = soulHearts < 1 || (redHearts < 1 && soulHearts == scale_for_hard_difficulty(1)); - if (isLastHeart && HasTrinket(TRINKET_MONKEY_PAW) && variant == PLAYER_VARIANT_PLAYER) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Monkey Paw)"); + if (isLastHeart && HasTrinket(TRINKET_MONKEY_PAW) && variant == PLAYER_VARIANT_PLAYER) monkey_paw_grant(*this); } 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 (isAstral) astral_projection_start(*this); blind_rage_finger_bone_hit(*this); if (isPenalized && HasCollectible(COLLECTIBLE_GLASS_CANNON)) glass_cannon_break(*this); @@ -889,25 +1047,30 @@ bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityR if (damageCooldown > 0 && !isDead && twin && twin->damageCooldown < damageCooldown && !twin->isDead) twin->damageCooldown = damageCooldown; if (HasTrinket(TRINKET_SWALLOWED_M80) && !(damageFlags & DAMAGE_NO_PENALTIES)) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Swallowed M80)"); + { + int odds = std::max(1, 3 - GetTrinketMultiplier(TRINKET_SWALLOWED_M80)); + if (GetTrinketRNG(TRINKET_SWALLOWED_M80).RandomInt(odds) == 0) + UseActiveItem({.item = COLLECTIBLE_KAMIKAZE, .flags = USE_NOANIM | USE_NOCOSTUME | USE_ALLOWNONMAIN}); + } bool isGlitching = isPlayingExtraAnimation && sprite.IsPlaying("Glitch"); if (!isDead && playerType == PLAYER_EDEN_B && isPenalized && !isGlitching) tainted_eden_glitch(*this); return true; } -// Counts the player's death in the bestiary of the enemy behind the hit. Dying to one's own Ipecac unlocks an -// achievement that is not written yet. +// Counts the player's death in the bestiary of the enemy behind the hit. Dying to an explosive poison tear (Ipecac) +// unlocks Lil Spewer. void Entity_Player::death_count(const EntityRef& source, uint64_t damageFlags) { PersistentGameData_Bestiary& bestiary = g_manager->persistentGameData.bestiary; - if (source.type >= ENTITY_FIRST_ENEMY && source.type <= ENEMY_TYPE_LAST) + if (source.type >= ENTITY_FIRST_ENEMY && source.type <= ENTITY_LAST_ENEMY) bestiary_count_add(bestiary.deaths, source.type, source.variant); - else if (source.spawnerType >= ENTITY_FIRST_ENEMY && source.spawnerType <= ENEMY_TYPE_LAST) + else if (source.spawnerType >= ENTITY_FIRST_ENEMY && source.spawnerType <= ENTITY_LAST_ENEMY) bestiary_count_add(bestiary.deaths, source.spawnerType, (int)source.spawnerVariant); - if ((damageFlags & DAMAGE_EXPLOSION) && source.type == ENTITY_TEAR && source.entity) - reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the achievement for dying to Ipecac)"); + if (!(damageFlags & DAMAGE_EXPLOSION) || source.type != ENTITY_TEAR || !source.entity) return; + TearFlags& tearFlags = static_cast(source.entity)->tearFlags; + if (tearFlags[TEAR_EXPLOSIVE] && tearFlags[TEAR_POISON]) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_LIL_SPEWER); } // 0060d090 Ends the invincibility frames. @@ -960,7 +1123,7 @@ bool Entity_Player::IsNullItemCostumeVisible(int nullItemID, int playerSpriteLay // donation hurt. bool Entity_Player::HasInvincibility(uint64_t damageFlags, const EntityRef& source) { - if (damageFlags & DAMAGE_INVINCIBLE_IGNORED) return false; + if (damageFlags & DAMAGE_INVINCIBLE) return false; TemporaryEffects& effects = temporaryEffects; bool isRedHit = damageFlags & DAMAGE_RED_HEARTS; @@ -1036,15 +1199,67 @@ float Entity_Player::local_volume_get() return (float)g_manager->optionsConfig.onlinePlayerVolume * REMOTE_VOLUME_SCALE; } -// 007d1c10 Breath of Life's holy light when the player is hit as it runs out, not written yet. True when it shines. +// 007d1c10 Breath of Life's answer to a hit in its first frames of invincibility: four holy beams strike around the +// player and it stays unhurtable for 30 frames more (as Book of Shadows), or with Book of Belial the Necronomicon +// goes off and the dark spell lasts. With the Book of Virtues its wisps are topped up to four. True when it answered. uint32_t Entity_Player::play_hurt_effects() { + constexpr int BREATH_BEAMS = 4; + constexpr float BREATH_BEAM_TURN = 90; + constexpr int BREATH_BEAM_TIMEOUT = 30; + constexpr float BREATH_BEAM_RISE = -12; + constexpr float BREATH_BEAM_DAMAGE = 12; + constexpr float BREATH_BEAM_DEPTH = 3000; + constexpr float LAST_BREATH_BEAM_DEPTH = -10; + constexpr int SHADOWS_FRAMES = 30; + constexpr int SHADOWS_LONG = 149; + constexpr int BELIAL_FRAMES = 150; + constexpr int BELIAL_COUNT = 20; + constexpr int BREATH_WISPS = 4; + constexpr ColorMod BREATH_BEAM_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; TemporaryEffect* effect = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE); bool isBlocked = damageCooldown > 0 && !HasEntityFlags(FLAG_NO_DAMAGE_BLINK); if (isBlocked || !effect || effect->count != 2) return 0; if (effect->cooldown < g_manager->itemConfig.GetCollectible(COLLECTIBLE_BREATH_OF_LIFE)->maxCooldown - BREATH_OF_LIFE_WINDOW) return 0; - reconstruction_missing("Entity_Player::play_hurt_effects 007d1c10 (Breath of Life)"); + + temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE, 1); + if (!HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE)) + { + for (int i = 0; i < BREATH_BEAMS; i++) + { + Entity_Laser* beam = Entity_Laser::ShootAngle({.position = pos, .posOffset = vector_make(0, BREATH_BEAM_RISE), + .source = this, .angleDegrees = (float)i * BREATH_BEAM_TURN, + .timeout = BREATH_BEAM_TIMEOUT, .variant = LASER_LIGHT_BEAM}); + beam->SetCollisionDamage(BREATH_BEAM_DAMAGE); + beam->SetColor(BREATH_BEAM_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + beam->isDisableFollowParent = true; + beam->renderDepthOffset = i == BREATH_BEAMS - 1 ? LAST_BREATH_BEAM_DEPTH : BREATH_BEAM_DEPTH; + } + TemporaryEffect* shadows = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_BOOK_OF_SHADOWS); + if (!shadows || shadows->cooldown <= SHADOWS_LONG) + { + TemporaryEffect shield(g_manager->itemConfig.GetCollectible(COLLECTIBLE_BOOK_OF_SHADOWS)); + shield.cooldown = SHADOWS_FRAMES; + temporaryEffects.AddEffect(shield, true, 1); + } + } + else + { + UseActiveItem({.item = COLLECTIBLE_NECRONOMICON, .flags = USE_NOANIM | USE_ALLOWNONMAIN}); + sound_play(SOUND_BLACK_POOF); + sound_play(SOUND_DEVIL_CARD); + TemporaryEffect spell(g_manager->itemConfig.GetNullItem(NULLITEM_DARK_ARTS)); + spell.cooldown = BELIAL_FRAMES; + temporaryEffects.AddEffect(spell, true, BELIAL_COUNT); + } + if (!HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) return 1; + + int wisps = 0; + for (Entity* entity : entity_query(ENTITY_FAMILIAR, Entity_Familiar::WISP)) + if (entity->subtype == COLLECTIBLE_BREATH_OF_LIFE && static_cast(entity)->player == this) wisps++; + for (int i = wisps; i < BREATH_WISPS; i++) AddWisp(COLLECTIBLE_BREATH_OF_LIFE, pos, true, false); + return 1; } // 007caaa0 Whether a heart container is a bone heart. @@ -1100,8 +1315,71 @@ bool Entity_Player::TryPreventDeath() return true; } +// Spirit Shackles' second chance: the player comes back as a shackled ghost with a last heart of its kind, its body +// left behind (once) in the middle of its death, chained to it. +static void spirit_shackles_bind(Entity_Player& player) +{ + constexpr int SHACKLED_COOLDOWN = 30; + constexpr int BODY_STATE = 10; + constexpr float SHACKLES_CHAIN_SCALE = 80; + constexpr float SHACKLES_CHAIN_REACH = 10; + player.temporaryEffects.AddNullEffect(NULLITEM_SHACKLES_GHOST, true, 1); + player.temporaryEffects.AddNullEffect(NULLITEM_SPIRIT_SHACKLES_DISABLED, true, 1); + player.soulHearts = 0; + player.blackHearts = 0; + player.eternalHearts = 0; + player.boneHeartsMask = 0; + player.boneHearts = 0; + player.rottenHearts = 0; + HealthType health = player.GetHealthType(); + if (player.maxHearts >= 1) player.redHearts = health == HEALTH_COIN ? 2 : 1; + else if (health == HEALTH_BONE) + { + player.redHearts = 0; + player.AddBoneHearts(1); + } + else if (health == HEALTH_COIN) + { + player.redHearts = 2; + player.maxHearts = 2; + } + else if (player.playerType == PLAYER_BETHANY) + { + player.maxHearts = 2; + player.redHearts = 1; + } + else + { + player.redHearts = 0; + player.soulHearts = 1; + } + player.damageCooldown = SHACKLED_COOLDOWN; + + if (!player.astralProjectionBody) + { + auto* body = static_cast(g_game->Spawn({.position = player.pos, .spawner = &player, + .type = ENTITY_EFFECT, .variant = EFFECT_DEVIL, + .seed = Random()})); + body->sprite = player.sprite; + if (LayerState* ghost = body->sprite.GetLayer("ghost")) ghost->isVisible = false; + body->sprite.overlayAnimState.SetAnimationData(nullptr); + body->sprite.Play("Death"); + body->AddEntityFlags(FLAG_DONT_OVERWRITE); + body->state = BODY_STATE; + body->Update(); + player.astralProjectionBody = body; + } + auto* chain = static_cast(g_game->Spawn({.position = player.pos, .type = ENTITY_EFFECT, + .variant = EFFECT_FORGOTTEN_CHAIN, .seed = Random()})); + chain->child = player.astralProjectionBody; + chain->target = &player; + chain->scale = SHACKLES_CHAIN_SCALE; + chain->targetPosition = vector_make(SHACKLES_CHAIN_REACH, 0); + chain->Update(); +} + // 007afc20 Kills the player out of hearts and starts the death sequence, unless it is dead, a ghost, berserk or -// projected. Spirit Shackles' second chance is not written yet. True when it killed. +// projected. Spirit Shackles gives a second chance instead. True when it killed. bool Entity_Player::try_trigger_astral_projection() { bool isOutOfHearts = redHearts < 1 && soulHearts < 1 && boneHearts < 1; @@ -1116,7 +1394,11 @@ bool Entity_Player::try_trigger_astral_projection() bool isShackled = HasCollectible(COLLECTIBLE_SPIRIT_SHACKLES) && temporaryEffects.GetNullEffectNum(NULLITEM_SPIRIT_SHACKLES_DISABLED) == 0 && temporaryEffects.GetNullEffectNum(NULLITEM_SHACKLES_GHOST) == 0; - if (isShackled) reconstruction_missing("Entity_Player::try_trigger_astral_projection 007afc20 (Spirit Shackles)"); + if (isShackled) + { + spirit_shackles_bind(*this); + return false; + } if (lastDamageSource.type == ENTITY_SLOT || (lastDamageFlags & DAMAGE_DEVIL)) Player_stats_add(g_game->onlinePlayerStats, ONLINE_STAT_DEAL_DEATHS, this, 1); lastDamageSource = EntityRef(); @@ -1125,12 +1407,98 @@ bool Entity_Player::try_trigger_astral_projection() return true; } -// 007d35b0 Ends Astral Projection's spirit form when the spirit is hit, not written yet. True when it ended. +// The spirit's way back to its body: a trail of ghostly wisps along the way (between 4 and 12, one per 20 units) +// drifting after it, and a white poof where the spirit was. +static void astral_trail_spawn(Entity_Player& player, Entity& body) +{ + constexpr float ASTRAL_TRAIL_STEP_SCALE = 0.1f; + constexpr float ASTRAL_TRAIL_STEP_MAX = 4; + constexpr float ASTRAL_TRAIL_SPACING = 20; + constexpr int ASTRAL_TRAIL_MIN = 4; + constexpr int ASTRAL_TRAIL_MAX = 12; + constexpr float ASTRAL_TRAIL_SCATTER = 15; + constexpr float ASTRAL_TRAIL_SCALE_RANGE = 0.3f; + constexpr float ASTRAL_TRAIL_HEIGHT = 16; + constexpr int ASTRAL_POOF_SUBTYPE = 10; + constexpr ColorMod ASTRAL_TRAIL_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 1, 1}}; + constexpr ColorMod ASTRAL_POOF_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; + Vector toBody = vector_sub(body.pos, player.pos); + Vector step = vector_scale(toBody, ASTRAL_TRAIL_STEP_SCALE); + if (vector_length(step) > ASTRAL_TRAIL_STEP_MAX) step = vector_resized(step, ASTRAL_TRAIL_STEP_MAX); + int count = std::clamp((int)std::floor(vector_length(toBody) / ASTRAL_TRAIL_SPACING), ASTRAL_TRAIL_MIN, ASTRAL_TRAIL_MAX); + + for (int i = 1; i <= count; i++) + { + float along = (float)i / (float)(count + 1); + Vector direction = random_direction(); + Vector scatter = vector_scale(direction, random_unit() * ASTRAL_TRAIL_SCATTER); + Vector spot = vector_add(scatter, vector_add(player.pos, vector_scale(toBody, along))); + uint32_t seed = Random(); + Vector velocity = vector_scale(step, random_unit() * HALF + HALF); + Entity* wisp = g_game->Spawn({.position = spot, .velocity = velocity, .type = ENTITY_EFFECT, + .variant = EFFECT_HAEMO_TRAIL, .seed = seed}); + wisp->SetColor(ASTRAL_TRAIL_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + float size = along * (random_unit() * ASTRAL_TRAIL_SCALE_RANGE + ASTRAL_TRAIL_SCALE_RANGE); + wisp->sprite.scale = vector_make(size, size); + wisp->posOffset = vector_make(player.posOffset.x, player.posOffset.y - player.sprite.scale.y * ASTRAL_TRAIL_HEIGHT); + } + Entity* poof = g_game->Spawn({.position = player.pos, .velocity = step, .subType = ASTRAL_POOF_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_POOF02, .seed = Random()}); + poof->SetColor(ASTRAL_POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + poof->posOffset = player.posOffset; + poof->sprite.scale = player.sprite.scale; +} + +// 007d35b0 Ends Astral Projection's spirit form when the spirit is hit: the spirit flies back to its body along a +// ghostly trail, flashes white with a bloom and the room's colours at once, and then dies if it has no hearts left +// (the death skipping ahead) or stays unhurtable for 4 seconds. True when it ended. bool Entity_Player::try_end_astral_projection() { + constexpr int ASTRAL_END_BLOOM = 10; + constexpr float ASTRAL_END_BLOOM_STRENGTH = 0.6f; + constexpr int ASTRAL_END_FLASH = 8; + constexpr int ASTRAL_END_COOLDOWN = 120; + constexpr float DEATH_SKIP_FRAME = 24; + constexpr ColorMod WHITE_FLASH = {{1, 1, 1, 1}, {0, 0, 0, 0}, {1, 1, 1}}; TemporaryEffect* astral = temporaryEffects.isDisabled ? nullptr : temporaryEffects.GetCollectibleEffect(COLLECTIBLE_ASTRAL_PROJECTION); if (!astral || astral->count != 1) return false; - reconstruction_missing("Entity_Player::try_end_astral_projection 007d35b0"); + + ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_ASTRAL_PROJECTION); + if (item) temporaryEffects.AddEffect(TemporaryEffect(item), true, 1); + RemoveCostume(item); + if (Entity* body = astralProjectionBody.get()) + { + astral_trail_spawn(*this, *body); + velocity = {}; + Teleport(body->pos, false, false); + body->Remove(); + } + + ResetColor(); + ColorMod flash = sprite.color; + color_multiply(flash, WHITE_FLASH); + SetColor(flash, ASTRAL_END_FLASH, COLOR_PRIORITY_DEFAULT, true, true); + Game& game = *g_game; + game.bloomDuration = ASTRAL_END_BLOOM; + game.bloomTimer = ASTRAL_END_BLOOM; + game.bloomStrength = ASTRAL_END_BLOOM_STRENGTH; + game.targetColorModifier = game.room->get_color_modifier(); + game.currentColorModifier = game.targetColorModifier; + game.isColorModifierLerped = false; + + try_trigger_astral_projection(); + if (!isDead) + { + damageCooldown = std::max(damageCooldown, ASTRAL_END_COOLDOWN); + return true; + } + if (std::string_view(GetDeathAnimName()) != "Death") return true; + PlayExtraAnimation("Death"); + if (sprite.animState.animData) sprite.animState.SetFrameFloat(DEATH_SKIP_FRAME); + int sound = SOUND_ISAACDIES; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.pitch = get_voice_pitch()}); + return true; } // 007828f0 The animation the player dies with: the Lost's for ghosts and the cursed, Forgotten's, or falling in a hole. diff --git a/src/entity_player_effects.cpp b/src/entity_player_effects.cpp index aea00df..0c00e65 100644 --- a/src/entity_player_effects.cpp +++ b/src/entity_player_effects.cpp @@ -1,7 +1,9 @@ #include "entity_player_effects.h" #include "boss_ai.h" +#include "boss_pool.h" #include "entity_bomb.h" #include "entity_effect.h" +#include "entity_familiar.h" #include "entity_pickup.h" #include "entity_npc.h" #include "entity_player.h" @@ -11,6 +13,8 @@ #include "game.h" #include "manager.h" #include "grid_entity_pit.h" +#include "grid_entity_poop.h" +#include "npc_basement.h" #include "npc_ai.h" #include "room.h" #include "room_grid.h" @@ -126,6 +130,9 @@ constexpr int VENUS_CHARM_FRAMES = 60; constexpr float SPOOKY_FEAR_REACH = 80; constexpr int SPOOKY_FEAR_FRAMES = -20; constexpr int SPOOKY_BOSS_FEAR_FRAMES = -60; +constexpr float VOLT_INTERVAL = 6; +constexpr float VOLT_REACH = 60; +constexpr float VOLT_DAMAGE = 0.75f; constexpr float MONSTRANCE_RADIUS = 90; constexpr float MONSTRANCE_PERIOD = 4; constexpr LerpRange MONSTRANCE_FALLOFF = {.inMin = 30, .inMax = 90, .outMin = 0, .outMax = 0.4f}; @@ -177,6 +184,7 @@ constexpr float WARNING_FADE_STEP = 0.3f; constexpr float WARNING_OFFSET = 0.3f; constexpr float WARNING_OFFSET_STEP = 0.06f; constexpr uint32_t FRAME_STAT_CACHE = CACHE_DAMAGE | CACHE_FIREDELAY | CACHE_TEARFLAG | CACHE_TEARCOLOR; +constexpr int GROUND_CONTACT_MAX = 4; // The flashes the frame lays on the player: Tooth and Nail's statue turning, and Mars' dash being ready. constexpr ColorMod GREY_FLASH = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0.8f, 0.8f, 0.8f}}; @@ -187,6 +195,57 @@ constexpr ColorMod DIRTY_MIND_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.255f, 0.16 constexpr ColorMod ROTTEN_TOMATO_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.45f, 0.1f, 0.09f}}; constexpr ColorMod NEPTUNUS_SPLAT = {{0, 0, 0, 0.08f}, {0, 0, 0, 0}, {0, 0, 0}}; +// Mom's foot stomps near the player (the Broken Shovel's first half before its use, or the Reversed High Priestess): +// past the room's first second, one check in five every 10 frames while fewer than two feet are down, never in Mom's +// own room. +static void moms_foot_update(Entity_Player& player) +{ + constexpr int FOOT_STOMP_PERIOD = 10; + constexpr int FOOT_STOMP_ODDS = 5; + constexpr int FOOT_STOMP_ROOM_GRACE = 30; + constexpr int FOOT_STOMP_FEET_MAX = 2; + constexpr float FOOT_STOMP_REACH = 40; + constexpr float FOOT_STOMP_DAMAGE = 100; + Game& game = *g_game; + Room& room = *game.room; + bool isShovel = player.HasCollectible(COLLECTIBLE_BROKEN_SHOVEL_1) && + !player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BROKEN_SHOVEL_1); + if (!isShovel && !player.temporaryEffects.HasNullEffect(NULLITEM_REVERSE_HIGH_PRIESTESS)) return; + if (!room.isInitialized || game.frameCount - room.enterFrame <= FOOT_STOMP_ROOM_GRACE) return; + if (!player.IsFrame(FOOT_STOMP_PERIOD, 0) || Random() % FOOT_STOMP_ODDS != 0 || room.bossId == BOSS_MOM) return; + if (entity_query(ENTITY_EFFECT, EFFECT_MOM_FOOT_STOMP).size() >= FOOT_STOMP_FEET_MAX) return; + + uint32_t seed = Random(); + Vector reach = vector_scale(random_direction(), FOOT_STOMP_REACH); + Vector spot = vector_add(player.pos, vector_scale(reach, random_unit())); + Entity* foot = g_game->Spawn({.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_MOM_FOOT_STOMP, .seed = seed}); + foot->targetPosition = foot->pos; + foot->SetCollisionDamage(FOOT_STOMP_DAMAGE); + foot->Update(); +} + +// The challenges' part of the items' frame: past 15 minutes Speed! hurts every 10 seconds, and in Pay to Play a living +// player without coins dies, to the Ultra Coin. +static void challenge_frame_update(Entity_Player& player) +{ + constexpr int SPEED_GRACE_FRAMES = 28800; + constexpr int SPEED_HURT_PERIOD = 300; + constexpr int SPEED_HURT_COUNTDOWN = 30; + Game& game = *g_game; + if (game.challenge == CHALLENGE_SPEED) + { + if (game.frameCount > SPEED_GRACE_FRAMES && player.IsFrame(SPEED_HURT_PERIOD, 0)) + player.TakeDamage(1, DAMAGE_TIMER | DAMAGE_INVINCIBLE, EntityRef(), SPEED_HURT_COUNTDOWN); + return; + } + if (game.challenge != CHALLENGE_PAY_TO_PLAY || player.isDead || player.numCoins > 0) return; + + player.Kill(EntityRef()); + EntityRef coin; + coin.type = ENTITY_ULTRA_COIN; + player.set_last_damage(0, coin); +} + // The Anarchist Cookbook's effect drops a troll bomb with the player's bomb effects every fifth frame it has left. static void anarchist_cookbook_update(Entity_Player& player) { @@ -203,6 +262,178 @@ static void anarchist_cookbook_update(Entity_Player& player) bomb.tearFlags = player.GetBombFlags(false); } +// Crack the Sky's effect calls a beam every fifth frame it has left: on a free spot somewhere in the room, or half the +// time near an enemy standing on open ground. The beam's cell is marked for pathing and it hits with the player's +// damage added. +static void crack_the_sky_update(Entity_Player& player) +{ + constexpr int BEAM_PERIOD = 5; + constexpr float BEAM_ROOM_MARGIN = 20; + constexpr int BEAM_GRID_PATH = 900; + TemporaryEffect* sky = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_CRACK_THE_SKY); + if (!sky || sky->cooldown % BEAM_PERIOD != 0) return; + + Room& room = *g_game->room; + Vector spot = room_free_pickup_position_find({.position = room.GetRandomPosition(BEAM_ROOM_MARGIN)}); + if (random_below(2) == 0) + { + std::vector targets; + for (Entity* entity : room.GetEntities()->updateEL) + if (entity->IsVulnerableEnemy(nullptr) && room_grid_collision_at(entity->pos) == GRIDCOLL_NONE) + targets.push_back(entity); + if (!targets.empty()) + spot = room_free_pickup_position_find({.position = targets[random_below((int)targets.size())]->pos}); + } + if (room_grid_collision_at(spot) == GRIDCOLL_NONE) room.SetGridPath(room.GetGridIndex(spot), BEAM_GRID_PATH); + + Entity* beam = g_game->Spawn({.position = spot, .spawner = &player, .type = ENTITY_EFFECT, + .variant = EFFECT_CRACK_THE_SKY, .seed = Random()}); + beam->SetCollisionDamage(beam->collisionDamage + player.damage); + beam->parent = &player; +} + +// Relax: every other frame it lasts, a poop drops where the player stands on an empty, decorated or webbed cell +// (not in a crawl space), with a fart and the candle Bird's Eye or Ghost Pepper fires. Hallowed Ground makes it holy +// one time in three, Meconium black (33, 66 or 100 in 100 by its copies) and Midas' Touch golden (luck helps). +static void relax_poop_update(Entity_Player& player) +{ + constexpr int HOLY_CHANCE = 33; + constexpr int RELAX_MECONIUM_CHANCE = 33; + constexpr int RELAX_MECONIUM_DOUBLE_CHANCE = 66; + constexpr int RELAX_MECONIUM_TRIPLE_CHANCE = 100; + constexpr int MIDAS_CHANCE = 26; + constexpr float MIDAS_LUCK = 10; + constexpr float RELAX_FART_RADIUS = 120; + TemporaryEffect* relax = player.temporaryEffects.GetNullEffect(NULLITEM_RELAX); + if (!relax || (relax->cooldown & 1) != 0) return; + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(player.pos); + GridEntity* grid = room.GetGridEntity((uint32_t)gridIndex); + if (grid && grid->type != GRID_DECORATION && grid->type != GRID_SPIDERWEB) return; + if (room.roomType == ROOM_DUNGEON) return; + + RNG& rng = player.GetPillRNG(PILLEFFECT_RELAX); + int variant = POOP_NORMAL; + if (player.HasCollectible(COLLECTIBLE_HALLOWED_GROUND) || + player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HALLOWED_GROUND)) + variant = player.GetCollectibleRNG(COLLECTIBLE_HALLOWED_GROUND).RandomInt(100) < HOLY_CHANCE ? POOP_WHITE : POOP_NORMAL; + if (player.HasTrinket(TRINKET_MECONIUM)) + { + int copies = player.GetTrinketMultiplier(TRINKET_MECONIUM); + int chance = copies == 2 ? RELAX_MECONIUM_DOUBLE_CHANCE + : copies == 3 ? RELAX_MECONIUM_TRIPLE_CHANCE + : RELAX_MECONIUM_CHANCE; + if ((int)player.GetTrinketRNG(TRINKET_MECONIUM).RandomInt(100) < chance) variant = POOP_BLACK; + } + if (player.HasCollectible(COLLECTIBLE_MIDAS_TOUCH) && + (int)rng.RandomInt(100) - (int)(player.luck * MIDAS_LUCK) < MIDAS_CHANCE) + variant = POOP_GOLDEN; + room.SpawnGridEntity(gridIndex, GRID_POOP, variant, rng.Next(), 0); + game_butter_bean_fart({.position = player.pos, .source = &player, .radius = RELAX_FART_RADIUS, + .isShowEffect = false, .isSuperKnockback = false}); + sound_play(SOUND_FART); + player.ShootCandle({}); +} + +// Telekinesis: enemy shots near the player (a versus rival's tears too) are caught and held still, to fly back +// at their own speed when the spell ends (a little later each), and tears not the player's own are caught to circle +// it. With the Book of Virtues each caught shot becomes a wisp instead. The spell's halo blinks in its last 2 seconds. +static void telekinesis_update(Entity_Player& player) +{ + constexpr float CATCH_REACH = 50; + constexpr float CATCH_HEIGHT_MIN = -50; + constexpr uint32_t CATCH_DELAY_RANGE = 15; + constexpr float BOUNCE_LOSS = 0.85f; + constexpr uint64_t CAUGHT_FLAGS_KEPT = ~0x41c1800ull & ~PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT; + constexpr int HALO_BLINK_FRAMES = 60; + TemporaryEffect* spell = player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_TELEKINESIS); + if (!spell) + { + if (player.telekinesisHalo) player.telekinesisHalo->Remove(); + player.telekinesisHalo = nullptr; + return; + } + + bool isVirtues = player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES); + uint32_t partitions = g_game->deathmatchManager.is_active() ? QUERY_PROJECTILES | QUERY_TEARS : QUERY_PROJECTILES; + for (Entity* entity : entity_query_radius(player.pos, CATCH_REACH, partitions)) + { + if (entity->type == ENTITY_PROJECTILE) + { + auto& shot = *static_cast(entity); + if ((shot.projectileFlags & PROJECTILE_CANT_HIT_PLAYER) || shot.height <= CATCH_HEIGHT_MIN) continue; + if (isVirtues) + { + player.AddWisp(COLLECTIBLE_TELEKINESIS, shot.pos, false, false); + shot.Remove(); + continue; + } + uint64_t flags = (shot.projectileFlags | PROJECTILE_CANT_HIT_PLAYER | PROJECTILE_HIT_ENEMIES) & CAUGHT_FLAGS_KEPT; + shot.projectileFlags = flags | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT | PROJECTILE_STASIS; + shot.changeFlags = flags; + shot.changeTimeout = random_below((int)CATCH_DELAY_RANGE) + spell->cooldown; + shot.changeVelocity = vector_length(shot.velocity); + shot.target = nullptr; + shot.parent = &player; + shot.targetPosition = {}; + if (shot.fallingAccel > 0 && shot.fallingSpeed > 0) shot.fallingSpeed = -shot.fallingSpeed * BOUNCE_LOSS; + continue; + } + if (entity->IsDescendantOf(&player) || entity->type != ENTITY_TEAR) continue; + auto& tear = *static_cast(entity); + if (tear.height <= CATCH_HEIGHT_MIN) continue; + if (isVirtues) + { + player.AddWisp(COLLECTIBLE_TELEKINESIS, tear.pos, false, false); + tear.Remove(); + continue; + } + tear.SetTearFlags(TearFlags().set(TEAR_INTERVAL_FLAGS).set(TEAR_PARENT_STEER)); + tear.intervalFlags = TearFlags(); + tear.interval = random_below((int)CATCH_DELAY_RANGE) + spell->cooldown; + tear.intervalSpeed = vector_length(tear.velocity); + tear.target = nullptr; + tear.parent = &player; + tear.spawnerEntity = &player; + tear.targetPosition = {}; + } + + if (!player.telekinesisHalo) + { + Entity* halo = g_game->Spawn({.position = player.pos, .spawner = &player, .subType = HALO_TELEKINESIS, + .type = ENTITY_EFFECT, .variant = EFFECT_HALO, .seed = Random()}); + halo->parent = &player; + player.telekinesisHalo = halo; + } + if (Entity* halo = player.telekinesisHalo.get()) + static_cast(halo)->state = spell->cooldown < HALO_BLINK_FRAMES ? 1 : 0; +} + +// Breath of Life's unhurtable spell: its halo is let go once the spell is over, the spell ends when the item leaves +// the first slot, and when it runs out the player takes a heart of damage and the spell starts again. +static void breath_of_life_update(Entity_Player& player) +{ + constexpr uint64_t BREATH_HIT_FLAGS = DAMAGE_NO_PENALTIES | DAMAGE_INVINCIBLE; + TemporaryEffects& effects = player.temporaryEffects; + TemporaryEffect* breath = effects.GetCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE); + if (!breath) + { + if (Entity* halo = player.breathOfLifeEffect.get()) halo->parent = nullptr; + player.breathOfLifeEffect = nullptr; + return; + } + if (player.activeItems[ACTIVE_SLOT_PRIMARY].item != COLLECTIBLE_BREATH_OF_LIFE) + { + effects.RemoveCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE, -1); + return; + } + if (breath->cooldown != 1) return; + effects.RemoveCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE, -1); + player.ResetDamageCooldown(); + player.TakeDamage(1, BREATH_HIT_FLAGS, EntityRef(), 0); + effects.AddCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE, true, 1); +} + // Faded Polaroid every 300 frames, one time in five, fades the player for 3 to 7 seconds (times its multiplier). static void faded_polaroid_update(Entity_Player& player) { @@ -221,6 +452,102 @@ static void faded_polaroid_update(Entity_Player& player) effects.AddEffect(fade, true, 1); } +// Empty Vessel: without red hearts the player flies (with its costume), and while it flies a room still fighting +// (any room in a versus match) gives it Book of Shadows' shield for 10 seconds every 40. +static void empty_vessel_update(Entity_Player& player) +{ + constexpr int SHIELD_PERIOD = 1200; + constexpr int SHIELD_FRAMES = 300; + if (!player.HasCollectible(COLLECTIBLE_EMPTY_VESSEL)) return; + TemporaryEffects& effects = player.temporaryEffects; + ItemConfig& config = g_manager->itemConfig; + bool isFlying = effects.HasCollectibleEffect(COLLECTIBLE_EMPTY_VESSEL); + if (player.redHearts < 1 && !isFlying) + { + effects.AddCollectibleEffect(COLLECTIBLE_EMPTY_VESSEL, true, 1); + player.AddCostume(config.GetNullItem(NULLITEM_EMPTY_VESSEL), false); + return; + } + if (!isFlying || !player.IsFrame(SHIELD_PERIOD, 0)) return; + if (g_game->room->IsClear() && !g_game->deathmatchManager.is_active()) return; + + TemporaryEffect shield(config.GetCollectible(COLLECTIBLE_BOOK_OF_SHADOWS)); + shield.cooldown = SHIELD_FRAMES; + effects.AddEffect(shield, true, 1); +} + +// Azazel's Rage: on a room's third frame (or once its beam is spent) the rage ends with the item gone. With four +// rooms gathered, a room still fighting (an ambush not yet over) unleashes its beam, which is not written yet. A +// spent beam's rage settles back into the item's costume. +static void azazels_rage_update(Entity_Player& player) +{ + constexpr int RAGE_ROOM_FRAME = 3; + constexpr int RAGE_READY = 4; + constexpr int RAGE_FIRING = 5; + TemporaryEffects& effects = player.temporaryEffects; + ItemConfig& config = g_manager->itemConfig; + Room& room = *g_game->room; + int rooms = effects.GetCollectibleEffectNum(COLLECTIBLE_AZAZELS_RAGE); + if (room.GetFrameCount() == RAGE_ROOM_FRAME || rooms == RAGE_FIRING) + { + if (!player.HasCollectible(COLLECTIBLE_AZAZELS_RAGE)) + { + effects.RemoveCollectibleEffect(COLLECTIBLE_AZAZELS_RAGE, -1); + player.RemoveCostume(config.GetCollectible(COLLECTIBLE_AZAZELS_RAGE)); + for (int stage = NULLITEM_AZAZELS_RAGE_1; stage <= NULLITEM_AZAZELS_RAGE_4; stage++) + player.RemoveCostume(config.GetNullItem(stage)); + } + else + { + bool isAmbush = room.roomType == ROOM_CHALLENGE || room.roomType == ROOM_BOSSRUSH; + bool isCalm = isAmbush ? room.IsAmbushDone() : room.IsClear(); + if (!isCalm && (rooms == RAGE_READY || rooms == RAGE_FIRING)) + reconstruction_missing("Entity_Player::update_effects 00794e50 (Azazel's Rage's beam)"); + } + } + if (effects.GetCollectibleEffectNum(COLLECTIBLE_AZAZELS_RAGE) <= RAGE_FIRING || player.azazelsRageLaser) return; + effects.RemoveCollectibleEffect(COLLECTIBLE_AZAZELS_RAGE, -1); + player.RemoveCostume(config.GetNullItem(NULLITEM_AZAZELS_RAGE_4)); + player.AddCostume(config.GetCollectible(COLLECTIBLE_AZAZELS_RAGE), false); +} + +// Redemption's light shines over the player while its effect holds a single charge, and goes once it is spent. +static void redemption_update(Entity_Player& player) +{ + Entity* light = player.redemptionEffect.get(); + if (player.temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_REDEMPTION) == 1) + { + if (light) return; + light = g_game->Spawn({.position = player.pos, .spawner = &player, .type = ENTITY_EFFECT, + .variant = EFFECT_REDEMPTION, .seed = Random()}); + light->parent = &player; + light->AddEntityFlags(FLAG_DONT_OVERWRITE | FLAG_PERSISTENT); + light->Update(); + player.redemptionEffect = light; + return; + } + if (!light || (light->type == ENTITY_EFFECT && static_cast(light)->state != 0)) return; + light->Remove(); + player.redemptionEffect = nullptr; +} + +// I'm Excited!!!: the room speeds up again each 30 seconds the pill has left, or at once for the floor (the horse +// pill's), each time with another speed up. +static void im_excited_update(Entity_Player& player) +{ + constexpr int EXCITED_STEP_FRAMES = 900; + if (!g_game->Level::GetStateFlag(LEVEL_STATE_BROKEN_WATCH_FAST)) + { + if (player.imExcitedSpeedupCountdown <= 0 || --player.imExcitedSpeedupCountdown % EXCITED_STEP_FRAMES != 0) return; + g_game->room->SetBrokenWatchState(BROKEN_WATCH_FAST); + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_BELT, false, 1); + return; + } + g_game->room->SetBrokenWatchState(BROKEN_WATCH_FAST); + player.temporaryEffects.AddCollectibleEffect(COLLECTIBLE_BELT, false, 1); + player.imExcitedSpeedupCountdown = 0; +} + // A link the player keeps to an aura riding on it: spawned once while it is wanted, else removed. static void aura_keep(Entity_Player& player, EntityPtr& aura, bool isWanted, int subType) { @@ -286,6 +613,21 @@ static void spooky_venus_update(Entity_Player& player) } } +// 120 Volt sparks a chain lightning from the player every sixth tick when a vulnerable enemy is near, at three +// quarters of its damage. A pacifist room has none. +static void volt_120_update(Entity_Player& player) +{ + if (!player.HasCollectible(COLLECTIBLE_120_VOLT) || !player.GetIntervalTicks(VOLT_INTERVAL, 0) || g_game->room->isPacifist) + return; + + for (Entity* enemy : entity_query_radius(player.pos, VOLT_REACH, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(&player)) continue; + chain_lightning_spawn({.position = player.pos, .spawner = &player, .damage = player.meleeDamage * VOLT_DAMAGE})->Update(); + return; + } +} + // Monstrance burns the vulnerable enemies around the player every fourth tick, harder the deeper the floor and the // nearer the enemy's edge, under its halo. A pacifist room has neither. static void monstrance_update(Entity_Player& player) @@ -447,6 +789,24 @@ static void birthright_dead_bird_update(Entity_Player& player) if (isLost && isDeadBirdIdle) effects.AddCollectibleEffect(COLLECTIBLE_DEAD_BIRD, true, 1); } +// Sumptorium's effect calls the player's clots back, one a frame (each a wisp with the Book of Virtues), and ends +// once none is left to call. +static void sumptorium_recall_update(Entity_Player& player) +{ + constexpr int CLOT_RECALLED = -3; + if (!player.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_SUMPTORIUM)) return; + + for (Entity* entity : entity_query(ENTITY_FAMILIAR, Entity_Familiar::BLOOD_BABY)) + { + auto& clot = *static_cast(entity); + if (clot.player != &player || clot.state != 0 || clot.subtype == BLOOD_CLOT_SUBTYPE_SPENT) continue; + clot.state = CLOT_RECALLED; + if (player.HasCollectible(COLLECTIBLE_BOOK_OF_VIRTUES)) player.AddWisp(COLLECTIBLE_SUMPTORIUM, player.pos, false, false); + return; + } + player.temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_SUMPTORIUM, -1); +} + // Purgatory keeps one of its rifts in a room still fighting (or under an ambush), checked every 30 frames. static void purgatory_update(Entity_Player& player) { @@ -635,8 +995,15 @@ void items_frame_update(Entity_Player& player) { TemporaryEffects& effects = player.temporaryEffects; + moms_foot_update(player); + challenge_frame_update(player); anarchist_cookbook_update(player); + crack_the_sky_update(player); + relax_poop_update(player); + breath_of_life_update(player); faded_polaroid_update(player); + empty_vessel_update(player); + redemption_update(player); dads_ring_update(player); if (effects.HasCollectibleEffect(COLLECTIBLE_NOTCHED_AXE) && !player.HasCollectible(COLLECTIBLE_NOTCHED_AXE)) effects.RemoveCollectibleEffect(COLLECTIBLE_NOTCHED_AXE, -1); @@ -645,6 +1012,7 @@ void items_frame_update(Entity_Player& player) if (effects.HasCollectibleEffect(COLLECTIBLE_URN_OF_SOULS) && !player.HasCollectible(COLLECTIBLE_URN_OF_SOULS)) effects.RemoveCollectibleEffect(COLLECTIBLE_URN_OF_SOULS, -1); spooky_venus_update(player); + volt_120_update(player); monstrance_update(player); mars_recharge_update(player); divine_intervention_recharge(player); @@ -654,10 +1022,14 @@ void items_frame_update(Entity_Player& player) effects.RemoveNullEffect(NULLITEM_REVERSE_STARS, 1); ibs_charge_update(player); birthright_dead_bird_update(player); + azazels_rage_update(player); + sumptorium_recall_update(player); purgatory_update(player); isaacs_heart_update(player); plan_c_update(player); linger_bean_update(player); + im_excited_update(player); + telekinesis_update(player); if (player.hallowedGroundCountdown > 0 && --player.hallowedGroundCountdown < 1) { player.AddCacheFlags(FRAME_STAT_CACHE); @@ -679,3 +1051,29 @@ void items_frame_update(Entity_Player& player) camo_fade_update(player); size_update(player); } + +// Adds count frames (up to 4) to a standing-in-something countdown, re-evaluating the stats the frame's effects give +// when the player steps in or out or when isChanged. +static void ground_contact_add(Entity_Player& player, int& countdown, int count, bool isChanged) +{ + int previous = countdown; + countdown = std::min(previous + count, GROUND_CONTACT_MAX); + if ((previous > 0) == (countdown > 0) && !isChanged) return; + + player.AddCacheFlags(FRAME_STAT_CACHE); + player.EvaluateItems(); +} + +// 007cbc60 Keeps the player standing in Hallowed Ground's aura a few frames more. +void Entity_Player::hallowed_ground_add(int count) +{ + ground_contact_add(*this, hallowedGroundCountdown, count, false); +} + +// 007d8740 Keeps the player standing in a creep that grants item effects (the flags) a few frames more. +void Entity_Player::creep_contact_add(int flags, int count) +{ + bool isChanged = grantedCollectibleFlags != (uint32_t)flags; + grantedCollectibleFlags = (uint32_t)flags; + ground_contact_add(*this, grantedCollectibleCountdown, count, isChanged); +} diff --git a/src/entity_player_evaluate.cpp b/src/entity_player_evaluate.cpp index 9e52d1c..0040827 100644 --- a/src/entity_player_evaluate.cpp +++ b/src/entity_player_evaluate.cpp @@ -38,8 +38,6 @@ constexpr float FALL_SPEED_DECAY = 0.9f; constexpr float FALL_SPEED_SLOPE = -9.49122142791748f; constexpr float FALL_SPEED_MIN_SLOPE = 0.01f; constexpr float G_FUEL_SPEED = 0.2f; -constexpr uint32_t DEBUG_HIGH_DAMAGE = 1 << 3; -constexpr uint32_t DEBUG_HIGH_LUCK = 1 << 8; constexpr float DEBUG_DAMAGE_BONUS = 40; constexpr float DEBUG_LUCK_BONUS = 50; constexpr int PILL_RANGE_DOWN = 11; @@ -153,9 +151,8 @@ static void bulbs_apply(Entity_Player& p, float& stat, float dimScale, float vib // The temporary effects the items' frame (update_effects 00794e50) and the shooting part (0077b020) ask about by id // but do not run yet: collectible effects and null effects. An effect the frame never asks about only counts down // there. The frame's own part (00782af0) runs or stops on its own. -constexpr int FRAME_COLLECTIBLE_EFFECTS[] = {28, 130, 160, 181, 325, 326, 409, 522, 543, - 550, 593, 673, 699, 705, 713, 714, 726, 729}; -constexpr int FRAME_NULL_EFFECTS[] = {60, 61, 66, 69, 111, 114, 116, 122, 128}; +constexpr int FRAME_COLLECTIBLE_EFFECTS[] = {130, 181, 593, 705, 714}; +constexpr int FRAME_NULL_EFFECTS[] = {60, 66, 69, 111, 114, 116, 122, 128}; // Whether the frame runs a temporary effect: the effects written for it, and those it never asks about. static bool is_frame_effect_known(const TemporaryEffect& effect) @@ -1484,20 +1481,20 @@ void Entity_Player::EvaluateItems() } // The collectibles the items' part of the frame (update_effects 00794e50) looks at, which the plain path does not -// cover yet: Judas's kept Book of Belial and 120 Volt's sparks. -constexpr int FRAME_ITEMS[] = {59, 559}; +// cover yet: Judas's kept Book of Belial. +constexpr int FRAME_ITEMS[] = {59}; // The trinkets the items' frame (00794e50) looks at that it does not run yet: Extension Cord. constexpr std::array FRAME_TRINKETS = {TRINKET_EXTENSION_CORD}; // What the player's frame does not run yet, empty when it runs its plain path: a character or run it is not -// reconstructed for, a temporary effect it asks about but does not run, or an item or trinket it handles. +// reconstructed for, a temporary effect it asks about but does not run, or an item or trinket it handles. The +// challenges' and daily runs' pieces of the frame are written where they fall. std::string Entity_Player::frame_gap() { Game& game = *g_game; if (!is_character_reconstructed(*this)) return "character " + std::to_string(playerType); if (variant != PLAYER_VARIANT_PLAYER || isCoopGhost || hasCurseMistEffect) return "a co-op baby, ghost or the mist"; - if (game.challenge != 0 || game.dailyChallenge._id != 0) return "a challenge or daily run"; if (game.seedEffects.CountSeedEffects() != 0 || game.deathmatchManager.is_active()) return "a seeded or versus run"; if (!proceduralItems.empty()) return "a glitched item"; for (const TemporaryEffect& effect : temporaryEffects.effects) diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index 1884c70..69da513 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -122,7 +122,6 @@ constexpr int POINTY_RIB_BLINK = 7; constexpr int SHOOP_BLINK = 10; constexpr int SHOOT_HISTORY_SIZE = 3; constexpr int SPECIAL_DAILY_BUTTER_BEAN = 41; -constexpr int SUPLEX_LANDING = 2; constexpr int SUPLEX_TARGET_VARIANT = 30; constexpr float MARKED_SPAWN_REACH = 5; constexpr float MARKED_STEER_SPEED = 8; @@ -441,8 +440,6 @@ void Entity_Player::update_body_animations() if (input.x != 0 || input.y != 0) recentMovementVector = input; Vector walkInput = walk_direction_update(input); 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_animate(*this); jupiter_update(*this, input); if (HasCollectible(COLLECTIBLE_MARS) && isControlsEnabled) mars_taps_read(*this); @@ -471,9 +468,24 @@ Vector Entity_Player::walk_direction_update(Vector input) return scaled; } +// Spin to Win keeps a twentieth of the speed the player had, and bounces it off the walls it hits (losing a fifth). +static void spin_momentum_apply(Entity_Player& player, Vector before) +{ + constexpr float SPIN_MOMENTUM = 0.05f; + constexpr float SPIN_BOUNCE = 0.8f; + if (!player.temporaryEffects.HasNullEffect(NULLITEM_SPIN_TO_WIN)) return; + player.velocity = vector_add(player.velocity, vector_scale(before, SPIN_MOMENTUM)); + if (!player.isCollidesWithGrid) return; + Vector normal = player.gridCollisionNormal; + Vector hit = player.gridCollisionVelocity; + float along = normal.x * hit.x + normal.y * hit.y; + Vector bounce = vector_scale(normal, along * SPIN_BOUNCE); + player.velocity = vector_make(hit.x - (bounce.x + bounce.x), hit.y - (bounce.y + bounce.y)); +} + // 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. +// Tainted Forgotten's body only slides to a stop, slowly while thrown. Spin to Win's spin keeps some momentum. void Entity_Player::walk_velocity_update(Vector walkInput) { Vector before = velocity; @@ -488,6 +500,7 @@ void Entity_Player::walk_velocity_update(Vector walkInput) velocity.x *= drag; if (isGrounded) velocity.y *= drag; else velocity.y += GRAVITY_PULL; + spin_momentum_apply(*this, before); return; } @@ -526,6 +539,7 @@ void Entity_Player::walk_velocity_update(Vector walkInput) velocity.x = moved.x * damping; if (isGrounded) velocity.y *= damping; else velocity.y += GRAVITY_PULL; + spin_momentum_apply(*this, before); } // Holds the lifted item where the body's held null is, shown while that null shows. Whether the item is lifted. @@ -661,7 +675,7 @@ static void marked_target_remove(Entity_Player& player) // target shoots on its own, which it does unless Gnawed Leaf has turned the player to stone. static bool marked_target_update(Entity_Player& player, const MarkedAim& aim) { - bool isSuplex = player.suplexState == SUPLEX_LANDING; + bool isSuplex = player.suplexState == SUPLEX_AIMING; int variant = player.weapons[1] ? player.weapons[1]->GetMarkedTargetVariant() : 0; if (isSuplex) variant = SUPLEX_TARGET_VARIANT; @@ -1414,7 +1428,7 @@ void Entity_Player::update_shooting() else if (isInputAllowed) { bool isFree = (!isPlayingExtraAnimation && !isPlayingItemAnimation) || bodySprite.IsFinished("LiftItem"); - bool isPresent = entityCollisionClass != ENTCOLL_NONE || suplexState == SUPLEX_LANDING || isCoopGhost || + bool isPresent = entityCollisionClass != ENTCOLL_NONE || suplexState == SUPLEX_AIMING || isCoopGhost || HasEntityFlags(FLAG_HELD) || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HOW_TO_JUMP) || IsHologram(); if (isFree && isPresent) shoot_input_read(input); diff --git a/src/entity_player_health.cpp b/src/entity_player_health.cpp index 95de1ee..f078f1f 100644 --- a/src/entity_player_health.cpp +++ b/src/entity_player_health.cpp @@ -36,20 +36,6 @@ constexpr float CONCEPTION_HEART_STEP = 40; // The game state bit set once the coins reach 99, which the original keeps one below Lua's STATE_MAX_COINS_OBTAINED. constexpr uint64_t GAME_STATE_MAX_COINS_BIT = 1ull << 43; -// Which consumables ConsumableCountChanged and SyncConsumables copy between players. -enum ConsumableMask : uint32_t -{ - CONSUMABLE_COINS = 0x1, - CONSUMABLE_KEYS = 0x2, - CONSUMABLE_BOMBS = 0x4, - CONSUMABLE_GOLDEN_KEY = 0x8, - CONSUMABLE_GOLDEN_BOMB = 0x10, - CONSUMABLE_SOUL_CHARGE = 0x20, - CONSUMABLE_GIGA_BOMBS = 0x40, - CONSUMABLE_POOP_MANA = 0x80, - CONSUMABLE_BLOOD_CHARGE = 0x100 -}; - // 007dd380 A heart amount as the deathmatch counts it, eight times the run's. int scale_for_hard_difficulty(int value) { diff --git a/src/entity_player_items.cpp b/src/entity_player_items.cpp index 4014d06..7f1e095 100644 --- a/src/entity_player_items.cpp +++ b/src/entity_player_items.cpp @@ -969,6 +969,29 @@ static void magic_8_ball_gain(Entity_Player& p, RNG& rng) pickup_drop(position, {PICKUP_TAROTCARD, item_card_roll(rng.Next()), seed, &p}); } +// Sol's pickup: the floor's boss room shows on the map and the floor remembers Sol's effect. +static void sol_gain() +{ + Game& game = *g_game; + if (game.lastBossRoomListIdx >= 0) game.roomList[game.lastBossRoomListIdx].displayFlags |= ROOM_DISPLAY_ICON; + game.minimap.Refresh(); + game.levelStateFlags |= 1u << LEVEL_STATE_SOL; +} + +// Mom's Ring's first pickup: a random rune, when any rune but the shard is unlocked. +static void moms_ring_gain(Entity_Player& p, RNG& rng) +{ + std::vector>& cards = g_manager->itemConfig.cards; + auto isRune = [](const std::unique_ptr& card) { + return card && card->id != RUNE_SHARD && card->cardType == CARD_RUNE && card->IsAvailable(); + }; + if (cards.size() < 2 || std::none_of(cards.begin() + 1, cards.end(), isRune)) return; + + int rune = ItemPool::GetCardEx((int)rng.Next(), 0, -1, 0, true); + Vector position = room_free_pickup_position_find({.position = p.pos}); + pickup_drop(position, {PICKUP_TAROTCARD, rune, rng.Next(), &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) @@ -1453,12 +1476,17 @@ static void collectible_effect_apply(Entity_Player& p, const CollectibleGain& ga case 644: if (isFirst) consolation_prize_gain(p, rng); return; - case 588: - case 593: case 732: - reconstruction_missing( - (std::string("Entity_Player::AddCollectible 0075f0e0 (the pickup effect of ") + - std::to_string(gain.type) + ")").c_str()); + if (isFirst) moms_ring_gain(p, rng); + return; + case 588: + sol_gain(); + return; + case 593: + p.isMarsDashReady = true; + p.marsCooldown = 0; + p.marsDashDirection = -1; + return; } } diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index 2de9348..b72fda5 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -101,8 +101,6 @@ void Entity_Player::SetShootingCooldown(int cooldown) } void Entity_Player::add_random_stat_up(RNG*) { reconstruction_missing("Entity_Player::add_random_stat_up 007c3980"); } void Entity_Player::dash_impact() { reconstruction_missing("Entity_Player::dash_impact 007c8240"); } -Entity* Entity_Player::ShootRedCandle(Vector) { reconstruction_missing("Entity_Player::ShootRedCandle 007c9130"); } -Entity* Entity_Player::ShootBlueCandle(Vector) { reconstruction_missing("Entity_Player::ShootBlueCandle 007c9350"); } void Entity_Player::apply_victory_lap_penalty(uint32_t) { reconstruction_missing("Entity_Player::apply_victory_lap_penalty 007c97f0"); @@ -114,15 +112,6 @@ void Entity_Player::apply_coop_baby_spawn_bonus() { reconstruction_missing("Entity_Player::apply_coop_baby_spawn_bonus 007cb090"); } -float Entity_Player::GetGreedDonationBreakChance() -{ - reconstruction_missing("Entity_Player::GetGreedDonationBreakChance 007cbb70"); -} -float Entity_Player::GetGreedDonationJamChance(PersistentGameData&) -{ - reconstruction_missing("Entity_Player::GetGreedDonationJamChance 007cbb90"); -} -void Entity_Player::hallowed_ground_add(int) { reconstruction_missing("Entity_Player::hallowed_ground_add 007cbc60"); } // 007cbcb0 The player a Tainted Soul acts through: the Tainted Forgotten it is twinned with, else the player itself. Entity_Player* Entity_Player::resolve_tainted_soul() @@ -148,13 +137,7 @@ void Entity_Player::AddUrnSouls(uint32_t) { reconstruction_missing("Entity_Playe void Entity_Player::AddGigaBombs(int) { reconstruction_missing("Entity_Player::AddGigaBombs 007d34f0"); } void Entity_Player::fire_saturnus_tears() { reconstruction_missing("Entity_Player::fire_saturnus_tears 007d3e40"); } 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::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::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"); } diff --git a/src/entity_player_passives.cpp b/src/entity_player_passives.cpp index 393e827..8ba3e61 100644 --- a/src/entity_player_passives.cpp +++ b/src/entity_player_passives.cpp @@ -7,6 +7,8 @@ #include "entity_pickup.h" #include "entity_player.h" #include "game.h" +#include "grid_entity_door.h" +#include "grid_entity_rock.h" #include "item_overlay.h" #include "log.h" #include "manager.h" @@ -19,6 +21,10 @@ #include "weapon.h" #include +// Cracked Orb reveals a room with its box and icon, and its flash on a wisp sits above it. +constexpr uint32_t CRACKED_ORB_SHOWN = ROOM_DISPLAY_BOX | ROOM_DISPLAY_ICON; +constexpr float CRACKED_ORB_LIFT = -16; + // 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; @@ -708,3 +714,69 @@ std::span passive_effect_behaviours() { return PASSIVE_EFFECT_BEHAVIOURS; } + +// Cracked Orb's poof where it opened something. +static void cracked_orb_poof(const Vector& position) +{ + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_CRACKED_ORB_POOF, .seed = Random()})->Update(); +} + +// 007d7c30 Cracked Orb, on a hit: one room of the floor the map does not show yet is revealed, the room's breakable +// rocks that hide something (tinted and super secret ones, and the crawlspace's rock) break, its locked doors open +// and the walls of its secret rooms blow open. When anything opened, the orb flashes at a position, or on the player. +void Entity_Player::trigger_cracked_orb(Vector position) +{ + Game& game = *g_game; + std::vector hidden; + for (int i = 0; i < game.nbRooms; i++) + { + RoomDescriptor& room = game.roomList[i]; + if ((room.displayFlags & CRACKED_ORB_SHOWN) != CRACKED_ORB_SHOWN) hidden.push_back(room.safeGridIndex); + } + if (!hidden.empty()) + { + uint32_t pick = GetCollectibleRNG(COLLECTIBLE_CRACKED_ORB).Next() % hidden.size(); + game.GetRoomByIdx(hidden[pick])->displayFlags |= CRACKED_ORB_SHOWN; + game.minimap.Refresh(); + effect_sound_play(SOUND_CRACKED_ORB); + } + + Room& room = *game.room; + bool isAnyOpened = false; + int crawlspaceRock = game.levelStateFlags & 1u << LEVEL_STATE_DUNGEON_ROCK_BROKEN ? -1 : room.dungeonRockIdx; + for (int i = 0; i < room.gridWidth * room.gridHeight; i++) + { + GridEntity* rock = i < ROOM_GRID_CELLS ? room.gridEntities[i] : nullptr; + if (!rock || !rock->IsBreakableRock() || (rock->state != ROCK_STATE_STANDING && rock->state != ROCK_STATE_CRACKED)) continue; + if (rock->type != GRID_ROCKT && rock->type != GRID_ROCK_SS && i != crawlspaceRock) continue; + + rock->Destroy(true, EntityRef(this)); + cracked_orb_poof(room.GetGridPosition(rock->gridIndex)); + isAnyOpened = true; + } + for (GridEntity_Door* door : room.doors) + { + if (!door) continue; + bool isLocked = door->variant >= DOOR_LOCKED && door->variant <= DOOR_LOCKED_KEYFAMILIAR; + bool isSecret = door->currentRoomType == ROOM_SECRET || door->targetRoomType == ROOM_SECRET || + door->currentRoomType == ROOM_SUPERSECRET || door->targetRoomType == ROOM_SUPERSECRET; + bool isOpened = isLocked ? door->TryUnlock(*this, true) : isSecret && door->TryBlowOpen(false, nullptr); + if (!isOpened) continue; + + cracked_orb_poof(room.GetGridPosition(door->gridIndex)); + isAnyOpened = true; + } + if (!isAnyOpened) return; + + auto* orb = static_cast(game.Spawn({.position = position, .type = ENTITY_EFFECT, + .variant = EFFECT_CRACKED_ORB_POOF, .seed = Random()})); + orb->sprite.scale = playerSpriteScale; + if (vector_is_zero(position)) + { + orb->pos = pos; + orb->posOffset = vector_add(posOffset, GetFlyingOffset()); + orb->FollowParent(this); + } + else orb->posOffset = vector_make(0, CRACKED_ORB_LIFT); + orb->Update(); +} diff --git a/src/entity_player_pockets.cpp b/src/entity_player_pockets.cpp index 8214a20..0eb3fa6 100644 --- a/src/entity_player_pockets.cpp +++ b/src/entity_player_pockets.cpp @@ -481,7 +481,7 @@ void Entity_Player::pocket_use_input() } else if (used.type == POCKET_PILL) { - for (Entity* entity : g_game->room->GetEntities()->updateEL) + for (Entity* entity : entities_live(g_game->room->GetEntities()->updateEL)) if (entity->IsFamiliar() && static_cast(entity)->player == this) static_cast(entity)->farting_baby_fart(); save.IncreaseEventCounter(EVENT_PILLS_USED, 1); diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp index 11aeaaf..ef4fd72 100644 --- a/src/entity_player_room.cpp +++ b/src/entity_player_room.cpp @@ -2,6 +2,7 @@ #include "entity_player_passives.h" #include "boss_ai.h" #include "entity_familiar.h" +#include "grid_entity_rock.h" #include "room_grid.h" #include "game.h" #include "grid_entity_door.h" @@ -21,7 +22,6 @@ constexpr int NULL_ITEM_BELIAL = 123; constexpr int NULL_ITEM_FORGOTTEN_CHALLENGE = 106; constexpr int BELIAL_NULL_COUNT = 4; constexpr int VERSUS_EFFECT_COOLDOWN = 300; -constexpr int PLAYER_THE_FORGOTTEN_B = 35; constexpr int PLAYER_NO_DOGMA = 40; constexpr int CHALLENGE_FORGOTTEN_COSTUME = 42; constexpr int BETHS_ESSENCE_WISPS = 5; @@ -42,7 +42,6 @@ constexpr int DOOR_STOP_BOSS_RUSH_COPIES = 2; 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; // 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, @@ -267,7 +266,7 @@ static void friendly_followers_place(Entity_Player& player) if (door && door->direction >= DIRECTION_LEFT && door->direction <= DIRECTION_DOWN) way = vector_scale(vector_from_direction(door->direction), -1); - for (Entity* entity : room.entityList.updateEL) + for (Entity* entity : entities_live(room.entityList.updateEL)) { if (game.isRestoringGlowingHourglassState && entity->type == ENTITY_BLOOD_PUPPY) { @@ -313,7 +312,7 @@ void Entity_Player::room_enter() bool isDogmaRoom = data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME; if (isDogmaRoom && collectibleCounts[COLLECTIBLE_DOGMA] < 1 && playerType != PLAYER_NO_DOGMA) AddCollectible(COLLECTIBLE_DOGMA, 0, true, 0, 0); - if (playerType == PLAYER_THE_FORGOTTEN_B && game.challenge == CHALLENGE_FORGOTTEN_COSTUME) + if (playerType == PLAYER_THEFORGOTTEN_B && game.challenge == CHALLENGE_FORGOTTEN_COSTUME) { ItemConfig_Item* costume = g_manager->itemConfig.GetNullItem(NULL_ITEM_FORGOTTEN_CHALLENGE); for (PlayerCostumeMap& layer : playerCostumeMap) diff --git a/src/entity_player_update.cpp b/src/entity_player_update.cpp index b5e59fc..8fd6093 100644 --- a/src/entity_player_update.cpp +++ b/src/entity_player_update.cpp @@ -466,8 +466,8 @@ static void how_to_jump_update(Entity_Player& player) wave->SetTimeout(HOW_TO_JUMP_WAVE_FRAMES); } -// Judas's Birthright aura (the Book of Belial kept as a passive) burns around a leaping or reviving player, and Dark -// Arts' dash ends at the next shot: both stop the game until reached. +// Judas's Birthright aura (the Book of Belial kept as a passive) burns around a leaping or reviving player (it stops +// the game until reached), and Dark Arts' dash ends at the next shot. static void leap_auras_update(Entity_Player& player) { TemporaryEffects& effects = player.temporaryEffects; @@ -475,8 +475,13 @@ static void leap_auras_update(Entity_Player& player) effects.HasCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE); if (player.HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) && isLeaping) reconstruction_missing("Entity_Player::Update 00782af0 (the Book of Belial's burning aura)"); - if (effects.HasCollectibleEffect(COLLECTIBLE_DARK_ARTS)) - reconstruction_missing("Entity_Player::Update 00782af0 (Dark Arts ended by a shot)"); + if (!effects.HasCollectibleEffect(COLLECTIBLE_DARK_ARTS)) return; + for (ButtonAction shot : {ACTION_SHOOT_LEFT, ACTION_SHOOT_UP, ACTION_SHOOT_RIGHT, ACTION_SHOOT_DOWN}) + if (input_is_action_triggered(shot, player.controllerIndex, nullptr)) + { + effects.RemoveCollectibleEffect(COLLECTIBLE_DARK_ARTS, -1); + return; + } } // The timers the frame counts down: the hurt, controls, fire and item hold cooldowns, and the co-op babies' buffs, diff --git a/src/entity_projectile.cpp b/src/entity_projectile.cpp index f313c8e..0e8ad09 100644 --- a/src/entity_projectile.cpp +++ b/src/entity_projectile.cpp @@ -1,4 +1,5 @@ #include "entity_projectile.h" +#include "boss_repentance.h" #include "entity_bomb.h" #include "entity_combat.h" #include "entity_effect.h" @@ -15,6 +16,7 @@ #include "npc_ai.h" #include "npc_basement.h" #include "room.h" +#include "room_grid.h" #include #include #include @@ -48,8 +50,7 @@ constexpr uint64_t CHANGE_BOTH_FLAGS = constexpr uint64_t BURST3_CHILD_CLEARED = PROJECTILE_CURVE_LEFT | PROJECTILE_CURVE_RIGHT | PROJECTILE_SINE_VELOCITY; // The flags whose effects belong to the late bosses and items, and are not reconstructed. -constexpr uint64_t UNRECONSTRUCTED_FLAGS = - PROJECTILE_STASIS | PROJECTILE_LASER_SHOT | PROJECTILE_BROCCOLI | PROJECTILE_SIDE_WAVE; +constexpr uint64_t UNRECONSTRUCTED_FLAGS = PROJECTILE_STASIS | PROJECTILE_LASER_SHOT; constexpr uint64_t FIRE_FLAGS = PROJECTILE_FIRE_WAVE | PROJECTILE_FIRE_WAVE_X | PROJECTILE_FIRE_SPAWN; // The glow a fiery, Heretic's, blue fire or side wave shot carries. @@ -230,6 +231,10 @@ constexpr float BURST8_CHILD_SCALE = 0.66f; constexpr float BACK_SPLIT_TURN = 24; constexpr float BACK_SPLIT_SPEED = 10; constexpr float BACK_SPLIT_ACCEL = -0.04f; +constexpr float SIDE_WAVE_ACCELERATION = 1.12f; +constexpr float SIDE_WAVE_FALL = -0.04f; +constexpr float SIDE_WAVE_SPEED = 0.15f; +constexpr float SIDE_WAVE_TICKS = 8; constexpr int BURSTSPLIT_COUNT = 16; constexpr float BURSTSPLIT_SPEED_MIN = -10; constexpr float BURSTSPLIT_SPEED_MAX = -22; @@ -237,7 +242,6 @@ constexpr float BURSTSPLIT_ANGLE = 70; constexpr float BURSTSPLIT_ACCEL = 0.75f; constexpr float BURSTSPLIT_SCALE_MIN = 0.9f; constexpr ColorMod BURSTSPLIT_SPLASH_COLOR = {{1, 1, 1, 1}, {0.2f, 1.2f, 0, 1}, {0, 0, 0}}; -constexpr ColorMod BURSTSPLIT_COLOR = {{1, 1, 1, 1}, {2.7f, 3, 2, 1}, {0, 0, 0}}; // The splash a dead shot leaves: poof sizes and sounds, the creep its flags leave and the explosion. constexpr float POOF_SCALE_SHARE = 0.8f; @@ -332,11 +336,9 @@ constexpr std::array, CONTINUUM_COLORS> CONTINUUM_COLORIZES {0.66f, 0, 0.66f}, {1, 0, 1}}}; -constexpr int ENTITY_TARBOY = 307; constexpr int ENTITY_SHADY = 888; constexpr int MOTHER_BALL = 10; constexpr int BEAST_FIRE_BALL = 20; -constexpr int ROTGUT_HEART = 2; constexpr int EFFECT_BONE_PARTICLE = 35; constexpr int EFFECT_CORN_POOF = 43; @@ -345,8 +347,21 @@ constexpr int EFFECT_COIN_POOF = 97; constexpr int EFFECT_GODHEAD_AURA = 123; constexpr int EFFECT_DOGMA_POOF = 200; constexpr int GODHEAD_AURA_SUBTYPE = 4; -constexpr int BLOOD_EXPLOSION_SPLASH = 3; constexpr int ACID_SPLAT_SUBTYPE = 0; + +// Rotgut's heart's shots: two out of its fire's burst, thirteen out of its spit, each at 6 to 10 up. +constexpr float ROTGUT_SHOT_SPEED_MIN = -6; +constexpr float ROTGUT_SHOT_SPEED_MAX = -10; +constexpr float ROTGUT_BURST_TURN = 30; +constexpr float ROTGUT_BURST_RISE = -6; +constexpr int ROTGUT_BURST_TIMEOUT = 6; +constexpr float ROTGUT_BURST_FALL = 0.2f; +constexpr int ROTGUT_SPLIT_SHOTS = 13; +constexpr float ROTGUT_SPLIT_TURN = 75; +constexpr int ROTGUT_SPLIT_TIMEOUT = 45; +constexpr float ROTGUT_SPLIT_FALL = -0.1f; +constexpr float ROTGUT_SPLIT_SCALE = 0.8f; +constexpr float ROTGUT_SPLIT_SCALE_RANGE = 0.6f; constexpr int FIRE_POOF_SUBTYPE = 1; constexpr int BONE_PARTICLE_SUBTYPE = 1; @@ -542,6 +557,203 @@ float Entity_Projectile::time_scale_get() } // 00653070 Flies the shot for a frame: its animation, the base update, its flags' steering and wiggles, its fall, + +// A fly ball (a broccoli shot): a shot whose subtype counts the flies (less 100 past 100, which then carry the count) +// that orbit it from its first frame, itself unseen. It homes in on the nearest player (not Mother's), goes once its +// flies are gone, and bursts them out backwards when it dies. +constexpr int FLY_BALL_LIVE = 1000; +constexpr int FLY_BALL_NESTED = 100; +constexpr uint64_t FLY_FLAGS = PROJECTILE_BROCCOLI | PROJECTILE_NO_WALL_COLLIDE; +constexpr float FLY_BRIGHT = 4; +constexpr float FLY_RADIUS_X = 20; +constexpr float FLY_RADIUS_Y = 8; +constexpr float FLY_RADIUS_LEAST = 0.8f; +constexpr float FLY_RADIUS_RANGE = 0.2f; +constexpr float FLY_SCALE_LEAST = 1.4f; +constexpr float FLY_SCALE_RANGE = 0.6f; +constexpr int FLY_ORBIT_FRAMES = 30; +constexpr float FLY_ORBIT_HEIGHT = -23; +constexpr float FLY_BURST_SPREAD = 80; +constexpr float FLY_BURST_REACH = 6; +constexpr float FLY_BURST_SPEED = 9; +constexpr float FLY_BURST_SPEED_RANGE = 3; +constexpr float FLY_BURST_FALL = -0.094f; +constexpr int FLY_BURST_WIGGLE = 30; +constexpr float FLY_BALL_MARGIN = 3; +constexpr ColorMod FLY_POP_COLOR = {{1, 1, 1, 1}, {4, 5, 1, 1}, {0, 0, 0}}; +constexpr ColorMod FLY_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {81 / 255.0f, 112 / 255.0f, 29 / 255.0f}}; +constexpr float FLY_POP_SCALE = 1.5f; +constexpr float FLY_POP_RISE = -20; +constexpr float FLY_POP_DEPTH = 4; +constexpr int FLY_MAGGOTS = 6; +constexpr float FLY_MAGGOT_REACH = 80; +constexpr float FLY_MAGGOT_FREE_REACH = 64; +constexpr float FLY_MAGGOT_JITTER = 38; +constexpr float FLY_MAGGOT_HEIGHT = -30; +constexpr float FLY_MAGGOT_HEIGHT_RANGE = 15; +constexpr float FLY_MAGGOT_STEP = 15; +constexpr float FLY_SPLAT_SIZE = 1.5f; +constexpr int FLY_BURST_SHAKE = 5; + +// The flies still orbiting a fly ball. +static std::vector fly_ball_flies(Entity_Projectile& ball) +{ + std::vector flies; + for (Entity* fly : g_game->room->entityList.updateEL) + if (fly->type == ENTITY_PROJECTILE && fly->target == &ball) + flies.push_back(static_cast(fly)); + return flies; +} + +// Its first frame: the flies spawn about it, each bright one time in two, on an orbit of its own, and it hides. +static void fly_ball_init(Entity_Projectile& ball) +{ + if (!(ball.projectileFlags & PROJECTILE_BROCCOLI) || ball.subtype < 1 || ball.subtype >= FLY_BALL_LIVE) return; + + int count = ball.subtype > FLY_BALL_NESTED ? ball.subtype - FLY_BALL_NESTED : ball.subtype; + for (int i = 0; i < count; i++) + { + auto* fly = static_cast(g_game->Spawn( + {.position = ball.pos, .spawner = ball.spawnerEntity, .type = ENTITY_PROJECTILE, .seed = Random()})); + fly->target = &ball; + fly->parent = ball.parent.get(); + ColorMod color = ball.sprite.color; + float bright = random_below(2) == 0 ? FLY_BRIGHT : 1; + color._tint[0] = color._tint[1] = color._tint[2] = bright; + fly->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + fly->projectileFlags = FLY_FLAGS; + fly->homingStrength = random_unit() * FULL_TURN_DEGREES; + float radius = random_unit() * FLY_RADIUS_RANGE + FLY_RADIUS_LEAST; + fly->targetPosition = vector_scale(vector_make(FLY_RADIUS_X * ball.scale, FLY_RADIUS_Y * ball.scale), radius); + fly->scale = random_unit() * FLY_SCALE_RANGE + FLY_SCALE_LEAST; + if (ball.subtype > FLY_BALL_NESTED) fly->subtype = count; + } + ball.sprite.color._tint[3] = 0; + ball.subtype = FLY_BALL_LIVE; +} + +// A fly circles its ball on an ellipse turned by its own angle (its homing strength), once every 30 frames. +static void fly_orbit_update(Entity_Projectile& fly) +{ + Entity* ball = fly.target; + if (!(fly.projectileFlags & PROJECTILE_BROCCOLI) || !ball || !ball->IsProjectile()) return; + + Vector across = vector_scale(vector_from_angle(fly.homingStrength), fly.targetPosition.x); + Vector along = vector_scale(vector_from_angle(fly.homingStrength + RIGHT_ANGLE_DEGREES), fly.targetPosition.y); + float turn = + (float)((uint32_t)(g_game->frameCount + (int)fly.initSeed) % FLY_ORBIT_FRAMES) * TAU / FLY_ORBIT_FRAMES; + Vector spot = + vector_add(vector_add(ball->pos, vector_scale(across, std::cos(turn))), vector_scale(along, std::sin(turn))); + fly.velocity = vector_sub(spot, fly.pos); + fly.friction = 1; + fly.fallingSpeed = 0; + fly.height = FLY_ORBIT_HEIGHT; +} + +// The ball dies: its flies burst out backwards across 160 degrees (any way when it was still), with maggots and green +// creep but for Mother's, and a splat. +static void fly_ball_burst(Entity_Projectile& ball) +{ + ball.subtype = 0; + npc_sound_play(SOUND_DEATH_BURST_SMALL, 1, 2, 1); + Entity* pop = g_game->Spawn({.position = ball.pos, + .subType = 3, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + pop->sprite.scale = vector_make(FLY_POP_SCALE, FLY_POP_SCALE); + pop->posOffset = vector_make(0, FLY_POP_RISE); + pop->renderDepthOffset = FLY_POP_DEPTH; + pop->SetColor(FLY_POP_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + + std::vector flies = fly_ball_flies(ball); + Vector back = vector_scale(vector_normalized(ball.velocity), -1); + float first = -FLY_BURST_SPREAD; + float last = FLY_BURST_SPREAD; + if (vector_is_zero(back)) + { + back = random_direction(); + first = -HALF_TURN_DEGREES; + last = HALF_TURN_DEGREES; + } + float step = 0; + if (flies.size() < 2) first = 0; + else step = (last - first) / (float)(flies.size() - 1); + for (size_t i = 0; i < flies.size(); i++) + { + Entity_Projectile& fly = *flies[i]; + Vector direction = vector_rotated(back, (float)i * step + first); + fly.pos = vector_add(ball.pos, vector_scale(direction, FLY_BURST_REACH)); + fly.velocity = vector_scale(direction, random_unit() * FLY_BURST_SPEED_RANGE + FLY_BURST_SPEED); + fly.projectileFlags = PROJECTILE_HIT_ENEMIES; + if (fly.subtype == FLY_BALL_LIVE) fly.projectileFlags |= PROJECTILE_BROCCOLI; + fly.entityGridCollisionClass = GRIDCOLL_NOPITS; + fly.fallingAccel = FLY_BURST_FALL; + fly.target = nullptr; + fly.wiggleFrameOffset = random_below(FLY_BURST_WIGGLE); + } + + ball.pos = g_game->room->GetClampedPositionImpl(ball.pos, FLY_BALL_MARGIN, FLY_BALL_MARGIN, FLY_BALL_MARGIN, + FLY_BALL_MARGIN); + if (ball.spawnerType != ENTITY_MOTHER) + { + for (int i = 0; i < FLY_MAGGOTS; i++) + { + Vector spot = random_direction(); + spot = vector_add(ball.pos, vector_scale(spot, random_unit() * FLY_MAGGOT_REACH)); + if (room_grid_collision_at(spot) > 0) + { + float jitterY = random_unit() * FLY_MAGGOT_JITTER - FLY_MAGGOT_JITTER * HALF; + float jitterX = random_unit() * FLY_MAGGOT_JITTER - FLY_MAGGOT_JITTER * HALF; + spot = vector_add(room_free_tile_position_find(spot, FLY_MAGGOT_FREE_REACH), + vector_make(jitterX, jitterY)); + } + Vector away = vector_normalized(vector_sub(spot, ball.pos)); + float height = random_unit() * FLY_MAGGOT_HEIGHT_RANGE + FLY_MAGGOT_HEIGHT; + float reach = random_unit() * FLY_MAGGOT_STEP; + small_maggot_jump_spawn(vector_add(ball.pos, vector_scale(away, reach)), height, ball.pos); + } + Entity* creep = g_game->Spawn({.position = ball.pos, + .spawner = &ball, + .type = ENTITY_EFFECT, + .variant = EFFECT_CREEP_GREEN, + .seed = Random()}); + creep->sprite.scale = vector_make(FLY_POP_SCALE, FLY_POP_SCALE); + } + float size = (random_unit() * HALF + HALF) * FLY_SPLAT_SIZE; + Entity* splat = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, 0, ball.pos, &ball); + splat->sprite.scale = vector_make(size, size); + splat->Update(); + splat->SetColor(FLY_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + game_shake_screen(FLY_BURST_SHAKE); +} + +// A live fly ball homes in on the nearest player (Mother's flies straight), goes when its flies are all gone, and +// bursts when it dies. +static void fly_ball_update(Entity_Projectile& ball) +{ + if (!(ball.projectileFlags & PROJECTILE_BROCCOLI) || ball.subtype != FLY_BALL_LIVE) return; + if (ball.isDead) return fly_ball_burst(ball); + + if (ball.spawnerType != ENTITY_MOTHER) + { + if (!ball.target) + if (Entity_Player* player = game_nearest_player(ball.pos)) ball.target = player; + if (Entity* target = ball.target) + { + Vector aim = vector_normalized(vector_sub(target->pos, ball.pos)); + if (vector_dot(ball.velocity, aim) > 0) + { + float speed = vector_length(ball.velocity); + ball.velocity = + vector_resized(vector_add(ball.velocity, vector_scale(aim, ball.speedMultiplier)), speed); + } + } + } + if (ball.GetIntervalTicks(4, 0) && fly_ball_flies(ball).empty()) ball.Remove(); +} + // and its splash once it has died. A shot the Broken Modem froze waits, then vanishes. void Entity_Projectile::Update() { @@ -565,13 +777,18 @@ void Entity_Projectile::Update() projectileFlags &= ~(PROJECTILE_GHOST | PROJECTILE_NO_WALL_COLLIDE); } Entity::Update(); - if (FrameCount() == 1) first_frame_update(); + if (FrameCount() == 1) + { + first_frame_update(); + fly_ball_init(*this); + } if (projectileFlags & PROJECTILE_BURST8) { bool isBloodfly = subtype == 0 && spawnerType == ENTITY_SUCKER && spawnerVariant == SUCKER_BLOODFLY; if (updateTime > (isBloodfly ? BURST8_BLOODFLY_LIFE : BURST8_LIFE)) isDead = true; } + fly_orbit_update(*this); trails_update(); if (isDead) return death_update(); @@ -894,19 +1111,60 @@ void Entity_Projectile::glow_trail_spawn(bool isPurple) particle->Update(); } -// The trails shots leave: a blue fire spawning shot's and a Necro bone's glow. The Beast's and Mother's are not -// reconstructed. +// A side wave shot sheds two speeding shots off its sides every 8 ticks, of its color and height. +static void side_wave_spawn(Entity_Projectile& shot) +{ + Vector across = vector_rotated(shot.velocity, RIGHT_ANGLE_DEGREES); + for (int side = -1; side < 2; side += 2) + { + uint32_t seed = Random(); + Vector velocity = vector_scale(across, SIDE_WAVE_SPEED * (float)side); + auto* wave = static_cast( + g_game->Spawn({.position = shot.pos, .velocity = velocity, .type = ENTITY_PROJECTILE, .seed = seed})); + wave->spawnerEntity = shot.spawnerEntity.get(); + wave->spawnerType = shot.spawnerType; + wave->spawnerVariant = shot.spawnerVariant; + wave->SetColor(shot.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + wave->height = shot.height; + wave->projectileFlags = PROJECTILE_ACCELERATE; + wave->fallingAccel = SIDE_WAVE_FALL; + wave->acceleration = SIDE_WAVE_ACCELERATION; + wave->Update(); + } +} + +// The trails shots leave: a blue fire spawning shot's and a Necro bone's glow, a side wave's shots, and the drops +// Mother's pound shots leave. The Beast's is not reconstructed. void Entity_Projectile::trails_update() { if ((projectileFlags & PROJECTILE_BLUE_FIRE_SPAWN) && GetIntervalTicks(TRAIL_TICKS, 0)) glow_trail_spawn(false); else if (spawnerType == ENTITY_NECRO && variant == PROJECTILE_BONE && GetIntervalTicks(TRAIL_TICKS, 0)) glow_trail_spawn(true); + if ((projectileFlags & PROJECTILE_SIDE_WAVE) && GetIntervalTicks(SIDE_WAVE_TICKS, 0)) side_wave_spawn(*this); bool isBeastFire = (projectileFlags & PROJECTILE_EXPLODE) && spawnerType == ENTITY_BEAST && spawnerVariant == BEAST_FIRE_BALL; + if (isBeastFire) reconstruction_missing("Entity_Projectile::Update 00653070: the Beast's fire trail"); + fly_ball_update(*this); + + // Mother's pound shots drop a falling shot of their color every 4 frames. + constexpr float MOTHER_TRAIL_SPEED = 0.2f; + constexpr float MOTHER_TRAIL_RISE = -6; + constexpr float MOTHER_TRAIL_FALL = 1; bool isMotherShot = spawnerType == ENTITY_MOTHER && spawnerVariant == 0 && subtype == 1; - if (isBeastFire || isMotherShot) - reconstruction_missing("Entity_Projectile::Update 00653070: a late boss's shot trail"); + if (!isMotherShot || !GetIntervalTicks(4, 0)) return; + uint32_t seed = Random(); + auto* drop = static_cast(g_game->Spawn({.position = pos, + .velocity = vector_scale(velocity, MOTHER_TRAIL_SPEED), + .type = ENTITY_PROJECTILE, + .seed = seed})); + drop->spawnerEntity = spawnerEntity.get(); + drop->spawnerType = spawnerType; + drop->spawnerVariant = spawnerVariant; + drop->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + drop->fallingSpeed = MOTHER_TRAIL_RISE; + drop->fallingAccel = MOTHER_TRAIL_FALL; + drop->Update(); } // Its splash: a poof by its variant or an explosion, the creep and splits its flags leave, then it is removed. @@ -1176,15 +1434,57 @@ void Entity_Projectile::death_flags_apply() if (isPin) npc_sound_play(SOUND_PIN_GOO, 1, 2, 1); } +// Rotgut's heart's fire bursting into two shots, 30 degrees either side of up, that start bouncing after 6 frames. +static void rotgut_burst_spawn(Entity_Projectile& shot) +{ + for (int side = -1; side <= 1; side += 2) + { + uint32_t seed = Random(); + float speed = lerp(ROTGUT_SHOT_SPEED_MIN, ROTGUT_SHOT_SPEED_MAX, random_unit()); + Vector velocity = vector_rotated(vector_make(0, speed), (float)side * ROTGUT_BURST_TURN); + Entity_Projectile* child = child_spawn(shot, {.position = vector_add(shot.pos, vector_make(0, ROTGUT_BURST_RISE)), + .velocity = velocity, + .spawner = shot.spawnerEntity, + .type = ENTITY_PROJECTILE, + .seed = seed}); + child->projectileFlags = PROJECTILE_NO_WALL_COLLIDE | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT; + child->changeFlags = 0; + child->changeTimeout = ROTGUT_BURST_TIMEOUT; + child->fallingAccel = ROTGUT_BURST_FALL; + child->SetColor(SHOT_COLOR_FIERY, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + } +} + +// Rotgut's heart's spit splitting into a fan of 13 shots up across 150 degrees that bounce after 45 frames, keeping +// its other flags. +static void rotgut_split_spawn(Entity_Projectile& shot) +{ + uint64_t kept = shot.projectileFlags & ~PROJECTILE_BURSTSPLIT; + for (int i = 0; i < ROTGUT_SPLIT_SHOTS; i++) + { + float speed = lerp(ROTGUT_SHOT_SPEED_MIN, ROTGUT_SHOT_SPEED_MAX, random_unit()); + float angle = lerp_range((float)i, {.inMax = ROTGUT_SPLIT_SHOTS - 1, .outMin = -ROTGUT_SPLIT_TURN, .outMax = ROTGUT_SPLIT_TURN}); + Entity_Projectile* child = child_spawn(shot, {.position = shot.pos, + .velocity = vector_rotated(vector_make(0, speed), angle), + .spawner = shot.spawnerEntity, + .type = ENTITY_PROJECTILE, + .seed = Random()}); + child->projectileFlags = kept | PROJECTILE_CHANGE_FLAGS_AFTER_TIMEOUT | PROJECTILE_BOUNCE; + child->changeFlags = kept; + child->changeTimeout = ROTGUT_SPLIT_TIMEOUT; + child->fallingAccel = ROTGUT_SPLIT_FALL; + child->scale = random_unit() * ROTGUT_SPLIT_SCALE_RANGE + ROTGUT_SPLIT_SCALE; + } +} + // The shots a dead shot splits into: four for BURST (a cross from Pin's), eight or six for BURST8, two back for // BACK_SPLIT and a fan of sixteen for BURSTSPLIT. void Entity_Projectile::death_bursts_spawn() { - if (projectileFlags & PROJECTILE_BURST) + bool isRotgutHeart = spawnerType == ENTITY_ROTGUT && spawnerVariant == ROTGUT_HEART; + if ((projectileFlags & PROJECTILE_BURST) && isRotgutHeart) rotgut_burst_spawn(*this); + else if (projectileFlags & PROJECTILE_BURST) { - if (spawnerType == ENTITY_ROTGUT && spawnerVariant == ROTGUT_HEART) - reconstruction_missing("Entity_Projectile::Update 00653070: Rotgut's bursting shot"); - bool isPin = spawnerType == ENTITY_PIN; float speed = vector_length(velocity); Vector shot = isPin ? vector_make(speed, 0) : vector_scale(random_direction(), speed); @@ -1280,12 +1580,11 @@ void Entity_Projectile::death_bursts_spawn() } if (!(projectileFlags & PROJECTILE_BURSTSPLIT)) return; - if (spawnerType == ENTITY_ROTGUT && spawnerVariant == ROTGUT_HEART) - reconstruction_missing("Entity_Projectile::Update 00653070: Rotgut's split shot"); sound_play(SOUND_BLOOD_SPLASH, 1, 1); Entity_Effect* splash = effect_spawn(EFFECT_BLOOD_EXPLOSION, pos, nullptr, BLOOD_EXPLOSION_SPLASH); if (splash) splash->SetColor(BURSTSPLIT_SPLASH_COLOR, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + if (isRotgutHeart) return rotgut_split_spawn(*this); for (int i = 0; i < BURSTSPLIT_COUNT; i++) { float speed = lerp(BURSTSPLIT_SPEED_MIN, BURSTSPLIT_SPEED_MAX, random_unit()); @@ -1298,7 +1597,7 @@ void Entity_Projectile::death_bursts_spawn() .seed = Random()}); if (!child) continue; - child->SetColor(BURSTSPLIT_COLOR, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); + child->SetColor(SHOT_COLOR_SICK_PALE, COLOR_PRIORITY_NONE, COLOR_PRIORITY, false, true); child->projectileFlags = projectileFlags & ~(PROJECTILE_BURSTSPLIT | PROJECTILE_EXPLODE); child->fallingAccel = BURSTSPLIT_ACCEL; child->scale = random_unit() * BURST_SCALE_SHARE + BURSTSPLIT_SCALE_MIN; diff --git a/src/entity_projectile.h b/src/entity_projectile.h index f2ab5dd..059565b 100644 --- a/src/entity_projectile.h +++ b/src/entity_projectile.h @@ -24,6 +24,12 @@ enum ProjectileVariant : int PROJECTILE_PEEP }; +// The tints the late bosses' shots take: sickly green, its paler glow, the rotten orange and the fiery one. +constexpr ColorMod SHOT_COLOR_SICK = {{1, 1, 1, 1}, {1.5f, 2, 1, 1}, {0, 0, 0}}; +constexpr ColorMod SHOT_COLOR_SICK_PALE = {{1, 1, 1, 1}, {2.7f, 3, 2, 1}, {0, 0, 0}}; +constexpr ColorMod SHOT_COLOR_ROTTEN = {{1, 1, 1, 1}, {3, 2, 1, 1}, {0, 0, 0}}; +constexpr ColorMod SHOT_COLOR_FIERY = {{1, 1, 1, 1}, {3.5f, 2.5f, 1, 1}, {0, 0, 0}}; + // Lua's ProjectileFlags: how a shot flies and what it does when it lands. // FIRE is PROJECTILE_FIRE_FLAG, the variant taking the plain name. enum ProjectileFlag : uint64_t diff --git a/src/entity_slot.cpp b/src/entity_slot.cpp index f3dc602..734fb44 100644 --- a/src/entity_slot.cpp +++ b/src/entity_slot.cpp @@ -1258,6 +1258,82 @@ void Entity_Slot::donation_pay(Entity_Player& player) state = SLOT_STATE_BROKEN; } +// The Greed donation machine's unlocks by its count, the last two at 1000 and when it first reaches 999, which sets +// off fireworks 80 above it for 450 frames. +constexpr std::array, 4> GREED_DONATION_EARLY_UNLOCKS = {{{2, 242}, {14, 243}, {33, 244}, {68, 245}}}; +constexpr std::array, 6> GREED_DONATION_LATE_UNLOCKS = { + {{111, ACHIEVEMENT_EVERYTHING_IS_TERRIBLE_2}, {234, 247}, {439, 248}, {500, 341}, {666, 249}, {879, 250}}}; +constexpr int ACHIEVEMENT_GREED_DONATION_FULL = 251; +constexpr int ACHIEVEMENT_GREED_DONATION_LAST = 275; +constexpr int FIREWORKS_TIMEOUT = 450; +constexpr float FIREWORKS_RISE = -80; +constexpr float GREED_JAM_ROLL = 100; + +// The Greed donation machine takes a coin: counted (and in the player's own counter) when the player or its spawner +// gave it, shown on its digits, unlocking achievements as it grows and at 1000 blowing up into dimes. It jams by the +// player's jam chance. +void Entity_Slot::greed_donation_pay(Entity_Player& player) +{ + PersistentGameData& data = *persistentData; + int count = (int)(data.eventCounters[EVENT_COUNTER_GREED_DONATIONS] % COUNTER_LIMIT); + + state = SLOT_STATE_IDLE; + if (isUnknown544) + { + if ((uint32_t)player.playerType < (uint32_t)COMPLETION_PLAYER_TYPE_COUNT) + data.IncreaseEventCounter(COMPLETION_MARKS[player.playerType][COMPLETION_GREED_DONATION].counter, 1); + data.IncreaseEventCounter(EVENT_COUNTER_GREED_DONATIONS, 1); + count++; + } + counter_show(count); + for (auto [needed, achievement] : GREED_DONATION_EARLY_UNLOCKS) + if (count >= needed) data.TryUnlock(achievement); + if (count >= COUNTER_FULL && data.TryUnlock(ACHIEVEMENT_GREED_DONATION_LAST)) + { + auto* fireworks = static_cast(g_game->Spawn( + {.position = pos, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_FIREWORKS, .seed = Random()})); + fireworks->SetTimeout(FIREWORKS_TIMEOUT); + fireworks->posOffset = vector_make(0, FIREWORKS_RISE); + fireworks->Update(); + } + for (auto [needed, achievement] : GREED_DONATION_LATE_UNLOCKS) + if (count >= needed) data.TryUnlock(achievement); + + if (count == COUNTER_FULL) + { + touch = 0; + timeout = COUNTER_DONE_FRAMES; + } + else + { + if (count >= COUNTER_LIMIT) + { + data.TryUnlock(ACHIEVEMENT_GREED_DONATION_FULL); + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + sprite.Play("Death"); + state = SLOT_STATE_BROKEN; + for (int i = 0; i < DONATION_PAYOUT_DIMES; i++) + { + Vector velocity = throw_velocity_get(pos, nullptr); + g_game->Spawn({.position = pos, + .velocity = velocity, + .subType = COIN_DIME, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = dropRNG.Next()}); + } + } + timeout = (int16_t)std::max(0, COIN_FRAMES - touch / TOUCH_SLOWDOWN); + } + npc_sound_play(SOUND_COIN_SLOT, 1, 2, 1); + + float jamChance = player.GetGreedDonationJamChance(data); + if (state == SLOT_STATE_BROKEN || dropRNG.RandomFloat() * GREED_JAM_ROLL >= jamChance) return; + sprite.Play(COIN_JAM_ANIMATIONS[Random() & 3]); + g_game->gameStateFlags |= 1ull << GAME_STATE_GREED_SLOT_JAMMED; + state = SLOT_STATE_BROKEN; +} + // The Bomb Bum pays its rolled prize: coins (or with Daemon's Tail most likely), hearts, or a Bomb Bum's collectible it // leaves for. void Entity_Slot::bomb_bum_pay(Entity_Player& player, RNG& prizeRng, int count) @@ -1485,8 +1561,7 @@ void Entity_Slot::payout(Entity_Player& player) restock_pay(player); break; case SLOT_GREED_DONATION_MACHINE: - if (sprite.overlayAnimState.IsEventTriggered("CoinInsert")) - reconstruction_missing("Entity_Slot::Update 0065d950: the Greed donation machine's coin"); + if (sprite.overlayAnimState.IsEventTriggered("CoinInsert")) greed_donation_pay(player); break; case SLOT_BATTERY_BUM: battery_bum_pay(player, prizeRng, count); diff --git a/src/entity_slot.h b/src/entity_slot.h index 38c74d2..8b4eccb 100644 --- a/src/entity_slot.h +++ b/src/entity_slot.h @@ -98,6 +98,7 @@ private: void shell_game_pay(Entity_Player& player, RNG& prizeRng, int count); void key_master_pay(RNG& prizeRng); void donation_pay(Entity_Player& player); + void greed_donation_pay(Entity_Player& player); void bomb_bum_pay(Entity_Player& player, RNG& prizeRng, int count); void restock_pay(Entity_Player& player); void battery_bum_pay(Entity_Player& player, RNG& prizeRng, int count); diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index 4812c29..55a6c13 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -53,11 +53,6 @@ constexpr float HOVER_OFFSET_SCALE = 0.4f; constexpr float FIXED_HEIGHT_OFFSET = -8; constexpr float GFUEL_NAIL_OFFSET = -12; -// The scale each RegularTear%d animation (1 to 13) draws at, the one a tear plays being the first at least its scale -// less the margin. A grown tear scales its layers by its scale over its animation's. -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}; @@ -262,6 +257,12 @@ 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 HORN_HAND_HOLD = 50; +constexpr float HORN_HAND_LEAD = 8; +constexpr float HORN_HAND_MARGIN = 10; +constexpr float HORN_HAND_RISE = 20; +constexpr float HORN_HAND_SPREAD = 40; +constexpr size_t HORN_HANDS_MAX = 2; // How Tiny Planet's and My Reflection's tears are thrown when fired. constexpr float ORBIT_FALL_SCALE = 3; @@ -2015,6 +2016,42 @@ static void knockback_apply(Entity& entity, Entity& source) entity.AddVelocity_divided(vector_scale(direction, BLADE_PUSH), false); } +// Little Horn's hand reaches up under a hit enemy (ahead of a boss or player, which it does not hold), unless two +// hands are out or a solid grid entity stands there. A held enemy stands still and flees. +static void horn_hand_grab(Entity& entity, Entity* source) +{ + Room& room = *g_game->room; + Vector at = entity.pos; + bool isHeavy = entity.IsBoss() || entity.config->isBoss || entity.type == ENTITY_PLAYER; + if (isHeavy) + { + Vector ahead = vector_add(entity.pos, vector_scale(entity.velocity, HORN_HAND_LEAD)); + float rise = -HORN_HAND_RISE - random_unit() * HORN_HAND_RISE; + float side = random_unit() * HORN_HAND_SPREAD - HORN_HAND_SPREAD * HALF; + at = room.GetClampedPositionImpl(vector_make(ahead.x + side, ahead.y + rise), HORN_HAND_MARGIN, HORN_HAND_MARGIN, + HORN_HAND_MARGIN, HORN_HAND_MARGIN); + } + GridEntity* grid = room_grid_entity_at(at); + if (grid && grid->collisionClass != COLLISION_NONE) return; + + std::vector hands = entity_query(ENTITY_EFFECT, EFFECT_BIG_HORN_HAND); + if (hands.size() >= HORN_HANDS_MAX) return; + + bool isFlipped = Random() & 1; + if (hands.size() == 1) isFlipped = !hands[0]->sprite.isFlipX; + if (!isHeavy) + { + static_cast(entity).hold_set(HORN_HAND_HOLD, at); + entity.AddFear(EntityRef(source), -HORN_HAND_HOLD, false); + } + Entity* spawner = source && source->spawnerEntity ? source->spawnerEntity.get() : source; + Entity* hand = g_game->Spawn({.position = at, .spawner = spawner, .type = ENTITY_EFFECT, + .variant = EFFECT_BIG_HORN_HAND, .seed = Random()}); + hand->target = &entity; + hand->sprite.isFlipX = isFlipped; + hand->Update(); +} + // 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. @@ -2033,8 +2070,7 @@ void Entity_Tear::ApplyTearFlagEffects(Entity* entity, const Vector& position, c 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_HORN] && isActiveEnemy && !entity->HasEntityFlags(FLAG_NO_TARGET)) horn_hand_grab(*entity, source); 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); diff --git a/src/entity_tear.h b/src/entity_tear.h index b3fcf4f..9c16ec7 100644 --- a/src/entity_tear.h +++ b/src/entity_tear.h @@ -2,8 +2,15 @@ #include "entity.h" #include "anm2.h" +#include #include +// The scale each RegularTear%d animation (1 to 13) draws at, the one a tear plays being the first at least its scale +// less the margin. A grown tear scales its layers by its scale over its animation's. +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; + // Lua's TearFlags bits the game reads. Bits 84 and 101 to 103 have no Lua name: It Hurts' creep on death, flags // swapped in on an interval, a speed reset on an interval, and steering back toward the parent. enum TearFlagBit : int @@ -323,6 +330,7 @@ struct Entity_Tear : Entity void fetus_hit(Entity& enemy); void belial_turn(); void rift_open(); + void jacobs_ladder_spark(Entity* target); void fire_split_projectiles(bool isHalved); void SetDeadEyeIntensity(float intensity); Entity_Tear* MakeMultidimensionalCopy(Entity* spawner); @@ -414,6 +422,7 @@ 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); +int tear_variant_blood(int variant); // Game::AttractEntities' arguments: where everything is pulled to, how hard and how far, and the one entity spared. struct Attraction diff --git a/src/entity_tear_death.cpp b/src/entity_tear_death.cpp index 06a1b6d..a17c1a4 100644 --- a/src/entity_tear_death.cpp +++ b/src/entity_tear_death.cpp @@ -4,6 +4,7 @@ #include "entity_familiar.h" #include "entity_knife.h" #include "entity_player.h" +#include "entity_effect.h" #include "game.h" #include "log.h" #include "manager.h" @@ -540,19 +541,31 @@ void Entity_Tear::blood_stains_spawn() } } -// 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*) +// 00676be0 Applies what its flags do when it dies above the floor: Parasite splits it in two, Compound Fracture into +// two shards and Jacob's Ladder sparks. A tear bouncing back up off water splits too, without explosions. +void Entity_Tear::apply_death_flag_effects(Entity* target) { 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_JACOBS] && isAbove) jacobs_ladder_spark(target); if (tearFlags[TEAR_RIFT]) rift_open(); } +// Jacob's Ladder: a chain lightning where the tear died at half its damage, starting from the enemy it hit, in its +// color (faded for a remote player's). +void Entity_Tear::jacobs_ladder_spark(Entity* target) +{ + Entity_Effect* chain = chain_lightning_spawn({.tearFlags = tearFlags, .position = pos, .spawner = spawnerEntity, + .damage = collisionDamage * 0.5f}); + if (target) chain->target = target; + ColorMod color = chain->sprite.color; + color._tint[3] *= tear_shot_alpha_get(*this); + chain->SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true); + chain->Update(); +} + // 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() diff --git a/src/entity_text.cpp b/src/entity_text.cpp index a4d0e0b..82bea4b 100644 --- a/src/entity_text.cpp +++ b/src/entity_text.cpp @@ -1,5 +1,28 @@ #include "entity_text.h" -#include "log.h" +#include "fx_layers.h" +#include "game.h" +#include "manager.h" + +#include +#include +#include + +constexpr KColor DAMAGE_TEXT_COLOR = kcolor_rgba(1, 0.392157f, 0.392157f, 1); +constexpr float FLOATING_RISE = -50; +constexpr float SCORE_GROW_RATE = 0.125f; +constexpr float SCORE_GROWN_SHRINK = 2.5f; +constexpr float SCORE_LIFT = 4; +constexpr float SCORE_START_SCALE = 4; +constexpr float DAMAGE_WOBBLE_RATE = 0.2f; +constexpr float DAMAGE_WOBBLE_WIDTH = 15; +constexpr int DAMAGE_FADE_FRAMES = 10; +constexpr int DAMAGE_LIFETIME = 25; +constexpr int FLOATING_LIFETIME = 90; +constexpr int OTHER_LIFETIME = 1000; +constexpr int SCORE_FLICKER_FRAMES = 15; +constexpr int SCORE_LIFETIME = 35; +constexpr int TEXT_FORMAT_LENGTH = 256; +constexpr int TEXT_RENDER_Z = 1000000; // 005ccc20 Collides with nothing it reacts to, letting the collision through. bool Entity_Text::HandleCollision(Entity*, bool) @@ -7,28 +30,104 @@ bool Entity_Text::HandleCollision(Entity*, bool) return true; } -// The rest of Entity_Text is not reconstructed yet. - -// 005ccca0 -void Entity_Text::Init(int, int, int, uint32_t) +// 005ccca0 A white, collisionless text drawn above everything, red and short for damage numbers. +void Entity_Text::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) { - reconstruction_missing("Entity_Text::Init 005ccca0"); + Entity::Init(entityType, entityVariant, entitySubType, seed); + timer = 0; + renderZOffset = TEXT_RENDER_Z; + textColor = WHITE; + entityGridCollisionClass = GRIDCOLL_NONE; + entityCollisionClass = ENTCOLL_NONE; + shadowSize = 0; + + switch (variant) + { + case TEXT_FLOATING: lifetime = FLOATING_LIFETIME; break; + case TEXT_DAMAGE: + textColor = DAMAGE_TEXT_COLOR; + lifetime = DAMAGE_LIFETIME; + break; + case TEXT_SCORE: lifetime = SCORE_LIFETIME; break; + default: lifetime = OTHER_LIFETIME; break; + } } -// 005ccd80 +// The damage number's sideways sway at a frame count since its spawn, mirrored for odd indices. +float Entity_Text::wobble_get(float frames) +{ + return std::sin(frames * DAMAGE_WOBBLE_RATE) * (index & 1 ? -DAMAGE_WOBBLE_WIDTH : DAMAGE_WOBBLE_WIDTH); +} + +// 005ccd80 Fades and sways the text by variant, writing its number on the first frame, moves it and removes it past +// its lifetime. void Entity_Text::Update() { - reconstruction_missing("Entity_Text::Update 005ccd80"); + char buffer[TEXT_FORMAT_LENGTH]; + + switch (variant) + { + case TEXT_FLOATING: + { + float fade = 1 - (float)timer / (float)lifetime; + textColor._alpha = fade * fade; + posOffset = vector_make(0, (1 - textColor._alpha) * FLOATING_RISE); + break; + } + case TEXT_DAMAGE: + if (timer == 0) + { + std::snprintf(buffer, sizeof(buffer), "%g", (double)targetPosition.x); + text = buffer; + } + textColor._alpha = (float)std::min(lifetime - timer, DAMAGE_FADE_FRAMES) / DAMAGE_FADE_FRAMES; + posOffset = vector_make(wobble_get((float)(g_game->frameCount - spawnFrame)), 0); + break; + case TEXT_SCORE: + { + if (timer == 0) + { + std::snprintf(buffer, sizeof(buffer), "%d", (int)targetPosition.x); + text = buffer; + } + bool isFlickeredOff = timer >= lifetime - SCORE_FLICKER_FRAMES && timer & 1; + textColor = WHITE; + textColor._alpha = isFlickeredOff ? 0 : 1; + break; + } + } + + timer++; + velocity = vector_scale(velocity, friction); + friction = baseFriction; + pos = vector_add(pos, velocity); + if (timer > lifetime) Remove(); } -// 005cd2e0 +// 005cd2e0 Keeps the damage number's sway smooth on the in-between frame. void Entity_Text::Interpolate() { - reconstruction_missing("Entity_Text::Interpolate 005cd2e0"); + if (variant == TEXT_DAMAGE) + posOffset = vector_make(wobble_get((float)(g_game->frameCount - spawnFrame) + HALF), 0); + Entity::Interpolate(); } -// 005ccfc0 -void Entity_Text::Render(const Vector&) +// 005ccfc0 Draws the text centred on its screen position, the score growing in from four times its size. +void Entity_Text::Render(const Vector& offset) { - reconstruction_missing("Entity_Text::Render 005ccfc0"); + if (!isExists) return; + + Font& font = g_manager->font6_PFTempestaSevenCondensed; + FontSettings settings; + float width = (float)font.GetStringWidth(text); + renderPosition = vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset); + if (variant != TEXT_SCORE) + return font.DrawString(text, vector_make(renderPosition.x - width * HALF, renderPosition.y), vector_make(1, 1), + textColor, settings); + + int flicker = g_game->IsPaused() ? 0 : (int)(g_manager->framecount + 1) % 2; + float grown = std::clamp((float)(flicker + timer * 2) * SCORE_GROW_RATE, 0.0f, 1.0f); + float scale = SCORE_START_SCALE - grown * SCORE_GROWN_SHRINK; + Vector at = vector_make(renderPosition.x - width * HALF * scale, renderPosition.y - scale * SCORE_LIFT); + font.DrawString(text, at, vector_make(scale, scale), textColor, settings); } diff --git a/src/entity_text.h b/src/entity_text.h index fb41c42..b9ce71a 100644 --- a/src/entity_text.h +++ b/src/entity_text.h @@ -2,13 +2,31 @@ #include "entity.h" +#include + +// Entity_Text's variants: a fading rising text, Spider Mod's damage numbers and the score sheet's points. +enum TextVariant : int +{ + TEXT_FLOATING, + TEXT_DAMAGE, + TEXT_SCORE +}; + // Construction and destruction (005ccc60) are the defaults. -// A floating text the debug console and some effects show. +// A floating text drawn at its position: a number from targetPosition.x set on its first Update, fading out over its +// lifetime and then removed. struct Entity_Text : Entity { + std::string text; + KColor textColor{}; + int lifetime = 0; + int timer = 0; + void Init(int type, int variant, int subType, uint32_t initSeed) override; void Update() override; void Interpolate() override; void Render(const Vector& offset) override; bool HandleCollision(Entity* collider, bool isLow) override; + + float wobble_get(float frames); }; diff --git a/src/familiar_afterbirth.cpp b/src/familiar_afterbirth.cpp new file mode 100644 index 0000000..6b12d63 --- /dev/null +++ b/src/familiar_afterbirth.cpp @@ -0,0 +1,772 @@ +#include "entity_familiar.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "entity_tear.h" +#include "entity_npc.h" +#include "game.h" +#include "grid_entity_door.h" +#include "npc_ai.h" +#include "npc_basement.h" +#include "room.h" +#include "room_grid.h" +#include "seeds.h" +#include +#include + +// Isaac's Heart: how far behind the player's aim it keeps, its leash and pull, its top speed and drag, its charge, and +// the burst of a full charge (BFFS! making it wider): its fart's reach, the push and how long the push lasts by weight +// and distance, its sounds, its blood, its creep and the ring of tears and the tears BFFS! adds. +constexpr float HEART_AIM_OFFSET = 60; +constexpr float HEART_LEASH = 40; +constexpr float HEART_ROOM_MARGIN = 6; +constexpr float HEART_PULL = 0.4f; +constexpr float HEART_SPEED = 15; +constexpr float HEART_DRAG = 0.8f; +constexpr int HEART_CHARGE_FRAMES = 30; +constexpr int HEART_CHARGE_SHOWN = 18; +constexpr float HEART_BURST_RADIUS = 120; +constexpr float HEART_BFFS_BURST_RADIUS = 180; +constexpr float HEART_PUSH = 16; +constexpr LerpRange HEART_PUSH_FRAMES = {.inMin = 10, .inMax = 120, .outMin = 20, .outMax = 1}; +constexpr float HEART_BURST_VOLUME = 2; +constexpr int HEART_BLOOD_SUBTYPE = 3; +constexpr int HEART_BFFS_SPLATS = 3; +constexpr float HEART_SPLAT_SPEED_MIN = 8; +constexpr float HEART_SPLAT_SPEED_RANGE = 4; +constexpr float HEART_SPLAT_REACH = 10; +constexpr float HEART_CREEP_SCALE = 1.2f; +constexpr float HEART_BFFS_CREEP_SCALE = 3; +constexpr int HEART_CREEP_FRAMES = 450; +constexpr int HEART_TEARS = 8; +constexpr float HEART_TEAR_SPEED = 12; +constexpr float HEART_TEAR_DAMAGE = 8; +constexpr int HEART_BFFS_TEARS = 10; +constexpr float HEART_BFFS_TEAR_SPEED = 10; +constexpr float HEART_BFFS_TEAR_SPEED_MIN = 0.7f; +constexpr float HEART_BFFS_TEAR_SPEED_RANGE = 0.2f; +constexpr float HEART_BFFS_TEAR_ACCEL = 0.8f; +constexpr float HEART_BFFS_TEAR_RISE = 25; +constexpr float HEART_BFFS_TEAR_SIZE_RANGE = 0.05f; +constexpr float HEART_BFFS_TEAR_SMALL = 0.9f; +constexpr float HEART_BFFS_TEAR_BIG = 1.3f; +constexpr float HEART_BFFS_TEAR_BIG_DAMAGE = 12; +constexpr float HEART_DEATH_LIFT = -10; +constexpr float HEART_REVIVE_DROP = 10; + +// The burst of a fully charged Isaac's Heart: a fart that pushes the enemies around it away (the light and near ones +// longer), blood, red creep and a ring of blood tears, BFFS! adding splats and a spray of tears. +static void isaacs_heart_burst(Entity_Familiar& heart) +{ + bool isBffs = heart.player->HasCollectible(COLLECTIBLE_BFFS); + float radius = isBffs ? HEART_BFFS_BURST_RADIUS : HEART_BURST_RADIUS; + game_butter_bean_fart({.position = heart.pos, .source = heart.player, .radius = radius, .isShowEffect = false}); + for (Entity* enemy : entity_query_radius(heart.pos, radius, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->IsDescendantOf(heart.spawnerEntity) || enemy->mass <= 0 || + enemy->HasEntityFlags(FLAG_NO_KNOCKBACK) || enemy->HasEntityFlags(FLAG_FRIENDLY)) + continue; + + Vector away = vector_sub(enemy->pos, heart.pos); + float distance = vector_length(away); + away = vector_scale(away, 1 / distance); + float weight = isBffs ? std::sqrt(enemy->mass) : enemy->mass; + float gap = distance - (enemy->size + heart.size); + int frames = (int)std::floor(lerp_range(weight + gap, HEART_PUSH_FRAMES)); + enemy->AddKnockback(EntityRef(&heart), vector_scale(away, HEART_PUSH), frames, true); + } + familiar_sound_play(SOUND_MEAT_IMPACTS, {.volume = HEART_BURST_VOLUME}); + familiar_sound_play(SOUND_BLOODSHOOT); + g_game->Spawn({.position = heart.pos, + .spawner = &heart, + .subType = HEART_BLOOD_SUBTYPE + (isBffs ? 1 : 0), + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}) + ->Update(); + for (int i = 0; isBffs && i < HEART_BFFS_SPLATS; i++) + { + Vector direction = random_direction(); + uint32_t seed = Random(); + float speed = random_unit() * HEART_SPLAT_SPEED_RANGE + HEART_SPLAT_SPEED_MIN; + g_game->Spawn({.position = vector_add(heart.pos, vector_scale(direction, HEART_SPLAT_REACH)), + .velocity = vector_scale(direction, speed), + .spawner = &heart, + .subType = HEART_BLOOD_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = seed}) + ->Update(); + } + + auto* creep = static_cast(g_game->Spawn( + {.position = heart.pos, .spawner = &heart, .type = ENTITY_EFFECT, .variant = EFFECT_PLAYER_CREEP_RED, .seed = Random()})); + float creepScale = isBffs ? HEART_BFFS_CREEP_SCALE : HEART_CREEP_SCALE; + creep->sprite.scale = vector_make(creepScale, creepScale); + creep->SetTimeout(HEART_CREEP_FRAMES); + creep->Update(); + + for (int i = 0; i < HEART_TEARS; i++) + { + Vector direction = vector_from_angle((float)i * 360.0f * 0.125f); + Entity* tear = g_game->Spawn({.position = heart.pos, + .velocity = vector_scale(direction, HEART_TEAR_SPEED), + .spawner = &heart, + .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, + .seed = Random()}); + tear->SetCollisionDamage(HEART_TEAR_DAMAGE); + tear->Update(); + } + for (int i = 0; isBffs && i < HEART_BFFS_TEARS; i++) + { + Vector velocity = vector_scale(random_direction(), HEART_BFFS_TEAR_SPEED); + velocity = vector_scale(velocity, random_unit() * HEART_BFFS_TEAR_SPEED_RANGE + HEART_BFFS_TEAR_SPEED_MIN); + auto* tear = static_cast(g_game->Spawn({.position = heart.pos, + .velocity = velocity, + .spawner = &heart, + .type = ENTITY_TEAR, + .variant = TEAR_BLOOD, + .seed = Random()})); + tear->fallingAccel = HEART_BFFS_TEAR_ACCEL; + tear->fallingSpeed = -random_unit() * HEART_BFFS_TEAR_RISE; + bool isBig = random_below(2) != 0; + float size = random_unit() * HEART_BFFS_TEAR_SIZE_RANGE; + tear->SetScale(size + (isBig ? HEART_BFFS_TEAR_BIG : HEART_BFFS_TEAR_SMALL)); + tear->SetCollisionDamage(isBig ? HEART_BFFS_TEAR_BIG_DAMAGE : HEART_TEAR_DAMAGE); + tear->Update(); + } +} + +// Part of 0061da10: Isaac's Heart charges while the player shoots and bursts once fully charged when the shooting +// stops (or the player's mark is set). +static void isaacs_heart_charge(Entity_Familiar& heart) +{ + if (heart.fireCooldown < 1 && heart.sprite.IsFinished()) heart.sprite.Play("FloatDown"); + int fireDirection = heart.player->fireDirection; + Vector aim{}; + if (heart.TryAimAtMarkedTarget(aim, heart.lastDirection, nullptr) && heart.fireCooldown >= HEART_CHARGE_FRAMES) + fireDirection = DIRECTION_NONE; + if (!heart.CanPlayerFire()) return; + + ANM2& sprite = heart.sprite; + if (fireDirection == DIRECTION_NONE) + { + if (heart.fireCooldown < 1) return; + + if (heart.fireCooldown < HEART_CHARGE_FRAMES) sprite.Play("FloatDown"); + else + { + sprite.Play("ChargeAttack", PLAY_FORCED); + heart.fireCooldown = 0; + isaacs_heart_burst(heart); + } + heart.fireCooldown = 0; + return; + } + if (heart.fireCooldown < 1 && !sprite.IsFinished() && !sprite.animState.IsLoopingAnimation()) return; + + heart.fireCooldown = std::min(heart.fireCooldown + 1, HEART_CHARGE_FRAMES); + if (heart.fireCooldown > HEART_CHARGE_SHOWN && sprite.IsPlaying("FloatDown")) return sprite.Play("ChargeStart"); + if (sprite.IsFinished()) sprite.Play("ChargeLoop"); +} + +// Part of 0061da10: Isaac's Heart hangs behind the player's aim (behind the punching bag in its challenge, by the +// Forgotten's body for Tainted Forgotten) and charges with the player's shots. It bursts in blood when the player dies +// and comes back when the player is revived. +void isaacs_heart_update(Entity_Familiar& heart) +{ + Entity_Player& player = *heart.player; + Entity* leader = &player; + if (g_game->challenge == CHALLENGE_GUARDIAN) + { + std::vector bags = familiar_query(Entity_Familiar::PUNCHING_BAG); + if (!bags.empty()) leader = bags[0]; + } + else if (player.playerType == PLAYER_THEFORGOTTEN_B && player.twin_get()) leader = player.twin_get(); + + if (heart.state != 0) + { + if (player.isDead) return; + + heart.pos = vector_add(player.pos, vector_make(0, HEART_REVIVE_DROP)); + g_game->Spawn({.position = heart.pos, .spawner = &heart, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}) + ->Update(); + heart.state = 0; + heart.isVisible = true; + heart.shadowSize = heart.config->shadowSize; + heart.entityCollisionClass = ENTCOLL_ALL; + return; + } + + Vector anchor = leader->pos; + if (leader->is_player()) anchor = vector_sub(anchor, vector_scale(player.aimDirection, HEART_AIM_OFFSET)); + Vector spot = g_game->room->GetClampedPosition( + vector_add(anchor, vector_resized(vector_sub(heart.pos, anchor), HEART_LEASH)), HEART_ROOM_MARGIN); + float distance = vector_distance(heart.pos, anchor); + if (distance > HEART_LEASH) + { + heart.velocity = vector_scale(vector_sub(spot, heart.pos), (distance - HEART_LEASH) / distance * HEART_PULL); + if (vector_length(heart.velocity) > HEART_SPEED) heart.velocity = vector_resized(heart.velocity, HEART_SPEED); + } + heart.friction *= HEART_DRAG; + isaacs_heart_charge(heart); + if (!player.isDead) return; + + heart.state = 1; + heart.isVisible = false; + heart.shadowSize = 0; + heart.entityCollisionClass = ENTCOLL_NONE; + Entity* blood = g_game->Spawn( + {.position = heart.pos, .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + blood->posOffset = vector_make(0, HEART_DEATH_LIFT); + blood->SetColor(heart.splatColor, -1, 255, false, true); + blood->Update(); + heart.BloodExplode(); +} + +// Yo Listen!: the secret doors and rocks it points out, how long it hovers at one, its wandering pace and turn, and +// its drag. +constexpr int YO_LISTEN_DOOR_OPEN = 2; +constexpr int YO_LISTEN_ROCK_BROKEN = 2; +constexpr int YO_LISTEN_HOVER_FRAMES = 150; +constexpr int YO_LISTEN_WANDER = 2; +constexpr float YO_LISTEN_WANDER_PULL = 0.5f; +constexpr float YO_LISTEN_TURN_MIN = 0.1f; +constexpr float YO_LISTEN_TURN_RANGE = 0.2f; +constexpr int YO_LISTEN_WANDER_STEPS = 3; +constexpr int YO_LISTEN_WANDER_STEP_FRAMES = 30; +constexpr float YO_LISTEN_DRAG = 0.8f; +constexpr int SOUND_YO_LISTEN = 914; + +// The spots Yo Listen! can point out: closed doors to unvisited secret rooms, the crawlspace's rock and the tinted +// rock, while unbroken. +static std::vector yo_listen_secrets() +{ + Room& room = *g_game->room; + std::vector spots; + for (GridEntity_Door* door : room.doors) + { + bool isSecret = door && (door->targetRoomType == ROOM_SECRET || door->targetRoomType == ROOM_SUPERSECRET); + if (isSecret && door->state != YO_LISTEN_DOOR_OPEN && g_game->GetRoomByIdx(door->targetRoomIdx)->visitedCount == 0) + spots.push_back(room.GetGridPosition(door->gridIndex)); + } + auto rockAt = [&](int index) { return index >= 0 && index < ROOM_GRID_CELLS ? room.gridEntities[index] : nullptr; }; + GridEntity* dungeonRock = rockAt(room.dungeonRockIdx); + if (!(g_game->levelStateFlags & 1u << LEVEL_STATE_DUNGEON_ROCK_BROKEN) && dungeonRock && dungeonRock->IsBreakableRock() && + dungeonRock->state != YO_LISTEN_ROCK_BROKEN) + spots.push_back(room.GetGridPosition(room.dungeonRockIdx)); + GridEntity* tintedRock = rockAt(room.tintedRockIdx); + if (tintedRock && (tintedRock->type == GRID_ROCKT || tintedRock->type == GRID_ROCK_SS) && + tintedRock->state != YO_LISTEN_ROCK_BROKEN) + spots.push_back(room.GetGridPosition(room.tintedRockIdx)); + return spots; +} + +// 00632d90 Yo Listen! flies to a secret door or rock of the room and hovers there a while, calling out (wandering on +// for good when it was the last one). With none, it wanders the room, turning toward random spots. +void Entity_Familiar::ai_variant_111() +{ + if (vector_is_zero(targetPosition) && state < YO_LISTEN_WANDER) + { + std::vector spots = yo_listen_secrets(); + if (spots.empty()) + { + state = YO_LISTEN_WANDER; + targetPosition = g_game->room->GetRandomPosition(0); + } + else + { + familiar_sound_play(SOUND_YO_LISTEN); + targetPosition = spots[Random() % (uint32_t)spots.size()]; + state = spots.size() == 1 ? 1 : 0; + } + fireCooldown = YO_LISTEN_HOVER_FRAMES; + } + + Vector toward = vector_sub(targetPosition, pos); + if (state != YO_LISTEN_WANDER) + { + if (vector_length_squared(toward) > 1) toward = vector_normalized(toward); + velocity = vector_add(velocity, toward); + friction *= YO_LISTEN_DRAG; + if (fireCooldown > 0 && --fireCooldown == 0) targetPosition = {}; + return; + } + + if (vector_length_squared(velocity) >= 1) + { + float turn = random_unit() * YO_LISTEN_TURN_RANGE + YO_LISTEN_TURN_MIN; + float heading = angle_lerp(vector_angle(velocity), vector_angle(toward), turn); + velocity = vector_add(velocity, vector_scale(vector_from_angle(heading), std::min(vector_length(toward), YO_LISTEN_WANDER_PULL))); + } + else velocity = vector_add(velocity, vector_resized(toward, YO_LISTEN_WANDER_PULL)); + friction *= YO_LISTEN_DRAG; + if (fireCooldown > 0 && --fireCooldown == 0) + { + targetPosition = g_game->room->GetRandomPosition(0); + fireCooldown = (int)(Random() % YO_LISTEN_WANDER_STEPS + 1) * YO_LISTEN_WANDER_STEP_FRAMES; + } +} + +// GB Bug: the pickups it rerolls (free ones, or closed chests), its pickup and chest rolls, its dash speed and the +// player's motion it carries, its bumps into walls, its hiding and how long a versus match keeps it hidden. +constexpr int GB_BUG_PICKUPS[] = {10, 20, 90, 40, 30, 70, 300, 350, 69, 41, 42}; +constexpr RNG GB_BUG_REROLL_RNG = {0, 9, 5, 25}; +constexpr uint32_t GB_BUG_CHEST_ODDS = 10; +constexpr uint32_t GB_BUG_KEEP_CHEST_ODDS = 5; +constexpr int GB_BUG_ANY_PICKUP = 1; +constexpr uint32_t GB_BUG_LOCKED_CHEST_MASK = 3; +constexpr float GB_BUG_DASH_SPEED = 10; +constexpr float GB_BUG_DASH_INHERIT = 0.6f; +constexpr float GB_BUG_ROOM_MARGIN = -100; +constexpr int GB_BUG_WALL_HITS = -10; +constexpr int GB_BUG_RECOVER_FRAMES = 30; +constexpr int GB_BUG_HIDDEN_STAGES = 3; +constexpr int GB_BUG_VERSUS_HIDE_FRAMES = 300; + +// Part of 00618b00: GB Bug turns a pickup into a random one (a chest one time in ten), and a chest into another chest +// (a locked one in four) or now and then a random pickup. +static void gb_bug_reroll(Entity_Pickup& pickup) +{ + RNG rng = GB_BUG_REROLL_RNG; + rng._seed = pickup.initSeed; + bool isChest = Entity_Pickup::IsChest(pickup.variant) && rng.Next() % GB_BUG_KEEP_CHEST_ODDS != 0; + if (!isChest && rng.Next() % GB_BUG_CHEST_ODDS != 0) + return pickup.Morph(pickup.type, 0, GB_BUG_ANY_PICKUP, true, false, false); + + int chest = (rng.Next() & GB_BUG_LOCKED_CHEST_MASK) == 0 ? PICKUP_LOCKEDCHEST : PICKUP_CHEST; + pickup.Morph(pickup.type, chest, 0, true, false, false); +} + +// Part of 00618b00: dashing GB Bug rerolls the first free pickup or closed chest it meets and hides, and bumps along +// walls and out of the room like the chargers. +static void gb_bug_dash(Entity_Familiar& bug, bool isIncubus) +{ + if (isIncubus) + { + bug.FollowParent(); + bug.entityGridCollisionClass = GRIDCOLL_NONE; + if (!bug.isVisible) + { + bug.fireCooldown = 1; + return; + } + } + for (Entity* entity : entity_query_radius(bug.pos, bug.size, QUERY_PICKUPS)) + { + auto* pickup = entity->type == ENTITY_PICKUP ? static_cast(entity) : nullptr; + bool isFree = pickup && familiar_listed(GB_BUG_PICKUPS, pickup->variant) && pickup->price == 0 && !pickup->isDead; + if (!pickup || (!isFree && !(Entity_Pickup::IsChest(pickup->variant) && pickup->subtype != 0))) continue; + + g_game->Spawn({.position = bug.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + bug.isVisible = false; + familiar_sound_play(SOUND_EDEN_GLITCH); + bug.subtype = 1; + if (familiar_versus()) bug.fireCooldown = GB_BUG_VERSUS_HIDE_FRAMES; + return gb_bug_reroll(*pickup); + } + + Room& room = *g_game->room; + if (bug.isCollidesWithGrid || bug.fireCooldown < -1 || !room.IsPositionInRoom(bug.pos, GB_BUG_ROOM_MARGIN)) + { + bug.entityGridCollisionClass = GRIDCOLL_NONE; + if (GridEntity* grid = room_grid_entity_at(bug.pos)) grid->Hurt(1, EntityRef(bug.player)); + bug.velocity = vector_scale(bug.velocity, HALF); + if (--bug.fireCooldown < GB_BUG_WALL_HITS) bug.fireCooldown = GB_BUG_RECOVER_FRAMES; + } + bug.entityCollisionClass = ENTCOLL_ALL; +} + +// 00618b00 (FamiliarAI::gb_bug) GB Bug follows the player and, sent off (its target position set), dashes the way it +// was sent with some of the player's motion. Having rerolled something it hides for a while, then comes back. +void gb_bug_update(Entity_Familiar& bug) +{ + bool isIncubus = bug.IsLilithBirthrightIncubus(); + if (bug.subtype != 0) + { + bug.entityCollisionClass = ENTCOLL_NONE; + bug.isVisible = false; + bug.FollowParent(); + if (familiar_versus() && (bug.fireCooldown > 0 ? --bug.fireCooldown : bug.fireCooldown) == 0) bug.subtype = 0; + if (bug.subtype > GB_BUG_HIDDEN_STAGES) + { + bug.subtype = 0; + bug.fireCooldown = 0; + bug.sprite.Play("Collide"); + return; + } + if (bug.subtype == 0 || bug.state < 1) return; + if (bug.subtype == 1) + g_game->Spawn({.position = bug.pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + bug.subtype++; + return; + } + + bug.isVisible = true; + bug.state = 0; + if (bug.fireCooldown < 0) return gb_bug_dash(bug, isIncubus); + + bug.FollowParent(); + if (!bug.sprite.IsPlaying("Float")) bug.sprite.Play("Float"); + if (isIncubus && bug.fireCooldown > 1) bug.fireCooldown = 1; + if (bug.fireCooldown > 0) bug.fireCooldown--; + if (!vector_is_zero(bug.targetPosition) && bug.fireCooldown < 1) + { + Entity_Player& player = *bug.player; + bug.fireCooldown = -1; + bug.entityGridCollisionClass = isIncubus ? GRIDCOLL_NONE : GRIDCOLL_BULLET; + Vector inherited = player.velocity; + if (std::fabs(bug.targetPosition.x) <= std::fabs(bug.targetPosition.y)) inherited.y = 0; + else inherited.x = 0; + bug.velocity = vector_add(vector_scale(bug.targetPosition, GB_BUG_DASH_SPEED), + vector_scale(inherited, GB_BUG_DASH_INHERIT * 2)); + if (vector_length_squared(bug.velocity) < GB_BUG_DASH_SPEED * GB_BUG_DASH_SPEED) + bug.velocity = vector_scale(vector_normalized(bug.velocity), GB_BUG_DASH_SPEED); + bug.friction = 1; + bug.targetPosition = {}; + } + bug.entityCollisionClass = ENTCOLL_NONE; +} + +// Lil Gurdy: its charge (up to 90 frames, the dash's speed growing with it), the player's motion its dash carries, +// how far it lets the player go before following, its splats, its wall bumps (what they break, their thuds and the +// enemy it bounces toward), its dash's slowing and drag, and its bounce off enemies (kept up while it still charges). +constexpr int LIL_GURDY_CHARGE_CAP = 90; +constexpr float LIL_GURDY_DASH_BASE = 5; +constexpr float LIL_GURDY_DASH_RANGE = 20; +constexpr float LIL_GURDY_DASH_INHERIT = 0.6f; +constexpr float LIL_GURDY_AIM_DEADZONE = 0.5f; +constexpr float LIL_GURDY_LEASH_SQUARED = 2500; +constexpr float LIL_GURDY_FOLLOW_PULL = 0.05f; +constexpr float LIL_GURDY_DRAG = 0.8f; +constexpr uint32_t LIL_GURDY_IDLE_SPLAT_ODDS = 3; +constexpr float LIL_GURDY_IDLE_SPLAT_INTERVAL = 10; +constexpr float LIL_GURDY_SPLAT_MIN = 0.2f; +constexpr float LIL_GURDY_SPLAT_RANGE = 0.5f; +constexpr float LIL_GURDY_SPLAT_STEP = 10; +constexpr float LIL_GURDY_SPLAT_FASTEST = 2; +constexpr float LIL_GURDY_WALL_DAMAGE_STEP = 10; +constexpr float LIL_GURDY_WALL_DAMAGE_CAP = 4; +constexpr float LIL_GURDY_HIT_RESET_SQUARED = 64; +constexpr TargetSearch LIL_GURDY_SEARCH = {.coneAngle = 15, .range = 800, .frameInterval = 0, .flags = TARGET_RETARGET | TARGET_NOT_NEAR_PLAYER | TARGET_PREFER_WEAK}; +constexpr float LIL_GURDY_LOUD_BUMP = 20; +constexpr float LIL_GURDY_SOFT_BUMP = 4; +constexpr float LIL_GURDY_BUMP_STEP = 0.125f; +constexpr float LIL_GURDY_LOUD_VOLUME = 0.8f; +constexpr int LIL_GURDY_DASH_SLOWING = 3; +constexpr float LIL_GURDY_SLOWING_FRAMES = 60; +constexpr float LIL_GURDY_DASH_PUSH = 3; +constexpr float LIL_GURDY_TOP_SPEED = 40; +constexpr float LIL_GURDY_DRAG_BASE = 0.8f; +constexpr float LIL_GURDY_DRAG_STEP = 0.02f; +constexpr float LIL_GURDY_DRAG_CAP = 0.98f; +constexpr float LIL_GURDY_BOUNCE_MIN = 0.0001f; +constexpr float LIL_GURDY_BOUNCE_KEPT = 0.95f; +constexpr float LIL_GURDY_BOUNCE_FRAMES = 100; +constexpr float LIL_GURDY_BOUNCE_BLEND_MIN = 0.2f; + +// Lil Gurdy's states: following and dashing. +enum LilGurdyState +{ + LIL_GURDY_FOLLOWING, + LIL_GURDY_DASHING +}; + +// Turns a dash toward the enemy best ahead of it, at the same speed. +static void lil_gurdy_aim(Entity_Familiar& gurdy, float speed) +{ + gurdy.velocity = vector_normalized(gurdy.velocity); + if (speed > 0 && !gurdy.HasEntityFlags(FLAG_CHARM)) + { + TargetSearch search = LIL_GURDY_SEARCH; + search.coneDirection = gurdy.velocity; + gurdy.PickEnemyTarget(search); + if (gurdy.target) gurdy.velocity = vector_normalized(vector_sub(gurdy.target->pos, gurdy.pos)); + } + gurdy.velocity = vector_scale(gurdy.velocity, speed); +} + +// Part of 0062ee30: resting Lil Gurdy charges while the player shoots and, let go, dashes the way it last faced, +// faster the longer it charged. It keeps near the player. +static void lil_gurdy_charge(Entity_Familiar& gurdy) +{ + Entity_Player& player = *gurdy.player; + gurdy.entityGridCollisionClass = GRIDCOLL_WALLS; + int direction = player.fireDirection; + if (vector_length(player.aimDirection) < LIL_GURDY_AIM_DEADZONE && !player.areOpposingShootDirectionsPressed) + direction = DIRECTION_NONE; + Vector aim = direction_unit(gurdy.lastDirection); + if (gurdy.TryAimAtMarkedTarget(aim, gurdy.lastDirection, nullptr) && gurdy.fireCooldown >= LIL_GURDY_CHARGE_CAP) + direction = DIRECTION_NONE; + + ANM2& look = gurdy.sprite; + bool isFiring = gurdy.CanPlayerFire(); + if (isFiring && direction != DIRECTION_NONE) + { + if (gurdy.fireCooldown == 0) look.Play("ChargeStart"); + gurdy.lastDirection = direction; + gurdy.fireCooldown++; + if (!look.IsPlaying()) look.Play("Charging"); + } + else if (isFiring && gurdy.fireCooldown < 1) + { + if (!look.IsPlaying()) look.Play("Idle"); + } + else if (isFiring) + { + gurdy.state = LIL_GURDY_DASHING; + gurdy.fireCooldown = std::min(gurdy.fireCooldown, LIL_GURDY_CHARGE_CAP); + gurdy.entityGridCollisionClass = GRIDCOLL_NOPITS; + float speed = (float)gurdy.fireCooldown / LIL_GURDY_CHARGE_CAP * LIL_GURDY_DASH_RANGE + LIL_GURDY_DASH_BASE; + gurdy.velocity = vector_add(gurdy.velocity, vector_scale(aim, speed)); + Vector inherited = vector_scale(player.velocity, LIL_GURDY_DASH_INHERIT * 2); + Vector along = vector_scale(aim, vector_dot(aim, inherited)); + if (vector_dot(aim, along) < 0) inherited = vector_sub(inherited, along); + gurdy.velocity = vector_add(gurdy.velocity, inherited); + look.Play("Dashing"); + } + if (gurdy.state != LIL_GURDY_FOLLOWING) return; + + gurdy.friction *= LIL_GURDY_DRAG; + if (vector_length_squared(vector_sub(gurdy.pos, player.pos)) <= LIL_GURDY_LEASH_SQUARED) return; + + Vector step = vector_scale(vector_sub(player.pos, gurdy.pos), LIL_GURDY_FOLLOW_PULL); + if (vector_length(step) > 1) step = vector_normalized(step); + if (gurdy.friction != 0) + gurdy.velocity = vector_add(gurdy.velocity, vector_scale(step, gurdy.speedMultiplier / gurdy.friction)); +} + +// Part of 0062ee30: dashing Lil Gurdy breaks what it slams into (harder the faster it goes) and bounces off walls +// toward an enemy with a thud. Its dash keeps up while charge is left, then drags it to a stop. +static float lil_gurdy_dash(Entity_Familiar& gurdy) +{ + if (gurdy.isCollidesWithGrid) + { + Room& room = *g_game->room; + Vector slam = gurdy.gridCollisionVelocity; + int index = room.GetGridIndex(vector_add(gurdy.pos, slam)); + if (index >= 0) + { + float damage = std::clamp(vector_length(slam) / LIL_GURDY_WALL_DAMAGE_STEP, 1.0f, LIL_GURDY_WALL_DAMAGE_CAP); + if (GridEntity* grid = room.GetGridEntity((uint32_t)index)) grid->Hurt((int)damage, EntityRef(gurdy.player)); + } + if (vector_length_squared(slam) > LIL_GURDY_HIT_RESET_SQUARED) gurdy.hitList.clear(); + lil_gurdy_aim(gurdy, vector_length(slam)); + float impact = -vector_dot(gurdy.velocity, gurdy.gridCollisionNormal); + if (impact > LIL_GURDY_LOUD_BUMP) familiar_sound_play(SOUND_DEATH_BURST_LARGE, {.volume = LIL_GURDY_LOUD_VOLUME}); + else if (impact > LIL_GURDY_SOFT_BUMP) + familiar_sound_play(SOUND_MEAT_JUMPS, + {.volume = std::clamp((impact - LIL_GURDY_SOFT_BUMP) * LIL_GURDY_BUMP_STEP, 0.0f, 1.0f) * HALF + HALF}); + } + + float speed = vector_length(gurdy.velocity); + if (gurdy.fireCooldown < 1) + gurdy.friction *= std::min(speed * LIL_GURDY_DRAG_STEP + LIL_GURDY_DRAG_BASE, LIL_GURDY_DRAG_CAP); + else + { + gurdy.fireCooldown -= LIL_GURDY_DASH_SLOWING; + if (speed > 0) + { + float push = std::clamp((float)gurdy.fireCooldown / LIL_GURDY_SLOWING_FRAMES, 0.0f, 1.0f) * (LIL_GURDY_DASH_PUSH / speed); + float kept = std::min(push + speed, LIL_GURDY_TOP_SPEED); + gurdy.velocity = vector_scale(gurdy.velocity, kept / speed); + speed = kept; + } + } + if (speed < 1) + { + gurdy.state = LIL_GURDY_FOLLOWING; + gurdy.fireCooldown = 0; + gurdy.sprite.Play("DashStop"); + } + return std::clamp(LIL_GURDY_SPLAT_STEP / speed, LIL_GURDY_SPLAT_FASTEST, LIL_GURDY_SPLAT_STEP); +} + +// 0062ee30 Lil Gurdy charges with the player's shots and dashes about the room, bouncing off walls and enemies, and +// leaving splats (now and then while it rests). +void Entity_Familiar::ai_lil_gurdy() +{ + float splatInterval = LIL_GURDY_IDLE_SPLAT_INTERVAL; + bool isSplatting = true; + if (state == LIL_GURDY_FOLLOWING) + { + lil_gurdy_charge(*this); + isSplatting = Random() % LIL_GURDY_IDLE_SPLAT_ODDS == 0; + } + else if (state == LIL_GURDY_DASHING) splatInterval = lil_gurdy_dash(*this); + else isSplatting = false; + + if (isSplatting && GetIntervalTicks(splatInterval, 0)) + { + Entity* splat = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, 0, pos, this); + float size = random_unit() * LIL_GURDY_SPLAT_RANGE + LIL_GURDY_SPLAT_MIN; + splat->sprite.scale = vector_make(size, size); + splat->Update(); + } + sprite.isFlipX = velocity.x < 0; +} + +// Part of 006261f0: Lil Gurdy hitting an enemy bounces off it like a ball, the enemy taking its share of the push by +// weight (a glancing hit turning it more), keeping its speed while it still charges, and heads for the next enemy. +void lil_gurdy_bounce(Entity_Familiar& gurdy, Entity& enemy) +{ + gurdy.hitList.clear(); + hit_list_insert(gurdy.hitList, enemy); + Vector apart = vector_sub(enemy.pos, gurdy.pos); + float distance = vector_length(apart); + if (distance <= LIL_GURDY_BOUNCE_MIN) return; + + Vector closing = vector_sub(gurdy.velocity, enemy.velocity); + float closingSpeed = vector_length(closing); + if (closingSpeed > (gurdy.size + enemy.size) * HALF && vector_dot(apart, closing) < 0) + { + float turn = vector_dot(vector_normalized(closing), vector_normalized(apart)); + apart = vector_add(apart, vector_scale(apart, turn + turn)); + distance = vector_length(apart); + } + Vector impulse = vector_scale(apart, closingSpeed / distance); + float share = gurdy.mass / (enemy.mass + gurdy.mass); + Vector kept = vector_sub(gurdy.velocity, vector_scale(impulse, 1 - share)); + if (gurdy.fireCooldown > 0 && !vector_is_zero(kept)) + { + Vector held = vector_resized(kept, vector_length(gurdy.velocity) * LIL_GURDY_BOUNCE_KEPT); + float blend = std::clamp((float)gurdy.fireCooldown / LIL_GURDY_BOUNCE_FRAMES, LIL_GURDY_BOUNCE_BLEND_MIN, 1.0f); + kept = vector_add(kept, vector_scale(vector_sub(held, kept), blend)); + } + gurdy.velocity = kept; + enemy.AddVelocity(vector_scale(impulse, share), true); + if (!vector_is_zero(gurdy.velocity) && !gurdy.HasEntityFlags(FLAG_CHARM)) lil_gurdy_aim(gurdy, vector_length(gurdy.velocity)); +} + +// Robo-Baby 2.0: how it steers with the player's shooting input (its grip, brake and drag), how it keeps inside the +// room, how often it looks for a target (less often in versus), how far, how close a target must be lined up, the grid +// path threshold its laser's line ignores, and how long its head faces the shot. +constexpr float ROBO_2_STEER = 1.25f; +constexpr float ROBO_2_GRIP = 0.79999995f; +constexpr float ROBO_2_BRAKE = -0.2f; +constexpr float ROBO_2_ACCEL_BASE = 3; +constexpr float ROBO_2_ACCEL_SCALE = 0.425f; +constexpr float ROBO_2_DRAG = 0.775f; +constexpr float ROBO_2_WALL_PUSH_MAX = 10; +constexpr int ROBO_2_FIRE_INTERVAL = 10; +constexpr int ROBO_2_VERSUS_FIRE_INTERVAL = 60; +constexpr float ROBO_2_RANGE = 280; +constexpr float ROBO_2_LINE_UP = 10; +constexpr int ROBO_2_LINE_THRESHOLD = 950; +constexpr int ROBO_2_SHOT_FRAMES = 13; +constexpr int ROBO_2_SHOOT_ANIM_FRAMES = 20; + +// The nearest enemy Robo-Baby 2.0 lines up with on either axis and can see, or none. +static Entity* robo_baby_2_target(Entity_Familiar& robo) +{ + Entity* best = nullptr; + float bestDistance = ROBO_2_RANGE; + for (Entity* enemy : g_game->room->entityList.updateEL) + { + bool isFoe = (familiar_versus() && enemy->type == ENTITY_PLAYER) || Entity::is_enemy_type(enemy->type); + bool isTargetable = !enemy->HasEntityFlags(FLAG_NO_TARGET) || enemy->type == ENTITY_BLOOD_PUPPY || + enemy->type == ENTITY_DARK_ESAU; + if (!isFoe || enemy->entityCollisionClass <= ENTCOLL_PLAYERONLY || enemy->isInvincible || enemy->isDead || + !isTargetable || enemy->IsDescendantOf(robo.spawnerEntity) || enemy->HasEntityFlags(FLAG_FRIENDLY | FLAG_NO_TARGET)) + continue; + + Vector toward = vector_sub(enemy->pos, robo.pos); + if (std::min(std::fabs(toward.x), std::fabs(toward.y)) >= enemy->size + ROBO_2_LINE_UP) continue; + + Vector edge = vector_sub(enemy->pos, vector_resized(toward, enemy->size)); + float distance = vector_distance(edge, robo.pos); + if (distance >= bestDistance || !room_check_line(robo.pos, edge, LINE_MODE_PROJECTILE, ROBO_2_LINE_THRESHOLD)) + continue; + + bestDistance = distance; + best = enemy; + } + return best; +} + +// 006196e0 (FamiliarAI::variant_53) Robo-Baby 2.0 drives about with the player's shooting input, kept inside the +// room, and fires its laser at an enemy lined up with it every few frames. +void robo_baby_2_update(Entity_Familiar& robo) +{ + Entity_Player& player = *robo.player; + Vector input{}; + if (player.isControlsEnabled && player.controlsCooldown < 1) + { + input = player.GetShootingJoystick(); + if (vector_length(input) > 1) input = vector_normalized(input); + } + Vector push = vector_scale(input, ROBO_2_STEER); + if (vector_is_zero(push)) robo.moveDirection = DIRECTION_DOWN; + else if (std::fabs(push.x) <= std::fabs(push.y)) robo.moveDirection = push.y > 0 ? DIRECTION_DOWN : DIRECTION_UP; + else robo.moveDirection = push.x > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT; + + Vector& velocity = robo.velocity; + if (!vector_is_zero(push)) + { + Vector along = vector_scale(push, vector_dot(push, velocity)); + velocity = vector_add(vector_scale(vector_sub(velocity, along), ROBO_2_GRIP), along); + } + float accel = (std::max(vector_dot(push, velocity) * ROBO_2_BRAKE, 0.0f) + ROBO_2_ACCEL_BASE) * ROBO_2_ACCEL_SCALE; + velocity = vector_scale(vector_add(velocity, vector_scale(push, accel)), ROBO_2_DRAG); + + Vector inside = vector_sub(g_game->room->GetClampedPositionImpl(robo.pos, 0, 0, 0, 0), robo.pos); + if (!vector_is_zero(inside)) + { + Vector back = vector_normalized(inside); + float strength = std::clamp(-vector_dot(back, velocity), 1.0f, ROBO_2_WALL_PUSH_MAX); + velocity = vector_add(velocity, vector_scale(back, strength * robo.speedMultiplier)); + } + + int interval = familiar_lullaby_delay(robo, familiar_versus() ? ROBO_2_VERSUS_FIRE_INTERVAL : ROBO_2_FIRE_INTERVAL); + bool isFrame = !robo.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && !g_game->IsPaused() && g_game->frameCount % interval == 0; + if (Entity* target = isFrame ? robo_baby_2_target(robo) : nullptr) + { + Vector toward = vector_sub(target->pos, robo.pos); + if (std::fabs(toward.x) <= std::fabs(toward.y)) robo.shootDirection = toward.y > 0 ? DIRECTION_DOWN : DIRECTION_UP; + else robo.shootDirection = toward.x <= 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + robo.headFrameDelay = ROBO_2_SHOT_FRAMES; + robo.fire_robo_baby_laser(direction_unit(robo.shootDirection)); + } + if (robo.headFrameDelay <= 0) return robo.PlayFloatAnim(robo.moveDirection); + + if (robo.headFrameDelay > ROBO_2_SHOOT_ANIM_FRAMES) robo.PlayShootAnim(robo.shootDirection); + else robo.PlayFloatAnim(robo.shootDirection); + robo.headFrameDelay--; +} + +// Sworn Protector: how far around it shots turn away, the push they turn toward, how near it reflects them and how +// near it stops them outright. +constexpr float SWORN_REACH = 30; +constexpr float SWORN_PUSH = 15; +constexpr float SWORN_TURN_MAX = 0.99f; +constexpr float SWORN_REFLECT_SQUARED = 400; +constexpr float SWORN_STOP_SQUARED = 64; + +// Part of 0061da10: Sworn Protector circles the player turning away the shots coming nearer to it than to the player +// (the more head-on, the harder), reflecting them close by and stopping them closer still. +void sworn_protector_update(Entity_Familiar& protector) +{ + Entity_Player& player = *protector.player; + uint32_t partitions = familiar_versus() ? QUERY_PROJECTILES | QUERY_TEARS : QUERY_PROJECTILES; + for (Entity* shot : entity_query_radius(protector.pos, SWORN_REACH, partitions)) + { + if (shot->HasEntityFlags(FLAG_FRIENDLY) || shot->IsDescendantOf(protector.spawnerEntity)) continue; + + Vector toward = vector_sub(protector.pos, shot->pos); + float nearSquared = vector_length_squared(toward); + if (vector_length_squared(vector_sub(shot->pos, player.pos)) <= nearSquared) continue; + + float headOn = vector_dot(vector_normalized(shot->velocity), vector_normalized(toward)); + float kept = std::min((float)std::acos((double)headOn) / PI_F, SWORN_TURN_MAX); + Vector push = vector_scale(vector_normalized(toward), SWORN_PUSH); + auto turned = [&] { return vector_add(vector_scale(shot->velocity, kept), vector_scale(push, 1 - kept)); }; + shot->velocity = turned(); + if (nearSquared < SWORN_REFLECT_SQUARED && shot->IsProjectile()) static_cast(shot)->Reflect(turned()); + else if (nearSquared < SWORN_REFLECT_SQUARED && shot->IsTear()) static_cast(shot)->Deflect(&protector, turned()); + if (nearSquared < SWORN_STOP_SQUARED) shot->isDead = true; + } + protector.velocity = vector_sub(protector.GetOrbitPosition(player.pos), protector.pos); +} diff --git a/src/familiar_ai.cpp b/src/familiar_ai.cpp index be1e135..c8e4da0 100644 --- a/src/familiar_ai.cpp +++ b/src/familiar_ai.cpp @@ -43,6 +43,22 @@ constexpr int SOUND_BIG_CHUBBY_CHARGE = 835; constexpr int SOUND_LITTLE_CHUBBY_CHARGE = 849; constexpr int CHARGE_SOUND_DELAY = 450; +// Lil Portal: how many coins of pickups fill it (a hundred a floor, capped), its four looks by fill (its idle reads the +// fill by twice the floor), the damage each level adds, the pickups it swallows, the special rooms it never opens in, +// and the portal it opens to its own room in a cleared room once full. +constexpr int LIL_PORTAL_FULL_STEP = 100; +constexpr int LIL_PORTAL_IDLE_STEP = 200; +constexpr int LIL_PORTAL_FULL_CAP = 1200; +constexpr int LIL_PORTAL_LEVEL_MAX = 3; +constexpr std::string_view LIL_PORTAL_CHARGE_ANIMS[] = {"Charge0", "Charge1", "Charge2", "Charge3"}; +constexpr std::string_view LIL_PORTAL_IDLE_ANIMS[] = {"Idle0", "Idle1", "Idle2", "Idle3"}; +constexpr float LIL_PORTAL_LEVEL_DAMAGE = 2; +constexpr int LIL_PORTAL_EATEN_PICKUPS[] = {10, 20, 90, 40, 30, 70, 300, 350, 69, 41, 42}; +constexpr int LIL_PORTAL_CLOSED_ROOMS[] = {-20, -18, -13, -4, -6, -19}; +constexpr float LIL_PORTAL_OPEN_SPEED_SQUARED = 400; +constexpr uint32_t ROOM_DESCRIPTOR_FLAG_PORTAL_LINKED = 1 << 17; +constexpr int LIL_PORTAL_TELEPORT_SUBTYPE = 980; + // The blue flies' chase: how far they look (further for Wrath locusts once the room settles), how they home in. constexpr float BLUE_FLY_RANGE = 200; constexpr float LOCUST_RANGE = 400; @@ -368,16 +384,74 @@ Entity* Entity_Player::AddBlueFlies(int amount, Vector spawnPos, Entity* chased) return fly; } +// How full Lil Portal is, by a step of coins per level, at most its top level. +static int lil_portal_level(Entity_Familiar& portal, int step) +{ + return std::clamp(portal.coins / (std::min(step, LIL_PORTAL_FULL_CAP) >> 2), 0, LIL_PORTAL_LEVEL_MAX); +} + +// Part of 006174c0: dashing Lil Portal shows its fill, hits harder the fuller it is and swallows the free pickups it +// passes over. +static void lil_portal_swallow(Entity_Familiar& portal) +{ + int level = lil_portal_level(portal, ((int)g_game->stage + 1) * LIL_PORTAL_FULL_STEP); + portal.sprite.Play(LIL_PORTAL_CHARGE_ANIMS[level]); + portal.SetCollisionDamage((float)level * LIL_PORTAL_LEVEL_DAMAGE + LIL_PORTAL_LEVEL_DAMAGE); + for (Entity* pickup : entity_query_radius(portal.pos, portal.size, QUERY_PICKUPS)) + if (pickup->type == ENTITY_PICKUP && familiar_listed(LIL_PORTAL_EATEN_PICKUPS, pickup->variant) && + static_cast(pickup)->price == 0) + Entity::ForceCollide(&portal, pickup, true); +} + +// Part of 006174c0: following Lil Portal shows its fill. Full and still in a cleared room outside the special rooms, it +// opens a portal to its own room once a floor, emptying itself. A spot it was sent to sets it dashing. +static void lil_portal_follow(Entity_Familiar& portal, Vector& aim, int& direction) +{ + Game& game = *g_game; + int full = std::min(((int)game.stage + 1) * LIL_PORTAL_FULL_STEP, LIL_PORTAL_FULL_CAP); + bool isRoomClear = game.room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; + if (!isRoomClear || game.isLilPortalOpened || portal.coins < full || + vector_length_squared(portal.velocity) >= LIL_PORTAL_OPEN_SPEED_SQUARED) + { + const AnimationState& shown = portal.sprite.animState; + if (!shown.animData || shown.animData->isLooping || !shown.isPlaying) + portal.sprite.Play(LIL_PORTAL_IDLE_ANIMS[lil_portal_level(portal, (int)game.stage * LIL_PORTAL_IDLE_STEP)]); + } + else if (!familiar_listed(LIL_PORTAL_CLOSED_ROOMS, game.currentRoomIdx)) + { + portal.sprite.Play("Spawn"); + if (portal.sprite.IsEventTriggered("Shoot")) + { + Vector spot = room_free_pickup_position_find({.position = portal.pos, .isAvoidDoors = true}); + portal.coins = 0; + familiar_sound_play(SOUND_THUMBSUP); + game.GetRoomByIdx(ROOM_LIL_PORTAL_IDX)->flags |= ROOM_DESCRIPTOR_FLAG_PORTAL_LINKED; + uint32_t seed = portal.player->GetCollectibleRNG(COLLECTIBLE_LIL_PORTAL).Next(); + g_game->Spawn({.position = spot, + .subType = LIL_PORTAL_TELEPORT_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_PORTAL_TELEPORT, + .seed = seed}); + portal.subtype = 1; + game.isLilPortalOpened = true; + } + } + if (portal.fireCooldown < 1 && !vector_is_zero(portal.targetPosition)) + { + aim = portal.targetPosition; + direction = DIRECTION_LEFT; + } +} + // A charger dashing: its look, and how it stops on a wall or out of the room, breaking what it hits (part of 006174c0). void Entity_Familiar::charger_dash() { - if (variant == LIL_PORTAL) - return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (this charger's dash)"); if (variant == JAW_BONE) return jaw_bone_dash(*this); bool isShowingDash = variant == LITTLE_CHUBBY || variant == BIG_CHUBBY || (variant == KNIFE_FULL && fireCooldown == -1); - if (std::fabs(velocity.y) < std::fabs(velocity.x)) + if (variant == LIL_PORTAL) lil_portal_swallow(*this); + else if (std::fabs(velocity.y) < std::fabs(velocity.x)) { if (isShowingDash) sprite.Play("FloatShootSide"); sprite.isFlipX = velocity.x < 0; @@ -418,8 +492,8 @@ void Entity_Familiar::charger_start(const Vector& aimDirection, int direction) } // 006174c0 The chargers (Little Chubby, Bob's Brain and their kin): follow, and dash the way the player shoots once -// recharged, Bob's Brain only while no other brain is out. A spent one (subtype set) hides and comes back after a -// while. Tainted Lilith's Incubus and the special chargers stop the game. +// recharged, Bob's Brain only while no other brain is out, Lil Portal only toward a spot it was sent to. A spent one +// (subtype set) hides and comes back after a while. Tainted Lilith's Incubus stops the game. void Entity_Familiar::ai_charger() { if (IsLilithBirthrightIncubus()) return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (Incubus)"); @@ -457,9 +531,9 @@ void Entity_Familiar::ai_charger() if (fireCooldown < 0) return charger_dash(); FollowParent(); - if (variant == LIL_PORTAL) return reconstruction_missing("Entity_Familiar::ai_charger 006174c0 (this charger)"); bool isKnifePiece = variant == KNIFE_PIECE_1 || variant == KNIFE_PIECE_2; - if (variant == JAW_BONE) jaw_bone_follow(*this); + if (variant == LIL_PORTAL) lil_portal_follow(*this, aim, direction); + else if (variant == JAW_BONE) jaw_bone_follow(*this); else if (isKnifePiece || variant == KNIFE_FULL) knife_follow(*this); else if (!sprite.IsPlaying("Float")) sprite.Play("Float"); if (fireCooldown > 0) fireCooldown--; @@ -475,6 +549,11 @@ void Entity_Familiar::ai_charger() isFree = false; break; } + if (variant == LIL_PORTAL) + { + isFree = !vector_is_zero(targetPosition) && fireCooldown < 1; + if (isFree) targetPosition = {}; + } if (fireCooldown < 1 && isFree) charger_start(aim, direction); } entityCollisionClass = variant == JAW_BONE ? ENTCOLL_ALL : ENTCOLL_NONE; diff --git a/src/familiar_body.cpp b/src/familiar_body.cpp index 329b284..580e7ff 100644 --- a/src/familiar_body.cpp +++ b/src/familiar_body.cpp @@ -1,5 +1,6 @@ #include "entity_effect.h" #include "entity_familiar.h" +#include "entity_npc.h" #include "entity_player.h" #include "game.h" #include "log.h" @@ -207,6 +208,102 @@ void detached_head_update(Entity_Familiar& head) player.tearsOffset = vector_sub(head.pos, player.pos); } +// Decap Attack's head: its fall (its height and fall speed kept in its target position) and its landing, its pull +// back to the player growing over fifteen frames, its red flash and blood trail, its splats, and how near the player +// takes it back (nearer while it still rests). +constexpr float DECAP_GRAVITY = 1.2f; +constexpr float DECAP_DRAG = 0.85f; +constexpr int DECAP_FLASH_INTERVAL = 4; +constexpr int DECAP_FLASH_FRAMES = 3; +constexpr ColorMod DECAP_FLASH = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {1, 0, 0}}; +constexpr LerpRange DECAP_PULL = {.inMin = 0, .inMax = 15, .outMin = 1, .outMax = 16}; +constexpr float DECAP_TRAIL_INTERVAL = 2; +constexpr float DECAP_TRAIL_SPEED = 0.5f; +constexpr float DECAP_TRAIL_LIFT = -8; +constexpr float DECAP_TRAIL_DEPTH = -5; +constexpr float DECAP_SPLAT_SPEED_SQUARED = 3; +constexpr int DECAP_SPLAT_INTERVAL = 3; +constexpr float DECAP_SPLAT_SIZE = 0.5f; +constexpr float DECAP_CATCH_SQUARED = 400; +constexpr float DECAP_RETURN_CATCH_SQUARED = 1600; +constexpr int DECAP_BLOOD_SUBTYPE = 2; + +// Part of 0061da10: Decap Attack's head pulls back to its player once called, flashing and trailing blood. +static void decap_head_return(Entity_Familiar& head) +{ + if (head.state == 1) head.hitList.clear(); + head.ClearEntityFlags(FLAG_THROWN); + if (head.state % DECAP_FLASH_INTERVAL == 0) head.SetColor(DECAP_FLASH, DECAP_FLASH_FRAMES, 255, true, true); + head.entityGridCollisionClass = GRIDCOLL_NONE; + float pull = lerp_range((float)head.state++, DECAP_PULL); + head.AddVelocity(vector_resized(vector_sub(head.player->pos, head.pos), pull), false); + if (!head.GetIntervalTicks(DECAP_TRAIL_INTERVAL, 0)) return; + + uint32_t seed = Random(); + Entity* trail = g_game->Spawn({.position = head.pos, + .velocity = vector_scale(head.velocity, DECAP_TRAIL_SPEED), + .spawner = &head, + .type = ENTITY_EFFECT, + .variant = EFFECT_HAEMO_TRAIL, + .seed = seed}); + trail->posOffset = vector_add(head.posOffset, vector_make(0, DECAP_TRAIL_LIFT)); + trail->renderDepthOffset = DECAP_TRAIL_DEPTH; + trail->Update(); +} + +// Part of 0061da10: a thrown Decap Attack head falls under gravity and lands with a thud (a bone's for the +// Forgotten) and a splash of blood. +static void decap_head_fall(Entity_Familiar& head) +{ + Vector& fall = head.targetPosition; + fall.x += head.speedMultiplier * fall.y; + fall.y += head.speedMultiplier * DECAP_GRAVITY; + head.entityGridCollisionClass = fall.y < 0 ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; + if (fall.x <= 0) return; + + fall = {}; + head.ClearEntityFlags(FLAG_THROWN); + int playerType = head.player->playerType; + if (playerType == PLAYER_THEFORGOTTEN || playerType == PLAYER_THEFORGOTTEN_B) + { + familiar_sound_play(SOUND_BONE_BOUNCE); + familiar_sound_play(SOUND_BONE_DROP); + return; + } + familiar_sound_play(SOUND_MEAT_JUMPS); + g_game->Spawn({.position = head.pos, .subType = DECAP_BLOOD_SUBTYPE, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}) + ->Update(); +} + +// Part of 0061da10: Decap Attack's thrown head falls and rests, splatting as it slides, the player's tears leaving +// from it. Called back it flies home, and the player catches it once near. +void decap_head_update(Entity_Familiar& head) +{ + Entity_Player& player = *head.player; + bool isFalling = head.targetPosition.x < 0 || head.targetPosition.y < 0; + if (head.state > 0) decap_head_return(head); + if (head.state > 0 || !isFalling) head.friction *= DECAP_DRAG; + else decap_head_fall(head); + + if (vector_length_squared(head.velocity) > DECAP_SPLAT_SPEED_SQUARED && head.IsFrame(DECAP_SPLAT_INTERVAL, 0)) + { + Entity* splat = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, 0, head.pos, &head); + splat->sprite.scale = vector_make(DECAP_SPLAT_SIZE, DECAP_SPLAT_SIZE); + splat->Update(); + } + head.posOffset.y = head.targetPosition.x; + player.tearsOffset = vector_sub(head.pos, player.pos); + if (head.HasEntityFlags(FLAG_THROWN)) return; + + float reach = head.state > 0 ? DECAP_RETURN_CATCH_SQUARED : DECAP_CATCH_SQUARED; + if (vector_length_squared(vector_sub(player.pos, head.pos)) > reach) return; + + player.AnimateCollectible(COLLECTIBLE_DECAP_ATTACK, "HideItem", "PlayerPickupSparkle"); + familiar_sound_play(SOUND_SCAMPER); + player.temporaryEffects.RemoveCollectibleEffect(COLLECTIBLE_DECAP_ATTACK, -1); + head.Remove(); +} + // Part of 00624e10: the detached head draws its player's glow, back and head at its own spot in the player's colour // (Decap Attack's a little lower), Scissors' even while the player is hidden. Guillotine's draws only while shown. void detached_head_render(Entity_Familiar& head, const Vector& offset) diff --git a/src/familiar_bums.cpp b/src/familiar_bums.cpp index f715fa2..839fa2e 100644 --- a/src/familiar_bums.cpp +++ b/src/familiar_bums.cpp @@ -321,3 +321,166 @@ void Entity_Familiar::ai_pickup_sack() else if (variant == DARK_BUM || (isSuper && hearts > DARK_BUM_HEARTS)) dark_bum_pay(*this, drops); else if (variant == KEY_BUM || isSuper) key_bum_pay(*this, drops); } + +// Bumbo: the coins each size needs (its sounds as it grows), its last size's walk (how near counts as reached, its +// path speed, its bombs and their odds), its damage, and the drops it gives near the player. +constexpr int BUMBO_SIZE_COINS[] = {6, 12, 24}; +constexpr int SOUND_BUMBO_SIZES[] = {843, 844, 845}; +constexpr float BUMBO_DROP_REACH_SQUARED = 6400; +constexpr TargetSearch BUMBO_SEARCH = {.range = 300, .frameInterval = 13}; +constexpr float BUMBO_PICKUP_REACH_SQUARED = 16; +constexpr float BUMBO_ENEMY_REACH_SQUARED = 400; +constexpr float BUMBO_PLAYER_REACH_SQUARED = 6400; +constexpr float BUMBO_PATH_SPEED = 0.75f; +constexpr int BUMBO_BOMB_INTERVAL = 60; +constexpr uint32_t BUMBO_BOMB_MASK = 3; +constexpr float BUMBO_BOMB_RANGE_SQUARED = 2500; +constexpr float BUMBO_BOMB_SPEED = 5; +constexpr float BUMBO_WALK_DRAG = 0.85f; +constexpr float BUMBO_WALK_SPEED = 2; +constexpr float BUMBO_LAST_DAMAGE = 2.5f; +constexpr float BUMBO_SHOT_DRAG = 0.2f; + +// Part of 0062f7f0: grown Bumbo walks the room, paths after a coin or an enemy (else back to the player) and lobs a +// bomb now and then at an enemy close by. +static void bumbo_walk(Entity_Familiar& bumbo, bool isDropping) +{ + if (!bumbo.target) bumbo.PickEnemyTarget(BUMBO_SEARCH); + Entity* target = bumbo.target.get(); + Vector goal = target ? target->pos : bumbo.player->pos; + float reach = !target ? BUMBO_PLAYER_REACH_SQUARED : target->type == ENTITY_PICKUP ? BUMBO_PICKUP_REACH_SQUARED : BUMBO_ENEMY_REACH_SQUARED; + Vector toward = vector_sub(goal, bumbo.pos); + float distance = vector_length_squared(toward); + if (distance > reach) bumbo.pathfinder.FindGridPath(goal, BUMBO_PATH_SPEED, 0, DIRECT_PATH_FAR); + if (target && bumbo.IsFrame(BUMBO_BOMB_INTERVAL, (int)bumbo.index) && (Random() & BUMBO_BOMB_MASK) == 0 && + distance < BUMBO_BOMB_RANGE_SQUARED) + { + uint32_t seed = Random(); + g_game->Spawn({.position = bumbo.pos, .velocity = vector_resized(toward, BUMBO_BOMB_SPEED), .spawner = &bumbo, + .type = ENTITY_BOMB, .seed = seed}); + } + bumbo.friction *= BUMBO_WALK_DRAG; + if (isDropping) return; + + if (vector_length(bumbo.velocity) < BUMBO_WALK_SPEED) return bumbo.sprite.Play("Level4Idle"); + bumbo.sprite.Play("Level4Walking"); + bumbo.sprite.isFlipX = bumbo.velocity.x < 0; +} + +// Part of 0062f7f0: Bumbo grows a size at 6, 12 and 24 coins. Grown, it walks out on its own and hits harder. +static void bumbo_grow(Entity_Familiar& bumbo) +{ + int size = (int)(std::ranges::upper_bound(BUMBO_SIZE_COINS, bumbo.coins) - std::begin(BUMBO_SIZE_COINS)); + if (size == 0) return; + if (size == BUMBO_LAST_SIZE) + { + if (bumbo.state == BUMBO_LAST_SIZE - 1) + { + bumbo.pos = room_free_pickup_position_find({.position = bumbo.pos}); + bumbo.entityGridCollisionClass = GRIDCOLL_GROUND; + bumbo.entityCollisionClass = ENTCOLL_ALL; + familiar_sound_play(SOUND_BUMBO_SIZES[size - 1]); + } + bumbo.collisionDamage = BUMBO_LAST_DAMAGE; + } + else if (bumbo.state == size - 1) familiar_sound_play(SOUND_BUMBO_SIZES[size - 1]); + bumbo.state = size; +} + +// Part of 0062f7f0: Bumbo's look by size while it is not dropping a pickup. +static void bumbo_animate(Entity_Familiar& bumbo) +{ + ANM2& look = bumbo.sprite; + bool isStill = vector_length_squared(bumbo.velocity) <= 1; + if (bumbo.state == 0 && !look.IsPlaying()) look.Play("Level1Float"); + else if (bumbo.state == 1) look.Play(isStill ? "Level2Idle" : "Level2Walking"); + else if (bumbo.state == 2 && (!look.IsPlaying() || look.animState.animData->isLooping)) + look.Play(isStill ? "Level3Idle" : "Level3Walking"); +} + +// 0062f7f0 (FamiliarAI::bumbo) Bumbo follows in the bums' line picking up coins, grows with them (shooting at its +// third size, walking out on its own at its fourth) and drops pickups near the player at its second and fourth. +void bumbo_update(Entity_Familiar& bumbo) +{ + bool isDropping = vector_length_squared(vector_sub(bumbo.player->pos, bumbo.pos)) < BUMBO_DROP_REACH_SQUARED && + bumbo.counter > 0 && (bumbo.state == 1 || bumbo.state == BUMBO_LAST_SIZE); + if (bumbo.state == BUMBO_LAST_SIZE) bumbo_walk(bumbo, isDropping); + bumbo_grow(bumbo); + + bool isCollected = false; + if (!bumbo.target || bumbo.target->isDead || bumbo.target->type != ENTITY_PICKUP) + { + if (bumbo.state != BUMBO_LAST_SIZE) + { + Vector lead = bumbo.player->pos; + float leadReach = BUM_PLAYER_REACH; + for (Entity_Familiar* other : familiar_query(-1)) + { + if (other == &bumbo) break; + if (!familiar_listed(LINED_BUM_VARIANTS, other->variant)) continue; + + lead = other->pos; + leadReach = BUM_LINE_REACH; + } + Vector toLead = vector_sub(lead, bumbo.pos); + float leadDistance = vector_length(toLead); + if (leadDistance > leadReach) bumbo.velocity = vector_add(bumbo.velocity, vector_scale(toLead, BUM_FOLLOW_PULL / leadDistance)); + if (bumbo.state == 2) + { + bumbo.Shoot(); + if (bumbo.headFrameDelay > 0) bumbo.friction *= BUMBO_SHOT_DRAG; + } + } + } + else + { + Vector toward = vector_sub(bumbo.target->pos, bumbo.pos); + if (vector_length_squared(toward) >= BUM_TOUCH_DISTANCE_SQUARED) + { + if (bumbo.state != BUMBO_LAST_SIZE) + bumbo.velocity = vector_add(bumbo.velocity, vector_scale(vector_normalized(toward), BUM_CHASE_PULL)); + } + else + { + bumbo.collide_with_entity(bumbo.target.get()); + if (bumbo.target && bumbo.target->isDead) + { + isCollected = true; + bumbo.target = nullptr; + } + } + } + + ANM2& look = bumbo.sprite; + if (isDropping && (!look.IsPlaying() || look.animState.animData->isLooping)) + { + if (bumbo.state == 1) look.Play("Level2Spawn", PLAY_FORCED); + else if (bumbo.state == BUMBO_LAST_SIZE) look.Play("Level4Spawn", PLAY_FORCED); + } + if (look.IsEventTriggered("Spawn")) + { + g_game->Spawn({.position = bumbo.pos, .spawner = &bumbo, .type = ENTITY_PICKUP, .seed = bumbo.dropRNG.Next()}); + bumbo.counter--; + } + if (!isDropping) bumbo_animate(bumbo); + if (bumbo.state != BUMBO_LAST_SIZE) + { + if (bumbo.state != 2 || bumbo.headFrameDelay < 1) bumbo.sprite.isFlipX = bumbo.velocity.x < 0; + bumbo.friction *= BUM_FRICTION; + } + if ((!isCollected && !bumbo.IsFrame(BUM_SEARCH_INTERVAL, 0)) || bumbo.target) return; + + float best = BUM_SEARCH_DISTANCE_SQUARED; + for (Entity* entity : entity_query_radius(bumbo.pos, BUM_SEARCH_RADIUS, QUERY_PICKUPS)) + { + auto* coin = entity->type == ENTITY_PICKUP ? static_cast(entity) : nullptr; + if (!coin || coin->variant != PICKUP_COIN || coin->isDead || coin->price != 0) continue; + + float distance = vector_length_squared(vector_sub(coin->pos, bumbo.pos)); + if (distance >= best) continue; + if (bumbo.entityGridCollisionClass == GRIDCOLL_GROUND && !bumbo.pathfinder.HasPathToPos(coin->pos, false)) continue; + + bumbo.target = coin; + best = distance; + } +} diff --git a/src/familiar_clot.cpp b/src/familiar_clot.cpp new file mode 100644 index 0000000..057d8cd --- /dev/null +++ b/src/familiar_clot.cpp @@ -0,0 +1,495 @@ +#include "entity_familiar.h" +#include "active_items.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_list.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "kage_graphics.h" +#include "menu_manager.h" +#include "npc_ai.h" +#include "room_grid.h" +#include "seeds.h" +#include +#include +#include + +// A clot's look by subtype (red, soul, black, eternal, gold, bone, rotten, then Lil Clot's): the health its slow +// bleed stops at, its sheet's crop, its splat colour and the colour of the trail it leaves when launched. +struct ClotLook +{ + float healthFloor = 0; + float cropX = 0; + float cropY = 0; + ColorMod splat = COLOR_DEFAULT; + ColorMod trail = COLOR_DEFAULT; +}; + +constexpr ColorMod clot_colorized(float red, float green, float blue, float alpha) +{ + return {{1, 1, 1, 1}, {red, green, blue, alpha}, {0, 0, 0}}; +} + +constexpr ColorMod clot_tinted(float red, float green, float blue) +{ + return {{red, green, blue, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +} + +// The clot table at 00c34238. +constexpr std::array CLOT_LOOKS = {{ + {1, 0, 0, COLOR_DEFAULT, clot_tinted(0.85f, 0, 0)}, + {5, 0, 48, clot_colorized(0.3f, 1.5f, 1.75f, 1), clot_tinted(0.3f, 0.8f, 1)}, + {5, 0, 96, clot_colorized(0.8f, 0.8f, 0.8f, 1), clot_tinted(0.1f, 0.1f, 0.1f)}, + {5, 0, 192, clot_colorized(4, 4, 4, 1), clot_tinted(1, 1, 1)}, + {5, 0, 240, clot_colorized(5, 3.8f, 0.6f, 1), clot_tinted(1, 0.8f, 0)}, + {5, 0, 144, clot_colorized(0, 0, 0, 0), clot_tinted(1, 1, 1)}, + {1, 0, 288, clot_colorized(0.9f, 0.3f, 0.2f, 1), clot_tinted(0.85f, 0.3f, 0.2f)}, + {3, 0, 0, clot_colorized(0, 0, 0, 0), clot_tinted(0.85f, 0, 0)}, +}}; + +// The clot's states: walking, landing, launched, back from a launch while Sumptorium's effect lasts, and the state a +// launched clot reaching the player jumps to. +constexpr int CLOT_WALKING = 0; +constexpr int CLOT_LANDING = 1; +constexpr int CLOT_LAUNCHED = 2; +constexpr int CLOT_RETURNED = -1000; +constexpr int CLOT_ARRIVED = 89; +constexpr int CLOT_ARRIVED_LIMIT = 92; + +// Walking: how its speed follows the player's, the grip it turns with and its drag, its crawlspace fall, the sheet's +// head columns and the shooting head's row, its walk's pace, and how hard it keeps off the player and other clots. +constexpr float CLOT_SPEED_SCALE = 0.25f; +constexpr float CLOT_SPEED_BASE = 0.75f; +constexpr float CLOT_TURN_GRIP = 0.8f; +constexpr float CLOT_BRAKE = -0.2f; +constexpr float CLOT_ACCEL_BASE = 3; +constexpr float CLOT_ACCEL_SCALE = 0.4f; +constexpr float CLOT_DRAG = 0.775f; +constexpr float CLOT_FALL = 0.225f; +constexpr float CLOT_HEAD_COLUMN = 24; +constexpr float CLOT_HEAD_COLUMNS = 72; +constexpr float CLOT_HEAD_SHOOT_ROW = 24; +constexpr int CLOT_HEAD_SHOOT_FRAMES = 8; +constexpr float CLOT_WALK_FULL_SPEED = 2.3f; +constexpr float CLOT_WALK_SPEED_SPAN = 1.3f; +constexpr float CLOT_RUN_SPEED = 6; +constexpr float CLOT_RUN_STEP = 0.25f; +constexpr float CLOT_SPACING_RADIUS = 8; +constexpr float CLOT_SPACING_PUSH = 2; + +// Its slow bleed toward its floor, its size and paleness by health (Lil Clot's by its own 3 health). +constexpr int CLOT_BLEED_INTERVAL = 15; +constexpr float CLOT_BLEED = 0.2f; +constexpr float CLOT_SIZE_BASE = 0.6f; +constexpr float CLOT_SIZE_RANGE = 0.5f; +constexpr float LIL_CLOT_SIZE_RANGE = 0.39999998f; +constexpr float CLOT_PALE = 0.6f; +constexpr float CLOT_PALE_RANGE = 1.1f; + +// Its launch at Sumptorium's call: a burst of blood, a push away from the player turned a little, its trail of blood, +// what it deals to what it passes, its flight home and how close counts as home, and its glowing trail. +constexpr float CLOT_BURST_SPEED = 6; +constexpr float CLOT_LAUNCH_SPREAD = 40; +constexpr float CLOT_BURST_LIFT = -6; +constexpr float CLOT_BURST_DEPTH = 10; +constexpr int CLOT_DRIP_INTERVAL = 2; +constexpr float CLOT_DRIP_SPEED_MIN = 0.25f; +constexpr float CLOT_DRIP_SPEED_RANGE = 0.25f; +constexpr float CLOT_DRIP_SIZE_MIN = 0.3f; +constexpr float CLOT_DRIP_SIZE_RANGE = 0.3f; +constexpr float CLOT_LIFT = -8; +constexpr float CLOT_HIT_RADIUS = 20; +constexpr float CLOT_HIT_SCALE = 3; +constexpr int CLOT_HIT_COUNTDOWN = 30; +constexpr float CLOT_HOME_SPEED = 20; +constexpr float CLOT_HOME_MARGIN = 2; +constexpr float CLOT_HOME_REACH = 10; +constexpr float CLOT_RETURN_DRAG = 0.25f; +constexpr float CLOT_TRAIL_SCALE = 2; +constexpr float CLOT_TRAIL_RADIUS = 0.15f; +constexpr float CLOT_TRAIL_ALPHA = 0.4f; + +// Tainted Eve's Birthright: a red clot's death drops a half heart. +constexpr float CLOT_HEART_SPEED_MIN = 2; +constexpr float CLOT_HEART_SPEED_RANGE = 3; +constexpr int CLOT_HEART_TIMEOUT = 60; + +// A walking clot's body by direction, and how long a fresh clot is safe from hits. +constexpr std::string_view CLOT_WALK_ANIMS[] = {"WalkLeft", "WalkUp", "WalkRight", "WalkDown"}; +constexpr int CLOT_SPAWN_COUNTDOWN = 20; + +// A clot's row in the table, the last for any subtype past it. +static const ClotLook& clot_look(Entity_Familiar& clot) +{ + return CLOT_LOOKS[std::min((uint32_t)clot.subtype, (uint32_t)CLOT_LIL)]; +} + +// The grid collision a clot walks with: over walls like a flying player, else on the ground. +static int clot_grid_class(Entity_Player& player) +{ + return player.entityGridCollisionClass <= GRIDCOLL_WALLS ? GRIDCOLL_WALLS : GRIDCOLL_GROUND; +} + +// Part of 0060de70: a clot starts walking down, cropped to its kind's look with its splat colour, Lil Clot with 3 +// health (thirty in a versus match), a soul clot with half again and a rotten one with half its health. +void blood_clot_init(Entity_Familiar& clot) +{ + clot.sprite.SetFrame("WalkDown", 0); + clot.sprite.SetOverlayFrame("HeadDown", 0); + clot.fireCooldown = 0; + clot.headFrameDelay = 0; + clot.damageCountdown = CLOT_SPAWN_COUNTDOWN; + clot.state = CLOT_WALKING; + clot.entityGridCollisionClass = GRIDCOLL_GROUND; + clot.shootDirection = DIRECTION_NONE; + + const ClotLook& look = clot_look(clot); + clot.sprite.GetLayer(0)->cropOffset = vector_make(look.cropX, look.cropY); + clot.sprite.GetLayer(1)->cropOffset = vector_make(look.cropX, look.cropY); + clot.splatColor = look.splat; + if (clot.subtype == CLOT_LIL) + { + clot.health = CLOT_LOOKS[CLOT_LIL].healthFloor * (familiar_versus() ? 10.0f : 1.0f); + return; + } + if (clot.subtype != CLOT_SOUL && clot.subtype != CLOT_ROTTEN) return; + + clot.maxHitPoints *= clot.subtype == CLOT_SOUL ? 1.5f : 0.5f; + clot.health = clot.maxHitPoints; +} + +// Part of 0064e0c0: a walking clot copies the player's movement input (none while the player drops), gripping toward +// the input and braking against it, faster with the player's speed. Its crawlspace fall keeps it off the vertical. +static Vector clot_steer(Entity_Familiar& clot, int gridClass) +{ + Entity_Player& player = *clot.player; + Vector input{}; + bool isClimbing = clot.HasEntityFlags(FLAG_APPLY_GRAVITY) && gridClass == GRIDCOLL_GROUND; + if (player.isControlsEnabled && player.controlsCooldown < 1) + { + input = player.GetMovementJoystick(); + if (isClimbing) input.y = 0; + if (vector_length(input) > 1) input = vector_resized(input, 1); + } + if (input_is_action_pressed(ACTION_DROP, player.controllerIndex, &player)) input = {}; + clot.targetPosition = input; + + Vector push = vector_scale(input, player.moveSpeed * CLOT_SPEED_SCALE + CLOT_SPEED_BASE); + clot.moveDirection = DIRECTION_NONE; + if (std::fabs(push.x) > std::fabs(push.y)) clot.moveDirection = push.x >= 0 ? DIRECTION_RIGHT : DIRECTION_LEFT; + else if (push.y < 0) clot.moveDirection = DIRECTION_UP; + else if (push.y > 0) clot.moveDirection = DIRECTION_DOWN; + + Vector& velocity = clot.velocity; + if (!vector_is_zero(push) && !isClimbing) + { + Vector along = vector_scale(push, vector_dot(push, velocity)); + velocity = vector_add(vector_scale(vector_sub(velocity, along), std::sqrt(CLOT_TURN_GRIP)), along); + } + float accel = (std::max(vector_dot(push, velocity) * CLOT_BRAKE, 0.0f) / player.moveSpeed + CLOT_ACCEL_BASE) * + CLOT_ACCEL_SCALE * HALF; + float drag = std::sqrt(CLOT_DRAG); + velocity.x = (push.x * accel + velocity.x) * drag; + velocity.y = push.y * accel + velocity.y; + velocity.y = isClimbing ? velocity.y + CLOT_FALL : velocity.y * drag; + return input; +} + +// Part of 0064e0c0: a walking clot's look. Its body walks the way it moves and its head (a column of the sheet) faces +// the player's shot, else its walk. The walk's pace follows its speed. +static void clot_animate(Entity_Familiar& clot, Vector input) +{ + bool isMoving = !vector_is_zero(input); + std::string_view anim = "Float"; + if (clot.entityGridCollisionClass == GRIDCOLL_GROUND) + anim = isMoving ? CLOT_WALK_ANIMS[vector_to_direction(input)] : "Idle"; + + Vector crop = vector_make(clot_look(clot).cropX, clot_look(clot).cropY); + if (clot.headFrameDelay > CLOT_HEAD_SHOOT_FRAMES) crop.y += CLOT_HEAD_SHOOT_ROW; + int facing = clot.shootDirection; + if (!clot.CanPlayerFire() || clot.player->fireDirection == DIRECTION_NONE || facing == DIRECTION_NONE) + facing = isMoving ? vector_to_direction(input) : DIRECTION_DOWN; + crop.x += CLOT_HEAD_COLUMNS - (float)facing * CLOT_HEAD_COLUMN; + clot.sprite.GetLayer(0)->cropOffset = crop; + clot.sprite.GetLayer(1)->cropOffset = crop; + clot.sprite.Play(anim); + + float pace = 1; + if (isMoving && clot.sprite.IsPlaying()) + { + float speed = vector_length(clot.velocity); + if (speed < CLOT_WALK_FULL_SPEED) pace = std::clamp((speed - 1) / CLOT_WALK_SPEED_SPAN, 0.0f, 1.0f) * HALF + HALF; + if (speed > CLOT_RUN_SPEED) pace = std::clamp((speed - CLOT_RUN_SPEED) * CLOT_RUN_STEP, 0.0f, 1.0f) + 1; + } + clot.sprite.playbackSpeed = pace; +} + +// Part of 0064e0c0: a walking clot keeps off its player and its player's other clots. +static void clot_space(Entity_Familiar& clot) +{ + Vector push{}; + for (Entity* other : entity_query_radius(clot.pos, CLOT_SPACING_RADIUS, QUERY_FAMILIARS | QUERY_PLAYERS)) + { + bool isOwner = other == clot.player; + auto* familiar = other->type == ENTITY_FAMILIAR ? static_cast(other) : nullptr; + if (!isOwner && !(familiar && familiar->variant == clot.variant && familiar->player == clot.player)) continue; + + Vector apart = vector_sub(clot.pos, other->pos); + if (!vector_is_zero(apart)) push = vector_add(push, vector_scale(apart, HALF / vector_length_squared(apart))); + } + if (vector_length(push) > CLOT_SPACING_PUSH) push = vector_resized(push, CLOT_SPACING_PUSH); + clot.velocity = vector_add(clot.velocity, vector_scale(push, clot.speedMultiplier)); +} + +// Part of 0064e0c0: a clot counting down to its launch bursts away from the player, invisible and untouchable, with a +// fresh hit list. +static void clot_launch(Entity_Familiar& clot) +{ + clot.state = CLOT_LAUNCHED; + clot.isVisible = false; + familiar_sound_play(SOUND_DEATH_BURST_SMALL); + Entity* burst = g_game->Spawn({.position = clot.pos, + .subType = 2, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + burst->SetColor(clot.splatColor, -1, 255, false, true); + burst->sprite.offset = vector_make(0, CLOT_BURST_LIFT); + burst->renderDepthOffset = CLOT_BURST_DEPTH; + burst->Update(); + + clot.entityCollisionClass = ENTCOLL_NONE; + clot.entityGridCollisionClass = GRIDCOLL_NONE; + Vector away = vector_resized(vector_sub(clot.pos, clot.player->pos), CLOT_BURST_SPEED); + clot.velocity = vector_rotated(away, random_unit() * CLOT_LAUNCH_SPREAD - CLOT_LAUNCH_SPREAD * HALF); + clot.hitList.clear(); +} + +// Part of 0064e0c0: a walking clot bleeds down toward its floor, paling and shrinking with its health. Lil Clot keeps +// its health and only shrinks. +static void clot_size(Entity_Familiar& clot) +{ + float scale = 0; + if (clot.subtype == CLOT_LIL) + scale = std::clamp(clot.health / CLOT_LOOKS[CLOT_LIL].healthFloor, 0.0f, 1.0f) * LIL_CLOT_SIZE_RANGE + CLOT_SIZE_BASE; + else + { + float floor = clot_look(clot).healthFloor; + if (clot.IsFrame(CLOT_BLEED_INTERVAL, 0) && clot.health > floor) + clot.health = std::max(clot.health - CLOT_BLEED, floor); + + float full = clot.config->baseHP; + float* colorize = clot.sprite.color._colorize; + std::fill(colorize, colorize + 3, 1.0f); + colorize[3] = CLOT_PALE - std::clamp(clot.health * clot.health / (full * full), 0.0f, 1.0f) * CLOT_PALE_RANGE; + scale = std::clamp(std::sqrt(clot.health / full), 0.0f, 1.0f) * CLOT_SIZE_RANGE + CLOT_SIZE_BASE; + } + clot.sprite.scale = vector_make(scale, scale); +} + +// Part of 0064e0c0: a walking clot (also after a launch while Sumptorium's effect lasts) follows the player's input, +// copies the player's weapon, and launches when its countdown runs out. +static void clot_walk(Entity_Familiar& clot, bool isPostMove) +{ + Entity_Player& player = *clot.player; + if (clot.state == CLOT_RETURNED && !player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_SUMPTORIUM)) + clot.state = CLOT_WALKING; + + int gridClass = clot_grid_class(player); + clot.entityGridCollisionClass = gridClass; + Vector input = clot_steer(clot, gridClass); + if (!isPostMove) + { + clot_animate(clot, input); + clot_space(clot); + } + clot.update_weapon(isPostMove); + if (clot.state > CLOT_RETURNED && clot.state < 0 && ++clot.state >= 0) clot_launch(clot); + if (!isPostMove) clot_size(clot); +} + +// Part of 0064e0c0: a clot home with its player gives its heart when the player can take it, a soul clot waiting +// while a black clot is out (unless a soul half is open) and a black clot while a soul clot is out and a soul half is +// open. Whether it was absorbed. +static bool clot_absorb(Entity_Familiar& clot) +{ + Entity_Player& player = *clot.player; + bool isSoulHalf = (player.soulHearts & 1) && !player.IsBlackHeart(player.soulHearts); + auto isOtherOut = [&](int otherKind) + { + for (Entity_Familiar* other : familiar_query(clot.variant)) + if (other->player == &player && other->subtype == otherKind) return true; + return false; + }; + + int sound = 0; + switch (clot.subtype) + { + case CLOT_RED: + if (!player.CanPickRedHearts()) return false; + sound = SOUND_BOSS2_BUBBLES; + player.AddHearts(1, true, false); + break; + case CLOT_SOUL: + if (!player.CanPickSoulHearts() || (!isSoulHalf && isOtherOut(CLOT_BLACK))) return false; + sound = SOUND_HOLY; + player.AddSoulHearts(1, false); + break; + case CLOT_BLACK: + if (!player.CanPickBlackHearts() || (isSoulHalf && isOtherOut(CLOT_SOUL))) return false; + sound = SOUND_UNHOLY; + player.AddBlackHearts(1); + break; + case CLOT_ETERNAL: + sound = SOUND_SUPERHOLY; + player.AddEternalHearts(1); + break; + case CLOT_GOLD: + if (!player.CanPickGoldenHearts()) return false; + sound = SOUND_GOLD_HEART; + player.AddGoldenHearts(1, false); + break; + case CLOT_BONE: + if (!player.CanPickBoneHearts()) return false; + sound = SOUND_BONE_HEART; + player.AddBoneHearts(1); + break; + case CLOT_ROTTEN: + if (!player.CanPickRottenHearts()) return false; + sound = SOUND_ROTTEN_HEART; + player.AddRottenHearts(2, false); + break; + default: return false; + } + familiar_sound_play(sound); + clot.Remove(); + return true; +} + +// Part of 0064e0c0: a launched clot's glowing trail, in its kind's colour. +static void clot_trail_spawn(Entity_Familiar& clot) +{ + Entity* trail = g_game->Spawn({.position = clot.pos, + .spawner = &clot, + .type = ENTITY_EFFECT, + .variant = EFFECT_SPRITE_TRAIL, + .seed = Random()}); + trail->sprite.color = clot_look(clot).trail; + trail->sprite.scale = vector_make(CLOT_TRAIL_SCALE, CLOT_TRAIL_SCALE); + bool isPremultiplied = KAGE::Graphics::manager.isPremultipliedAlpha; + trail->sprite.GetLayer(0)->blendMode = {BLEND_EQUATION_ADD, isPremultiplied ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA, + BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, BLEND_FACTOR_ONE, + BLEND_FACTOR_ONE_MINUS_SRC_ALPHA}; + auto& effect = static_cast(*trail); + effect.minRadius = CLOT_TRAIL_RADIUS; + effect.maxRadius = CLOT_TRAIL_RADIUS; + trail->parent = &clot; + trail->Update(); + clot.child = trail; +} + +// Part of 0064e0c0: a launched clot drips blood, hits each enemy it passes once (three times the player's damage) and +// flies home faster and faster. Home, it gives its heart or, a few frames on, walks again. +static void clot_fly(Entity_Familiar& clot) +{ + if (clot.IsFrame(CLOT_DRIP_INTERVAL, 0)) + { + uint32_t seed = Random(); + float speed = random_unit() * CLOT_DRIP_SPEED_RANGE + CLOT_DRIP_SPEED_MIN; + Entity* drip = g_game->Spawn({.position = clot.pos, + .velocity = vector_scale(clot.velocity, speed), + .type = ENTITY_EFFECT, + .variant = EFFECT_HAEMO_TRAIL, + .seed = seed}); + drip->SetColor(clot.splatColor, -1, 255, false, true); + float size = random_unit() * CLOT_DRIP_SIZE_RANGE + CLOT_DRIP_SIZE_MIN; + drip->sprite.scale = vector_make(size, size); + drip->posOffset = vector_add(clot.posOffset, vector_make(0, CLOT_LIFT)); + } + + for (Entity* enemy : entity_query_radius(clot.pos, CLOT_HIT_RADIUS, QUERY_ENEMIES)) + { + if (!enemy->IsVulnerableEnemy(nullptr) || enemy->HasEntityFlags(FLAG_FRIENDLY) || + EntityList::HitListContains(clot.hitList, *enemy)) + continue; + + hit_list_insert(clot.hitList, *enemy); + enemy->TakeDamage(clot.player->meleeDamage * CLOT_HIT_SCALE, 0, EntityRef(&clot), CLOT_HIT_COUNTDOWN); + } + + float pull = (float)(clot.state++ - 1); + Vector home = vector_normalized(vector_sub(clot.player->pos, clot.pos)); + clot.velocity = vector_add(clot.velocity, vector_scale(home, pull * pull * clot.speedMultiplier)); + if (vector_length(clot.velocity) > CLOT_HOME_SPEED) clot.velocity = vector_resized(clot.velocity, CLOT_HOME_SPEED); + + float reach = std::max(vector_length(clot.velocity) + CLOT_HOME_MARGIN, CLOT_HOME_REACH); + if (vector_distance(clot.pos, clot.player->pos) <= reach) + { + clot.state = std::max(clot.state, CLOT_ARRIVED); + if (!clot_absorb(clot) && clot.state > CLOT_ARRIVED_LIMIT) + { + clot.state = CLOT_RETURNED; + if (clot.child) clot.child->Remove(); + clot.isVisible = true; + clot.entityGridCollisionClass = clot_grid_class(*clot.player); + clot.entityCollisionClass = ENTCOLL_ENEMIES; + clot.velocity = vector_scale(clot.velocity, CLOT_RETURN_DRAG); + } + } + if (!clot.child && clot.state > CLOT_LANDING) clot_trail_spawn(clot); +} + +// 0064e0c0 The clots of Sumptorium and Lil Clot, run on each update and again after each move: they walk with the +// player's input and copy the player's shots, and launched they fly home through the enemies, their trail following. +void Entity_Familiar::ai_blood_clot(bool isPostMove) +{ + if (state == CLOT_LANDING) + { + if (sprite.IsPlaying() || isPostMove) return; + + entityCollisionClass = ENTCOLL_ENEMIES; + state = CLOT_WALKING; + return; + } + if (state < CLOT_LAUNCHED) return clot_walk(*this, isPostMove); + + if (!isPostMove) clot_fly(*this); + if (!child) return; + + child->sprite.color._tint[3] = CLOT_TRAIL_ALPHA; + child->pos = vector_add(vector_add(pos, posOffset), vector_make(0, CLOT_LIFT)); +} + +// Part of 00624a80: a clot moves itself between frames (its drag scaled to the time step), runs again and predicts its +// grid collision. +void blood_clot_interpolate(Entity_Familiar& clot) +{ + float drag = timescale_factor(clot.friction, clot.speedMultiplier); + clot.velocity = vector_scale(clot.velocity, drag); + clot.friction = clot.baseFriction; + clot.pos = vector_add(clot.pos, vector_scale(clot.velocity, clot.speedMultiplier)); + clot.ai_blood_clot(true); + clot.CollideWithGrid(GRID_COLLISION_SIMULATE); +} + +// Part of 00610540: a red clot of Tainted Eve with Birthright drops a half heart as it dies. +void blood_clot_death(Entity_Familiar& clot) +{ + Entity_Player* player = clot.player; + if (player->playerType != PLAYER_EVE_B || !player->HasCollectible(COLLECTIBLE_BIRTHRIGHT) || clot.subtype != CLOT_RED) + return; + + uint32_t seed = clot.dropRNG.Next(); + Vector direction = random_direction(); + float speed = random_unit() * CLOT_HEART_SPEED_RANGE + CLOT_HEART_SPEED_MIN; + auto* heart = static_cast(g_game->Spawn({.position = clot.pos, + .velocity = vector_scale(direction, speed), + .spawner = &clot, + .subType = HEART_HALF, + .type = ENTITY_PICKUP, + .variant = PICKUP_HEART, + .seed = seed})); + heart->timeout = CLOT_HEART_TIMEOUT; + heart->Update(); +} diff --git a/src/familiar_collision.cpp b/src/familiar_collision.cpp index f20b161..18dd5a0 100644 --- a/src/familiar_collision.cpp +++ b/src/familiar_collision.cpp @@ -25,13 +25,12 @@ constexpr int POOTER_SUPER = 2; constexpr int CONTACT_VARIANTS[] = {33, 60, 15, 14, 79, 77, 3, 104, 44, 45, 46, 47, 32, 83, 121, 126, 226, 224, 210, 218, 206, 237, 229, 204}; -// The familiars whose touch, block or hit has an effect of its own not reconstructed yet. -constexpr int UNWRITTEN_TOUCH_VARIANTS[] = {87, 243, 204, 93}; -constexpr int UNWRITTEN_BLOCK_VARIANTS[] = {228, 238, 201}; -constexpr int UNWRITTEN_ENEMY_TOUCH_VARIANTS[] = {228, 238, 201}; +// The familiars whose block or hit has an effect of its own not reconstructed yet. +constexpr int UNWRITTEN_BLOCK_VARIANTS[] = {201}; +constexpr int UNWRITTEN_ENEMY_TOUCH_VARIANTS[] = {201}; // The hit Tinytoma takes from each shot it stops. constexpr float TINYTOMA_SHOT_HURT = 3.5f; -constexpr int UNWRITTEN_DEATH_VARIANTS[] = {128, 229, 234, 201, 238}; +constexpr int UNWRITTEN_DEATH_VARIANTS[] = {128, 229, 234, 201}; // 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}; @@ -273,8 +272,7 @@ void Entity_Familiar::collision_hurt(Entity& collider, float damageMultiplier, f collider.AddIce(EntityRef(this), CUBE_ICE_FRAMES); } if (variant == LEECH && familiar_versus()) reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (a versus Leech)"); - if (variant == LIL_GURDY && damageMultiplier > 0) - reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (Lil Gurdy's bounce)"); + if (variant == LIL_GURDY && damageMultiplier > 0) lil_gurdy_bounce(*this, collider); if (variant == SHADE) state += (int)dealt; else if (variant == LEPROSY && ++state >= LEPROSY_HITS) @@ -344,6 +342,14 @@ bool Entity_Familiar::collision_contact(Entity& collider, float damageMultiplier familiar_sound_play(SOUND_INSECT_POP, {.frameDelay = SOUND_POP_DELAY}); return true; } + if (variant == GB_BUG && subtype == 0 && collider.IsActiveEnemy(DEAD_EXCLUDED) && collider.type != ENTITY_PLAYER) + { + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + isVisible = false; + familiar_sound_play(SOUND_EDEN_GLITCH); + subtype = 1; + reconstruction_missing("Game::RerollEnemy 007050c0 (GB Bug's reroll of an enemy)"); + } if (variant == BBF || variant == BOBS_BRAIN) brain_explode(*this, collider, damageMultiplier); if (variant == HOLY_WATER && subtype == 0) holy_water_break(*this); return isIgnored; @@ -400,7 +406,8 @@ bool Entity_Familiar::collision_block(Entity& collider, bool isIgnored) else if (variant == BONE_ORBITAL || variant == SWARM_FLY_ORBITAL || (variant == BONE_SPUR && (state += BONE_WEAR) > BONE_WEAR_LIMIT)) Kill(EntityRef()); - if (variant == TINYTOMA || variant == TINYTOMA_2) TakeDamage(TINYTOMA_SHOT_HURT, 0, EntityRef(&collider), 1); + if (variant == MINISAAC || variant == BLOOD_BABY) TakeDamage(1, 0, EntityRef(&collider), 1); + else if (variant == TINYTOMA || variant == TINYTOMA_2) TakeDamage(TINYTOMA_SHOT_HURT, 0, EntityRef(&collider), 1); collider.isDead = true; return isIgnored; } @@ -520,7 +527,8 @@ bool Entity_Familiar::HandleCollision(Entity* collider, bool isLow) if (collider->type == ENTITY_PLAYER && orbitSpeed < 0) return true; isIgnored = false; } - if (familiar_listed(UNWRITTEN_TOUCH_VARIANTS, variant) || sirenHelper) + if (variant == PSY_FLY && psy_fly_touch(*this, *collider)) return true; + if (sirenHelper) reconstruction_missing("Entity_Familiar::HandleCollision 006261f0 (this familiar's touch)"); if (variant == DEPRESSION) depression_touch(*this, *collider); @@ -643,7 +651,8 @@ bool Entity_Familiar::TakeDamage(float damage, uint64_t damageFlags, const Entit } // 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. +// familiars that die their own way (the bone orbitals, the swarm flies, the Dips) stop the game. Tainted +// Eve's clots refresh her heart effects. void Entity_Familiar::Kill(const EntityRef& source) { if (!isDead && (variant == TINYTOMA || variant == TINYTOMA_2)) @@ -665,7 +674,9 @@ void Entity_Familiar::Kill(const EntityRef& source) blood->SetColor(splatColor, -1, 255, false, true); blood->Update(); BloodExplode(); + if (variant == BLOOD_BABY) blood_clot_death(*this); } Entity::Kill(source); Remove(); + if (variant == BLOOD_BABY && player && player->playerType == PLAYER_EVE_B) player->UpdateHeartDependentEffects(); } diff --git a/src/familiar_evaluate.cpp b/src/familiar_evaluate.cpp index cdc45ea..6a34f48 100644 --- a/src/familiar_evaluate.cpp +++ b/src/familiar_evaluate.cpp @@ -63,8 +63,6 @@ constexpr int NULLITEM_HALO_FLY_LOSS = 107; constexpr int HALO_FLY_CAP = 10; constexpr int ACHIEVEMENT_CUBE_OF_MEAT_FULL = 144; constexpr int ACHIEVEMENT_BALL_OF_BANDAGES_FULL = 19; -constexpr int COLLECTIBLE_KEY_BUM = 388; -constexpr int COLLECTIBLE_BUM_FRIEND = 144; constexpr int COLLECTIBLE_LIL_DELIRIUM = 519; // Super Bum's arrival: the state flag that shows its page once, the page, and the three bums it takes the place of. @@ -369,3 +367,152 @@ void familiars_evaluate(Entity_Player& p) } if (familiarItems > FAMILIAR_ACHIEVEMENT_COUNT) g_manager->persistentGameData.TryUnlock(ACHIEVEMENT_FAMILIARS); } + +// What sacrificing a familiar takes back: the Super Bum part and Key Piece it may stand for, the conception familiars' +// bits (a familiar a conception gave takes nothing), and Big Fan's and Esau Jr.'s extra null effect. +constexpr int SUPER_BUM_PART_ITEMS[] = {COLLECTIBLE_BUM_FRIEND, COLLECTIBLE_DARK_BUM, COLLECTIBLE_KEY_BUM}; +constexpr RNG SUPER_BUM_PART_RNG = {0, 2, 21, 9}; +constexpr std::pair CONCEPTION_FAMILIAR_BITS[] = { + {COLLECTIBLE_LEECH, 1 << 0}, {COLLECTIBLE_DARK_BUM, 1 << 1}, {COLLECTIBLE_DEMON_BABY, 1 << 2}, + {COLLECTIBLE_INCUBUS, 1 << 3}, {COLLECTIBLE_LIL_BRIMSTONE, 1 << 4}, {COLLECTIBLE_SUCCUBUS, 1 << 5}, + {COLLECTIBLE_GUARDIAN_ANGEL, 1 << 6}, {COLLECTIBLE_HOLY_WATER, 1 << 7}, {COLLECTIBLE_RELIC, 1 << 8}, + {COLLECTIBLE_SWORN_PROTECTOR, 1 << 9}, {COLLECTIBLE_SERAPHIM, 1 << 10}}; +constexpr int CUBE_OF_MEAT_FIRST = Entity_Familiar::CUBE_OF_MEAT_1 - 1; +constexpr int BALL_OF_BANDAGES_FIRST = Entity_Familiar::BALL_OF_BANDAGES_1 - 1; + +// How many copies of a sacrificed familiar's collectible go: a conception familiar's none, Halo of Flies' only when +// no spare fly is left, a Cube of Meat's or Ball of Bandages' levels beyond what the Potato Peeler gave, and Leprosy's +// none (it only loses a count). Any other one copy. +static int sacrifice_count(Entity_Familiar& familiar, int collectible) +{ + Entity_Player& player = *familiar.player; + bool isConceived = player.HasCollectible(COLLECTIBLE_IMMACULATE_CONCEPTION) || + player.HasCollectible(COLLECTIBLE_CAMBION_CONCEPTION); + auto bit = std::ranges::find(CONCEPTION_FAMILIAR_BITS, collectible, &std::pair::first); + if (isConceived && bit != std::end(CONCEPTION_FAMILIAR_BITS)) + return player.conceptionFamiliarFlags & bit->second ? 0 : 1; + + auto peel = [&](int& peeled, int levels) + { + int taken = std::min(levels, peeled); + peeled -= taken; + return levels - taken; + }; + switch (collectible) + { + case COLLECTIBLE_HALO_OF_FLIES: + { + int& spare = player.pillEffectUses[COLLECTIBLE_HALO_OF_FLIES]; + if (spare > 0) + { + spare--; + return 0; + } + if (!player.HasCollectible(COLLECTIBLE_HALO_OF_FLIES)) return 0; + spare++; + return 1; + } + case COLLECTIBLE_LEPROSY: + player.numLeprosy--; + return 0; + case COLLECTIBLE_CUBE_OF_MEAT: return peel(player.potatoPeelerCounter, familiar.variant - CUBE_OF_MEAT_FIRST); + case COLLECTIBLE_BALL_OF_BANDAGES: + return peel(player.potatoPeelerBandageCounter, familiar.variant - BALL_OF_BANDAGES_FIRST); + default: return 1; + } +} + +// Part of 0063b8b0: takes one copy of a sacrificed familiar's collectible, ending its effect when only the effect +// gave it (an active without a passive cache, or one of the floor's effect items). +static void sacrifice_collectible(Entity_Player& player, ItemConfig_Item& item, int index) +{ + TemporaryEffects& effects = player.temporaryEffects; + bool isEffect = !effects.isDisabled && effects.has_item_effect(&item); + if (isEffect && !(item.type == ITEM_ACTIVE && !item.isPassiveCache)) + { + std::vector& floorItems = player.levelEffectItems; + auto found = std::ranges::find(floorItems, item.id); + if (found == floorItems.end()) isEffect = false; + else + { + floorItems.erase(found); + // The original reads the floor list at the copy's index after erasing, out of range when it ran short. + if (index < (int)floorItems.size()) + if (ItemConfig_Item* other = g_manager->itemConfig.GetCollectible(floorItems[index])) + effects.RemoveEffect(other, 1); + } + } + if (isEffect) effects.RemoveEffect(&item, 1); + else player.RemoveCollectible(item.id, false, 0, true); +} + +// 0063b8b0 Sacrificial Altar's take of a familiar: it leaves, and its player loses what gave it (a collectible copy, +// a trinket, a null effect, a count or a transformation). +void Entity_Familiar::RemoveFromPlayer(uint8_t) +{ + Remove(); + Entity_Player& owner = *player; + ItemConfig& items = g_manager->itemConfig; + ItemConfig_Item* given = item; + bool isEvaluated = false; + switch (variant) + { + case KEY_FULL: + given = items.GetCollectible(owner.HasCollectible(COLLECTIBLE_KEY_PIECE_2) ? COLLECTIBLE_KEY_PIECE_2 : COLLECTIBLE_KEY_PIECE_1); + isEvaluated = true; + break; + case BIG_FAN: + if (!owner.temporaryEffects.HasNullEffect(NULLITEM_HALO_FLY_LOSS)) break; + owner.temporaryEffects.RemoveNullEffect(NULLITEM_HALO_FLY_LOSS, 1); + return owner.AddCacheFlags(CACHE_FAMILIARS), owner.EvaluateItems(); + case SUPER_BUM: + { + RNG rng = SUPER_BUM_PART_RNG; + rng._seed = initSeed; + given = items.GetCollectible(SUPER_BUM_PART_ITEMS[rng.RandomInt(3)]); + isEvaluated = true; + break; + } + case TONSIL: + owner.tonsilCount = (short)std::max(owner.tonsilCount - 1, 0); + return owner.AddCacheFlags(CACHE_FAMILIARS), owner.EvaluateItems(); + case SPIDER_BABY: + if (owner.playerForms[PLAYER_FORM_SPIDER_BABY] > 0) + owner.IncrementPlayerFormCounter(PLAYER_FORM_SPIDER_BABY, -owner.playerForms[PLAYER_FORM_SPIDER_BABY]); + return; + case ESAU_JR: + owner.temporaryEffects.RemoveNullEffect(NULLITEM_HALO_FLY_LOSS, 1); + return owner.AddCacheFlags(CACHE_FAMILIARS), owner.EvaluateItems(); + } + + if (given && given->type == ITEM_TRINKET && owner.HasTrinket(given->id)) owner.TryRemoveTrinket(given->id); + else if (given && (given->type == ITEM_PASSIVE || given->type == ITEM_ACTIVE || given->type == ITEM_FAMILIAR)) + { + int copies = sacrifice_count(*this, given->id); + for (int i = 0; i < copies; i++) sacrifice_collectible(owner, *given, i); + } + if (!isEvaluated) return; + + owner.AddCacheFlags(CACHE_FAMILIARS); + owner.EvaluateItems(); +} + +// 0064bab0 The Siren lets a charmed familiar go: back to its own player (the charm's extra Big Fan or Guardian Angel +// count dropped from a stand-in player), its helper gone. The Siren's own minion leaves. +void Entity_Familiar::RemoveFromPlayer() +{ + if (sirenOriginalPlayer) + { + if (!player->isValid && variant == BIG_FAN) player->collectibleCounts[COLLECTIBLE_BIG_FAN]--; + else if (!player->isValid && variant == GUARDIAN_ANGEL) player->collectibleCounts[COLLECTIBLE_GUARDIAN_ANGEL]--; + set_player(sirenOriginalPlayer); + } + sirenCharmFrames = 0; + sirenOriginalPlayer = nullptr; + if (sirenHelper) + { + sirenHelper->Remove(); + sirenHelper = nullptr; + } + if (variant == SIREN_MINION) Remove(); +} diff --git a/src/familiar_locust.cpp b/src/familiar_locust.cpp index e126c0f..d77935d 100644 --- a/src/familiar_locust.cpp +++ b/src/familiar_locust.cpp @@ -157,6 +157,7 @@ constexpr float LOCUST_FART_RADIUS = 15; constexpr float FART_SCALE = 0.4f; constexpr float LOCUST_BUTTER_BEAN_RADIUS = 40; constexpr float RIFT_DAMAGE = 0.25f; +constexpr float JACOBS_DAMAGE = 0.25f; constexpr float RIFT_SCALE = 0.4f; // How the shot sprites fade in while it flies and out after, and where they draw (a locust's sprite sits 25 up), at @@ -710,7 +711,7 @@ static void locust_rift(Entity_Familiar& locust, float scale) } // 00649290 What a locust's hit sets off besides the tear effects: bone shards, a rift, an explosion, Black Powder's -// circle, creep, the Necronomicon, the Maw of the Void's ring, farts and a brimstone beam. Jacob's Ladder, devolving, +// circle, creep, the Necronomicon, the Maw of the Void's ring, farts, a brimstone beam and Jacob's Ladder. Devolving, // erasing and the shockwave stop the game. static void locust_hit_effects(Entity_Familiar& locust, const TearFlags& flags, uint32_t locustFlags, Entity& target) { @@ -737,7 +738,12 @@ static void locust_hit_effects(Entity_Familiar& locust, const TearFlags& flags, } } if (flags[TEAR_JACOBS]) - reconstruction_missing("Entity_Familiar::apply_tear_flag_effects 00649290 (Jacob's Ladder)"); + { + Entity_Effect* chain = chain_lightning_spawn( + {.tearFlags = flags, .position = locust.pos, .spawner = &player, .damage = player.damage * JACOBS_DAMAGE}); + chain->target = ⌖ + chain->Update(); + } if (flags[TEAR_RIFT]) locust_rift(locust, locust.sprite.scale.x); if (locustFlags & LOCUST_FLAG_EXPLODE) diff --git a/src/familiar_missing.cpp b/src/familiar_missing.cpp index 64f1581..6c847e0 100644 --- a/src/familiar_missing.cpp +++ b/src/familiar_missing.cpp @@ -16,12 +16,6 @@ void Entity_Familiar::farting_baby_fart() reconstruction_missing("Entity_Familiar::farting_baby_fart 0062c8d0 (Acid Baby and Lil Spewer)"); } -// 0062ee30 -void Entity_Familiar::ai_lil_gurdy() -{ - reconstruction_missing("Entity_Familiar::ai_lil_gurdy 0062ee30"); -} - // 00631850 void Entity_Familiar::move_to_parent_offset() { @@ -40,42 +34,18 @@ void Entity_Familiar::delirium_morph() reconstruction_missing("Entity_Familiar::delirium_morph 00631b20"); } -// 006322f0 -void Entity_Familiar::init_lil_harbinger_sprite() -{ - reconstruction_missing("Entity_Familiar::init_lil_harbinger_sprite 006322f0"); -} - -// 00632d90 -void Entity_Familiar::ai_variant_111() -{ - reconstruction_missing("Entity_Familiar::ai_variant_111 00632d90"); -} - // 00634b10 void Entity_Familiar::ai_lil_spewer() { reconstruction_missing("Entity_Familiar::ai_lil_spewer 00634b10"); } -// 006378c0 -void Entity_Familiar::ai_lil_harbingers() -{ - reconstruction_missing("Entity_Familiar::ai_lil_harbingers 006378c0"); -} - // 0063aef0 Entity_Laser* Entity_Familiar::sprinkler_shoot_laser(float, float) { reconstruction_missing("Entity_Familiar::sprinkler_shoot_laser 0063aef0"); } -// 0063b8b0 -void Entity_Familiar::RemoveFromPlayer(uint8_t) -{ - reconstruction_missing("Entity_Familiar::RemoveFromPlayer 0063b8b0"); -} - // 0063c1c0 void Entity_Familiar::ai_minisaac() { @@ -94,42 +64,12 @@ void Entity_Familiar::minisaac_find_target() reconstruction_missing("Entity_Familiar::minisaac_find_target 0063dd60"); } -// 006424d0 -void Entity_Familiar::ai_bird_cage() -{ - reconstruction_missing("Entity_Familiar::ai_bird_cage 006424d0"); -} - -// 006444d0 -Entity* Entity_Familiar::aim_reflected_projectile() -{ - reconstruction_missing("Entity_Familiar::aim_reflected_projectile 006444d0"); -} - -// 00644e80 -void Entity_Familiar::ai_shadow_intruder_damocles(bool) -{ - reconstruction_missing("Entity_Familiar::ai_shadow_intruder_damocles 00644e80"); -} - -// 0064bab0 -void Entity_Familiar::RemoveFromPlayer() -{ - reconstruction_missing("Entity_Familiar::RemoveFromPlayer 0064bab0"); -} - // 0064d1d0 void Entity_Familiar::update_star_of_bethlehem_speed(bool) { reconstruction_missing("Entity_Familiar::update_star_of_bethlehem_speed 0064d1d0"); } -// 0064e0c0 -void Entity_Familiar::ai_blood_clot(bool) -{ - reconstruction_missing("Entity_Familiar::ai_blood_clot 0064e0c0"); -} - // 009615e0 uint8_t Entity_Familiar::multidimensional_baby_copy_knife(Entity_Knife*, Entity*) { diff --git a/src/familiar_repentance.cpp b/src/familiar_repentance.cpp index a1b277e..36270a1 100644 --- a/src/familiar_repentance.cpp +++ b/src/familiar_repentance.cpp @@ -1,4 +1,5 @@ #include "entity_familiar.h" +#include "entity_bomb.h" #include "entity_config.h" #include "entity_effect.h" #include "entity_npc.h" @@ -7,12 +8,15 @@ #include "entity_tear.h" #include "capsule.h" #include "game.h" +#include "log.h" #include "npc_ai.h" #include "npc_basement.h" #include "room.h" +#include "room_descriptor.h" #include "room_grid.h" #include "seeds.h" #include +#include #include // Intruder: how often it shoots from the player's head, its drag, how far ahead it leads a target with its spit and @@ -648,6 +652,209 @@ void bot_fly_update(Entity_Familiar& fly) fly.target = nullptr; } +// Psy Fly: its glowing trail, how near the player's spot it looks for shots (sooner in versus), its orbit pull and +// settling, its dash at a shot, how long it dashes before tiring, its bounce back after a block, and the swatted flies +// it turns blue and the reflected tears it fires. +constexpr ColorMod PSY_FLY_TRAIL_COLOR = {{0.7f, 0, 0.85f, 0}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float PSY_FLY_TRAIL_SCALE = 0.6f; +constexpr float PSY_FLY_TRAIL_RADIUS = 0.12f; +constexpr float PSY_FLY_TRAIL_ALPHA = 0.8f; +constexpr float PSY_FLY_TRAIL_LIFT = -16; +constexpr float PSY_FLY_RANGE = 100; +constexpr int PSY_FLY_VERSUS_SEARCH = -60; +constexpr float PSY_FLY_ORBIT_REACH = 24; +constexpr float PSY_FLY_ORBIT_PULL = 4; +constexpr float PSY_FLY_SETTLE_CAP = 5; +constexpr float PSY_FLY_DRAG = 0.8f; +constexpr float PSY_FLY_REST_DRAG = 0.5f; +constexpr float PSY_FLY_DASH_DRAG = 0.7f; +constexpr int PSY_FLY_DASH_COOLDOWN = 4; +constexpr float PSY_FLY_DASH_LEAD = 0.04f; +constexpr float PSY_FLY_DASH_SPEED = 15; +constexpr int PSY_FLY_DASH_LIMIT = 60; +constexpr int PSY_FLY_BOUNCE_FRAME = 14; +constexpr float PSY_FLY_BOUNCE = -2; +constexpr int PSY_FLY_REST_JITTER = 14; +constexpr int PSY_FLY_BLOCKING = 12; +constexpr int PSY_FLY_SWATTED_TYPES[] = {ENTITY_FLY, ENTITY_ATTACKFLY, ENTITY_RING_OF_FLIES, ENTITY_SWARM, ENTITY_ARMYFLY, ENTITY_WILLO}; +constexpr float PSY_FLY_TEAR_SPEED = 10; +constexpr float PSY_FLY_TEAR_DAMAGE = 2; +constexpr float PSY_FLY_TEAR_SIZE = 0.2f; +constexpr float PSY_FLY_TEAR_SIZE_BASE = 0.8f; +constexpr ColorMod PSY_FLY_TEAR_COLOR = {{0.4f, 0.15f, 0.38f, 1}, {0, 0, 0, 0}, {0.35f, 0, 0.7f}}; +constexpr float PSY_FLY_STILL = 1e-05f; + +// Part of 00644780: Psy Fly's trail, following it faintly while it rests. +static void psy_fly_trail(Entity_Familiar& fly) +{ + if (fly.child) return; + + Entity* trail = g_game->Spawn( + {.position = fly.pos, .spawner = &fly, .type = ENTITY_EFFECT, .variant = EFFECT_SPRITE_TRAIL, .seed = Random()}); + trail->sprite.color = PSY_FLY_TRAIL_COLOR; + auto& effect = static_cast(*trail); + effect.minRadius = PSY_FLY_TRAIL_RADIUS; + effect.maxRadius = PSY_FLY_TRAIL_RADIUS; + trail->sprite.scale = vector_make(PSY_FLY_TRAIL_SCALE, PSY_FLY_TRAIL_SCALE); + trail->parent = &fly; + trail->Update(); + fly.child = trail; +} + +// Part of 00644780: an idle Psy Fly heads for its orbit spot, settling in ahead of the player's motion, and comes off +// its dash count. +static void psy_fly_orbit(Entity_Familiar& fly, int steps) +{ + Entity_Player& player = *fly.player; + Vector spot = fly.GetOrbitPosition(player.pos); + Vector toward = vector_sub(spot, fly.pos); + if (vector_length(toward) >= PSY_FLY_ORBIT_REACH) + { + fly.friction *= PSY_FLY_DRAG; + fly.velocity = vector_add(fly.velocity, vector_scale(vector_normalized(toward), PSY_FLY_ORBIT_PULL * fly.speedMultiplier)); + } + else + { + Vector lead = vector_scale(vector_add(player.velocity, player.velocity), 1 / player.friction); + Vector settle = vector_scale(vector_sub(spot, vector_add(lead, fly.pos)), HALF); + if (vector_length(settle) > PSY_FLY_SETTLE_CAP && !fly.HasEntityFlags(FLAG_SPIN)) + settle = vector_resized(settle, PSY_FLY_SETTLE_CAP); + fly.friction *= PSY_FLY_DRAG; + fly.velocity = vector_scale(vector_add(lead, settle), 1 / fly.friction); + } + if (fly.headFrameDelay < 0) fly.headFrameDelay = std::min(fly.headFrameDelay + steps, 0); + fly.child->sprite.color._tint[3] = 0; + fly.fireCooldown--; +} + +// Part of 00644780: a resting Psy Fly bounces back once after its block and jitters its rest down. +static void psy_fly_rest(Entity_Familiar& fly, int steps) +{ + if (fly.headFrameDelay > 0) fly.headFrameDelay = std::max(fly.headFrameDelay - steps, 0); + for (; steps > 0; steps--) + { + int left = fly.fireCooldown; + if (left == PSY_FLY_BOUNCE_FRAME) + { + fly.velocity = vector_scale(fly.velocity, PSY_FLY_BOUNCE); + fly.fireCooldown = PSY_FLY_BOUNCE_FRAME - 1; + } + else if (fly.fireCooldown--, (uint32_t)(left - 2) >= PSY_FLY_REST_JITTER) + continue; + if ((Random() & 1) == 0) fly.fireCooldown--; + } + fly.friction *= PSY_FLY_REST_DRAG; +} + +// Part of 00644780: Psy Fly dashes at where its shot will be, tiring after a while. +static void psy_fly_dash(Entity_Familiar& fly, int steps) +{ + Entity& shot = *fly.target; + fly.fireCooldown = PSY_FLY_DASH_COOLDOWN; + float lead = vector_distance(shot.pos, fly.pos) * PSY_FLY_DASH_LEAD * shot.friction; + Vector predicted = vector_add(shot.pos, vector_scale(shot.velocity, lead)); + if (predicted.x != fly.pos.x || predicted.y != fly.pos.y) + fly.velocity = vector_add(fly.velocity, vector_scale(vector_normalized(vector_sub(predicted, fly.pos)), + PSY_FLY_DASH_SPEED * fly.speedMultiplier)); + fly.headFrameDelay += steps; + if (fly.headFrameDelay > PSY_FLY_DASH_LIMIT) fly.headFrameDelay = -PSY_FLY_DASH_LIMIT; + fly.friction *= PSY_FLY_DASH_DRAG; +} + +// 00644780 (FamiliarAI::variant_204) Psy Fly orbits the player until a shot threatens the player's spot, dashes at it, +// rests after blocking and tires after dashing too long, its trail glowing while it hunts. +void psy_fly_update(Entity_Familiar& fly) +{ + psy_fly_trail(fly); + int steps = (int)fly.updateTime - (int)fly.prevUpdateTime; + if (fly.state == 0) + { + fly.fireCooldown = 0; + fly.headFrameDelay = 0; + fly.state = 1; + } + if (fly.headFrameDelay >= 0 && fly.fireCooldown <= (familiar_versus() ? PSY_FLY_VERSUS_SEARCH : 0)) + threatening_shot_target(fly, PSY_FLY_RANGE, THREAT_KEEP); + + if (!fly.target && fly.fireCooldown < 1) psy_fly_orbit(fly, steps); + else + { + if (fly.target) psy_fly_dash(fly, steps); + else psy_fly_rest(fly, steps); + fly.child->sprite.color._tint[3] = PSY_FLY_TRAIL_ALPHA; + } + fly.child->pos = vector_add(vector_add(fly.pos, fly.posOffset), vector_make(0, PSY_FLY_TRAIL_LIFT)); +} + +// 006444d0 The enemy a reflected shot goes for: the charming Siren's target, else the enemy most ahead of the +// familiar's flight (any at random when it is still). +Entity* Entity_Familiar::aim_reflected_projectile() +{ + Entity* charmer = player->parent.get(); + if (HasEntityFlags(FLAG_CHARM) && charmer && Entity::is_enemy_type(charmer->type)) + return static_cast(charmer)->GetPlayerTarget(); + + Vector heading = vector_normalized(velocity); + bool isStill = vector_length_squared(velocity) <= PSY_FLY_STILL; + Entity* best = nullptr; + float bestScore = 0; + for (Entity* enemy : g_game->room->entityList.updateEL) + { + bool isFoe = (familiar_versus() && enemy->type == ENTITY_PLAYER) || Entity::is_enemy_type(enemy->type); + bool isTargetable = !enemy->HasEntityFlags(FLAG_NO_TARGET) || enemy->type == ENTITY_DARK_ESAU || + enemy->type == ENTITY_BLOOD_PUPPY; + if (!isFoe || enemy->entityCollisionClass <= ENTCOLL_PLAYERONLY || enemy->isInvincible || enemy->isDead || + !isTargetable) + continue; + + float score = isStill ? random_unit() : vector_dot(heading, vector_normalized(vector_sub(enemy->pos, pos))); + if (score <= bestScore) continue; + + bestScore = score; + best = enemy; + } + return best; +} + +// Part of 006261f0: a hunting Psy Fly turns a shot it meets back as a homing tear at an enemy, and a fly it meets into +// a blue fly. Whether it handled the touch. +bool psy_fly_touch(Entity_Familiar& fly, Entity& collider) +{ + if (fly.fireCooldown <= PSY_FLY_BLOCKING || fly.HasEntityFlags(FLAG_CHARM)) return false; + + if (collider.type == ENTITY_PROJECTILE) + { + if (static_cast(collider).projectileFlags & PROJECTILE_EXPLODE) return false; + + collider.isDead = true; + Entity* aimed = fly.aim_reflected_projectile(); + Vector direction = aimed ? vector_normalized(vector_sub(aimed->pos, fly.pos)) + : vector_length_squared(fly.velocity) <= PSY_FLY_STILL ? random_direction() + : vector_normalized(fly.velocity); + float damage = fly.GetMultiplier() * PSY_FLY_TEAR_DAMAGE; + float size = fly.GetMultiplier() * PSY_FLY_TEAR_SIZE + PSY_FLY_TEAR_SIZE_BASE; + auto* tear = static_cast(g_game->Spawn({.position = fly.pos, + .velocity = vector_scale(direction, PSY_FLY_TEAR_SPEED), + .spawner = &fly, + .type = ENTITY_TEAR, + .seed = Random()})); + tear->SetCollisionDamage(damage); + tear->SetTearFlags(TearFlags().set(TEAR_HOMING)); + tear->SetColor(PSY_FLY_TEAR_COLOR, -1, 255, false, true); + tear->SetScale(size); + tear->target = aimed; + tear->Update(); + return true; + } + if (!familiar_listed(PSY_FLY_SWATTED_TYPES, collider.type) || collider.isDead || collider.HasEntityFlags(FLAG_FRIENDLY)) + return false; + + collider.Remove(); + Entity* blue = fly.player->AddBlueFlies(1, collider.pos, nullptr); + blue->velocity = collider.velocity; + return true; +} + // Whether Lil Dumpy fears what is about to hit its player: a harmful enemy (a player in versus) or an enemy shot // whose path meets the player's, not the player's own. static bool is_dumpy_danger(Entity_Familiar& dumpy, Entity& entity, const Capsule& playerPath) @@ -745,3 +952,543 @@ void lil_dumpy_update(Entity_Familiar& dumpy) float pace = std::clamp((vector_length(dumpy.velocity) - DUMPY_HIT_SPEED_MIN) / DUMPY_HIT_SPEED_RANGE, 0.0f, 1.0f); dumpy.collisionDamage = dumpy.GetMultiplier() * pace * DUMPY_HIT_DAMAGE; } + +// Bird Cage: how far its jump looks for an enemy, how far its landing follows a moving one, its landing's crush (the +// shockwaves it sends toward the enemies near, BFFS! sending three more around), its debris and its shake. +constexpr TargetSearch BIRD_CAGE_JUMP_SEARCH = {.range = 10000, .frameInterval = 0, .flags = TARGET_RETARGET | TARGET_PREFER_HEALTHY}; +constexpr float BIRD_CAGE_FOLLOW_SQUARED = 10000; +constexpr float BIRD_CAGE_CRUSH_DAMAGE = 45; +constexpr float BIRD_CAGE_CRUSH_RADIUS = 24; +constexpr float BIRD_CAGE_WAVE_REACH = 256; +constexpr float BIRD_CAGE_WAVE_STILL = 0.001f; +constexpr int BIRD_CAGE_BFFS_WAVES = 3; +constexpr int BIRD_CAGE_DEBRIS = 4; +constexpr float BIRD_CAGE_DEBRIS_SPREAD = 12; +constexpr float BIRD_CAGE_DEBRIS_SPEED = 5; +constexpr int BIRD_CAGE_SHAKE = 12; + +// The bird cage's states: perched, jumping up, coming down and flying. +enum BirdCageState +{ + BIRD_CAGE_PERCHED, + BIRD_CAGE_JUMPING, + BIRD_CAGE_FALLING, + BIRD_CAGE_FLYING +}; + +// A crackwave of the bird cage's landing, sent at an angle. +static void bird_cage_wave(Entity_Familiar& cage, float angle) +{ + auto* wave = static_cast(g_game->Spawn( + {.position = cage.pos, .spawner = cage.player, .type = ENTITY_EFFECT, .variant = EFFECT_CRACKWAVE, .seed = Random()})); + wave->parent = &cage; + wave->rotation = angle; + wave->Update(); +} + +// Part of 006424d0: the bird cage lands crushing what is under it, sending a crackwave at the enemies around it (any +// way when there are none), and shakes the room. +static void bird_cage_land(Entity_Familiar& cage) +{ + familiar_sound_play(SOUND_HELLBOSS_GROUNDPOUND); + explosion_damage({.position = cage.pos, .source = cage.player, .damage = BIRD_CAGE_CRUSH_DAMAGE, .radius = BIRD_CAGE_CRUSH_RADIUS}); + + Vector toward{}; + for (Entity* enemy : g_game->room->entityList.updateEL) + { + Vector to = vector_sub(enemy->pos, cage.pos); + float distance = vector_length(to); + bool isFoe = (familiar_versus() && enemy->type == ENTITY_PLAYER) || Entity::is_enemy_type(enemy->type); + bool isTargetable = !enemy->HasEntityFlags(FLAG_NO_TARGET) || enemy->type == ENTITY_BLOOD_PUPPY || + enemy->type == ENTITY_DARK_ESAU; + if (isFoe && enemy->entityCollisionClass > ENTCOLL_PLAYERONLY && !enemy->isInvincible && !enemy->isDead && + isTargetable && distance <= BIRD_CAGE_WAVE_REACH && distance > 0) + toward = vector_add(toward, vector_scale(to, 1 / distance)); + } + if (vector_length_squared(toward) < BIRD_CAGE_WAVE_STILL) toward = random_direction(); + float angle = vector_angle(toward); + bird_cage_wave(cage, angle); + for (int i = 0; cage.player->HasCollectible(COLLECTIBLE_BFFS) && i < BIRD_CAGE_BFFS_WAVES; i++) + bird_cage_wave(cage, angle += RIGHT_ANGLE_DEGREES); + + for (int i = 0; i < BIRD_CAGE_DEBRIS; i++) + { + Vector direction = vector_from_angle(random_unit() * FULL_TURN_DEGREES); + Vector spot = vector_add(cage.pos, vector_scale(direction, random_unit() * BIRD_CAGE_DEBRIS_SPREAD)); + g_game->Spawn({.position = spot, + .velocity = vector_scale(direction, BIRD_CAGE_DEBRIS_SPEED), + .type = ENTITY_EFFECT, + .variant = EFFECT_ROCK_PARTICLE, + .seed = Random()}) + ->Update(); + } + game_shake_screen(BIRD_CAGE_SHAKE); +} + +// 006424d0 The bird cage: perched, it jumps at an enemy and crashes down on it (keeping up with it while it is near), +// then flies as a bird. Without an enemy it flies straight away. +void Entity_Familiar::ai_bird_cage() +{ + ANM2& look = sprite; + switch (state) + { + case BIRD_CAGE_PERCHED: + PickEnemyTarget(BIRD_CAGE_JUMP_SEARCH); + if (target) + { + targetPosition = target->pos; + look.Play("JumpUp", PLAY_FORCED); + state = BIRD_CAGE_JUMPING; + return; + } + look.Play("Flying"); + state = BIRD_CAGE_FLYING; + return; + case BIRD_CAGE_JUMPING: + if (!look.IsPlaying()) + { + look.Play("JumpDown"); + state = BIRD_CAGE_FALLING; + } + if (target && !target->isDead) targetPosition = target->pos; + break; + case BIRD_CAGE_FALLING: + pos = targetPosition; + if (look.IsEventTriggered("Hit")) bird_cage_land(*this); + else if (!look.IsPlaying()) + { + look.Play("Flying"); + state = BIRD_CAGE_FLYING; + } + if (target && !target->isDead && vector_length_squared(vector_sub(target->pos, targetPosition)) < BIRD_CAGE_FOLLOW_SQUARED) + targetPosition = target->pos; + break; + case BIRD_CAGE_FLYING: return ai_flying_bird(); + default: return; + } + if (target && target->isDead) target = nullptr; + velocity = {}; +} + +// Worm Friend: how far it hunts, how far it strays from the player with nothing to hunt, how it leads its prey, how +// close it grabs from, how long it holds (less a player in versus) and rests after, its grip's slowing, how often it +// bites, and its drag above ground and below. +constexpr TargetSearch WORM_FRIEND_SEARCH = {.range = 365, .frameInterval = 13, .flags = TARGET_PREFER_HEALTHY}; +constexpr float WORM_FRIEND_LEASH_SQUARED = 6400; +constexpr float WORM_FRIEND_LEAD = 0.1f; +constexpr float WORM_FRIEND_STEER = 5; +constexpr float WORM_FRIEND_GRAB_SQUARED = 900; +constexpr int WORM_FRIEND_HOLD_FRAMES = 150; +constexpr int WORM_FRIEND_VERSUS_HOLD_FRAMES = 45; +constexpr int WORM_FRIEND_REST_FRAMES = 90; +constexpr int WORM_FRIEND_SNARE_STATE = 2; +constexpr int WORM_FRIEND_SNARE_DEPTH = 200; +constexpr float WORM_FRIEND_MISS_FRAME = 10; +constexpr float WORM_FRIEND_SLOWING = 0.9f; +constexpr ColorMod WORM_FRIEND_SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {0.15686275f, 0.15686275f, 0.15686275f}}; +constexpr int WORM_FRIEND_BITE_INTERVAL = 15; +constexpr int WORM_FRIEND_BITE_COUNTDOWN = 30; +constexpr float WORM_FRIEND_DRAG = 0.9f; +constexpr float WORM_FRIEND_HOLD_DRAG = 0.5f; +constexpr int WORM_FRIEND_HIDDEN_LAYER = 2; +constexpr int WORM_FRIEND_DEPTH = -100; + +// Worm Friend's states: burrowing, holding its prey, and letting go. +enum WormFriendState +{ + WORM_FRIEND_BURROWING, + WORM_FRIEND_HOLDING, + WORM_FRIEND_RELEASING +}; + +// Part of 0060de70: Worm Friend starts hidden underground, its grab finished. +void worm_friend_init(Entity_Familiar& worm) +{ + worm.isVisible = false; + worm.sprite.GetLayer(WORM_FRIEND_HIDDEN_LAYER)->isVisible = false; + worm.sprite.Play("GrabEnd"); + worm.sprite.SetLastFrame(); + worm.renderZOffset = WORM_FRIEND_DEPTH; +} + +// Part of 0064bfa0: burrowing Worm Friend tunnels toward where its prey is heading (else back near the player), and +// bursts out to grab it once close. +static void worm_friend_tunnel(Entity_Familiar& worm) +{ + Entity* prey = worm.target.get(); + if (!prey) + { + Vector toward = vector_sub(worm.player->pos, worm.pos); + if (vector_length_squared(toward) > WORM_FRIEND_LEASH_SQUARED) + worm.velocity = vector_add(worm.velocity, vector_scale(vector_normalized(toward), worm.speedMultiplier)); + return; + } + + float lead = vector_distance(worm.pos, prey->pos) * WORM_FRIEND_LEAD; + Vector toward = vector_sub(vector_add(prey->pos, vector_scale(prey->velocity, lead)), worm.pos); + Vector steer = vector_add(toward, vector_scale(vector_sub(prey->velocity, worm.velocity), WORM_FRIEND_STEER)); + worm.velocity = vector_add(worm.velocity, vector_scale(vector_normalized(steer), worm.speedMultiplier)); + if (worm.isVisible || vector_length_squared(toward) >= WORM_FRIEND_GRAB_SQUARED) return; + + if (worm.child) worm.child->Remove(); + worm.child = nullptr; + worm.UpdateDirtColor(); + worm.sprite.Play("Grab", PLAY_FORCED); + worm.isVisible = true; + familiar_sound_play(SOUND_MEAT_JUMPS); + bool isPlayerPrey = familiar_versus() && prey->type == ENTITY_PLAYER; + worm.fireCooldown = isPlayerPrey ? WORM_FRIEND_VERSUS_HOLD_FRAMES : WORM_FRIEND_HOLD_FRAMES; +} + +// Part of 0064bfa0: Worm Friend's grab lands on its Shoot event, snaring its prey when close enough, else it sinks +// back. The second Shoot lets go. +static void worm_friend_snap(Entity_Familiar& worm) +{ + if (worm.state == WORM_FRIEND_BURROWING) + { + Entity* prey = worm.target.get(); + if (prey && vector_length_squared(vector_sub(worm.pos, prey->pos)) < WORM_FRIEND_GRAB_SQUARED) + { + auto* snare = static_cast(g_game->Spawn({.position = worm.pos, + .spawner = &worm, + .type = ENTITY_EFFECT, + .variant = EFFECT_WORM_FRIEND_SNARE, + .seed = Random()})); + snare->parent = &worm; + snare->state = WORM_FRIEND_SNARE_STATE; + snare->renderZOffset = WORM_FRIEND_SNARE_DEPTH; + worm.child = snare; + snare->Update(); + worm.state = WORM_FRIEND_HOLDING; + worm.targetPosition = worm.pos; + return; + } + if (worm.child) worm.child->Remove(); + worm.child = nullptr; + worm.sprite.Play("GrabEnd"); + worm.sprite.SetFrame(WORM_FRIEND_MISS_FRAME); + worm.targetPosition = {}; + } + else if (worm.state == WORM_FRIEND_HOLDING) worm.state = WORM_FRIEND_RELEASING; + else return; + familiar_sound_play(SOUND_MAGGOT_ENTER_GROUND); +} + +// 0064bfa0 (FamiliarAI::worm_friend) Worm Friend tunnels after an enemy, bursts out and holds it in place, slowed and +// bitten every so often, then lets go and burrows again after a rest. +void worm_friend_update(Entity_Familiar& worm) +{ + ANM2& look = worm.sprite; + if (worm.fireCooldown == 0 && !worm.isVisible) worm.PickEnemyTarget(WORM_FRIEND_SEARCH); + if (vector_is_zero(worm.targetPosition)) worm_friend_tunnel(worm); + else worm.velocity = vector_sub(worm.targetPosition, worm.pos); + if (look.IsEventTriggered("Shoot")) worm_friend_snap(worm); + + Entity* prey = worm.target.get(); + if (worm.state == WORM_FRIEND_HOLDING && (!prey || prey->entityCollisionClass == ENTCOLL_NONE || worm.fireCooldown < 1)) + look.Play("GrabEnd"); + if (worm.isVisible && !look.IsPlaying()) + { + if (worm.state == WORM_FRIEND_HOLDING) look.Play("GrabLoop"); + else + { + worm.fireCooldown = WORM_FRIEND_REST_FRAMES; + worm.state = WORM_FRIEND_BURROWING; + worm.isVisible = false; + worm.targetPosition = {}; + worm.target = nullptr; + } + } + if (worm.fireCooldown > 0) worm.fireCooldown--; + worm.entityCollisionClass = ENTCOLL_NONE; + if (worm.state == WORM_FRIEND_BURROWING) + { + worm.velocity = vector_scale(worm.velocity, WORM_FRIEND_DRAG); + return; + } + + worm.velocity = vector_scale(worm.velocity, WORM_FRIEND_HOLD_DRAG); + prey = worm.target.get(); + if (worm.state != WORM_FRIEND_HOLDING || !prey) return; + + prey->velocity = vector_sub(worm.pos, prey->pos); + prey->AddSlowing(EntityRef(&worm), -1, WORM_FRIEND_SLOWING, WORM_FRIEND_SLOW_COLOR, false); + if (worm.fireCooldown > 0 && worm.fireCooldown % WORM_FRIEND_BITE_INTERVAL == 0) + prey->TakeDamage(worm.GetMultiplier() * worm.collisionDamage, 0, EntityRef(&worm), WORM_FRIEND_BITE_COUNTDOWN); +} + +// The Lil Harbingers (7 Seals): their five looks (War, Pestilence, Famine, Death, Conquest), the damage each hits +// with, how fast each flies and how often each sends locusts (Conquest two), the creep Pestilence and Famine leave, +// how near counts as there, and how long each keeps its look. +constexpr std::string_view HARBINGER_SHEETS[] = { + "gfx/familiar/familiar_122_miniwar.png", "gfx/familiar/familiar_122_minipestilence.png", + "gfx/familiar/familiar_122_minifamine.png", "gfx/familiar/familiar_122_minideath.png", + "gfx/familiar/familiar_122_miniconquest.png"}; +constexpr float HARBINGER_DAMAGE[] = {1.5f, 0.5f, 0.5f, 1.5f, 0.5f}; +constexpr float HARBINGER_SPEED[] = {2.5f, 2, 2, 1.5f, 2}; +constexpr int HARBINGER_LOCUST_FRAMES[] = {150, 90, 90, 90, 60}; +constexpr int HARBINGER_LAST = HARBINGER_KINDS - 1; +constexpr int HARBINGER_LOOK_FRAMES = 300; +constexpr float HARBINGER_PULL = 2; +constexpr float HARBINGER_THERE_SQUARED = 25; +constexpr int HARBINGER_SEEK_INTERVAL = 3; +constexpr int HARBINGER_CREEP_INTERVAL = 12; +constexpr int HARBINGER_CREEP_FRAMES = 120; + +// The harbingers by subtype. +enum HarbingerKind +{ + HARBINGER_WAR, + HARBINGER_PESTILENCE, + HARBINGER_FAMINE, + HARBINGER_DEATH, + HARBINGER_CONQUEST +}; + +// The kind a harbinger's subtype stands for, logging one past Conquest (which counts as Conquest). +static int harbinger_kind(Entity_Familiar& harbinger) +{ + if ((uint32_t)harbinger.subtype > HARBINGER_LAST) + { + std::string message = std::format("[err] Wrong Harbinger subtype {}!\n", (uint32_t)harbinger.subtype); + KAGE_LogMessage(LOG_ASSERT, (uint8_t*)message.data()); + } + return (int)std::min((uint32_t)harbinger.subtype, (uint32_t)HARBINGER_LAST); +} + +// 006322f0 A Lil Harbinger takes its kind's look and damage. +void Entity_Familiar::init_lil_harbinger_sprite() +{ + subtype = harbinger_kind(*this); + for (int i = 0; i < (int)sprite.layerStates.size(); i++) sprite.ReplaceSpritesheet(i, HARBINGER_SHEETS[subtype]); + sprite.LoadGraphics(); + sprite.Play("FloatDown"); + collisionDamage = HARBINGER_DAMAGE[subtype]; +} + +// Part of 006378c0: War and Death chase the nearest enemy (or wander), now and then looking around again. +static void harbinger_seek(Entity_Familiar& harbinger) +{ + if (vector_length_squared(vector_sub(harbinger.pos, harbinger.targetPosition)) < HARBINGER_THERE_SQUARED) + harbinger.velocity = {}; + Game& game = *g_game; + if (harbinger.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || game.IsPaused() || + (game.frameCount + harbinger.index) % HARBINGER_SEEK_INTERVAL != 0) + return; + + Entity* nearest = nullptr; + float nearestSquared = 0; + for (Entity* enemy : game.room->entityList.updateEL) + { + bool isFoe = (familiar_versus() && enemy->type == ENTITY_PLAYER) || Entity::is_enemy_type(enemy->type); + bool isTargetable = !enemy->HasEntityFlags(FLAG_NO_TARGET) || enemy->type == ENTITY_BLOOD_PUPPY || + enemy->type == ENTITY_DARK_ESAU; + if (!isFoe || enemy->entityCollisionClass <= ENTCOLL_PLAYERONLY || enemy->isInvincible || enemy->isDead || + !isTargetable) + continue; + + float squared = vector_length_squared(vector_sub(enemy->pos, harbinger.pos)); + if (nearest && squared >= nearestSquared) continue; + + nearest = enemy; + nearestSquared = squared; + } + if (nearest) harbinger.targetPosition = nearest->pos; + else if (vector_length_squared(vector_sub(harbinger.pos, harbinger.targetPosition)) < HARBINGER_THERE_SQUARED) + harbinger.targetPosition = game.room->GetRandomPosition(harbinger.size); +} + +// Part of 006378c0: Pestilence and Famine wander the room, leaving their creep while it is not yet cleared. +static void harbinger_wander(Entity_Familiar& harbinger) +{ + Room& room = *g_game->room; + if (vector_length_squared(vector_sub(harbinger.pos, harbinger.targetPosition)) < HARBINGER_THERE_SQUARED) + harbinger.targetPosition = room.GetRandomPosition(harbinger.size); + bool isCreeping = harbinger.subtype == HARBINGER_PESTILENCE || harbinger.subtype == HARBINGER_FAMINE; + if (!isCreeping || !harbinger.IsFrame(HARBINGER_CREEP_INTERVAL, (int)harbinger.index) || + (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR)) + return; + + int creepVariant = harbinger.subtype == HARBINGER_PESTILENCE ? EFFECT_PLAYER_CREEP_GREEN : EFFECT_PLAYER_CREEP_BLACK; + auto* creep = static_cast(g_game->Spawn( + {.position = harbinger.pos, .spawner = harbinger.player, .type = ENTITY_EFFECT, .variant = creepVariant, .seed = Random()})); + creep->timeout = HARBINGER_CREEP_FRAMES; + creep->lifespan = HARBINGER_CREEP_FRAMES; + creep->damageSource = 1; +} + +// 006378c0 A Lil Harbinger flies about the room (War and Death after the nearest enemy, Pestilence and Famine leaving +// creep) and now and then sends a locust of its kind (Conquest two), changing kind every 300 frames. +void Entity_Familiar::ai_lil_harbingers() +{ + if (state > HARBINGER_LOOK_FRAMES) + { + subtype = (int)(dropRNG.Next() % HARBINGER_KINDS); + targetPosition = {}; + init_lil_harbinger_sprite(); + g_game->Spawn({.position = pos, .spawner = this, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()})->Update(); + state = 0; + } + if (vector_is_zero(targetPosition)) targetPosition = g_game->room->GetRandomPosition(size); + state++; + velocity = vector_add(velocity, vector_resized(vector_sub(targetPosition, pos), HARBINGER_PULL)); + if (subtype == HARBINGER_WAR || subtype == HARBINGER_DEATH) harbinger_seek(*this); + else harbinger_wander(*this); + + int kind = harbinger_kind(*this); + if (vector_length(velocity) > HARBINGER_SPEED[kind]) velocity = vector_resized(velocity, HARBINGER_SPEED[kind]); + if (++fireCooldown >= HARBINGER_LOCUST_FRAMES[kind] && !linkedEntity) + { + fireCooldown = 0; + int locusts = subtype == HARBINGER_CONQUEST ? 2 : 1; + Entity* locust = nullptr; + for (int i = 0; i < locusts; i++) + locust = g_game->Spawn({.position = pos, .spawner = player, .subType = subtype + 1, .type = ENTITY_FAMILIAR, + .variant = BLUE_FLY, .seed = Random()}); + sprite.Play("PreSpawn", PLAY_FORCED); + linkedEntity = locust; + shot_owner_convert(linkedEntity.get()); + } + if (sprite.animState.animData && !sprite.animState.isPlaying && sprite.animState.animData->name == "PreSpawn") + sprite.Play("FloatDown"); + if (std::fabs(velocity.x) > 0) sprite.isFlipX = velocity.x < 0; +} + +// Damocles: its idle looks (the rare third one time in ten, the second four times in ten), how often it may fall and +// the chance (in ten thousand) its subtype holds, the hit it deals the player, and the gore of its fall: three bursts +// around the player, each of a few blood particles flying slow and the rest flung as gibs, then the sword left behind. +constexpr float DAMOCLES_RARE_IDLE = 0.1f; +constexpr float DAMOCLES_SECOND_IDLE = 0.5f; +constexpr int DAMOCLES_FALL_INTERVAL = 4; +constexpr uint32_t DAMOCLES_FALL_ODDS = 10000; +constexpr uint64_t DAMOCLES_DAMAGE_FLAGS = 0x2002800; +constexpr int DAMOCLES_DAMAGE_COUNTDOWN = 30; +constexpr int DAMOCLES_BLOOD_SUBTYPE = 3; +constexpr int DAMOCLES_BURSTS = 3; +constexpr float DAMOCLES_BURST_SPEED_MIN = 6; +constexpr float DAMOCLES_BURST_SPEED_RANGE = 15; +constexpr int DAMOCLES_GIBS_MIN = 5; +constexpr uint32_t DAMOCLES_GIBS_RANGE = 6; +constexpr float DAMOCLES_GIB_SPREAD = 10; +constexpr float DAMOCLES_SLOW_SPEED = 0.2f; +constexpr int DAMOCLES_GIB_SUBTYPE = 99; +constexpr float DAMOCLES_GIB_LIFT = -8; +constexpr int DAMOCLES_SWORD_STATE = 1; + +// Damocles' states: hanging up, swaying, and falling. +enum DamoclesState +{ + DAMOCLES_UP, + DAMOCLES_HANGING, + DAMOCLES_FALLING +}; + +// Part of 00644e80: a burst of the player's blood around them, a few particles drifting and the rest flung as gibs. +static void damocles_burst(Entity_Player& player) +{ + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float speed = random_unit() * DAMOCLES_BURST_SPEED_RANGE + DAMOCLES_BURST_SPEED_MIN; + Vector burst = vector_scale(vector_make(std::cos(angle), std::sin(angle)), speed); + uint32_t roll = Random(); + int drifting = (int)(roll & 1) + 1; + int count = (int)(roll & 1) + DAMOCLES_GIBS_MIN + (int)(Random() % DAMOCLES_GIBS_RANGE); + for (int i = 0; i < count; i++) + { + Vector turned = vector_rotated(burst, random_unit() * DAMOCLES_GIB_SPREAD - DAMOCLES_GIB_SPREAD * HALF); + Vector velocity = vector_scale(turned, random_unit()); + Vector spot = vector_add(player.pos, velocity); + uint32_t seed = Random(); + if (i < drifting) + { + g_game->Spawn({.position = spot, .velocity = vector_scale(velocity, DAMOCLES_SLOW_SPEED), .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_PARTICLE, .seed = seed}) + ->Update(); + continue; + } + auto* gib = static_cast(g_game->Spawn({.position = spot, .velocity = velocity, .subType = DAMOCLES_GIB_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_PARTICLE, .seed = seed})); + gib->Update(); + gib->fallingSpeed = DAMOCLES_GIB_LIFT; + } +} + +// Part of 00644e80: Damocles falls, killing the player (unless invincible) in a shower of gore, and leaves its sword. +static void damocles_fall(Entity_Familiar& damocles) +{ + if (!damocles.sprite.IsEventTriggered("Hit")) return; + + Entity_Player& player = *damocles.player; + familiar_sound_play(SOUND_MEATY_DEATHS); + player.damageCooldown = 0; + if (!player.HasInvincibility(0, EntityRef())) + { + player.TakeDamage(1, DAMOCLES_DAMAGE_FLAGS, EntityRef(&damocles), DAMOCLES_DAMAGE_COUNTDOWN); + player.Kill(EntityRef()); + g_game->Spawn({.position = player.pos, .subType = DAMOCLES_BLOOD_SUBTYPE, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + for (int i = 0; i < DAMOCLES_BURSTS; i++) damocles_burst(player); + } + auto* sword = static_cast( + g_game->Spawn({.position = damocles.pos, .type = ENTITY_EFFECT, .variant = EFFECT_DEVIL, .seed = Random()})); + std::swap(sword->sprite, damocles.sprite); + sword->state = DAMOCLES_SWORD_STATE; + sword->Update(); + player.RemoveCollectible(COLLECTIBLE_DAMOCLES_PASSIVE, false, 0, true); + damocles.Remove(); +} + +// 00644e80 Damocles hangs over the player, swaying, and every fourth frame may fall (its subtype the chance in ten +// thousand). Between frames it only keeps over the player. +void Entity_Familiar::ai_shadow_intruder_damocles(bool isInterpolating) +{ + pos = player->pos; + velocity = {}; + if (isInterpolating) return; + + if (state == DAMOCLES_UP) + { + state = DAMOCLES_HANGING; + fireCooldown = 0; + return sprite.Play("Idle"); + } + if (state == DAMOCLES_FALLING) + { + sprite.Play("Fall"); + return damocles_fall(*this); + } + if (state != DAMOCLES_HANGING) return; + + if (!sprite.IsPlaying()) + { + float roll = random_unit(); + sprite.Play(roll < DAMOCLES_RARE_IDLE ? "Idle3" : roll < DAMOCLES_SECOND_IDLE ? "Idle2" : "Idle", PLAY_FORCED); + } + if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused() || g_game->frameCount % DAMOCLES_FALL_INTERVAL != 0 || + subtype < 1) + return; + if ((int)(Random() % DAMOCLES_FALL_ODDS) >= subtype) return; + + familiar_sound_play(SOUND_THREAD_SNAP, {.frameDelay = 0}); + state = DAMOCLES_FALLING; +} + +// 00650610 (FamiliarAI::vanishing_twin) The Vanishing Twin follows the player, hidden while its twin lives. Without a +// boss to copy (its coins hold the boss's type) it only follows. Copying the floor's boss stops the game. +void vanishing_twin_update(Entity_Familiar& twin) +{ + twin.entityCollisionClass = ENTCOLL_NONE; + if (twin.state == 1) + { + twin.isVisible = false; + return; + } + if (twin.coins != 0) return reconstruction_missing("FamiliarAI::vanishing_twin 00650610 (the twin of a boss)"); + + twin.sprite.Play("Idle"); + twin.FollowParent(); + twin.isVisible = true; + twin.targetPosition = {}; + twin.state = 0; + twin.fireCooldown = 0; +} diff --git a/src/familiar_variants.cpp b/src/familiar_variants.cpp index 2c09021..3eefb9b 100644 --- a/src/familiar_variants.cpp +++ b/src/familiar_variants.cpp @@ -1029,7 +1029,7 @@ static void stitches_belial_cut(Entity_Familiar& stitches, float damage) { Vector along = vector_scale(toPlayer, 1 / length); bool isVersus = familiar_versus(); - for (Entity* entity : g_game->room->entityList.updateEL) + for (Entity* entity : entities_live(g_game->room->entityList.updateEL)) { if (!entity || entity->entityCollisionClass == ENTCOLL_NONE || entity->IsFriendly()) continue; bool isTarget = (isVersus && entity->type == ENTITY_PLAYER) || diff --git a/src/fx_layers.cpp b/src/fx_layers.cpp index 3a383e2..2fc8c59 100644 --- a/src/fx_layers.cpp +++ b/src/fx_layers.cpp @@ -35,9 +35,6 @@ constexpr uint32_t DELETE_THIS_RNG_SHIFT = 14; // The color an image draw takes to keep its quad's own colors. constexpr KColor COLOR_UNSET = kcolor_rgba(-1, -1, -1, -1); -constexpr int FILTER_LINEAR = 1; -constexpr int WRAP_CLAMP = 1; -constexpr int WRAP_REPEAT = 0; // fxlayers.xml numbers stages by chapter: 1 to 4 the chapters' first floors, then Blue Womb (5) and on. constexpr int CHAPTER_LAST = 4; diff --git a/src/fx_layers.h b/src/fx_layers.h index 79cb757..fb5ed00 100644 --- a/src/fx_layers.h +++ b/src/fx_layers.h @@ -63,6 +63,8 @@ constexpr uint32_t WHITE_ARGB = 0xffffffff; constexpr uint32_t BLACK_ARGB = 0xff000000; constexpr uint32_t CLEAR_ARGB = 0; constexpr uint32_t TEXT_ARGB = 0xff362f2d; +// A sprite drawn solid white: its own color dropped and white added. +constexpr ColorMod SOLID_WHITE = {{0, 0, 0, 1}, {0, 0, 0, 0}, {1, 1, 1}}; // Construction (0098f720), assignment (009937b0) and destruction are the defaults. // How a stage's rooms look (REPENTOGON's FXParams), from fxlayers.xml's fxParams: the color grading, water and shadows. diff --git a/src/game.cpp b/src/game.cpp index 678f734..93488f1 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -34,8 +34,6 @@ constexpr const char* OLD_TV_SURFACE = "Old TV Surface"; constexpr const char* HALLUCINATION_SURFACE = "Hallucination Surface"; constexpr const char* HALLUCINATION_SNAPSHOT = "Hallucination Snapshot"; constexpr const char* COLORMOD_SURFACE = "Colormod Surface"; -constexpr int FILTER_NEAREST = 0; -constexpr int FILTER_LINEAR = 1; constexpr int BLOOM_DURATION_DEFAULT = 30; constexpr int REVIVE_MACHINE_COINS = 10; @@ -46,7 +44,6 @@ constexpr float COLOR_CHANNEL_MAX = 255; constexpr std::array TINT_ATTRIBUTES = {"r", "g", "b", "a"}; // The fortune generator's xorshift (shift index 35), the start's fade in speed, and the cover an instant fade starts on. -constexpr uint32_t FORTUNE_RNG_SHIFT = 35; constexpr float START_FADE_SPEED = 0.04f; constexpr float FADE_IN_ALPHA_INSTANT = 1e-05f; @@ -473,7 +470,7 @@ void Game::Start(int playerType, uint32_t startChallenge, const Seeds& seeds, Di seedEffects.ClearSeedEffects(); for (int effect : GetChallengeParams().seedEffects) seedEffects.AddSeedEffect(effect); } - fortuneRNG.SetSeed(seedEffects.GetNextSeed(), FORTUNE_RNG_SHIFT); + fortuneRNG.SetSeed(seedEffects.GetNextSeed(), DEFAULT_SHIFT_INDEX); bool isReadOnly = seedEffects.isCustomRun || seedEffects.AchievementUnlocksDisallowed() || Manager::AchievementUnlocksDisallowed() || isRerun || challenge != 0; @@ -550,8 +547,6 @@ constexpr float PIXELATION_MIN = 0.0001f; constexpr float BLOOM_RATIO = 2; constexpr float OLD_TV_TIME_SCALE = 0.05f; constexpr float ASCENT_FADE_FRAMES = 90; -constexpr uint32_t DEBUG_FLAG_PLAYER_INFO = 1 << 11; -constexpr uint32_t DEBUG_FLAG_LUA_MEMORY = 1 << 13; constexpr float PI = std::numbers::pi_v; // Draws a whole surface over the screen in a color. @@ -776,9 +771,9 @@ static void effects_resolve(Game& game, bool isRoomSnapshot, bool isOldTv) else if (game.fadeOutColor._alpha > 0) render_color_shader_pass(KAGE::Graphics::color_quad_rect({}, screen, game.fadeOutColor)); - if (game.debugFlags & DEBUG_FLAG_PLAYER_INFO && !game.playerManager.playerList.empty()) + if (game.debugFlags & DEBUG_PLAYER_INFO && !game.playerManager.playerList.empty()) reconstruction_missing("Game::Render 006fbc10: the player debug info"); - if (game.debugFlags & DEBUG_FLAG_LUA_MEMORY) reconstruction_missing("render_debug_lua_memory 00872090"); + if (game.debugFlags & DEBUG_LUA_MEMORY) reconstruction_missing("render_debug_lua_memory 00872090"); } // 006fbc10 Draws the run's frame. The room, or the room transition, draws through the effect surfaces that are on (old diff --git a/src/game.h b/src/game.h index 81f7cbf..686d2d1 100644 --- a/src/game.h +++ b/src/game.h @@ -61,6 +61,24 @@ enum Difficulty : uint32_t DIFFICULTY_GREEDIER }; +// The console's debug flags (debugFlags), by bit: "debug N" toggles bit N - 1. +enum DebugFlag : uint32_t +{ + DEBUG_ENTITY_POSITIONS = 1u << 0, + DEBUG_GRID_VALUES = 1u << 1, + DEBUG_INFINITE_HP = 1u << 2, + DEBUG_HIGH_DAMAGE = 1u << 3, + DEBUG_ROOM_INFO = 1u << 4, + DEBUG_HITSPHERES = 1u << 5, + DEBUG_DAMAGE_VALUES = 1u << 6, + DEBUG_HIGH_LUCK = 1u << 8, + DEBUG_QUICK_KILL = 1u << 9, + DEBUG_GRID_INDICES = 1u << 10, + DEBUG_PLAYER_INFO = 1u << 11, + DEBUG_GRID_COLLISION = 1u << 12, + DEBUG_LUA_MEMORY = 1u << 13 +}; + // The run's state flags (Lua's GameStateFlag) the curated code reads, by bit. enum GameStateFlag : int { @@ -295,6 +313,7 @@ public: bool isDebug = false; bool isFadeInIconShown = false; bool isInstantFadeIn = false; + bool isLilPortalOpened = false; bool isPocketItemRewindSaved = false; bool isRerun = false; bool isRestoringGlowingHourglassState = false; diff --git a/src/game_end.cpp b/src/game_end.cpp index b96b0d0..82459fe 100644 --- a/src/game_end.cpp +++ b/src/game_end.cpp @@ -17,7 +17,6 @@ // The cutscene each ending plays, none for a death. Mom's Heart's first eleven kills each play the next of the Womb's // endings (cutscenes 4 to 14), any later one the credits. constexpr std::array ENDING_CUTSCENES = {0, 0, 3, 0, 15, 16, 18, 17, 19, 21, 20, 22, 23, 24, 26}; -constexpr int CUTSCENE_CREDITS = 2; constexpr int WOMB_ENDINGS = 11; constexpr int WOMB_ENDING_BEFORE_FIRST = 3; diff --git a/src/game_over.cpp b/src/game_over.cpp index 242ff1b..fedacda 100644 --- a/src/game_over.cpp +++ b/src/game_over.cpp @@ -43,8 +43,6 @@ 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; -constexpr size_t SEED_HALF_LENGTH = 4; -constexpr size_t SEED_SECOND_HALF = 5; constexpr uint32_t SEED_COLOR_ARGB = 0xff362f2d; constexpr float SHADE_ALPHA = 128 / 255.0f; @@ -54,15 +52,12 @@ constexpr int LOCATION_FRAME_DEFAULT = 4; constexpr int LOCATION_FRAME_ALT = 7; constexpr int LOCATION_FRAME_ASCENT = 12; constexpr int LOCATION_ALT_LAST_STAGE = 8; -constexpr int ASCENT_LAST_STAGE = 6; constexpr int GREED_STAGE_SHOP = 5; constexpr int GREED_SHOP_LOCATION = 10; constexpr int PORTRAIT_UNKNOWN = 149; constexpr int PORTRAIT_BOMB = 65; -constexpr uint64_t DAMAGE_TIMER = 1ull << 17; - // 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}}; constexpr std::pair DAMAGE_PORTRAITS[] = { diff --git a/src/game_restore.cpp b/src/game_restore.cpp index a79a4be..9846b97 100644 --- a/src/game_restore.cpp +++ b/src/game_restore.cpp @@ -19,9 +19,6 @@ constexpr uint32_t ROOM_REF_HALF_MASK = 0xffff; constexpr uint32_t ROOM_REF_MODE_MASK = 0xff; constexpr uint32_t PLAYER_RNG_SHIFT = 34; -constexpr uint32_t FORTUNE_RNG_SHIFT = 35; -constexpr uint32_t ITEM_RNG_SHIFT = 35; -constexpr uint32_t GLITCH_BABY_SHIFT = 35; constexpr uint32_t ITEM_POOL_SHIFT = 3; constexpr uint32_t DEVIL_ANGEL_SHIFT = 2; constexpr uint8_t HOLY_MANTLE_SAVED = 2; @@ -149,7 +146,7 @@ void Game::restore_game_state(GameState& state, GameRestore restore) playerManager.init_main_player(playerType, seedEffects.playerInitSeed); itemPool.Init(state.itemPool.seed, manager.modManager.TryRedirectPath(ITEM_POOLS_XML)); bossPool.init(seedEffects.GetStartSeed()); - fortuneRNG.SetSeed(state.fortuneSeed, FORTUNE_RNG_SHIFT); + fortuneRNG.SetSeed(state.fortuneSeed, DEFAULT_SHIFT_INDEX); uint32_t startSeed = seedEffects.GetStartSeed(); std::string seedText = Seeds::Seed2String(seedEffects.GetStartSeed()); @@ -161,7 +158,7 @@ void Game::restore_game_state(GameState& state, GameRestore restore) } playerManager.rng.SetSeed(state.playerManagerSeed, PLAYER_RNG_SHIFT); - fortuneRNG.SetSeed(state.fortuneSeed, FORTUNE_RNG_SHIFT); + fortuneRNG.SetSeed(state.fortuneSeed, DEFAULT_SHIFT_INDEX); itemPool.RestoreGameState(state.itemPool); bossPool.restore_game_state(state.bossPool); proceduralItemManager.items_restore(state.proceduralItemSeeds); @@ -402,7 +399,7 @@ void PlayerManager::RestoreGameState(GameState& state) if (!state.players.empty()) { GameStatePlayer& first = state.players.front(); - glitchBabyRng.SetSeed((uint32_t)first.glitchBabySeed, GLITCH_BABY_SHIFT); + glitchBabyRng.SetSeed((uint32_t)first.glitchBabySeed, DEFAULT_SHIFT_INDEX); randomBabyCount = first.randomBabyCount; randomBabies = first.randomBabies; } @@ -479,7 +476,7 @@ static void co_player_restore(Entity_Player& player, const CoPlayerState& saved) static void rng_seeds_restore(std::vector& rngs, const std::vector& seeds, size_t configCount) { for (size_t i = 0; i < std::min({rngs.size(), seeds.size(), configCount}); i++) - rngs[i].SetSeed(seeds[i], ITEM_RNG_SHIFT); + rngs[i].SetSeed(seeds[i], DEFAULT_SHIFT_INDEX); } // 007ae4b0 Restores a player from its save: its controller (and character, rewinding), its name, collectible counts, diff --git a/src/game_transition.cpp b/src/game_transition.cpp index 41490dc..01d0ea2 100644 --- a/src/game_transition.cpp +++ b/src/game_transition.cpp @@ -19,7 +19,6 @@ constexpr int ROOM_INDEX_MAX = LEVEL_GRID_CELLS - 1; constexpr int DIMENSION_MAX = 2; constexpr int DOOR_SIDES = 4; constexpr int SIDE_ACROSS = 2; -constexpr int MINESHAFT_ENTRANCE_SUBTYPE = 10; constexpr int MAZE_MOVE_CHANCE = 10; constexpr int MAZE_SWAP_CHANCE = 5; constexpr int MAZE_SHAKE_FRAMES = 30; @@ -39,8 +38,6 @@ constexpr int BLUE_ROOM_DIFFICULTY_MAX = 10; constexpr RNG BLUE_ROOM_RNG = {0, 5, 27, 28}; // The room indices the players leave without becoming the room they came from: the ones off the map that only lead on. -constexpr int ROOM_PASSAGE_IDX = -14; -constexpr int ROOM_PASSAGE_EXIT_IDX = -15; // Whether a room type hides behind a secret door. static bool is_secret_type(int type) @@ -410,10 +407,10 @@ void Level::ChangeRoom(int targetRoomIdx, int dimension) int previousIdx = lastRoomIdx; bool isOldKept = oldRoomIdx >= 0 || oldRoomIdx == ROOM_DUNGEON_IDX || oldRoomIdx == ROOM_DEBUG_IDX || oldRoomIdx == ROOM_GIDEON_DUNGEON_IDX || oldRoomIdx == ROOM_SECRET_SHOP_IDX; - bool isOldPassage = oldRoomIdx == ROOM_PASSAGE_IDX || oldRoomIdx == ROOM_PASSAGE_EXIT_IDX; + bool isOldPassage = oldRoomIdx == ROOM_ROTGUT_DUNGEON1_IDX || oldRoomIdx == ROOM_ROTGUT_DUNGEON2_IDX; if (newRoomIdx >= 0 ? !isOldPassage : isOldKept) lastRoomIdx = oldRoomIdx; - if (newRoomIdx == ROOM_PASSAGE_IDX) lastRoomIdx = previousIdx; + if (newRoomIdx == ROOM_ROTGUT_DUNGEON1_IDX) lastRoomIdx = previousIdx; currentDimensionIdx = dimension; currentRoomIdx = newRoomIdx; currentRoomMap = &roomMap[dimension * LEVEL_GRID_CELLS]; diff --git a/src/game_update.cpp b/src/game_update.cpp index ee0b596..5f58b43 100644 --- a/src/game_update.cpp +++ b/src/game_update.cpp @@ -32,7 +32,6 @@ constexpr int ASCENT_SHAKE_BASE = 2; constexpr int DEATH_CERTIFICATE_SHAKE = 10; constexpr int HUD_REFRESH_INTERVAL = 30; constexpr uint64_t FADE_IN_ICON_MS = 3000; -constexpr uint64_t NS_PER_MS = 1000000; // The room's render surface, its size and margin, centered on the screen. constexpr float ROOM_SURFACE_WIDTH = 338; constexpr float ROOM_SURFACE_HEIGHT = 182; diff --git a/src/generic_prompt.cpp b/src/generic_prompt.cpp index cc0f77f..60c4c02 100644 --- a/src/generic_prompt.cpp +++ b/src/generic_prompt.cpp @@ -42,7 +42,6 @@ constexpr float DISCLAIMER_WIDTH = 0.9f; constexpr uint64_t CHOICES_WAIT_MS = 5000; constexpr float SPINNER_DROP = 0.33f; constexpr float SPINNER_SCALE = 0.8f; -constexpr unsigned int FILTER_LINEAR = 1; // The disclaimer on screen: its popup, which disclaimer it is, who hears the answer, and the spinner shown while its // choices wait. diff --git a/src/greed.cpp b/src/greed.cpp new file mode 100644 index 0000000..429cd1d --- /dev/null +++ b/src/greed.cpp @@ -0,0 +1,757 @@ +#include "ambush.h" +#include "entity_config.h" +#include "entity_effect_combat.h" +#include "entity_factory.h" +#include "entity_npc.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "grid_entity_poop.h" +#include "grid_entity_pressure_plate.h" +#include "log.h" +#include "music_manager.h" +#include "npc_alt.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include "level.h" +#include "manager.h" +#include "persistent_game_data.h" +#include "room.h" +#include "room_config.h" +#include +#include +#include +#include + +// A room of a Greed floor's fixed layout: its cell, shape and type, and the cell and side it joins the layout through +// (none for the start room). +struct GreedRoom +{ + XY position; + RoomShape shape = ROOMSHAPE_1x1; + int type = ROOM_DEFAULT; + XY linkPos; + int connectDirection = DIRECTION_NONE; +}; + +// A Greed floor: the tall start room, the shop above, the two treasure rooms on the right (none on the shop floor), +// the curse room on the left and the exit below. The lower treasure room is the floor's own, which Devil's Crown and +// the item pools tell apart. +constexpr std::array GREED_ROOMS = {{ + {{6, 6}, ROOMSHAPE_1x2, ROOM_DEFAULT, XY_NONE, DIRECTION_NONE}, + {{5, 5}, ROOMSHAPE_2x1, ROOM_SHOP, {6, 5}, DIRECTION_UP}, + {{7, 7}, ROOMSHAPE_1x1, ROOM_TREASURE, {7, 7}, DIRECTION_RIGHT}, + {{7, 6}, ROOMSHAPE_1x1, ROOM_TREASURE, {7, 6}, DIRECTION_RIGHT}, + {{5, 6}, ROOMSHAPE_1x1, ROOM_CURSE, {5, 6}, DIRECTION_LEFT}, + {{6, 8}, ROOMSHAPE_1x1, ROOM_GREED_EXIT, {6, 8}, DIRECTION_DOWN}, +}}; +constexpr uint32_t GREED_TREASURE_ROOM_IDX = 6 * LEVEL_GRID_WIDTH + 7; + +// Ultra Greed's floor: the start room, the room above it and the boss's tall room past that. +constexpr std::array ULTRA_GREED_ROOMS = {{ + {{6, 6}, ROOMSHAPE_1x1, ROOM_DEFAULT, XY_NONE, DIRECTION_NONE}, + {{6, 5}, ROOMSHAPE_1x1, ROOM_BOSS, {6, 5}, DIRECTION_UP}, + {{6, 3}, ROOMSHAPE_1x2, ROOM_BOSS, {6, 4}, DIRECTION_UP}, +}}; +constexpr uint32_t ULTRA_GREED_BOSS_VARIANT = 1000; +constexpr uint32_t ULTRA_GREED_ANTEROOM_VARIANT_MAX = 999; + +// A Greed treasure room's subtype: Pay to Win's, and 15 in 100 (raised by Golden Horse Shoe's multiplier) the more +// options kind while someone holds the horse shoe. +constexpr int GREED_TREASURE_OPTIONS = 1; +constexpr int GREED_TREASURE_PAY_TO_WIN = 2; +constexpr uint32_t GREED_HORSE_SHOE_ROLLS = 100; +constexpr uint32_t GREED_HORSE_SHOE_HITS = 15; + +// The difficulties every Greed room is drawn within. +constexpr int GREED_DIFFICULTY_MIN = 1; +constexpr int GREED_DIFFICULTY_MAX = 10; + +// The angel shop's subtype. +constexpr int ANGEL_SHOP_SUBTYPE = 1; + +// A query for a Greed room of a type, a stage and a shape, with the doors its slot has. +static RoomQuery greed_query(int stageId, int type, RoomShape shape, uint32_t doors) +{ + return {.requiredDoors = doors, + .shape = shape, + .maxDifficulty = GREED_DIFFICULTY_MAX, + .minDifficulty = GREED_DIFFICULTY_MIN, + .stageId = stageId, + .type = type}; +} + +// A generator room for a room of the fixed layout. +static LevelGenerator_Room greed_slot(const GreedRoom& room) +{ + LevelGenerator_Room slot; + + slot.position = room.position; + slot.shape = room.shape; + slot.linkPos = room.linkPos; + slot.connectDirection = room.connectDirection; + return slot; +} + +static int greed_treasure_subtype(RNG& rng) +{ + PlayerManager& players = g_game->playerManager; + int subtype = players.AnyoneHasTrinket(TRINKET_PAY_TO_WIN) ? GREED_TREASURE_PAY_TO_WIN : 0; + uint32_t rolls = + GREED_HORSE_SHOE_ROLLS / (uint32_t)std::max(1, players.GetTrinketMultiplier(TRINKET_GOLDEN_HORSE_SHOE)); + + if (rng.RandomInt(rolls) < GREED_HORSE_SHOE_HITS && players.AnyoneHasTrinket(TRINKET_GOLDEN_HORSE_SHOE)) + subtype = + GREED_TREASURE_OPTIONS + (players.AnyoneHasTrinket(TRINKET_PAY_TO_WIN) ? GREED_TREASURE_PAY_TO_WIN : 0); + return subtype; +} + +// Seeds a room off the map and draws its config from the normal special rooms. +static void greed_off_map_room_init(Level& level, int idx, int type, int subtype) +{ + RoomDescriptor& desc = *level.GetRoomByIdx(idx); + RoomQuery query = greed_query(STAGE_ID_SPECIAL_ROOMS, type, ROOMSHAPE_ANY, 0); + + query.subtype = subtype; + query.mode = ROOM_MODE_NORMAL; + desc.InitSeeds(level.generationRNG); + desc.data = g_game->roomConfig.GetRandomRoom(level.generationRNG.Next(), WEIGHT_REDUCE, query); +} + +// Lays out a normal Greed floor and draws its twelve wave seeds. Its rooms come from the special rooms but for the +// start room and the treasure rooms (falling back to the special rooms). +static void greed_floor_generate(Level& level) +{ + RoomConfig& roomConfig = g_game->roomConfig; + RNG& rng = level.generationRNG; + int stageId = RoomConfig::GetStageID((int)level.stage, (int)level.stageType, ROOM_MODE_CURRENT); + LevelGenerator generator(rng.Next()); + std::vector rooms; + + generator.rooms.reserve(GREED_ROOMS.size() + 1); + for (const GreedRoom& room : GREED_ROOMS) + { + if (room.type == ROOM_TREASURE && level.stage == STAGE_GREED_SHOP) continue; + rooms.push_back(&room); + generator.CreateRoom(greed_slot(room)); + } + level.lastBossRoomListIdx = generator.rooms[0].generationIndex; + LevelGenerator_Room* superSecret = generator.try_add_dead_end(nullptr); + + std::vector configs; + for (size_t i = 0; i < rooms.size(); i++) + { + LevelGenerator_Room& slot = generator.rooms[i]; + int type = rooms[i]->type; + RoomQuery query = + greed_query(type == ROOM_DEFAULT ? stageId : STAGE_ID_SPECIAL_ROOMS, type, slot.shape, slot.doors); + + if (type == ROOM_TREASURE) + { + query.stageId = stageId; + query.subtype = greed_treasure_subtype(rng); + configs.push_back( + roomConfig.GetRandomRoomWithFallbackStage(rng.Next(), WEIGHT_REDUCE, query, STAGE_ID_SPECIAL_ROOMS)); + } + else + configs.push_back(roomConfig.GetRandomRoom(rng.Next(), WEIGHT_REDUCE, query)); + } + + // The original reads a missing dead end's doors through a null pointer. Here it draws for no doors. + RoomQuery superSecretQuery = + greed_query(STAGE_ID_SPECIAL_ROOMS, ROOM_SUPERSECRET, ROOMSHAPE_1x1, superSecret ? superSecret->doors : 0); + RoomConfig_Room* superSecretConfig = roomConfig.GetRandomRoom(rng.Next(), WEIGHT_REDUCE, superSecretQuery); + + level.roomMap.fill(-1); + level.nbRooms = 0; + level.greedModeTreasureRoomIdx = GREED_TREASURE_ROOM_IDX; + for (size_t i = 0; i < configs.size(); i++) level.place_room(generator.rooms[i], configs[i], rng.Next(), nullptr); + if (superSecret) level.place_room(*superSecret, superSecretConfig, rng.Next(), nullptr); + for (uint32_t& seed : level.greedWaveSeeds) seed = rng.Next(); +} + +// Lays out Ultra Greed's floor from its fixed start and boss rooms and a drawn room between them. +static void ultra_greed_floor_generate(Level& level) +{ + RoomConfig& roomConfig = g_game->roomConfig; + RNG& rng = level.generationRNG; + LevelGenerator generator(rng.Next()); + + generator.rooms.reserve(ULTRA_GREED_ROOMS.size()); + for (const GreedRoom& room : ULTRA_GREED_ROOMS) generator.CreateRoom(greed_slot(room)); + + RoomQuery anteroomQuery = greed_query(STAGE_ID_ULTRA_GREED, ROOM_BOSS, ROOMSHAPE_1x1, generator.rooms[1].doors); + anteroomQuery.maxVariant = ULTRA_GREED_ANTEROOM_VARIANT_MAX; + + RoomConfig_Room* start = + roomConfig.GetRoomByStageTypeAndVariant(STAGE_ID_ULTRA_GREED, ROOM_DEFAULT, 0, ROOM_MODE_CURRENT); + RoomConfig_Room* anteroom = roomConfig.GetRandomRoom(rng.Next(), WEIGHT_REDUCE, anteroomQuery); + RoomConfig_Room* boss = roomConfig.GetRoomByStageTypeAndVariant(STAGE_ID_ULTRA_GREED, ROOM_BOSS, + ULTRA_GREED_BOSS_VARIANT, ROOM_MODE_CURRENT); + + level.roomMap.fill(-1); + level.nbRooms = 0; + level.lastBossRoomListIdx = generator.rooms[2].generationIndex; + std::array configs = {start, anteroom, boss}; + for (size_t i = 0; i < configs.size(); i++) level.place_room(generator.rooms[i], configs[i], rng.Next(), nullptr); +} + +// (00743550, 0074378b, 00743fc3) Lays out a Greed floor (Ultra Greed's on the last), then the rooms off the map from +// the normal special rooms: the error room, black market, crawl space, the Member Card's shop and the angel shop. +void Level::generate_greed() +{ + PersistentGameData& data = g_manager->persistentGameData; + + if (stage < STAGE_ULTRA_GREED) + greed_floor_generate(*this); + else + ultra_greed_floor_generate(*this); + + greed_off_map_room_init(*this, ROOM_ERROR_IDX, ROOM_ERROR, -1); + greed_off_map_room_init(*this, ROOM_BLACK_MARKET_IDX, ROOM_BLACK_MARKET, -1); + greed_off_map_room_init(*this, ROOM_DUNGEON_IDX, ROOM_DUNGEON, -1); + + RNG shopRng = {generationRNG.Next(), 3, 3, 26}; + uint32_t lowLevel = + shopRng.RandomInt(1 + data.Unlocked(ACHIEVEMENT_STORE_UPGRADE_2) + data.Unlocked(ACHIEVEMENT_STORE_UPGRADE_4)); + uint32_t highLevel = shopRng.RandomInt(1 + data.Unlocked(ACHIEVEMENT_STORE_UPGRADE_3)); + + greed_off_map_room_init(*this, ROOM_SECRET_SHOP_IDX, ROOM_SHOP, (int)(lowLevel + highLevel)); + generationRNG.Next(); + greed_off_map_room_init(*this, ROOM_ANGEL_SHOP_IDX, ROOM_ANGEL, ANGEL_SHOP_SUBTYPE); +} + +// Greed's waves: twelve, the boss waves from the ninth (one later in Greedier), the last of them the devil wave the +// button calls only once it shows the pentagram. A wave's timer counts frames, none while the button waits. +constexpr uint32_t GREED_WAVE_LAST = GREED_WAVE_SEED_COUNT; +constexpr uint32_t GREED_DEVIL_WAVE = 11; +constexpr int WAVE_TIMER_FRAMES = 30; +constexpr int WAVE_TIMER_NONE = -1; +constexpr int WAVE_TIMER_CLEARED = 19; + +// A normal wave's seconds by floor (more each wave), one less in Greed once Everything Is Terrible 2 is unlocked, +// and a boss wave's from its base and its step per wave past the sixth. Greedier counts down faster. +constexpr std::array GREED_WAVE_SECONDS = {0, 8, 8, 7, 6}; +constexpr std::array GREEDIER_WAVE_SECONDS = {0, 9, 7, 5, 4}; +constexpr int GREED_WAVE_SECONDS_LATE = 8; +constexpr int GREEDIER_WAVE_SECONDS_LATE = 3; +constexpr int GREED_BOSS_SECONDS = 28; +constexpr int GREED_BOSS_SECONDS_FAST = 25; +constexpr int GREED_BOSS_SECONDS_STEP = 3; +constexpr int GREEDIER_BOSS_SECONDS = 15; +constexpr int GREED_BOSS_STEP_FROM = 6; + +// The coins a wave pays: two (one in Greedier) for a normal wave, two more for a boss wave, one more for Greedier's +// first boss wave and three more for its last, none for the devil wave. One less after the button was pressed +// against a running wave by someone it could not hurt, one more every third wave in a row cleared without red heart +// damage. +constexpr int GREED_WAVE_COINS = 2; +constexpr int GREEDIER_WAVE_COINS = 1; +constexpr int BOSS_WAVE_COINS = 2; +constexpr int GREEDIER_LAST_BOSS_COINS = 3; +constexpr int CLEAN_WAVE_STREAK = 3; + +// The difficulty of the rooms a wave is drawn from by the waves before it, in Greed and in Greedier, any past them. +constexpr std::array GREED_WAVE_DIFFICULTY = {1, 1, 1, 5, 5, 5, 10, 10, 1, 5, 10}; +constexpr std::array GREEDIER_WAVE_DIFFICULTY = {1, 1, 1, 5, 5, 5, 10, 10, 10, 1, 5, 10}; + +// The coins drop on the room's middle column four cells down, each in a poof of gold. +constexpr int COIN_ROW = 4; +constexpr float COIN_SPARKLE_SPEED_MIN = 2; +constexpr float COIN_SPARKLE_SPEED_RANGE = 3; +constexpr uint32_t COIN_SPARKLE_COUNT_MIN = 5; +constexpr uint32_t COIN_SPARKLE_COUNT_RANGE = 3; + +// A wave's pentagrams draw above the floor's decorations. +constexpr int WAVE_PENTAGRAM_RENDER_Z = 1001; + +static bool is_greedier() +{ + return g_game->difficulty == DIFFICULTY_GREEDIER; +} + +// The first boss wave, and the devil wave. +static uint32_t greed_boss_wave() +{ + return GREED_BOSS_WAVE + is_greedier(); +} + +static uint32_t greed_devil_wave() +{ + return GREED_DEVIL_WAVE + is_greedier(); +} + +// A called wave's timer: the frames until the next wave comes by itself, none for the last normal and the last boss +// wave and the devil wave, which wait for the button. +static int greed_wave_timer(uint32_t wave, int wavesBefore) +{ + Game& game = *g_game; + uint32_t greedier = is_greedier(); + bool isFast = !greedier && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_EVERYTHING_IS_TERRIBLE_2); + + if (wave == greed_boss_wave() - 1 || wave == greed_boss_wave() + 1 || wave >= greed_devil_wave()) + return WAVE_TIMER_NONE; + if (wave >= greed_boss_wave()) + { + if (greedier) return GREEDIER_BOSS_SECONDS * WAVE_TIMER_FRAMES; + int seconds = isFast ? GREED_BOSS_SECONDS_FAST : GREED_BOSS_SECONDS; + return ((wavesBefore - GREED_BOSS_STEP_FROM) * GREED_BOSS_SECONDS_STEP + seconds) * WAVE_TIMER_FRAMES; + } + + const std::array& table = greedier ? GREEDIER_WAVE_SECONDS : GREED_WAVE_SECONDS; + int seconds = game.stage < table.size() ? table[game.stage] + : (greedier ? GREEDIER_WAVE_SECONDS_LATE : GREED_WAVE_SECONDS_LATE); + return (seconds - isFast + wavesBefore) * WAVE_TIMER_FRAMES; +} + +// The coins a called wave pays when it is the first time the wave is reached, before the penalty and the streak. +static int greed_wave_coins(uint32_t wave) +{ + bool isGreedier = is_greedier(); + int coins = isGreedier ? GREEDIER_WAVE_COINS : GREED_WAVE_COINS; + + if (wave >= greed_boss_wave()) coins += BOSS_WAVE_COINS; + if (isGreedier && wave == greed_boss_wave() - 1) coins++; + if (isGreedier && wave == greed_devil_wave() - 1) coins += GREEDIER_LAST_BOSS_COINS; + return wave == greed_devil_wave() ? 0 : coins; +} + +// The wave's music: the shop floor's challenge fight or the floor's layer for a normal wave, then the boss fight +// (Satan's for the devil wave, the Repentance floors' own, or the room's alternate). +static void greed_wave_music(Room& room, uint32_t wave, int stageId) +{ + Game& game = *g_game; + MusicManager& music = g_manager->musicManager; + + if (wave < greed_boss_wave()) + { + if (stageId == STAGE_ID_GREED_SHOP) + music.Crossfade(MUSIC_CHALLENGE_FIGHT, MUSIC_FADE_RATE); + else + music.EnableLayer(0, LAYER_FADE); + return; + } + bool isRepentance = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; + bool isAltMusic = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_ALT_BOSS_MUSIC; + int track = wave == greed_devil_wave() ? MUSIC_SATAN_BOSS + : isRepentance ? MUSIC_BOSS3 + : isAltMusic ? MUSIC_BOSS2 + : MUSIC_BOSS; + music.Crossfade(track, MUSIC_FADE_RATE); +} + +// The coins a wave pays drop in the room's middle, each with a poof of gold. +static void greed_wave_pay(Room& room, int coins, RNG& rng) +{ + int column = room.gridWidth / 2; + int cell = + column >= 0 && column < room.gridWidth && room.gridHeight > COIN_ROW ? column + room.gridWidth * COIN_ROW : -1; + Vector center = room.GetGridPosition(cell); + + for (int i = 0; i < coins; i++) + { + Vector position = room_free_pickup_position_find({.position = center}); + Entity* coin = g_game->Spawn({.position = position, + .subType = COIN_PENNY, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = rng.Next()}); + + if (auto* pickup = dynamic_cast(coin)) pickup->AppearFast(); + float speed = random_unit() * COIN_SPARKLE_SPEED_RANGE + COIN_SPARKLE_SPEED_MIN; + int count = (int)(Random() % COIN_SPARKLE_COUNT_RANGE + COIN_SPARKLE_COUNT_MIN); + game_particles_spawn({.position = position, .speed = speed, .count = count, .variant = EFFECT_GOLD_PARTICLE}); + } +} + +// Where a wave's entry rises: its own cell, or the nearest free spot when the cell is off the grid, blocked, or on a +// path. The dungeon of Home keeps its cells. +static int greed_wave_cell(Room& room, int cell, Vector& position) +{ + RoomConfig_Room* data = room.descriptor->data; + bool isKept = data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME; + GridEntity* grid = cell >= 0 ? room.gridEntities[cell] : nullptr; + bool isBlocked = + cell < 0 || (grid ? grid->collisionClass != COLLISION_NONE : room.gridPaths[cell] >= GRID_PATH_SOLID); + + if (isKept || !isBlocked) return cell; + position = room_free_pickup_position_find({.position = position}); + return room.GetGridIndex(position); +} + +// Spawns a wave's layout: each spawn breaks the grid entity on its cell, then rises from a pentagram (an enemy with +// the ambush flag), appears as an effect at once, or is spawned as the room would. +static void greed_wave_entries_spawn(Room& room, RoomConfig_Room& wave, RNG& rng) +{ + if (room.gridWidth != wave.width + 2) log_printf(LOG_ASSERT, "Greed Mode wave does not match room size\n"); + + for (RoomSpawn& spawn : wave.spawns) + { + float roll = rng.RandomFloat(); + int cell = spawn.x + (spawn.y + 1) * room.gridWidth + 1; + Vector position = room.GetGridPosition(cell); + + if ((uint32_t)cell < ROOM_GRID_CELLS && room.gridEntities[cell]) room.gridEntities[cell]->Destroy(true, {}); + cell = greed_wave_cell(room, cell, position); + if (spawn.entries.empty()) continue; + + RoomEntry entry = *spawn.PickEntry(roll); + uint32_t seed = rng.Next(); + room_entry_transform(room, entry, cell, seed); + if (entry.type < 1) continue; + if (entry.type >= ENTITY_EFFECT) + { + room_entry_spawn(room, entry, {.gridIndex = cell, .seed = seed}); + continue; + } + if (entry.type == WAVE_ENTRY_EFFECT) + { + Entity* effect = g_game->Spawn({.position = position, + .subType = entry.subtype, + .type = ENTITY_EFFECT, + .variant = entry.variant, + .seed = rng.Next()}); + effect->Update(); + effect->spawnGridIndex = cell; + continue; + } + Entity_Effect* pentagram = pentagram_spawn({.position = position, + .subType = entry.subtype, + .type = (int)entry.type, + .variant = entry.variant, + .seed = rng.Next()}, + cell); + bool isVersusPlayer = g_game->deathmatchManager.is_active() && entry.type == ENTITY_PLAYER; + + pentagram->renderZOffset = WAVE_PENTAGRAM_RENDER_Z; + if (isVersusPlayer || entry.type >= ENTITY_FIRST_ENEMY) pentagram->AddEntityFlags(FLAG_AMBUSH); + } +} + +// Whether Greedier may make an entity a champion: an active enemy spawned this frame that is no boss. +static Entity_NPC* greedier_champion_candidate(Entity& entity) +{ + if (!entity.IsActiveEnemy(DEAD_EXCLUDED) || entity.IsBoss() || entity.spawnFrame != g_game->frameCount) + return nullptr; + + auto* npc = dynamic_cast(&entity); + EntityConfig_Entity* config = + npc ? g_manager->entityConfig.GetEntity(npc->type, npc->variant, npc->subtype) : nullptr; + return config && config->isCanBeChampion ? npc : nullptr; +} + +// Greedier makes one of the wave's new enemies a champion unless one already is. +static void greedier_champion_make(Room& room, RNG& rng) +{ + std::vector candidates; + + for (Entity* entity : room.entityList.updateEL) + if (Entity_NPC* npc = greedier_champion_candidate(*entity)) + { + if (npc->isChampion) return; + candidates.push_back(npc); + } + if (candidates.empty()) return; + + Entity_NPC* chosen = candidates[rng.Next() % candidates.size()]; + chosen->MakeChampion(rng.Next(), -1, false); +} + +// 00816910 Calls Greed's next wave: the room shuts, the wave's timer and music start, a wave reached the first time +// pays its coins (and the players' locusts come), and its enemies rise from a challenge room of the floor drawn for +// the wave (a boss room for the boss waves) by the wave's seed. Greedier makes one of them a champion. +void Room::SpawnGreedModeWave() +{ + Game& game = *g_game; + int wavesBefore = game.greedModeWave; + uint32_t wave = std::min((uint32_t)wavesBefore + 1, GREED_WAVE_LAST); + int stageId = RoomConfig::GetStageID((int)game.stage, (int)game.stageType, ROOM_MODE_CURRENT); + RNG rng = {game.greedWaveSeeds[wave - 1], 1, 27, 27}; + + descriptor->flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR; + for (GridEntity_Door* door : doors) + { + if (!door) continue; + if (door->state != DOOR_STATE_CLOSED) + { + door->state = DOOR_STATE_CLOSED; + door->UpdateAnimation(); + for (int type : {door->currentRoomType, door->targetRoomType}) + if (type == ROOM_SECRET || type == ROOM_SUPERSECRET || type == ROOM_ULTRASECRET) + door->openAnimation = "Open"; + } + if (door->variant == DOOR_UNLOCKED) door->Bar(); + } + + game.greedModeWave = (int)wave; + greedWaveTimer = greed_wave_timer(wave, wavesBefore); + greed_wave_music(*this, wave, stageId); + + int coins = greed_wave_coins(wave); + if (coins && (game.levelStateFlags & 1u << LEVEL_STATE_GREED_LOST_PENALTY)) + { + coins--; + game.levelStateFlags &= ~(1u << LEVEL_STATE_GREED_LOST_PENALTY); + } + if (game.greedWavesClearedWithoutRedHeartDamage > 0 && + game.greedWavesClearedWithoutRedHeartDamage % CLEAN_WAVE_STREAK == 0) + coins++; + game.greedWavesClearedWithoutRedHeartDamage++; + + int sound = SOUND_SUMMON_PENTA; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.frameDelay = 3}); + + size_t band = (size_t)wavesBefore; + std::span bands = is_greedier() ? std::span(GREEDIER_WAVE_DIFFICULTY) : GREED_WAVE_DIFFICULTY; + RoomQuery query = {.shape = descriptor->data->shape, + .maxDifficulty = band < bands.size() ? bands[band] : GREED_DIFFICULTY_MAX, + .minDifficulty = band < bands.size() ? bands[band] : GREED_DIFFICULTY_MIN, + .stageId = stageId, + .type = wave < greed_boss_wave() ? ROOM_CHALLENGE : ROOM_BOSS}; + RoomConfig_Room* waveRoom = game.roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + + if (!waveRoom) + { + log_printf(LOG_INFO, "Did not find wave level %d (greed mode).\n", wave); + return; + } + log_printf(LOG_INFO, "Spawning greed mode wave from room variant %d.\n", waveRoom->variant); + if ((uint32_t)game.greedLastPaidWave < wave) + { + game.playerManager.trigger_room_clear(); + greed_wave_pay(*this, coins, rng); + game.greedLastPaidWave = (int)wave; + for (Entity_Player* player : game.playerManager.playerList) player->spawn_locusts(); + } + + isInitialized = false; + greed_wave_entries_spawn(*this, *waveRoom, rng); + if (is_greedier()) greedier_champion_make(*this, rng); + isInitialized = true; +} + +// Ultra Greed's room opens its fight once a player walks in past its doorway: Monstro drops on that player first in +// the plain layout. +constexpr float ULTRA_GREED_ENTRY_Y = 320; +constexpr int MONSTRO_SUBTYPE_ANY = -1; + +// The first player who walked into Ultra Greed's room, or none. +static Entity_Player* ultra_greed_room_entrant() +{ + for (Entity_Player* player : g_game->playerManager.playerList) + if (player->pos.y < ULTRA_GREED_ENTRY_Y) return player; + return nullptr; +} + +// 00801ee0 Greed mode's waves: the timer runs down to the next wave, cut short to its last frames once the wave is +// beaten, and Ultra Greed's room starts its fight (Monstro first, in the plain layout) once a player walks in. +void Room::UpdateGreedWave() +{ + Game& game = *g_game; + + if (!game.IsGreedMode()) return; + if (greedWaveTimer > 0) + { + greedWaveTimer--; + if (GetAliveEnemiesCount() < 1 && greedWaveTimer > WAVE_TIMER_CLEARED) + { + game.greedLastBeatenWave = game.greedModeWave; + greedWaveTimer = WAVE_TIMER_CLEARED; + } + else if (greedWaveTimer == 0) + SpawnGreedModeWave(); + } + + if (game.stage != STAGE_ULTRA_GREED || roomType != ROOM_BOSS) return; + if (game.levelStateFlags & 1u << LEVEL_STATE_GREED_MONSTRO_SPAWNED) return; + Entity_Player* entrant = ultra_greed_room_entrant(); + if (!entrant) return; + + g_manager->musicManager.Play(MUSIC_BOSS, g_manager->optionsConfig.musicVolume); + descriptor->flags &= ~ROOM_DESCRIPTOR_FLAG_ALT_BOSS_MUSIC; + game.levelStateFlags |= 1u << LEVEL_STATE_GREED_MONSTRO_SPAWNED; + if (descriptor->data->subtype == 0) + { + Entity* monstro = game.Spawn( + {.position = entrant->pos, .subType = MONSTRO_SUBTYPE_ANY, .type = ENTITY_MONSTRO, .seed = Random()}); + monstro->ClearEntityFlags(FLAG_APPEAR); + monstro->Update(); + } + TriggerOutput(0); + + int sound = SOUND_CASTLEPORTCULLIS; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); +} + +// Greed's button: a player this close presses it, and it stays pressed until every player is this far away. +constexpr float GREED_BUTTON_PRESS_DISTANCE = 25; +constexpr float GREED_BUTTON_LEAVE_DISTANCE = 30; +constexpr float GREED_BUTTON_HURT = 1; +constexpr int GREED_BUTTON_HURT_COUNTDOWN = 30; + +// Calling a wave ends Taurus's charge: the player's speed bonus is lost and the charge starts over. +static void taurus_restart(Entity_Player& player) +{ + bool isTaurus = player.HasCollectible(COLLECTIBLE_TAURUS) || player.GetZodiacEffect() == COLLECTIBLE_TAURUS; + + if (!isTaurus || player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_TAURUS)) return; + player.taurusSpeedBonus = 0; + player.SetColor(COLOR_DEFAULT, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (ItemConfig_Item* taurus = g_manager->itemConfig.GetCollectible(COLLECTIBLE_TAURUS)) + player.temporaryEffects.AddEffect(TemporaryEffect(taurus), true, 1); +} + +// 009839f0 Runs Greed mode's wave button: a player stepping on it presses it (hurt for it while a wave runs, or +// costing a coin of the next wave when it cannot hurt them), and once its switch animation ends it calls the next +// wave, or stops the timer while one runs. It rises again once everyone stepped off, unless the waves are over or a +// wave runs with the room still shut. A beaten wave holds it down until the next is called. +void GridEntity_PressurePlate::update_greed_button() +{ + Game& game = *g_game; + Room& room = *game.room; + bool isWaveRunning = room.greedWaveTimer > 0; + bool isClear = room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR; + Vector center = room.GetGridPosition(gridIndex); + bool isNear = false; + bool isEveryoneAway = true; + + for (Entity_Player* player : game.playerManager.playerList) + { + if (player->variant != PLAYER_VARIANT_PLAYER || player->isCoopGhost) continue; + + float distance = vector_length_squared(vector_sub(center, player->pos)); + isNear |= distance < GREED_BUTTON_PRESS_DISTANCE * GREED_BUTTON_PRESS_DISTANCE; + isEveryoneAway &= !(distance <= GREED_BUTTON_LEAVE_DISTANCE * GREED_BUTTON_LEAVE_DISTANCE); + if (distance >= GREED_BUTTON_PRESS_DISTANCE * GREED_BUTTON_PRESS_DISTANCE || state != PLATE_UNPRESSED) continue; + + if (isWaveRunning) + { + if (player->GetHealthType() == HEALTH_COIN || player->HasInstantDeathCurse()) + game.levelStateFlags |= 1u << LEVEL_STATE_GREED_LOST_PENALTY; + else + player->TakeDamage(GREED_BUTTON_HURT, DAMAGE_SPIKES | DAMAGE_NO_PENALTIES, {}, + GREED_BUTTON_HURT_COUNTDOWN); + } + break; + } + + GreedButtonColor color = isWaveRunning ? GREED_BUTTON_RED : GREED_BUTTON_NORMAL; + if (state == PLATE_UNPRESSED && isNear) + { + state = PLATE_GREED_PRESSED; + if (!sprite.IsPlaying() || sprite.GetAnimation() != "Switched") + { + int sound = SOUND_BUTTON_PRESS; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound); + } + update_greed_button_anim(color); + } + if (!sprite.IsPlaying() && (state == PLATE_GREED_PRESSED || state == PLATE_GREED_HELD)) + { + if (state == PLATE_GREED_PRESSED && !isWaveRunning) + { + room.SpawnGreedModeWave(); + for (Entity_Player* player : game.playerManager.playerList) taurus_restart(*player); + } + else if (state == PLATE_GREED_PRESSED) + room.greedWaveTimer = WAVE_TIMER_NONE; + state = PLATE_PRESSED; + update_greed_button_anim(color); + } + + bool isTimerRunning = room.greedWaveTimer > 0; + color = isTimerRunning ? GREED_BUTTON_RED : GREED_BUTTON_NORMAL; + if (state == PLATE_PRESSED && isEveryoneAway && (uint32_t)game.greedModeWave < greed_devil_wave() && + (isTimerRunning || isClear)) + { + state = PLATE_UNPRESSED; + update_greed_button_anim(color); + } + else if (state == PLATE_UNPRESSED && !isTimerRunning && !isClear) + { + state = PLATE_GREED_HELD; + update_greed_button_anim(color); + } + play_pending_animation(); +} + +// The Greed donation machine's jam chance: certain for the characters past the table, else from the coins the +// character has donated (e^(0.023 coins) - 1, at most 100), a fifth of it rounded, at most 1 in Greedier. +constexpr float DONATION_JAM_UNKNOWN = 99.9f; +constexpr float DONATION_JAM_GROWTH = 0.023f; +constexpr float DONATION_JAM_MAX = 100; +constexpr float DONATION_JAM_SHARE = 0.2f; +constexpr float DONATION_JAM_GREEDIER_MAX = 1; + +// 007cbb90 The chance in percent the Greed donation machine jams, from a save's donation counter. +float Entity_Player::GetGreedDonationJamChance(PersistentGameData& data) +{ + if ((uint32_t)playerType >= (uint32_t)COMPLETION_PLAYER_TYPE_COUNT) return DONATION_JAM_UNKNOWN; + + uint32_t donated = data.eventCounters[COMPLETION_MARKS[playerType][COMPLETION_GREED_DONATION].counter]; + float chance = std::min(std::exp((float)donated * DONATION_JAM_GROWTH) - 1, DONATION_JAM_MAX); + chance = std::floor(chance * DONATION_JAM_SHARE + HALF); + return g_game->difficulty == DIFFICULTY_GREEDIER ? std::min(DONATION_JAM_GREEDIER_MAX, chance) : chance; +} + +// 007cbb70 The chance the machine breaks: its jam chance from the game's save. +float Entity_Player::GetGreedDonationBreakChance() +{ + return GetGreedDonationJamChance(g_manager->persistentGameData); +} + +// A gold room: the floor and walls washed gold, the grid entities a paler gold. +constexpr ColorMod GOLD_ROOM_COLOR = {{1, 1, 1, 1}, {5, 3, 0, 0.8f}, {0, 0, 0}}; +constexpr ColorMod GOLD_GRID_COLOR = {{1, 1, 1, 1}, {3, 1.8f, 0, 0.8f}, {0, 0, 0}}; + +// 007ebd50 Room::SpawnGridEntityDesc: a grid entity spawned on a free cell (a flat one where nothing collides, any +// other where the path is not blocked) from a saved description, replacing what stood there. +static bool room_grid_desc_spawn(Room& room, int gridIndex, const GridEntityDesc& desc) +{ + if ((uint32_t)gridIndex >= ROOM_GRID_CELLS) + { + log_printf(LOG_ASSERT, "SpawnGridEntity: Grid index invalid\n"); + return false; + } + bool isFlat = desc._type == GRID_TRAPDOOR || desc._type == GRID_STAIRS || desc._type == GRID_PRESSURE_PLATE || + desc._type == GRID_TELEPORTER; + bool isFree = + isFlat ? room.GetGridCollision(gridIndex) == COLLISION_NONE : room.gridPaths[gridIndex] <= GRID_PATH_FREED; + GridEntity* grid = isFree ? CreateGridEntity((GridEntityType)desc._type, gridIndex) : nullptr; + if (!grid) return false; + + delete room.gridEntities[gridIndex]; + room.gridEntities[gridIndex] = grid; + grid->desc_load(desc); + grid->collisionClass = COLLISION_NONE; + grid->subclass_init(); + grid->spawnCount++; + grid->isInitialized = true; + grid->spawnFrame = g_game->frameCount; + return true; +} + +// 00820ac0 Turns the room gold (Ultra Greed's room once he turns): its floor and walls, every poop to gold poop and +// every other grid entity's look. +void Room::TurnGold() +{ + floorColor = GOLD_ROOM_COLOR; + wallColor = GOLD_ROOM_COLOR; + for (int i = 0; i < ROOM_GRID_CELLS; i++) + { + GridEntity* grid = gridEntities[i]; + if (!grid) continue; + if (grid->type != GRID_POOP) + grid->sprite.color = GOLD_GRID_COLOR; + else if (grid->variant != POOP_GOLDEN) + { + GridEntityDesc gold = grid->desc_save(); + gold._variant = POOP_GOLDEN; + room_grid_desc_spawn(*this, i, gold); + } + } +} diff --git a/src/grid_entity_door.cpp b/src/grid_entity_door.cpp index 0b9cd11..1cc107b 100644 --- a/src/grid_entity_door.cpp +++ b/src/grid_entity_door.cpp @@ -47,7 +47,6 @@ constexpr float DEG_TO_RAD = 0.017453292f; // The frame a closing or opening door plays its sound on, and the sounds. constexpr int DOOR_SOUND_FRAME = 2; constexpr int DOOR_SOUND_DELAY = 10; -constexpr int SOUND_DOOR_HEAVY_CLOSE = 35; constexpr int SOUND_METAL_DOOR_CLOSE = 46; constexpr int SOUND_METAL_DOOR_OPEN = 47; constexpr int SOUND_MEAT_FEET_SLOW = 68; diff --git a/src/grid_entity_gravity.cpp b/src/grid_entity_gravity.cpp index 2aa7dd4..f8897aa 100644 --- a/src/grid_entity_gravity.cpp +++ b/src/grid_entity_gravity.cpp @@ -1,5 +1,14 @@ #include "grid_entity_gravity.h" -#include "log.h" +#include "backdrop.h" +#include "entity_player.h" +#include "game.h" +#include "room.h" +#include + +// A ledge cell shows one of the dungeon's floor tiles: Rotgut's at a random frame of its Floor, the others one of +// three Floor animations. +constexpr RNG GRAVITY_RNG = {0, 5, 21, 12}; +constexpr int GRAVITY_FLOOR_KINDS = 3; // 0099b510 Blocks nothing. void GridEntity_Gravity::subclass_init() @@ -7,14 +16,37 @@ void GridEntity_Gravity::subclass_init() collisionClass = COLLISION_NONE; } -// 0099b520 Loads the cell's look from the walls around it. +// 0099b520 Over a block or wall it shows a ledge tile of its dungeon (Rotgut's, Gideon's or an item dungeon's). void GridEntity_Gravity::PostInit() { - reconstruction_missing("GridEntity_Gravity::PostInit 0099b520"); + Room& room = *g_game->room; + Vector below = room.GetGridPosition(gridIndex); + GridEntity* ground = + room.GetGridEntity((uint32_t)room.GetGridIndex(vector_make(below.x, below.y + GRID_CELL_SIZE))); + if (!ground || (ground->type != GRID_ROCKB && ground->type != GRID_WALL)) return; + + RNG floorRng = GRAVITY_RNG; + floorRng._seed = spawnSeed; + if (room.backdropType == BACKDROP_DUNGEON_ROTGUT) + { + sprite.Load("gfx/grid/Tiles_Rotgut.anm2", GRAPHICS_LOAD); + sprite.SetFrame("Floor", 0); + int frames = sprite.animState.animData ? sprite.animState.GetAnimationLength() : 0; + uint32_t frame = floorRng.RandomInt((uint32_t)frames); + if (sprite.animState.animData) sprite.animState.SetFrameFloat((float)frame); + return; + } + if (room.backdropType == BACKDROP_DUNGEON_GIDEON) + sprite.Load("gfx/grid/Tiles_Itemdungeon_Gideon.anm2", GRAPHICS_LOAD); + else sprite.Load("gfx/grid/Tiles_Itemdungeon.anm2", GRAPHICS_LOAD); + sprite.Play("Floor" + std::to_string(floorRng.Next() % GRAVITY_FLOOR_KINDS + 1)); } -// 0099b980 Pulls the players in the column. +// 0099b980 The players standing in it fall, and its tile animates. void GridEntity_Gravity::Update() { - reconstruction_missing("GridEntity_Gravity::Update 0099b980"); + Room& room = *g_game->room; + for (Entity_Player* player : g_game->playerManager.playerList) + if (room.GetGridIndex(player->pos) == gridIndex) player->AddEntityFlags(FLAG_APPLY_GRAVITY); + sprite.Update(); } diff --git a/src/grid_entity_pressure_plate.cpp b/src/grid_entity_pressure_plate.cpp index 3db043b..8e193b5 100644 --- a/src/grid_entity_pressure_plate.cpp +++ b/src/grid_entity_pressure_plate.cpp @@ -1,6 +1,7 @@ #include "grid_entity_pressure_plate.h" #include "entity_pickup.h" #include "entity_player.h" +#include "entity_slot.h" #include "font.h" #include "game.h" #include "grid_entity_door.h" @@ -56,9 +57,7 @@ constexpr uint32_t REWARD_BOMBS_MAX = 2; constexpr int REWARD_CHESTS[] = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, PICKUP_BOMBCHEST, PICKUP_REDCHEST}; // The slots and bomb a reward plate drops (Lua's SlotVariant and BombVariant). -constexpr int SLOT_MACHINE = 1; constexpr int SLOT_FORTUNE_TELLING = 3; -constexpr int SLOT_DONATION = 8; constexpr int BOMB_TROLL = 3; // An ambush brings two to four enemies, near the doors no player stands within reach of, scattered a little. @@ -247,7 +246,8 @@ void GridEntity_PressurePlate::update_press() else if (frames > AMBUSH_RESPAWN_FRAME && room.IsClear()) state = PLATE_PRESSED; } -// Greed's button for the coming wave: the last boss wave's look, a boss wave's, or the plain one. +// (00983970, 009839b0) Game::IsGreedBoss and IsGreedFinalBoss: Greed's button for the coming wave, the last boss +// wave's look, a boss wave's, or the plain one. static std::string_view greed_look_pick(std::string_view finalBoss, std::string_view boss, std::string_view plain) { Game& game = *g_game; @@ -292,12 +292,6 @@ void GridEntity_PressurePlate::play_pending_animation() sprite.Play(nextGreedAnimation); } -// 009839f0 Runs Greed mode's wave button. -void GridEntity_PressurePlate::update_greed_button() -{ - reconstruction_missing("GridEntity_PressurePlate::update_greed_button 009839f0"); -} - // Where a slot fits: the spot, when a cell beside it on both axes is free, else a free spot near the room's center. static Vector slot_position_get(Vector position) { @@ -353,7 +347,7 @@ static void plate_reward_spawn(GridEntity& plate, RNG& rng) else if (roll < ROLL_DONATION) { position = slot_position_get(position); - entity_spawn(ENTITY_SLOT, SLOT_DONATION, position, rng.Next()); + entity_spawn(ENTITY_SLOT, SLOT_DONATION_MACHINE, position, rng.Next()); } else entity_spawn(ENTITY_BOMB, BOMB_TROLL, position, rng.Next()); } diff --git a/src/hud.cpp b/src/hud.cpp index 8480c4b..7df09b8 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -69,7 +69,6 @@ constexpr KAGE::Graphics::BlendMode BLEND_MODE_PREMULTIPLIED = { KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_ONE, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA, KAGE::Graphics::FACTOR_ONE, KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA}; -constexpr int FILTER_LINEAR = 1; constexpr int CHARGE_BAR_FLASH_FRAMES = 8; constexpr int SOUND_FORTUNE_PAPER = 252; @@ -946,7 +945,6 @@ void HUD::render_run_icons(Vector& cursor, Vector shake, float& statsX) constexpr float LAP_TEXT_X = 18; constexpr float GREED_TEXT_X = 4; constexpr float ROUNDING = 0.5f; - constexpr int GREED_WAVES = 10; Game& game = *g_game; Font& font6 = g_manager->font6_PFTempestaSevenCondensed; diff --git a/src/item_overlay.cpp b/src/item_overlay.cpp index 528240e..b0aaa1d 100644 --- a/src/item_overlay.cpp +++ b/src/item_overlay.cpp @@ -115,7 +115,7 @@ static void sleep_nightmare_update(ANM2& overlay, OverlayUpdate mode) if (isBedroom && game.stage == STAGE_HOME && game.stageType == STAGETYPE_ORIGINAL) { game.SetStage(STAGE_HOME, STAGETYPE_WOTL); - reconstruction_missing("Room::reload_backdrop 007f2070"); + game.room->reload_backdrop(); } return; } diff --git a/src/item_overlay.h b/src/item_overlay.h index 452b7f7..606133c 100644 --- a/src/item_overlay.h +++ b/src/item_overlay.h @@ -28,6 +28,7 @@ enum GiantbookOverlay : int GIANTBOOK_MISSING_PAGE_2 = 31, GIANTBOOK_HAGALAZ = 20, GIANTBOOK_CLICKER = 39, + GIANTBOOK_SLEEP = 33, GIANTBOOK_SLEEP_NIGHTMARE = 44, GIANTBOOK_MEGA_MUSH = 45, GIANTBOOK_ETERNAL_BLACK_HEART = 46, diff --git a/src/item_pool.cpp b/src/item_pool.cpp index 8a77e82..a4617b1 100644 --- a/src/item_pool.cpp +++ b/src/item_pool.cpp @@ -86,7 +86,6 @@ constexpr float REPICK_EDGE_DIVISOR = 3.37317f; constexpr int MAX_DEFAULT_ITEM = 732; constexpr int ROSARY_CHANCE_PER_MULTIPLIER = 2; constexpr int GOLDEN_TRINKET_ODDS = 50; -constexpr uint32_t DEBUG_GOLDEN_TRINKETS = 0x8; constexpr uint32_t TRINKET_GOLDEN = 0x8000; constexpr uint32_t STATE_SATANIC_BIBLE_USED = 0x20000; constexpr uint32_t DESCRIPTOR_DEVIL_TREASURE = 0x800; @@ -118,7 +117,6 @@ constexpr int ONANS_STREAK_BANNED[] = {68, 118, 329, 52, 168, 114, 395, 394, 55, constexpr int PILL_HORSE = 0x800; constexpr int PILL_COLORS = 13; -constexpr int PILL_GOLD = 14; constexpr int PILL_GOLD_ODDS = 140; constexpr int PILL_HORSE_ODDS = 70; constexpr int PILL_EFFECT_NONE = -1; @@ -256,7 +254,7 @@ void ItemPool::Init(uint32_t startSeed, std::string_view path) std::vector effects; for (int color = 1; color <= PILL_COLORS; color++) colors.push_back(color); RNG::Shuffle(&itemPoolRNG, colors.data(), colors.data() + colors.size()); - colors.push_back(PILL_GOLD); + colors.push_back(PILL_COLOR_GOLD); for (auto& pill : config.pillEffects) { @@ -793,8 +791,8 @@ static bool is_trinket_drawable(TrinketPoolItem& slot) // 00733ca0 Draws a trinket: random slots for half the pool's size (at least one), then the next drawable slot after a // random one. -// Taking it removes it from the pool. Once golden trinkets are unlocked, one in 50 is golden. Lua's MC_GET_TRINKET -// may override it. +// Taking it removes it from the pool. Once golden trinkets are unlocked, one in 50 is golden (every one with the high +// damage debug flag). Lua's MC_GET_TRINKET may override it. // The original crashes on a slot whose trinket is missing. Here such a slot cannot be drawn. uint32_t ItemPool::GetTrinket(TrinketDraw draw) { @@ -832,7 +830,7 @@ uint32_t ItemPool::GetTrinket(TrinketDraw draw) if (!g_manager->persistentGameData.Unlocked(ACHIEVEMENT_GOLDEN_TRINKETS)) return trinket; bool isGolden = rng_make(rng._seed, GOLDEN_SHIFT).Next() % GOLDEN_TRINKET_ODDS == 0 || - (g_game && (g_game->debugFlags & DEBUG_GOLDEN_TRINKETS)); + (g_game && (g_game->debugFlags & DEBUG_HIGH_DAMAGE)); return isGolden ? trinket | TRINKET_GOLDEN : trinket; } @@ -877,7 +875,7 @@ int ItemPool::GetPill(uint32_t drawSeed) int color = (int)(rng.Next() % PILL_COLORS) + 1; if (rng.Next() % PILL_GOLD_ODDS == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_GOLD_PILLS)) - color = PILL_GOLD; + color = PILL_COLOR_GOLD; if (rng.Next() % PILL_HORSE_ODDS == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_HORSE_PILLS)) color |= PILL_HORSE; @@ -939,7 +937,7 @@ int ItemPool::ForceAddPillEffect(int pillEffect) // The identified slot of a pill color, every color past the known ones sharing the last. static int pill_slot_get(uint32_t pillColor) { - return std::min((int)(pillColor & PILL_COLOR_MASK), PILL_GOLD); + return std::min((int)(pillColor & PILL_COLOR_MASK), PILL_COLOR_GOLD); } // 00718ea0 diff --git a/src/item_pool.h b/src/item_pool.h index 42fc742..4295457 100644 --- a/src/item_pool.h +++ b/src/item_pool.h @@ -9,6 +9,9 @@ #include constexpr int PILL_COLOR_SLOTS = 15; +// The odds GetCardEx's callers draw a special card and a rune with. +constexpr int CARD_SPECIAL_CHANCE = 25; +constexpr int CARD_RUNE_CHANCE = 10; // The item pools, as itempools.xml names them in this order. enum ItemPoolType : int diff --git a/src/kage_graphics.h b/src/kage_graphics.h index 4654731..dad2a50 100644 --- a/src/kage_graphics.h +++ b/src/kage_graphics.h @@ -10,6 +10,19 @@ #include #include +// How a texture samples: nearest or linear, repeating or clamped at its edges. +enum TextureFilter : int +{ + FILTER_NEAREST, + FILTER_LINEAR +}; + +enum TextureWrap : int +{ + WRAP_REPEAT, + WRAP_CLAMP +}; + namespace KAGE::Graphics { class ImageBase; diff --git a/src/level.cpp b/src/level.cpp index a3d9748..c286f6d 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -2,6 +2,7 @@ #include "boss_pool.h" #include "entity_effect.h" #include "entity_familiar.h" +#include "entity_pickup.h" #include "entity_player.h" #include "game.h" #include "grid_entity_door.h" @@ -36,14 +37,11 @@ constexpr float DUNGEON_EXIT_Y = 280; constexpr float BLACK_MARKET_EXIT_X = 560; constexpr float SECRET_SHOP_ENTRY_X = 440; constexpr float SECRET_SHOP_ENTRY_Y = 168; -constexpr int ROOM_OFF_MAP_14_IDX = -14; -constexpr float OFF_MAP_14_ENTRY_X = 320; -constexpr float OFF_MAP_14_ENTRY_Y = 160; -constexpr int ROOM_OFF_MAP_15_IDX = -15; -constexpr float OFF_MAP_15_ENTRY_X = 80; -constexpr float OFF_MAP_15_ENTRY_Y = 400; +constexpr float ROTGUT_DUNGEON1_ENTRY_X = 320; +constexpr float ROTGUT_DUNGEON1_ENTRY_Y = 160; +constexpr float ROTGUT_DUNGEON2_ENTRY_X = 80; +constexpr float ROTGUT_DUNGEON2_ENTRY_Y = 400; -constexpr uint32_t ASCENT_LAST_STAGE = 6; constexpr int VOID_STAGE_ID_LAST = 17; constexpr uint32_t CHALLENGE_XXXXXXXXL = 21; @@ -51,7 +49,6 @@ constexpr uint32_t CHALLENGE_XXXXXXXXL = 21; // The Ascent's music: the alternate path's stages take the layers past the chapters'. constexpr int ALT_PATH_LAYER_FIRST = 3; constexpr int DIMENSION_MINESHAFT = 2; -constexpr int ENEMY_TYPE_LAST = 999; // X-Ray Vision opening a hidden door: the wall crack turned to the door's side, and its sound. constexpr int XRAY_DOOR_SIDES = 4; constexpr float XRAY_WALL_TURN = 90; @@ -90,10 +87,6 @@ constexpr int ACHIEVEMENT_SOMETHING_FROM_THE_FUTURE = 16; constexpr int ACHIEVEMENT_SOMETHING_CUTE = 17; constexpr int ACHIEVEMENT_SOMETHING_STICKY = 18; constexpr int ACHIEVEMENT_SOMETHING_ICKY = 68; -constexpr int ACHIEVEMENT_STORE_UPGRADE_1 = 151; -constexpr int ACHIEVEMENT_STORE_UPGRADE_2 = 152; -constexpr int ACHIEVEMENT_STORE_UPGRADE_3 = 153; -constexpr int ACHIEVEMENT_STORE_UPGRADE_4 = 154; constexpr int ACHIEVEMENT_SOMETHING_WICKED = 346; constexpr int ACHIEVEMENT_SOMETHING_WICKED_PLUS = 347; constexpr int ACHIEVEMENT_THE_FORGOTTEN = 390; @@ -102,12 +95,10 @@ 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 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 TREASURE_SUBTYPE_KNIFE_PIECE = 34; constexpr int LIL_PORTAL_ROOM_VARIANT = 2; constexpr int GRID_SPAWN_PIT_FIRST = 3000; @@ -164,8 +155,6 @@ constexpr uint32_t CHEST_ROOM_ODDS = 10; constexpr uint32_t CHEST_ROOM_KEY_ODDS = 3; constexpr uint32_t BEDROOM_ODDS = 50; constexpr uint32_t BEDROOM_DYING_ODDS = 5; -constexpr int MIRROR_ROOM_SUBTYPE = 34; -constexpr int MINESHAFT_ENTRANCE_SUBTYPE = 10; constexpr int MINESHAFT_RAIL_PLATE_SUBTYPE = 1; constexpr int GRID_SPAWN_PIT_RAIL = 3002; constexpr int RAIL_RAISE_SHAKE = 20; @@ -334,7 +323,6 @@ constexpr int ROOM_COUNT_STAGE_DIVISOR = 3; constexpr int GIANT_ROOM_SHARE = 3; constexpr int GIANT_ROOM_DIVISOR = 5; constexpr int CORPSE_BACKDROP_ODDS = 5; -constexpr uint32_t GENERATION_SHIFT_INDEX = 35; constexpr uint32_t DEVIL_ANGEL_SHIFT_INDEX = 2; constexpr uint32_t ROOM_SEEDS_SHIFT_INDEX = 12; constexpr uint32_t LIL_PORTAL_SHIFT_INDEX = 25; @@ -404,6 +392,23 @@ static void delirium_distances_set(Level& level) } } +// Part of 00744940: Myosotis keeps the loose pickups left in the floor's visited rooms (not shop items, chests, +// pedestals, the big chest, trophies, beds, throwable bombs or Mom's chest) for the next floor's first room. +void Level::myosotis_pickups_collect() +{ + constexpr std::array MYOSOTIS_LEFT = {PICKUP_BED, PICKUP_TROPHY, PICKUP_BIGCHEST, PICKUP_THROWABLEBOMB, + PICKUP_MOMSCHEST, PICKUP_COLLECTIBLE, PICKUP_SHOPITEM}; + for (RoomDescriptor& room : roomList) + { + if (!room.data || room.visitedCount == 0) continue; + for (const EntitySaveState& saved : room.savedEntities) + { + bool isLoose = saved.type == ENTITY_PICKUP && saved.intStorage3 == 0 && !Entity_Pickup::IsChest(saved.variant); + if (isLoose && std::ranges::find(MYOSOTIS_LEFT, saved.variant) == MYOSOTIS_LEFT.end()) myosotisPickups.push_back(saved); + } + } +} + // 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) @@ -415,7 +420,7 @@ void Level::Init(bool isResetLilPortalRoom) game.gameStateFlags &= ~(1ull << LEVEL_GAME_STATE_MAX_COINS_OBTAINED); myosotisPickups.clear(); - if (isMyosotis) reconstruction_missing("Level::Init 00744940: Myosotis's pickups need EntitySaveState's fields"); + if (isMyosotis) myosotis_pickups_collect(); currentRoomMap = roomMap.data(); isLevelGenerating = true; @@ -433,7 +438,7 @@ void Level::Init(bool isResetLilPortalRoom) uint32_t stageSeed = game.seedEffects.GetStageSeed((int)effectiveStage); - generationRNG.SetSeed(stageSeed, GENERATION_SHIFT_INDEX); + generationRNG.SetSeed(stageSeed, DEFAULT_SHIFT_INDEX); devilAngelRoomRNG.SetSeed(stageSeed, DEVIL_ANGEL_SHIFT_INDEX); generationRNG.Next(); if (game.challenge == CHALLENGE_RED_REDEMPTION) InitStageSeeds(); @@ -467,7 +472,7 @@ void Level::Init(bool isResetLilPortalRoom) RNG curseRng{}; - curseRng.SetSeed(generationRNG._seed, GENERATION_SHIFT_INDEX); + curseRng.SetSeed(generationRNG._seed, DEFAULT_SHIFT_INDEX); bool isCurseRolled = stage != STAGE_HOME && !IsAscent() && curseOdds != 0 && !game.playerManager.FirstCollectibleOwner(COLLECTIBLE_BLACK_CANDLE, LAZARUS_SHARE_CHECK) && game.dailyChallenge._specialDailyId != SPECIAL_DAILY_NO_CURSES; @@ -1254,7 +1259,7 @@ static bool boss_rooms_place(SpecialRoomPlacement& placement) return false; if (!(bossRoom = generator.place_boss_room(config->shape, config->doors, BOSS_ROOM_NEXT))) return false; boss_room_commit(level, *bossRoom, config); - level.generationRNG.SetSeed(savedSeed, GENERATION_SHIFT_INDEX); + level.generationRNG.SetSeed(savedSeed, DEFAULT_SHIFT_INDEX); } if (bossRoom) generator.block_room_area(*bossRoom); return true; @@ -1403,7 +1408,7 @@ static bool treasure_rooms_place(SpecialRoomPlacement& placement) if (crown_multiplier_get(level) >= 3) desc->displayFlags |= ROOM_DISPLAY_ICON; if (i == 0) firstSeed = level.generationRNG._seed; } - level.generationRNG.SetSeed(firstSeed, GENERATION_SHIFT_INDEX); + level.generationRNG.SetSeed(firstSeed, DEFAULT_SHIFT_INDEX); return true; } @@ -2732,12 +2737,6 @@ void Level::generate_backwards() reconstruction_missing("Level::generate_backwards 00742ef0"); } -// (00743550, 0074378b, 00743fc3) Lays out a Greed floor. -void Level::generate_greed() -{ - reconstruction_missing("Level::generate_greed 00743550"); -} - // 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 @@ -2817,10 +2816,69 @@ void Level::generate_blue_womb() off_map_room_init(*this, ROOM_ANGEL_SHOP_IDX, generationRNG, room_query(STAGE_ID_SPECIAL_ROOMS, ROOM_ANGEL, 1)); } -// 0074de30 Lays out Home. +// Home's rooms (all of type default, told apart by subtype): Isaac's bedroom, the hallway, Mom's bedroom, the other +// hallway, the living room and the closet. +struct HomeRoom +{ + XY position; + RoomShape shape = ROOMSHAPE_1x1; + XY linkPos; + int connectDirection = DIRECTION_NONE; + RoomShape configShape = ROOMSHAPE_1x1; + int subtype = 0; +}; + +constexpr std::array HOME_ROOMS = {{ + {{6, 6}, ROOMSHAPE_1x1, XY_NONE, DIRECTION_NONE, ROOMSHAPE_1x1, 0}, + {{6, 7}, ROOMSHAPE_1x2, {6, 7}, DIRECTION_DOWN, ROOMSHAPE_IIV, 1}, + {{5, 8}, ROOMSHAPE_1x2, {5, 8}, DIRECTION_LEFT, ROOMSHAPE_1x2, 3}, + {{4, 7}, ROOMSHAPE_1x2, {4, 8}, DIRECTION_LEFT, ROOMSHAPE_IIV, 1}, + {{4, 6}, ROOMSHAPE_1x1, {4, 6}, DIRECTION_UP, ROOMSHAPE_1x1, 2}, + {{7, 7}, ROOMSHAPE_IH, {7, 7}, DIRECTION_RIGHT, ROOMSHAPE_IH, 10}, +}}; +constexpr size_t HOME_LAST_BOSS_ROOM = 2; +constexpr int BEAST_ROOM_VARIANT = 666; + +// 0074de30 Lays out Home by hand from its own rooms, Mom's bedroom counted the last boss room. Off the map, the error +// room, black market and crawl space from the generation RNG, and the Beast's crawl space as the secret exit. void Level::generate_home_level() { - reconstruction_missing("Level::generate_home_level 0074de30"); + RoomConfig& roomConfig = g_game->roomConfig; + LevelGenerator generator(generationRNG.Next()); + std::array configs{}; + + for (const HomeRoom& room : HOME_ROOMS) + { + LevelGenerator_Room slot; + slot.linkPos = room.linkPos; + slot.position = room.position; + slot.shape = room.shape; + slot.connectDirection = room.connectDirection; + generator.CreateRoom(slot); + } + for (size_t i = 0; i < HOME_ROOMS.size(); i++) + { + RoomQuery query = room_query(STAGE_ID_HOME, ROOM_DEFAULT, HOME_ROOMS[i].subtype); + query.shape = HOME_ROOMS[i].configShape; + configs[i] = random_room_get(generationRNG.Next(), query); + } + + roomMap.fill(-1); + nbRooms = 0; + for (size_t i = 0; i < HOME_ROOMS.size(); i++) + { + place_room(generator.rooms[i], configs[i], generationRNG.Next(), nullptr); + if (i == HOME_LAST_BOSS_ROOM) lastBossRoomListIdx = nbRooms - 1; + } + + 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)); + RoomDescriptor& beast = *GetRoomByIdx(ROOM_SECRET_EXIT_IDX); + beast.InitSeeds(generationRNG); + beast.data = + roomConfig.GetRoomByStageTypeAndVariant(STAGE_ID_HOME, ROOM_DUNGEON, BEAST_ROOM_VARIANT, ROOM_MODE_CURRENT); } // 007508c0 Lays out a Red Redemption floor. @@ -3148,8 +3206,8 @@ Vector Level::GetEnterPosition() return vector_make(lastRoomIdx == ROOM_BLACK_MARKET_IDX ? BLACK_MARKET_EXIT_X : DUNGEON_EXIT_X, DUNGEON_EXIT_Y); } if (currentRoomIdx == ROOM_SECRET_SHOP_IDX) return vector_make(SECRET_SHOP_ENTRY_X, SECRET_SHOP_ENTRY_Y); - if (currentRoomIdx == ROOM_OFF_MAP_14_IDX) return vector_make(OFF_MAP_14_ENTRY_X, OFF_MAP_14_ENTRY_Y); - if (currentRoomIdx == ROOM_OFF_MAP_15_IDX) return vector_make(OFF_MAP_15_ENTRY_X, OFF_MAP_15_ENTRY_Y); + if (currentRoomIdx == ROOM_ROTGUT_DUNGEON1_IDX) return vector_make(ROTGUT_DUNGEON1_ENTRY_X, ROTGUT_DUNGEON1_ENTRY_Y); + if (currentRoomIdx == ROOM_ROTGUT_DUNGEON2_IDX) return vector_make(ROTGUT_DUNGEON2_ENTRY_X, ROTGUT_DUNGEON2_ENTRY_Y); if (currentRoomIdx >= 0 && currentRoomIdx == dungeonReturnRoomIndex) { RoomDescriptor* last = GetRoomByIdx(lastRoomIdx); @@ -3228,10 +3286,27 @@ void Level::update_treasure_room_doors_for_trinket() game.UpdateVisibility(); } -// 0074beb0 Sets up Rotgut's room. +// 0074beb0 Draws Rotgut's two dungeon rooms (dungeon subtypes 2 and 3) from the stage's seed, each once. void Level::init_rotgut_dungeon_room() { - reconstruction_missing("Level::init_rotgut_dungeon_room 0074beb0"); + constexpr int ROTGUT_FIRST_SUBTYPE = 2; + constexpr uint32_t ROTGUT_RNG_SHIFT1 = 5; + constexpr uint32_t ROTGUT_RNG_SHIFT2 = 27; + constexpr uint32_t ROTGUT_FIRST_SHIFT = 8; + constexpr uint32_t ROTGUT_SECOND_SHIFT = 21; + bool isAltStage = stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B; + uint32_t seed = g_game->seedEffects.GetStageSeed(isAltStage ? stage + 1 : stage); + + for (int i = 0; i < 2; i++) + { + RoomDescriptor& desc = *GetRoomByIdx(ROOM_ROTGUT_DUNGEON1_IDX - i); + if (desc.data) continue; + + RNG rng = {seed, ROTGUT_RNG_SHIFT1, ROTGUT_RNG_SHIFT2, i == 0 ? ROTGUT_FIRST_SHIFT : ROTGUT_SECOND_SHIFT}; + desc.InitSeeds(rng); + RoomQuery query = {.stageId = 0, .subtype = ROTGUT_FIRST_SUBTYPE + i, .type = ROOM_DUNGEON}; + desc.data = g_game->roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + } } // 008e11b0 Sets up Genesis's room. @@ -3536,7 +3611,7 @@ bool Level::UpdateBackwardsPathStages() for (Entity* entity : room->entityList.updateEL) { bool isCounted = (game.deathmatchManager.is_active() && entity->type == ENTITY_PLAYER) || - (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENEMY_TYPE_LAST); + (entity->type >= ENTITY_FIRST_ENEMY && entity->type <= ENTITY_LAST_ENEMY); if (isCounted && entity->CanShutDoors() && !entity->isDead && !entity->HasEntityFlags(FLAG_NO_TARGET)) health += entity->health; } diff --git a/src/level.h b/src/level.h index 9039149..f8bf78e 100644 --- a/src/level.h +++ b/src/level.h @@ -17,8 +17,9 @@ constexpr int ROOM_MAP_CELLS = DIMENSION_COUNT * LEVEL_GRID_CELLS; constexpr int OFF_MAP_ROOM_COUNT = 20; constexpr int ROOM_DESCRIPTOR_COUNT = ROOM_MAP_CELLS + OFF_MAP_ROOM_COUNT; constexpr int GREED_WAVE_SEED_COUNT = 12; -// Greed mode's boss wave, one later in Greedier. +// Greed mode's boss wave, one later in Greedier, and its normal waves, one more in Greedier. constexpr int GREED_BOSS_WAVE = 9; +constexpr int GREED_WAVES = 10; constexpr int VENTRICLE_RAZOR_PORTAL_COUNT = 2; constexpr int PORTAL_ROOM_NONE = -99999; @@ -60,6 +61,8 @@ enum OffMapRoom : int ROOM_GIDEON_DUNGEON_IDX = -11, ROOM_GENESIS_IDX = -12, ROOM_SECRET_SHOP_IDX = -13, + ROOM_ROTGUT_DUNGEON1_IDX = -14, + ROOM_ROTGUT_DUNGEON2_IDX = -15, ROOM_BLUE_ROOM_IDX = -16, ROOM_EXTRA_BOSS_IDX = -17, ROOM_ANGEL_SHOP_IDX = -18, @@ -79,6 +82,7 @@ enum LevelStateFlag : int LEVEL_STATE_COMPASS_EFFECT = 7, LEVEL_STATE_MAP_EFFECT = 8, LEVEL_STATE_BLUE_MAP_EFFECT = 9, + LEVEL_STATE_GREED_LOST_PENALTY = 11, LEVEL_STATE_GREED_MONSTRO_SPAWNED = 12, LEVEL_STATE_DUNGEON_ROCK_BROKEN = 13, LEVEL_STATE_MAMA_MEGA = 14, @@ -116,8 +120,9 @@ enum StageType : uint32_t STAGETYPE_REPENTANCE_B }; -// Home's night stage type. +// Home's night stage type, and the last floor the Ascent walks back up. constexpr int STAGE_TYPE_HOME_NIGHT = 1; +constexpr uint32_t ASCENT_LAST_STAGE = 6; // A floor's depth (Lua's LevelStage), from Basement I to Home. Greed mode counts its own floors, its shop the sixth. enum LevelStage : int @@ -251,6 +256,7 @@ public: bool isLevelGenerating = false; void Init(bool isResetLilPortalRoom); + void myosotis_pickups_collect(); void reset_room_list(bool isResetLilPortalRoom); void lil_portal_room_init(); void generate_dungeon(RNG& curseRng); diff --git a/src/level_generator.cpp b/src/level_generator.cpp index 17f92fb..86cd062 100644 --- a/src/level_generator.cpp +++ b/src/level_generator.cpp @@ -1,5 +1,6 @@ #include "level_generator.h" #include "platform.h" +#include "seeds.h" #include #include #include @@ -11,7 +12,6 @@ struct ShapeSpot RoomShape shape; }; -constexpr uint32_t GENERATION_SHIFT_INDEX = 35; constexpr int SHAPE_SPOT_COUNT = 13; constexpr int RESIZE_SPOT_COUNT = SHAPE_SPOT_COUNT + 1; constexpr int START_BRANCHES_MIN = 2; @@ -122,7 +122,7 @@ template static void elements_shuffle(RNG& rng, std::vector& ele LevelGenerator::LevelGenerator(uint32_t seed) { roomMap.fill(-1); - rng.SetSeed(seed, GENERATION_SHIFT_INDEX); + rng.SetSeed(seed, DEFAULT_SHIFT_INDEX); } // 009adbb0 Grows a layout of settings.roomCount rooms past the start, adds up to five dead ends while short of diff --git a/src/level_stage.cpp b/src/level_stage.cpp index 5f72ed3..d2b3b23 100644 --- a/src/level_stage.cpp +++ b/src/level_stage.cpp @@ -7,7 +7,6 @@ #include constexpr int STAGE_ROLLED_LAST = 9; -constexpr int ASCENT_STAGE_LAST = 6; constexpr int GRID_ROOM_BLUE_WOMB = -8; constexpr int GRID_ROOM_THE_VOID = -9; @@ -143,7 +142,7 @@ void Level::SetNextStage() int nextStage = 0; int nextStageType = stageType; - if (stage >= 1 && (int)stage <= ASCENT_STAGE_LAST && game.GetStateFlag(GAME_STATE_BACKWARDS_PATH)) + if (stage >= 1 && stage <= ASCENT_LAST_STAGE && game.GetStateFlag(GAME_STATE_BACKWARDS_PATH)) return ascent_stage_set(*this); if (game.IsGreedMode()) diff --git a/src/lua_api_game.cpp b/src/lua_api_game.cpp index 9e23c5d..4ee9cc1 100644 --- a/src/lua_api_game.cpp +++ b/src/lua_api_game.cpp @@ -191,6 +191,14 @@ static void game_effects_register(lua_State* state) lua_method(state, "ShowRule", [](Game&) { fortune_show(FORTUNE_RULES); }); } +// (00893df0, 008ba960) Lua's Game:SpawnEntityDesc reads its description as a class the game never registers, so no +// script can pass one: a nil fails at once, anything else fails the class check (which in the original reads the +// missing class's table and breaks). Both raise the argument error here. entity_desc_spawn does the spawning. +static int game_entity_desc_spawn(lua_State* state) +{ + return luaL_argerror(state, 2, lua_pushfstring(state, "EntityDesc expected, got %s", luaL_typename(state, 2))); +} + // (00704f20, 006f9770) Registers how Game moves the run on: its frame and draw, room and floor changes, rerolls, // the ending and the next victory lap. // The original hands StartStageTransition a player from its stack. Here it has none. @@ -213,8 +221,8 @@ static void game_flow_register(lua_State* state) reconstruction_missing("Game::RerollEnemy 007050c0"); return false; }); - lua_method(state, "SpawnEntityDesc", - [](Game&, LuaIgnored, Vector, Entity*) { reconstruction_missing("Game::SpawnEntityDesc 006fece0"); }); + lua_pushcfunction(state, game_entity_desc_spawn); + lua_table_set(state, -2, "SpawnEntityDesc"); lua_method(state, "End", [](Game&, GameEnding ending) { game_end(ending); }); lua_method(state, "FinishChallenge", [](Game&) { challenge_finish(); }); lua_method(state, "NextVictoryLap", [](Game&) { reconstruction_missing("Game::NextVictoryLap 006f7ac0"); }); diff --git a/src/lua_callbacks.cpp b/src/lua_callbacks.cpp index 4a01379..0b2e38e 100644 --- a/src/lua_callbacks.cpp +++ b/src/lua_callbacks.cpp @@ -11,7 +11,6 @@ #include "entity_projectile.h" #include "entity_tear.h" #include "game.h" -#include "log.h" #include "lua_api.h" #include "room_config.h" @@ -26,12 +25,6 @@ struct CallbackRun int param = CALLBACK_PARAM_NONE; }; -// Stops where a mod has a function for a callback LuaEngine does not run yet. -void lua_callback_check(LuaCallback callback, const char* name) -{ - if (lua_engine_get().enabledCallbacks[callback]) reconstruction_missing(name); -} - // Calls _RunCallback with a callback's id, its filter parameter and its arguments when a mod added a function for it, // leaving its one result on the stack. Whether it ran, false without a function or on an error, which is logged. // The callers, result readers and error throws the original instantiates per callback are this and its readers diff --git a/src/lua_callbacks.h b/src/lua_callbacks.h index 2b502f9..0b1df9b 100644 --- a/src/lua_callbacks.h +++ b/src/lua_callbacks.h @@ -125,5 +125,3 @@ struct LuaItemUse bool isDischarge = false; bool isRemove = false; }; - -void lua_callback_check(LuaCallback callback, const char* name); diff --git a/src/lua_engine.cpp b/src/lua_engine.cpp index 59bbfcc..aa3fdbb 100644 --- a/src/lua_engine.cpp +++ b/src/lua_engine.cpp @@ -24,7 +24,6 @@ constexpr const char* PATH_SEPARATORS = "/\\"; constexpr const char* RUN_CALLBACK = "_RunCallback"; constexpr const char* UNLOAD_MOD = "_UnloadMod"; -constexpr uint64_t NS_PER_MS = 1000000; constexpr int API_VERSION_NONE = -1; constexpr int API_VERSION_CURRENT = 1; constexpr int GC_COOLDOWN_FRAMES = 600; diff --git a/src/manager.cpp b/src/manager.cpp index 839391d..5166ecd 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -49,7 +49,6 @@ constexpr std::string_view LANGUAGE_UNKNOWN = "XX"; constexpr int LANGUAGE_DEFAULT = 0; constexpr uint32_t CUTSCENE_INTRO = 1; -constexpr uint32_t CUTSCENE_CREDITS = 2; constexpr uint32_t CUTSCENE_COUNT = 27; constexpr int MENU_STATE_TITLE = 1; @@ -57,7 +56,6 @@ constexpr float SCREEN_WIDTH = 480; constexpr float SCREEN_HEIGHT = 270; constexpr int DEFAULT_STAGE = 1; constexpr float SFX_VOLUME_MODIFIER_STEP = 0.005f; -constexpr uint64_t NS_PER_MS = 1000000; // The shader Manager::Init needs loaded to keep the water surface option on. constexpr const char* WATER_SURFACE_V1_SHADER = "WaterSurface"; @@ -158,9 +156,6 @@ constexpr const char* CJK_SMALL_FONT = "font/CJK/LanaPixel.fnt"; constexpr const char* TEAM_MEAT_10_FONT = "font/TeamMeatEx/TeamMeatEx10.fnt"; constexpr const char* TEAM_MEAT_12_FONT = "font/TeamMeatEx/TeamMeatEx12.fnt"; constexpr const char* TEAM_MEAT_16_FONT = "font/TeamMeatEx/TeamMeatEx16.fnt"; -constexpr int LANGUAGE_JAPANESE = 2; -constexpr int LANGUAGE_KOREAN = 11; -constexpr int LANGUAGE_CHINESE = 13; constexpr uint32_t MISSING_CHARACTER = '?'; // challenges.xml: its root, the version it must have, the fixed challenge slots and the list separator. diff --git a/src/menu_character.cpp b/src/menu_character.cpp index 2dee77e..b706c1d 100644 --- a/src/menu_character.cpp +++ b/src/menu_character.cpp @@ -1,4 +1,5 @@ #include "menu_character.h" +#include "entity_player.h" #include "fx_layers.h" #include "game.h" #include "kage_input.h" @@ -116,7 +117,6 @@ constexpr int MARK_HARD = 2; constexpr int MARK_ONLINE_NORMAL = 4; constexpr int MARK_ONLINE_HARD = 8; -constexpr int PLAYER_EDEN = 9; constexpr int PLAYER_TAINTED_EDEN = 30; constexpr int MENU_ID_RANDOM = 0; constexpr int MENU_ID_EDEN = 10; diff --git a/src/menu_controller_select.cpp b/src/menu_controller_select.cpp index c104b92..ce1e775 100644 --- a/src/menu_controller_select.cpp +++ b/src/menu_controller_select.cpp @@ -10,7 +10,6 @@ constexpr size_t NAME_MAX_LENGTH = 18; constexpr size_t NAME_CUT_LENGTH = 16; constexpr size_t ENTRY_LIMIT = 6; constexpr int CURSOR_LAYER = 2; -constexpr int LANGUAGE_ENGLISH = 0; constexpr float LIST_X = 265; constexpr float LIST_Y = 60; constexpr float ROW_HEIGHT = 20; diff --git a/src/menu_daily_challenge.cpp b/src/menu_daily_challenge.cpp index 2dcaa19..e3889dc 100644 --- a/src/menu_daily_challenge.cpp +++ b/src/menu_daily_challenge.cpp @@ -24,7 +24,6 @@ constexpr int CURSOR_LAYER = 5; constexpr int SKETCH_PAPER_LAYER = 11; constexpr int POPUP_PICTURE_LAYER = 2; constexpr float BUTTON_HIDDEN = 96; -constexpr int LANGUAGE_ENGLISH = 0; // Where the texts sit: the player's name shrunk to fit its width, the countdown, and the streaks scaled down. diff --git a/src/menu_manager.cpp b/src/menu_manager.cpp index 3f23915..d074d2c 100644 --- a/src/menu_manager.cpp +++ b/src/menu_manager.cpp @@ -54,7 +54,6 @@ constexpr float OVERLAY_BLEED = 0.5f; constexpr uint32_t MENU_BACKGROUND_ARGB = 0xffccbebb; constexpr float CHANNEL_MAX = 255; constexpr int CLAMP_TO_EDGE = 1; -constexpr int FILTER_LINEAR = 1; constexpr int KEY_REPEAT_DELAY = 49; constexpr int KEY_REPEAT_INTERVAL = 10; constexpr int CHARACTER_MENU_SHOWN = 1; diff --git a/src/menu_special_seeds.cpp b/src/menu_special_seeds.cpp index 21ece7a..eccb1cd 100644 --- a/src/menu_special_seeds.cpp +++ b/src/menu_special_seeds.cpp @@ -33,7 +33,6 @@ constexpr int PAPER_LAST_PIECE = 4; constexpr uint32_t PAPER_SEED = 0xb00b135; constexpr uint32_t CHECKMARK_SEED = 0x512578; constexpr uint32_t CHECKMARK_FRAMES = 3; -constexpr uint32_t DEFAULT_SHIFT_INDEX = 35; // Where a line's parts sit: its text from the line's place, the checkmark, cursor and no achievement icon from the // text, and how far down each kind of line pushes the next. @@ -66,9 +65,6 @@ constexpr float CHALLENGE_VIEW_Y = -216; constexpr int KEY_REPEAT_DELAY = 29; constexpr int KEY_REPEAT_INTERVAL = 5; constexpr int DYSLEXIA_TIME = 30; -constexpr int LANGUAGE_ENGLISH = 0; -constexpr int LANGUAGE_JAPANESE = 2; -constexpr int LANGUAGE_KOREAN = 11; // What string_scramble_seeded does at each character, by a draw out of 15: swap with the next or the one before, // drop it, or put a random letter or a space before it. Any other draw keeps it. diff --git a/src/mod_manager.cpp b/src/mod_manager.cpp index 10d4ff5..7503af1 100644 --- a/src/mod_manager.cpp +++ b/src/mod_manager.cpp @@ -67,7 +67,6 @@ constexpr KAGE::Graphics::VertexAttribute MOD_SHADER_ATTRIBUTES[] = { {"RenderData", KAGE::Graphics::VERTEX_VEC4}, {"Scale", KAGE::Graphics::VERTEX_FLOAT}}; // The wrap mode that clamps texture coordinates to the edge. -constexpr int WRAP_CLAMP = 1; // The floats of the sprite vertex before RenderData: position, color and texture coordinates. constexpr int SHADER_RENDER_DATA_OFFSET = 9; constexpr int CALLBACK_PARAM_NONE = -1; diff --git a/src/music_manager.h b/src/music_manager.h index 280e260..ac8963d 100644 --- a/src/music_manager.h +++ b/src/music_manager.h @@ -67,6 +67,7 @@ enum MusicId : int MUSIC_BOSS_RUSH = 39, MUSIC_JINGLE_BOSS_RUSH_OUTRO = 40, MUSIC_BOSS3 = 41, + MUSIC_JINGLE_BOSS_OVER3 = 42, MUSIC_MOTHER_BOSS = 43, MUSIC_DOGMA_BOSS = 44, MUSIC_BEAST_BOSS = 45, @@ -76,12 +77,15 @@ enum MusicId : int MUSIC_TITLE_REPENTANCE = 63, MUSIC_REVERSE_GENESIS_START = 64, MUSIC_HUSH_TRANSITION = 65, + MUSIC_DOGMA_INTRO = 67, MUSIC_JINGLE_STRANGE_DOOR = 68, MUSIC_ECHOES_REVERSE = 69, + MUSIC_JINGLE_BOSS_OVER = 83, MUSIC_JINGLE_SECRET_ROOM_FIND = 85, MUSIC_TREASURE_JINGLE_FIRST = 87, MUSIC_JINGLE_CHALLENGE_OUTRO = 92, MUSIC_GAME_START_JINGLE = 95, + MUSIC_JINGLE_BOSS_OVER2 = 97, MUSIC_VOID_BOSS = 103, MUSIC_DOWNPOUR = 104, MUSIC_DOWNPOUR_REVERSED = 114, diff --git a/src/npc_adult_leech.cpp b/src/npc_adult_leech.cpp new file mode 100644 index 0000000..11db948 --- /dev/null +++ b/src/npc_adult_leech.cpp @@ -0,0 +1,397 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "room_grid.h" +#include + +// The Adult Leech's states: crawling, crossing the room (Rotgut's), burrowing, surfacing under its target, lunging +// sideways, charging and its charge's hit. +constexpr int ADULT_LEECH_CRAWL = NPC_STATE_IDLE; +constexpr int ADULT_LEECH_CROSS = NPC_STATE_SUICIDE; +constexpr int ADULT_LEECH_BURROW = NPC_STATE_JUMP; +constexpr int ADULT_LEECH_SURFACE = NPC_STATE_STOMP; +constexpr int ADULT_LEECH_LUNGE = NPC_STATE_ATTACK; +constexpr int ADULT_LEECH_CHARGE = NPC_STATE_ATTACK2; +constexpr int ADULT_LEECH_CHARGE_HIT = NPC_STATE_ATTACK3; + +constexpr ColorMod ADULT_LEECH_BLOOD_COLOR = {{1, 1, 1, 1}, {2.4f, 0.7f, 0.7f, 1}, {0, 0, 0}}; +constexpr float ADULT_LEECH_FRICTION = 0.8f; +constexpr float ADULT_LEECH_LUNGE_FRICTION = 0.86f; +constexpr float ADULT_LEECH_SPEED = 0.7f; +constexpr float ADULT_LEECH_TURN_SPREAD = 90; +constexpr uint32_t ADULT_LEECH_TURN_ODDS = 30; +constexpr uint64_t ADULT_LEECH_HELD_FLAGS = FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK; + +// Its attacks: a burrow below two thirds health (one in three while its target is off its row), resurfacing under +// it after 30 frames one in 15, and a lunge one in three when lined up within 30. +constexpr float ADULT_LEECH_ROW = 80; +constexpr float ADULT_LEECH_BURROW_HEALTH = 0.66f; +constexpr uint32_t ADULT_LEECH_ATTACK_ODDS = 3; +constexpr float ADULT_LEECH_LUNGE_ROW = 30; +constexpr float ADULT_LEECH_LUNGE_START = 0.5f; +constexpr float ADULT_LEECH_BURROW_PULL = 0.3f; +constexpr int ADULT_LEECH_SURFACE_WAIT = 30; +constexpr uint32_t ADULT_LEECH_SURFACE_ODDS = 15; +constexpr float ADULT_LEECH_SURFACE_CHASE = 0.8f; +constexpr float ADULT_LEECH_SURFACE_PULL = 0.7f; +constexpr int ADULT_LEECH_SURFACE_SHAKE = 12; +constexpr float ADULT_LEECH_SPLASH_HEIGHT = -14; +constexpr float ADULT_LEECH_RING_FALL = -0.02f; +constexpr float ADULT_LEECH_RING_SPEED = 8; +constexpr float ADULT_LEECH_RING_SHOTS = 10; + +// The lunge and crossing: sideways, drifting toward the target's row (10 either side) at up to 2, speeding up by 0.2 to +// 5; a crosser leaves 80 beyond the walls. A lunge bounces off walls hit over 10 with a splash and a ring of 12. +constexpr float ADULT_LEECH_CROSS_START = 2; +constexpr float ADULT_LEECH_ROW_MARGIN = 10; +constexpr float ADULT_LEECH_ROW_DRIFT = 0.12f; +constexpr float ADULT_LEECH_DRIFT_MAX = 2; +constexpr float ADULT_LEECH_SPEED_UP = 0.2f; +constexpr float ADULT_LEECH_SPEED_MAX = 5; +constexpr float ADULT_LEECH_EXIT_MARGIN = 80; +constexpr float ADULT_LEECH_FAR = 500; +constexpr float ADULT_LEECH_BOUNCE_SPEED = 10; +constexpr float ADULT_LEECH_BOUNCE_FACING = 0.6f; +constexpr float ADULT_LEECH_BOUNCE_PUSH = 2.5f; +constexpr int ADULT_LEECH_BOUNCE_REST = 12; +constexpr int ADULT_LEECH_BOUNCE_SHAKE = 6; +constexpr float ADULT_LEECH_BOUNCE_REACH = 14; +constexpr float ADULT_LEECH_BOUNCE_SPLASH_DEPTH = 5; +constexpr float ADULT_LEECH_BOUNCE_FALL = 0.08f; +constexpr float ADULT_LEECH_BOUNCE_SHOT_REACH = 8; +constexpr float ADULT_LEECH_BOUNCE_SPEED_SHOT = 10; +constexpr float ADULT_LEECH_BOUNCE_SHOTS = 12; + +// The charge: at 3.8 until it stalls 10 frames, or a wall hit with a splash and 12 shots, then knocked back 5. +constexpr float ADULT_LEECH_CHARGE_SPEED = 3.8f; +constexpr float ADULT_LEECH_CHARGE_STALL = 3; +constexpr int ADULT_LEECH_CHARGE_STALL_FRAMES = 10; +constexpr int ADULT_LEECH_CHARGE_SHOTS = 12; +constexpr float ADULT_LEECH_CHARGE_KNOCK = 5; +constexpr float ADULT_LEECH_SPLAT_SIZE = 0.5f; +constexpr float ADULT_LEECH_SPLAT_SIZE_RANGE = 1.4f; + +// Its death: three blood bursts about it, 80 wide and 30 deep, lifted 10 to 50. +constexpr int ADULT_LEECH_DEATH_BURSTS = 3; +constexpr float ADULT_LEECH_DEATH_WIDTH = 80; +constexpr float ADULT_LEECH_DEATH_DEPTH = 30; +constexpr float ADULT_LEECH_DEATH_LIFT = -10; +constexpr float ADULT_LEECH_DEATH_LIFT_RANGE = 40; + +// 004d8f20 A crawling heading: up to 45 degrees off the horizontal, either way, and half the time turned toward its +// target's row. +static Vector adult_leech_heading(Entity& target, Vector position) +{ + Vector heading = vector_from_angle((random_unit() - HALF) * ADULT_LEECH_TURN_SPREAD); + if ((Random() & 1) == 0) heading.x = -heading.x; + if ((Random() & 1) != 0) return heading; + bool isAway = (heading.y < 0 && position.y < target.pos.y) || (heading.y > 0 && target.pos.y < position.y); + if (isAway) heading.y = -heading.y; + return heading; +} + +// The drift toward the target's row while moving sideways at the speed v2.y. +static float leech_row_drift(Entity_NPC& npc, float settled) +{ + float targetY = npc.GetPlayerTarget()->pos.y; + float drift = settled; + if (targetY > npc.pos.y + ADULT_LEECH_ROW_MARGIN) drift = ADULT_LEECH_ROW_DRIFT; + else if (targetY < npc.pos.y - ADULT_LEECH_ROW_MARGIN) drift = -ADULT_LEECH_ROW_DRIFT; + return std::clamp(npc.v2.y * drift, -ADULT_LEECH_DRIFT_MAX, ADULT_LEECH_DRIFT_MAX); +} + +// Crawling: toward its target when charmed or forced, away when afraid, else on a heading it turns one in 30 frames +// (out of a block toward free ground), then a burrow or a lunge. +static void leech_crawl_update(Entity_NPC& npc, Room& room) +{ + if (npc.i1 >= 1) + { + npc.i1 -= npc_ticks_get(npc); + npc.friction *= 0.9f; + return; + } + npc.friction *= ADULT_LEECH_FRICTION; + Vector& heading = npc.pathfinder.moveDirection; + if (npc.HasEntityFlags(FLAG_CHARM) || npc.forcedTarget) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), ADULT_LEECH_SPEED, 0, DIRECT_PATH_FAR); + else if (npc.HasEntityFlags(FLAG_FEAR)) npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + else + { + if (vector_is_zero(heading)) heading = adult_leech_heading(*npc.GetPlayerTarget(), npc.pos); + npc_push(npc, vector_scale(heading, ADULT_LEECH_SPEED)); + if (room_grid_collision_at(npc.pos) == COLLISION_NONE) + { + if (Random() % ADULT_LEECH_TURN_ODDS == 0) heading = adult_leech_heading(*npc.GetPlayerTarget(), npc.pos); + if (npc.isCollidesWithGrid) heading = vector_scale(heading, -1); + } + else if (Random() % ADULT_LEECH_TURN_ODDS == 0) + heading = vector_normalized(vector_sub(room_free_pickup_position_find({.position = npc.pos}), npc.pos)); + } + npc.sprite.Play("MoveHori"); + npc.sprite.isFlipX = npc.velocity.x < 0; + if (npc.HasEntityFlags(ADULT_LEECH_HELD_FLAGS)) return; + + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + bool isInRow = std::abs(toward.y) <= std::abs(toward.x) && std::abs(toward.y) <= ADULT_LEECH_ROW; + bool isBurrow = npc.stateFrame < 0 && !isInRow && npc.health / npc.maxHitPoints < ADULT_LEECH_BURROW_HEALTH && + Random() % ADULT_LEECH_ATTACK_ODDS == 0 && room_grid_collision_at(npc.pos) == COLLISION_NONE; + if (isBurrow) + { + npc.stateFrame = 0; + npc.state = ADULT_LEECH_BURROW; + npc.targetPosition = room.GetGridPosition(room.GetGridIndex(npc.pos)); + return; + } + if (Random() % ADULT_LEECH_ATTACK_ODDS != 0 || std::abs(toward.y) >= ADULT_LEECH_LUNGE_ROW) return; + npc.PlaySound(SOUND_BIG_LEECH, 1, 10, false, 1); + npc.targetPosition = vector_make(toward.x > 0 ? 1.0f : -1.0f, 0); + npc.state = ADULT_LEECH_LUNGE; + npc.v2.y = ADULT_LEECH_LUNGE_START; +} + +// Crossing the room for Rotgut: sideways and speeding up, gone 80 past the far wall. +static void leech_cross_update(Entity_NPC& npc) +{ + npc.v2.y = std::max(npc.v2.y, ADULT_LEECH_CROSS_START); + npc.friction *= ADULT_LEECH_LUNGE_FRICTION; + npc.sprite.Play("MoveHori"); + float direction = npc.targetPosition.x; + npc.sprite.isFlipX = direction < 0; + float drift = leech_row_drift(npc, npc.targetPosition.y); + if (npc.friction != 0) + { + npc.velocity.x = npc.speedMultiplier * direction * npc.v2.y / npc.friction + npc.velocity.x; + npc.velocity.y = drift * npc.speedMultiplier / npc.friction + npc.velocity.y; + } + npc.v2.y = std::min(npc.v2.y + ADULT_LEECH_SPEED_UP, ADULT_LEECH_SPEED_MAX); + Room& room = *g_game->room; + bool isOutRight = npc.velocity.x > 0 && npc.pos.x > room.bottomRightPos.x + ADULT_LEECH_EXIT_MARGIN; + bool isOutLeft = npc.velocity.x < 0 && npc.pos.x < room.topLeftPos.x - ADULT_LEECH_EXIT_MARGIN; + if (isOutRight || isOutLeft) npc.Remove(); +} + +// Burrowing into its cell, then resurfacing under its target after 30 frames, one in 15. +static void leech_burrow_update(Entity_NPC& npc) +{ + npc.friction = ADULT_LEECH_FRICTION; + npc.velocity = vector_add( + vector_scale(vector_sub(npc.targetPosition, npc.pos), ADULT_LEECH_BURROW_PULL / ADULT_LEECH_FRICTION), + npc.velocity); + npc.sprite.Play("Burrow"); + if (npc.sprite.IsEventTriggered("Sound")) npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + if (npc.sprite.IsEventTriggered("Hit")) + { + npc.PlaySound(SOUND_MAGGOT_ENTER_GROUND, 1, 2, false, 1); + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (npc.sprite.IsPlaying()) return; + + npc.stateFrame += npc_ticks_get(npc); + npc.targetPosition = {}; + npc.velocity = {}; + if (npc.stateFrame <= ADULT_LEECH_SURFACE_WAIT || Random() % ADULT_LEECH_SURFACE_ODDS != 0) return; + npc.state = ADULT_LEECH_SURFACE; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.pos = npc.GetPlayerTarget()->pos; + npc.stateFrame = 0; + npc.PlaySound(SOUND_BIG_LEECH, 1, 10, false, 1); +} + +// Moving toward its target position when it has one, else following its target (surfacing) or settling. +static void leech_hold(Entity_NPC& npc, float pull) +{ + if (vector_is_zero(npc.targetPosition)) + { + npc.friction *= pull; + return; + } + npc.friction *= ADULT_LEECH_SURFACE_PULL; + npc_push(npc, vector_sub(npc.targetPosition, npc.pos)); +} + +// Resurfacing: chasing its target underground, then bursting up with a splash and a ring of shots. +static void leech_surface_update(Entity_NPC& npc) +{ + npc.sprite.Play("ChargeDown"); + if (vector_is_zero(npc.targetPosition) && npc.entityGridCollisionClass == GRIDCOLL_GROUND) + npc.pathfinder.FindGridPath(npc.GetPlayerTarget()->pos, ADULT_LEECH_SURFACE_CHASE, 0, DIRECT_PATH_FAR); + else leech_hold(npc, ADULT_LEECH_FRICTION); + + if (npc.sprite.IsEventTriggered("Hit")) + { + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + game_shake_screen(ADULT_LEECH_SURFACE_SHAKE); + npc.PlaySound(SOUND_MEATY_DEATHS, 1, 2, false, 1); + npc.velocity = {}; + npc.targetPosition = npc.pos; + npc.entityCollisionClass = ENTCOLL_ALL; + blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH_BIG, npc.pos, vector_make(0, ADULT_LEECH_SPLASH_HEIGHT), + ADULT_LEECH_BLOOD_COLOR, {}); + ProjectileParams params; + params.fallingAccelModifier = ADULT_LEECH_RING_FALL; + npc.FireProjectiles(npc.pos, vector_make(ADULT_LEECH_RING_SPEED, ADULT_LEECH_RING_SHOTS), PROJECTILES_RING, + params); + } + if (npc.sprite.IsEventTriggered("Sound")) + { + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + npc.targetPosition = {}; + } + if (npc.sprite.IsPlaying()) return; + npc.state = ADULT_LEECH_CRAWL; + npc.targetPosition = {}; +} + +// A lunge's wall bounce: hit over 10 head on, it splashes, rings out 12 shots and rests 12 frames. +static void leech_bounce(Entity_NPC& npc) +{ + if (vector_length(npc.gridCollisionVelocity) <= ADULT_LEECH_BOUNCE_SPEED) return; + if (vector_dot(npc.gridCollisionNormal, vector_normalized(npc.gridCollisionVelocity)) <= ADULT_LEECH_BOUNCE_FACING) + return; + game_shake_screen(ADULT_LEECH_BOUNCE_SHAKE); + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + npc.velocity = vector_sub(npc.velocity, vector_scale(npc.gridCollisionNormal, ADULT_LEECH_BOUNCE_PUSH)); + npc.i1 = ADULT_LEECH_BOUNCE_REST; + Vector front = vector_add(vector_scale(npc.targetPosition, ADULT_LEECH_BOUNCE_REACH), npc.pos); + Entity* splash = blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH, front, vector_make(0, ADULT_LEECH_SPLASH_HEIGHT), + COLOR_DEFAULT, {}); + splash->renderDepthOffset = ADULT_LEECH_BOUNCE_SPLASH_DEPTH; + splash->SetColor(ADULT_LEECH_BLOOD_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + ProjectileParams params; + params.fallingAccelModifier = ADULT_LEECH_BOUNCE_FALL; + Vector from = vector_add(vector_scale(npc.targetPosition, ADULT_LEECH_BOUNCE_SHOT_REACH), npc.pos); + npc.FireProjectiles(from, vector_make(ADULT_LEECH_BOUNCE_SPEED_SHOT, ADULT_LEECH_BOUNCE_SHOTS), PROJECTILES_RING, + params); + npc.sprite.PlayOverlay("BounceOverlay", PLAY_FORCED); +} + +// The lunge: sideways along its target's row, speeding up while slow or near, until it meets a wall. +static void leech_lunge_update(Entity_NPC& npc) +{ + npc.friction *= ADULT_LEECH_LUNGE_FRICTION; + npc.sprite.Play("MoveHori"); + float direction = npc.targetPosition.x; + npc.sprite.isFlipX = direction < 0; + if (npc.HasEntityFlags(ADULT_LEECH_HELD_FLAGS) && !npc.isCollidesWithGrid) + { + npc.state = ADULT_LEECH_CRAWL; + npc.targetPosition = {}; + return; + } + if (npc.isCollidesWithGrid) + { + leech_bounce(npc); + npc.state = ADULT_LEECH_CRAWL; + npc.targetPosition = {}; + return; + } + + float targetX = npc.GetPlayerTarget()->pos.x; + float drift = leech_row_drift(npc, npc.targetPosition.y); + if (npc.friction != 0) + { + npc.velocity.x = direction * npc.v2.y * npc.speedMultiplier / npc.friction + npc.velocity.x; + npc.velocity.y = npc.speedMultiplier * drift / npc.friction + npc.velocity.y; + } + if (npc.v2.y < 1 || std::abs(npc.pos.x - targetX) < ADULT_LEECH_FAR) + npc.v2.y = std::min(npc.speedMultiplier * ADULT_LEECH_SPEED_UP + npc.v2.y, ADULT_LEECH_SPEED_MAX); +} + +// The charge: straight on at 3.8, stopping when stalled 10 frames, or slamming a wall with a splash and 12 shots. +static void leech_charge_update(Entity_NPC& npc) +{ + npc.friction *= ADULT_LEECH_LUNGE_FRICTION; + npc.sprite.Play("Charge"); + Vector direction = npc.targetPosition; + npc.sprite.isFlipX = direction.x < 0; + if (vector_length(npc.velocity) >= ADULT_LEECH_CHARGE_STALL) npc.stateFrame = 0; + else npc.stateFrame += npc_ticks_get(npc); + npc_push(npc, vector_scale(direction, ADULT_LEECH_CHARGE_SPEED)); + + if (npc.isCollidesWithGrid && vector_dot(npc.targetPosition, npc.gridCollisionNormal) > ADULT_LEECH_BOUNCE_FACING) + { + game_shake_screen(ADULT_LEECH_SURFACE_SHAKE); + npc.PlaySound(SOUND_MEATY_DEATHS, 1, 2, false, 1); + npc.velocity = {}; + npc.targetPosition = npc.pos; + // The original offsets the splash by its position times 14 (not its heading), as here. + Vector splashAt = vector_add(vector_scale(npc.pos, ADULT_LEECH_BOUNCE_REACH), npc.pos); + blood_explosion_spawn(BLOOD_EXPLOSION_SPLASH_BIG, splashAt, vector_make(0, ADULT_LEECH_SPLASH_HEIGHT), + ADULT_LEECH_BLOOD_COLOR, {}); + npc.FireBossProjectiles(ADULT_LEECH_CHARGE_SHOTS, {}, 0, ProjectileParams()); + npc.state = ADULT_LEECH_CHARGE_HIT; + } + else if (npc.stateFrame > ADULT_LEECH_CHARGE_STALL_FRAMES) + { + npc.state = ADULT_LEECH_CRAWL; + npc.targetPosition = {}; + } + if ((Random() & 1) == 0) npc.MakeSplat(random_unit() * ADULT_LEECH_SPLAT_SIZE_RANGE + ADULT_LEECH_SPLAT_SIZE); +} + +// The charge's hit: knocked back off the wall, then crawling again. +static void leech_charge_hit_update(Entity_NPC& npc) +{ + npc.sprite.Play("ChargeHit"); + if (npc.sprite.IsEventTriggered("Sound")) + { + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + npc.velocity.x += npc.sprite.isFlipX ? ADULT_LEECH_CHARGE_KNOCK : -ADULT_LEECH_CHARGE_KNOCK; + npc.targetPosition = {}; + } + leech_hold(npc, 0.9f); + if (npc.sprite.IsPlaying()) return; + npc.state = ADULT_LEECH_CRAWL; + npc.targetPosition = {}; +} + +// 004d9000 The Adult Leech: a big leech crawling about, lunging along its target's row, burrowing under it below +// two thirds health, and crossing the room for Rotgut. Its overlay's Deform null squashes it. +void npc_adult_leech_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = ADULT_LEECH_CRAWL; + npc.i1 = 0; + npc.stateFrame = -1; + break; + case ADULT_LEECH_CRAWL: + leech_crawl_update(npc, room); + break; + case ADULT_LEECH_CROSS: + leech_cross_update(npc); + break; + case ADULT_LEECH_BURROW: + leech_burrow_update(npc); + break; + case ADULT_LEECH_SURFACE: + leech_surface_update(npc); + break; + case ADULT_LEECH_LUNGE: + leech_lunge_update(npc); + break; + case ADULT_LEECH_CHARGE: + leech_charge_update(npc); + break; + case ADULT_LEECH_CHARGE_HIT: + leech_charge_hit_update(npc); + break; + } + + const NullFrame* deform = + npc.sprite.overlayAnimState.animData ? npc.sprite.overlayAnimState.GetNullFrame("Deform") : nullptr; + if (deform && deform->isVisible) npc.sprite.GetLayer(0)->size = deform->scale; + if (!npc.isDead) return; + + for (int i = 0; i < ADULT_LEECH_DEATH_BURSTS; i++) + { + float depth = (random_unit() - HALF) * ADULT_LEECH_DEATH_DEPTH; + float width = (random_unit() - HALF) * ADULT_LEECH_DEATH_WIDTH; + Vector spot = vector_make(width + npc.pos.x, depth + npc.pos.y); + float lift = ADULT_LEECH_DEATH_LIFT - random_unit() * ADULT_LEECH_DEATH_LIFT_RANGE; + int subType = (int)(Random() & 1) + BLOOD_EXPLOSION_SPLASH; + blood_explosion_spawn(subType, spot, vector_make(0, lift), COLOR_DEFAULT, {}); + } +} diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp index 5c58ddb..8c7291e 100644 --- a/src/npc_ai.cpp +++ b/src/npc_ai.cpp @@ -1,5 +1,7 @@ #include "npc_ai.h" #include "boss_ai.h" +#include "boss_repentance.h" +#include "boss_final.h" #include "npc_alt.h" #include "game.h" #include "manager.h" @@ -57,24 +59,6 @@ static void beast_update(Entity_NPC& npc) } } -// Mother's forms, by variant: her two phases, her rotten gapers, worms and balls. -static void mother_update(Entity_NPC& npc) -{ - switch (npc.variant) - { - case 0: - return NpcAI::ENTITY_MOTHER(&npc); - case 10: - return NpcAI::ENTITY_MOTHER_2(&npc); - case 20: - return NpcAI::ENTITY_ROTTEN_GAPER(&npc); - case 30: - return NpcAI::ENTITY_MOTHER_worm(&npc); - case 100: - return NpcAI::ENTITY_MOTHER_ball(&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) { @@ -265,7 +249,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 52: return npc_sin_update(npc); case 53: - return (void)NpcAI::ENTITY_DOPLE(&npc); + return npc_dople_update(npc); case 56: return npc_lump_update(npc); case 57: @@ -353,7 +337,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 102: return boss_isaac_update(npc); case 201: - return (void)NpcAI::ENTITY_STONE_EYE(&npc); + return npc_stone_eye_update(npc); case 202: return npc_stone_shooter_update(npc); case 204: @@ -388,7 +372,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 224: return npc_oob_update(npc); case 225: - return (void)NpcAI::ENTITY_BLACK_MAW(&npc); + return npc_black_maw_update(npc); case 226: case 227: case 277: @@ -463,9 +447,9 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 292: return npc_movable_tnt_update(npc); case 293: - return (void)NpcAI::ENTITY_ULTRA_COIN(&npc); + return npc_ultra_coin_update(npc); case 294: - return (void)NpcAI::ENTITY_ULTRA_DOOR(&npc); + return npc_ultra_door_update(npc); case 295: return npc_corn_mine_update(npc); case 296: @@ -483,15 +467,15 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 306: return npc_portal_update(npc); case 307: - return (void)NpcAI::ENTITY_TARBOY(&npc); + return npc_tarboy_update(npc); case 308: - return (void)NpcAI::ENTITY_FISTULOID(&npc); + return npc_fistuloid_update(npc); case 309: return npc_gush_update(npc); case 310: return npc_leper_update(npc); case 311: - return (void)NpcAI::ENTITY_MR_MINE(&npc); + return npc_mr_mine_update(npc); case 402: return boss_brownie_update(npc); case 403: @@ -501,7 +485,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 405: return boss_rag_man_update(npc); case 406: - return (void)NpcAI::ENTITY_ULTRA_GREED(&npc); + return npc_ultra_greed_update(npc); case 407: return boss_hush_update(npc); case 409: @@ -519,7 +503,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 804: return npc_quake_grimace_update(npc); case 805: - return (void)NpcAI::ENTITY_BISHOP(&npc); + return npc_bishop_update(npc); case 806: return npc_bubbles_update(npc); case 808: @@ -547,11 +531,11 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 821: return npc_blaster_update(npc); case 822: - return (void)NpcAI::ENTITY_BOUNCER(&npc); + return npc_bouncer_update(npc); case 823: return npc_quakey_update(npc); case 824: - return (void)NpcAI::ENTITY_GYRO(&npc); + return npc_gyro_update(npc); case 825: return npc_fire_worm_update(npc); case 826: @@ -565,15 +549,15 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 830: return npc_big_bony_update(npc); case 831: - return (void)NpcAI::ENTITY_GUTTED_FATTY(&npc); + return npc_gutted_fatty_update(npc); case 832: return npc_exorcist_update(npc); case 833: - return (void)NpcAI::ENTITY_CANDLER(&npc); + return npc_candler_update(npc); case 834: return npc_whipper_update(npc); case 835: - return (void)NpcAI::ENTITY_PEEPER_FATTY(&npc); + return npc_peeper_fatty_update(npc); case 837: return npc_henry_update(npc); case 838: @@ -583,19 +567,19 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 844: return npc_bomb_gagger_update(npc); case 850: - return (void)NpcAI::ENTITY_GAPER_L2(&npc); + return npc_gaper_l2_update(npc); case 851: - return (void)NpcAI::ENTITY_TWITCHY(&npc); + return npc_twitchy_update(npc); case 852: - return (void)NpcAI::ENTITY_SPIKEBALL(&npc); + return npc_spikeball_update(npc); case 853: - return (void)NpcAI::ENTITY_SMALL_MAGGOT(&npc); + return npc_small_maggot_update(npc); case 854: - return (void)NpcAI::ENTITY_ADULT_LEECH(&npc); + return npc_adult_leech_update(npc); case 855: return (void)NpcAI::ENTITY_CHARGER_L2(&npc); case 856: - return (void)NpcAI::ENTITY_GASBAG(&npc); + return npc_gasbag_update(npc); case 857: return (void)NpcAI::ENTITY_COHORT(&npc); case 860: @@ -607,7 +591,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 864: return npc_mockulus_update(npc); case 865: - return (void)NpcAI::ENTITY_EVIS(&npc); + return npc_evis_update(npc); case 866: return npc_dark_esau_update(npc); case 867: @@ -627,7 +611,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 878: return (void)NpcAI::ENTITY_BUTT_SLICKER(&npc); case 879: - return (void)NpcAI::ENTITY_BLOATY(&npc); + return npc_bloaty_update(npc); case 880: return npc_flesh_maiden_update(npc); case 881: @@ -645,7 +629,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 887: return npc_dusty_deaths_head_update(npc); case 888: - return (void)NpcAI::ENTITY_SHADY(&npc); + return npc_shady_update(npc); case 889: return npc_clickety_clack_update(npc); case 890: @@ -683,10 +667,9 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 910: return npc.variant == 2 ? (void)NpcAI::ENTITY_CHIMERA(&npc) : NpcAI::ENTITY_CHIMERA_body(&npc); case 911: - if (npc.variant == 2) return NpcAI::ENTITY_ROTGUT(&npc); - return npc.variant == 1 ? NpcAI::ENTITY_ROTGUT_maggot(&npc) : NpcAI::ENTITY_ROTGUT_face(&npc); + return boss_rotgut_update(npc); case 912: - return mother_update(npc); + return boss_mother_update(npc); case 913: return boss_min_min_update(npc); case 914: @@ -696,13 +679,13 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 916: return (void)NpcAI::ENTITY_BUMBINO(&npc); case 917: - return (void)NpcAI::ENTITY_COLOSTOMIA(&npc); + return boss_colostomia_update(npc); case 918: - return (void)NpcAI::ENTITY_TURDLET(&npc); + return boss_turdlet_update(npc); case 919: return (void)NpcAI::ENTITY_RAGLICH(&npc); case 920: - return (void)NpcAI::ENTITY_HORNY_BOYS(&npc); + return boss_horny_boys_update(npc); case 921: if (npc.variant == 0) return NpcAI::ENTITY_CLUTCH(&npc); reconstruction_missing("npc_ai_update 006c2990: Clutch's orbitals"); @@ -716,7 +699,7 @@ static void npc_ai_routine_run(Entity_NPC& npc) case 951: return beast_update(npc); case 960: - return (void)NpcAI::ENTITY_GENERIC_PROP(&npc); + return npc_generic_prop_update(npc); case 965: return npc_minecart_update(npc); case 966: diff --git a/src/npc_ai.h b/src/npc_ai.h index fe66265..39ef48e 100644 --- a/src/npc_ai.h +++ b/src/npc_ai.h @@ -62,6 +62,18 @@ constexpr int RAGLING_RAG_MAN = 1; constexpr int KNIGHT_BLACK = 4; constexpr int DANGLE = 1; +// Evis' cord (its variant 10), the Peeping Fatty's eyes (its first two queued entities) and the Gutted Fatty's +// Festering Guts (its variant 20). +constexpr int EVIS_CORD = 10; +constexpr size_t PEEPING_FATTY_EYES = 2; +constexpr int FESTERING_GUTS = 20; + +// The splat of the grilled enemies (the Clotty's, the Gyro's): burnt black. +constexpr ColorMod GRILLED_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.14117648f, 0.12156863f, 0.10980392f}}; + +// The deadzone of a controlled enemy's input. +constexpr float CONTROLLER_DEADZONE = 0.1f; + // The splats poop enemies leave: the plain brown, and the lighter one of corn, Brownie's dips and the Dross. constexpr ColorMod POOP_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; constexpr ColorMod LIGHT_POOP_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; diff --git a/src/npc_alt.h b/src/npc_alt.h index b6b2a18..f2f03a9 100644 --- a/src/npc_alt.h +++ b/src/npc_alt.h @@ -6,6 +6,12 @@ // 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}}; +// A cord's points sit in vectorDeque1 as triples: the point, its velocity, and its height with the height's speed. +constexpr size_t CORD_STRIDE = 3; + +// The splat of the Corpse's bloated enemies (the Gutted Fatty, the level 2 Gaper): white, faintly washed. +constexpr ColorMod BLOATED_SPLAT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 0.65f}, {0, 0, 0}}; + // The alt path enemies' AIs (the Downpour, Dross, Mines and Ashpit) the dispatcher (npc_ai_update) runs by type. void npc_blaster_update(Entity_NPC& npc); void npc_quakey_update(Entity_NPC& npc); @@ -26,6 +32,36 @@ void npc_poot_mine_update(Entity_NPC& npc); void npc_clickety_clack_update(Entity_NPC& npc); void npc_henry_update(Entity_NPC& npc); void npc_bomb_gagger_update(Entity_NPC& npc); +void npc_small_maggot_update(Entity_NPC& npc); +Entity_NPC* small_maggot_fling(const Vector& position, float height, const Vector& velocity, float rise); +void npc_gaper_l2_update(Entity_NPC& npc); +void npc_candler_update(Entity_NPC& npc); +void npc_bishop_update(Entity_NPC& npc); +void npc_gyro_update(Entity_NPC& npc); +void npc_bouncer_update(Entity_NPC& npc); +void npc_shady_update(Entity_NPC& npc); +void npc_peeper_fatty_update(Entity_NPC& npc); +void npc_dople_update(Entity_NPC& npc); +void npc_twitchy_update(Entity_NPC& npc); +void npc_evis_update(Entity_NPC& npc); +void npc_gutted_fatty_update(Entity_NPC& npc); +void npc_fatty_wander(Entity_NPC& npc); +Vector npc_weave_direction_get(Entity_NPC& npc); +void npc_bloaty_update(Entity_NPC& npc); +void npc_rotten_gaper_update(Entity_NPC& npc); + +// The walks Entity_NPC::anim_walk_frame_4dir picks between (its arguments): left, right, up and down, and the speed +// below which it stands. +struct WalkAnims +{ + std::string_view left; + std::string_view right; + std::string_view up; + std::string_view down; + float threshold = 0; +}; + +void npc_walk_animate_4dir(Entity_NPC& npc, const WalkAnims& anims); // What rock_spider_throw throws: a rock, tinted or coal rock spider (their variants), or a coal fire (a fireplace). enum RockSpiderKind diff --git a/src/npc_basement.h b/src/npc_basement.h index 44b2325..9b28018 100644 --- a/src/npc_basement.h +++ b/src/npc_basement.h @@ -30,6 +30,9 @@ void npc_baby_long_legs_update(Entity_NPC& npc); void npc_movable_tnt_update(Entity_NPC& npc); void npc_vis_update(Entity_NPC& npc); +// The Vis' Chubber worm (its variant), which the Fistuloid also spits. +constexpr int CHUBBER_WORM = 22; + // Cancels an enemy's pending damage of the given kinds, but the players' own, friendly ones' and TNT's. void npc_hostile_damage_ignore(Entity_NPC& npc, uint64_t damageFlags); diff --git a/src/npc_bishop.cpp b/src/npc_bishop.cpp new file mode 100644 index 0000000..bf737b0 --- /dev/null +++ b/src/npc_bishop.cpp @@ -0,0 +1,53 @@ +#include "npc_alt.h" +#include "room.h" +#include "room_grid.h" + +// The Bishop wakes on its cell and holds there, marking it for the pathfinder (unless it rides a minecart). Hit, it +// answers two times in three with a plus of glowing shots. +constexpr int BISHOP_PATH_MARKER = 900; +constexpr uint32_t BISHOP_ANSWER_ODDS = 3; +constexpr float BISHOP_SHOT_SPEED = 12; +constexpr ColorMod BISHOP_SPLAT_COLOR = {{1, 1, 1, 1}, {0.8f, 0.78f, 0.74f, 1}, {0, 0, 0}}; +constexpr ColorMod BISHOP_SHOT_COLOR = {{0.99f, 1, 1, 1}, {3, 3, 3, 1}, {0.15f, 0.15f, 0.2f}}; + +// 004e7ea0 The Bishop's AI: it stands on its cell and, hit, shoots a plus of glowing shots. +void npc_bishop_update(Entity_NPC& npc) +{ + Entity* minecart = npc.minecart.get(); + if (npc.state == NPC_STATE_INIT) + { + Room& room = *g_game->room; + int cell = room.GetGridIndex(npc.pos); + if (cell >= 0) npc.targetPosition = room.GetGridPosition(cell); + npc.state = NPC_STATE_IDLE; + npc.splatColor = BISHOP_SPLAT_COLOR; + npc_anim_loop(npc.sprite, "WakeUp"); + } + else if (npc.state == NPC_STATE_IDLE) + { + if (!npc.sprite.IsPlaying()) npc_anim_loop(npc.sprite, "Idle"); + if (npc.pendingDamage > 0 && Random() % BISHOP_ANSWER_ODDS != 0) + { + npc_anim_loop(npc.sprite, "Shoot"); + npc.state = NPC_STATE_ATTACK; + } + } + else if (npc.state == NPC_STATE_ATTACK) + { + if (npc.sprite.IsEventTriggered("Shoot")) + { + ProjectileParams params; + params.color = BISHOP_SHOT_COLOR; + npc.FireProjectiles(npc.pos, vector_make(BISHOP_SHOT_SPEED, 0), PROJECTILES_PLUS, params); + npc.PlaySound(SOUND_STONESHOOT, 1, 2, false, 1); + } + if (!npc.sprite.IsPlaying()) npc.state = NPC_STATE_IDLE; + } + + if (!vector_is_zero(npc.targetPosition)) + { + Vector toward = vector_sub(npc.targetPosition, npc.pos); + npc.velocity = vector_make(toward.x / npc.friction, toward.y / npc.friction); + } + if (!minecart) room_path_raise_at(npc.targetPosition, BISHOP_PATH_MARKER); +} diff --git a/src/npc_black_maw.cpp b/src/npc_black_maw.cpp new file mode 100644 index 0000000..e62cb09 --- /dev/null +++ b/src/npc_black_maw.cpp @@ -0,0 +1,152 @@ +#include "npc_depths.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "game.h" +#include "menu_manager.h" +#include "room.h" + +// The Black Maw drifts after its target (staying 20 off it, or wandering when confused), and charges off across the +// room when level with it, coming back the other way. One frame in 120 it calls up a leech while fewer than eight +// enemies are about. It dies in an explosion. +constexpr float MAW_TARGET_LEAD = 10; +constexpr float MAW_CONTROL_REACH = 100; +constexpr int MAW_CONFUSED_FRAMES = 30; +constexpr int MAW_CONFUSED_MIN = 15; +constexpr float MAW_NEAR_SQUARED = 400; +constexpr float MAW_NEAR = 20; +constexpr float BLACK_MAW_FRICTION = 0.8f; +constexpr float MAW_LEVEL = 20; +constexpr float MAW_SETTLE_FRAMES = 45; +constexpr uint32_t MAW_SUMMON_ODDS = 120; +constexpr int MAW_ENEMY_LIMIT = 8; +constexpr int MAW_SUMMON_COOLDOWN = 90; +constexpr float MAW_SUMMON_REACH = 20; +constexpr float MAW_CHARGE_SPEED = 25; +constexpr float MAW_RETURN_SPEED = 18; +constexpr float MAW_OFFSCREEN = 200; +constexpr float MAW_BLAST_DAMAGE = 40; +constexpr float MAW_BLAST_RADIUS = 60; +constexpr ColorMod MAW_SPLAT_COLOR = {{0.1f, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Drifting: after its target (or where its controller points), wandering on a held heading when confused, and +// charging or summoning when it may. +static void black_maw_drift(Entity_NPC& npc) +{ + npc.sprite.Play("Walk"); + Vector toward = vector_sub(npc.CalcTargetPosition(MAW_TARGET_LEAD), npc.pos); + if (npc.controllerID != -1) toward = vector_scale(npc.GetControllerInput(0), MAW_CONTROL_REACH); + if (npc.HasEntityFlags(FLAG_CONFUSION) && npc.controllerID == -1) + { + int period = (int)(Random() % MAW_CONFUSED_FRAMES) + MAW_CONFUSED_MIN; + if (!npc.IsFrame(period, npc.index) && !npc.isCollidesWithGrid) toward = npc.v1; + else npc.v1 = toward; + float lengthSquared = vector_length_squared(toward); + if (lengthSquared < MAW_NEAR_SQUARED && lengthSquared != 0) toward = vector_scale(toward, MAW_NEAR / std::sqrt(lengthSquared)); + } + npc.friction *= BLACK_MAW_FRICTION; + Vector direction = vector_normalized(toward); + if (npc.friction != 0) + { + npc.velocity.x += direction.x * npc.speedMultiplier / npc.friction; + npc.velocity.y += direction.y * npc.speedMultiplier / npc.friction; + } + npc.sprite.isFlipX = toward.x < 0; + if (npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return; + + bool isCharging = npc.controllerID == -1 ? std::abs(toward.y) < MAW_LEVEL && npc.updateTime > MAW_SETTLE_FRAMES + : npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT); + if (isCharging) + { + npc_anim_restart(npc.sprite, "Charge"); + npc.PlaySound(SOUND_MONSTER_YELL_A, 1, 2, false, 1); + npc.targetPosition = npc.pos; + npc.state = NPC_STATE_ATTACK; + npc.velocity = {}; + npc.stateFrame = 0; + npc.entityGridCollisionClass = GRIDCOLL_WALLS_Y; + return; + } + + bool isSummoning = npc.controllerID == -1 ? Random() % MAW_SUMMON_ODDS == 0 + : npc.IsControllerActionPressed(ACTION_BOMB) && npc.i1 <= 0; + if (!isSummoning || npc.GetAliveEnemyCount() >= MAW_ENEMY_LIMIT) return; + + npc_anim_restart(npc.sprite, "Summon"); + npc.state = NPC_STATE_SUMMON; + npc.velocity = {}; + npc.stateFrame = 0; + npc.i1 = MAW_SUMMON_COOLDOWN; +} + +// The charge: once shaken loose it runs off one side of the room, then turns back. +static void black_maw_charge(Entity_NPC& npc) +{ + npc.velocity.y = 0; + if (!npc.sprite.IsPlaying()) npc_anim_loop(npc.sprite, "Charge Shake"); + if (npc.sprite.IsPlaying("Charge Shake")) npc.velocity.x = npc.sprite.isFlipX ? -MAW_CHARGE_SPEED : MAW_CHARGE_SPEED; + + float speed = npc.velocity.x; + bool isGone = (speed > 0 && npc.pos.x > g_game->room->bottomRightPos.x + MAW_OFFSCREEN) || + (speed < 0 && npc.pos.x < -MAW_OFFSCREEN); + if (!isGone) return; + + npc.state = NPC_STATE_ATTACK2; + npc.stateFrame++; + npc.sprite.isFlipX = !npc.sprite.isFlipX; +} + +// Coming back across, it drifts again once past where it started. +static void black_maw_return(Entity_NPC& npc) +{ + float speed = npc.sprite.isFlipX ? -MAW_RETURN_SPEED : MAW_RETURN_SPEED; + npc.velocity = vector_make(speed, 0); + bool isPast = (speed < 0 && npc.targetPosition.x > npc.pos.x) || (speed > 0 && npc.pos.x > npc.targetPosition.x); + if (npc.stateFrame < 1 || !isPast) return; + + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.state = NPC_STATE_MOVE; +} + +// 0053b2f0 The Black Maw's AI: it drifts after its target, charges across the room when level with it and calls up +// leeches. It dies in an explosion. +void npc_black_maw_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.state = NPC_STATE_MOVE; + npc.v1 = {}; + npc.splatColor = MAW_SPLAT_COLOR; + return; + } + if (npc.i1 > 0) npc.i1 -= npc_ticks_get(npc); + + if (npc.state == NPC_STATE_MOVE) black_maw_drift(npc); + else if (npc.state == NPC_STATE_ATTACK) black_maw_charge(npc); + else if (npc.state == NPC_STATE_ATTACK2) black_maw_return(npc); + else if (npc.state == NPC_STATE_SUMMON) + { + if (!npc.sprite.IsPlaying()) + { + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.state = NPC_STATE_MOVE; + } + else if (npc.sprite.IsEventTriggered("Summon")) + { + npc.PlaySound(SOUND_SUMMONSOUND, 1, 2, false, 1); + uint32_t seed = Random(); + Vector position = vector_add(vector_scale(random_direction(), MAW_SUMMON_REACH), npc.pos); + g_game->Spawn({.position = position, .spawner = &npc, .type = ENTITY_LEECH, .seed = seed}); + } + } + if (!npc.isDead || npc.HasEntityFlags(FLAG_SHRINK)) return; + + explosion_damage({.position = npc.pos, + .source = &npc, + .damage = MAW_BLAST_DAMAGE, + .radius = MAW_BLAST_RADIUS, + .isDamageSource = false, + .isLineCheck = true}); + bomb_crater_spawn(npc.pos, nullptr, 1); + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); +} diff --git a/src/npc_bloaty.cpp b/src/npc_bloaty.cpp new file mode 100644 index 0000000..d5e1fa0 --- /dev/null +++ b/src/npc_bloaty.cpp @@ -0,0 +1,207 @@ +#include "npc_alt.h" +#include "entity_effect.h" +#include "entity_projectile.h" +#include "room.h" +#include +#include + +// The Bloaty wanders as the fatties do, gurgling, and 60 to 209 frames apart (60 under control) spews a line of green +// creep along one of eight ways, picked near where it moves and pointing into the room. Damage shortens the wait 8 +// frames a point. +constexpr float BLOATY_FRICTION = 0.6f; +constexpr float BLOATY_WALK_THRESHOLD = 0.1f; +constexpr uint32_t BLOATY_GURGLE_ODDS = 20; +constexpr int BLOATY_GURGLE_DELAY = 60; +constexpr int SPEW_WAIT_RANGE = 150; +constexpr int SPEW_WAIT_MIN = 60; +constexpr float SPEW_CONTROL_RANGE = 1000; +constexpr float SPEW_DAMAGE_SCALE = 8; +constexpr int SPEW_DIRECTIONS = 8; +constexpr float SPEW_STEP_DEGREES = 45; +constexpr float SPEW_SPREAD = 90; +constexpr float SPEW_CHECK_REACH = 80; +constexpr float SPEW_FRICTION = 0.4f; +constexpr std::array SPEW_ANIMS = { + "AttackRight", "AttackDownRight", "AttackDown", "AttackDownRight", + "AttackRight", "AttackUpRight", "AttackUp", "AttackUpRight"}; +constexpr int SPEW_FLIP_FIRST = 3; +constexpr int SPEW_FLIP_COUNT = 3; + +// The spew: eight puddles 25 apart growing from 0.97, one a tick, each with a splash (and a splat out of water), and +// a lob every other puddle. +constexpr int SPEW_PUDDLES = 8; +constexpr float SPEW_PUDDLE_GAP = 25; +constexpr float SPEW_PUDDLE_GROWTH = 0.07f; +constexpr float SPEW_PUDDLE_MIN = 0.9f; +constexpr int SPEW_CREEP_FRAMES = 90; +constexpr float SPEW_SOUND_VOLUME = 0.6f; +constexpr int SPEW_SOUND_DELAY = 10; +constexpr float SPEW_SPLASH_LIFT = -16; +constexpr float SPEW_SPLASH_BACK = 5; +constexpr float SPEW_SPLASH_DEPTH = 10; +constexpr float SPEW_SPLAT_WATER = 0.2f; +constexpr float SPEW_LOB_TRAJECTORY = 10; +constexpr float SPEW_LOB_SCALE = 0.65f; +constexpr float SPEW_LOB_SPREAD = 20; +constexpr float SPEW_LOB_SPEED = 4; +constexpr float SPEW_LOB_SPEED_MIN = 4; +constexpr float SPEW_CONTROL_TURN = 45; +constexpr ColorMod SPEW_SPLASH_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.08f, 0.5f, 0.01f}}; +constexpr ColorMod SPEW_SPLAT_COLOR = {{0, 0, 0, 0.5f}, {0, 0, 0, 0}, {0.08f, 0.5f, 0.01f}}; +constexpr ColorMod SPEW_LOB_COLOR = {{1, 1, 1, 1}, {0.4f, 2, 0.5f, 1}, {0, 0, 0}}; + +// Its death: a green splash and a wide puddle. +constexpr ColorMod DEATH_SPLASH_COLOR = {{1, 1, 1, 1}, {0.25f, 0.8f, 0.35f, 1}, {0, 0, 0}}; +constexpr float DEATH_CREEP_SCALE = 2; + +// A green puddle of the Bloaty's, lasting 90 frames. +static Entity* bloaty_creep_spawn(Entity_NPC& npc, Vector position, float scale) +{ + auto* creep = static_cast(g_game->Spawn( + {.position = position, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_GREEN, .seed = Random()})); + creep->timeout = SPEW_CREEP_FRAMES; + creep->lifespan = SPEW_CREEP_FRAMES; + creep->sprite.scale = vector_make(scale, scale); + creep->Update(); + return creep; +} + +// Its spew's way: near where it moves (up to 45 degrees off) and pointing 80 into the room, eight tries, or where its +// controller points. +static void bloaty_spew_aim(Entity_NPC& npc) +{ + if (npc.controllerID != -1) + { + Vector input = npc.GetControllerMovementInput(0); + float steps = normalize_angle_degrees(vector_angle(input) / SPEW_STEP_DEGREES); + npc.i2 = (int)(steps + SPEW_DIRECTIONS) % SPEW_DIRECTIONS; + npc.UpdateControllerMovement(true); + return; + } + for (int i = 0; i < SPEW_DIRECTIONS; i++) + { + float moving = vector_angle(npc.velocity); + float angle = normalize_angle_degrees(random_unit() * SPEW_SPREAD + moving - SPEW_SPREAD / 2); + npc.i2 = (int)(angle / SPEW_STEP_DEGREES + SPEW_DIRECTIONS) % SPEW_DIRECTIONS; + Vector spot = vector_add(vector_scale(vector_from_angle(npc.i2 * SPEW_STEP_DEGREES), SPEW_CHECK_REACH), npc.pos); + if (g_game->room->IsPositionInRoom(spot, 0)) return; + } +} + +// Walking: it wanders and gurgles, and once its wait is up (and its controller's target in range) starts to spew. +static void bloaty_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", BLOATY_WALK_THRESHOLD); + npc.friction *= BLOATY_FRICTION; + npc_fatty_wander(npc); + if (Random() % BLOATY_GURGLE_ODDS == 0) npc.PlaySound(SOUND_ANGRY_GURGLE, 1, BLOATY_GURGLE_DELAY, false, 1); + + if (npc.projectileCooldown > 0 && (npc.projectileCooldown -= npc_ticks_get(npc)) > 0) return; + if (npc.controllerID != -1 && !npc.IsTargetInAttackRange(SPEW_CONTROL_RANGE, 0, true)) return; + + npc.state = NPC_STATE_ATTACK; + bloaty_spew_aim(npc); + npc_anim_loop(npc.sprite, SPEW_ANIMS[npc.i2]); + npc.sprite.isFlipX = npc.i2 >= SPEW_FLIP_FIRST && npc.i2 < SPEW_FLIP_FIRST + SPEW_FLIP_COUNT; + npc.stateFrame = 0; +} + +// A puddle of the spew (the stateFrame'th): its creep, its splash and splat inside the room, and every other one a lob +// fanned up to 10 degrees off the spew. +static void bloaty_puddle(Entity_NPC& npc, Vector direction) +{ + npc.stateFrame++; + Vector spot = vector_add(vector_scale(direction, npc.stateFrame * SPEW_PUDDLE_GAP), npc.pos); + float scale = npc.stateFrame * SPEW_PUDDLE_GROWTH + SPEW_PUDDLE_MIN; + bloaty_creep_spawn(npc, spot, scale); + if (g_game->room->IsPositionInRoom(spot, 0)) + { + float push = random_unit(); + Vector velocity = vector_scale(npc.targetPosition, push); + velocity = vector_add(velocity, velocity); + float lift = random_unit() * SPEW_SPLASH_LIFT; + Vector position = vector_sub(spot, vector_scale(npc.targetPosition, SPEW_SPLASH_BACK)); + Entity* splash = g_game->Spawn({.position = position, + .velocity = velocity, + .subType = 2, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + splash->SetColor(SPEW_SPLASH_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splash->sprite.offset = vector_make(0, lift); + splash->renderDepthOffset = SPEW_SPLASH_DEPTH; + splash->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + if (g_game->room->waterAmount < SPEW_SPLAT_WATER) + { + Entity* splat = + g_game->Spawn({.position = spot, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + splat->sizeMulti = vector_make(scale, scale); + splat->SetColor(SPEW_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + } + } + if (npc.stateFrame & 1) return; + + Entity_Projectile* lob = npc.FireBossProjectiles(1, {}, SPEW_LOB_TRAJECTORY, ProjectileParams()); + lob->scale *= SPEW_LOB_SCALE; + float fan = random_unit() * SPEW_LOB_SPREAD - SPEW_LOB_SPREAD / 2; + Vector fanned = vector_rotated(direction, fan); + float speed = random_unit() * SPEW_LOB_SPEED + SPEW_LOB_SPEED_MIN; + lob->velocity = vector_scale(fanned, speed); + lob->SetColor(SPEW_LOB_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// Spewing: a burp on Shoot, then a puddle a tick along its way (turned toward its controller's aim) up to eight, and +// back to walking once the animation ends. +static void bloaty_spew(Entity_NPC& npc) +{ + npc.UpdateControllerMovement(false); + if (npc.sprite.IsEventTriggered("Shoot")) + { + int burp = Random() & 1 ? SOUND_BOSS_GURGLE_ROAR : SOUND_BOSS_LITE_GURGLE; + npc.PlaySound(burp, 1, SPEW_SOUND_DELAY, false, 1); + npc.PlaySound(SOUND_HEARTOUT, SPEW_SOUND_VOLUME, SPEW_SOUND_DELAY, false, 1); + } + if (npc.sprite.WasEventTriggered("Shoot")) + { + float angle = npc.i2 * SPEW_STEP_DEGREES; + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) + angle = angle_approach(angle, vector_angle(npc.controllerMovement), SPEW_CONTROL_TURN); + Vector direction = vector_from_angle(angle); + for (int tick = 0; tick < npc_ticks_get(npc) && npc.stateFrame < SPEW_PUDDLES; tick++) bloaty_puddle(npc, direction); + } + if (!npc.sprite.IsPlaying()) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.projectileCooldown = npc.controllerID == -1 ? (int)(Random() % SPEW_WAIT_RANGE) + SPEW_WAIT_MIN : SPEW_WAIT_MIN; + } + npc.friction *= SPEW_FRICTION; +} + +// 00563da0 The Bloaty's AI: it wanders and now and then spews a line of green creep and lobs. It dies in a green +// splash and puddle. +void npc_bloaty_update(Entity_NPC& npc) +{ + npc.UpdateChargeBar(SPEW_WAIT_MIN, 0, (float)npc.projectileCooldown, true); + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.sprite.SetFrame("WalkVert", 0); + npc.projectileCooldown = npc.controllerID == -1 ? (int)(Random() % SPEW_WAIT_RANGE) + SPEW_WAIT_MIN : SPEW_WAIT_MIN; + npc.i1 = 0; + float heading = normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES); + npc.v1 = vector_make(heading, heading); + return; + } + if (npc.state == NPC_STATE_MOVE) bloaty_walk(npc); + else if (npc.state == NPC_STATE_ATTACK) bloaty_spew(npc); + + if (npc.pendingDamage > 0) npc.projectileCooldown -= std::max(1, (int)(npc.pendingDamage * SPEW_DAMAGE_SCALE)); + if (!npc.isDead) return; + + Entity* splash = g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BIG_SPLASH, .seed = Random()}); + splash->SetColor(DEATH_SPLASH_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splash->Update(); + bloaty_creep_spawn(npc, npc.pos, DEATH_CREEP_SCALE); +} diff --git a/src/npc_boom_fly.cpp b/src/npc_boom_fly.cpp index a7527ab..6f08813 100644 --- a/src/npc_boom_fly.cpp +++ b/src/npc_boom_fly.cpp @@ -64,7 +64,6 @@ constexpr float RED_RING_SHOTS = 6; constexpr float RING_SPEED = 8; constexpr float RING_HARD_SPEED = 10; constexpr ColorMod SICK_BLAST_COLOR = {{1, 1, 1, 1}, {1, 1, 0, 0.5f}, {0, 0, 0}}; -constexpr ColorMod SICK_SHOT_COLOR = {{1, 1, 1, 1}, {1.5f, 2, 1, 1}, {0, 0, 0}}; constexpr float SICK_SHOT_SPEED = 10; constexpr float SICK_SHOTS = 6; constexpr int SICK_CLOUDS = 8; @@ -277,7 +276,7 @@ static void sick_fly_burst(Entity_NPC& npc) if (!isChimeras) { ProjectileParams params; - params.color = SICK_SHOT_COLOR; + params.color = SHOT_COLOR_SICK; npc.FireProjectiles(npc.pos, vector_make(SICK_SHOT_SPEED, SICK_SHOTS), PROJECTILES_RING, params); } for (int i = 0; i < SICK_CLOUDS; i++) diff --git a/src/npc_bouncer.cpp b/src/npc_bouncer.cpp new file mode 100644 index 0000000..0b8ec97 --- /dev/null +++ b/src/npc_bouncer.cpp @@ -0,0 +1,170 @@ +#include "npc_alt.h" +#include "entity_effect.h" +#include "entity_projectile.h" + +// The Bouncer flees its target, whimpering now and then. Once its fuse (v1.x, 6 to 10 seconds, burned faster by +// damage) is out, while fleeing, it inflates one frame in 20 and then chases its target, quivering. +constexpr float BOUNCER_FUSE_MIN = 6; +constexpr float BOUNCER_FUSE_RANGE = 4; +constexpr float FUSE_BURN = 1.0f / 30; +constexpr float FUSE_DAMAGE_SCALE = 3.5f; +constexpr int BOUNCER_WHIMPER_DELAY_RANGE = 100; +constexpr int BOUNCER_WHIMPER_DELAY_MIN = 45; +constexpr int WHIMPER_SETTLE_FRAMES = 10; +constexpr int INFLATE_SETTLE_FRAMES = 30; +constexpr uint32_t INFLATE_ODDS = 20; +constexpr int INFLATE_SOUND_DELAY = 30; +constexpr float INFLATE_SIZE = 1.5f; +constexpr float BOUNCER_FRICTION = 0.8f; +constexpr float INFLATING_FRICTION = 0.6f; +constexpr float BOUNCER_CHASE_SPEED = 0.9f; +constexpr int BOUNCER_CHASE_PATH_MARKER = 900; +constexpr int BOUNCER_HEAD_LAYER = 1; +constexpr float BOUNCER_WALK_THRESHOLD = 0.1f; + +// Popped inflated, it bursts in a fart, three gibs 4 frames apart, a ring of 12 shots and 22 slowing lobs. Otherwise +// it dies in a cross of shots (unless shrunk). +constexpr float POP_PITCH = 1.5f; +constexpr int BOUNCER_POP_SHAKE = 6; +constexpr int POP_SHAKE_AFTER = 8; +constexpr float POP_FART_RADIUS = 120; +constexpr int POP_GIB_DELAY = 3; +constexpr int POP_GIBS = 4; +constexpr float POP_GIB_SPEED = 12; +constexpr float POP_GIB_LIFT = -26; +constexpr int POP_GIB_SIZE = 3; +constexpr int POP_RING_SHOTS = 12; +constexpr int POP_LOBS = 22; +constexpr float POP_LOB_SPREAD = 5; +constexpr float POP_LOB_SPEED = 15; +constexpr float POP_LOB_HEIGHT = -22; +constexpr float POP_LOB_HEIGHT_RANGE = 8; +constexpr float POP_LOB_FALL = -0.06f; +constexpr float POP_LOB_FALL_RANGE = 0.030000005f; +constexpr float POP_LOB_ACCEL = 0.9f; +constexpr float POP_LOB_SCALE = 1.1999999f; +constexpr float POP_LOB_SCALE_MIN = 0.6f; +constexpr float BOUNCER_DEATH_SHOT_SPEED = 10; + +// 00501e10 NpcHelper::bouncer_death_gib: a gib of the popped Bouncer thrown out from the timer. +static void bouncer_death_gib(Entity_Effect* timer) +{ + Vector direction = random_direction(); + Vector velocity = vector_scale(direction, random_unit() * POP_GIB_SPEED); + Entity* gib = g_game->Spawn({.position = timer->pos, + .velocity = velocity, + .subType = POP_GIB_SIZE, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()}); + gib->sprite.offset = vector_make(velocity.x + 0, velocity.y + POP_GIB_LIFT); +} + +// Fleeing: it whimpers, its head follows its walk, it inflates once its fuse is out, and damage burns the fuse. +static void bouncer_flee(Entity_NPC& npc) +{ + npc.pathfinder.EvadeTarget(npc.CalcTargetPosition(0), STATUS_OBEYED); + int age = g_game->frameCount - npc.spawnFrame; + bool isEvading = npc.pathfinder.evadeMovementCountdown > 0; + if (isEvading && age > WHIMPER_SETTLE_FRAMES) + npc.PlaySound(SOUND_SCARED_WHIMPER, 1, (int)(Random() % BOUNCER_WHIMPER_DELAY_RANGE) + BOUNCER_WHIMPER_DELAY_MIN, false, 1); + npc.AnimWalkFrame("WalkHori", "WalkVert", BOUNCER_WALK_THRESHOLD); + if (!npc.sprite.IsPlaying()) npc.sprite.SetOverlayFrame("HeadWalkVert", 0); + else + npc.sprite.PlayOverlay(std::abs(npc.velocity.x) <= std::abs(npc.velocity.y) ? "HeadWalkVert" : "HeadWalkHori"); + + if (age > INFLATE_SETTLE_FRAMES && isEvading && npc.v1.x <= 0 && Random() % INFLATE_ODDS == 0) + { + npc.sprite.PlayOverlay("HeadInflate"); + npc.state = NPC_STATE_ATTACK; + } + if (npc.v1.x > 0) + { + npc.v1.x -= FUSE_BURN; + if (npc.pendingDamage > 0) npc.v1.x = std::max(npc.v1.x - npc.pendingDamage / FUSE_DAMAGE_SCALE, 0.0f); + } + npc.friction *= BOUNCER_FRICTION; +} + +// Inflated: once its head is full (stateFrame) it chases its target along its grid path, quivering. +static void bouncer_chase(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", BOUNCER_WALK_THRESHOLD); + if (npc.stateFrame == 0) + { + if (!npc.sprite.IsOverlayPlaying()) npc.stateFrame = 1; + npc.friction *= INFLATING_FRICTION; + return; + } + if (!npc.sprite.IsPlaying()) npc.sprite.SetOverlayFrame("HeadWalkInflated", 0); + else npc.sprite.PlayOverlay("HeadWalkInflated"); + npc.sprite.GetLayer(BOUNCER_HEAD_LAYER)->pos.x = (g_game->frameCount - npc.spawnFrame) & 1 ? -1.0f : 1.0f; + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), BOUNCER_CHASE_SPEED, BOUNCER_CHASE_PATH_MARKER, DIRECT_PATH_FAR); +} + +// Popped inflated: the fart, gibs, a ring of shots and the slowing lobs. +static void bouncer_pop(Entity_NPC& npc) +{ + npc_sound_play(SOUND_ROCKET_BLAST_DEATH, 1, 2, POP_PITCH); + game_shake_screen(BOUNCER_POP_SHAKE); + game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = POP_FART_RADIUS, .isShowEffect = false}); + Entity_Effect* timer = Entity_Effect::CreateTimer(reinterpret_cast(&bouncer_death_gib), POP_GIB_DELAY, POP_GIBS, false); + timer->pos = npc.pos; + game_shake_screen(POP_SHAKE_AFTER); + npc.FireBossProjectiles(POP_RING_SHOTS, {}, 0, ProjectileParams()); + + for (int i = 0; i < POP_LOBS; i++) + { + Vector direction = random_direction(); + float speed = random_unit(); + Vector position = vector_add(vector_scale(direction, POP_LOB_SPREAD), npc.pos); + Vector velocity = vector_make(direction.x * POP_LOB_SPEED * speed, direction.y * POP_LOB_SPEED * speed); + auto* lob = static_cast(g_game->Spawn( + {.position = position, .velocity = velocity, .spawner = &npc, .type = ENTITY_PROJECTILE, .seed = Random()})); + lob->fallingSpeed = 0; + lob->height = POP_LOB_HEIGHT - random_unit() * POP_LOB_HEIGHT_RANGE; + lob->fallingAccel = POP_LOB_FALL - random_unit() * POP_LOB_FALL_RANGE; + lob->acceleration = POP_LOB_ACCEL; + lob->projectileFlags = PROJECTILE_ACCELERATE_EX; + lob->scale = random_unit() * POP_LOB_SCALE + POP_LOB_SCALE_MIN; + npc.fire_projectile_from_params(lob); + lob->Update(); + } +} + +// 00501f30 The Bouncer's AI: it flees its target until its fuse runs out, then inflates and chases it. Popped +// inflated it bursts in shots and lobs, otherwise in a cross of shots. +void npc_bouncer_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.sprite.PlayOverlay("HeadAppear"); + npc.sprite.SetFrame("WalkVert", 0); + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + npc.v1.x = random_unit() * BOUNCER_FUSE_RANGE + BOUNCER_FUSE_MIN; + break; + case NPC_STATE_IDLE: + bouncer_flee(npc); + break; + case NPC_STATE_ATTACK: + npc.AnimWalkFrame("WalkHori", "WalkVert", BOUNCER_WALK_THRESHOLD); + if (npc.sprite.overlayAnimState.IsEventTriggered("Inflate")) + { + npc.PlaySound(SOUND_INFLATE, 1, INFLATE_SOUND_DELAY, false, 1); + npc.state = NPC_STATE_SPECIAL; + npc.size *= INFLATE_SIZE; + } + npc.friction *= INFLATING_FRICTION; + break; + case NPC_STATE_SPECIAL: + bouncer_chase(npc); + break; + } + if (!npc.isDead) return; + + if (npc.state == NPC_STATE_SPECIAL) bouncer_pop(npc); + else if (!npc.HasEntityFlags(FLAG_SHRINK)) + npc.FireProjectiles(npc.pos, vector_make(BOUNCER_DEATH_SHOT_SPEED, 0), PROJECTILES_CROSS, ProjectileParams()); +} diff --git a/src/npc_candler.cpp b/src/npc_candler.cpp new file mode 100644 index 0000000..b32a8fe --- /dev/null +++ b/src/npc_candler.cpp @@ -0,0 +1,137 @@ +#include "npc_alt.h" +#include "npc_fireplace.h" +#include "boss_ai.h" +#include "room.h" +#include + +// The Candler drifts diagonally, bouncing off walls, fleeing a target within 180 when afraid or shrunk and wandering +// when confused. +constexpr float CANDLER_FRICTION = 0.8f; +constexpr float CANDLER_TURN_SPEED_Y = 0.1f; +constexpr float CANDLER_FLEE_RANGE = 180; +constexpr float CANDLER_FLEE_SCALE = 0.02f; + +// 15 to 73 frames apart it lights a moveable fire on a free cell 20 or more from the others (a fire per five cells of +// the room's floor at most), kicked off at 20 on a random diagonal. A small Candler's fire has two thirds the health. +constexpr int LIGHT_DELAY_RANGE = 30; +constexpr int LIGHT_DELAY_MIN = 15; +constexpr float FIRE_CLEARANCE_SQUARED = 400; +constexpr float FIRE_FAR_SQUARED = 1e10f; +constexpr int FIRE_CELLS_PER_FIRE = 5; +constexpr float KICK_SPEED = 20; +constexpr float KICK_DIAGONAL = 45; +constexpr int LIGHT_SOUND_DELAY = 10; +constexpr float SMALL_FIRE_HEALTH = 0.666f; + +// Its wax: dark, washed light. +constexpr ColorMod CANDLER_SPLAT_COLOR = {{0, 0, 0, 0.3f}, {0, 0, 0, 0}, {0.8f, 0.8f, 0.8f}}; + +// 004e4870 NpcHelper::candler_is_free_cell: whether the cell at a position is open and no teleporter. +static bool candler_is_free_cell(const Vector& position) +{ + Room& room = *g_game->room; + int cell = room.GetGridIndex(position); + if (room.GetGridCollision(cell) != 0 || cell < 0) return false; + return cell >= (int)ROOM_GRID_CELLS || !room.gridEntities[cell] || room.gridEntities[cell]->type != GRID_TELEPORTER; +} + +// Whether it may light a fire here: the room holds fewer than a fire per five floor cells, none within 20. +static bool candler_is_fire_room(Entity_NPC& npc) +{ + Room& room = *g_game->room; + std::vector fires = entity_query(ENTITY_FIREPLACE, FIRE_MOVEABLE); + if ((int)fires.size() >= (room.gridHeight - 2) * (room.gridWidth - 2) / FIRE_CELLS_PER_FIRE) return false; + + float nearest = FIRE_FAR_SQUARED; + for (Entity* fire : fires) nearest = std::min(nearest, vector_length_squared(vector_sub(npc.pos, fire->pos))); + return fires.empty() || nearest > FIRE_CLEARANCE_SQUARED; +} + +// Its light: on Shoot it kicks itself off at 20 along a random diagonal and lights a fire where it stood. +static void candler_light(Entity_NPC& npc) +{ + npc.friction *= CANDLER_FRICTION; + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + float angle = (float)(Random() & 3) * RIGHT_ANGLE_DEGREES + KICK_DIAGONAL; + npc.state = NPC_STATE_IDLE; + npc.velocity = vector_scale(vector_from_angle(angle), KICK_SPEED); + if (candler_is_free_cell(npc.pos)) + { + npc.PlaySound(SOUND_CANDLE_LIGHT, 1, LIGHT_SOUND_DELAY, false, 1); + Entity* fire = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_FIREPLACE, .variant = FIRE_MOVEABLE, .seed = Random()}); + fire->targetPosition = fire->pos; + if (npc.sprite.scale.x <= 1) fire->health *= SMALL_FIRE_HEALTH; + } + uint32_t first = Random(); + npc.projectileDelay = (int)(first % LIGHT_DELAY_RANGE) + LIGHT_DELAY_MIN + (int)(Random() % LIGHT_DELAY_RANGE); +} + +// Idle: once its delay runs out, calm and on a free cell, it starts lighting a fire if there is room for one. +static void candler_idle(Entity_NPC& npc) +{ + if (!npc.sprite.IsPlaying()) npc_anim_loop(npc.sprite, "Idle"); + if (npc.projectileDelay > 0) npc.projectileDelay--; + if (npc.projectileDelay != 0 || npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return; + if (!candler_is_free_cell(npc.pos) || !candler_is_fire_room(npc)) return; + + npc_anim_restart(npc.sprite, "Attack"); + npc.state = NPC_STATE_ATTACK; +} + +// Its drift: held in the room, pushed along its diagonal (not while lighting), and away from a near target when +// afraid. Confused, it wanders. +static void candler_drift(Entity_NPC& npc, float push) +{ + npc.pos = g_game->room->GetClampedPositionImpl(npc.pos, 0, 0, 0, 0); + uint64_t flags = npc.flags; + if ((flags & FLAG_CONFUSION) && !(flags & FLAG_CHARM)) + { + npc.friction *= CANDLER_FRICTION; + npc.pathfinder.MoveRandomly(STATUS_OBEYED); + return; + } + + float signY = npc.velocity.y >= CANDLER_TURN_SPEED_Y ? 1 : -1; + float signX = npc.velocity.x >= 0 ? 1 : -1; + npc.friction *= CANDLER_FRICTION; + if (npc.friction != 0) + { + npc.velocity.y += npc.speedMultiplier * signY * push / npc.friction; + npc.velocity.x += npc.speedMultiplier * signX * push / npc.friction; + } + if (!(flags & (FLAG_FEAR | FLAG_SHRINK))) return; + + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float distance = vector_length(away); + float flee = std::clamp((CANDLER_FLEE_RANGE - distance) * CANDLER_FLEE_SCALE, 0.0f, 1.0f); + if (flee <= 0 || npc.friction == 0) return; + + if (distance > 0) away = vector_scale(away, 1 / distance); + npc.velocity.x += away.x * flee * npc.speedMultiplier / npc.friction; + npc.velocity.y += away.y * flee * npc.speedMultiplier / npc.friction; +} + +// 004e4970 The Candler's AI: it drifts about bouncing off walls and now and then lights a moveable fire where it +// floats, kicking itself away. +void npc_candler_update(Entity_NPC& npc) +{ + float push = 1; + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc_anim_loop(npc.sprite, "Idle"); + uint32_t first = Random(); + npc.projectileDelay = (int)(Random() % LIGHT_DELAY_RANGE) + LIGHT_DELAY_MIN + (int)(first % LIGHT_DELAY_RANGE); + npc.velocity = random_direction(); + npc.splatColor = CANDLER_SPLAT_COLOR; + } + else if (npc.state == NPC_STATE_IDLE) candler_idle(npc); + else if (npc.state == NPC_STATE_ATTACK) + { + candler_light(npc); + push = 0; + } + candler_drift(npc, push); +} diff --git a/src/npc_caves.h b/src/npc_caves.h index b4d7bb1..883816e 100644 --- a/src/npc_caves.h +++ b/src/npc_caves.h @@ -16,6 +16,7 @@ void npc_one_tooth_update(Entity_NPC& npc); void npc_fat_bat_update(Entity_NPC& npc); void npc_dukie_update(Entity_NPC& npc); void npc_gurgle_update(Entity_NPC& npc); +void npc_stone_eye_update(Entity_NPC& npc); // The other enemies' AIs the dispatcher runs: the eternal fly, Pitfall and Pustule. void npc_eternal_fly_update(Entity_NPC& npc); diff --git a/src/npc_clickety_clack.cpp b/src/npc_clickety_clack.cpp index e949f91..a439f60 100644 --- a/src/npc_clickety_clack.cpp +++ b/src/npc_clickety_clack.cpp @@ -157,7 +157,7 @@ static bool clack_pile_update(Entity_NPC& npc) } if (npc.sprite.IsEventTriggered("Shoot") && !npc.IsFriendly() && !clack_any_standing()) { - for (Entity* other : g_game->room->entityList.updateEL) + for (Entity* other : entities_live(g_game->room->entityList.updateEL)) if (other->type == ENTITY_CLICKETY_CLACK && !other->HasEntityFlags(FLAG_FRIENDLY)) other->Kill(EntityRef()); return false; } diff --git a/src/npc_clotty.cpp b/src/npc_clotty.cpp index 16ae5ba..8d7936d 100644 --- a/src/npc_clotty.cpp +++ b/src/npc_clotty.cpp @@ -68,7 +68,6 @@ constexpr float GRILL_WATER_MAX = 0.2f; constexpr uint64_t DAMAGE_FIRE_CLOTTY = 1ull << 1; constexpr ColorMod CLOT_SPLAT_COLOR = {{0.02f, 0.05f, 0.05f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; -constexpr ColorMod GRILLED_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.14117648f, 0.12156863f, 0.10980392f}}; constexpr ColorMod CLOT_SHOT_COLOR = {{1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, 1}, {0, 0, 0}}; static bool is_grilled(Entity_NPC& npc) diff --git a/src/npc_collision.cpp b/src/npc_collision.cpp index a84d99c..1d8fc6a 100644 --- a/src/npc_collision.cpp +++ b/src/npc_collision.cpp @@ -15,12 +15,7 @@ #include // The NPC types whose contacts differ from the generic ones. -constexpr int ENTITY_SWARM = 281; -constexpr int ENTITY_ULTRA_COIN = 293; -constexpr int ENTITY_FISTULOID = 308; constexpr int ENTITY_BOUNCER = 822; -constexpr int ENTITY_GASBAG = 856; -constexpr int ENTITY_ARMYFLY = 868; constexpr int ENTITY_BUTT_SLICKER = 878; constexpr int ENTITY_NERVE_ENDING_2 = 964; @@ -138,6 +133,38 @@ static bool is_same_friendliness(Entity& first, Entity& second) return first.IsFriendly() == second.IsFriendly(); } +// The Black Knight's armour: a tear striking it where it cannot be hurt beeps off and, unless it shot lately, comes +// back as a shot its size, mirrored off the side it faces (down, up, or the way it looks sideways), or straight back +// when the tear grazes it. +static void black_knight_reflect(Entity_NPC& npc, Entity_Tear& tear) +{ + constexpr float KNIGHT_BEEP_VOLUME = 0.75f; + constexpr float KNIGHT_BEEP_PITCH = 0.85f; + constexpr float KNIGHT_BEEP_PITCH_RANGE = 0.08f; + constexpr float KNIGHT_GRAZE = 0.3f; + constexpr int KNIGHT_SHOT_SIZES = 13; + + if (npc.CanBeDamagedFromVelocity(tear.velocity) || npc.HasEntityFlags(FLAG_SHRINK)) return; + npc_sound_play(SOUND_BEEP, KNIGHT_BEEP_VOLUME, 2, random_unit() * KNIGHT_BEEP_PITCH_RANGE + KNIGHT_BEEP_PITCH); + if (npc.projectileCooldown >= 1) return; + + Vector facing = vector_make(0, 1); + const std::string& animation = npc.sprite.GetAnimation(); + if (animation == "Up") facing = vector_make(0, -1); + else if (animation == "Hori") facing = vector_make(npc.sprite.isFlipX ? -1.0f : 1.0f, 0); + if (std::abs(vector_dot(facing, vector_normalized(tear.velocity))) < KNIGHT_GRAZE) + facing = vector_normalized(vector_sub(tear.pos, npc.pos)); + + ProjectileParams params; + int size = 1; + for (size_t i = 0; i + 1 < TEAR_ANIMATION_SCALES.size() && tear.fScale > TEAR_ANIMATION_SCALES[i] + TEAR_ANIMATION_MARGIN; i++) + size++; + params.scale = ((float)std::min(size, KNIGHT_SHOT_SIZES) - 3) / 3; + float along = vector_dot(facing, tear.velocity); + Vector mirrored = vector_sub(tear.velocity, vector_scale(facing, along + along)); + npc.FireProjectiles(npc.pos, mirrored, PROJECTILES_SINGLE, params); +} + // The first contacts, before the AI's collision call: Dark Esau passes shots, a white fire spares a player it cannot // hurt, a magnetized enemy collides with the enemies of another target and minecarts pass each other. static Verdict contact_early(Contact& contact) @@ -157,8 +184,7 @@ static Verdict contact_early(Contact& contact) if (collider.type == ENTITY_TEAR && npc.type == ENTITY_KNIGHT && npc.variant == KNIGHT_BLACK) { TearFlags& flags = collider.ToTear()->tearFlags; - if (!flags[TEAR_EXPLOSIVE] && !flags[TEAR_LUDOVICO]) - reconstruction_missing("Entity_NPC::HandleCollision 006cd410: the Black Knight's tear reflection"); + if (!flags[TEAR_EXPLOSIVE] && !flags[TEAR_LUDOVICO]) black_knight_reflect(npc, *collider.ToTear()); } if (collider.type == ENTITY_PLAYER && npc.type == ENTITY_MINECART && npc.variant == MINECART_EXIT) reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a minecart leaving the room"); diff --git a/src/npc_depths.h b/src/npc_depths.h index 404d108..13d0954 100644 --- a/src/npc_depths.h +++ b/src/npc_depths.h @@ -30,3 +30,23 @@ 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); +void npc_black_maw_update(Entity_NPC& npc); +void npc_fistuloid_update(Entity_NPC& npc); +void npc_mr_mine_update(Entity_NPC& npc); +void npc_tarboy_update(Entity_NPC& npc); +void npc_ultra_coin_update(Entity_NPC& npc); +void npc_ultra_door_update(Entity_NPC& npc); +Entity_NPC* ultra_door_opposite(Entity_NPC& door, const std::vector& doors); +void npc_ultra_greed_update(Entity_NPC& npc); +void ultra_greed_heal(Entity_NPC& greed, int amount); +bool greed_coin_collect(Entity_Pickup& coin, Entity* collector); + +// Ultra Greed's coins by variant (spinner, key, bomb, heart), and the bomb coin that leaves a penny. +constexpr int COIN_SPINNER = 0; +constexpr int COIN_KEY = 1; +constexpr int COIN_BOMB = 2; +constexpr int COIN_HEART = 3; +constexpr int ULTRA_COIN_PENNY_SUBTYPE = 1; + +// The gold blast of Ultra Greed's bomb coins and smashes. +constexpr ColorMod ULTRA_GREED_BLAST_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.5f, 0.25f, 0}}; diff --git a/src/npc_dip.cpp b/src/npc_dip.cpp index 71114e6..2ca754c 100644 --- a/src/npc_dip.cpp +++ b/src/npc_dip.cpp @@ -36,7 +36,6 @@ constexpr float DRIP_CURRENT_PUSH = 8; constexpr float DRIP_FRICTION = 0.9f; constexpr int DRIP_REHOP_FRAME = 10; constexpr int DRIP_REHOP_ODDS = 3; -constexpr float CONTROLLER_DEADZONE = 0.1f; // A hop: a random way (away from its target while it fears it), faster for the corn dips. The Drip hops at its // target one time in three and against the room's current. diff --git a/src/npc_dople.cpp b/src/npc_dople.cpp new file mode 100644 index 0000000..343e309 --- /dev/null +++ b/src/npc_dople.cpp @@ -0,0 +1,234 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "npc_gehenna.h" +#include +#include "entity_player.h" +#include "room.h" +#include "weapon.h" + +// The Dople (variant 0) and Evil Twin (variant 1) mirror their player through the room's center, facing the other +// way (the same way when confused), and shoot back whenever the player shoots. The Dople alternates its shots side to +// side, the Evil Twin shoots three at once every 30 frames. A controlled one walks as a player does. +constexpr int EVIL_TWIN = 1; +constexpr float MIRROR_FRICTION = 0.75f; +constexpr float MIRROR_SPEED_SCALE = 2; +constexpr int MIRROR_TURN = 2; +constexpr int DOPLE_DIRECTIONS = 4; +constexpr float DOPLE_SHOT_SPEED = 10; +constexpr float SHOT_CARRY = 0.6f; +constexpr float DOPLE_SHOT_SCALE = 1.4f; +constexpr float SHOT_FALL_SPEED = 1; +constexpr float DOPLE_SHOT_FALL_ACCEL = -0.101f; +constexpr float SHOT_SIDE = 0.2f; +constexpr float SHOT_SIDE_MIN = 0.3f; +constexpr int TWIN_SHOT_COOLDOWN = 30; +constexpr int CONTROLLED_SHOT_COOLDOWN = 10; +constexpr int DOPLE_HEAD_SHOOT_FRAMES = 3; +constexpr int DOPLE_HEAD_SHOOT_FRAME = 2; +constexpr float SHOT_CONTROL_RANGE = 1000; + +// A controlled one moves in two half steps: the input fades the velocity across it, accelerates it (more against its +// motion) and damps it. +constexpr float CONTROL_DAMPING = 0.775f; +constexpr float CONTROL_ACROSS_FADE = 0.8f; +constexpr float CONTROL_TURN_BOOST = -0.2f; +constexpr float CONTROL_ACCEL = 3; +constexpr float CONTROL_ACCEL_SCALE = 0.4f; +constexpr float CONTROL_IDLE_SPEED_SQUARED = 0.01f; + +// Its walk speeds up its animation: from half speed at 1 to full at 2.3, and up to double past 6. +constexpr float WALK_MIN_SPEED = 1; +constexpr float WALK_FULL_SPEED = 2.3f; +constexpr float WALK_SPAN = 1.3f; +constexpr float DOPLE_WALK_FAST_SPEED = 6; +constexpr float WALK_FAST_SCALE = 0.25f; + +// Mirroring: it stands opposite its player, its velocity doubled back, facing away from the player's head. +static int dople_mirror(Entity_NPC& npc, Entity& target, int facing) +{ + npc.friction *= MIRROR_FRICTION; + Vector center = Room::GetCenterPos(); + facing = (facing + MIRROR_TURN) % DOPLE_DIRECTIONS; + if (npc.HasEntityFlags(FLAG_CONFUSION)) facing = (facing + MIRROR_TURN) % DOPLE_DIRECTIONS; + npc.targetPosition = npc.pos; + npc.pos = vector_sub(vector_scale(center, MIRROR_SPEED_SCALE), target.pos); + Vector away = vector_sub({}, target.velocity); + npc.velocity = vector_add(away, away); + return facing; +} + +// Controlled: two half steps of a player's walk, facing where it is steered (or moves, or down when still). +static int dople_steer(Entity_NPC& npc, Vector input) +{ + Vector v = vector_scale(npc.velocity, HALF); + float damping = std::sqrt(CONTROL_DAMPING); + Vector half = vector_scale(input, HALF); + for (int step = 0; step < 2; step++) + { + if (!vector_is_zero(input)) + { + Vector along = vector_scale(input, vector_dot(v, input)); + v = vector_add(vector_scale(vector_sub(v, along), std::sqrt(CONTROL_ACROSS_FADE)), along); + } + float accel = (std::max(vector_dot(v, input) * CONTROL_TURN_BOOST, 0.0f) + CONTROL_ACCEL) * CONTROL_ACCEL_SCALE; + float factor = timescale_factor(damping, npc.speedMultiplier); + v.x = (half.x * accel * npc.speedMultiplier + v.x) * factor; + v.y = (half.y * accel * npc.speedMultiplier + v.y) * factor; + } + npc.velocity = vector_add(v, v); + + Vector steer = npc.GetControllerMovementInput(CONTROLLER_DEADZONE); + if (!vector_is_zero(steer)) return axis_direction_get(steer); + if (vector_length_squared(npc.velocity) <= CONTROL_IDLE_SPEED_SQUARED) return DIRECTION_DOWN; + return axis_direction_get(npc.velocity); +} + +// Its shot (unless afraid or on cooldown): along its facing (or its controller's aim) carrying a share of its own +// motion, the Dople's set off to alternating sides, the Evil Twin's three wide. +static void dople_shoot(Entity_NPC& npc, int facing) +{ + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.projectileCooldown >= 1) return; + + ProjectileParams params; + params.fallingSpeedModifier = SHOT_FALL_SPEED; + params.fallingAccelModifier = DOPLE_SHOT_FALL_ACCEL; + params.scale = DOPLE_SHOT_SCALE; + Vector aim = vector_from_direction(facing); + if (npc.controllerID != -1) aim = vector_cardinal(npc.GetControllerMovementInput(CONTROLLER_DEADZONE)); + Vector carry = vector_scale(npc.velocity, SHOT_CARRY); + Vector along = vector_scale(aim, vector_dot(carry, aim)); + if (vector_dot(along, aim) < 0) carry = vector_sub(carry, along); + Vector shot = vector_add(vector_scale(aim, DOPLE_SHOT_SPEED), carry); + + Vector origin = npc.pos; + if (npc.i2 != 0) + { + float side = random_unit() * SHOT_SIDE + SHOT_SIDE_MIN; + origin.x -= npc.i2 * shot.y * side; + origin.y -= npc.i2 * shot.x * side; + } + ProjectilesMode mode = PROJECTILES_SINGLE; + if (npc.variant == EVIL_TWIN) + { + npc.projectileCooldown = TWIN_SHOT_COOLDOWN; + mode = PROJECTILES_THREE; + } + else if (npc.controllerID != -1) npc.projectileCooldown = CONTROLLED_SHOT_COOLDOWN; + npc.FireProjectiles(origin, shot, mode, params); + npc.projectileDelay = DOPLE_HEAD_SHOOT_FRAMES; + npc.i2 = -npc.i2; +} + +// Its head faces its way, its mouth open a moment after a shot. +static void dople_head_animate(Entity_NPC& npc, int facing) +{ + int frame = npc.projectileDelay >= 1 ? DOPLE_HEAD_SHOOT_FRAME : 0; + if (facing == DIRECTION_DOWN) return npc.sprite.SetOverlayFrame("HeadDown", frame); + if (facing == DIRECTION_UP) return npc.sprite.SetOverlayFrame("HeadUp", frame); + + npc.sprite.SetOverlayFrame("HeadHori", frame); + npc.sprite.GetLayer(1)->isFlipX = facing == DIRECTION_LEFT; +} + +// A controlled one walks by its input, its animation quickening with its speed. +static void dople_steered_walk_animate(Entity_NPC& npc, Vector input) +{ + std::string_view walk = npc.variant == EVIL_TWIN ? "WalkDown" : "WalkVert"; + bool isFlipX = false; + bool isStill = vector_is_zero(input); + if (isStill && npc.variant != EVIL_TWIN) npc.sprite.SetFrame(walk, 0); + else + { + if (!isStill && std::abs(input.x) > std::abs(input.y)) + { + walk = "WalkHori"; + isFlipX = input.x < 0; + } + else if (!isStill && npc.variant == EVIL_TWIN) walk = input.y >= 0 ? "WalkDown" : "WalkUp"; + npc.sprite.Play(walk); + } + npc.sprite.GetLayer(0)->isFlipX = isFlipX; + + float playback = 1; + if (npc.sprite.IsPlaying()) + { + float speed = vector_length(npc.velocity); + if (speed < WALK_FULL_SPEED) playback = std::clamp((speed - WALK_MIN_SPEED) / WALK_SPAN, 0.0f, 1.0f) * HALF + HALF; + if (speed > DOPLE_WALK_FAST_SPEED) playback = std::clamp((speed - DOPLE_WALK_FAST_SPEED) * WALK_FAST_SCALE, 0.0f, 1.0f) + 1; + } + npc.sprite.playbackSpeed = playback; +} + +// A mirroring one walks the way it moves, or the way it was pushed since last frame, standing still once it is not. +static void dople_mirror_walk_animate(Entity_NPC& npc, int facing) +{ + std::string_view walk = "WalkVert"; + if (vector_length(npc.velocity) >= WALK_MIN_SPEED) + { + if (std::abs(npc.velocity.y) < std::abs(npc.velocity.x)) + { + npc.sprite.Play("WalkHori"); + npc.sprite.GetLayer(0)->isFlipX = npc.velocity.x < 0; + return; + } + if (npc.variant != 0) walk = npc.velocity.y <= 0 ? "WalkUp" : "WalkDown"; + return npc.sprite.Play(walk); + } + + float moveX = std::abs(npc.pos.x - npc.targetPosition.x); + float moveY = std::abs(npc.pos.y - npc.targetPosition.y); + if (moveX < WALK_MIN_SPEED && moveY < WALK_MIN_SPEED) + { + if (npc.variant == 0) return npc.sprite.SetFrame("WalkVert", 0); + return npc.sprite.SetFrame(facing != DIRECTION_UP ? "WalkDown" : "WalkUp", 0); + } + if (moveY < moveX) + { + npc.sprite.Play("WalkHori"); + npc.sprite.GetLayer(0)->isFlipX = npc.velocity.x < 0; + return; + } + // The original tests the distance moved, never negative, so a twin pushed upright always walks up. + if (npc.variant != 0) walk = moveY <= 0 ? "WalkDown" : "WalkUp"; + npc.sprite.Play(walk); +} + +// 00525650 The Dople's and Evil Twin's AI: they stand opposite their player across the room's center, mirroring +// its moves, and shoot back each time it shoots. +void npc_dople_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.ClearEntityFlags(FLAG_APPEAR); + npc.projectileDelay = 0; + npc.projectileCooldown = 0; + npc.state = NPC_STATE_MOVE; + if (npc.variant == 0) npc.i2 = 1; + npc.entityGridCollisionClass = npc.variant == 0 ? GRIDCOLL_GROUND : GRIDCOLL_WALLS; + return; + } + + Entity* target = npc.GetPlayerTarget(); + Entity_Player* player = target->type == ENTITY_PLAYER ? target->ToPlayer() : nullptr; + int facing = player ? (int)player->headDirection : axis_direction_get(target->velocity); + Vector input{}; + if (npc.controllerID == -1) facing = dople_mirror(npc, *target, facing); + else + { + input = npc.GetControllerInput(0); + facing = dople_steer(npc, input); + } + + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + if (npc.projectileDelay > 0) npc.projectileDelay -= npc_ticks_get(npc); + Weapon* tears = player ? player->weapons[1].get() : nullptr; + int fireDelay = tears ? (int)tears->fireDelay : 0; + bool isShooting = npc.controllerID == -1 ? player && npc.i1 < fireDelay + : npc.IsTargetInAttackRange(SHOT_CONTROL_RANGE, 0, true); + if (isShooting) dople_shoot(npc, facing); + if (player) npc.i1 = fireDelay; + + dople_head_animate(npc, facing); + if (npc.controllerID != -1) dople_steered_walk_animate(npc, input); + else dople_mirror_walk_animate(npc, facing); +} diff --git a/src/npc_evis.cpp b/src/npc_evis.cpp new file mode 100644 index 0000000..ce21f76 --- /dev/null +++ b/src/npc_evis.cpp @@ -0,0 +1,273 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "capsule.h" +#include "room_grid.h" +#include + +// Evis walks the grid's axes, marking its cell, and lashes out its cord at a target in line within 30 (or across the +// row within 300), aiming up to 50 degrees off its axis ahead of the target's path. +constexpr float EVIS_WALK_SPEED = 0.7f; +constexpr float EVIS_FRICTION = 0.8f; +constexpr int EVIS_PATH_MARKER = 900; +constexpr float EVIS_WALK_THRESHOLD = 0.1f; +constexpr float LASH_ALIGN = 30; +constexpr float LASH_RANGE = 300; +constexpr float LASH_LEAD = 0.1f; +constexpr float LASH_SPREAD = 50; +constexpr float LASH_START = 10; +constexpr float CORD_REST_LENGTH = 160; + +// Reeling a caught player in, its cord's rest length shortens a third a frame down to 10, swelling the cord to 6. +// A stretched cord pulls the player in and Evis a quarter as hard toward them. +constexpr float REEL_SPEED = 0.33f; +constexpr float REEL_MIN = 10; +constexpr float CORD_SWELL = 6; +constexpr float CORD_LIFT = -24; +constexpr float EVIS_LEASH_PULL = 0.14f; +constexpr float LEASH_SELF_SHARE = 0.25f; + +// The cord: seven points laid from Evis out to its tip, the inner five jostled to alternate sides. Its tip flies out +// and back over 15 frames, 200 at the farthest, until it catches a player, whom it holds 10 up (20 when flying). +constexpr int EVIS_CORD_POINTS = 7; +constexpr float CORD_HEIGHT = -20; +constexpr float CORD_JOSTLE = 4; +constexpr float CORD_JOSTLE_SPEED = 20; +constexpr float EVIS_CORD_DEPTH = 16; +constexpr float CORD_FLIGHT_FRAMES = 15; +constexpr float CORD_REACH = 200; +constexpr float CORD_REEL_SHARE = 0.2f; +constexpr float CORD_DRAG = 0.2f; +constexpr float HOLD_HEIGHT = -10; +constexpr float HOLD_HEIGHT_FLYING = -20; +constexpr float CATCH_VOLUME = 0.5f; +constexpr int CATCH_SHAKE = 6; + +// Plays the cord pose (Pull or Attack01) facing its lash (v1). +static void evis_pose_play(Entity_NPC& npc, std::string_view side, std::string_view up, std::string_view down) +{ + if (std::abs(npc.v1.y) > std::abs(npc.v1.x)) return npc.sprite.Play(npc.v1.y >= 0 ? down : up); + + npc.sprite.Play(side); + npc.sprite.isFlipX = npc.v1.x < 0; +} + +// Its lash: on Shoot the cord flies at the target's path, clamped to 50 degrees off the lash's axis. +static void evis_lash(Entity_NPC& npc) +{ + evis_pose_play(npc, "Attack01Horiz", "Attack01Up", "Attack01Down"); + if (npc.sprite.IsEventTriggered("Shoot")) + { + Entity* target = npc.GetPlayerTarget(); + float lead = vector_distance(npc.pos, target->pos) * LASH_LEAD; + float axis = vector_angle(vector_cardinal(npc.v1)); + Vector aim = vector_normalized(vector_sub(vector_add(target->pos, vector_scale(target->velocity, lead)), npc.pos)); + float offset = std::clamp(normalize_angle_degrees(vector_angle(aim) - axis), -LASH_SPREAD, LASH_SPREAD); + Vector direction = vector_from_angle(offset + axis); + + Entity* cord = g_game->Spawn({.position = vector_add(npc.pos, vector_scale(direction, LASH_START)), + .spawner = &npc, + .type = ENTITY_EVIS, + .variant = EVIS_CORD, + .seed = Random()}); + cord->parent = &npc; + cord->targetPosition = direction; + npc.child = cord; + cord->Update(); + npc_sound_play(SOUND_MEATHEADSHOOT, 1, 2, 1); + npc.aiFloat = CORD_REST_LENGTH; + } + if (npc.sprite.IsFinished()) npc.state = NPC_STATE_IDLE; +} + +// Reeling: its cord shortens and swells while it holds on. +static void evis_reel(Entity_NPC& npc) +{ + npc.friction *= EVIS_FRICTION; + evis_pose_play(npc, "PullHoriz", "PullUp", "PullDown"); + npc.aiFloat = std::max(npc.aiFloat - REEL_SPEED, REEL_MIN); + Entity_NPC* cord = npc.ChildNPC(); + if (!cord) + { + npc.state = NPC_STATE_IDLE; + return; + } + cord->aiFloat = std::clamp(npc.aiFloat / CORD_REST_LENGTH, 0.0f, 1.0f) * CORD_SWELL; + cord->posOffset = vector_make(0, CORD_LIFT); +} + +// A cord that caught someone keeps Evis reeling, both drawn together past its rest length. +static void evis_leash(Entity_NPC& npc) +{ + Entity_NPC* cord = npc.ChildNPC(); + Entity* caught = cord ? cord->target.get() : nullptr; + if (!caught) return; + + npc.state = NPC_STATE_STOMP; + Vector away = vector_sub(npc.pos, caught->pos); + float stretch = std::max(vector_length(away) - npc.aiFloat, 0.0f); + Vector pull = vector_scale(vector_scale(vector_normalized(away), stretch), EVIS_LEASH_PULL); + npc.velocity = vector_sub(npc.velocity, vector_scale(vector_scale(pull, LEASH_SELF_SHARE), npc.speedMultiplier)); + caught->velocity = vector_add(caught->velocity, vector_scale(pull, caught->speedMultiplier)); + npc.v1 = vector_normalized(vector_sub(caught->pos, npc.pos)); +} + +// The cord's first frame: laid from Evis to its tip, the inner points jostled to alternate sides. It takes no part +// in the room and asks for the update and interpolation calls before each update. +static void evis_cord_init(Entity_NPC& cord, Entity& evis) +{ + cord.splatColor = COLOR_GREEN_SPLAT; + cord.ClearEntityFlags(FLAG_APPEAR); + cord.AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + Vector side = vector_rotated(cord.targetPosition, RIGHT_ANGLE_DEGREES); + std::deque& points = cord.vectorDeque1; + for (int i = 0; i < EVIS_CORD_POINTS; i++) + { + float along = (float)i / (EVIS_CORD_POINTS - 1); + points.push_back(vector_add(vector_scale(vector_sub(cord.pos, evis.pos), along), evis.pos)); + points.push_back({}); + points.push_back(vector_make(CORD_HEIGHT, 0)); + if (i == 0 || i == EVIS_CORD_POINTS - 1) continue; + + float sign = i & 1 ? 1 : -1; + Vector& point = points[points.size() - CORD_STRIDE]; + point = vector_add(vector_scale(vector_scale(side, random_unit() * CORD_JOSTLE), sign), point); + Vector& speed = points[points.size() - CORD_STRIDE + 1]; + speed = vector_add(vector_scale(vector_scale(side, random_unit() * CORD_JOSTLE_SPEED), sign), speed); + } + cord.vectorDeque2 = cord.vectorDeque1; + cord.aiCallFlags = AI_CALL_PRE_UPDATE | AI_CALL_INTERPOLATE; + cord.state = NPC_STATE_IDLE; + cord.entityGridCollisionClass = GRIDCOLL_NONE; + cord.entityCollisionClass = ENTCOLL_NONE; + cord.sprite.SetFrame("Gut", 0); + cord.renderDepthOffset += EVIS_CORD_DEPTH; +} + +// Before its update the cord holds its catch, or catches the first player a stretch of it touches. +static void evis_cord_catch(Entity_NPC& cord) +{ + if (Entity* caught = cord.target.get()) + { + cord.velocity = vector_sub(caught->pos, cord.pos); + cord.posOffset.y = caught->IsFlying() ? HOLD_HEIGHT_FLYING : HOLD_HEIGHT; + } + for (size_t i = 0; i < cord.vectorDeque1.size() && !cord.target; i += CORD_STRIDE) + { + Capsule capsule = cord.GetCollisionCapsule(vector_sub(cord.vectorDeque1[i], cord.pos)); + for (Entity* entity : entity_query_capsule(capsule, QUERY_PLAYERS)) + { + if (entity->type != ENTITY_PLAYER) continue; + + npc_sound_play(SOUND_MEATY_DEATHS, CATCH_VOLUME, 2, 1); + game_shake_screen(CATCH_SHAKE); + entity->velocity = {}; + cord.target = entity; + break; + } + } +} + +// The cord's flight before and during an interpolation: free, its tip flies out and back and is gone once back, +// reeling its points in on the way back. Its ends then follow Evis and the tip and it steps (a half step drawn only). +static void evis_cord_flight(Entity_NPC& cord, bool isInterpolation) +{ + Entity* evis = cord.parent.get(); + if (!cord.target) + { + float lag = isInterpolation ? cord.speedMultiplier * -HALF : 0; + float flight = (lag + cord.updateTime) / CORD_FLIGHT_FRAMES; + float arc = flight + flight - 1; + float reach = (1 - arc * arc) * CORD_REACH; + if (flight > 0 && reach <= 0) + { + if (!isInterpolation) cord.Remove(); + return; + } + if (evis) + { + cord.pos = vector_add(vector_scale(cord.targetPosition, reach), evis->pos); + if (flight > HALF && !isInterpolation) + for (size_t i = 0; i + CORD_STRIDE < EVIS_CORD_POINTS * CORD_STRIDE; i += CORD_STRIDE) + { + Vector reel = vector_scale(vector_sub(evis->pos, cord.vectorDeque1[i]), CORD_REEL_SHARE); + cord.vectorDeque1[i + 1] = vector_add(vector_scale(reel, cord.speedMultiplier), cord.vectorDeque1[i + 1]); + } + } + } + std::deque& points = cord.vectorDeque1; + if (!evis || points.empty()) return; + + points[0] = evis->pos; + points[1] = vector_scale(evis->velocity, CORD_DRAG); + points[2] = vector_make(CORD_HEIGHT, 0); + points[points.size() - 3] = cord.pos; + points[points.size() - 2] = cord.velocity; + points[points.size() - 1] = vector_make(cord.posOffset.y, 0); + cord.UpdateCordChain(isInterpolation); +} + +// Evis' cord (variant 10): laid out on its first frame, it flies out and back until it catches a player. Without +// Evis it dies, and on dying it bursts into blood along its points. +static void evis_cord_update(Entity_NPC& cord) +{ + bool isInterpolation = cord.aiCallPhase == AI_PHASE_INTERPOLATE; + if (cord.aiCallPhase == AI_PHASE_PRE_UPDATE || isInterpolation) + { + if (cord.aiCallPhase == AI_PHASE_PRE_UPDATE && !cord.parent) return cord.Kill(EntityRef()); + if (cord.aiCallPhase == AI_PHASE_PRE_UPDATE) evis_cord_catch(cord); + return evis_cord_flight(cord, isInterpolation); + } + + if (cord.state == NPC_STATE_INIT) + { + if (!cord.parent) return cord.Remove(); + evis_cord_init(cord, *cord.parent); + } + if (!cord.isDead) return; + + for (size_t i = 0; i < EVIS_CORD_POINTS * CORD_STRIDE; i += CORD_STRIDE) + if (i + 2 < cord.vectorDeque1.size()) + blood_explosion_spawn(1, cord.vectorDeque1[i], vector_make(0, cord.vectorDeque1[i + 2].x), cord.splatColor, {}); +} + +// 004df3f0 Evis' AI: it walks the grid's axes and lashes its cord at a target in line, reeling in a player it +// catches. Its cord (variant 10) flies out, catches and holds. +void npc_evis_update(Entity_NPC& npc) +{ + if (npc.variant == EVIS_CORD) return evis_cord_update(npc); + if (npc.state != NPC_STATE_INIT) + { + npc.friction *= EVIS_FRICTION; + room_path_raise_at(npc.pos, EVIS_PATH_MARKER); + } + + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_IDLE; + npc.splatColor = COLOR_GREEN_SPLAT; + break; + case NPC_STATE_IDLE: + { + npc.AnimWalkFrame("WalkHori", "WalkHori", EVIS_WALK_THRESHOLD); + npc.pathfinder.MoveRandomlyAxisAligned(EVIS_WALK_SPEED, STATUS_OBEYED); + if (!npc.IsFrame(3, npc.index)) break; + + Vector toward = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + bool isInLine = std::abs(toward.x) < LASH_ALIGN || + (std::abs(toward.y) < LASH_ALIGN && vector_length(toward) < LASH_RANGE); + if (!isInLine) break; + + npc.state = NPC_STATE_ATTACK; + npc.v1 = toward; + break; + } + case NPC_STATE_STOMP: + evis_reel(npc); + break; + case NPC_STATE_ATTACK: + evis_lash(npc); + break; + } + evis_leash(npc); +} diff --git a/src/npc_fireplace.cpp b/src/npc_fireplace.cpp index 82715b2..c45bb04 100644 --- a/src/npc_fireplace.cpp +++ b/src/npc_fireplace.cpp @@ -7,6 +7,7 @@ #include "game.h" #include "npc_ai.h" #include "npc_alt.h" +#include "npc_caves.h" #include "room.h" #include @@ -84,6 +85,26 @@ constexpr float RELIGHT_BLUE = 0.5f; // The sounds of a fire: lit again, and put out. constexpr float PUT_OUT_VOLUME = 0.85f; +// A moveable fire burns, then fades in Disappear. A plain one lasts 300 frames (180 colliding with the grid), a blue +// one loses a health each time its speed adds up to 90, and a purple one lasts. Its flame never shrinks below a tenth. +constexpr int MOVEABLE_FIRE_BURNING = NPC_STATE_IDLE; +constexpr int MOVEABLE_FIRE_FADING = NPC_STATE_SPECIAL; +constexpr int MOVEABLE_FIRE_FRAMES = 300; +constexpr int MOVEABLE_FIRE_GRID_FRAMES = 180; +constexpr float MOVEABLE_FIRE_BLUE_BURN = 90; +constexpr float MOVEABLE_FIRE_FADED_HEALTH = 0.01f; +constexpr float MOVEABLE_FLAME_MIN = 0.1f; +constexpr int MOVEABLE_FLAME_LAYER = 0; +constexpr uint64_t MOVEABLE_FIRE_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | FLAG_NO_DEATH_TRIGGER | + FLAG_NO_FLASH_ON_DAMAGE | FLAG_NO_PHYSICS_KNOCKBACK; + +// A moveable fire coasts to a stop, or is pulled to its target. The Beast's fires neither coast nor stop, and every 30 +// frames one in four goes out on its own. +constexpr float MOVEABLE_FIRE_COAST = 0.95f; +constexpr float MOVEABLE_FIRE_PULL = 0.6f; +constexpr float BEAST_FIRE_INTERVAL = 30; +constexpr uint32_t BEAST_FIRE_ODDS = 4; + // What a fire drops: one time in four (one in ten on Hard), from normal fires a heart one time in four and else a // coin, from blue fires a soul heart (a black heart past one Daemon's Tail). Daemon's Tail turns four hearts in five // away, by its own RNG off the drop RNG. @@ -383,6 +404,111 @@ static void fire_ember_update(Entity_NPC& npc) if (color) ember->SetColor(*color, -1, EMBER_PRIORITY, false, true); } +// Sizes a moveable fire's flame to its health, a tenth at the least. +static void moveable_flame_size_set(Entity_NPC& npc) +{ + float share = npc.health * (1 - MOVEABLE_FLAME_MIN) / npc.maxHitPoints + MOVEABLE_FLAME_MIN; + npc.sprite.GetLayer(MOVEABLE_FLAME_LAYER)->size = vector_make(share, share); +} + +// Starts a moveable fire fading: it stops colliding and plays Disappear. +static void moveable_fire_fade(Entity_NPC& npc) +{ + npc.state = MOVEABLE_FIRE_FADING; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; +} + +// Whether a burning moveable fire burnt out with time: a blue one by its speed, a plain one by its age. +static bool moveable_fire_is_burnt(Entity_NPC& npc) +{ + if (npc.variant == FIRE_MOVEABLE_PURPLE) return false; + if (npc.variant != FIRE_MOVEABLE_BLUE) + return g_game->frameCount - npc.spawnFrame > (npc.entityGridCollisionClass ? MOVEABLE_FIRE_GRID_FRAMES : MOVEABLE_FIRE_FRAMES); + + npc.v1.x += npc.speedMultiplier; + if (npc.v1.x <= MOVEABLE_FIRE_BLUE_BURN) return false; + + npc.v1.x -= MOVEABLE_FIRE_BLUE_BURN; + npc.health = std::max(npc.health - 1, FIRE_OUT_HEALTH); + moveable_flame_size_set(npc); + return npc.health < FIRE_LIT_HEALTH; +} + +// A burning moveable fire's hits: an explosion puts it out, other hits cost a plain one health as a fire's do (blue +// and purple ones shrug them off). Put out, it fades with a hiss, silent when it went out on its own. +static void moveable_fire_damage_update(Entity_NPC& npc) +{ + bool isHitProof = npc.variant == FIRE_MOVEABLE_BLUE || npc.variant == FIRE_MOVEABLE_PURPLE; + if (npc.pendingDamage <= 0) return; + + if (npc.pendingDamageFlags & DAMAGE_EXPLOSION) npc.health = FIRE_OUT_HEALTH; + else if (!isHitProof) + { + for (DamageEvent& event : npc.damageEvents) + if (event.damage > 0) npc.health -= hit_cost_get(event.damage); + npc.health = std::max(npc.health, FIRE_OUT_HEALTH); + } + moveable_flame_size_set(npc); + if (npc.health >= FIRE_LIT_HEALTH) return; + + moveable_fire_fade(npc); + npc_anim_loop(npc.sprite, "Disappear"); + if (!(npc.pendingDamageFlags & DAMAGE_TIMER)) npc_sound_play(SOUND_STEAM_HALFSEC, PUT_OUT_VOLUME, 2, 1); +} + +// A burning moveable fire: it idles, coasts or is pulled to its target, burns out, and takes its hits. +static void moveable_fire_burn(Entity_NPC& npc) +{ + bool isBeastFire = npc.spawnerType == ENTITY_BEAST; + if (npc_anim_is_done(npc)) npc_anim_loop(npc.sprite, "Idle"); + + if (!vector_is_zero(npc.targetPosition)) + { + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + npc.friction *= MOVEABLE_FIRE_PULL; + } + else if (!isBeastFire) npc.friction *= MOVEABLE_FIRE_COAST; + + if (moveable_fire_is_burnt(npc)) + { + moveable_fire_fade(npc); + npc.sprite.Play("Disappear"); + return; + } + if (isBeastFire && npc.GetIntervalTicks(BEAST_FIRE_INTERVAL, 0) && Random() % BEAST_FIRE_ODDS == 0) + npc.TakeDamage(1, DAMAGE_TIMER, EntityRef(), FIRE_WATER_DAMAGE_COUNTDOWN); + moveable_fire_damage_update(npc); +} + +// 006d0ec0 NpcHelper::fireplace_moveable_update: a moveable fire (the Flaming Fatty's, the Beast's, the blue and purple +// ones of fire items). It appears, burns until time or hits put it out, then fades away and is removed. Water douses +// a plain one here as well as in the fireplace's AI. +static void fire_moveable_update(Entity_NPC& npc) +{ + if (npc.variant == FIRE_MOVEABLE && g_game->room->waterAmount > FIRE_WATER_LEVEL && npc.IsFrame(FIRE_WATER_FRAMES, (int)npc.index)) + npc.TakeDamage(1, 0, EntityRef(), FIRE_WATER_DAMAGE_COUNTDOWN); + + if (npc.state == NPC_STATE_INIT) + { + npc.ClearEntityFlags(FLAG_APPEAR); + npc.AddEntityFlags(MOVEABLE_FIRE_FLAGS); + moveable_flame_size_set(npc); + npc_anim_loop(npc.sprite, "Appear"); + npc.state = MOVEABLE_FIRE_BURNING; + if (!vector_is_zero(npc.targetPosition)) npc.entityGridCollisionClass = GRIDCOLL_NONE; + } + else if (npc.state == MOVEABLE_FIRE_BURNING) moveable_fire_burn(npc); + else if (npc.state == MOVEABLE_FIRE_FADING) + { + npc.health = std::max(npc.health - 1, MOVEABLE_FIRE_FADED_HEALTH); + if (npc_anim_is_done(npc)) npc.Remove(); + } + npc.damageEvents.clear(); + npc.pendingDamage = 0; + npc.pendingDamageFlags = 0; +} + // 006d18d0 The fireplace's AI: normal fires are doused by water and put out by shots, red ones spit, blue and purple // ones go out only to explosions, white ones never. A lit fire hurts what touches it, throws embers and drops loot // when put out. A fire that is out and finds a grid entity under it, off a minecart, is removed. Moveable fires and @@ -393,7 +519,7 @@ void npc_fireplace_update(Entity_NPC& npc) npc.TakeDamage(1, 0, EntityRef(), FIRE_WATER_DAMAGE_COUNTDOWN); if (npc.variant == FIRE_COAL) return npc_rock_spider_update(npc); if (npc.variant == FIRE_MOVEABLE || npc.variant == FIRE_MOVEABLE_BLUE || npc.variant == FIRE_MOVEABLE_PURPLE) - return NpcHelper::fireplace_moveable_update(&npc); + return fire_moveable_update(npc); if (npc.state == NPC_STATE_INIT) return fire_init(npc); if (npc.state == FIRE_STATE_RELIGHT) fire_relight(npc); diff --git a/src/npc_fistuloid.cpp b/src/npc_fistuloid.cpp new file mode 100644 index 0000000..407ad79 --- /dev/null +++ b/src/npc_fistuloid.cpp @@ -0,0 +1,230 @@ +#include "npc_alt.h" +#include "active_items.h" +#include "boss_ai.h" +#include "entity_projectile.h" +#include "manager.h" +#include "menu_manager.h" +#include "room_grid.h" +#include + +// The Fistuloid weaves after its target (or circles the Matriarch, its parent, unless it is her held one), and near +// its target now and then spits a shot, recoiling. Killed, it ejects a Chubber worm along the way its target lies. +constexpr float FISTULOID_SPEED = 0.7f; +constexpr float FISTULOID_FRICTION = 0.9f; +constexpr float SPIT_RANGE_SQUARED = 10000; +constexpr uint32_t FISTULOID_SPIT_ODDS = 5; +constexpr float FISTULOID_SPIT_CONTROL_RANGE = 1000; +constexpr float FISTULOID_SPIT_SPEED = 10; +constexpr float SPIT_RECOIL = 1.2f; +constexpr int FISTULOID_SPIT_COOLDOWN = 30; +constexpr int MATRIARCH_SPITTING = NPC_STATE_ATTACK2; + +// Around the Matriarch it keeps an ellipse 90 wide and 76 high, its angle (v1.x) turning with the game's frames, +// closing at most 10 a frame. +constexpr float FISTULOID_ORBIT_RADIUS = 90; +constexpr float ORBIT_SQUASH = 0.84f; +constexpr float FISTULOID_ORBIT_SPEED = 0.035f; +constexpr float ORBIT_CATCHUP = 10; + +// A decaying one hurts itself now and then. The Matriarch's held one dies to her red acid shots, and a Fistuloid +// gone adds to her wait. +constexpr float DECAY_SHARE = 0.4f; +constexpr int SELF_HIT_COUNTDOWN = 30; +constexpr int MATRIARCH_DELAY_PER_LOSS = 150; + +// The ejection: the worm thrown at 12 along an axis on Shoot, the Fistuloid gone after. +constexpr float EJECT_FRICTION = 0.5f; +constexpr float EJECT_SPEED = 12; +constexpr float EJECTING_HEALTH = 0.1f; + +// npc_distribute_orbit_angles 00547040: the Matriarch's other circling Fistuloids spread evenly round her from the +// smallest of their angles. +static void fistuloid_orbit_spread(Entity_NPC& npc) +{ + Entity* matriarch = npc.parent.get(); + if (!matriarch) return; + + std::vector orbiters; + float first = FULL_TURN_DEGREES; + for (Entity* entity : entity_query(ENTITY_FISTULOID, -1)) + { + auto* other = static_cast(entity); + if (other->parent.get() != matriarch || other == matriarch->child.get() || other->isDead) continue; + if (other->state == NPC_STATE_SUICIDE) continue; + + orbiters.push_back(other); + first = std::min(first, other->v1.x); + } + if (orbiters.size() < 2) return; + + float step = TAU / (float)orbiters.size(); + for (size_t i = 0; i < orbiters.size(); i++) orbiters[i]->v1.x = (float)i * step + first; +} + +// Walking: weaving (unless circling), and off cooldown and calm, spitting at a near target one time in five. +static void fistuloid_walk(Entity_NPC& npc, Entity& target, bool isOrbiting) +{ + npc.sprite.Play("Idle"); + if (!isOrbiting) + { + Vector direction = npc_weave_direction_get(npc); + npc.velocity.x += direction.x * FISTULOID_SPEED * npc.speedMultiplier; + npc.velocity.y += direction.y * FISTULOID_SPEED * npc.speedMultiplier; + } + npc.sprite.isFlipX = npc.velocity.x > 0; + if (npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return; + if (npc.i1 >= 1) + { + npc.i1 -= npc_ticks_get(npc); + return; + } + + if (npc.controllerID == -1) + { + auto* spawner = static_cast(npc.spawnerEntity.get()); + bool isMatriarchSpitting = spawner && spawner->type == ENTITY_MATRIARCH && spawner->state == MATRIARCH_SPITTING; + if (isMatriarchSpitting || vector_length_squared(vector_sub(npc.pos, target.pos)) >= SPIT_RANGE_SQUARED) return; + if (Random() % FISTULOID_SPIT_ODDS != 0) return; + } + else if (!npc.IsTargetInAttackRange(FISTULOID_SPIT_CONTROL_RANGE, 0, true)) return; + + npc.controllerMovement = npc.controllerID == -1 ? Vector{} : npc.GetControllerMovementInput(CONTROLLER_DEADZONE); + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Attack"); + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) npc.sprite.isFlipX = npc.pos.x < target.pos.x; + else npc.sprite.isFlipX = npc.controllerMovement.x > 0; +} + +// The spit: on Shoot a shot at its target (or its controller's aim), recoiling while it plays unless circling. +static void fistuloid_spit(Entity_NPC& npc, Entity& target, bool isOrbiting) +{ + npc.UpdateControllerMovement(false); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_WORM_SPIT, 1, 2, false, 1); + Vector aim = vector_normalized(vector_sub(target.pos, npc.pos)); + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) aim = npc.controllerMovement; + npc.v2 = aim; + npc.FireProjectiles(npc.pos, vector_scale(aim, FISTULOID_SPIT_SPEED), PROJECTILES_SINGLE, ProjectileParams()); + npc.sprite.isFlipX = aim.x > 0; + } + if (!isOrbiting && npc.sprite.WasEventTriggered("Shoot")) + { + npc.velocity.x += -npc.v2.x * SPIT_RECOIL * npc.speedMultiplier; + npc.velocity.y += -npc.v2.y * SPIT_RECOIL * npc.speedMultiplier; + } + if (npc.sprite.IsPlaying()) return; + + npc.state = NPC_STATE_MOVE; + npc.i1 = FISTULOID_SPIT_COOLDOWN; +} + +// Ejecting: held still, on Shoot it throws out its Chubber worm (unless shrunk) and dies. +static void fistuloid_eject(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_NONE; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + npc.friction *= EJECT_FRICTION; + if (!npc.sprite.IsEventTriggered("Shoot")) return; + + if (!npc.HasEntityFlags(FLAG_SHRINK)) + { + uint32_t seed = Random(); + auto* worm = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = vector_scale(npc.v1, EJECT_SPEED), + .spawner = &npc, + .subType = 1, + .type = ENTITY_VIS, + .variant = CHUBBER_WORM, + .seed = seed})); + worm->state = NPC_STATE_INIT; + worm->Update(); + } + npc.Kill(EntityRef()); +} + +// Circling the Matriarch: toward its spot on her ellipse, keeping up with her. +static void fistuloid_orbit(Entity_NPC& npc) +{ + Entity& matriarch = *npc.parent; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + int parity = g_manager->framecount % 2; + float angle = npc.v1.x - ((float)parity * HALF + (float)g_game->frameCount) * HALF * PI_F * FISTULOID_ORBIT_SPEED; + Vector spot = vector_make(std::cos(angle) * FISTULOID_ORBIT_RADIUS + matriarch.pos.x, + std::sin(angle) * FISTULOID_ORBIT_RADIUS * ORBIT_SQUASH + matriarch.pos.y); + Vector gap = vector_scale(vector_sub(spot, vector_add(matriarch.velocity, npc.pos)), HALF); + float distance = vector_length(gap); + if (distance > ORBIT_CATCHUP && distance > 0) gap = vector_scale(gap, ORBIT_CATCHUP / distance); + npc.velocity = vector_make((matriarch.velocity.x + gap.x) / npc.friction, (matriarch.velocity.y + gap.y) / npc.friction); +} + +// The Matriarch's held one dies to her red acid shots touching it. +static void fistuloid_matriarch_acid_check(Entity_NPC& npc) +{ + Entity* matriarch = npc.parent.get(); + if (npc.isDead || !matriarch || matriarch->type != ENTITY_MATRIARCH || matriarch->child.get() != &npc) return; + + for (Entity* entity : entity_query_radius(npc.pos, npc.size, QUERY_PROJECTILES)) + { + if (entity->spawnerType != ENTITY_MATRIARCH) continue; + if (!(static_cast(entity)->projectileFlags & PROJECTILE_ACID_RED)) continue; + + npc.TakeDamage(npc.maxHitPoints, 0, EntityRef(entity), SELF_HIT_COUNTDOWN); + break; + } +} + +// Killed, it holds on to eject its worm along the axis its target (or its controller's aim) lies on. Circling, it +// lets the others spread out, and the Matriarch waits longer. +static void fistuloid_death(Entity_NPC& npc, bool isOrbiting) +{ + if (isOrbiting) fistuloid_orbit_spread(npc); + if (auto* matriarch = static_cast(npc.parent.get()); matriarch && matriarch->type == ENTITY_MATRIARCH) + matriarch->i1 += MATRIARCH_DELAY_PER_LOSS; + if (npc.state == NPC_STATE_SUICIDE || npc.state == NPC_STATE_DEATH) return; + + Vector aim = vector_sub(npc.CalcTargetPosition(0), npc.pos); + if (npc.controllerID != -1 && !vector_is_zero(npc.GetControllerInput(0))) aim = npc.GetControllerInput(0); + if (std::abs(aim.x) <= std::abs(aim.y)) npc.v1 = vector_make(0, aim.y <= 0 ? -1.0f : 1.0f); + else npc.v1 = vector_make(aim.x <= 0 ? -1.0f : 1.0f, 0); + npc.targetPosition = npc.pos; + npc.sprite.Play("Eject"); + npc.state = NPC_STATE_SUICIDE; + npc.RemoveStatusEffects(); + npc.isInvincible = true; + npc.isDead = false; + npc.health = EJECTING_HEALTH; + npc.stateFrame = -1; +} + +// 00545f70 The Fistuloid's AI: it weaves after its target (or circles the Matriarch) and spits shots, and killed it +// ejects a Chubber worm. +void npc_fistuloid_update(Entity_NPC& npc) +{ + bool isOrbiting = npc.parent && npc.parent->child.get() != &npc && npc.controllerID == -1; + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.i1 = 0; + return; + } + + Entity& target = *npc.GetPlayerTarget(); + if (npc.state == NPC_STATE_MOVE) fistuloid_walk(npc, target, isOrbiting); + else if (npc.state == NPC_STATE_ATTACK) fistuloid_spit(npc, target, isOrbiting); + else if (npc.state == NPC_STATE_SUICIDE) fistuloid_eject(npc); + + if (isOrbiting) fistuloid_orbit(npc); + else + { + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.friction = FISTULOID_FRICTION; + } + if (npc.isKillOnTouch && npc.IsFrame(4, 0) && (Random() & 1) == 0) + npc.TakeDamage(npc.maxHitPoints * DECAY_SHARE, 0, EntityRef(), SELF_HIT_COUNTDOWN); + fistuloid_matriarch_acid_check(npc); + if (npc.controllerID != -1 && input_is_action_pressed(ACTION_ITEM, npc.controllerID, &npc) && + npc.state != NPC_STATE_SUICIDE) + npc.Kill(EntityRef()); + if (npc.isDead) fistuloid_death(npc, isOrbiting); +} diff --git a/src/npc_gaper.cpp b/src/npc_gaper.cpp index 90e36bf..f366603 100644 --- a/src/npc_gaper.cpp +++ b/src/npc_gaper.cpp @@ -6,6 +6,7 @@ #include "entity_tear.h" #include "game.h" #include "manager.h" +#include "npc_alt.h" #include "room.h" #include "room_grid.h" #include "sfx_manager.h" @@ -44,12 +45,10 @@ constexpr float STONEY_SPEED_CROSS = 0.48000002f; constexpr float NULLS_SPEED = 0.90000004f; // The walk: the gap path marker each leaves (the Stoney's lower), the walk animation's threshold, and fleeing. -constexpr int PATH_MARKER = 900; constexpr int PATH_MARKER_STONEY = 100; constexpr float WALK_THRESHOLD = 0.1f; constexpr float FLEE_FRICTION = 0.8f; constexpr float ATTACK_FRICTION = 0.4f; -constexpr float CONTROLLER_DEADZONE = 0.1f; // A dying gaper that was not torn apart gets up one time in two, a Gusher pacing one time in three. constexpr float GAPER_OVERKILL = -25; @@ -630,7 +629,7 @@ static void stoney_update(Entity_NPC& npc) // fatties wind up and attack, Cyclopia shoots and trails creep, the Stoney pants and crumbles with the room. void npc_gaper_update(Entity_NPC& npc) { - if (npc.type == ENTITY_GAPER && npc.variant == GAPER_ROTTEN) return NpcAI::ENTITY_ROTTEN_GAPER(&npc); + if (npc.type == ENTITY_GAPER && npc.variant == GAPER_ROTTEN) return npc_rotten_gaper_update(npc); if (npc.pendingDamage > 0) for (DamageEvent& event : npc.damageEvents) @@ -647,7 +646,7 @@ void npc_gaper_update(Entity_NPC& npc) npc.aiFloat = gaper_speed_get(npc); if (!npc.HasEntityFlags(FLAG_SHRINK | FLAG_FEAR)) { - int marker = npc.type == ENTITY_STONEY ? PATH_MARKER_STONEY : PATH_MARKER; + int marker = npc.type == ENTITY_STONEY ? PATH_MARKER_STONEY : GRID_PATH_FREED; npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), npc.aiFloat, marker, DIRECT_PATH_FAR); } else diff --git a/src/npc_gaper_l2.cpp b/src/npc_gaper_l2.cpp new file mode 100644 index 0000000..4192835 --- /dev/null +++ b/src/npc_gaper_l2.cpp @@ -0,0 +1,231 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_effect.h" + +// The level 2 Gaper (variant 0) loses its head (variant 1, the level 2 Horf) on dying and runs on headless (variant +// 2, the level 2 Gusher). +constexpr int GAPER_L2_HEAD = 1; +constexpr int GAPER_L2_HEADLESS = 2; +constexpr int GAPER_L2_UNMARKED = 2; + +// The Gaper walks its grid path at 0.6, groaning now and then in plain sight. +constexpr float GAPER_L2_SPEED = 0.6f; +constexpr int GAPER_PATH_MARKER = 900; +constexpr float GAPER_FLEE_FRICTION = 0.8f; +constexpr float GAPER_WALK_THRESHOLD = 0.1f; +constexpr uint32_t GAPER_GROAN_ODDS = 3; +constexpr int GAPER_GROAN_DELAY = 40; +constexpr float GAPER_GROAN_PITCH = 0.9f; +constexpr float HEAD_DROP = -10; +constexpr int GAPER_L2_HEAD_LAYER = 1; + +// The head drifts toward its target and spits a charged maggot 15 to 44 frames in (45 after each). +constexpr float GAPER_L2_HEAD_FRICTION = 0.93f; +constexpr float HEAD_DRIFT = 0.13f; +constexpr int HEAD_FIRST_SPIT_RANGE = 30; +constexpr int HEAD_FIRST_SPIT_MIN = 15; +constexpr int HEAD_SPIT_REST = 45; +constexpr float HEAD_SPIT_PITCH = 0.9f; +constexpr float HEAD_SPIT_SPEED = 10; +constexpr float HEAD_SPIT_REACH = 0.3f; +constexpr float HEAD_SPIT_HEIGHT = -24; +constexpr float HEAD_SPIT_RISE = -8; +constexpr float HEAD_SPIT_DEPTH = 1; +constexpr int HEAD_SPIT_BLOOD = 5; + +// Headless, it staggers about turning at random, and every 15 frames one time in four throws out a maggot (while 15 +// or fewer are out). +constexpr float HEADLESS_FRICTION = 0.8f; +constexpr float HEADLESS_SPEED = 1.2f; +constexpr float HEADLESS_TURN = 0.1f; +constexpr int HEADLESS_THROW_FRAMES = 15; +constexpr uint32_t HEADLESS_THROW_ODDS = 4; +constexpr size_t MAGGOT_LIMIT = 15; +constexpr float MAGGOT_THROW_MIN = 2; +constexpr float MAGGOT_THROW_HEIGHT = -16; +constexpr float MAGGOT_THROW_RISE = -8; +constexpr uint32_t GAPER_L2_WORM_ODDS = 20; +constexpr float WORM_INTERVAL = 4; + +// They all drip white one frame in ten. +constexpr uint32_t GAPER_L2_DRIP_ODDS = 10; +constexpr float GAPER_L2_DRIP_SIZE = 0.5f; +constexpr float GAPER_L2_DRIP_MIN = 0.4f; + +// The head drifts toward its target (or where its controller points) and spits once its wait is up. +static void head_update(Entity_NPC& npc) +{ + npc.friction *= GAPER_L2_HEAD_FRICTION; + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.splatColor = BLOATED_SPLAT_COLOR; + npc.projectileCooldown = (int)(Random() % HEAD_FIRST_SPIT_RANGE) + HEAD_FIRST_SPIT_MIN; + return; + } + if (npc.state == NPC_STATE_MOVE) + { + npc.sprite.Play("Idle"); + npc.projectileCooldown -= npc_ticks_get(npc); + if (npc.projectileCooldown < 1) + { + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Shoot"); + } + Vector toward = vector_sub(npc.CalcTargetPosition(0), npc.pos); + if (npc.controllerID != -1) toward = npc.GetControllerInput(0); + float length = vector_length(toward); + if (length > 0 && npc.friction != 0) + { + npc.velocity.x += toward.x * (HEAD_DRIFT / length) * npc.speedMultiplier / npc.friction; + npc.velocity.y += toward.y * (HEAD_DRIFT / length) * npc.speedMultiplier / npc.friction; + } + return; + } + if (npc.state != NPC_STATE_ATTACK) return; + + npc.UpdateControllerMovement(false); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_SHAKEY_KID_ROAR, 1, 2, false, HEAD_SPIT_PITCH); + Vector aim = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) aim = npc.controllerMovement; + float length = vector_length(aim); + if (length > 0) aim = vector_scale(aim, HEAD_SPIT_SPEED / length); + + auto* blood = static_cast( + blood_explosion_spawn(HEAD_SPIT_BLOOD, npc.pos, vector_make(0, HEAD_SPIT_HEIGHT), npc.splatColor, {})); + blood->renderDepthOffset = HEAD_SPIT_DEPTH; + blood->FollowParent(&npc); + blood->sprite.isFlipX = true; + small_maggot_fling(vector_add(vector_scale(aim, HEAD_SPIT_REACH), npc.pos), HEAD_SPIT_HEIGHT, aim, HEAD_SPIT_RISE); + } + if (npc.sprite.IsPlaying()) return; + + npc.state = NPC_STATE_MOVE; + npc.sprite.Play("Idle"); + npc.projectileCooldown = HEAD_SPIT_REST; +} + +// The Gaper walks its grid path (fleeing when afraid or shrunk), its head kept on the body's frame and facing. +static void gaper_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", GAPER_WALK_THRESHOLD); + if (npc.sprite.IsPlaying() && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat((float)(int)npc.sprite.animState.animFrame); + npc.sprite.GetLayer(GAPER_L2_HEAD_LAYER)->isFlipX = npc.sprite.isFlipX; + + npc.aiFloat = GAPER_L2_SPEED; + Vector target = npc.CalcTargetPosition(0); + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + npc.pathfinder.FindGridPath(target, npc.aiFloat, npc.subtype == GAPER_L2_UNMARKED ? -1 : GAPER_PATH_MARKER, + DIRECT_PATH_FAR); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= GAPER_FLEE_FRICTION; + } + + bool isGroaning = npc.controllerID == -1 + ? npc.IsHostileTo(npc.GetPlayerTarget()) && npc.pathfinder.hasDirectPath && + Random() % GAPER_GROAN_ODDS == 0 + : npc.IsControllerActionTriggered(CONTROLLER_ACTION_GROAN); + if (isGroaning) npc.PlaySound(SOUND_ZOMBIE_WALKER_KID, 1, GAPER_GROAN_DELAY, false, GAPER_GROAN_PITCH); +} + +// Killed, the Gaper becomes the headless one, bleeding at full health, and its head pops off. Whether it did. +static bool gaper_behead(Entity_NPC& npc) +{ + if (!npc.isDead || npc.variant != 0) return false; + + npc.Morph(npc.type, GAPER_L2_HEADLESS, 0, -1); + npc.sprite.PlayOverlay("Blood"); + npc.health = npc.maxHitPoints; + npc.sprite.isOverlayRenderFirst = true; + npc.isDead = false; + npc.v1.x = vector_angle(vector_sub(npc.pos, npc.CalcTargetPosition(0))); + auto* head = static_cast(g_game->Spawn({.position = vector_make(npc.pos.x + 0, npc.pos.y + HEAD_DROP), + .spawner = &npc, + .type = npc.type, + .variant = GAPER_L2_HEAD, + .seed = Random()})); + if (npc.isChampion) head->MakeChampion(npc.initSeed, npc.championColorIdx, false); + head->ClearEntityFlags(FLAG_APPEAR); + head->Update(); + return true; +} + +// Headless, it staggers along a heading (v1.x) drifting at random toward where it moves, bouncing off walls, and +// throws out maggots. +static void headless_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", 0); + npc.friction *= HEADLESS_FRICTION; + float wobble = random_unit() - HALF; + npc.v1.x = wobble + wobble + npc.v1.x; + npc.v1.x = angle_approach(npc.v1.x, vector_angle(npc.velocity), HEADLESS_TURN); + Vector heading = vector_from_angle(npc.v1.x); + npc.velocity = vector_add(vector_scale(vector_scale(heading, HEADLESS_SPEED), npc.speedMultiplier), npc.velocity); + if (npc.isCollidesWithGrid) + { + Vector normal = npc.gridCollisionNormal; + float along = vector_dot(normal, heading); + npc.v1.x = vector_angle(vector_sub(heading, vector_scale(vector_add(normal, normal), along))); + } + if (npc.projectileCooldown > 0) + { + npc.projectileCooldown -= npc_ticks_get(npc); + return; + } + + if (Random() % HEADLESS_THROW_ODDS == 0 && entity_query(ENTITY_SMALL_MAGGOT, -1).size() <= MAGGOT_LIMIT) + { + Vector direction = random_direction(); + float speed = random_unit(); + speed = speed + speed + MAGGOT_THROW_MIN; + small_maggot_spawn(npc.pos, MAGGOT_THROW_HEIGHT, vector_scale(direction, speed), MAGGOT_THROW_RISE); + npc_sound_play(SOUND_BLOODSHOOT, 1, 2, 1); + } + npc.projectileCooldown = HEADLESS_THROW_FRAMES; +} + +// The headless one also drips worms now and then. +static void headless_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.sprite.Play("WalkVert"); + npc.sprite.PlayOverlay("Blood"); + npc.sprite.isOverlayRenderFirst = true; + npc.state = NPC_STATE_MOVE; + npc.splatColor = BLOATED_SPLAT_COLOR; + npc.projectileCooldown = HEADLESS_THROW_FRAMES; + } + else if (npc.state == NPC_STATE_MOVE) headless_walk(npc); +} + +// 004e2b40 The level 2 Gaper's AI and its head's and headless body's: it walks after its target until killed, then +// its head floats on spitting charged maggots and its body staggers about throwing maggots. All drip white. +void npc_gaper_l2_update(Entity_NPC& npc) +{ + if (npc.variant == GAPER_L2_HEAD) head_update(npc); + else if (npc.variant == GAPER_L2_HEADLESS) headless_update(npc); + else + { + if (npc.state == NPC_STATE_INIT) + { + npc.sprite.SetOverlayFrame("Head", 0); + npc.sprite.SetFrame("WalkVert", 0); + npc.state = NPC_STATE_MOVE; + npc.splatColor = BLOATED_SPLAT_COLOR; + } + else if (npc.state == NPC_STATE_MOVE) gaper_walk(npc); + if (gaper_behead(npc)) return; + } + + if (Random() % GAPER_L2_DRIP_ODDS == 0) + npc.MakeSplat(random_unit() * GAPER_L2_DRIP_SIZE + GAPER_L2_DRIP_MIN)->SetColor(BLOATED_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (npc.variant != GAPER_L2_HEADLESS || Random() % GAPER_L2_WORM_ODDS != 0 || npc.GetIntervalTicks(WORM_INTERVAL, 0) == 0) return; + + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_WORM, .seed = Random()})->Update(); +} diff --git a/src/npc_gasbag.cpp b/src/npc_gasbag.cpp new file mode 100644 index 0000000..ccd6146 --- /dev/null +++ b/src/npc_gasbag.cpp @@ -0,0 +1,105 @@ +#include "boss_repentance.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "npc_gehenna.h" +#include "room_grid.h" + +// The Gasbag sits wrapped in eight smoke clouds and, while fewer than eight Army Flies are about, lets out a column of +// them toward its target, each following the one before. +constexpr int GASBAG_CLOUDS = 8; +constexpr float GASBAG_CLOUD_STEP = 45; +constexpr float GASBAG_CLOUD_REACH = 100; +constexpr int GASBAG_CLOUD_FRAMES = 60; +constexpr uint32_t GASBAG_WAIT_RANGE = 30; +constexpr int GASBAG_WAIT = 15; +constexpr size_t GASBAG_FLY_LIMIT = 8; +constexpr int GASBAG_FLY_EVERY = 6; +constexpr float GASBAG_FLY_REACH = 10; +constexpr float GASBAG_FLY_SPEED = 5; +constexpr int GASBAG_FLY_TURN = 30; +constexpr int GASBAG_REST = 90; + +// One fly of the column, chained behind the last one let out while that one leads none. +static void gasbag_fly_spawn(Entity_NPC& npc) +{ + uint32_t seed = Random(); + Vector heading = npc.v1; + auto* fly = static_cast( + g_game->Spawn({.position = vector_add(vector_scale(heading, GASBAG_FLY_REACH), npc.pos), + .velocity = vector_scale(heading, GASBAG_FLY_SPEED), + .spawner = &npc, + .type = ENTITY_ARMYFLY, + .seed = seed})); + fly->ClearEntityFlags(FLAG_APPEAR); + Entity* last = npc.entityRef.get(); + if (last && !last->child) + { + fly->parent = last; + last->child = fly; + } + npc.entityRef = fly; + fly->Update(); + fly->i1 = axis_direction_get(heading); + fly->i2 = GASBAG_FLY_TURN; +} + +// The attack: on its Shoot event a fly every six frames along the axis toward its target, then a rest. Whether it is +// still attacking. +static bool gasbag_attack(Entity_NPC& npc, int ticks) +{ + if (npc.sprite.IsEventTriggered("Sound")) npc_sound_play(SOUND_LOW_INHALE, 1, 2, 1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_MONSTER_GRUNT_1, 1, 2, 1); + npc_sound_play(SOUND_SUMMONSOUND, 1, 2, 1); + npc.projectileCooldown = 1; + npc.v1 = vector_cardinal(vector_sub(npc.CalcTargetPosition(0), npc.pos)); + npc.entityRef = nullptr; + } + for (int tick = 0; tick < ticks && npc.projectileCooldown > 0; tick++, npc.projectileCooldown++) + if (npc.projectileCooldown % GASBAG_FLY_EVERY == 1) gasbag_fly_spawn(npc); + if (npc.sprite.IsPlaying()) return true; + npc.projectileCooldown = GASBAG_REST; + return false; +} + +// 004dd7f0 The Gasbag's AI: fixed in place in its clouds, letting out Army Fly columns, its cell kept clear of paths. +void npc_gasbag_update(Entity_NPC& npc) +{ + int ticks = npc_ticks_get(npc); + if (npc.state == NPC_STATE_INIT) + { + npc.targetPosition = npc.pos; + for (int i = 0; i < GASBAG_CLOUDS; i++) + { + Vector spot = + vector_add(vector_rotated(vector_make(GASBAG_CLOUD_REACH, 0), (float)i * GASBAG_CLOUD_STEP), npc.pos); + auto* cloud = static_cast(g_game->Spawn({.position = spot, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_SMOKE_CLOUD, + .seed = Random()})); + cloud->parent = &npc; + cloud->timeout = GASBAG_CLOUD_FRAMES; + cloud->lifespan = GASBAG_CLOUD_FRAMES; + cloud->Update(); + } + npc.projectileCooldown = (int)(Random() % GASBAG_WAIT_RANGE) + GASBAG_WAIT; + npc.state = NPC_STATE_IDLE; + } + else if (npc.state == NPC_STATE_IDLE) + { + npc.sprite.Play("Idle"); + npc.projectileCooldown -= ticks; + if (npc.projectileCooldown < 1 && entity_query(ENTITY_ARMYFLY, -1).size() < GASBAG_FLY_LIMIT) + { + npc.projectileCooldown = 0; + npc.state = NPC_STATE_ATTACK; + npc.sprite.Play("Attack"); + } + } + else if (npc.state == NPC_STATE_ATTACK && !gasbag_attack(npc, ticks)) npc.state = NPC_STATE_IDLE; + + room_path_raise_at(npc.pos, GRID_PATH_FREED); + npc.velocity = vector_sub(npc.targetPosition, npc.pos); +} diff --git a/src/npc_generic_prop.cpp b/src/npc_generic_prop.cpp new file mode 100644 index 0000000..9876182 --- /dev/null +++ b/src/npc_generic_prop.cpp @@ -0,0 +1,101 @@ +#include "boss_repentance.h" +#include "game.h" +#include "log.h" +#include "entity_player.h" +#include "grid_entity_door.h" +#include "manager.h" +#include "music_manager.h" +#include "room.h" + +// A generic prop: held where it stands playing its default animation, untouchable and untargeted, faded in the +// Death Certificate's dimension. Home's TV (variant 4, and the lamp, 3) idle on their second animation by night. +constexpr uint64_t PROP_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | FLAG_NO_DEATH_TRIGGER | + FLAG_DONT_OVERWRITE | FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK | FLAG_HIDE_HP_BAR | + FLAG_NO_PLAYER_CONTROL; +constexpr ColorMod PROP_FADED_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 0.2f}, {0, 0, 0}}; +constexpr int PROP_LAMP = 3; +constexpr int PROP_TV = 4; +constexpr int PROP_HOME_STAGE = 13; +constexpr int PROP_TV_WAIT = 4; + +// Home's TV by night calls Dogma once a player passes in front of it (crossing its line, or coming within 80 of it): +// the players freeze, the bombs go off, the doors close and the intro music fades in. +static void tv_dogma_call(Entity_NPC& npc) +{ + constexpr float TV_FRONT = 100; + constexpr float TV_FRONT_REACH = 120; + constexpr float TV_LINE_HALF = 10; + constexpr float TV_SCREEN_DROP = 60; + constexpr float TV_NEAR_SQUARED = 6400; + constexpr RNG TV_RNG_SHIFTS = {0, 1, 11, 16}; + constexpr float DOGMA_LEFT = 8; + constexpr float DOGMA_DROP = 40; + constexpr float DOGMA_INTRO_FADE = 0.04f; + + Game& game = *g_game; + float line = npc.pos.x; + float front = npc.pos.y + TV_FRONT; + for (Entity_Player* player : game.playerManager.playerList) + { + if (player->variant != 0 || player->isDead || std::abs(player->pos.y - front) > TV_FRONT_REACH) continue; + float from = player->prevPosition.x; + bool isCrossed = (from < line - TV_LINE_HALF && line - TV_LINE_HALF <= player->pos.x) || + (line + TV_LINE_HALF < from && player->pos.x <= line + TV_LINE_HALF); + Vector toScreen = vector_sub(vector_make(npc.pos.x, npc.pos.y + TV_SCREEN_DROP), player->prevPosition); + if (!isCrossed && vector_length_squared(toScreen) > TV_NEAR_SQUARED) continue; + + npc.i1 = 1; + RNG rng = TV_RNG_SHIFTS; + rng._seed = npc.initSeed; + Entity* dogma = game.Spawn({.position = vector_make(npc.pos.x - DOGMA_LEFT, npc.pos.y + DOGMA_DROP), + .spawner = &npc, + .type = ENTITY_DOGMA, + .seed = rng.Next()}); + dogma->targetPosition = npc.pos; + dogma->Update(); + for (Entity_Player* frozen : game.playerManager.playerList) frozen->isControlsEnabled = false; + for (Entity* bomb : std::vector(game.room->entityList.updateEL)) + if (bomb->type == ENTITY_BOMB) bomb->Kill(EntityRef()); + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) + { + GridEntity_Door* door = game.room->doors[slot]; + if (!door || door->state == DOOR_STATE_CLOSED) continue; + door->state = DOOR_STATE_CLOSED; + door->UpdateAnimation(); + for (int type : {door->currentRoomType, door->targetRoomType}) + if (type == ROOM_SECRET || type == ROOM_SUPERSECRET || type == ROOM_ULTRASECRET) + door->openAnimation = "Open"; + } + g_manager->musicManager.Crossfade(MUSIC_DOGMA_INTRO, DOGMA_INTRO_FADE); + return; + } +} + +// 00551d30 The generic prop's AI: still, untouchable props, and Home's TV calling Dogma by night. +void npc_generic_prop_update(Entity_NPC& npc) +{ + Game& game = *g_game; + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.targetPosition = npc.pos; + npc.sprite.Play(npc.sprite.GetDefaultAnimationName()); + npc.ClearEntityFlags(FLAG_APPEAR); + npc.AddEntityFlags(PROP_FLAGS); + npc.isInvincible = true; + if (game.currentDimensionIdx == DIMENSION_DEATH_CERTIFICATE) + npc.SetColor(PROP_FADED_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + return; + } + if (npc.state != NPC_STATE_IDLE) return; + + bool isHomeNight = (npc.variant == PROP_TV || npc.variant == PROP_LAMP) && game.stage == PROP_HOME_STAGE && + game.stageType == STAGETYPE_WOTL; + if (isHomeNight) + { + npc.sprite.Play("Idle2"); + if (npc.variant == PROP_TV && npc.i1 == 0 && game.frameCount - npc.spawnFrame > PROP_TV_WAIT) + tv_dogma_call(npc); + } + npc.velocity = vector_sub(npc.targetPosition, npc.pos); +} diff --git a/src/npc_gutted_fatty.cpp b/src/npc_gutted_fatty.cpp new file mode 100644 index 0000000..bd07557 --- /dev/null +++ b/src/npc_gutted_fatty.cpp @@ -0,0 +1,564 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "entity_projectile.h" +#include + +// The Gutted Fatty (variant 0) drops an eye (variant 10) at each third of its health lost and spits out Festering +// Guts (variant 20), which bounce off and lay Chargers. +constexpr int GUTTED_EYE = 10; + +// It wanders along a heading (v1.y) turning 10 degrees a frame toward a goal heading (v1.x), picked anew every 45 to +// 164 frames, on bumping a wall one time in four, at random when confused, away when afraid, and along the grid path +// to its target when charmed. +constexpr float GUTTED_SPEED = 1.2f; +constexpr float GUTTED_CONTROL_SCALE = 1.25f; +constexpr float GUTTED_FRICTION = 0.6f; +constexpr float GUTTED_TURN = 10; +constexpr int GUTTED_HEADING_FRAMES = 120; +constexpr int GUTTED_HEADING_MIN = 45; +constexpr int GUTTED_STATUS_HEADING = 10; +constexpr uint32_t GUTTED_CONFUSED_ODDS = 5; +constexpr float GUTTED_PATH_SPEED = 1; +constexpr int GUTTED_PATH_MARKER = 900; +constexpr uint32_t GUTTED_GROAN_ODDS = 80; +constexpr int GUTTED_GROAN_DELAY = 60; +constexpr float GUTTED_GROAN_PITCH = 0.6f; +constexpr float GUTTED_WALK_THRESHOLD = 0.1f; + +// It spits guts 60 to 209 frames apart (90 to 269 after a spit, 60 under control), at 45 to 134 degrees down, held +// back while three of its friendliness are out. Damage shortens the wait 12 frames a point. +constexpr int SPIT_COOLDOWN_RANGE = 150; +constexpr int SPIT_COOLDOWN_MIN = 60; +constexpr int SPIT_REST_RANGE = 180; +constexpr int SPIT_REST_MIN = 90; +constexpr uint32_t GUTS_LIMIT = 2; +constexpr int SPIT_ANGLE_RANGE = 90; +constexpr int SPIT_ANGLE_MIN = 45; +constexpr float SPIT_CONTROL_MIN = 45; +constexpr float SPIT_CONTROL_MAX = 135; +constexpr int SPIT_CONTROL_ANGLE = 90; +constexpr float GUTTED_SPIT_CONTROL_RANGE = 1000; +constexpr float GUTTED_SPIT_SPEED = 10; +constexpr float SPIT_VOLUME = 0.6f; +constexpr int GUTTED_SPIT_SOUND_DELAY = 10; +constexpr float GUTTED_SPIT_BLOOD_LIFT = -20; +constexpr float SPIT_FRICTION = 0.4f; +constexpr float SPIT_DAMAGE_SCALE = 12; +constexpr float GUTS_LAUNCH_SPEED = -8; +constexpr float GUTS_LAUNCH_HEIGHT = -15; +constexpr uint32_t GUTTED_SPLAT_ODDS = 6; +constexpr float GUTTED_SPLAT_SIZE = 1.4f; +constexpr float GUTTED_SPLAT_MIN = 0.5f; + +// Its eyes hide behind crop rows of 48 per eye left, and pop out with a squish, thrown 3 aside and 5 down. +constexpr int GUTTED_EYES = 2; +constexpr float EYE_CROP_ROW = 48; +constexpr float EYE_HEALTH_SHARE = 3; +constexpr float EYE_THROW_SIDE = 3; +constexpr float EYE_THROW_DOWN = 5; +constexpr float EYE_BLOOD_DEPTH = 10; + +// Its death: a dark red splash, four blood bursts thrown 40 out at 7 between -45 and -135 degrees, and 15 ticks of +// four lobbed shots. +constexpr ColorMod GUTTED_SPLASH_COLOR = {{0.5f, 0.1f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int DEATH_BURSTS = 4; +constexpr float DEATH_BURST_ANGLE = -45; +constexpr float DEATH_BURST_SPREAD = 90; +constexpr float DEATH_BURST_SPEED = 7; +constexpr float GUTTED_DEATH_BURST_REACH = 40; +constexpr float DEATH_BURST_LIFT = -28; +constexpr int DEATH_BURST_Z = 500; +constexpr int DEATH_SHOT_TICKS = 15; +constexpr uint64_t DEATH_SHOT_FLAGS = FLAG_CHARM | FLAG_FRIENDLY | FLAG_WEAKNESS; +constexpr int DEATH_SHOTS = 2; +constexpr float GUTTED_DEATH_SHOT_SPEED = 2.8f; +constexpr float DEATH_SHOT_SPREAD = 5; +constexpr float DEATH_SHOT_FALL_ACCEL = 2; +constexpr float DEATH_SHOT_SCALE = 1.4f; +constexpr float DEATH_SHOT_RISE = -15; +constexpr float DEATH_SHOT_RISE_RANGE = 60; +constexpr float DEATH_SHOT_HEIGHT = -23; +constexpr float DEATH_SHOT_LOW_RANGE = 15; +constexpr float DEATH_SHOT_HIGH_RANGE = 1000; + +// The eye crawls after its target (or back to the Gutted Fatty when the target is over 240 from it), weaving up to +// 40 degrees once 1000 off, kept apart from the other eyes. +constexpr float EYE_SPEED = 0.6f; +constexpr float GUTTED_EYE_FRICTION = 0.85f; +constexpr float GUTTED_EYE_LEASH = 240; +constexpr float EYE_WEAVE = 40; +constexpr float EYE_WEAVE_NEAR = 200; +constexpr float EYE_WEAVE_SPAN = 800; +constexpr float EYE_WEAVE_PERIOD = 60; +constexpr float EYE_APART_SCALE = 0.1f; +constexpr float EYE_APART_MIN = 10; +constexpr float EYE_APART_PULL = 10; +constexpr RNG EYE_RNG_SHIFTS = {0, 5, 9, 7}; +constexpr uint32_t EYE_SPLAT_ODDS = 4; +constexpr float EYE_SPLAT_SIZE = 0.3f; +constexpr float EYE_SPLAT_MIN = 0.3f; + +// The guts wander the grid's axes and lay a Charger now and then. Thrown, they fall back with creep and land. +constexpr float GUTS_WALK_SPEED = 0.75f; +constexpr float GUTS_DRAG_X = 0.85f; +constexpr float GUTS_DRAG_Y = 0.8f; +constexpr float GUTTED_GUTS_FRICTION = 0.7f; +constexpr float GUTS_LAY_FRICTION = 0.6f; +constexpr uint32_t GUTS_LAY_ODDS = 15; +constexpr float GUTS_LAY_LIFT = -6; +constexpr float GUTS_CHARGER_DROP = 10; +constexpr float GUTS_GRAVITY = 0.7f; +constexpr float GUTS_CREEP_SIZE = 0.3f; +constexpr float GUTS_CREEP_MIN = 0.4f; +constexpr int GUTS_CREEP_FRAMES = 30; +constexpr float GUTTED_GUTS_SPLAT_SIZE = 0.5f; +constexpr float GUTS_SPLAT_MIN = 0.5f; +constexpr float GUTS_LAND_CREEP = 1.4f; + +// 006c1870 Entity_NPC::anim_walk_frame_4dir: a walk by the way it moves (left, right, up or down), or the down walk's +// first frame when it is slower than the threshold (half for a slowed champion). Its forward vector follows. +void npc_walk_animate_4dir(Entity_NPC& npc, const WalkAnims& anims) +{ + float threshold = anims.threshold; + if (npc.isChampion && npc.championSpeed < 1) threshold *= HALF; + if (vector_length_squared(npc.velocity) < threshold * threshold) + { + npc.sprite.SetFrame(anims.down, 0); + npc.forwardVector = vector_make(0, 1); + return; + } + + Vector v = npc.velocity; + if (std::abs(v.x) <= std::abs(v.y)) npc_anim_loop(npc.sprite, v.y < 0 ? anims.up : anims.down); + else npc_anim_loop(npc.sprite, v.x < 0 ? anims.left : anims.right); + npc.forwardVector = vector_cardinal(v); +} + +// Its creep: a red puddle a size across, lasting 30 frames. +static Entity* guts_creep_spawn(Entity_NPC& npc, float size) +{ + auto* creep = static_cast(g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_CREEP_RED, .seed = Random()})); + creep->timeout = GUTS_CREEP_FRAMES; + creep->lifespan = GUTS_CREEP_FRAMES; + creep->sprite.scale = vector_make(size, size); + return creep; +} + +// 004e0930 NpcHelper::gutted_fatty_burst_projectiles: a tick of the death burst, two low lobs and two high ones from +// the timer, with the Gutted Fatty's champion color, scale and flags. +static void gutted_fatty_burst_tick(Entity_Effect* timer) +{ + for (float heightRange : {DEATH_SHOT_LOW_RANGE, DEATH_SHOT_HIGH_RANGE}) + for (int shot = 0; shot < DEATH_SHOTS; shot++) + { + Vector direction = random_direction(); + uint32_t seed = Random(); + Vector velocity = vector_scale(direction, random_unit() * GUTTED_DEATH_SHOT_SPEED); + Vector position = vector_add(timer->pos, vector_scale(direction, DEATH_SHOT_SPREAD * random_unit())); + auto* projectile = static_cast( + g_game->Spawn({.position = position, .velocity = velocity, .type = ENTITY_PROJECTILE, .seed = seed})); + projectile->spawnerType = ENTITY_GUTTED_FATTY; + projectile->fallingAccel = DEATH_SHOT_FALL_ACCEL; + projectile->scale = random_unit() * DEATH_SHOT_SCALE; + projectile->fallingSpeed = DEATH_SHOT_RISE - random_unit() * DEATH_SHOT_RISE_RANGE; + projectile->height = DEATH_SHOT_HEIGHT - random_unit() * heightRange; + projectile->apply_spawn_flags({.flags = timer->flags, .scale = timer->scale, .championColor = timer->state}); + projectile->Update(); + } +} + +// Its death: a splash, the four blood bursts (unless shrunk or killswitched) and the timer of lobbed shots. +static void gutted_fatty_death(Entity_NPC& npc) +{ + npc.MakeBloodPoof(npc.pos, npc.splatColor, 1); + Entity* splash = spawn_at(ENTITY_EFFECT, EFFECT_BIG_SPLASH, 0, npc.pos, nullptr); + splash->SetColor(GUTTED_SPLASH_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + splash->Update(); + if (npc.HasEntityFlags(FLAG_SHRINK | FLAG_KILLSWITCH)) return; + + for (int burst = 0; burst < DEATH_BURSTS; burst++) + { + float angle = (DEATH_BURST_ANGLE - random_unit() * DEATH_BURST_SPREAD) * DEGREES_TO_RADIANS; + Vector direction = vector_make(std::cos(angle), std::sin(angle)); + Entity* blood = blood_explosion_spawn(2, vector_add(npc.pos, vector_scale(direction, GUTTED_DEATH_BURST_REACH)), + vector_make(0, DEATH_BURST_LIFT), COLOR_DEFAULT, + vector_scale(direction, DEATH_BURST_SPEED)); + blood->renderZOffset = DEATH_BURST_Z; + blood->sprite.rotation = random_unit() * FULL_TURN_DEGREES; + blood->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + + Entity_Effect* timer = + Entity_Effect::CreateTimer(reinterpret_cast(&gutted_fatty_burst_tick), 1, DEATH_SHOT_TICKS, false); + timer->pos = npc.pos; + timer->state = npc.isChampion ? npc.championColorIdx : -1; + timer->flags |= npc.flags & DEATH_SHOT_FLAGS; + timer->scale = npc.scale; + timer->Update(); +} + +// Before its update: each third of its health lost pops out an eye (the left, then the right) with a squish. +static void gutted_fatty_eyes_update(Entity_NPC& npc) +{ + while (npc.projectileDelay > 0 && npc.health < npc.projectileDelay * npc.maxHitPoints / EYE_HEALTH_SHARE) + { + npc.projectileDelay--; + npc_sound_play(SOUND_PLOP, 1, 2, 1); + bool isRight = npc.projectileDelay == 1; + Vector eye = npc.GetNullOffset(isRight ? "RightEye" : "LeftEye"); + Vector position = vector_make(eye.x + npc.pos.x, npc.pos.y + 0); + Entity* blood = g_game->Spawn( + {.position = position, .subType = 2, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + blood->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + blood->sprite.offset = vector_make(0, eye.y); + blood->renderDepthOffset = EYE_BLOOD_DEPTH; + + Vector throwVelocity = vector_make(isRight ? EYE_THROW_SIDE : -EYE_THROW_SIDE, EYE_THROW_DOWN); + Entity* thrown = g_game->Spawn({.position = position, + .velocity = throwVelocity, + .spawner = &npc, + .type = npc.type, + .variant = GUTTED_EYE, + .seed = Random()}); + thrown->ClearEntityFlags(FLAG_APPEAR); + thrown->parent = &npc; + thrown->Update(); + } + float crop = npc.projectileDelay * EYE_CROP_ROW; + npc.sprite.GetLayer(2)->cropOffset.y = crop; + npc.sprite.GetLayer(1)->cropOffset.y = crop; +} + +// A new goal heading of a fatty: random when confused, away when afraid, along its grid path to the target when charmed. +static void gutted_fatty_heading_pick(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_CONFUSION)) + { + if (Random() % GUTTED_CONFUSED_ODDS == 0) npc.v1.x = normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES); + return; + } + if (npc.HasEntityFlags(FLAG_CHARM) || npc.forcedTarget) + { + Entity* target = npc.GetPlayerTarget(); + if (!npc.IsFrame(5, npc.index)) return; + + Vector pos = npc.pos; + Vector velocity = npc.velocity; + float friction = npc.friction; + npc.pathfinder.Reset(); + npc.pathfinder.FindGridPath(target->pos, GUTTED_PATH_SPEED, GUTTED_PATH_MARKER, DIRECT_PATH_FAR); + npc.v1.x = vector_angle(npc.velocity); + npc.pos = pos; + npc.velocity = velocity; + npc.friction = friction; + return; + } + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) npc.v1.x = vector_angle(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); +} + +// The fatties' wandering (the Gutted Fatty's, the Bloaty's): under a status it turns sooner, it heads on turning +// toward its goal, bounces off walls now and then, and picks a new goal once its time is up. A controlled one walks +// where its controller points. +void npc_fatty_wander(Entity_NPC& npc) +{ + if (npc.controllerID != -1) + { + Vector input = npc.GetControllerInput(0); + npc.velocity.x += input.x * GUTTED_SPEED * GUTTED_CONTROL_SCALE * npc.speedMultiplier; + npc.velocity.y += input.y * GUTTED_SPEED * GUTTED_CONTROL_SCALE * npc.speedMultiplier; + return; + } + if (npc.HasEntityFlags(FLAG_CHARM | FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK) || npc.forcedTarget) + npc.i1 = GUTTED_STATUS_HEADING; + gutted_fatty_heading_pick(npc); + npc.i1 -= npc_ticks_get(npc); + + Vector heading = vector_from_angle(npc.v1.y); + npc.velocity.x += heading.x * GUTTED_SPEED * npc.speedMultiplier; + npc.velocity.y += heading.y * GUTTED_SPEED * npc.speedMultiplier; + npc.v1.y = angle_approach(npc.v1.y, npc.v1.x, GUTTED_TURN); + if (npc.isCollidesWithGrid && (Random() & 3) == 0) + { + Vector normal = npc.gridCollisionNormal; + float along = vector_dot(normal, heading); + npc.v1.x = vector_angle(vector_sub(heading, vector_scale(vector_add(normal, normal), along))); + } + if (npc.i1 >= 1) return; + + npc.v1.x = normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES); + npc.i1 = (int)(Random() % GUTTED_HEADING_FRAMES) + GUTTED_HEADING_MIN; +} + +// Whether three or more guts of its friendliness are out, which holds its spit back. +static bool gutted_fatty_is_guts_full(Entity_NPC& npc) +{ + uint32_t count = 0; + for (Entity* guts : entity_query(ENTITY_GUTTED_FATTY, FESTERING_GUTS)) + if (guts->HasEntityFlags(FLAG_FRIENDLY) == npc.HasEntityFlags(FLAG_FRIENDLY)) count++; + return count > GUTS_LIMIT; +} + +// Walking: it wanders (or follows its controller), groans, and spits once its wait is up. +static void gutted_fatty_walk(Entity_NPC& npc) +{ + npc_walk_animate_4dir(npc, {"WalkLeft", "WalkRight", "WalkVert", "WalkVert", GUTTED_WALK_THRESHOLD}); + npc.friction *= GUTTED_FRICTION; + npc_fatty_wander(npc); + if (Random() % GUTTED_GROAN_ODDS == 0) npc.PlaySound(SOUND_ANGRY_GURGLE, 1, GUTTED_GROAN_DELAY, false, GUTTED_GROAN_PITCH); + + if (npc.projectileCooldown >= 1) npc.projectileCooldown -= npc_ticks_get(npc); + if (npc.projectileCooldown < 1 && gutted_fatty_is_guts_full(npc)) npc.projectileCooldown = SPIT_COOLDOWN_MIN; + if (npc.projectileCooldown >= 1) return; + if (npc.controllerID != -1 && !npc.IsTargetInAttackRange(GUTTED_SPIT_CONTROL_RANGE, 0, true)) return; + + npc.state = NPC_STATE_ATTACK; + if (npc.controllerID == -1) npc.i2 = (int)(Random() % SPIT_ANGLE_RANGE) + SPIT_ANGLE_MIN; + else + { + float angle = normalize_angle_degrees(vector_angle(npc.GetControllerMovementInput(0))); + npc.i2 = angle < SPIT_CONTROL_MIN || angle > SPIT_CONTROL_MAX ? SPIT_CONTROL_ANGLE : (int)std::floor(angle); + npc.UpdateControllerMovement(true); + } + npc.sprite.Play("Attack"); + npc.stateFrame = 0; +} + +// The spit: on Shoot a gurgle, a gush of blood and the guts thrown at its angle (i2), up in a spin. +static void gutted_fatty_spit(Entity_NPC& npc) +{ + npc.UpdateControllerMovement(false); + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.PlaySound(SOUND_HEARTOUT, SPIT_VOLUME, GUTTED_SPIT_SOUND_DELAY, false, 1); + blood_explosion_spawn(3, npc.pos, vector_make(0, GUTTED_SPIT_BLOOD_LIFT), npc.splatColor, {}); + Vector velocity = vector_scale(vector_from_angle((float)npc.i2), GUTTED_SPIT_SPEED); + auto* guts = static_cast(g_game->Spawn({.position = npc.pos, + .velocity = velocity, + .spawner = &npc, + .type = npc.type, + .variant = FESTERING_GUTS, + .seed = Random()})); + guts->ClearEntityFlags(FLAG_APPEAR); + guts->Update(); + guts->state = NPC_STATE_JUMP; + guts->sprite.Play("Spin", PLAY_FORCED); + guts->v1 = vector_make(GUTS_LAUNCH_SPEED, GUTS_LAUNCH_HEIGHT); + guts->posOffset.y = GUTS_LAUNCH_HEIGHT; + guts->entityCollisionClass = ENTCOLL_PLAYEROBJECTS; + } + if (npc.sprite.IsPlaying()) return; + + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.projectileCooldown = npc.controllerID == -1 ? (int)(Random() % SPIT_REST_RANGE) + SPIT_REST_MIN : SPIT_REST_MIN; +} + +// The Gutted Fatty: its first frame, its walk and spit, its wait shortened by damage, its drip and its death. +static void gutted_fatty_update(Entity_NPC& npc) +{ + npc.UpdateChargeBar(SPIT_COOLDOWN_MIN, 0, (float)npc.projectileCooldown, true); + if (npc.state == NPC_STATE_INIT) + { + npc.aiCallFlags = AI_CALL_PRE_UPDATE; + npc.state = NPC_STATE_MOVE; + npc.sprite.SetFrame("WalkVert", 0); + npc.projectileCooldown = + npc.controllerID == -1 ? (int)(Random() % SPIT_COOLDOWN_RANGE) + SPIT_COOLDOWN_MIN : SPIT_COOLDOWN_MIN; + npc.i1 = 0; + float heading = normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES); + npc.v1 = vector_make(heading, heading); + npc.projectileDelay = GUTTED_EYES; + npc.sprite.GetLayer(2)->cropOffset.y = GUTTED_EYES * EYE_CROP_ROW; + npc.sprite.GetLayer(1)->cropOffset.y = GUTTED_EYES * EYE_CROP_ROW; + npc.splatColor = BLOATED_SPLAT_COLOR; + return; + } + if (npc.state == NPC_STATE_MOVE) gutted_fatty_walk(npc); + else if (npc.state == NPC_STATE_ATTACK) + { + gutted_fatty_spit(npc); + npc.friction *= SPIT_FRICTION; + } + + if (npc.pendingDamage > 0) npc.projectileCooldown -= std::max(1, (int)(npc.pendingDamage * SPIT_DAMAGE_SCALE)); + if (Random() % GUTTED_SPLAT_ODDS == 0) npc.MakeSplat(random_unit() * GUTTED_SPLAT_SIZE + GUTTED_SPLAT_MIN); + if (npc.isDead) gutted_fatty_death(npc); +} + +// The way a weaving crawler heads (the Gutted Fatty's eye, the Fistuloid): after its target, or back to its parent +// when the target is over 240 from it, weaving up to 40 degrees once 1000 off (half under control, toward its +// controller's aim), kept apart from the others of its kind. +Vector npc_weave_direction_get(Entity_NPC& npc) +{ + RNG rng = EYE_RNG_SHIFTS; + rng._seed = npc.initSeed; + Vector goal = npc.CalcTargetPosition(0); + if (npc.parent && vector_distance(npc.pos, goal) > GUTTED_EYE_LEASH) goal = npc.parent->pos; + float phase = rng.RandomFloat(); + float far = std::clamp((vector_distance(npc.pos, goal) - EYE_WEAVE_NEAR) / EYE_WEAVE_SPAN, 0.0f, 1.0f); + float weave = EYE_WEAVE - far * EYE_WEAVE; + Vector direction = vector_normalized(vector_sub(goal, npc.pos)); + if (npc.controllerID != -1) + { + direction = npc.GetControllerInput(0); + weave *= HALF; + } + float wave = std::sin(((float)(g_game->frameCount - npc.spawnFrame) / EYE_WEAVE_PERIOD + phase) * TAU); + direction = vector_rotated(direction, wave * weave); + + if (npc.controllerID == -1) + { + int count = 0; + Vector apart{}; + 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 <= 0) continue; + + count++; + float falloff = distance * EYE_APART_SCALE + EYE_APART_MIN; + apart.x += away.x / distance / falloff * EYE_APART_PULL; + apart.y += away.y / distance / falloff * EYE_APART_PULL; + } + if (count > 0) direction = vector_normalized(vector_make(apart.x / count + direction.x, apart.y / count + direction.y)); + } + return direction; +} + +// The eye: invulnerable, it crawls after its target weaving, kept apart from the others, and dies with the Gutted +// Fatty. +static void gutted_eye_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_HIDE_HP_BAR); + npc.aiCallFlags = AI_CALL_COLLISION; + npc.state = NPC_STATE_MOVE; + npc.isInvincible = true; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.splatColor = BLOATED_SPLAT_COLOR; + return; + } + if (npc.state != NPC_STATE_MOVE) return; + + npc.sprite.Play("Walk"); + if (!npc.parent || npc.parent->isDead) npc.Kill(EntityRef()); + if (Random() % EYE_SPLAT_ODDS == 0) npc.MakeSplat(random_unit() * EYE_SPLAT_SIZE + EYE_SPLAT_MIN); + + Vector direction = npc_weave_direction_get(npc); + npc.velocity = vector_add(vector_scale(vector_scale(direction, EYE_SPEED), npc.speedMultiplier), npc.velocity); + npc.friction = GUTTED_EYE_FRICTION; +} + +// Festering Guts thrown up: they fall back, leaving creep and splats every other tick, and land with a splat. +static void guts_fall(Entity_NPC& npc) +{ + npc.sprite.Play("Spin"); + npc.v1.x += GUTS_GRAVITY; + npc.v1.y += npc.v1.x; + npc.posOffset.y = npc.v1.y; + if (npc.GetIntervalTicks(2, 0) != 0) + { + float size = random_unit() * GUTS_CREEP_SIZE + GUTS_CREEP_MIN; + guts_creep_spawn(npc, size); + Entity* splat = g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float splatSize = random_unit() * GUTTED_GUTS_SPLAT_SIZE + GUTS_SPLAT_MIN; + splat->sprite.scale = vector_make(splatSize * size, splatSize * size); + splat->Update(); + } + if (npc.v1.y <= -npc.v1.x) return; + + npc.posOffset.y = 0; + npc.v1 = {}; + npc.state = NPC_STATE_MOVE; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.entityCollisionClass = ENTCOLL_ALL; + npc.PlaySound(SOUND_SPLATTER, 1, 2, false, 1); + npc.sprite.Play("Land"); + blood_explosion_spawn(2, npc.pos, {}, npc.splatColor, {}); + guts_creep_spawn(npc, GUTS_LAND_CREEP); +} + +// The guts wander the grid's axes and, their wait up, one time in 15 start laying, resetting their kin's waits. +static void guts_walk(Entity_NPC& npc) +{ + const AnimationData* data = npc.sprite.animState.animData; + if (!data || !data->isLooping) + { + if (!data || !npc.sprite.animState.isPlaying) npc.sprite.Play("Idle"); + npc.friction *= GUTTED_GUTS_FRICTION; + return; + } + + npc.pathfinder.MoveRandomlyAxisAligned(GUTS_WALK_SPEED, STATUS_OBEYED); + npc.velocity.x *= timescale_factor(GUTS_DRAG_X, npc.speedMultiplier); + npc.velocity.y *= timescale_factor(GUTS_DRAG_Y, npc.speedMultiplier); + if (npc.projectileCooldown > 0 && (npc.projectileCooldown -= npc_ticks_get(npc)) > 0) return; + if (Random() % GUTS_LAY_ODDS != 0) return; + + npc.sprite.Play("Spawn"); + npc.state = NPC_STATE_SUMMON; + npc.projectileCooldown = (int)(Random() % SPIT_COOLDOWN_RANGE) + SPIT_COOLDOWN_MIN; + for (Entity* other : entity_query(npc.type, npc.variant)) + { + if (other == &npc || other->HasEntityFlags(FLAG_FRIENDLY) != npc.HasEntityFlags(FLAG_FRIENDLY)) continue; + + auto& kin = static_cast(*other); + kin.projectileCooldown = std::max(kin.projectileCooldown, (int)(Random() % SPIT_COOLDOWN_RANGE) + SPIT_COOLDOWN_MIN); + } +} + +// Festering Guts: they wander, lay Chargers with a gush of blood, and fall back when thrown. +static void festering_guts_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + npc.sprite.Play("Idle"); + npc.projectileCooldown = + npc.controllerID == -1 ? (int)(Random() % SPIT_COOLDOWN_RANGE) + SPIT_COOLDOWN_MIN : SPIT_COOLDOWN_MIN; + npc.splatColor = BLOATED_SPLAT_COLOR; + return; + case NPC_STATE_MOVE: + return guts_walk(npc); + case NPC_STATE_JUMP: + return guts_fall(npc); + case NPC_STATE_SUMMON: + npc.friction *= GUTS_LAY_FRICTION; + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_SUMMONSOUND, 1, 2, 1); + blood_explosion_spawn(2, npc.pos, vector_make(0, GUTS_LAY_LIFT), npc.splatColor, {}); + Vector position = vector_make(npc.pos.x + 0, npc.pos.y + GUTS_CHARGER_DROP); + g_game->Spawn({.position = position, .spawner = &npc, .type = ENTITY_CHARGER, .seed = Random()}); + } + if (npc.sprite.IsPlaying()) return; + + npc.sprite.Play("Idle"); + npc.state = NPC_STATE_MOVE; + return; + } +} + +// 004e0dd0 The Gutted Fatty's AI and its eyes' and Festering Guts': it wanders and spits guts, which lay Chargers, +// and drops its eyes as it is hurt. Its eyes ignore it in collisions. +void npc_gutted_fatty_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_COLLISION) + { + if (npc.collisionEntity == npc.spawnerEntity.get()) npc.collisionResult = 0; + return; + } + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE) + { + if (npc.variant == 0) gutted_fatty_eyes_update(npc); + return; + } + if (npc.variant == FESTERING_GUTS) return festering_guts_update(npc); + if (npc.variant == GUTTED_EYE) return gutted_eye_update(npc); + gutted_fatty_update(npc); +} diff --git a/src/npc_gyro.cpp b/src/npc_gyro.cpp new file mode 100644 index 0000000..53054ad --- /dev/null +++ b/src/npc_gyro.cpp @@ -0,0 +1,314 @@ +#include "npc_alt.h" +#include "npc_fireplace.h" +#include "room.h" +#include "entity_effect.h" +#include +#include +#include + +// The Gyro (variant 0) and Grilled Gyro (variant 1) roll along a heading (v1.x) turned toward a goal heading (v1.y), +// set every 10 to 49 frames at random or (one time in three, in a clear line) at the target. The Gyro rests 0 to 29 +// frames between goals. +constexpr int GRILLED_GYRO = 1; +constexpr float GYRO_FRICTION = 0.8f; +constexpr float GYRO_SPEED = 1.2f; +constexpr float GYRO_TURN = 10; +constexpr float GYRO_CONTROL_TURN = 20; +constexpr uint32_t GYRO_AIM_ODDS = 3; +constexpr int GYRO_GOAL_FRAMES = 40; +constexpr int GYRO_GOAL_MIN = 10; +constexpr int GYRO_REST_FRAMES = 30; +constexpr int GYRO_STATUS_FRAMES = 10; +constexpr uint32_t GYRO_CONFUSED_ODDS = 5; +constexpr float GYRO_PATH_SPEED = 1; +constexpr int GYRO_PATH_MARKER = 900; +constexpr float GYRO_WALK_SPEED = 0.1f; +constexpr float GYRO_PLAYBACK_SCALE = 0.5f; + +// Off its cooldown (i2), one time in 14 with the target ahead in a clear line, it dashes for 60 frames (80 grilled), +// homing 5 degrees a frame, and rests 30 to 59 frames after. +constexpr float DASH_AHEAD = 0.7f; +constexpr uint32_t GYRO_DASH_ODDS = 14; +constexpr int GYRO_DASH_FRAMES = 60; +constexpr int GRILLED_DASH_FRAMES = 80; +constexpr int DASH_SOUND_DELAY = 30; +constexpr float GYRO_DASH_FRICTION = 0.96f; +constexpr float DASH_SPEED = 0.9f; +constexpr float DASH_TURN = 5; +constexpr int DASH_REST = 30; +constexpr int DASH_REST_RANGE = 30; +constexpr int DASH_CHARGE_BAR = -30; + +// A dash hitting a wall head on bounces back 1.4 and ends within 10 frames (the Gyro's), a glancing one bounces 1.8 +// and turns. The Grilled Gyro drops fires as it dashes. +constexpr float WALL_HEAD_ON = 0.4f; +constexpr float GYRO_WALL_BOUNCE = 1.4f; +constexpr float WALL_GLANCE_BOUNCE = 1.8f; +constexpr int WALL_DASH_LEFT = 10; +constexpr uint32_t FIRE_ODDS = 4; +constexpr float FIRE_HEALTH = 0.2f; +constexpr float FIRE_HEALTH_MIN = 0.4f; + +// Hit, it staggers for 10 frames (5 under control), dragging for the first three. Fire turns a Gyro grilled. +constexpr int STAGGER_FRAMES = 10; +constexpr int STAGGER_CONTROL_FRAMES = 5; +constexpr int STAGGER_DRAG_FRAMES = 7; +constexpr float STAGGER_FRICTION = 0.6f; + +// It drips one frame in six, one in three dashing. +constexpr uint32_t GYRO_DRIP_ODDS = 6; +constexpr uint32_t DASH_DRIP_ODDS = 3; +constexpr float GYRO_DRIP_SIZE = 0.5f; +constexpr float GYRO_DRIP_MIN = 0.2f; + +// Its eight facings by heading, from the right turning down. The side ones mirror. +constexpr std::array GYRO_FACINGS = {"Left", "LeftDown", "Down", "LeftDown", + "Left", "LeftUp", "Up", "LeftUp"}; + +// A drip of the Gyro's, burnt black for the grilled one. +static void gyro_splat(Entity_NPC& npc) +{ + Entity_Effect* splat = npc.MakeSplat(random_unit() * GYRO_DRIP_SIZE + GYRO_DRIP_MIN); + if (npc.variant == GRILLED_GYRO) splat->SetColor(GRILLED_SPLAT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// A new goal heading while under a status or a controller, as the Gutted Fatty picks it. The speed it rolls at. +static float gyro_steer(Entity_NPC& npc) +{ + if (npc.controllerID != -1) + { + if (!vector_is_zero(npc.GetControllerInput(CONTROLLER_DEADZONE))) npc.v1.y = vector_angle(npc.GetControllerInput(0)); + return vector_length(npc.GetControllerInput(0)); + } + if (npc.HasEntityFlags(FLAG_CONFUSION)) + { + if (Random() % GYRO_CONFUSED_ODDS == 0) npc.v1.y = normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES); + } + else if (npc.HasEntityFlags(FLAG_CHARM) || npc.forcedTarget) + { + Entity* target = npc.GetPlayerTarget(); + if (npc.IsFrame(5, npc.index)) + { + Vector pos = npc.pos; + Vector velocity = npc.velocity; + float friction = npc.friction; + npc.pathfinder.Reset(); + npc.pathfinder.FindGridPath(target->pos, GYRO_PATH_SPEED, GYRO_PATH_MARKER, DIRECT_PATH_FAR); + npc.v1.y = vector_angle(npc.velocity); + npc.pos = pos; + npc.velocity = velocity; + npc.friction = friction; + } + } + else if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + npc.v1.y = vector_angle(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); + return 1; +} + +// Rolling on its heading, turning toward its goal, bouncing off walls now and then. +static void gyro_roll(Entity_NPC& npc) +{ + float speed = gyro_steer(npc); + npc.stateFrame -= npc_ticks_get(npc); + Vector heading = vector_from_angle(npc.v1.x); + npc.velocity.x += heading.x * GYRO_SPEED * speed * npc.speedMultiplier; + npc.velocity.y += heading.y * GYRO_SPEED * speed * npc.speedMultiplier; + npc.v1.x = angle_approach(npc.v1.x, npc.v1.y, npc.controllerID == -1 ? GYRO_TURN : GYRO_CONTROL_TURN); + if (npc.isCollidesWithGrid && (Random() & 3) == 0) + { + Vector normal = npc.gridCollisionNormal; + float along = vector_dot(normal, heading); + npc.v1.y = vector_angle(vector_sub(heading, vector_scale(vector_add(normal, normal), along))); + } + if (npc.stateFrame < 1 && npc.variant == 0) npc.stateFrame = -(int)(Random() % GYRO_REST_FRAMES); +} + +// Its own goals: rolling (a positive stateFrame) or, once rested, a new goal at random or at its target. +static void gyro_goal_update(Entity_NPC& npc) +{ + bool isFree = !npc.HasEntityFlags(FLAG_CHARM | FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK) && npc.controllerID == -1 && + !npc.forcedTarget; + if (!isFree) npc.stateFrame = GYRO_STATUS_FRAMES; + if (!isFree || npc.stateFrame > 0) return gyro_roll(npc); + + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame < 0) return; + + Entity* target = npc.GetPlayerTarget(); + if (!room_check_line(npc.pos, target->pos, LINE_MODE_GROUND, 0) || Random() % GYRO_AIM_ODDS != 0) + npc.v1.y = normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES); + else npc.v1.y = vector_angle(vector_sub(target->pos, npc.pos)); + npc.stateFrame = (int)(Random() % GYRO_GOAL_FRAMES) + GYRO_GOAL_MIN; +} + +// Off cooldown it dashes at a target ahead in a clear line (or on its controller's shot). +static void gyro_dash_start(Entity_NPC& npc) +{ + if (npc.i2 < 0) + { + npc.i2 += npc_ticks_get(npc); + return; + } + if (npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return; + + Entity* target = npc.GetPlayerTarget(); + bool isSeen = npc.controllerID == -1 ? room_check_line(npc.pos, target->pos, LINE_MODE_GROUND, 0) + : npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT); + if (!isSeen) return; + + Vector heading = vector_from_angle(npc.v1.x); + Vector toward = npc.controllerID == -1 ? vector_sub(target->pos, npc.pos) : heading; + if (vector_dot(heading, toward) <= DASH_AHEAD || (npc.controllerID == -1 && Random() % GYRO_DASH_ODDS != 0)) return; + + npc.v1.x = vector_angle(toward); + npc.v1.y = npc.v1.x; + npc.state = NPC_STATE_ATTACK; + npc.PlaySound(SOUND_FART_GURG, 1, DASH_SOUND_DELAY, false, 1); + npc.velocity = {}; + npc.i2 = npc.variant == GRILLED_GYRO ? GRILLED_DASH_FRAMES : GYRO_DASH_FRAMES; +} + +// Walking: its goals and roll, its walk speed, its dash and drip. The animation it walks by. +static std::string_view gyro_walk(Entity_NPC& npc, float& playbackSpeed) +{ + npc.friction *= GYRO_FRICTION; + gyro_goal_update(npc); + + std::string_view base = "Idle"; + float speed = vector_length(npc.velocity); + if (speed > GYRO_WALK_SPEED) + { + base = "Walk"; + playbackSpeed = std::clamp(speed * GYRO_PLAYBACK_SCALE, 0.0f, 1.0f); + } + gyro_dash_start(npc); + if (Random() % GYRO_DRIP_ODDS == 0) gyro_splat(npc); + return base; +} + +// The dash: it homes on its target (or its controller's aim), bounces off walls, ends once its time runs out or under +// a status, and the grilled one drops fires. +static void gyro_dash(Entity_NPC& npc) +{ + npc.friction *= GYRO_DASH_FRICTION; + Vector heading = vector_from_angle(npc.v1.x); + float push = npc.variant == GRILLED_GYRO ? 1 : DASH_SPEED; + npc.velocity.x += heading.x * push * npc.speedMultiplier; + npc.velocity.y += heading.y * push * npc.speedMultiplier; + npc.v1.y = vector_angle(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + float turn = DASH_TURN; + if (npc.controllerID != -1) + { + if (!vector_is_zero(npc.GetControllerInput(CONTROLLER_DEADZONE))) npc.v1.y = vector_angle(npc.GetControllerInput(0)); + turn = vector_length(npc.GetControllerInput(0)) * DASH_TURN; + } + npc.v1.x = angle_approach(npc.v1.x, npc.v1.y, turn); + + if (npc.isCollidesWithGrid) + { + Vector normal = npc.gridCollisionNormal; + float along = vector_dot(normal, heading); + float bounce = GYRO_WALL_BOUNCE; + if (along >= WALL_HEAD_ON) + { + if (npc.variant != GRILLED_GYRO && npc.i2 > WALL_DASH_LEFT) npc.i2 = WALL_DASH_LEFT; + } + else + { + npc.v1.x = vector_angle(vector_sub(heading, vector_scale(vector_add(normal, normal), along))); + bounce = WALL_GLANCE_BOUNCE; + } + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + Vector hit = npc.gridCollisionVelocity; + float into = vector_dot(hit, normal); + npc.velocity = vector_sub(hit, vector_scale(vector_scale(normal, bounce), into)); + } + + npc.i2 -= npc_ticks_get(npc); + if (npc.i2 < 1 || npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) + { + int rest = npc.controllerID == -1 ? (int)(Random() % DASH_REST_RANGE) : 0; + npc.i2 = -DASH_REST - rest; + npc.state = NPC_STATE_MOVE; + } + if (npc.variant == GRILLED_GYRO && npc.IsFrame(4, npc.index) && Random() % FIRE_ODDS == 0) + { + Entity* fire = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_FIREPLACE, .variant = FIRE_MOVEABLE, .seed = Random()}); + fire->health *= random_unit() * FIRE_HEALTH + FIRE_HEALTH_MIN; + fire->targetPosition = fire->pos; + } + if (Random() % DASH_DRIP_ODDS == 0) gyro_splat(npc); +} + +// Its facing: the base animation toward its heading (mirrored), kept on its frame when only the facing changed. +static void gyro_animate(Entity_NPC& npc, std::string_view base, float playbackSpeed) +{ + ANM2& sprite = npc.sprite; + bool isSameBase = sprite.animState.animData && sprite.animState.animData->name.starts_with(base); + int frame = isSameBase ? sprite.GetFrame() : -1; + int facings = (int)GYRO_FACINGS.size(); + npc.i1 = ((int)std::floor(npc.v1.x / (HALF_TURN_DEGREES / 4) + HALF) + facings) % facings; + char name[64]; + std::snprintf(name, sizeof(name), "%.*s%.*s", (int)base.size(), base.data(), (int)GYRO_FACINGS[npc.i1].size(), + GYRO_FACINGS[npc.i1].data()); + sprite.isFlipX = npc.v1.x >= -RIGHT_ANGLE_DEGREES && npc.v1.x <= RIGHT_ANGLE_DEGREES; + if (!sprite.animState.animData || sprite.GetAnimation() != name) + { + sprite.Play(name); + if (frame >= 0) sprite.SetFrame((float)frame); + } + sprite.playbackSpeed = playbackSpeed; + npc.forwardVector = vector_from_angle(npc.v1.x); +} + +// Fire never hurts it, and turns a Gyro grilled. +static void gyro_fire_absorb(Entity_NPC& npc) +{ + for (DamageEvent& event : npc.damageEvents) + { + if (!(event.damageFlags & DAMAGE_FIRE)) continue; + + npc.pendingDamage -= event.damage; + event.damage = 0; + if (npc.type != ENTITY_GYRO || npc.variant != 0) continue; + + npc.Morph(ENTITY_GYRO, GRILLED_GYRO, 0, -1); + npc.splatColor = GRILLED_SPLAT_COLOR; + } +} + +// 004ff620 The Gyro's AI: it rolls about, now and then dashing at a target ahead, bouncing off walls. Hit, it +// staggers. The Grilled Gyro dashes longer, dropping fires, and fire turns a Gyro grilled. +void npc_gyro_update(Entity_NPC& npc) +{ + npc.UpdateChargeBar(DASH_CHARGE_BAR, 0, (float)npc.i2, true); + std::string_view base; + float playbackSpeed = 1; + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.i1 = 0; + npc.stateFrame = 0; + npc.v1 = vector_make(normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES), 0); + npc.i2 = 0; + npc.projectileCooldown = 0; + if (npc.variant == GRILLED_GYRO) npc.splatColor = GRILLED_SPLAT_COLOR; + } + else if (npc.state == NPC_STATE_MOVE) base = gyro_walk(npc, playbackSpeed); + else if (npc.state == NPC_STATE_ATTACK) + { + base = "Dash"; + gyro_dash(npc); + } + + if (npc.pendingDamage > 0 && npc.projectileCooldown < 1) + npc.projectileCooldown = npc.controllerID == -1 ? STAGGER_FRAMES : STAGGER_CONTROL_FRAMES; + if (npc.projectileCooldown > 0) + { + if (npc.projectileCooldown > STAGGER_DRAG_FRAMES) npc.friction *= STAGGER_FRICTION; + npc.projectileCooldown -= npc_ticks_get(npc); + } + if (!base.empty()) gyro_animate(npc, base, playbackSpeed); + gyro_fire_absorb(npc); +} diff --git a/src/npc_hive.cpp b/src/npc_hive.cpp index 3aabc11..a3c855f 100644 --- a/src/npc_hive.cpp +++ b/src/npc_hive.cpp @@ -4,6 +4,7 @@ #include "room.h" #include "room_grid.h" #include +#include #include // The hives this AI runs: the Hive (with its drowned, holy and tainted variants), the Nest and the Willo hive. @@ -51,6 +52,20 @@ constexpr float WILLO_LEECH_REACH = 80; constexpr float WILLO_LEECH_SCATTER = 10; constexpr float WILLO_LEECH_HEIGHT = -10; +// The tainted Hive lets out a ring of six flies on its attack, led by the first, each holding on 200 to 299 longer. +// Dying it bursts into a swarm: boom flies, suckers, attack flies, flies and army flies scattered 5 to 15 around it. +// Its rings' flies but every fifth by seed do not count toward its crowd. +constexpr int TAINTED_RING_FLIES = 6; +constexpr int TAINTED_RING_SUBTYPE = 1; +constexpr uint32_t TAINTED_RING_HOLD_RANGE = 100; +constexpr int TAINTED_RING_HOLD_MIN = 200; +constexpr uint32_t TAINTED_CROWD_EVERY = 5; +constexpr float TAINTED_BURST_SCATTER = 10; +constexpr float TAINTED_BURST_SCATTER_MIN = 5; +constexpr std::array, 13> TAINTED_BURST = {{{ENTITY_BOOMFLY, 0}, {ENTITY_BOOMFLY, 1}, {ENTITY_SUCKER, 0}, + {ENTITY_SUCKER, 1}, {ENTITY_SUCKER, 3}, {ENTITY_ATTACKFLY, 0}, {ENTITY_ATTACKFLY, 0}, {ENTITY_FLY, 0}, {ENTITY_FLY, 0}, + {ENTITY_ARMYFLY, 0}, {ENTITY_ARMYFLY, 0}, {ENTITY_ARMYFLY, 0}, {ENTITY_ARMYFLY, 0}}}; + static Entity* spawn_free(Entity_NPC& npc, int type, int variant, const Vector& position, const Vector& velocity, int subType) { @@ -137,7 +152,19 @@ static void hive_release(Entity_NPC& npc) return; } if (npc.type == ENTITY_HIVE && npc.variant == HIVE_TAINTED) - reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: the tainted Hive's ring of flies"); + { + Entity* leader = nullptr; + for (int i = 0; i < TAINTED_RING_FLIES; i++) + { + Entity* ringFly = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .subType = TAINTED_RING_SUBTYPE, .type = ENTITY_RING_OF_FLIES, .seed = Random()}); + if (!leader) leader = ringFly; + ringFly->parent = leader; + ringFly->ClearEntityFlags(FLAG_APPEAR); + ringFly->health = (float)(int)(Random() % TAINTED_RING_HOLD_RANGE + TAINTED_RING_HOLD_MIN) + 0 + ringFly->health; + } + return; + } Entity* fly = spawn_free(npc, npc.type == ENTITY_HIVE ? ENTITY_ATTACKFLY : ENTITY_SPIDER, 0, npc.pos, {}, 0); fly->isKillOnTouch = true; @@ -187,7 +214,21 @@ static void hive_death(Entity_NPC& npc) for (int i = 0; i < count; i++) { if (npc.type == ENTITY_HIVE && npc.variant == HIVE_TAINTED) - reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: the tainted Hive's ring of flies"); + { + for (auto [type, variant] : TAINTED_BURST) + { + uint32_t seed = Random(); + Vector direction = random_direction(); + float reach = random_unit() * TAINTED_BURST_SCATTER + TAINTED_BURST_SCATTER_MIN; + Entity* spawned = g_game->Spawn({.position = vector_add(vector_scale(direction, reach), npc.pos), + .spawner = &npc, + .type = type, + .variant = variant, + .seed = seed}); + spawned->ClearEntityFlags(FLAG_APPEAR); + } + continue; + } if (npc.type == ENTITY_WILLO_HIVE) { if (npc.variant != 1) @@ -254,7 +295,8 @@ void npc_hive_update(Entity_NPC& npc) int crowd = npc.GetAliveEnemyCount(); if (npc.type == ENTITY_HIVE && npc.variant == HIVE_TAINTED) - reconstruction_missing("NpcAI::ENTITY_HIVE 0050c370: the tainted Hive's own flies left out of the crowd"); + for (Entity* ringFly : entity_query(ENTITY_RING_OF_FLIES, -1)) + if (ringFly->parent.get() != ringFly && ringFly->initSeed % TAINTED_CROWD_EVERY == 0) crowd--; if (npc.v1.x - npc.speedMultiplier <= 0 && (int)(Random() % REST_CROWD_RANGE) + REST_CROWD_MIN <= crowd) npc.v1.x += (float)((int)(Random() % REST_RANGE) + REST_MIN); if (npc.pathfinder.evadeMovementCountdown > 0) hive_attack_start(npc); diff --git a/src/npc_hopper.cpp b/src/npc_hopper.cpp index f4110d1..7875738 100644 --- a/src/npc_hopper.cpp +++ b/src/npc_hopper.cpp @@ -4,6 +4,7 @@ #include "game.h" #include "room.h" #include "room_grid.h" +#include "loot_list.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. @@ -250,6 +251,26 @@ static void hopper_shoot_update(Entity_NPC& npc, Vector toward) if (!npc.sprite.animState.animData || !npc.sprite.animState.isPlaying) hopper_idle_reset(npc); } +// Pon lands only on open floor off the pits: while its spot is blocked or past path level 199 it tries up to ten +// random spots its jump's reach away. +constexpr int PON_PATH_LIMIT = 199; +constexpr int PON_SPOT_TRIES = 10; +constexpr uint32_t PON_SPOT_PIT = 2; + +static uint32_t pon_landing_find(Entity_NPC& npc, float bonus, Vector& spot, uint32_t collision) +{ + Room& room = *g_game->room; + if (room.GetGridPath(room.GetGridIndex(spot)) > PON_PATH_LIMIT) collision = PON_SPOT_PIT; + for (int i = 0; i < PON_SPOT_TRIES && collision != 0; i++) + { + Vector candidate = vector_add(vector_scale(random_direction(), bonus + RANDOM_HOP_REACH), npc.pos); + spot = room.GetClampedPositionImpl(candidate, 0, 0, 0, 0); + collision = room_grid_collision_at(spot); + if (room.GetGridPath(room.GetGridIndex(spot)) > PON_PATH_LIMIT) collision = PON_SPOT_PIT; + } + return collision; +} + // A rested hopper picks its next spot: toward its target when in range (the flaming one leading it), else a random // one, clamped into the room. It hops to the middle of a free cell there, or the Ragling attacks now and then. static void hopper_hop_start(Entity_NPC& npc, const HopperJump& jump, const HopperAnims& anims, const Vector& aim, @@ -270,7 +291,7 @@ static void hopper_hop_start(Entity_NPC& npc, const HopperJump& jump, const Hopp spot = room.GetClampedPosition(spot, HOP_CLAMP_MARGIN); uint32_t collision = vector_is_zero(spot) ? COLLISION_BLOCKED : room_grid_collision_at(spot); - if (npc.type == ENTITY_PON) reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: Pon's search for a landing spot"); + if (npc.type == ENTITY_PON) collision = pon_landing_find(npc, jump.bonus, spot, collision); bool isAttacking = Random() % RAGLING_ATTACK_ODDS == 0; if (isAttacking && npc.type == ENTITY_RAGLING && !npc.HasEntityFlags(FLAG_DISTRACTED)) { @@ -554,6 +575,103 @@ static void ragling_update(Entity_NPC& npc) else if (npc.state == NPC_STATE_SPECIAL) npc.sprite.Play("Die"); } +// Eggy dying bursts over a few seconds, spawning swarm spiders: every third tick of its first 15 (from the second), +// every sixth of its first 32 (from the first) and every 15th up to 60. A dark red champion's revivals thin them +// out. Each hops off short, mid or long (3, 2 and 1 in 6), and Eggy dies once its animation ends. +constexpr int EGGY_BURST_FIRST = 15; +constexpr int EGGY_BURST_FIRST_EVERY = 3; +constexpr int EGGY_BURST_FIRST_AT = 2; +constexpr int EGGY_BURST_SECOND = 32; +constexpr int EGGY_BURST_SECOND_EVERY = 6; +constexpr int EGGY_BURST_LAST = 61; +constexpr int EGGY_BURST_LAST_EVERY = 15; +constexpr int EGGY_REVIVAL_ODDS_MAX = 3; +constexpr int EGGY_SHRINK_FRAMES = -150; +constexpr float EGGY_BURST_HEALTH = 0.1f; +constexpr RNG EGGY_HOP_RNG_SHIFTS = {0, 5, 9, 7}; + +// A spider's hop out of Eggy: its animation, the frame it starts on and its speed range. +struct EggyHop +{ + std::string_view anim; + int frame = 0; + float speedRange = 0; + float speedMin = 0; +}; +constexpr std::array EGGY_HOPS = {{{"HopShort", 4, 1, 5}, {"Hop", 5, 2, 8}, {"HopLong", 6, 3, 10}}}; +constexpr std::array EGGY_HOP_WEIGHTS = {3, 2, 1}; + +// A swarm spider hopping out of the bursting Eggy. +static void eggy_spider_spawn(Entity_NPC& npc) +{ + if (npc.championRegenCount > 0) + { + uint32_t odds = (uint32_t)std::min(npc.championRegenCount + 1, EGGY_REVIVAL_ODDS_MAX); + if (Random() % odds != 0) return; + } + uint32_t seed = npc.dropRNG.Next(); + Vector position = vector_add(random_direction(), npc.pos); + auto* spider = static_cast( + g_game->Spawn({.position = position, .spawner = &npc, .type = ENTITY_SWARM_SPIDER, .seed = seed})); + spider->AddEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK); + + WeightedOutcomePicker picker; + for (int i = 0; i < (int)EGGY_HOP_WEIGHTS.size(); i++) picker.AddOutcomeWeight(i, EGGY_HOP_WEIGHTS[i]); + Vector direction = random_direction(); + RNG rng = EGGY_HOP_RNG_SHIFTS; + rng._seed = Random() | 1; + int pick = picker.PickOutcome(rng); + if (pick >= 0 && pick < (int)EGGY_HOPS.size()) + { + const EggyHop& hop = EGGY_HOPS[pick]; + spider->sprite.Play(hop.anim); + spider->sprite.SetFrame((float)hop.frame); + float speed = random_unit() * hop.speedRange + hop.speedMin; + direction = vector_make(direction.x * speed, direction.y * speed); + } + spider->targetPosition = direction; + spider->state = NPC_STATE_JUMP; + spider->velocity = direction; +} + +// Bursting: held in place, it shudders on Jump and lets spiders out tick by tick, dying once the animation ends. +static void eggy_burst_update(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_NONE; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + if (npc.sprite.IsEventTriggered("Jump")) + { + npc.PlaySound(SOUND_PLOP, 1, 2, false, 1); + npc.PlaySound(SOUND_BOIL_HATCH, 1, 2, false, 1); + npc.stateFrame = 0; + } + if (npc.stateFrame >= 0) + for (int tick = 0; tick < npc_ticks_get(npc); tick++) + { + int frame = ++npc.stateFrame; + bool isSpawning = (frame < EGGY_BURST_FIRST && frame % EGGY_BURST_FIRST_EVERY == EGGY_BURST_FIRST_AT) || + (frame < EGGY_BURST_SECOND && frame % EGGY_BURST_SECOND_EVERY == 1) || + (frame < EGGY_BURST_LAST && frame % EGGY_BURST_LAST_EVERY == 0); + if (isSpawning) eggy_spider_spawn(npc); + } + if (!npc.sprite.IsPlaying()) npc.Kill(EntityRef()); +} + +// Killed, Eggy holds on to burst: cured (but staying shrunk), invulnerable, barely alive and held where it died. +static void eggy_burst_start(Entity_NPC& npc) +{ + npc.sprite.Play("Die"); + npc.state = NPC_STATE_SUICIDE; + bool isShrunk = npc.HasEntityFlags(FLAG_SHRINK); + npc.RemoveStatusEffects(); + if (isShrunk) npc.AddShrink(EntityRef(&npc), EGGY_SHRINK_FRAMES, false); + npc.stateFrame = -1; + npc.isInvincible = true; + npc.isDead = false; + npc.health = EGGY_BURST_HEALTH; + npc.targetPosition = npc.pos; +} + // 00526470 The hoppers' AI: they rest, then hop to a cell toward their target (or anywhere when it is out of range), // landing with a thud. Fire turns a hopper into a flaming one, the Keeper and Ministro stop to shoot, and Rag Man's // Raglings play dead for him. @@ -592,8 +710,8 @@ void npc_hopper_update(Entity_NPC& npc) if (npc.state == NPC_STATE_IDLE && !vector_is_zero(npc.targetPosition)) npc.targetPosition = {}; bool isEggy = npc.type == ENTITY_HOPPER && npc.variant == HOPPER_EGGY; - if (isEggy && (npc.state == NPC_STATE_SUICIDE || (npc.isDead && npc.state != NPC_STATE_DEATH))) - reconstruction_missing("NpcAI::ENTITY_HOPPER 00526470: Eggy bursting into spiders"); + if (isEggy && npc.state == NPC_STATE_SUICIDE) eggy_burst_update(npc); + if (isEggy && npc.isDead && npc.state != NPC_STATE_SUICIDE && npc.state != NPC_STATE_DEATH) eggy_burst_start(npc); npc.stateFrame += npc_ticks_get(npc); npc.friction *= HOPPER_FRICTION; diff --git a/src/npc_mr_mine.cpp b/src/npc_mr_mine.cpp new file mode 100644 index 0000000..5839c91 --- /dev/null +++ b/src/npc_mr_mine.cpp @@ -0,0 +1,344 @@ +#include "npc_depths.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "game.h" +#include "room.h" +#include "room_grid.h" +#include + +// Mr. Mine (variant 0) lives in the pits: it rises out of one, now and then lunges at its target, and digs back into +// the best pit toward its target. Its neck (variant 10) is eight segments strung from its pit to its head. +constexpr int MINE_VARIANT_LAST = 9; +constexpr int MINE_NECK = 10; +constexpr int MINE_NECK_SEGMENTS = 8; +constexpr int MINE_NECK_HIDDEN_Z = -100; +constexpr int MINE_PIT_TIMER = 5; +constexpr int MINE_LOST_FRAMES = 30; + +// Out of its pit it waits 12 frames, then (every fourth tick, calm) lunges at 14 at a target heading within 130 in a +// clear line, waiting 30 after. It digs in again one tick in 30 after 16 frames (or once told to), and a charmed one +// one tick in 50. +constexpr int MINE_OUT_COOLDOWN = 12; +constexpr float MINE_LUNGE_LEAD = 3; +constexpr float MINE_LUNGE_RANGE_SQUARED = 16900; +constexpr float MINE_LUNGE_SPEED = 14; +constexpr int MINE_LUNGE_COOLDOWN = 30; +constexpr int MINE_DIG_SETTLE = 16; +constexpr uint32_t MINE_DIG_ODDS = 30; +constexpr uint32_t MINE_CHARMED_DIG_ODDS = 50; +constexpr int MINE_DIG_NOW = 1000; +constexpr uint32_t MINE_LUNGE_REST_ODDS = 5; + +// A lunge pulls back toward its pit, damped less the more of its lunge is left. +constexpr float MINE_PULL_NEAR = 5; +constexpr int MINE_PULL_FIRST_FRAMES = 14; +constexpr float MINE_PULL = 0.7f; +constexpr float MINE_PULL_DAMPING = 0.9f; +constexpr float MINE_PULL_DAMPING_PER_FRAME = 0.0028f; + +// Surfacing and diving in water it splashes, 4 to 9 droplets thrown up to 4 out. +constexpr float MINE_SPLASH_SCALE = 1.5f; +constexpr uint32_t MINE_DROPLETS_RANGE = 6; +constexpr uint32_t MINE_DROPLETS_MIN = 4; +constexpr float MINE_DROPLET_SPEED = 4; +constexpr float MINE_DROPLET_SCALE_MIN = 1; + +// It dies in a ring of six shots. +constexpr float MINE_RING_SPEED = 8; +constexpr float MINE_RING_SHOTS = 6; + +// A neck segment sits along the line from the pit to the head's layer (in the 0.65 scaled sprite), its share along +// it set by its index, and fades in as the neck stretches. +constexpr float NECK_SPRITE_SCALE = 0.65f; +constexpr float NECK_LAST_INDEX = 7; +constexpr float NECK_SHARE = 0.125f; +constexpr float NECK_LIFT = 14; +constexpr float NECK_DEPTH = -1000; +constexpr float NECK_FADE = 0.025f; +constexpr int NECK_HEAD_LAYER = 1; + +// A splash of droplets where it breaks the water, the dive's a little bigger. +static void mine_droplets_spawn(Entity_NPC& npc, bool isGrown) +{ + for (uint32_t count = Random() % MINE_DROPLETS_RANGE + MINE_DROPLETS_MIN; count != 0; count--) + { + Vector direction = random_direction(); + float speed = random_unit(); + Vector velocity = vector_make(direction.x * speed * MINE_DROPLET_SPEED, direction.y * speed * MINE_DROPLET_SPEED); + Entity* droplet = g_game->Spawn({.position = vector_add(velocity, npc.pos), + .velocity = velocity, + .spawner = &npc, + .subType = 1, + .type = ENTITY_EFFECT, + .variant = EFFECT_WATER_SPLASH, + .seed = Random()}); + droplet->Update(); + if (!isGrown) continue; + + float scale = random_unit() + MINE_DROPLET_SCALE_MIN; + droplet->sprite.scale = vector_make(scale, scale); + } +} + +// Whether its room holds water to splash in. +static bool mine_is_wet() +{ + Room& room = *g_game->room; + return room.waterAmount > 0 || (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER); +} + +// Its first frame: the neck strung out hidden, and Mr. Mine dug in. +static void mine_init(Entity_NPC& npc) +{ + for (int i = 0; i < MINE_NECK_SEGMENTS; i++) + { + Entity* segment = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_MR_MINE, .variant = MINE_NECK, .seed = Random()}); + auto& neck = static_cast(*segment); + neck.parent = &npc; + neck.entityCollisionClass = ENTCOLL_NONE; + neck.shadowSize = 0; + neck.renderZOffset = MINE_NECK_HIDDEN_Z; + neck.ClearEntityFlags(FLAG_APPEAR); + neck.AddEntityFlags(FLAG_NO_DEATH_TRIGGER); + neck.isVisible = false; + neck.v1.x = (float)i; + } + npc.ClearEntityFlags(FLAG_APPEAR); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.i1 = -1; + npc.i2 = -1; + npc_anim_loop(npc.sprite, "DigIn"); + npc.sprite.SetLastFrame(); +} + +// A neck segment: strung along the line from the pit to the head while the head shows, hidden at the pit else. +static void mine_neck_update(Entity_NPC& neck) +{ + Entity_NPC* mine = neck.ParentNPC(); + if (!mine || mine->type != ENTITY_MR_MINE) return neck.Remove(); + + const AnimationFrame* head = mine->sprite.animState.GetLayerFrame(NECK_HEAD_LAYER); + if (!head || !head->isVisible) + { + neck.pos = mine->targetPosition; + neck.isVisible = false; + return; + } + + float share = (NECK_LAST_INDEX - neck.v1.x) * NECK_SHARE; + neck.isVisible = true; + Vector reach = vector_sub(vector_make(mine->pos.x + head->pos.x / NECK_SPRITE_SCALE, mine->pos.y + 0), mine->targetPosition); + neck.velocity = vector_make(share * reach.x + mine->targetPosition.x - neck.pos.x, + share * reach.y + mine->targetPosition.y - neck.pos.y); + float rise = head->pos.y / NECK_SPRITE_SCALE - NECK_LIFT; + neck.posOffset.y = rise * share + NECK_LIFT; + neck.renderZOffset = (int)std::floor((1 - share) * NECK_DEPTH); + float stretch = std::sqrt(rise * rise + reach.y * reach.y + reach.x * reach.x); + neck.sprite.GetLayer(0)->color._tint[3] = std::clamp(stretch * share * NECK_FADE, 0.0f, 1.0f); +} + +// Dug in: it surfaces at the pit it marked, or the best one toward its target. With none for 30 frames it is gone +// (a charmed one waits). Whether it is still there. +static bool mine_underground(Entity_NPC& npc, Room& room) +{ + int pit = npc.i1; + if (pit >= 0) + { + GridEntity* grid = pit < (int)ROOM_GRID_CELLS ? room.gridEntities[pit] : nullptr; + if (!grid || grid->type != GRID_PIT || grid->collisionClass != COLLISION_PIT) pit = -1; + } + if (pit < 0) + { + pit = Entity_NPC::FindTargetPit(npc.pos, npc.CalcTargetPosition(0), (uint32_t)npc.i2); + npc.i1 = pit; + } + if (pit < 0) + { + npc.stateFrame += npc_ticks_get(npc); + if (npc.stateFrame <= MINE_LOST_FRAMES || npc.HasEntityFlags(FLAG_FRIENDLY)) return true; + npc.Remove(); + return false; + } + + npc.stateFrame = 0; + npc.targetPosition = room.GetGridPosition(pit); + npc.pos = npc.targetPosition; + npc.velocity = {}; + npc.state = NPC_STATE_JUMP; + npc.sprite.Play("DigOut"); + npc.i2 = npc.i1; + return true; +} + +// Surfacing: it shows (with its shadow) on Shoot, splashing in water, and waits once out. +static void mine_dig_out(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.shadowSize = npc.config->shadowSize; + if (mine_is_wet()) + { + Entity* splash = g_game->Spawn( + {.position = npc.pos, .spawner = &npc, .type = ENTITY_EFFECT, .variant = EFFECT_WATER_SPLASH, .seed = Random()}); + splash->sprite.scale = vector_make(MINE_SPLASH_SCALE, MINE_SPLASH_SCALE); + splash->Update(); + mine_droplets_spawn(npc, false); + } + } + if (npc.sprite.IsPlaying()) return; + + npc.projectileCooldown = MINE_OUT_COOLDOWN; + npc.sprite.Play("Idle"); + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; +} + +// Diving: it hides (and its shadow) on Shoot, splashing in water, and is underground once in. +static void mine_dig_in(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.shadowSize = 0; + if (mine_is_wet()) mine_droplets_spawn(npc, true); + } + if (npc.sprite.IsPlaying()) return; + + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; +} + +// Out of its pit: it faces its target, lunges at it when it may, and digs back in when it is time. +static void mine_surfaced(Entity_NPC& npc) +{ + if (npc.projectileCooldown > 0) npc.projectileCooldown = std::max(npc.projectileCooldown - npc_ticks_get(npc), 0); + Entity* target = npc.GetPlayerTarget(); + npc.sprite.isFlipX = target->pos.x < npc.pos.x; + if (npc.IsFrame(4, 0) && npc.projectileCooldown < 1 && !npc.HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) + { + Vector lead = vector_sub(vector_add(vector_scale(target->velocity, MINE_LUNGE_LEAD), target->pos), npc.pos); + float distanceSquared = vector_length_squared(lead); + if (distanceSquared < MINE_LUNGE_RANGE_SQUARED && room_check_line(npc.pos, target->pos, LINE_MODE_EXPLOSION, 0)) + { + npc.PlaySound(SOUND_MEATHEADSHOOT, 1, 2, false, 1); + float scale = MINE_LUNGE_SPEED / std::sqrt(distanceSquared); + npc.velocity = vector_make(scale * lead.x / npc.friction, scale * lead.y / npc.friction); + npc.sprite.isFlipX = lead.x < 0; + npc.state = NPC_STATE_ATTACK; + npc.stateFrame = 0; + npc.projectileCooldown = MINE_LUNGE_COOLDOWN; + } + } + + bool isDigging = npc.stateFrame >= MINE_DIG_SETTLE && Random() % MINE_DIG_ODDS == 0; + isDigging = isDigging || npc.stateFrame > MINE_DIG_NOW - 1 || + (npc.HasEntityFlags(FLAG_FRIENDLY) && Random() % MINE_CHARMED_DIG_ODDS == 0); + if (isDigging) + { + int pit = Entity_NPC::FindTargetPit(npc.pos, npc.CalcTargetPosition(0), (uint32_t)npc.i1); + if (pit >= 0) + { + npc.i1 = pit; + npc.stateFrame = 0; + npc.sprite.Play("DigIn"); + npc.state = NPC_STATE_STOMP; + } + } + if (npc.stateFrame > 0 || npc.pendingDamage > 0) npc.stateFrame += npc_ticks_get(npc); +} + +// The lunge: pulled back toward its pit, until back there it rests (and most times digs in at once). +static void mine_lunge(Entity_NPC& npc) +{ + Vector back = vector_sub(npc.targetPosition, npc.pos); + float distance = vector_length(back); + if (distance >= MINE_PULL_NEAR || npc.projectileCooldown > MINE_PULL_FIRST_FRAMES) + { + if (npc.friction != 0) + { + npc.velocity.x += back.x * (MINE_PULL / distance) * npc.speedMultiplier / npc.friction; + npc.velocity.y += back.y * (MINE_PULL / distance) * npc.speedMultiplier / npc.friction; + } + float damping = (float)npc.projectileCooldown * MINE_PULL_DAMPING_PER_FRAME + MINE_PULL_DAMPING; + npc.friction *= timescale_factor(damping, npc.speedMultiplier); + } + else + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = Random() % MINE_LUNGE_REST_ODDS != 0 ? MINE_DIG_NOW : 0; + } + npc.projectileCooldown -= npc_ticks_get(npc); +} + +// Its pit kept open for it, held to its pit, and killed once its pit is filled in. +static void mine_pit_hold(Entity_NPC& npc, Room& room) +{ + if (npc.state != NPC_STATE_ATTACK && !vector_is_zero(npc.targetPosition)) + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + int pit = npc.i1; + if (pit >= 0 && npc.state != NPC_STATE_IDLE && pit < (int)ROOM_GRID_CELLS && room.gridEntities[pit] && + room.gridEntities[pit]->type == GRID_PIT) + room.gridTimers[pit] = MINE_PIT_TIMER; + if (npc.entityCollisionClass == ENTCOLL_NONE || vector_is_zero(npc.targetPosition)) return; + if (room_grid_collision_at(npc.targetPosition) != COLLISION_PIT) npc.Kill(EntityRef()); +} + +// 005492c0 Mr. Mine's AI and its neck's: it hides in the pits and rises to lunge at its target on its stretching +// neck, digging into another pit. It dies in a ring of shots. +void npc_mr_mine_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + if (npc.variant <= MINE_VARIANT_LAST) mine_init(npc); + npc.state = NPC_STATE_IDLE; + return; + } + if (npc.variant > MINE_VARIANT_LAST) + { + if (npc.variant == MINE_NECK) mine_neck_update(npc); + return; + } + if (npc.isDead) + { + if (npc.HasEntityFlags(FLAG_SHRINK)) return; + ProjectileParams params; + params.circleAngle = 0; + npc.FireProjectiles(npc.pos, vector_make(MINE_RING_SPEED, MINE_RING_SHOTS), PROJECTILES_RING, params); + npc.PlaySound(SOUND_SHAKEY_KID_ROAR, 1, 2, false, 1); + return; + } + + Room& room = *g_game->room; + if (room.isInitialized && g_game->frameCount == room.enterFrame && npc.HasEntityFlags(FLAG_FRIENDLY)) + { + npc.state = NPC_STATE_IDLE; + npc.sprite.Play("DigIn"); + npc.sprite.SetLastFrame(); + npc.i1 = -1; + npc.i2 = -1; + npc.entityCollisionClass = ENTCOLL_NONE; + } + if (npc.projectileCooldown > 0) npc.projectileCooldown = std::max(npc.projectileCooldown - npc_ticks_get(npc), 0); + + switch (npc.state) + { + case NPC_STATE_IDLE: + if (!mine_underground(npc, room)) return; + break; + case NPC_STATE_JUMP: + mine_dig_out(npc); + break; + case NPC_STATE_STOMP: + mine_dig_in(npc); + break; + case NPC_STATE_MOVE: + mine_surfaced(npc); + break; + case NPC_STATE_ATTACK: + mine_lunge(npc); + break; + } + mine_pit_hold(npc, room); +} diff --git a/src/npc_peeper_fatty.cpp b/src/npc_peeper_fatty.cpp new file mode 100644 index 0000000..fe7d75d --- /dev/null +++ b/src/npc_peeper_fatty.cpp @@ -0,0 +1,419 @@ +#include "npc_alt.h" +#include "entity_effect.h" +#include "entity_npc.h" +#include "npc_basement.h" +#include "room.h" +#include +#include + +// The Peeping Fatty (variant 0) walks toward whichever of its two eyes (variant 10) has the shortest look, and 60 to +// 209 frames apart (60 under control) farts out a ring of six shots. +constexpr int PEEPER_EYE = 10; +constexpr float PEEPER_WALK_THRESHOLD = 0.1f; +constexpr float PEEPER_FRICTION = 0.6f; +constexpr float PEEPER_SPEED = 1.2f; +constexpr float PEEPER_CONTROL_SCALE = 1.25f; +constexpr float PEEPER_EYE_FAR = 1e8f; +constexpr float PEEPER_PATH_SPEED_SCALE = 100; +constexpr float PEEPER_PATH_SPEED_MAX = 0.5f; +constexpr int PEEPER_PATH_MARKER = 900; +constexpr uint32_t PEEPER_GROAN_ODDS = 40; +constexpr int PEEPER_GROAN_DELAY = 60; +constexpr int PEEPER_WAIT_RANGE = 150; +constexpr int PEEPER_WAIT_MIN = 60; +constexpr uint32_t PEEPER_ATTACK_ODDS = 60; +constexpr float PEEPER_ATTACK_RANGE = 1000; +constexpr float PEEPER_FART_RADIUS = 120; +constexpr float PEEPER_RING_SPEED = 8; +constexpr float PEEPER_RING_SHOTS = 6; +constexpr float PEEPER_ATTACK_FRICTION = 0.4f; +constexpr float PEEPER_EYE_SPREAD = 30; + +// The chase a fatty without eyes falls back on (PathFinder::update_chase_movement): its heading (movementTarget.y) +// turning toward a goal heading (movementTarget.x) picked every 45 to 164 frames (moveCountdown). +constexpr float CHASE_TURN = 10; +constexpr int CHASE_STATUS_FRAMES = 10; +constexpr uint32_t CHASE_CONFUSED_ODDS = 5; +constexpr float CHASE_PATH_SPEED = 1; +constexpr int CHASE_FRAMES = 120; +constexpr int CHASE_FRAMES_MIN = 45; + +// An eye hangs 20 up on a cord of six points from the fatty, leashed loose to 75. It looks around (aiFloat), at its +// target within 200 straight ahead, or at a player, enemy, pickup or bomb in its gaze over 120 from the fatty, and +// drifts to 40 short of what it looks at. +constexpr int EYE_CORD_POINTS = 6; +constexpr float EYE_CORD_SPACING = 5; +constexpr float EYE_HEIGHT = -20; +constexpr float EYE_START_LOOK = 90; +constexpr float EYE_START_REACH = 10000; +constexpr float EYE_START_DROP = 100; +constexpr int EYE_CORD_SETTLE_STEPS = 10; +constexpr int EYE_CORD_SETTLE_FRAMES = 2; +constexpr float EYE_PARENT_DRAG = 0.2f; +constexpr float PEEPER_EYE_LEASH = 75; +constexpr float EYE_LEASH_PULL = 0.1f; +constexpr float EYE_LEASH_SHARE = 0.3f; +constexpr float PEEPER_EYE_FRICTION = 0.95f; +constexpr float EYE_SIGHT_SQUARED = 40000; +constexpr float EYE_GAZE = 0.85f; +constexpr float EYE_SEEK_CLEARANCE_SQUARED = 14400; +constexpr float EYE_FORGET_SQUARED = 80; +constexpr uint32_t EYE_FORGET_ODDS = 20; +constexpr float EYE_SIDE = 0.1f; +constexpr int EYE_FORGET_DELAY = 45; +constexpr float EYE_LOOK_SHARE = 0.5f; +constexpr float EYE_STOP_SHORT = 40; +constexpr float EYE_PULL = 0.25f; +constexpr float PEEPER_EYE_TURN = 0.5f; +constexpr int EYE_GAZE_TRIES = 10; +constexpr float EYE_GAZE_SPREAD = 220; +constexpr float EYE_GAZE_REACH = 200; +constexpr float EYE_GAZE_CHECK = 80; +constexpr int EYE_GAZE_FRAMES = 60; +constexpr int EYE_GAZE_MIN = 15; +constexpr int EYE_IDLE_FRAMES = 8; +constexpr int EYE_IDLE_RIGHT = 4; + +// 007e6b90 PathFinder::update_chase_movement: a fatty heads on, turning toward its goal heading, which it picks anew +// once its time is up, on bumping a wall one time in four, at random when confused, away when afraid, and along its +// grid path when charmed. A controlled one walks where its controller points. +void PathFinder::update_chase_movement() +{ + auto* npc = static_cast(entity->to_npc_or_coop_player()); + if (npc && npc->controllerID != -1) + { + npc->friction *= PEEPER_FRICTION; + Vector input = npc->GetControllerInput(0); + npc->velocity.x += input.x * PEEPER_SPEED * PEEPER_CONTROL_SCALE * npc->speedMultiplier; + npc->velocity.y += input.y * PEEPER_SPEED * PEEPER_CONTROL_SCALE * npc->speedMultiplier; + return; + } + + entity->friction *= PEEPER_FRICTION; + if (entity->HasEntityFlags(FLAG_CHARM | FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) moveCountdown = CHASE_STATUS_FRAMES; + if (npc && npc->HasEntityFlags(FLAG_CONFUSION)) + { + if (Random() % CHASE_CONFUSED_ODDS == 0) + movementTarget.x = normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES); + } + else if (npc && npc->HasEntityFlags(FLAG_CHARM)) + { + Entity* target = npc->GetPlayerTarget(); + if (npc->IsFrame(5, npc->index)) + { + Reset(); + FindGridPath(target->pos, CHASE_PATH_SPEED, PEEPER_PATH_MARKER, DIRECT_PATH_FAR); + movementTarget.x = vector_angle(npc->velocity); + } + } + else if (npc && npc->HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + movementTarget.x = vector_angle(vector_sub(npc->pos, npc->GetPlayerTarget()->pos)); + + moveCountdown -= entity->update_ticks_get(); + Vector heading = vector_from_angle(movementTarget.y); + entity->velocity.x += heading.x * PEEPER_SPEED * entity->speedMultiplier; + entity->velocity.y += heading.y * PEEPER_SPEED * entity->speedMultiplier; + movementTarget.y = angle_approach(movementTarget.y, movementTarget.x, CHASE_TURN); + if (entity->isCollidesWithGrid && (Random() & 3) == 0) + { + Vector normal = entity->gridCollisionNormal; + float along = vector_dot(normal, heading); + movementTarget.x = vector_angle(vector_sub(heading, vector_scale(vector_add(normal, normal), along))); + } + if (moveCountdown >= 1) return; + + movementTarget.x = normalize_angle_degrees(random_unit() * FULL_TURN_DEGREES); + moveCountdown = (int)(Random() % CHASE_FRAMES) + CHASE_FRAMES_MIN; +} + +// Whether an eye's fatty is still there to hang from: an enemy, or a player in a versus match. +static bool peeper_eye_is_hung(Entity_NPC& eye) +{ + return eye.parent && Entity::is_enemy_type(eye.parent->type); +} + +// The fatty's eye socket an eye hangs from: the left one for subtype 0, the right one else. +static Vector peeper_socket_get(Entity_NPC& eye) +{ + return eye.ParentNPC()->GetNullOffset(eye.subtype == 0 ? "LeftEye" : "RightEye"); +} + +// Before each update and interpolation an eye's cord follows both ends (laid anew on the room's first frames) and a +// stretched cord pulls the eye back toward its socket. Without its fatty the eye dies. +static void peeper_eye_cord_update(Entity_NPC& eye) +{ + if (!peeper_eye_is_hung(eye)) + { + if (eye.aiCallPhase == AI_PHASE_PRE_UPDATE) eye.Kill(EntityRef()); + return; + } + + Entity& fatty = *eye.parent; + std::deque& cord = eye.vectorDeque1; + // The original writes the cord's ends even when it never laid one. Here an eye without a cord skips it. + if (cord.size() < CORD_STRIDE * 2) return; + Vector cordPos = eye.GetNullOffset("CordPos"); + cord[0] = vector_make(eye.posOffset.x + cordPos.x + eye.pos.x, eye.pos.y + 0); + cord[1] = eye.velocity; + cord[2] = vector_make(eye.posOffset.y + cordPos.y, 0); + Vector socket = peeper_socket_get(eye); + Vector anchor = vector_make(fatty.pos.x + socket.x, fatty.pos.y + 0); + cord[cord.size() - 3] = anchor; + cord[cord.size() - 2] = vector_scale(fatty.velocity, EYE_PARENT_DRAG); + cord[cord.size() - 1] = vector_make(socket.y, 0); + + Room& room = *g_game->room; + if (!room.isInitialized || g_game->frameCount - room.enterFrame < EYE_CORD_SETTLE_FRAMES) + { + for (int point = 1; point < EYE_CORD_POINTS; point++) + { + float along = (float)point / EYE_CORD_SPACING; + size_t i = point * CORD_STRIDE; + cord[i] = vector_add(vector_scale(vector_sub(anchor, cord[0]), along), cord[0]); + cord[i + 1] = {}; + cord[i + 2] = vector_make((socket.y - cord[2].x) * along + cord[2].x, 0); + } + eye.vectorDeque2 = eye.vectorDeque1; + } + else eye.UpdateCordChain(eye.aiCallPhase == AI_PHASE_INTERPOLATE); + + Vector toward = vector_sub(anchor, eye.pos); + float distance = vector_length(toward); + if (distance <= PEEPER_EYE_LEASH) return; + + eye.velocity.x += toward.x / distance * (distance - PEEPER_EYE_LEASH) * EYE_LEASH_PULL * EYE_LEASH_SHARE * eye.speedMultiplier; + eye.velocity.y += toward.y / distance * (distance - PEEPER_EYE_LEASH) * EYE_LEASH_PULL * EYE_LEASH_SHARE * eye.speedMultiplier; +} + +// An eye's first frame: invulnerable, hung 20 up with its cord laid from its socket and settled. +static void peeper_eye_init(Entity_NPC& eye) +{ + eye.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_HIDE_HP_BAR); + eye.aiCallFlags = AI_CALL_PRE_UPDATE | AI_CALL_INTERPOLATE | AI_CALL_COLLISION; + eye.isInvincible = true; + eye.entityGridCollisionClass = GRIDCOLL_WALLS; + eye.state = NPC_STATE_MOVE; + eye.posOffset.y = EYE_HEIGHT; + eye.sprite.Play("Idle2"); + eye.aiFloat = EYE_START_LOOK; + eye.v2.x = EYE_START_REACH; + eye.targetPosition = vector_make(eye.pos.x + 0, eye.pos.y + EYE_START_DROP); + eye.sprite.PlayOverlay("Cord"); + eye.sprite.GetLayer(1)->isVisible = false; + if (!eye.parent || !eye.parent->IsEnemy()) return; + + eye.sprite.isFlipX = eye.subtype == 0; + Vector cordPos = eye.GetNullOffset("CordPos"); + Vector start = vector_make(cordPos.x + eye.posOffset.x + eye.pos.x, eye.pos.y + 0); + float startHeight = eye.posOffset.y + cordPos.y; + Vector socket = peeper_socket_get(eye); + float rise = socket.y - startHeight; + Vector span = vector_make(eye.parent->pos.x + socket.x - start.x, eye.parent->pos.y + 0 - start.y); + for (int point = 0; point < EYE_CORD_POINTS; point++) + { + float along = (float)point / EYE_CORD_SPACING; + eye.vectorDeque1.push_back(vector_make(along * span.x + start.x, along * span.y + start.y)); + eye.vectorDeque1.push_back({}); + eye.vectorDeque1.push_back(vector_make(along * rise + startHeight, 0)); + } + eye.vectorDeque2 = eye.vectorDeque1; + for (int i = 0; i < EYE_CORD_SETTLE_STEPS; i++) eye.UpdateCordChain(false); +} + +// What a free eye catches in its gaze: a player, another kind of enemy, a pickup or bomb over 120 from the fatty. +static Entity* peeper_eye_gaze_find(Entity_NPC& eye, Vector look) +{ + for (Entity* entity : g_game->room->entityList.updateEL) + { + int type = entity->type; + bool isSeen = type == ENTITY_PLAYER || (type >= ENTITY_FIRST_ENEMY && type <= ENTITY_LAST_ENEMY && type != eye.type) || + type == ENTITY_PICKUP || type == ENTITY_BOMB; + if (!isSeen || entity->isDead) continue; + if (vector_length_squared(vector_sub(eye.parent->pos, entity->pos)) <= EYE_SEEK_CLEARANCE_SQUARED) continue; + if (vector_dot(look, vector_normalized(vector_sub(entity->pos, eye.pos))) > EYE_GAZE) return entity; + } + return nullptr; +} + +// The eye looks about: at its fatty's target in sight straight ahead, else (every third tick, its delay out) at +// whatever its gaze falls on. It forgets what it looked at when near it (now and then) or once it is on the fatty's +// wrong side, drifts toward what it looks at, turns its gaze there, and picks a new spot to look to now and then. +static void peeper_eye_look(Entity_NPC& eye) +{ + Entity_NPC& fatty = *eye.ParentNPC(); + Entity* target = fatty.GetPlayerTarget(); + Vector aim = fatty.CalcTargetPosition(0); + Vector look = vector_from_angle(eye.aiFloat); + if (eye.projectileDelay > 0) eye.projectileDelay -= npc_ticks_get(eye); + + bool isTargetSeen = vector_length_squared(vector_sub(eye.pos, aim)) < EYE_SIGHT_SQUARED && + vector_dot(look, vector_normalized(vector_sub(aim, eye.pos))) > EYE_GAZE; + if (isTargetSeen) eye.SetRef_bec(target); + else if (!eye.entityRef && eye.GetIntervalTicks(3, 0) != 0 && eye.projectileDelay < 1) + if (Entity* seen = peeper_eye_gaze_find(eye, look)) eye.SetRef_bec(seen); + + Vector lookPos = eye.entityRef ? eye.entityRef->pos : eye.targetPosition; + bool isNear = vector_length_squared(vector_sub(lookPos, eye.pos)) < EYE_FORGET_SQUARED; + bool isForgotten = isNear && Random() % EYE_FORGET_ODDS == 0 && eye.entityRef.get() != target; + float side = eye.subtype == 0 ? 1 : -1; + if (isForgotten || side * vector_normalized(vector_sub(lookPos, fatty.pos)).x > EYE_SIDE) + { + eye.SetRef_bec(nullptr); + eye.projectileCooldown = 0; + eye.projectileDelay = EYE_FORGET_DELAY; + } + + Entity* looked = eye.entityRef.get(); + eye.v2.x = vector_distance(lookPos, eye.pos); + if (looked) eye.v2.x *= EYE_LOOK_SHARE; + Vector goal = lookPos; + if (looked == target) eye.v2.x *= 0; + else goal = vector_add(lookPos, vector_resized(vector_sub(eye.pos, lookPos), EYE_STOP_SHORT)); + eye.AddVelocity(vector_resized(vector_sub(goal, eye.pos), EYE_PULL), false); + Vector turn = vector_resized(vector_sub(goal, eye.pos), PEEPER_EYE_TURN); + eye.aiFloat = vector_angle(vector_make(eye.speedMultiplier * turn.x + look.x, eye.speedMultiplier * turn.y + look.y)); +} + +// A new spot to look to: up to 110 degrees off its side, 200 out from the fatty, its check 80 out inside the room. +static void peeper_eye_gaze_pick(Entity_NPC& eye) +{ + Entity& fatty = *eye.parent; + for (int i = 0; i < EYE_GAZE_TRIES; i++) + { + float side = eye.subtype == 0 ? -1 : 1; + Vector direction = vector_scale(vector_from_angle(random_unit() * EYE_GAZE_SPREAD - EYE_GAZE_SPREAD / 2), side); + eye.targetPosition = vector_add(vector_scale(direction, EYE_GAZE_REACH), fatty.pos); + if (g_game->room->IsPositionInRoom(vector_add(vector_scale(direction, EYE_GAZE_CHECK), fatty.pos), 0)) break; + } +} + +// An eye: it hangs and looks about, its idle frame set by where it looks. +static void peeper_eye_update(Entity_NPC& eye) +{ + if (eye.state == NPC_STATE_INIT) return peeper_eye_init(eye); + if (eye.state != NPC_STATE_MOVE) return; + + eye.friction *= PEEPER_EYE_FRICTION; + if (!eye.parent || !eye.parent->IsEnemy()) return; + + peeper_eye_look(eye); + if (eye.projectileCooldown < 1) + { + peeper_eye_gaze_pick(eye); + eye.projectileCooldown = (int)(Random() % EYE_GAZE_FRAMES) + EYE_GAZE_MIN; + } + else eye.projectileCooldown -= npc_ticks_get(eye); + + int step = (int)std::floor(normalize_angle_degrees(eye.aiFloat) / (HALF_TURN_DEGREES / 4) + HALF); + int frame = (eye.subtype != 0 ? step + EYE_IDLE_FRAMES : EYE_IDLE_RIGHT - step) % EYE_IDLE_FRAMES; + char name[16]; + std::snprintf(name, sizeof(name), "Idle%d", frame); + eye.sprite.Play(name); +} + +// The fatty walks toward the eye with the shortest look (or chases on its own without eyes), groans, and farts out +// its ring once its wait is up. +static void peeper_fatty_walk(Entity_NPC& npc) +{ + npc_walk_animate_4dir(npc, {"WalkLeft", "WalkRight", "WalkVert", "WalkVert", PEEPER_WALK_THRESHOLD}); + if (npc.controllerID != -1) + { + npc.friction *= PEEPER_FRICTION; + Vector input = npc.GetControllerInput(0); + npc.velocity.x += input.x * PEEPER_SPEED * PEEPER_CONTROL_SCALE * npc.speedMultiplier; + npc.velocity.y += input.y * PEEPER_SPEED * PEEPER_CONTROL_SCALE * npc.speedMultiplier; + } + else + { + Entity* nearest = nullptr; + float best = PEEPER_EYE_FAR; + for (EntityPtr& eye : npc.entityDeque) + { + if (!eye || !Entity::is_enemy_type(eye->type)) continue; + + float reach = static_cast(eye.get())->v2.x; + if (reach >= best) continue; + best = reach; + nearest = eye.get(); + } + if (nearest) + { + float speed = best > 0 ? std::min(vector_distance(nearest->pos, npc.pos) / PEEPER_PATH_SPEED_SCALE, PEEPER_PATH_SPEED_MAX) + : PEEPER_PATH_SPEED_MAX; + npc.pathfinder.FindGridPath(nearest->pos, speed, PEEPER_PATH_MARKER, DIRECT_PATH_FAR); + } + else npc.pathfinder.update_chase_movement(); + } + if (Random() % PEEPER_GROAN_ODDS == 0) npc.PlaySound(SOUND_ANGRY_GURGLE, 1, PEEPER_GROAN_DELAY, false, 1); + + if (npc.projectileCooldown > 0 && (npc.projectileCooldown -= npc_ticks_get(npc)) > 0) return; + bool isAttacking = (npc.controllerID == -1 && Random() % PEEPER_ATTACK_ODDS == 0) || + npc.IsTargetInAttackRange(PEEPER_ATTACK_RANGE, 0, true); + if (!isAttacking) return; + + npc.state = NPC_STATE_ATTACK; + npc_walk_animate_4dir(npc, {"AttackLeft", "AttackRight", "AttackVert", "AttackVert", 0}); + npc.stateFrame = 0; +} + +// The fatty: its eyes dropped on its first frame, its walk and its fart. +static void peeper_fatty_update(Entity_NPC& npc) +{ + npc.UpdateChargeBar(PEEPER_WAIT_MIN, 0, (float)npc.projectileCooldown, true); + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.sprite.SetFrame("WalkVert", 0); + npc.projectileCooldown = npc.controllerID == -1 ? (int)(Random() % PEEPER_WAIT_RANGE) + PEEPER_WAIT_MIN : PEEPER_WAIT_MIN; + npc.entityDeque.resize(PEEPING_FATTY_EYES); + for (int i = 0; i < (int)PEEPING_FATTY_EYES; i++) + { + uint32_t seed = npc.dropRNG.Next(); + Vector position = vector_make((i == 0 ? -PEEPER_EYE_SPREAD : PEEPER_EYE_SPREAD) + npc.pos.x, npc.pos.y + PEEPER_EYE_SPREAD); + Entity* eye = g_game->Spawn({.position = position, + .spawner = &npc, + .subType = i, + .type = npc.type, + .variant = PEEPER_EYE, + .seed = seed}); + npc.entityDeque[i] = eye; + eye->parent = &npc; + eye->Update(); + } + return; + } + if (npc.state == NPC_STATE_MOVE) return peeper_fatty_walk(npc); + if (npc.state != NPC_STATE_ATTACK) return; + + if (npc.sprite.IsEventTriggered("Shoot")) + { + game_butter_bean_fart({.position = npc.pos, .source = &npc, .radius = PEEPER_FART_RADIUS}); + npc.FireProjectiles(npc.pos, vector_make(PEEPER_RING_SPEED, PEEPER_RING_SHOTS), PROJECTILES_RING, ProjectileParams()); + } + if (npc.sprite.IsFinished()) + { + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + npc.projectileCooldown = npc.controllerID == -1 ? (int)(Random() % PEEPER_WAIT_RANGE) + PEEPER_WAIT_MIN : PEEPER_WAIT_MIN; + } + npc.friction *= PEEPER_ATTACK_FRICTION; +} + +// 005562b0 The Peeping Fatty's AI and its eyes': it walks toward where its eyes look and farts out rings of shots. +// Its eyes hang on cords, gaze about and catch sight of things. They ignore it in collisions. +void npc_peeper_fatty_update(Entity_NPC& npc) +{ + bool isEye = npc.variant == PEEPER_EYE; + if (npc.aiCallPhase == AI_PHASE_PRE_UPDATE || npc.aiCallPhase == AI_PHASE_INTERPOLATE) + { + if (isEye) peeper_eye_cord_update(npc); + return; + } + if (npc.aiCallPhase == AI_PHASE_COLLISION) + { + if (isEye && npc.collisionEntity == npc.parent.get()) npc.collisionResult = 0; + return; + } + if (isEye) peeper_eye_update(npc); + else peeper_fatty_update(npc); +} diff --git a/src/npc_render_parts.cpp b/src/npc_render_parts.cpp index 969d48f..61ab722 100644 --- a/src/npc_render_parts.cpp +++ b/src/npc_render_parts.cpp @@ -2,10 +2,7 @@ #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; +// Evis' cord layer, the Scourge's chain links and the Chimera's body, as their renders know them. constexpr int EVIS_CORD_LAYER = 1; constexpr int SCOURGE_CHAIN_LINK = 10; constexpr int SCOURGE_LINK_SHOWN = NPC_STATE_JUMP; diff --git a/src/npc_rotten_gaper.cpp b/src/npc_rotten_gaper.cpp new file mode 100644 index 0000000..126ba5a --- /dev/null +++ b/src/npc_rotten_gaper.cpp @@ -0,0 +1,214 @@ +#include "npc_alt.h" +#include "active_items.h" +#include "entity_effect.h" +#include "entity_projectile.h" +#include "game.h" +#include "menu_manager.h" +#include "room.h" +#include "room_grid.h" +#include +#include + +// The rotten gaper's kinds (its subtype, one of five picked on its first frame when none is given), each walking its +// path at its own pace. The second paths straight from anywhere, the third keeps apart from its kin and drops +// maggots and worms, the fifth charges in a weave. +constexpr int ROTTEN_KINDS = 5; +constexpr RNG ROTTEN_KIND_RNG = {0, 1, 5, 16}; +constexpr std::array ROTTEN_PACES = {1, 1.2f, 1.5f, 0.8f, 0.9f, 1.9f}; +constexpr int ROTTEN_DIRECT = 2; +constexpr int ROTTEN_LONER = 3; +constexpr int ROTTEN_CHARGER = 5; +constexpr float ROTTEN_SPEED = 0.6f; +constexpr int ROTTEN_PATH = 900; +constexpr float ROTTEN_WALK_THRESHOLD = 0.1f; +constexpr float ROTTEN_FLEE_FRICTION = 0.8f; +constexpr int ROTTEN_GROAN_DELAY = 40; +constexpr uint32_t ROTTEN_GROAN_ODDS = 3; + +// The loner, farther than 80 from its target, flees a kin of another kind within 60 for 30 to 44 ticks. Past 60 ticks +// it drops a Small Maggot one time in eight while its group holds fewer than six, and it sheds a worm one time in 20 +// every 4 ticks. +constexpr float LONER_CROWD_RANGE = 80; +constexpr float LONER_CROWD_RADIUS = 60; +constexpr uint32_t LONER_FLEE_RANGE = 15; +constexpr int LONER_FLEE_MIN = 30; +constexpr int LONER_MAGGOT_FRAMES = 60; +constexpr uint32_t LONER_MAGGOT_ODDS = 8; +constexpr size_t LONER_MAGGOTS = 6; +constexpr uint32_t LONER_WORM_ODDS = 20; +constexpr float LONER_WORM_INTERVAL = 4; + +// The charger slows to three quarters within 80 of its target (full pace past 180), and with its target in sight +// heads for a spot 60 off it along its velocity turned up to 20 degrees either way. +constexpr float CHARGER_SLOW_RANGE = 80; +constexpr float CHARGER_SLOW_SPAN = 100; +constexpr float CHARGER_SLOW_SHARE = 0.25f; +constexpr float CHARGER_WEAVE = 20; +constexpr float CHARGER_AIM = 60; +constexpr float CHARGER_FRICTION = 0.9f; + +// Mother's rotten gapers rise up the room, groaning one time in ten. Killed by Mother, one bursts into four shots and +// lobs a head at a spot within 40 of its target, at a twentieth of the distance a tick (25 at most). +constexpr int MOTHER_GAPER_MOTHER = 0; +constexpr float MOTHER_GAPER_FRICTION = 0.75f; +constexpr uint32_t MOTHER_GAPER_GROAN_ODDS = 10; +constexpr int MOTHER_GAPER_SHOTS = 4; +constexpr float MOTHER_GAPER_SHOT_TRAJECTORY = 10; +constexpr float MOTHER_GAPER_SHOT_SPEED = 0.4f; +constexpr float MOTHER_GAPER_LOB_SPREAD = 40; +constexpr float MOTHER_GAPER_LOB_TURN = 3.14f * 2; +constexpr float MOTHER_GAPER_LOB_FALL = -0.06f; +constexpr float MOTHER_GAPER_LOB_PACE = 0.05f; +constexpr float MOTHER_GAPER_LOB_SPEED = 25; + +// The arc that lands the lob on its spot: its fall accelerates by 1.32, from a fall speed solved for its flight time +// under the shots' drag of 0.9 a tick. +constexpr float HEAD_LOB_FALL_ACCEL = 1.32f; +constexpr float HEAD_LOB_DRAG = 0.9f; +constexpr float HEAD_LOB_DRAG_SPAN = -9.491221f; +constexpr float HEAD_LOB_DRAG_FLOOR = 0.01f; +constexpr float HEAD_LOB_LANDING = -5; +constexpr float HEAD_LOB_GRAVITY = 14.200001f; + +// Its first frame: a gaper given no kind takes one, and it walks with its head on its first frame, in green blood. +static void rotten_gaper_init(Entity_NPC& npc) +{ + if (npc.subtype == 0 && npc.type == ENTITY_GAPER) + { + RNG rng = ROTTEN_KIND_RNG; + rng._seed = npc.initSeed; + npc.Morph(npc.type, npc.variant, (int)rng.RandomInt(ROTTEN_KINDS) + 1, -1); + } + npc.sprite.SetOverlayFrame("Head", 0); + npc.sprite.SetFrame("WalkVert", 0); + npc.state = NPC_STATE_MOVE; + npc.splatColor = COLOR_GREEN_SPLAT; +} + +// The loner: it picks a kin of another kind to flee while far from its target, drops maggots into its group and sheds +// worms. +static void rotten_loner_update(Entity_NPC& npc, const Vector& target) +{ + npc.i1 -= npc.i1 > 0 ? npc_ticks_get(npc) : 0; + if (npc.i1 < 1) npc.entityRef = nullptr; + if (!npc.entityRef && vector_distance(target, npc.pos) > LONER_CROWD_RANGE) + for (Entity* other : entity_query_radius(npc.pos, LONER_CROWD_RADIUS, QUERY_ENEMIES)) + { + bool isKin = other != &npc && other->type == npc.type && other->variant == npc.variant && other->subtype != npc.subtype; + bool isSameSide = (other->flags & FLAG_FRIENDLY) == (npc.flags & FLAG_FRIENDLY); + if (!isKin || !isSameSide || (other->flags & FLAG_NO_TARGET)) continue; + + npc.entityRef = other; + npc.i1 = (int)(Random() % LONER_FLEE_RANGE) + LONER_FLEE_MIN; + break; + } + + npc.i2 += npc_ticks_get(npc); + if (npc.i2 > LONER_MAGGOT_FRAMES && Random() % LONER_MAGGOT_ODDS == 0) + { + npc.i2 = 0; + if (Entity_NPC::QueryNPCsGroup((int)npc.index).size() < LONER_MAGGOTS) + { + Entity* maggot = g_game->Spawn({.position = npc.pos, .spawner = &npc, .type = ENTITY_SMALL_MAGGOT, .seed = Random()}); + maggot->ClearEntityFlags(FLAG_APPEAR); + maggot->Update(); + static_cast(maggot)->groupIdx = (int)npc.index; + } + } + if (Random() % LONER_WORM_ODDS == 0 && npc.GetIntervalTicks(LONER_WORM_INTERVAL, 0)) + g_game->Spawn({.position = npc.pos, .type = ENTITY_EFFECT, .variant = EFFECT_WORM, .seed = Random()})->Update(); +} + +// The charger: slower near its target, it weaves at it in sight and paths to it otherwise. +static void rotten_charger_update(Entity_NPC& npc, const Vector& target) +{ + float near = std::clamp((vector_distance(npc.pos, target) - CHARGER_SLOW_RANGE) / CHARGER_SLOW_SPAN, 0.0f, 1.0f); + npc.aiFloat *= near * CHARGER_SLOW_SHARE + (1 - CHARGER_SLOW_SHARE); + if (!room_check_line(npc.pos, target, 0, 0)) + return npc.pathfinder.FindGridPath(target, npc.aiFloat, -1, DIRECT_PATH_FAR); + + Vector weave = vector_rotated(npc.velocity, random_unit() * CHARGER_WEAVE * 2 - CHARGER_WEAVE); + weave = vector_resized(weave, vector_distance(target, npc.pos)); + Vector aim = vector_add(target, vector_resized(vector_sub(vector_add(npc.pos, weave), target), CHARGER_AIM)); + npc.velocity = vector_add(npc.velocity, vector_scale(vector_normalized(vector_sub(aim, npc.pos)), npc.aiFloat * npc.speedMultiplier)); + npc.friction *= CHARGER_FRICTION; +} + +// Its walk at its kind's pace: fleeing its target when feared or shrunk (the loner its kin), the charger weaving, +// the others along their paths. It groans one time in three while it sees its target, or on its player's pill button. +static void rotten_gaper_walk(Entity_NPC& npc) +{ + Vector target = npc.CalcTargetPosition(0); + if ((uint32_t)npc.subtype <= (uint32_t)ROTTEN_KINDS) npc.aiFloat *= ROTTEN_PACES[npc.subtype]; + if (npc.subtype == ROTTEN_LONER) rotten_loner_update(npc, target); + + bool isScared = npc.flags & (FLAG_FEAR | FLAG_SHRINK); + if (isScared || npc.entityRef) + { + Entity* threat = isScared ? npc.GetPlayerTarget() : npc.entityRef.get(); + npc.pathfinder.EvadeTarget(threat->pos, STATUS_OBEYED); + npc.friction *= ROTTEN_FLEE_FRICTION; + } + else if (npc.subtype == ROTTEN_CHARGER) rotten_charger_update(npc, target); + else npc.pathfinder.FindGridPath(target, npc.aiFloat, npc.subtype == ROTTEN_DIRECT ? -1 : ROTTEN_PATH, DIRECT_PATH_FAR); + + bool isGroaning = npc.controllerID == -1 ? npc.IsHostileTo(npc.GetPlayerTarget()) && npc.pathfinder.hasDirectPath && + Random() % ROTTEN_GROAN_ODDS == 0 + : input_is_action_triggered(ACTION_PILL_CARD, npc.controllerID, &npc); + if (isGroaning) npc.PlaySound(SOUND_ZOMBIE_WALKER_KID, 1, ROTTEN_GROAN_DELAY, false, 1); +} + +// One of Mother's, killed by Mother herself: four shots, and a head lobbed onto a spot near its target. +static void mother_gaper_burst(Entity_NPC& npc) +{ + ProjectileParams params; + params.velocityMulti = MOTHER_GAPER_SHOT_SPEED; + npc.FireBossProjectiles(MOTHER_GAPER_SHOTS, {}, MOTHER_GAPER_SHOT_TRAJECTORY, params); + + Vector spot = npc.GetPlayerTarget()->pos; + float angle = random_unit() * MOTHER_GAPER_LOB_TURN; + float reach = random_unit() * MOTHER_GAPER_LOB_SPREAD; + Vector toSpot = vector_sub(vector_add(spot, vector_make(std::cos(angle) * reach, std::sin(angle) * reach)), npc.pos); + float distance = vector_length(toSpot); + params.velocityMulti = 1; + params.fallingAccelModifier = MOTHER_GAPER_LOB_FALL; + params.variant = PROJECTILE_HEAD; + Vector velocity = distance > 0 ? vector_scale(toSpot, std::min(distance * MOTHER_GAPER_LOB_PACE, MOTHER_GAPER_LOB_SPEED) / distance) : toSpot; + Entity_Projectile* head = npc.fire_projectiles(npc.pos, velocity, PROJECTILES_SINGLE, params); + if (!head) return; + + head->fallingAccel = HEAD_LOB_FALL_ACCEL; + float time = distance / vector_length(head->velocity); + float drag = std::max((std::pow(HEAD_LOB_DRAG, time) - 1) * HEAD_LOB_DRAG_SPAN, HEAD_LOB_DRAG_FLOOR); + head->fallingSpeed = (HEAD_LOB_LANDING - head->height - (time - drag) * HEAD_LOB_GRAVITY) / drag; +} + +// 004da590 The rotten gaper's AI (Mother's too, her variant 20): it walks its path at its kind's pace with its head +// turning along, groaning in sight, and flees its target when feared or shrunk. Mother's rise up the room instead +// and burst when she kills them. +void npc_rotten_gaper_update(Entity_NPC& npc) +{ + bool isMothers = npc.type == ENTITY_MOTHER; + if (npc.state == NPC_STATE_INIT) rotten_gaper_init(npc); + else if (npc.state == NPC_STATE_MOVE || npc.state == NPC_STATE_ATTACK) + { + ANM2& sprite = npc.sprite; + npc.AnimWalkFrame("WalkHori", "WalkVert", ROTTEN_WALK_THRESHOLD); + if (!sprite.overlayAnimState.animData || !sprite.overlayAnimState.isPlaying) sprite.SetOverlayFrame("Head", 0); + if (sprite.animState.animData && sprite.animState.isPlaying && sprite.overlayAnimState.animData) + sprite.SetOverlayFrame((int)sprite.animState.animFrame); + npc.aiFloat = ROTTEN_SPEED; + + if (isMothers) + { + npc.friction *= MOTHER_GAPER_FRICTION; + npc.velocity.y -= npc.speedMultiplier; + if (Random() % MOTHER_GAPER_GROAN_ODDS == 0) npc.PlaySound(SOUND_ZOMBIE_WALKER_KID, 1, ROTTEN_GROAN_DELAY, false, 1); + } + else rotten_gaper_walk(npc); + } + if (!isMothers || !npc.isDead) return; + + for (DamageEvent& event : npc.killDamageEvents) + if (event.source.type == ENTITY_MOTHER && event.source.variant == MOTHER_GAPER_MOTHER) mother_gaper_burst(npc); +} diff --git a/src/npc_shady.cpp b/src/npc_shady.cpp new file mode 100644 index 0000000..73a4cba --- /dev/null +++ b/src/npc_shady.cpp @@ -0,0 +1,166 @@ +#include "npc_alt.h" +#include "boss_ai.h" +#include "entity_effect.h" +#include "grid_entity_trap_door.h" + +// Shady walks its grid path at 0.3 (fleeing when afraid or shrunk), growling in plain sight. Off its 120 frame +// cooldown it leaps at its target (one frame in 10 within 120, one in 40 anywhere) and slams down in four crackwaves. +// Off its 100 frame delay it spits a big dark shot one frame in 10. +constexpr float SHADY_SPEED = 0.3f; +constexpr int SHADY_PATH_MARKER = 900; +constexpr float SHADY_FRICTION = 0.8f; +constexpr float SHADY_WALK_THRESHOLD = 0.1f; +constexpr uint32_t SHADY_GROWL_ODDS = 3; +constexpr int SHADY_GROWL_DELAY = 60; +constexpr float LEAP_NEAR = 120; +constexpr uint32_t LEAP_NEAR_ODDS = 10; +constexpr uint32_t SHADY_LEAP_ODDS = 40; +constexpr float SHADY_LEAP_SPEED = 12; +constexpr int SHADY_LEAP_COOLDOWN = 120; +constexpr int LEAP_SOUND_DELAY = 10; +constexpr int SHADY_SLAM_SOUND_DELAY = 20; +constexpr int SHADY_SLAM_SHAKE = 14; +constexpr float SLAM_RIPPLE_AMPLITUDE = 0.035f; +constexpr float SLAM_RIPPLE_SPEED = 0.03f; +constexpr int SLAM_RIPPLE_FRAMES = 10; +constexpr int SLAM_WAVES = 4; +constexpr int SLAM_WAVE_SUBTYPE = 10; +constexpr float SHADY_LANDED_FRICTION = 0.9f; +constexpr float AIR_FRICTION = 0.6f; +constexpr uint32_t SHADY_SPIT_ODDS = 10; +constexpr float SHADY_SPIT_CONTROL_RANGE = 1000; +constexpr int SPIT_DELAY = 100; +constexpr float SHADY_SPIT_SPEED = 10; +constexpr float SPIT_BLOOD_SHARE = 0.4f; +constexpr float SHADY_SPIT_BLOOD_LIFT = -25; +constexpr float SHADY_SPIT_SCALE = 2; +constexpr float SHADY_SPIT_FALL_ACCEL = -0.08f; +constexpr ColorMod SHADY_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr ColorMod SHADY_SPIT_COLOR = {{-1, -1, -1, 1}, {0, 0, 0, 0}, {1, 0, 0}}; + +// Its leap toward a spot, at 12 (where its controller moves or points). +static void shady_leap(Entity_NPC& npc, Vector targetPos) +{ + npc.sprite.Play("Jump"); + npc.state = NPC_STATE_ATTACK; + npc.targetPosition = vector_scale(vector_normalized(vector_sub(targetPos, npc.pos)), SHADY_LEAP_SPEED); + if (npc.controllerID != -1) + { + npc.targetPosition = vector_scale(npc.GetControllerMovementInput(0), SHADY_LEAP_SPEED); + if (vector_is_zero(npc.targetPosition)) npc.targetPosition = vector_scale(npc.GetControllerInput(0), SHADY_LEAP_SPEED); + } + npc.projectileCooldown = SHADY_LEAP_COOLDOWN; +} + +// Walking its path, it counts down its leap and spit and starts one when it may. +static void shady_walk(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", SHADY_WALK_THRESHOLD); + if (npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && npc.controllerID == -1) + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= SHADY_FRICTION; + if (npc.pathfinder.evadeMovementCountdown > 0) npc.friction *= SHADY_FRICTION; + return; + } + + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), SHADY_SPEED, SHADY_PATH_MARKER, DIRECT_PATH_FAR); + if (npc.projectileCooldown > 0) npc.projectileCooldown -= npc_ticks_get(npc); + if (npc.projectileDelay > 0) npc.projectileDelay -= npc_ticks_get(npc); + Vector targetPos = npc.GetPlayerTarget()->pos; + if (npc.projectileCooldown < 1) + { + bool isLeaping = npc.controllerID == -1 + ? (vector_distance(npc.pos, targetPos) < LEAP_NEAR && Random() % LEAP_NEAR_ODDS == 0) || + Random() % SHADY_LEAP_ODDS == 0 + : npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT); + if (isLeaping) return shady_leap(npc, targetPos); + } + if (npc.projectileDelay >= 1) return; + + bool isSpitting = npc.controllerID == -1 ? Random() % SHADY_SPIT_ODDS == 0 + : npc.IsTargetInAttackRange(SHADY_SPIT_CONTROL_RANGE, 0, true); + if (!isSpitting) return; + + npc.AnimWalkFrame("AttackHori", "AttackVert", 0); + npc.state = NPC_STATE_ATTACK2; + npc.projectileDelay = SPIT_DELAY; +} + +// The leap: off on Jump, and on Shoot the slam: a quake, a ripple, a blood poof and four crackwaves. +static void shady_jump(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Jump")) + { + npc.PlaySound(SOUND_SCAMPER, 1, LEAP_SOUND_DELAY, false, 1); + npc.velocity.x += npc.speedMultiplier * npc.targetPosition.x; + npc.velocity.y += npc.speedMultiplier * npc.targetPosition.y; + npc.targetPosition = {}; + } + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_HELLBOSS_GROUNDPOUND, 1, SHADY_SLAM_SOUND_DELAY, 1); + game_shake_screen(SHADY_SLAM_SHAKE); + shockwave_make(npc.pos, SLAM_RIPPLE_AMPLITUDE, SLAM_RIPPLE_SPEED, SLAM_RIPPLE_FRAMES); + npc.MakeBloodPoof(npc.pos, COLOR_DEFAULT, 1); + for (int i = 0; i < SLAM_WAVES; i++) + { + auto* wave = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .subType = SLAM_WAVE_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACKWAVE, + .seed = Random()})); + wave->parent = &npc; + wave->rotation = i * RIGHT_ANGLE_DEGREES; + } + } + if (npc.sprite.WasEventTriggered("Shoot")) npc.friction *= AIR_FRICTION; + else npc.friction *= vector_is_zero(npc.targetPosition) ? SHADY_LANDED_FRICTION : AIR_FRICTION; +} + +// The spit: on Shoot a big dark shot at its target, with a gush of blood. +static void shady_spit(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc_sound_play(SOUND_HEARTOUT, 1, 2, 1); + Vector shot = vector_scale(vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)), SHADY_SPIT_SPEED); + blood_explosion_spawn(3, npc.pos, vector_make(0, SHADY_SPIT_BLOOD_LIFT), COLOR_DEFAULT, vector_scale(shot, SPIT_BLOOD_SHARE)); + ProjectileParams params; + params.scale = SHADY_SPIT_SCALE; + params.fallingAccelModifier = SHADY_SPIT_FALL_ACCEL; + params.bulletFlags = PROJECTILE_SIDE_WAVE; + params.color = SHADY_SPIT_COLOR; + npc.FireProjectiles(npc.pos, shot, PROJECTILES_SINGLE, params); + } + npc.friction *= AIR_FRICTION; +} + +// 005522d0 Shady's AI: it walks after its target, leaping and slamming the floor into crackwaves, and spits big dark +// shots. +void npc_shady_update(Entity_NPC& npc) +{ + switch (npc.state) + { + case NPC_STATE_INIT: + npc.state = NPC_STATE_MOVE; + npc.sprite.Play("WalkVert"); + npc.splatColor = SHADY_SPLAT_COLOR; + return; + case NPC_STATE_MOVE: + shady_walk(npc); + if (npc.pathfinder.hasDirectPath && Random() % SHADY_GROWL_ODDS == 0) + npc.PlaySound(SOUND_MONSTER_ROAR_1, 1, SHADY_GROWL_DELAY, false, 1); + return; + case NPC_STATE_ATTACK: + shady_jump(npc); + break; + case NPC_STATE_ATTACK2: + shady_spit(npc); + break; + default: + return; + } + if (!npc.sprite.IsPlaying()) npc.state = NPC_STATE_MOVE; +} diff --git a/src/npc_small_maggot.cpp b/src/npc_small_maggot.cpp new file mode 100644 index 0000000..b954047 --- /dev/null +++ b/src/npc_small_maggot.cpp @@ -0,0 +1,324 @@ +#include "npc_alt.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "room.h" +#include "room_grid.h" + +// The Small Maggot's cluster variant, which bursts into its subtype's count of maggots. +constexpr int MAGGOT_CLUSTER = 10; +constexpr float CLUSTER_SPREAD = 38; +constexpr RNG CLUSTER_RNG_SHIFTS = {0, 1, 11, 16}; +constexpr RNG FLING_RNG_SHIFTS = {0, 5, 9, 7}; + +// It crawls a while one way, turning a little each frame, and steers off blocked cells. +constexpr int CRAWL_FRAMES = 30; +constexpr int CRAWL_MIN = 10; +constexpr int CRAWL_SCARED_FRAMES = 5; +constexpr float CRAWL_TURN = 4; +constexpr float CRAWL_SPEED = 0.3f; +constexpr float CRAWL_SPEED_MIN = 0.15f; +constexpr float CRAWL_CHASE_SCALE = 2; +constexpr float CRAWL_LOOKAHEAD = 6; +constexpr int CRAWL_STEER_TRIES = 10; +constexpr float CRAWL_FRICTION = 0.8f; + +// It is alerted by a hit, or now and then by a visible player, a foe (when charmed) or an alerted maggot within 80. It +// calms down one frame in 25. +constexpr float ALERT_RADIUS = 80; +constexpr uint32_t ALERT_ODDS = 4; +constexpr uint32_t CALM_ODDS = 25; + +// In the air it falls back down, or in a crawlspace it drops, and lands with a splat. +constexpr float AIR_GRAVITY = 0.7f; +constexpr float AIR_HIGH = -50; +constexpr float AIR_HIT_SLOWDOWN = 0.1f; +constexpr float FALL_OUT_MARGIN = 30; +constexpr int FALL_SPLASH_SUBTYPE = 66; + +// A maggot flung charged (i1 2) flickers through these colors until it hits a wall. +constexpr ColorMod FLUNG_COLORS[] = { + {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0.5f, 0, 0}}, + {{0.8f, 0.6f, 0.6f, 1}, {0, 0, 0, 0}, {0, 0, 0}}, + {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}, +}; + +// How it was put in the air (i1): jumping onto a spot, thrown, or flung charged. +enum MaggotAir +{ + AIR_JUMPED, + AIR_THROWN, + AIR_FLUNG +}; + +// A cluster's first frame: it bursts into its subtype's count of maggots and is gone. +static void small_maggot_burst(Entity_NPC& npc) +{ + npc.ClearEntityFlags(FLAG_APPEAR); + RNG rng = CLUSTER_RNG_SHIFTS; + rng._seed = npc.initSeed; + for (int i = 0; i < npc.subtype; i++) + { + float offsetY = rng.RandomFloat() * CLUSTER_SPREAD - CLUSTER_SPREAD / 2; + float offsetX = rng.RandomFloat() * CLUSTER_SPREAD - CLUSTER_SPREAD / 2; + Vector position = vector_add(npc.pos, vector_make(offsetX, offsetY)); + Entity* maggot = g_game->Spawn({.position = position, .type = npc.type, .seed = Random()}); + maggot->ClearEntityFlags(FLAG_APPEAR); + maggot->Update(); + } + npc.Remove(); +} + +// A maggot's first frame: it starts crawling some random way. +static void small_maggot_init(Entity_NPC& npc) +{ + if (npc.spawnGridIndex >= 0) npc.ClearEntityFlags(FLAG_APPEAR); + npc.state = NPC_STATE_IDLE; + RNG rng = CLUSTER_RNG_SHIFTS; + rng._seed = Random(); + float angle = (float)rng._seed * RANDOM_UNIT_SCALE * RANDOM_HALF_TURN * 2; + npc.pathfinder.movementTarget = vector_make(std::cos(angle), std::sin(angle)); + npc.pathfinder.moveCountdown = (int)(rng.Next() % CRAWL_FRAMES) + CRAWL_MIN; +} + +// Whether something in reach alerts it: a visible player, a foe when charmed, or an alerted maggot. +static bool small_maggot_is_alerted_by(Entity_NPC& npc, Entity& other) +{ + if (npc.HasEntityFlags(FLAG_CHARM)) + { + if (other.IsVulnerableEnemy(nullptr) && !other.HasEntityFlags(FLAG_FRIENDLY)) return true; + } + else if (other.type == ENTITY_PLAYER && !other.ToPlayer()->IsInvisible()) return true; + return other.type == ENTITY_SMALL_MAGGOT && static_cast(other).i2 == 1; +} + +// Calming one frame in 25 once alerted, or alerted by a hit or (now and then) by what is about it. +static void small_maggot_alert_update(Entity_NPC& npc) +{ + if (npc.i2 != 0) + { + if (Random() % CALM_ODDS == 0) npc.i2 = 0; + return; + } + if (npc.health < npc.maxHitPoints) + { + npc.i2 = 1; + return; + } + if (!npc.IsFrame(4, 0) || Random() % ALERT_ODDS != 0) return; + + for (Entity* other : entity_query_radius(npc.pos, ALERT_RADIUS, QUERY_FAMILIARS | QUERY_ENEMIES | QUERY_PLAYERS)) + { + if (!small_maggot_is_alerted_by(npc, *other)) continue; + npc.i2 = 1; + break; + } +} + +// A new crawl: at its target when charmed, forced or alerted in a clear line (twice as fast), away when afraid, +// anywhere when confused, steered off blocked cells, with a fresh turn, speed and length. +static void small_maggot_crawl_pick(Entity_NPC& npc, Room& room) +{ + Vector& heading = npc.pathfinder.movementTarget; + Vector targetPos = npc.GetPlayerTarget()->pos; + float speedScale = 1; + bool isChasing = npc.HasEntityFlags(FLAG_CHARM) || npc.forcedTarget || + (npc.i2 == 1 && room_check_line(npc.pos, targetPos, LINE_MODE_CELL, 0)); + if (isChasing) + { + Vector toward = vector_sub(targetPos, npc.pos); + heading = vector_length(toward) <= 0 ? toward : vector_normalized(toward); + speedScale = CRAWL_CHASE_SCALE; + } + else if (npc.HasEntityFlags(FLAG_FEAR)) heading = vector_sub({}, vector_normalized(vector_sub(targetPos, npc.pos))); + else if (npc.HasEntityFlags(FLAG_CONFUSION)) heading = random_direction(); + if (vector_is_zero(heading)) heading = random_direction(); + + for (int i = 0; i < CRAWL_STEER_TRIES; i++) + { + int ahead = room.GetGridIndex(vector_add(npc.pos, vector_scale(heading, CRAWL_LOOKAHEAD))); + if (room.GetGridCollision(ahead) == 0) break; + heading = vector_rotated(heading, RIGHT_ANGLE_DEGREES - random_unit() * HALF_TURN_DEGREES); + } + npc.pathfinder.moveDirection.x = CRAWL_TURN / 2 - random_unit() * CRAWL_TURN; + npc.pathfinder.moveDirection.y = (random_unit() * CRAWL_SPEED + CRAWL_SPEED_MIN) * speedScale; + npc.pathfinder.moveCountdown = (int)(Random() % CRAWL_FRAMES) + CRAWL_MIN; +} + +// Crawling: it alerts and calms, picks a new crawl once the last runs out (sooner when scared or bumping a wall), and +// moves along its heading, turning. In a crawlspace it crawls only left or right. +static void small_maggot_crawl(Entity_NPC& npc, Room& room) +{ + if (room.roomType == ROOM_DUNGEON && g_game->frameCount - npc.spawnFrame < 2) npc.pathfinder.moveCountdown = 0; + int countdown = npc.isCollidesWithGrid ? 0 : npc.pathfinder.moveCountdown; + bool isScared = npc.HasEntityFlags(FLAG_CHARM | FLAG_CONFUSION | FLAG_FEAR) || npc.forcedTarget; + if (isScared && countdown > CRAWL_SCARED_FRAMES) countdown = CRAWL_SCARED_FRAMES; + npc.pathfinder.moveCountdown = countdown - npc_ticks_get(npc); + + small_maggot_alert_update(npc); + if (npc.pathfinder.moveCountdown < 1) small_maggot_crawl_pick(npc, room); + + Vector& heading = npc.pathfinder.movementTarget; + npc.friction *= CRAWL_FRICTION; + npc.velocity = vector_add(npc.velocity, vector_scale(heading, npc.pathfinder.moveDirection.y * npc.speedMultiplier)); + heading = vector_rotated(heading, npc.pathfinder.moveDirection.x); + if (room.roomType == ROOM_DUNGEON) heading = vector_make(heading.x > 0 ? 1 : -1, 0); +} + +// Back on the ground it crawls again with a splat, unless thrown onto a blocked cell, which kills it. +static void small_maggot_land(Entity_NPC& npc, bool isCrawlspace) +{ + npc.posOffset.y = 0; + npc.v1.x = 0; + npc.state = NPC_STATE_IDLE; + if (!isCrawlspace) + { + if (npc.entityGridCollisionClass == GRIDCOLL_BULLET && room_grid_collision_at(npc.pos) != 0) + return npc.Kill(EntityRef()); + npc.entityCollisionClass = ENTCOLL_ALL; + } + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.PlaySound(SOUND_SPLATTER, 1, 2, false, 1); + npc.sprite.Play("Land"); +} + +// In the air: a jumping maggot passes over everything, a thrown one hits players and their things. High up it only +// meets walls. A flung one flickers along at its speed (v1.y) until it hits a wall. A falling one drops by its rise +// (v1.x) and lands. In a crawlspace it falls until it touches ground. +static void small_maggot_air(Entity_NPC& npc, Room& room) +{ + if (npc.i1 == AIR_JUMPED) + { + npc.velocity = npc.targetPosition; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + } + else + { + npc.entityCollisionClass = npc.spawnerType == ENTITY_BEAST ? ENTCOLL_NONE : ENTCOLL_PLAYEROBJECTS; + npc.entityGridCollisionClass = GRIDCOLL_BULLET; + } + + if (room.roomType == ROOM_DUNGEON) + { + bool isBeastDungeon = room.IsBeastDungeon(); + if (isBeastDungeon) npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = isBeastDungeon ? GRIDCOLL_NONE : GRIDCOLL_WALLS; + npc.velocity.y += npc.speedMultiplier * AIR_GRAVITY; + if (npc.isCollidesWithGrid) small_maggot_land(npc, true); + return; + } + + if (npc.posOffset.y < AIR_HIGH) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + } + if (npc.i1 != AIR_FLUNG) + { + npc.v1.x += AIR_GRAVITY; + npc.posOffset.y += npc.v1.x; + if (npc.posOffset.y > -npc.v1.x) small_maggot_land(npc, false); + return; + } + + npc.sprite.GetLayer(0)->color = FLUNG_COLORS[(int)npc.updateTime % std::size(FLUNG_COLORS)]; + npc.entityGridCollisionClass = GRIDCOLL_NOPITS; + npc.velocity = vector_resized(npc.velocity, npc.v1.y); + if (!npc.isCollidesWithGrid) return; + + npc.i1 = AIR_THROWN; + npc.sprite.GetLayer(0)->color = COLOR_DEFAULT; + npc.velocity = vector_scale(npc.velocity, AIR_HIT_SLOWDOWN); + npc.ClearEntityFlags(FLAG_NO_KNOCKBACK); +} + +// 004d8d10 NpcHelper::gaper_l2_spawn_maggot: a small maggot flung charged from a position, a height up, at a velocity +// and rise, keeping that speed until it hits a wall. In a crawlspace the height and rise move it instead. +Entity_NPC* small_maggot_fling(const Vector& position, float height, const Vector& velocity, float rise) +{ + Room& room = *g_game->room; + auto* maggot = + static_cast(g_game->Spawn({.position = position, .type = ENTITY_SMALL_MAGGOT, .seed = Random()})); + maggot->ClearEntityFlags(FLAG_APPEAR); + maggot->v1 = vector_make(rise, vector_length(velocity)); + maggot->targetPosition = velocity; + maggot->velocity = velocity; + maggot->state = NPC_STATE_SPECIAL; + maggot->i1 = AIR_FLUNG; + maggot->AddEntityFlags(FLAG_NO_KNOCKBACK); + if (room.roomType == ROOM_DUNGEON) + { + maggot->pos.y += height; + maggot->velocity.y += rise; + } + else maggot->posOffset.y = height; + maggot->Update(); + + maggot->pathfinder.movementTarget = vector_normalized(maggot->velocity); + RNG crawl = FLING_RNG_SHIFTS; + crawl._seed = maggot->initSeed; + maggot->pathfinder.moveCountdown = (int)(crawl.Next() % CRAWL_FRAMES) + CRAWL_MIN; + return maggot; +} + +// Its crawl faces one of five ways, mirrored for the left. +static void small_maggot_animate(Entity_NPC& npc, Vector facing) +{ + if (npc.state == NPC_STATE_SPECIAL) + { + npc.sprite.isFlipX = npc.velocity.x < 0; + return npc_anim_loop(npc.sprite, "Bullet"); + } + const AnimationData* data = npc.sprite.animState.animData; + if (data && !data->isLooping && npc.sprite.animState.isPlaying) return; + + npc.sprite.isFlipX = facing.x < 0; + float angle = std::atan2(facing.y, std::abs(facing.x)) * RADIANS_TO_DEGREES; + switch ((int)std::floor((angle + HALF_TURN_DEGREES / 8) / (HALF_TURN_DEGREES / 4))) + { + case -2: + return npc_anim_loop(npc.sprite, "MoveUp"); + case -1: + return npc_anim_loop(npc.sprite, "MoveDiagonalUp"); + case 0: + return npc_anim_loop(npc.sprite, "MoveHori"); + case 1: + return npc_anim_loop(npc.sprite, "MoveDiagonalDown"); + default: + return npc_anim_loop(npc.sprite, "MoveDown"); + } +} + +// 004d77b0 The Small Maggot's AI: it crawls about, turning, and chases its target once alerted. Thrown, it lands +// with a splat. A cluster bursts into maggots. In the Home crawlspace a maggot dropping off the bottom splashes away. +void npc_small_maggot_update(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector startVelocity = npc.velocity; + Vector facing = startVelocity; + bool isCluster = npc.variant == MAGGOT_CLUSTER && !npc.isDead; + if (npc.state == NPC_STATE_INIT && isCluster) return small_maggot_burst(npc); + if (npc.state == NPC_STATE_INIT) + { + small_maggot_init(npc); + facing = npc.pathfinder.movementTarget; + } + else if (npc.state == NPC_STATE_IDLE) + { + small_maggot_crawl(npc, room); + facing = npc.pathfinder.movementTarget; + } + else if (npc.state == NPC_STATE_SPECIAL) small_maggot_air(npc, room); + small_maggot_animate(npc, facing); + + float bottom = room.bottomRightPos.y - FALL_OUT_MARGIN; + if (!room.IsBeastDungeon() || npc.velocity.y <= 0 || npc.pos.y <= bottom) return; + + Entity* splash = g_game->Spawn({.position = vector_make(npc.pos.x, bottom), + .subType = FALL_SPLASH_SUBTYPE, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF02, + .seed = Random()}); + splash->Update(); + npc.Remove(); +} diff --git a/src/npc_spikeball.cpp b/src/npc_spikeball.cpp new file mode 100644 index 0000000..9bf8cbf --- /dev/null +++ b/src/npc_spikeball.cpp @@ -0,0 +1,90 @@ +#include "boss_repentance.h" +#include "entity_effect.h" +#include "npc_basement.h" +#include "npc_gehenna.h" +#include "player_manager.h" + +// The Spikeball rolls back and forth along a row or column (its subtype's direction, kept to its cell's line), turning +// at blocks and at other Spikeballs ahead. It cannot be hurt and is gone once the room is won. +constexpr float SPIKEBALL_FRICTION = 0.7f; +constexpr float SPIKEBALL_SPEED = 3; +constexpr float SPIKEBALL_PROBE = 20; +constexpr float SPIKEBALL_SNAP = 0.9f; +constexpr int SPIKEBALL_CLEAR_DELAY = 80; +constexpr int SPIKEBALL_DIRECTIONS = 4; +constexpr int SPIKEBALL_POOF = 2; +constexpr uint64_t SPIKEBALL_FLAGS = FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET | FLAG_NO_BLOOD_SPLASH | FLAG_HIDE_HP_BAR; + +// Its collision call: turning back from a Spikeball ahead, and passing through the enemies of its side. +static void spikeball_collide(Entity_NPC& npc) +{ + Entity& other = *npc.collisionEntity; + if (other.type == ENTITY_SPIKEBALL) + { + Vector toward = vector_normalized(vector_sub(other.pos, npc.pos)); + if (vector_dot(toward, vector_from_direction(npc.i1)) > 0) + { + npc.i1 = (npc.i1 + 2) % SPIKEBALL_DIRECTIONS; + return; + } + } + bool isVersusPlayer = g_game->deathmatchManager.is_active() && other.type == ENTITY_PLAYER; + bool isNpc = other.type >= 10 && other.type <= 999; + if ((isVersusPlayer || isNpc) && other.HasEntityFlags(FLAG_FRIENDLY) == npc.HasEntityFlags(FLAG_FRIENDLY)) + npc.collisionResult = 0; +} + +// Rolling along its line, turning at a block 20 ahead, drawn to its cell's row or column across it. +static void spikeball_roll(Entity_NPC& npc, Room& room) +{ + Vector direction = vector_from_direction(npc.i1); + npc.velocity = vector_add(vector_scale(direction, SPIKEBALL_SPEED * npc.speedMultiplier), npc.velocity); + if (room_grid_collision_at(vector_add(vector_scale(direction, SPIKEBALL_PROBE), npc.pos)) > COLLISION_PIT) + npc.i1 = (npc.i1 + 2) % SPIKEBALL_DIRECTIONS; + npc.sprite.Play("Idle"); + + Vector line = room.GetGridPosition(npc.pathfinder.gridIndex); + float keep = 1 - timescale_factor(SPIKEBALL_SNAP, npc.speedMultiplier); + if (std::abs(direction.y) <= std::abs(direction.x)) npc.velocity.y += (line.y - npc.pos.y - npc.velocity.y) * keep; + else npc.velocity.x += (line.x - npc.pos.x - npc.velocity.x) * keep; +} + +// 004dc490 The Spikeball's AI: rolling along its line, gone with a poof once the enemies it came with are dead (80 +// frames into the room, plates aside), the plates are pressed or someone has the Flat File. A killed one stays gone. +void npc_spikeball_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_COLLISION) return spikeball_collide(npc); + + Game& game = *g_game; + Room& room = *game.room; + npc.friction *= SPIKEBALL_FRICTION; + if (npc.state == NPC_STATE_INIT) + { + npc.i1 = npc.subtype & 3; + npc.state = NPC_STATE_IDLE; + npc.isInvincible = true; + npc.aiCallFlags = AI_CALL_COLLISION; + npc.AddEntityFlags(SPIKEBALL_FLAGS); + npc.pathfinder.gridIndex = room.GetGridIndex(npc.pos); + npc.entityGridCollisionClass = GRIDCOLL_NOPITS; + npc.splatColor = COLOR_GREEN_SPLAT; + npc.i2 = npc.GetAliveEnemyCount() > 0 || room.isTriggerPressurePlates; + } + else if (npc.state == NPC_STATE_IDLE) spikeball_roll(npc, room); + + bool isAlone = npc.i2 != 0 && npc.GetAliveEnemyCount() < 1 && room.isInitialized && + game.frameCount - room.enterFrame > SPIKEBALL_CLEAR_DELAY && !room.isTriggerPressurePlates; + if (isAlone || room_plates_is_triggered() || game.playerManager.AnyoneHasTrinket(TRINKET_FLAT_FILE)) + npc.Kill(EntityRef()); + if (!npc.isDead) return; + + if (npc.spawnGridIndex >= 0) + game.GetRoomByIdx(game.currentRoomIdx)->restrictedGridIndexes.insert(npc.spawnGridIndex); + if (npc.variant == 0) + game.Spawn({.position = npc.pos, + .spawner = &npc, + .subType = SPIKEBALL_POOF, + .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, + .seed = Random()}); +} diff --git a/src/npc_stone_eye.cpp b/src/npc_stone_eye.cpp new file mode 100644 index 0000000..7140970 --- /dev/null +++ b/src/npc_stone_eye.cpp @@ -0,0 +1,138 @@ +#include "npc_caves.h" +#include "entity_effect.h" +#include "entity_laser.h" +#include "game.h" +#include "room.h" +#include + +// The Stone Eye turns 2 degrees a tick on its cell (or toward its controller's aim), keeping a thin laser out along +// its gaze one time in three it has none. Once the room's enemies are gone it stops on its first frame. +constexpr float STONE_EYE_TURN = 2; +constexpr float STONE_EYE_FRICTION = 0.8f; +constexpr float EYE_FRAME_OFFSET = 15; +constexpr float EYE_SQUASH = 0.5f; +constexpr uint32_t LASER_ODDS = 3; +constexpr float LASER_LIFT = -20; +constexpr int LASER_FRAMES_PER_STEP = 3; +constexpr float LASER_STEP_DEGREES = 30; +constexpr float LASER_REACH_X = 20; +constexpr float LASER_REACH_Y = 14; +constexpr int LASER_TIMEOUT = 2; +constexpr float STOP_VOLUME = 0.5f; + +// It blocks its cell for the pathfinder (950), and its wreck too once dead (900), unless it rides a minecart. +constexpr int STONE_EYE_PATH_LIMIT = 951; +constexpr int EYE_PATH_MARKER = 950; +constexpr int EYE_DEAD_PATH_MARKER = 900; +constexpr ColorMod EYE_SPLAT_COLOR = {{1, 1, 1, 1}, {1, 1, 1, 1}, {0, 0, 0}}; + +// Marks the cell at a position with a path level, unless it holds one of 951 or more. +static void stone_eye_cell_mark(const Vector& position, int level) +{ + Room& room = *g_game->room; + auto cell = (uint32_t)room.GetGridIndex(position); + if (cell < ROOM_GRID_CELLS && room.gridPaths[cell] < STONE_EYE_PATH_LIMIT) room.gridPaths[cell] = level; +} + +// Its gaze: 2 degrees further a tick, or toward its controller's aim in 2 degree steps, kept within a turn. +static float stone_eye_turn(Entity_NPC& npc) +{ + if (npc.controllerID == -1) npc.v1.x += STONE_EYE_TURN; + else + { + Vector aim = npc.GetControllerMovementInput(CONTROLLER_DEADZONE); + if (!vector_is_zero(aim)) + { + float half = std::floor(vector_angle(aim) * HALF); + npc.v1.x = angle_approach(npc.v1.x, half + half - RIGHT_ANGLE_DEGREES, STONE_EYE_TURN); + if (npc.v1.x < 0) npc.v1.x += FULL_TURN_DEGREES; + } + } + if (npc.v1.x > FULL_TURN_DEGREES) npc.v1.x -= FULL_TURN_DEGREES; + return npc.v1.x; +} + +// Its laser along its gaze, the gaze squashed into the stone's perspective, from the eye's spot on its frame. +static void stone_eye_laser_update(Entity_NPC& npc, float angle, int frame) +{ + float radians = angle * DEGREES_TO_RADIANS; + float gaze = (float)std::atan2((double)std::sin(radians), (double)(std::cos(radians) * EYE_SQUASH)) * RADIANS_TO_DEGREES; + if (auto* laser = static_cast(npc.child.get())) + { + laser->lastAngleDegrees = laser->angleDegrees; + laser->startAngleDegrees = gaze + RIGHT_ANGLE_DEGREES; + laser->angleDegrees = gaze + RIGHT_ANGLE_DEGREES; + laser->sprite.rotation = gaze + RIGHT_ANGLE_DEGREES - RIGHT_ANGLE_DEGREES; + return; + } + if (Random() % LASER_ODDS != 0) return; + + float spot = ((float)((frame + 1) / LASER_FRAMES_PER_STEP) * LASER_STEP_DEGREES + HALF_TURN_DEGREES) * DEGREES_TO_RADIANS - + PI_F / 2; + Vector origin = vector_make(std::cos(spot) * LASER_REACH_X + npc.pos.x, std::sin(spot) * LASER_REACH_Y + npc.pos.y); + Entity_Laser* laser = Entity_Laser::ShootAngle({.position = origin, + .posOffset = vector_make(0, LASER_LIFT), + .source = &npc, + .angleDegrees = gaze + RIGHT_ANGLE_DEGREES, + .timeout = LASER_TIMEOUT, + .variant = LASER_THIN_RED}); + npc.child = laser; + laser->entityGridCollisionClass = GRIDCOLL_NOPITS; + laser->isDisableInitSound = true; + laser->Update(); +} + +// 00505d00 The Stone Eye's AI: an invulnerable stone that turns on its cell sweeping a thin laser, until the room's +// enemies are gone. +void npc_stone_eye_update(Entity_NPC& npc) +{ + Entity* minecart = npc.minecart.get(); + if (npc.state == NPC_STATE_INIT) + { + npc.targetPosition = npc.pos; + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_HIDE_HP_BAR); + npc.isInvincible = true; + npc.v1.x = 0; + npc.state = NPC_STATE_MOVE; + npc_anim_restart(npc.sprite, "Rotate"); + if (!minecart) stone_eye_cell_mark(npc.pos, EYE_PATH_MARKER); + npc.splatColor = EYE_SPLAT_COLOR; + return; + } + if (npc.isDead && !minecart) stone_eye_cell_mark(npc.pos, EYE_DEAD_PATH_MARKER); + npc.friction *= STONE_EYE_FRICTION; + npc.velocity = vector_sub(npc.targetPosition, npc.pos); + + if (npc.state == NPC_STATE_IDLE) + { + if (npc.sprite.GetFrame() == 0 && npc.sprite.animState.animData) npc.sprite.animState.isPlaying = false; + return; + } + if (npc.state != NPC_STATE_MOVE) return; + + const AnimationData* data = npc.sprite.animState.animData; + if (!data || !data->isLooping) + { + npc_anim_restart(npc.sprite, "Rotate"); + if (npc.GetAliveEnemyCount() < 1) + { + npc.state = NPC_STATE_IDLE; + if (npc.sprite.animState.animData) npc.sprite.animState.isPlaying = false; + return; + } + } + + float angle = stone_eye_turn(npc); + int frame = -1; + if (npc.sprite.animState.animData) + { + float length = (float)npc.sprite.animState.animData->length; + npc.sprite.animState.SetFrameFloat((float)(int)(length * ((angle + EYE_FRAME_OFFSET) / FULL_TURN_DEGREES))); + frame = npc.sprite.GetFrame(); + } + stone_eye_laser_update(npc, angle, frame); + if (npc.GetAliveEnemyCount() >= 1) return; + + npc.state = NPC_STATE_IDLE; + npc.PlaySound(SOUND_HEARTIN, STOP_VOLUME, 2, false, 1); +} diff --git a/src/npc_tarboy.cpp b/src/npc_tarboy.cpp new file mode 100644 index 0000000..245d5ab --- /dev/null +++ b/src/npc_tarboy.cpp @@ -0,0 +1,415 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "entity_combat.h" +#include "entity_effect.h" +#include "game.h" +#include "menu_manager.h" +#include "room.h" +#include "room_grid.h" + +// The Tar Boy (subtype 0) blocks its cell, sinks into its black creep and rises from another puddle toward its target, +// spits goo at where its target heads, and sends its mouth (subtype 1) up out of a puddle there to bite. It leaves +// creep where it stands every eighth frame. +constexpr int TARBOY_MOUTH = 1; +constexpr int TARBOY_PATH_LIMIT = 951; +constexpr int TARBOY_PATH_MARKER = 900; +constexpr float TARBOY_FRICTION = 0.8f; +constexpr float TARBOY_CHARGE_BAR = 90; +constexpr int TARBOY_REST_RANGE = 40; +constexpr int TARBOY_REST_MIN = 20; +constexpr int TARBOY_SPIT_REST_MIN = 15; +constexpr int TARBOY_CONTROL_REST = 2; +constexpr uint32_t TARBOY_ATTACK_ODDS = 8; + +// It sinks toward its target (to a random spot one time in 16 when within 120) into the puddle nearest that, one at +// least 20 frames from drying, off the paths, over 120 from it. +constexpr float SINK_NEAR = 120; +constexpr uint32_t SINK_RANDOM_ODDS = 16; +constexpr float SINK_RANDOM_MARGIN = 20; +constexpr float SINK_FAR_SQUARED = 1e10f; +constexpr float PUDDLE_CENTERED_SQUARED = 100; +constexpr int PUDDLE_FRESH_FRAMES = 20; +constexpr int PUDDLE_PATH_LIMIT = 400; +constexpr float PUDDLE_CLEARANCE_SQUARED = 120; +constexpr float PUDDLE_NEAR_SQUARED = 676; +constexpr int SINK_CONTROL_FRAME = 6; + +// Its attacks: at where its target heads (a tenth of its speed per unit of distance), a bite out of a puddle there +// (four times in five, between 60 and 280 away) or a lob of six goo shots. +constexpr float LEAD_SCALE = 0.1f; +constexpr float BITE_NEAR = 60; +constexpr float BITE_FAR = 280; +constexpr uint32_t BITE_ODDS = 5; +constexpr int TARBOY_SPIT_SHOTS = 6; +constexpr float SPIT_TRAJECTORY = 10; +constexpr float TARBOY_SPIT_SCALE = 0.7f; +constexpr int TARBOY_SPIT_SOUND_DELAY = 15; +constexpr ColorMod TARBOY_SPIT_COLOR = {{1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, 1}, {0, 0, 0}}; +constexpr float BITE_DAMAGE = 8; +constexpr float BITE_RADIUS = 12; +constexpr float BITE_PLAYER_THRESHOLD = 50; +constexpr ColorMod TARBOY_SPLAT_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// A controlled one wades under its creep, hurting itself every 120 frames, and surfaces once still or after 90. +constexpr float WADE_SPEED = 2; +constexpr int WADE_HURT_FRAMES = 120; +constexpr int WADE_HURT_AFTER = 90; +constexpr float WADE_HURT = 10; +constexpr int WADE_HURT_COUNTDOWN = 30; +constexpr float WADE_GIB_SPREAD = 20; +constexpr float WADE_HURT_VOLUME = 0.5f; +constexpr float WADE_HURT_PITCH = 2; +constexpr float WADE_STILL_SQUARED = 1; +constexpr int WADE_SURFACE_FRAMES = 90; +constexpr float WADE_PUDDLE_REACH_SQUARED = 1600; + +// The creep it leaves: every eighth frame, lasting 30 frames, twice the size. +constexpr int CREEP_EVERY = 8; +constexpr int TARBOY_CREEP_FRAMES = 30; +constexpr float TARBOY_CREEP_SCALE = 2; + +// Whether an effect is one of its puddles: black creep, or a friendly one's player creep. +static bool tarboy_is_puddle(Entity_NPC& npc, Entity& entity) +{ + if (entity.type != ENTITY_EFFECT) return false; + return entity.variant == EFFECT_CREEP_BLACK || + (npc.HasEntityFlags(FLAG_FRIENDLY) && entity.variant == EFFECT_PLAYER_CREEP_BLACK); +} + +// 005441e0 NpcHelper::tarboy_is_creep_near: whether one of its puddles lies within 26 of a position. +static bool tarboy_is_creep_near(Entity_NPC& npc, const Vector& position) +{ + for (Entity* entity : g_game->room->entityList.updateEL) + if (tarboy_is_puddle(npc, *entity) && vector_length_squared(vector_sub(position, entity->pos)) < PUDDLE_NEAR_SQUARED) + return true; + return false; +} + +// The open cell centre of a puddle lying centred on it, if any. +static bool tarboy_puddle_cell_get(Room& room, Entity& puddle, Vector& center) +{ + int cell = room.GetGridIndex(puddle.pos); + if (cell < 0) return false; + center = room.GetGridPosition(cell); + return room.GetGridCollision(cell) == 0; +} + +// The puddle nearest a goal to rise from: fresh, centred on an open cell off the paths, over 120 from it. +static Vector tarboy_puddle_pick(Entity_NPC& npc, Vector goal) +{ + Room& room = *g_game->room; + Vector best{}; + float bestDistance = SINK_FAR_SQUARED; + for (Entity* entity : room.entityList.updateEL) + { + Vector center; + if (!tarboy_is_puddle(npc, *entity) || !tarboy_puddle_cell_get(room, *entity, center)) continue; + if (vector_length_squared(vector_sub(entity->pos, center)) >= PUDDLE_CENTERED_SQUARED) continue; + if (static_cast(entity)->timeout <= PUDDLE_FRESH_FRAMES) continue; + + int cell = room.GetGridIndex(center); + if (cell < (int)ROOM_GRID_CELLS && room.gridPaths[cell] >= PUDDLE_PATH_LIMIT) continue; + if (vector_length_squared(vector_sub(npc.pos, center)) <= PUDDLE_CLEARANCE_SQUARED) continue; + + float distance = vector_length_squared(vector_sub(goal, center)); + if (distance >= bestDistance) continue; + best = center; + bestDistance = distance; + } + return best; +} + +// The puddle nearest itself within 40, for a controlled one to surface in. +static Vector tarboy_puddle_nearest(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector best{}; + float bestDistance = WADE_PUDDLE_REACH_SQUARED; + for (Entity* entity : room.entityList.updateEL) + { + Vector center; + if (!tarboy_is_puddle(npc, *entity) || !tarboy_puddle_cell_get(room, *entity, center)) continue; + + float distance = vector_length_squared(vector_sub(npc.pos, center)); + if (distance >= bestDistance) continue; + best = center; + bestDistance = distance; + } + return best; +} + +// The sink: toward its target (or a random spot when near), into the puddle nearest that. A controlled one sinks +// where it stands once steered. +static void tarboy_sink(Entity_NPC& npc, Entity& target) +{ + if (npc.controllerID != -1 && vector_is_zero(npc.GetControllerInput(CONTROLLER_DEADZONE))) return; + + Vector goal{}; + if (vector_distance(target.pos, npc.pos) > SINK_NEAR) goal = npc.CalcTargetPosition(0); + else if ((Random() & (SINK_RANDOM_ODDS - 1)) == 0) goal = g_game->room->GetRandomPosition(SINK_RANDOM_MARGIN); + + if (npc.controllerID != -1) + { + npc.sprite.Play("Teleport"); + npc.sprite.SetFrame(SINK_CONTROL_FRAME); + npc.state = NPC_STATE_MOVE; + npc.v1 = npc.pos; + return; + } + if (vector_is_zero(goal)) return; + + Vector puddle = tarboy_puddle_pick(npc, goal); + if (vector_is_zero(puddle)) return; + + npc.sprite.Play("Teleport"); + npc.state = NPC_STATE_MOVE; + npc.v1 = puddle; +} + +// Its mouth, risen out of a puddle at a spot to bite, its own mouth replacing any before. +static void tarboy_mouth_spawn(Entity_NPC& npc, Vector spot) +{ + if (npc.child && npc.child->isExists) npc.child->Remove(); + uint32_t seed = npc.dropRNG.Next(); + auto* mouth = static_cast(g_game->Spawn( + {.position = spot, .spawner = &npc, .subType = TARBOY_MOUTH, .type = npc.type, .variant = npc.variant, .seed = seed})); + mouth->AddEntityFlags(FLAG_HIDE_HP_BAR | FLAG_NO_PLAYER_CONTROL | FLAG_NO_STATUS_EFFECTS); + mouth->ClearEntityFlags(FLAG_APPEAR); + mouth->parent = &npc; + mouth->entityCollisionClass = ENTCOLL_NONE; + mouth->splatColor = npc.splatColor; + npc.child = mouth; + mouth->state = NPC_STATE_IDLE; + mouth->sprite.SetFrame("Mouth", 0); +} + +// An attack at where its target heads (or its controller's aim): a bite out of a puddle there, or a lob of goo. +static void tarboy_attack(Entity_NPC& npc, Entity& target) +{ + float distance = vector_distance(npc.pos, target.pos); + Vector lead = vector_add(vector_scale(vector_scale(target.velocity, LEAD_SCALE), distance), target.pos); + bool isCreepNear = false; + bool isBiting = false; + if (npc.controllerID == -1) + { + isCreepNear = tarboy_is_creep_near(npc, lead); + isBiting = distance > BITE_NEAR && distance < BITE_FAR && Random() % BITE_ODDS != 0; + } + else + { + lead = npc.GetAimTargetPosition(); + isCreepNear = tarboy_is_creep_near(npc, lead); + isBiting = npc.IsControllerActionPressed(ACTION_BOMB); + } + if (isBiting && room_grid_collision_at(lead) == 0 && isCreepNear) + { + npc.sprite.Play("Attack2"); + npc.state = NPC_STATE_ATTACK2; + npc.sprite.isFlipX = lead.x < npc.pos.x; + return tarboy_mouth_spawn(npc, lead); + } + if (npc.controllerID != -1 && !npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT)) return; + + npc.sprite.Play("Attack"); + npc.state = NPC_STATE_ATTACK; + npc.sprite.isFlipX = lead.x < npc.pos.x; +} + +// Standing: one time in eight (or on its controller's buttons) it attacks, otherwise it sinks away. +static void tarboy_stand(Entity_NPC& npc, Entity& target) +{ + if (!npc.sprite.IsPlaying()) npc.sprite.Play("Idle"); + npc.SpawnControlTarget(0, -1); + if (npc.i1 != 0) return; + + bool isAttacking = npc.controllerID == -1 ? (Random() & (TARBOY_ATTACK_ODDS - 1)) == 0 + : npc.IsControllerActionPressed(CONTROLLER_ACTION_SHOOT) || + npc.IsControllerActionPressed(ACTION_BOMB); + if (isAttacking) tarboy_attack(npc, target); + else tarboy_sink(npc, target); +} + +// A controlled one under its creep: it wades, hurting itself after a while, and surfaces in a puddle (or where it is +// when on one) once still or worn out. +static void tarboy_wade(Entity_NPC& npc) +{ + npc.i2 += npc_ticks_get(npc); + if (npc.i2 > WADE_HURT_FRAMES) + { + npc.i2 = WADE_HURT_AFTER; + npc.TakeDamage(WADE_HURT, 0, EntityRef(), WADE_HURT_COUNTDOWN); + gibs_spawn({.color = npc.splatColor, .position = npc.pos, .spawner = &npc, .spread = WADE_GIB_SPREAD, .amount = 1, + .gibFlags = 1}); + npc.PlaySound(SOUND_MEATY_DEATHS, WADE_HURT_VOLUME, 2, false, WADE_HURT_PITCH); + } + npc.pathfinder.FindGridPath({}, WADE_SPEED, 0, DIRECT_PATH_FAR); + if (npc.velocity.x != 0) npc.sprite.isFlipX = npc.velocity.x > 0; + if (npc.sprite.IsPlaying()) return; + + bool isStill = vector_is_zero(npc.GetControllerInput(CONTROLLER_DEADZONE)) && + vector_length_squared(npc.velocity) < WADE_STILL_SQUARED; + if ((!isStill && npc.i2 < WADE_SURFACE_FRAMES) || room_grid_collision_at(npc.pos) != 0) return; + if (!tarboy_is_creep_near(npc, npc.pos)) + { + Vector puddle = tarboy_puddle_nearest(npc); + if (vector_is_zero(puddle)) return; + npc.pos = puddle; + } + npc.targetPosition = npc.pos; + npc.sprite.Play("TeleportEnd"); + npc.state = NPC_STATE_JUMP; + npc.i2 = 0; +} + +// Sinking: it leaves the room's floor on Shoot, marks the puddle it rises from, and rises there once under. Whether +// it is held to its spot this frame. +static bool tarboy_teleport(Entity_NPC& npc, Entity& target) +{ + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + } + if (npc.controllerID != -1) + { + if (npc.entityCollisionClass != ENTCOLL_NONE) return true; + tarboy_wade(npc); + return false; + } + + Room& room = *g_game->room; + int cell = room.GetGridIndex(npc.v1); + if (cell >= 0) room.SetGridPath(cell, TARBOY_PATH_MARKER); + if (npc.sprite.IsPlaying()) return true; + + npc.pos = npc.v1; + npc.targetPosition = npc.v1; + npc.sprite.Play("TeleportEnd"); + npc.state = NPC_STATE_JUMP; + npc.sprite.isFlipX = target.pos.x < npc.pos.x; + return true; +} + +// Back to standing, resting 20 to 59 frames (15 to 54 after an attack, 2 under control). +static void tarboy_rest(Entity_NPC& npc, int restMin) +{ + npc.state = NPC_STATE_IDLE; + npc.i1 = npc.controllerID == -1 ? (int)(Random() % TARBOY_REST_RANGE) + restMin : TARBOY_CONTROL_REST; +} + +// The spit: on Shoot six goo shots lobbed at where its target heads (or its controller's aim). +static void tarboy_spit(Entity_NPC& npc, Entity& target) +{ + npc.SpawnControlTarget(0, -1); + if (npc.sprite.IsEventTriggered("Shoot")) + { + float distance = vector_distance(npc.pos, target.pos); + Vector aim = vector_add(vector_scale(vector_scale(target.velocity, LEAD_SCALE), distance), target.pos); + if (npc.controllerID != -1) aim = npc.GetAimTargetPosition(); + npc.sprite.isFlipX = aim.x < npc.pos.x; + ProjectileParams params; + params.bulletFlags = PROJECTILE_GOO; + params.color = TARBOY_SPIT_COLOR; + params.scale = TARBOY_SPIT_SCALE; + npc.FireBossProjectiles(TARBOY_SPIT_SHOTS, aim, SPIT_TRAJECTORY, params); + npc.PlaySound(SOUND_MEATHEADSHOOT, 1, TARBOY_SPIT_SOUND_DELAY, false, 1); + } + if (!npc.sprite.IsPlaying()) tarboy_rest(npc, TARBOY_SPIT_REST_MIN); +} + +// The bite: its mouth keeps its frame and bites around it every other tick between Shoot and ShootEnd, and is gone +// once done. +static void tarboy_bite(Entity_NPC& npc) +{ + npc.SpawnControlTarget(0, -1); + Entity* mouth = npc.child.get(); + if (mouth && mouth->sprite.animState.animData) mouth->sprite.animState.SetFrameFloat((float)npc.sprite.GetFrame()); + if (npc.sprite.IsEventTriggered("Shoot")) npc.PlaySound(SOUND_WEIRD_WORM_SPIT, 1, 2, false, 1); + bool isBiting = npc.sprite.WasEventTriggered("Shoot") && !npc.sprite.WasEventTriggered("ShootEnd"); + if (isBiting && mouth && mouth->isExists && npc.GetIntervalTicks(2, 0) != 0) + damage_radius({.position = mouth->pos, + .source = &npc, + .damage = BITE_DAMAGE, + .playerDamageThreshold = BITE_PLAYER_THRESHOLD, + .radius = BITE_RADIUS}); + if (npc.sprite.IsPlaying()) return; + + if (mouth) mouth->Remove(); + tarboy_rest(npc, TARBOY_SPIT_REST_MIN); +} + +// Its creep where it stands, every eighth frame (not mid sink). +static void tarboy_creep_leave(Entity_NPC& npc) +{ + if (npc.HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused()) return; + if ((g_game->frameCount + (int)npc.index) % CREEP_EVERY != 0) return; + if (npc.controllerID == -1 && npc.state == NPC_STATE_MOVE) return; + + int variant = npc.HasEntityFlags(FLAG_FRIENDLY) ? EFFECT_PLAYER_CREEP_BLACK : EFFECT_CREEP_BLACK; + auto* creep = static_cast( + g_game->Spawn({.position = npc.targetPosition, .spawner = &npc, .type = ENTITY_EFFECT, .variant = variant, .seed = Random()})); + creep->timeout = TARBOY_CREEP_FRAMES; + creep->lifespan = TARBOY_CREEP_FRAMES; + creep->sprite.scale = vector_make(TARBOY_CREEP_SCALE, TARBOY_CREEP_SCALE); + creep->Update(); +} + +// 005442a0 The Tar Boy's AI and its mouth's: it sinks into its tar and rises elsewhere, spits goo and bites out of +// the puddles, leaving tar about. Its mouth dies with it. +void npc_tarboy_update(Entity_NPC& npc) +{ + if (npc.subtype == TARBOY_MOUTH) + { + npc.entityCollisionClass = ENTCOLL_NONE; + if (!npc.parent || !npc.parent->isExists) npc.Kill(EntityRef()); + return; + } + + Room& room = *g_game->room; + int cell = room.GetGridIndex(npc.pos); + if (cell >= 0 && cell < (int)ROOM_GRID_CELLS && room.gridPaths[cell] < TARBOY_PATH_LIMIT) + room.gridPaths[cell] = TARBOY_PATH_MARKER; + Entity& target = *npc.GetPlayerTarget(); + npc.UpdateChargeBar(TARBOY_CHARGE_BAR, 0, (float)npc.i2, true); + npc.friction *= TARBOY_FRICTION; + if (npc.state == NPC_STATE_INIT) + { + npc.splatColor = TARBOY_SPLAT_COLOR; + npc.state = NPC_STATE_IDLE; + npc.sprite.Play("Idle"); + npc.targetPosition = npc.pos; + npc.i1 = npc.controllerID == -1 ? (int)(Random() % TARBOY_REST_RANGE) + TARBOY_REST_MIN : TARBOY_CONTROL_REST; + return; + } + + bool isHeld = true; + switch (npc.state) + { + case NPC_STATE_IDLE: + tarboy_stand(npc, target); + break; + case NPC_STATE_MOVE: + isHeld = tarboy_teleport(npc, target); + break; + case NPC_STATE_JUMP: + if (npc.sprite.IsEventTriggered("Shoot")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.PlaySound(SOUND_MEAT_JUMPS, 1, 2, false, 1); + } + if (!npc.sprite.IsPlaying()) tarboy_rest(npc, TARBOY_REST_MIN); + break; + case NPC_STATE_ATTACK: + tarboy_spit(npc, target); + break; + case NPC_STATE_ATTACK2: + tarboy_bite(npc); + break; + } + if (isHeld) npc.velocity = vector_sub(npc.targetPosition, npc.pos); + + if (npc.i1 > 0) npc.i1 -= npc_ticks_get(npc); + tarboy_creep_leave(npc); +} diff --git a/src/npc_twitchy.cpp b/src/npc_twitchy.cpp new file mode 100644 index 0000000..36f3ae6 --- /dev/null +++ b/src/npc_twitchy.cpp @@ -0,0 +1,229 @@ +#include "npc_alt.h" +#include "entity_knife.h" +#include "room.h" +#include "room_grid.h" + +// It walks the grid path to its target (fleeing when afraid or shrunk), groaning now and then in plain sight, and +// twitches its head one frame in 70. +constexpr float TWITCHY_WALK_SPEED = 0.6f; +constexpr float TWITCHY_FLEE_FRICTION = 0.8f; +constexpr uint32_t TWITCHY_GROAN_ODDS = 3; +constexpr float GROAN_VOLUME = 0.8f; +constexpr int TWITCHY_GROAN_DELAY = 120; +constexpr uint32_t TWITCH_ODDS = 70; +constexpr float TWITCHY_WALK_THRESHOLD = 0.1f; + +// Off cooldown it leaps at its target one frame in 30, within 260 or one time in 10, 1 to 3 hops in a row. Each lands +// on a free cell ahead of where the target is heading, 40 past it and at most 200 away. +constexpr uint32_t TWITCHY_LEAP_ODDS = 30; +constexpr float LEAP_RANGE = 260; +constexpr uint32_t LEAP_FAR_ODDS = 10; +constexpr uint32_t LEAP_HOPS = 3; +constexpr float LEAP_LEAD = 0.1f; +constexpr float LEAP_OVERSHOOT = 40; +constexpr float LEAP_MAX = 200; +constexpr float LEAP_FREE_SEARCH = 64; +constexpr float LEAP_ACCEL = 0.03f; +constexpr float GROUND_FRICTION = 0.6f; +constexpr int HOP_AGAIN_FRAME = 2; +constexpr int TWITCHY_LEAP_COOLDOWN = 5; + +// It dodges the nearest shot within 40 of hitting it in 4 frames, a bomb counting four times as close, hopping 60 to +// 160 aside at up to 20 degrees off square, onto a free cell away from players. +constexpr float DODGE_LOOK_RADIUS = 200; +constexpr float DODGE_LOOKAHEAD = 4; +constexpr float DODGE_FAR = 1e8f; +constexpr float DODGE_BOMB_SCALE = 0.25f; +constexpr float DODGE_RANGE_SQUARED = 1600; +constexpr int DODGE_TRIES = 10; +constexpr float DODGE_SPREAD = 40; +constexpr float DODGE_REACH = 100; +constexpr float DODGE_MIN = 60; +constexpr float DODGE_PLAYER_CLEARANCE = 60; +constexpr int DODGE_FRAME = 5; +constexpr int DODGE_COOLDOWN = 2; + +// It drips a splat one frame in six. +constexpr uint32_t TWITCHY_DRIP_ODDS = 6; +constexpr float TWITCHY_DRIP_SIZE = 0.5f; +constexpr float TWITCHY_DRIP_MIN = 0.2f; + +// 004db3c0 NpcHelper::twitchy_jump_target: ahead of its target's path by a tenth of its velocity per unit of +// distance, 40 past, at most 200 away, on a free cell. +static Vector twitchy_jump_target(Entity_NPC& npc) +{ + Room& room = *g_game->room; + Vector target = npc.CalcTargetPosition(0); + Entity* player = npc.GetPlayerTarget(); + float distance = vector_distance(npc.pos, player->pos); + target = vector_add(target, vector_scale(vector_scale(player->velocity, LEAP_LEAD), distance)); + target = vector_add(target, vector_scale(vector_normalized(vector_sub(target, npc.pos)), LEAP_OVERSHOOT)); + target = room.GetClampedPositionImpl(target, 0, 0, 0, 0); + if (vector_distance(npc.pos, target) > LEAP_MAX) + target = vector_add(npc.pos, vector_scale(vector_normalized(vector_sub(target, npc.pos)), LEAP_MAX)); + if ((int)room.GetGridCollision(room.GetGridIndex(target)) > 0) + target = room_free_tile_position_find(target, LEAP_FREE_SEARCH); + return target; +} + +// Starts a leap at a spot: the head hides and it passes over the floor's things. +static void twitchy_leap(Entity_NPC& npc, Vector spot) +{ + npc.sprite.RemoveOverlay(); + npc.state = NPC_STATE_JUMP; + npc.targetPosition = spot; + npc.v1.x = 0; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; +} + +// Walking: it paths or flees, groans, twitches, and now and then leaps. Whether it walks on. +static bool twitchy_walk(Entity_NPC& npc) +{ + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK)) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), TWITCHY_WALK_SPEED, 0, DIRECT_PATH_FAR); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= TWITCHY_FLEE_FRICTION; + } + if (npc.pathfinder.hasDirectPath && Random() % TWITCHY_GROAN_ODDS == 0) + npc_sound_play(SOUND_ANGRY_GURGLE, GROAN_VOLUME, TWITCHY_GROAN_DELAY, 1); + if (Random() % TWITCH_ODDS == 0 && npc.sprite.IsOverlayPlaying("Head")) + npc.sprite.PlayOverlay(Random() & 1 ? "HeadTwitch" : "HeadTwitch2"); + + int cooldown = npc.projectileCooldown; + if (cooldown > 0) npc.projectileCooldown = cooldown = cooldown - npc_ticks_get(npc); + if (npc.i2 > 0) npc.i2 -= npc_ticks_get(npc); + if (cooldown >= 1 || Random() % TWITCHY_LEAP_ODDS != 0 || npc.HasEntityFlags(FLAG_FEAR | FLAG_CONFUSION | FLAG_SHRINK)) + return true; + + Vector spot = twitchy_jump_target(npc); + if (vector_distance(npc.pos, spot) >= LEAP_RANGE && Random() % LEAP_FAR_ODDS != 0) return true; + + twitchy_leap(npc, spot); + npc.sprite.Play("Jump"); + npc.i1 = (int)(Random() % LEAP_HOPS) + 1; + return false; +} + +// In a leap it closes on its spot from its Jump event, faster each frame, and slides to a stop on the ground. Each +// landing thuds, and while hops remain it leaps on. Whether it walks again. +static bool twitchy_jump(Entity_NPC& npc) +{ + if (!vector_is_zero(npc.targetPosition)) + { + if (npc.sprite.WasEventTriggered("Jump")) + { + npc.v1.x += npc.speedMultiplier * LEAP_ACCEL; + Vector step = vector_add(npc.pos, vector_scale(vector_sub(npc.targetPosition, npc.pos), npc.v1.x)); + Vector moved = vector_sub(step, npc.pos); + npc.velocity = vector_make(moved.x / npc.friction, moved.y / npc.friction); + if (npc.v1.x >= 1) npc.targetPosition = {}; + } + else npc.friction *= GROUND_FRICTION; + } + + if (npc.sprite.IsEventTriggered("Land")) + { + npc_sound_play(SOUND_MEAT_IMPACTS, 1, 2, 1); + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + if (--npc.i1 > 0) + { + npc_anim_restart(npc.sprite, "Jump"); + npc.sprite.SetFrame(HOP_AGAIN_FRAME); + npc.targetPosition = twitchy_jump_target(npc); + npc.v1.x = 0; + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + } + } + if (npc.sprite.IsPlaying()) return false; + + npc.state = NPC_STATE_MOVE; + npc.projectileCooldown = TWITCHY_LEAP_COOLDOWN; + return true; +} + +// The nearest threat: a tear, bomb or knife whose spot 4 frames on comes closest, a bomb counting four times as close +// (and shrinking the bar for every later one too). None within 40. +static Entity* twitchy_threat_find(Entity_NPC& npc) +{ + Entity* threat = nullptr; + float best = DODGE_FAR; + for (Entity* entity : entity_query_radius(npc.pos, DODGE_LOOK_RADIUS, QUERY_TEARS | QUERY_ENEMIES)) + { + if (entity->type != ENTITY_TEAR && entity->type != ENTITY_KNIFE && entity->type != ENTITY_BOMB) continue; + + Vector motion = entity->velocity; + if (entity->type == ENTITY_KNIFE) + { + auto* knife = static_cast(entity); + motion = vector_scale(vector_from_angle(knife->rotation), knife->knifeVelocity); + } + float distance = vector_length_squared(vector_sub(npc.pos, vector_add(entity->pos, vector_scale(motion, DODGE_LOOKAHEAD)))); + if (entity->type == ENTITY_BOMB) best *= DODGE_BOMB_SCALE; + if (best <= distance) continue; + + best = distance; + threat = entity; + } + return best < DODGE_RANGE_SQUARED ? threat : nullptr; +} + +// Off its dodge cooldown (i2) a walking Twitchy hops aside from the nearest threat. +static void twitchy_dodge(Entity_NPC& npc) +{ + Entity* threat = twitchy_threat_find(npc); + if (!threat) return; + + Room& room = *g_game->room; + Vector side = vector_normalized(vector_rotated(vector_sub(threat->pos, npc.pos), RIGHT_ANGLE_DEGREES)); + Vector spot{}; + for (int i = 0; i < DODGE_TRIES; i++) + { + Vector away = Random() & 1 ? vector_sub({}, side) : side; + away = vector_rotated(away, random_unit() * DODGE_SPREAD - DODGE_SPREAD / 2); + Vector candidate = vector_add(npc.pos, vector_scale(away, random_unit() * DODGE_REACH + DODGE_MIN)); + if (room.GetGridCollision(room.GetGridIndex(candidate)) != 0) continue; + if (npc.IsPlayerInRadius(candidate, DODGE_PLAYER_CLEARANCE)) continue; + + spot = candidate; + break; + } + if (vector_is_zero(spot)) return; + + twitchy_leap(npc, spot); + npc_anim_loop(npc.sprite, "Jump"); + npc.sprite.SetFrame(DODGE_FRAME); + npc.i1 = 1; + npc.i2 = DODGE_COOLDOWN; +} + +// The walk, with its head kept on the body's frame. +static void twitchy_walk_animate(Entity_NPC& npc) +{ + npc.AnimWalkFrame("WalkHori", "WalkVert", TWITCHY_WALK_THRESHOLD); + if (!npc.sprite.IsOverlayPlaying()) npc.sprite.PlayOverlay("Head"); + if (npc.sprite.IsOverlayPlaying("Head")) npc.sprite.SetOverlayFrame(npc.sprite.GetFrame()); +} + +// 004db6a0 Twitchy's AI: it walks at its target, twitching, and leaps at it in short hops. It hops aside from tears, +// bombs and knives about to hit it, and drips green. +void npc_twitchy_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_MOVE; + npc.sprite.SetFrame("WalkVert", 0); + npc.sprite.SetOverlayFrame("Head", 0); + npc.splatColor = COLOR_GREEN_SPLAT; + npc.projectileCooldown = 0; + npc.stateFrame = 0; + npc.v1.x = 0; + npc.i1 = 0; + } + else if (npc.state == NPC_STATE_MOVE && twitchy_walk(npc)) twitchy_walk_animate(npc); + else if (npc.state == NPC_STATE_JUMP && twitchy_jump(npc)) twitchy_walk_animate(npc); + + if (npc.state == NPC_STATE_MOVE && npc.i2 <= 0) twitchy_dodge(npc); + if (Random() % TWITCHY_DRIP_ODDS == 0) npc.MakeSplat(random_unit() * TWITCHY_DRIP_SIZE + TWITCHY_DRIP_MIN); +} diff --git a/src/npc_ultra_coin.cpp b/src/npc_ultra_coin.cpp new file mode 100644 index 0000000..578ea4e --- /dev/null +++ b/src/npc_ultra_coin.cpp @@ -0,0 +1,338 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_effect.h" +#include "entity_effect_combat.h" +#include "entity_pickup.h" +#include "game.h" +#include "manager.h" +#include "persistent_game_data.h" +#include +#include + +// Ultra Greed's coins by variant: the spinner bouncing about until it wears out, the key flying to open a door, the +// bomb pulsing until it blows up, and the heart flying to heal Ultra Greed. Their fuses run longer the more health +// Ultra Greed has left (half to whole), shorter once Everything Is Terrible 2 is unlocked or in a daily or debug run, +// where they are also 15 percent tougher. +constexpr std::array COIN_APPEARS = {"AppearNeutral", "AppearKey", "AppearBomb", "AppearHeart"}; +constexpr std::array COIN_SPINS = {"SpinningNeutral", "SpinningKey", "SpinningBomb", "SpinningHeart"}; +constexpr float COIN_OFFSET_X = 5; +constexpr float COIN_OFFSET_Y = -3; +constexpr float COIN_TOUGH_SCALE = 1.15f; +constexpr float COIN_FUSE_SHARE = 0.5f; +constexpr float COIN_TOUGH_FUSE = 0.9f; +constexpr float COIN_FRICTION = 0.8f; +constexpr float COIN_MOVE_FRICTION = 0.1f; +constexpr ColorMod COIN_SPLAT_COLOR = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The spinner wears out over 330 frames, spinning faster and drifting in a slow circle (its way by its index) and a +// random way every 120 frames, kicked off walls. +constexpr float SPINNER_FRICTION = 0.9f; +constexpr float SPINNER_WEAR_FRAMES = 330; +constexpr float SPINNER_PLAYBACK_MIN = 2; +constexpr int SPINNER_PHASE_SPREAD = 0x231d; +constexpr float SPINNER_CIRCLE_FRAMES = 240; +constexpr float SPINNER_CIRCLE_PUSH = 0.12f; +constexpr int SPINNER_TURN_FRAMES = 120; +constexpr float SPINNER_DRIFT = 0.1f; +constexpr float SPINNER_WALL_KICK = 9; + +// The key and heart change after 225 and 150 frames, flying at 2 to their door or to Ultra Greed. The bomb starts +// pulsing after 60 and blows up once its pulse ends. +constexpr float KEY_FUSE = 225; +constexpr float HEART_FUSE = 150; +constexpr float COIN_BOMB_FUSE = 60; +constexpr float COIN_CHANGE_FRAME = 7; +constexpr float COIN_CHANGE_VOLUME = 0.7f; +constexpr float COIN_FLIGHT_SPEED = 2; +constexpr int HEART_HEAL = 3; +constexpr float HEART_HEAL_PITCH = 0.9f; +constexpr int DOOR_OPENING = NPC_STATE_SUMMON; +constexpr float BOMB_DAMAGE = 40; +constexpr float BOMB_RADIUS_SCALE = 1.8f; +constexpr float BOMB_PENNY_SPEED = 2; + +// Broken it crumbles in a shower of gold. +constexpr int COIN_GOLD_PARTICLES = 6; +constexpr float BOMB_PARTICLE_SPEED = 10; +constexpr float CRUMBLE_PARTICLE_SPEED = 5; +constexpr float CRUMBLE_PITCH = 1.2f; +constexpr float CRUMBLE_PITCH_RANGE = 0.3f; +constexpr int CRUMBLE_SOUND_DELAY = 30; + +// Ultra Greed's heal (UltraGreed_Heal): an eighth of a percent of its health per point, its heal count capped at 25, +// and a green flash. +constexpr int GREED_HEAL_CAP = 25; +constexpr float GREED_HEAL_SHARE = 0.00125f; +constexpr float GREED_HEAL_FLASH_POINTS = 3; +constexpr int GREED_HEAL_FLASH_FRAMES = 4; +constexpr int GREED_HEAL_FLASH_MAX = 15; +constexpr float GREED_HEAL_GREEN = 0.84f; + +// Whether Ultra Greed's coins are tougher: Everything Is Terrible 2 is unlocked, or a daily or debug run is on. +static bool ultra_coin_is_tough() +{ + if (g_manager->persistentGameData.achievements[ACHIEVEMENT_EVERYTHING_IS_TERRIBLE_2]) return true; + if (g_manager->state != MANAGER_STATE_GAME || !g_game) return false; + return g_game->dailyChallenge._id != 0 || g_game->isDebug; +} + +// 0059e2a0 NpcHelper::UltraGreed_Heal: Ultra Greed heals a share of its health and flashes green. +void ultra_greed_heal(Entity_NPC& greed, int amount) +{ + greed.i2 = std::min(greed.i2 + amount, GREED_HEAL_CAP); + greed.health = std::min(greed.maxHitPoints * GREED_HEAL_SHARE * (float)amount + greed.health, greed.maxHitPoints); + float flash = std::min((float)amount / GREED_HEAL_FLASH_POINTS, 1.0f); + ColorMod color = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0, flash * GREED_HEAL_GREEN, flash * 0}}; + greed.SetColor(color, std::min(amount * GREED_HEAL_FLASH_FRAMES, GREED_HEAL_FLASH_MAX), COLOR_PRIORITY_DEFAULT, true, true); +} + +// How long its fuse is: half to whole, by the share of health Ultra Greed has left, a tenth shorter when tough. +static float ultra_coin_fuse_share() +{ + float health = 0; + float maxHealth = 0; + for (Entity* greed : entity_query(ENTITY_ULTRA_GREED, -1)) + { + if (greed->maxHitPoints <= 0 || greed->isDead) continue; + health += greed->health; + maxHealth += greed->maxHitPoints; + } + if (maxHealth <= 0) return 1; + + float share = std::clamp(health / maxHealth, 0.0f, 1.0f) * COIN_FUSE_SHARE + COIN_FUSE_SHARE; + return ultra_coin_is_tough() ? share * COIN_TOUGH_FUSE : share; +} + +// The spinner wears out as it spins, circling and drifting, kicked off walls. +static void ultra_coin_spin(Entity_NPC& npc) +{ + npc.friction *= SPINNER_FRICTION; + float friction = npc.friction; + npc.health -= npc.maxHitPoints * npc.speedMultiplier / SPINNER_WEAR_FRAMES; + if (npc.health < 0) npc.isDead = true; + float playback = std::clamp(npc.health / npc.maxHitPoints, 0.0f, 1.0f); + playback = playback + playback + SPINNER_PLAYBACK_MIN; + npc.sprite.playbackSpeed = playback; + npc.stateFrame += (int)playback; + + float phase = (float)((int)npc.index * SPINNER_PHASE_SPREAD + npc.stateFrame) / SPINNER_CIRCLE_FRAMES; + if ((npc.index & 1) == 0) phase *= -1; + float angle = phase * TAU; + if (friction != 0) + { + npc.velocity.y += npc.speedMultiplier * std::sin(angle) * SPINNER_CIRCLE_PUSH * playback / friction; + npc.velocity.x += npc.speedMultiplier * (std::cos(angle) * SPINNER_CIRCLE_PUSH) * playback / friction; + } + if (npc.IsFrame(SPINNER_TURN_FRAMES, npc.index)) npc.v1 = random_direction(); + if (npc.friction != 0) + { + npc.velocity.y += npc.speedMultiplier * npc.v1.y * SPINNER_DRIFT * playback / npc.friction; + npc.velocity.x += npc.speedMultiplier * npc.v1.x * SPINNER_DRIFT * playback / npc.friction; + } + if (!npc.isCollidesWithGrid) return; + + Vector kick = vector_scale(npc.gridCollisionNormal, -SPINNER_WALL_KICK); + float strength = random_unit(); + if (npc.friction == 0) return; + npc.velocity.y += npc.speedMultiplier * kick.y * strength / npc.friction; + npc.velocity.x += npc.speedMultiplier * kick.x * strength / npc.friction; +} + +// The key or heart changing to fly off, once its fuse is out and its spin turns past frame 7. +static bool ultra_coin_is_turning(Entity_NPC& npc, std::string_view spin) +{ + float frame = npc.sprite.animState.animData ? npc.sprite.animState.animFrame : -1; + if (npc.sprite.animState.animData && frame >= COIN_CHANGE_FRAME) return false; + return npc.speedMultiplier * npc.sprite.playbackSpeed + frame >= COIN_CHANGE_FRAME && npc.sprite.IsPlaying(spin); +} + +// Starts the key's or heart's change. +static void ultra_coin_change(Entity_NPC& npc, std::string_view change) +{ + npc.state = NPC_STATE_MOVE; + npc.sprite.Play(change); + npc_sound_play(SOUND_THUMBSUP, COIN_CHANGE_VOLUME, 2, 1); +} + +// The bomb: it pulses once its fuse is out, and once its pulse ends blows up (the penny kind dropping a penny one +// time in two). Whether it blew up. +static bool ultra_coin_bomb(Entity_NPC& npc, float fuse) +{ + if (fuse * COIN_BOMB_FUSE < npc.updateTime) + { + float frame = npc.sprite.animState.animData ? npc.sprite.animState.animFrame : -1; + bool isTurning = frame < COIN_CHANGE_FRAME && npc.speedMultiplier * npc.sprite.playbackSpeed + frame >= COIN_CHANGE_FRAME && + npc.sprite.IsPlaying("SpinningBomb"); + if (isTurning || npc.sprite.IsPlaying("IdleBomb")) + { + npc.sprite.Play("PulseBomb"); + npc.sprite.playbackSpeed = 1 / fuse; + } + } + + bool isExploded = false; + uint32_t pennies = 0; + if (npc.sprite.animState.animData && !npc.sprite.animState.isPlaying && npc.sprite.GetAnimation() == "PulseBomb") + { + explosion_effects({.color = ULTRA_GREED_BLAST_COLOR, + .position = npc.pos, + .source = &npc, + .damage = BOMB_DAMAGE, + .radiusMultiplier = BOMB_RADIUS_SCALE, + .isDamageSource = false, + .isLineCheck = true}); + if (npc.subtype == ULTRA_COIN_PENNY_SUBTYPE) pennies = Random() & 1; + game_particles_spawn({.position = npc.pos, .speed = BOMB_PARTICLE_SPEED, .count = COIN_GOLD_PARTICLES, .variant = EFFECT_GOLD_PARTICLE}); + isExploded = true; + } + npc.friction *= COIN_FRICTION; + for (; pennies != 0; pennies--) + { + Entity* penny = g_game->Spawn({.position = npc.pos, .type = ENTITY_PICKUP, .variant = PICKUP_COIN, .seed = Random()}); + if (!penny) continue; + Vector direction = random_direction(); + penny->velocity = vector_scale(direction, BOMB_PENNY_SPEED); + } + return isExploded; +} + +// The key or heart in flight: it changes, then flies at 2 to its target (the door it opens, Ultra Greed it heals), +// steering straight at it, and is spent once there (or with nothing to fly to). Whether it is still there. +static bool ultra_coin_fly(Entity_NPC& npc, std::string_view change, std::string_view move) +{ + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + if (npc.sprite.IsPlaying(change) || !npc.sprite.IsPlaying()) + { + npc.friction *= COIN_MOVE_FRICTION; + if (npc.sprite.IsPlaying()) return true; + npc.velocity = {}; + npc.sprite.Play(move); + return true; + } + if (!npc.sprite.IsPlaying(move)) return true; + + Entity* target = nullptr; + if (npc.variant == COIN_KEY) + { + for (Entity* door : entity_query(ENTITY_ULTRA_DOOR, -1)) + if (static_cast(door)->i1 == npc.i1) target = door; + } + else + { + float best = 0; + for (Entity* greed : entity_query(ENTITY_ULTRA_GREED, -1)) + { + float distance = vector_length_squared(vector_sub(npc.pos, greed->pos)); + if (target && distance >= best) continue; + target = greed; + best = distance; + } + } + if (target) + { + Vector pull = vector_resized(vector_sub(target->pos, npc.pos), COIN_FLIGHT_SPEED); + npc.velocity = vector_add(vector_scale(pull, npc.speedMultiplier), npc.velocity); + if (npc.variant == COIN_HEART) npc.velocity = vector_resized(pull, vector_length(npc.velocity)); + if (vector_length(npc.velocity) <= vector_distance(npc.pos, target->pos)) return true; + + if (npc.variant == COIN_KEY) + { + static_cast(target)->state = DOOR_OPENING; + npc_sound_play(SOUND_UNLOCK, 1, 2, 1); + } + else + { + ultra_greed_heal(*static_cast(target), HEART_HEAL); + npc_sound_play(SOUND_PENNYPICKUP, 1, 2, HEART_HEAL_PITCH); + } + } + npc.Remove(); + return false; +} + +// Broken (or worn out) it crumbles in gold, and is gone once it has. +static void ultra_coin_crumble(Entity_NPC& npc) +{ + if (npc.isDead) + { + float pitch = random_unit() * CRUMBLE_PITCH_RANGE + CRUMBLE_PITCH; + npc_sound_play(SOUND_ULTRA_GREED_COIN_DESTROY, 1, CRUMBLE_SOUND_DELAY, pitch); + npc.isDead = false; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.RemoveStatusEffects(); + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + game_particles_spawn({.position = npc.pos, .speed = CRUMBLE_PARTICLE_SPEED, .count = COIN_GOLD_PARTICLES, .variant = EFFECT_GOLD_PARTICLE}); + npc_anim_loop(npc.sprite, "Crumble"); + npc.sprite.playbackSpeed = 1; + npc.state = NPC_STATE_SPECIAL; + npc.sortingLayer = 0; + npc.shadowSize = 0; + } + else if (npc.state != NPC_STATE_SPECIAL) return; + + npc.friction *= COIN_MOVE_FRICTION; + if (!npc.sprite.IsPlaying()) npc.Remove(); +} + +// 005a4820 Ultra Greed's coins' AI: they appear and spin, the spinner wearing out, the key flying to open a door, +// the bomb blowing up and the heart flying to heal Ultra Greed. Broken they crumble in gold. +void npc_ultra_coin_update(Entity_NPC& npc) +{ + if (npc.state == NPC_STATE_INIT) + { + npc.ClearEntityFlags(FLAG_APPEAR); + npc.state = NPC_STATE_APPEAR_CUSTOM; + npc.splatColor = COIN_SPLAT_COLOR; + npc.entityCollisionClass = ENTCOLL_NONE; + npc.sprite.offset = vector_make(COIN_OFFSET_X, COIN_OFFSET_Y); + if (!ultra_coin_is_tough()) return; + + npc.maxHitPoints *= COIN_TOUGH_SCALE; + npc.health *= COIN_TOUGH_SCALE; + return; + } + + float fuse = ultra_coin_fuse_share(); + bool isKind = npc.variant >= COIN_SPINNER && npc.variant <= COIN_HEART; + if (npc.state == NPC_STATE_APPEAR_CUSTOM) + { + if (isKind) npc.sprite.Play(COIN_APPEARS[npc.variant]); + if (!npc.sprite.IsPlaying()) + { + npc.state = NPC_STATE_IDLE; + npc.stateFrame = 0; + npc.entityCollisionClass = ENTCOLL_ALL; + if (isKind) npc.sprite.Play(COIN_SPINS[npc.variant]); + } + } + else if (npc.state == NPC_STATE_IDLE) + { + switch (npc.variant) + { + case COIN_SPINNER: + ultra_coin_spin(npc); + break; + case COIN_KEY: + if (fuse * KEY_FUSE < npc.updateTime) ultra_coin_change(npc, "KeyChange"); + npc.friction *= COIN_FRICTION; + break; + case COIN_BOMB: + if (ultra_coin_bomb(npc, fuse)) return npc.Remove(); + break; + case COIN_HEART: + if (fuse * HEART_FUSE < npc.updateTime && ultra_coin_is_turning(npc, "SpinningHeart")) + ultra_coin_change(npc, "HeartChange"); + npc.friction *= COIN_FRICTION; + break; + } + } + else if (npc.state == NPC_STATE_MOVE) + { + if (npc.variant == COIN_KEY && !ultra_coin_fly(npc, "KeyChange", "KeyMove")) return; + if (npc.variant == COIN_HEART && !ultra_coin_fly(npc, "HeartChange", "HeartMove")) return; + } + ultra_coin_crumble(npc); +} diff --git a/src/npc_ultra_door.cpp b/src/npc_ultra_door.cpp new file mode 100644 index 0000000..d2fd323 --- /dev/null +++ b/src/npc_ultra_door.cpp @@ -0,0 +1,203 @@ +#include "npc_depths.h" +#include "boss_ai.h" +#include "entity_laser.h" +#include "room.h" +#include "room_config.h" +#include "room_grid.h" +#include + +// Ultra Greed's doors sit in the room's door slots, an invulnerable background sprite pushed 23 into the wall. A key +// coin opens one to let out Greed Gapers, and Ultra Greed opens them to fire a shoop beam across the room, either +// from one door, or from whichever of a facing pair is farther from the target once it walks between them. +constexpr int DOOR_SLOTS = 8; +constexpr float DOOR_SPREAD = 80; +constexpr float DOOR_SLOT_DEGREES = 90; +constexpr float DOOR_WALL_DEPTH = 23.076923f; +constexpr float ULTRA_DOOR_SOUND_VOLUME = 0.5f; +constexpr int ULTRA_DOOR_SOUND_DELAY = 20; +constexpr std::array DOOR_OPPOSITES = {2, 3, 0, 1, 6, 7, 4, 5}; +constexpr ColorMod DOOR_SPLAT_COLOR = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}}; + +// Its states: closed, letting Greed Gapers out (every 10 frames up to 80), firing alone (on frame 15, closing after +// 36), opened by Ultra Greed without firing, and firing across with its pair (on frame 5, closing after 26). +constexpr int DOOR_CLOSED = NPC_STATE_IDLE; +constexpr int DOOR_GAPERS = NPC_STATE_SUMMON; +constexpr int DOOR_FIRING = NPC_STATE_ATTACK; +constexpr int DOOR_OPEN = NPC_STATE_ATTACK2; +constexpr int DOOR_CROSSFIRE = NPC_STATE_ATTACK3; +constexpr int GAPER_EVERY = 10; +constexpr int GAPERS_FRAMES = 80; +constexpr int FIRING_FRAME = 15; +constexpr int FIRING_FRAMES = 36; +constexpr int CROSSFIRE_FRAME = 5; +constexpr int CROSSFIRE_FRAMES = 26; +constexpr float CROSSFIRE_ALIGN = 30; +constexpr int CROSSFIRE_VERTICAL = 180; + +// The beam: a shoop laser for 15 frames from 10 inside the room, gold tinted. +constexpr float DOOR_BEAM_MARGIN = -10; +constexpr float DOOR_BEAM_LIFT = -5; +constexpr int DOOR_BEAM_TIMEOUT = 15; +constexpr ColorMod DOOR_BEAM_COLOR = {{0.8f, 0.5f, 0.15f, 1}, {0, 0, 0, 0}, {0.6f, 0.3f, 0.1f}}; + +// 0059e630 NpcHelper::UltraDoor_Opposite: the door in the slot facing a door's, if any. +Entity_NPC* ultra_door_opposite(Entity_NPC& door, const std::vector& doors) +{ + int slot = (uint32_t)door.i1 < (uint32_t)DOOR_SLOTS ? DOOR_OPPOSITES[door.i1] : -1; + for (Entity* entity : doors) + if (static_cast(entity)->i1 == slot) return static_cast(entity); + return nullptr; +} + +// Its first frame: in the room's nearest free door slot (none within 80 holding a door), turned to face in and set +// into the wall. +static void ultra_door_init(Entity_NPC& npc, const std::vector& doors) +{ + npc.state = NPC_STATE_APPEAR_CUSTOM; + npc.splatColor = DOOR_SPLAT_COLOR; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.AddEntityFlags(FLAG_NO_STATUS_EFFECTS | FLAG_NO_TARGET); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + npc.isInvincible = true; + npc.sortingLayer = SORTING_DOOR; + + Room& room = *g_game->room; + int best = -1; + Vector bestSpot{}; + for (int slot = 0; slot < DOOR_SLOTS; slot++) + { + if (!(room.descriptor->data->doors & (1u << slot))) continue; + + Vector spot = room.GetGridPosition(room.doorGridPositions[slot]); + if (best != -1 && vector_distance(npc.pos, bestSpot) <= vector_distance(npc.pos, spot)) continue; + bool isTaken = false; + for (Entity* door : doors) isTaken = isTaken || vector_distance(door->pos, spot) < DOOR_SPREAD; + if (isTaken) continue; + + best = slot; + bestSpot = spot; + } + if (best != -1) + { + npc.i1 = best; + npc.pos = bestSpot; + } + float angle = (float)npc.i1 * DOOR_SLOT_DEGREES; + npc.sprite.rotation = angle - RIGHT_ANGLE_DEGREES; + npc.pos = vector_add(vector_scale(vector_from_angle(angle), DOOR_WALL_DEPTH), npc.pos); + npc.targetPosition = npc.pos; +} + +// Keeps it opening: the Open animation (with a heavy door sound) unless it is opening or open already, then Opened. +// Whether it stands open. +static bool ultra_door_open(Entity_NPC& npc, int startFrame) +{ + ANM2& sprite = npc.sprite; + if (!sprite.IsPlaying() || (sprite.GetAnimation() != "Open" && sprite.GetAnimation() != "Opened")) + { + sprite.Play("Open"); + npc.stateFrame = startFrame; + npc_sound_play(SOUND_DOOR_HEAVY_OPEN, ULTRA_DOOR_SOUND_VOLUME, ULTRA_DOOR_SOUND_DELAY, 1); + } + if (!sprite.animState.animData) return false; + if (!sprite.animState.isPlaying && sprite.GetAnimation() == "Open") sprite.Play("Opened"); + return sprite.IsPlaying("Opened"); +} + +// Its beam across the room along its facing, owned by Ultra Greed when there is one. +static void ultra_door_fire(Entity_NPC& npc, const std::vector& greeds) +{ + Vector origin = g_game->room->GetClampedPositionImpl(npc.pos, DOOR_BEAM_MARGIN, DOOR_BEAM_MARGIN, DOOR_BEAM_MARGIN, DOOR_BEAM_MARGIN); + Entity* owner = greeds.empty() ? &npc : greeds.front(); + Entity_Laser* beam = Entity_Laser::ShootAngle({.position = origin, + .posOffset = vector_make(0, DOOR_BEAM_LIFT), + .source = &npc, + .angleDegrees = (float)npc.i1 * DOOR_SLOT_DEGREES, + .timeout = DOOR_BEAM_TIMEOUT, + .variant = LASER_SHOOP}); + if (!beam) return; + + beam->sprite.color = DOOR_BEAM_COLOR; + beam->spawnerEntity = owner; + beam->Update(); +} + +// The crossfire: once the target stands level with a facing pair, the farther door fires and the nearer one holds +// (a lone door fires when the target is level with it). +static void ultra_door_crossfire_pick(Entity_NPC& npc, const std::vector& doors) +{ + Entity* target = npc.GetPlayerTarget(); + Entity_NPC* opposite = ultra_door_opposite(npc, doors); + if (!target) return; + + Entity_NPC* firing = opposite; + Entity_NPC* holding = &npc; + if (opposite && vector_distance(target->pos, opposite->pos) > vector_distance(target->pos, npc.pos)) + { + firing = &npc; + holding = opposite; + } + float offset = npc.i1 % CROSSFIRE_VERTICAL == 0 ? target->pos.y - npc.pos.y : target->pos.x - npc.pos.x; + if (std::abs(offset) >= CROSSFIRE_ALIGN) return; + + holding->stateFrame = 0; + holding->i2 = 0; + if (!firing) return; + firing->stateFrame = 0; + holding->i2 = 1; +} + +// 005a5b60 The Ultra Greed doors' AI: closed in its slot, it opens to let out Greed Gapers when a key coin reaches +// it, and Ultra Greed opens it to fire a beam across the room. +void npc_ultra_door_update(Entity_NPC& npc) +{ + std::vector greeds = entity_query(ENTITY_ULTRA_GREED, -1); + std::vector doors = entity_query(ENTITY_ULTRA_DOOR, -1); + if (npc.state == NPC_STATE_INIT) return ultra_door_init(npc, doors); + + ANM2& sprite = npc.sprite; + if (npc.state == NPC_STATE_APPEAR_CUSTOM) + { + sprite.Play("Closed"); + npc.state = DOOR_CLOSED; + } + if (sprite.animState.animData && !sprite.animState.isPlaying && sprite.GetAnimation() == "Close") sprite.Play("Closed"); + + if (npc.state == DOOR_CLOSED) + { + if (!sprite.IsPlaying() || (sprite.GetAnimation() != "Close" && sprite.GetAnimation() != "Closed")) + { + sprite.Play("Close"); + npc_sound_play(SOUND_DOOR_HEAVY_CLOSE, ULTRA_DOOR_SOUND_VOLUME, ULTRA_DOOR_SOUND_DELAY, 1); + } + if (sprite.animState.animData && !sprite.animState.isPlaying && sprite.GetAnimation() == "Close") + sprite.Play("Closed"); + } + if (npc.state == DOOR_GAPERS && ultra_door_open(npc, 0)) + { + if (++npc.stateFrame % GAPER_EVERY == 0) + { + Room& room = *g_game->room; + room_free_pickup_position_find({.position = room.GetRandomPosition(0)}); + Entity* gaper = g_game->Spawn({.position = npc.pos, .type = ENTITY_GREED_GAPER, .seed = Random()}); + if (gaper) gaper->Update(); + } + if (npc.stateFrame > GAPERS_FRAMES) npc.state = DOOR_CLOSED; + } + if ((npc.state == DOOR_FIRING || npc.state == DOOR_OPEN) && ultra_door_open(npc, 0)) + { + npc.stateFrame++; + if (npc.state == DOOR_FIRING && npc.stateFrame == FIRING_FRAME) ultra_door_fire(npc, greeds); + if (npc.stateFrame > FIRING_FRAMES) npc.state = DOOR_CLOSED; + } + if (npc.state == DOOR_CROSSFIRE && ultra_door_open(npc, -1)) + { + ultra_door_crossfire_pick(npc, doors); + if (npc.stateFrame >= 0) npc.stateFrame++; + if (npc.stateFrame == CROSSFIRE_FRAME && npc.i2 == 0) ultra_door_fire(npc, greeds); + if (npc.stateFrame > CROSSFIRE_FRAMES) npc.state = DOOR_CLOSED; + } + npc.velocity = {}; + npc.pos = npc.targetPosition; +} diff --git a/src/npc_ultra_greed.cpp b/src/npc_ultra_greed.cpp new file mode 100644 index 0000000..e5ccd94 --- /dev/null +++ b/src/npc_ultra_greed.cpp @@ -0,0 +1,1706 @@ +#include "npc_depths.h" +#include "active_items.h" +#include "boss_ai.h" +#include "entity_bomb.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_effect_combat.h" +#include "entity_pickup.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "game.h" +#include "grid_entity_trap_door.h" +#include "loot_list.h" +#include "manager.h" +#include "menu_manager.h" +#include "npc_ai.h" +#include "path_finder.h" +#include "persistent_game_data.h" +#include "room.h" +#include "room_grid.h" +#include "sfx_manager.h" +#include +#include +#include + +// Ultra Greed's states (Ultra Greedier is variant 1): hanging from his chains before the fight, standing, walking to +// the coins, the jump onto the target, Greedier breaking out of the gold, the slot machine, the stomping tantrum, the +// dash's wind up and the dash, guarding while his minions fight, the single and the long spin, the coin spit, one or +// two smashes, and turning to gold. +enum UltraGreedState : int +{ + ULTRA_GREED_HANGING = NPC_STATE_APPEAR_CUSTOM, + ULTRA_GREED_IDLE = NPC_STATE_IDLE, + ULTRA_GREED_WALK = NPC_STATE_MOVE, + ULTRA_GREED_JUMP = NPC_STATE_JUMP, + ULTRA_GREED_BREAK_FREE = NPC_STATE_SPECIAL, + ULTRA_GREED_SLOTS = 100, + ULTRA_GREED_STOMPS = 200, + ULTRA_GREED_TANTRUM = 300, + ULTRA_GREED_DASH = 310, + ULTRA_GREED_GUARD = 400, + ULTRA_GREED_SPIN_ONCE = 500, + ULTRA_GREED_SPIN = 510, + ULTRA_GREED_SHOOT = 600, + ULTRA_GREED_SMASH = 700, + ULTRA_GREED_SMASH_TWICE = 710, + ULTRA_GREED_TURN_GOLD = 9000, + ULTRA_GREED_GOLD = 9001 +}; + +// His shield, raised once Everything Is Terrible 2 is unlocked (or in a daily or debug run, where he is 15 percent +// tougher), doubled while he spins, guards or pulls the slots, and Greedier's weaker one. He is twice as wide as tall. +constexpr float ULTRA_GREED_SHIELD = 65; +constexpr float ULTRA_GREED_SHIELD_TOUGH = 85; +constexpr float ULTRA_GREEDIER_SHIELD = 45; +constexpr float ULTRA_GREEDIER_SHIELD_TOUGH = 60; +constexpr float ULTRA_GREED_TOUGH_SCALE = 1.15f; +constexpr int ULTRA_GREED_SHIELD_FRAMES = 120; +constexpr float ULTRA_GREED_WIDTH = 2; +constexpr float ULTRA_GREED_HEIGHT = 1; + +// His rage, 0 to 1: grows as his health drops (15 of 25 points) and with i2 (10 more, one lost every 30 frames), and +// fades while he turns gold. It tints him red. +constexpr float RAGE_HEALTH_POINTS = 15; +constexpr float RAGE_POINTS = 25; +constexpr int RAGE_DECAY_FRAMES = 30; +constexpr float RAGE_GOLD_FADE_FRAMES = 10; +constexpr ColorMod ULTRA_GREED_RAGE_COLOR = {{1, 1, 1, 1}, {1, 0.2f, 0.2f, 0}, {0, 0, 0}}; + +// Greedier sheds gold as he is hurt: up to 10 particles for 100 damage. Both shed it from their body's texels. +constexpr float GOLD_SHED_DAMAGE = 100; +constexpr float GOLD_SHED_MAX = 10; +constexpr float GOLD_SAMPLE_HEIGHT = 187.5f; +constexpr float GOLD_SAMPLE_WIDTH = 125; +constexpr float GOLD_TEXEL_ALPHA = 0.9f; +constexpr int GOLD_PARTICLE_BURST = 7; +constexpr float GOLD_PARTICLE_SPEED = 12; +constexpr int BLING_RENDER_Z = 1000; + +// Hanging, the camera holds 100 above him. After 60 frames he drops to fight. +constexpr float HANGING_CAMERA_RISE = 100; +constexpr int HANGING_FRAMES = 60; +constexpr float HANGING_FRICTION = 0.01f; +constexpr int HANGING_SHAKE = 15; +constexpr float STOMP_PITCH_MIN = 0.9f; +constexpr float STOMP_PITCH_RANGE = 0.2f; +constexpr int WALK_STOMP_SHAKE = 5; + +// The walk: at 4 a frame (Greedier at 0.6 of that), slower between steps, capped at 10 times his rage's 1 to 1.7 +// (3 times while dashing), toward the coin worth the most for its distance or a random spot at least 180 off. +constexpr float WALK_ACCELERATION = 4; +constexpr float GREEDIER_PACE = 0.6f; +constexpr float WALK_SPEED_CAP = 10; +constexpr float WALK_STEP_SLOW = 0.7f; +constexpr float WALK_CAP_SLOW = 0.6f; +constexpr float WALK_FRICTION_SLOW = 0.6f; +constexpr float UG_WALK_FRICTION = 0.8f; +constexpr float WALK_RAGE_SPEED = 0.7f; +constexpr float DASH_SPEED_SCALE = 3; +constexpr float WALK_PLAYBACK_SCALE = 0.8f; +constexpr int WALK_SPOT_TRIES = 20; +constexpr float WALK_SPOT_FAR = 180; +constexpr float WALK_PATH_SPEED = 1; +constexpr int WALK_PATH_THRESHOLD = 900; +constexpr float WALK_FAR_DISTANCE = 1e8f; +constexpr int UG_IDLE_FRAMES = 30; + +// The frames of his walk cycle on which a foot is down: he moves at full pace on them. +constexpr int STEP_FIRST_END = 4; +constexpr int STEP_SECOND_START = 14; +constexpr int STEP_SECOND_END = 18; +constexpr int STEP_LAST_START = 28; + +// A new attack is drawn every 15 frames while he stands or walks. Six minions or more make him guard, under five he +// stops. A single slot machine pull at under three coins out, the coins worth six or more keep him walking. +constexpr int ATTACK_DRAW_FRAMES = 15; +constexpr int GUARD_MINIONS = 6; +constexpr int GUARD_END_MINIONS = 5; +constexpr int FEW_MINIONS = 2; +constexpr int SLOTS_COIN_LIMIT = 3; +constexpr int COINS_WORTH_WALKING = 6; +constexpr int KEEPERS_MAX = 4; +constexpr float DASH_LEAD = 16; +constexpr float DASH_TARGET_MARGIN = 20; +constexpr float SPIN_ONCE_REACH = 3; +constexpr float SHOOT_RANGE_MIN = 200; +constexpr float SHOOT_RANGE_MAX = 320; +constexpr float SMASH_RANGE = 100; +constexpr float UG_JUMP_RANGE = 400; + +// The attack weights, by Ultra Greed's rage (from the base, rising by the rage weight): the slots, the dash, the +// single and the long spin, the coin spit, the stomps and walking on. Greedier also smashes and jumps. +constexpr int WEIGHT_SLOTS = 30; +constexpr float WEIGHT_SLOTS_RAGE = 20; +constexpr int WEIGHT_FEW_MINIONS = 30; +constexpr int WEIGHT_TANTRUM = 30; +constexpr float WEIGHT_TANTRUM_RAGE = 20; +constexpr int WEIGHT_SPIN_ONCE = 70; +constexpr float WEIGHT_SPIN_ONCE_RAGE = 130; +constexpr int WEIGHT_SPIN = 15; +constexpr float WEIGHT_SPIN_RAGE = 20; +constexpr int WEIGHT_SHOOT = 50; +constexpr float WEIGHT_SHOOT_RAGE = 30; +constexpr int WEIGHT_GREEDIER_SHOOT = 80; +constexpr float WEIGHT_GREEDIER_SHOOT_RAGE = 40; +constexpr int WEIGHT_STOMPS = 20; +constexpr float WEIGHT_STOMPS_RAGE = 20; +constexpr int WEIGHT_GREEDIER_STOMPS = 10; +constexpr float WEIGHT_GREEDIER_STOMPS_RAGE = 5; +constexpr int WEIGHT_WALK = 100; +constexpr float WEIGHT_WALK_RAGE = 40; +constexpr float WEIGHT_GREEDIER_WALK_RAGE = 70; +constexpr int WEIGHT_WALK_FEW_MINIONS = 60; +constexpr int WEIGHT_WALK_COINS = 500; +constexpr float UG_WEIGHT_SMASH = 20; +constexpr float WEIGHT_SMASH_DROP = 10; +constexpr int WEIGHT_SMASH_TWICE_MINIONS = 3; +constexpr float WEIGHT_JUMP = 10; +constexpr float WEIGHT_JUMP_RANGE = 40; +constexpr RNG ATTACK_DRAW_RNG = {0, 5, 9, 7}; + +// The coin spit: 11 fast in a three, four or five spread (Greedier's wider and exploding), or six boss shots. +constexpr int SHOT_SPREADS[] = {PROJECTILES_THREE_WIDE, PROJECTILES_FOUR, PROJECTILES_FIVE}; +constexpr int SHOT_BOSS = 50; +constexpr int SHOT_BOSS_COUNT = 6; +constexpr int SHOT_WEIGHT = 100; +constexpr uint32_t SHOT_RNG_SHIFT = 35; +constexpr float COIN_SHOT_HEIGHT = -80; +constexpr float COIN_SHOT_SCALE = 1.6f; +constexpr float COIN_SHOT_SPEED = 11; +constexpr float COIN_SHOT_FALL_ACCEL = 0.06f; +constexpr float COIN_SHOT_FALL_SPEED = 10; +constexpr float GREEDIER_SPREAD = 1.6f; + +// The tantrum winds the dash up until frame 12. The dash leaves dust and stops on a wall held 6 frames or after 90. +constexpr int TANTRUM_DASH_FRAME = 12; +constexpr int DASH_DUST = 3; +constexpr float DASH_DUST_BACK = -3.5f; +constexpr float DASH_DUST_SCALE = 2; +constexpr float DASH_DUST_LIFT = -20; +constexpr float DASH_DUST_LIFT_RANGE = 40; +constexpr int DASH_DUST_RENDER_Z = 2000; +constexpr int DASH_TICKS = 90; +constexpr int DASH_TIMED_OUT = 100; +constexpr int DASH_WALL_FRAMES = 6; + +// The smash hits 60 below him with a 60 damage gold blast, then one draw: some doors (100) or all (70). The second +// of two comes from his other hand. +constexpr float SMASH_DROP = 60; +constexpr int SMASH_TWICE_LAST = 1; +constexpr float SMASH_DAMAGE = 60; +constexpr float SMASH_RADIUS_SCALE = 1.8f; +constexpr int SMASH_SOME_DOORS = 0; +constexpr int SMASH_ALL_DOORS = 1; +constexpr int SMASH_SOME_WEIGHT = 100; +constexpr int SMASH_ALL_WEIGHT = 70; +constexpr int SMASH_SOME_SHAKE = 13; +constexpr int SMASH_ALL_SHAKE = 18; +constexpr int SMASH_TWICE_SHAKE = 10; + +// The spin: a new spot to drift to every 30 frames, circling over 240, kicked off walls, a coin shot every 8 frames +// turning 12 degrees by 0.707 each, lasting 120 frames less 60 by rage. Spinning, he knocks players and familiars +// (charmed, enemies) aside from 2.4 sizes off, by 70 degrees, for 2 damage (30 to enemies). +constexpr int SPIN_SPOT_FRAMES = 30; +constexpr float SPIN_CIRCLE_FRAMES = 240; +constexpr float SPIN_CIRCLE_PUSH = 0.7f; +constexpr float SPIN_WALL_KICK = 20; +constexpr int SPIN_SHOT_FRAMES = 8; +constexpr float SPIN_SHOT_TURN = 12 * 0.707f; +constexpr float UG_SPIN_SHOT_SPEED = 10; +constexpr float UG_SPIN_FRAMES = 120; +constexpr float SPIN_RAGE_FRAMES = 60; +constexpr int SPIN_ONCE_HIT_FRAME = 3; +constexpr float SPIN_QUERY_REACH = 3; +constexpr float SPIN_HIT_REACH = 2.4f; +constexpr float SPIN_KNOCK_DEGREES = 70; +constexpr float SPIN_KNOCK = 5; +constexpr float SPIN_DAMAGE = 2; +constexpr float SPIN_ENEMY_DAMAGE = 30; +constexpr int SPIN_HIT_COUNTDOWN = 30; +constexpr float SPIN_SOUND_FADE = 0.15f; + +// The stomps: faster with rage, shaking the room and, on each foot, a Keeper (up to four) or Greedier's two bomb +// coins. They stop on the loop after 75 frames at rage 0. +constexpr int STOMPS_SHAKE = 10; +constexpr float STOMPS_FRAMES = 75; +constexpr float KEEPER_DROP = 1.3f; +constexpr int GREEDIER_STOMP_COINS = 2; +constexpr float STOMP_RIPPLE = 0.025f; +constexpr int UG_STOMP_RIPPLE_FRAMES = 25; + +// The jump: up to the target with a roar and 15 gold, raining coin shots every 5 frames from 3 to 5 fast over 60 +// frames (falling at 30 to 35 from 800 up), then down with 30 gold, a ripple and five crack waves. +constexpr int JUMP_SHAKE = 8; +constexpr int JUMP_GOLD = 15; +constexpr float UG_JUMP_PULL = 2; +constexpr int JUMP_SHOT_FRAMES = 5; +constexpr float JUMP_SHOT_RAMP_FRAMES = 60; +constexpr float JUMP_SHOT_SPEED = 3; +constexpr float JUMP_SHOT_RAMP = 2; +constexpr float JUMP_SHOT_HEIGHT = -800; +constexpr float JUMP_SHOT_FALL_ACCEL = 2; +constexpr float JUMP_SHOT_FALL_SPEED = 30; +constexpr float JUMP_SHOT_FALL_RANGE = 5; +constexpr int JUMP_SPARKLES = 2; +constexpr float JUMP_SPARKLE_SPEED = 3; +constexpr float JUMP_SPARKLE_HEIGHT = -800; +constexpr int LAND_GOLD = 30; +constexpr int UG_LAND_SHAKE = 18; +constexpr int LAND_CRACKWAVES = 5; +constexpr float UG_JUMP_FRICTION = 0.8f; +constexpr float UG_SLOW_FRICTION = 0.4f; +constexpr float UG_SPIN_FRICTION = 0.8f; + +// The slot machine: it spins 51 frames less 21 by rage, then shows a key (a key coin for each door, two each below a +// fifth of his health), a bomb (12 bomb coins), a heart (7 heart coins) or a spinner (7 spinners), one coin every so +// many frames. The win plays up to 60 frames (less 40 by rage) after. +constexpr float SLOTS_SPIN_FRAMES = 51; +constexpr float SLOTS_SPIN_RAGE = 21; +constexpr int SLOTS_OUTCOMES = 4; +constexpr float SLOTS_LOW_HEALTH = 0.2f; +constexpr float SLOTS_WIN_FRAMES = 60; +constexpr float SLOTS_WIN_RAGE = 40; +constexpr int SLOTS_SOUND_DELAY = 90; +constexpr int SLOTS_START_SOUND_DELAY = 60; +constexpr int TANTRUM_SOUND_DELAY = 30; +constexpr int SMASH_SOUND_DELAY = 45; + +// What each slot outcome pays: the coin variant, how many and every how many frames. +struct SlotPayout +{ + int coin = -1; + int count = 1; + int interval = 30; +}; + +constexpr std::array SLOT_PAYOUTS = { + {{COIN_KEY, 0, 8}, {COIN_BOMB, 12, 2}, {COIN_HEART, 7, 7}, {COIN_SPINNER, 7, 7}}}; + +// Turning gold: a gold flash every frame, the sounds and on Disappear a hundred gold bursts, a penny and the room +// turned to gold. Greedier (and on Greedier or hard, Ultra Greed's gold) breaks free after. +constexpr int TURN_GOLD_BURSTS = 100; +constexpr int TURN_GOLD_BURST_PARTICLES = 4; +constexpr float TURN_GOLD_BURST_SPEED = 10; +constexpr float TURN_GOLD_BURST_STEP = -2; +constexpr float TURN_GOLD_REACH = 2; +constexpr float TURN_GOLD_PENNY_RISE = -3; +constexpr float TURN_GOLD_LAST_PITCH = 0.6f; +constexpr int BREAK_GOLD_START = 7; +constexpr int BREAK_GOLD = 60; +constexpr float BREAK_PITCH = 0.5f; + +// The flags he holds while invulnerable (turning gold, breaking free), and the bestiary's variant of Greedier. +constexpr uint64_t ULTRA_GREED_STILL_FLAGS = + FLAG_NO_STATUS_EFFECTS | FLAG_NO_KNOCKBACK | FLAG_NO_PHYSICS_KNOCKBACK | FLAG_DONT_COUNT_BOSS_HP; +constexpr uint64_t ULTRA_GREED_BREAK_CLEARED = ULTRA_GREED_STILL_FLAGS | FLAG_NO_FLASH_ON_DAMAGE | FLAG_HIDE_HP_BAR; +constexpr int ULTRA_GREEDIER_VARIANT = 1; + +// His walk breaks the rocks his collision points press on (10 percent out), bridging the pit behind each. +constexpr float COLLISION_POINT_REACH = 1.1f; + +// Each footfall's dust: a footprint, Greedier's gold, 16 puffs kicked up and maybe a rock particle, scaled out from +// the foot. +constexpr float FOOT_SCALE = 0.65f; +constexpr float FOOT_SCATTER = 15; +constexpr int FOOT_GOLD = 10; +constexpr float FOOT_GOLD_SPEED = 8; +constexpr int FOOT_PUFFS = 16; +constexpr float FOOT_PUFF_SPEED = 3; +constexpr float FOOT_VELOCITY_SHARE = 0.5f; +constexpr int FOOT_PUFF_RENDER_Z = 1000; +constexpr ColorMod FOOT_PUFF_COLOR = {{1, 1, 1, 1}, {0, 0, 0, 0}, {0.11764707f, 0.058823533f, 0.019607844f}}; +constexpr float FOOT_ROCK_LIFT = 2; + +// What Ultra Greed's room holds this frame: the coins' worth, his coins, minions (two coins count as one) and doors. +struct UltraGreedRoom +{ + std::vector doors; + int coinsOut = 0; + int coinWorth = 0; + int keepers = 0; + int minions = 0; +}; + +// The controlling player's movement, none without one. +struct UltraGreedControl +{ + Vector move{}; + float push = 0; + bool isControlled = false; +}; + +// The attack the walk settles on, and the dash's way. +struct UltraGreedPlan +{ + Vector dashWay{}; + int next = ULTRA_GREED_WALK; +}; + +// 0059e390 A bling where a random point of the sprite's body shows. +void Entity_NPC::CreateBling() +{ + float sampleY = (random_unit() - 1) * GOLD_SAMPLE_HEIGHT; + float sampleX = (random_unit() - HALF) * GOLD_SAMPLE_WIDTH; + KColor texel = sprite.GetTexel({.sample = vector_make(sampleX, sampleY), .alphaThreshold = GOLD_TEXEL_ALPHA}); + + if (texel._alpha < 1) return; + Entity* bling = + g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_ULTRA_GREED_BLING, .seed = Random()}); + bling->sprite.offset = vector_make(sampleX, sampleY); + bling->renderZOffset = BLING_RENDER_Z; +} + +// 0059e4c0 Gold bursting from random points of the sprite's body, each from where it shows. +void Entity_NPC::CreateGoldParticles(uint32_t count) +{ + for (; count != 0; count--) + { + float sampleY = (random_unit() - 1) * GOLD_SAMPLE_HEIGHT; + float sampleX = (random_unit() - HALF) * GOLD_SAMPLE_WIDTH; + KColor texel = sprite.GetTexel({.sample = vector_make(sampleX, sampleY), .alphaThreshold = GOLD_TEXEL_ALPHA}); + + if (texel._alpha < 1) continue; + game_particles_spawn({.position = vector_make(sampleX + pos.x, pos.y), + .height = sampleY, + .speed = GOLD_PARTICLE_SPEED, + .count = GOLD_PARTICLE_BURST, + .variant = EFFECT_GOLD_PARTICLE}); + } +} + +static bool ultra_greed_is_tough() +{ + return g_manager->persistentGameData.Unlocked(ACHIEVEMENT_EVERYTHING_IS_TERRIBLE_2); +} + +static void ultra_greed_sound(int sound, int frameDelay, float pitch = 1) +{ + npc_sound_play(sound, 1, frameDelay, pitch); +} + +// A footfall's thud, pitched by the champion color. +static void ultra_greed_stomp_sound(Entity_NPC& npc, int sound, float pitch) +{ + npc.PlaySound(sound, 1, 2, false, pitch); +} + +static float stomp_pitch() +{ + return random_unit() * STOMP_PITCH_RANGE + STOMP_PITCH_MIN; +} + +// The room's coins worth, Ultra Greed's coins and minions, and his doors. +static UltraGreedRoom ultra_greed_room_read() +{ + UltraGreedRoom room; + int coins = 0; + int gapers = 0; + + for (Entity* coin : entity_query(ENTITY_PICKUP, PICKUP_COIN)) + if (auto* pickup = dynamic_cast(coin)) room.coinWorth += pickup->GetCoinValue(); + coins = (int)entity_query(ENTITY_ULTRA_COIN, -1).size(); + gapers = (int)entity_query(ENTITY_GREED_GAPER, -1).size(); + room.keepers = (int)entity_query(ENTITY_KEEPER, -1).size(); + room.doors = entity_query(ENTITY_ULTRA_DOOR, -1); + room.coinsOut = coins; + room.minions = coins / 2 + gapers + room.keepers; + return room; +} + +// His doors in the room's door slots the layout has, unless friendly or already there, each told its slot. +static void ultra_greed_doors_spawn(Entity_NPC& npc, const UltraGreedRoom& scene) +{ + Room& room = *g_game->room; + + if (npc.HasEntityFlags(FLAG_FRIENDLY) || !scene.doors.empty()) return; + for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++) + { + if (!(room.descriptor->data->doors & 1u << slot)) continue; + Entity* door = g_game->Spawn({.position = room.GetGridPosition(room.doorGridPositions[slot]), + .spawner = &npc, + .type = ENTITY_ULTRA_DOOR, + .seed = Random()}); + if (auto* doorNpc = dynamic_cast(door)) + { + doorNpc->i1 = slot; + doorNpc->Update(); + } + } +} + +// The first frame: tougher once Everything Is Terrible 2 is unlocked, twice as wide, crushing rocks, his doors, and +// hanging from the ceiling. +static void ultra_greed_init(Entity_NPC& npc, const UltraGreedRoom& scene, float shield) +{ + if (ultra_greed_is_tough()) + { + npc.maxHitPoints *= ULTRA_GREED_TOUGH_SCALE; + npc.health *= ULTRA_GREED_TOUGH_SCALE; + } + npc.SetSize(npc.size, vector_make(ULTRA_GREED_WIDTH, ULTRA_GREED_HEIGHT), npc.config->gridCollisionPoints); + npc.pathfinder.canCrushRocks = true; + ultra_greed_doors_spawn(npc, scene); + npc.shieldStrength = shield; + npc.shieldFrames = ULTRA_GREED_SHIELD_FRAMES; + npc.v1.y = 0; + npc.state = ULTRA_GREED_HANGING; + npc.ClearEntityFlags(FLAG_APPEAR); + npc.sprite.Play("Hanging"); +} + +// Killed, he turns gold where he stands: every projectile vanishes, the other bosses die and his doors shut. +static void ultra_greed_gold_start(Entity_NPC& npc) +{ + npc.state = ULTRA_GREED_TURN_GOLD; + npc.targetPosition = npc.pos; + npc.AddEntityFlags(FLAG_DONT_COUNT_BOSS_HP); + npc.stateFrame = 0; + npc.isDead = false; + + std::vector entities = g_game->room->entityList.updateEL; + for (Entity* entity : entities) + { + if (entity->type == ENTITY_ULTRA_GREED) continue; + if (entity->type == ENTITY_PROJECTILE) + entity->isDead = true; + else if (entity->is_valid_boss_enemy()) + entity->Kill(EntityRef(&npc)); + else if (auto* door = dynamic_cast(entity); door && entity->type == ENTITY_ULTRA_DOOR) + door->state = NPC_STATE_IDLE; + } + g_manager->persistentGameData.AddBestiaryKill(npc.type, npc.variant); +} + +// The controlling player's movement, read action by action. +static UltraGreedControl ultra_greed_control_read(Entity_NPC& npc) +{ + UltraGreedControl control; + + if (npc.controllerID == -1) return control; + control.isControlled = true; + float left = input_action_value_get(ACTION_LEFT, npc.controllerID, &npc); + float right = input_action_value_get(ACTION_RIGHT, npc.controllerID, &npc); + float up = input_action_value_get(ACTION_UP, npc.controllerID, &npc); + float down = input_action_value_get(ACTION_DOWN, npc.controllerID, &npc); + control.move = vector_make(right - left, down - up); + if (vector_length_squared(control.move) > 1) control.move = vector_resized(control.move, 1); + control.push = vector_length(control.move); + return control; +} + +// His rage, 0 to 1, from his health and i2, fading out while he turns gold. +static float ultra_greed_rage(Entity_NPC& npc) +{ + float health = lerp_range(npc.health, {.inMax = npc.maxHitPoints}); + float rage = + std::clamp(((float)npc.i2 + (RAGE_HEALTH_POINTS - health * RAGE_HEALTH_POINTS)) / RAGE_POINTS, 0.0f, 1.0f); + + if (npc.state == ULTRA_GREED_TURN_GOLD) + { + float fade = std::clamp((float)npc.sprite.GetFrame() / RAGE_GOLD_FADE_FRAMES, 0.0f, 1.0f); + return rage - rage * fade; + } + return npc.state == ULTRA_GREED_GOLD ? 0 : rage; +} + +// Hanging until he tears free and drops into the fight, the camera held above him. +static void ultra_greed_hanging(Entity_NPC& npc, bool isStomp) +{ + g_game->room->camera->SetFocusPosition(vector_make(npc.pos.x, npc.pos.y - HANGING_CAMERA_RISE)); + npc.friction = HANGING_FRICTION; + npc.entityCollisionClass = ENTCOLL_NONE; + if (npc.sprite.IsEventTriggered("Tear")) + { + game_shake_screen(HANGING_SHAKE); + ultra_greed_stomp_sound(npc, SOUND_ULTRA_GREED_ROAR_1, 1); + } + if (isStomp) + { + game_shake_screen(HANGING_SHAKE); + ultra_greed_stomp_sound(npc, SOUND_FORESTBOSS_STOMPS, stomp_pitch()); + } + if (npc.sprite.IsPlaying("Hanging") && npc.stateFrame > HANGING_FRAMES) npc.sprite.Play("Appearing"); + npc.stateFrame++; + if (!npc.sprite.IsPlaying() && npc.sprite.GetAnimation() == "Appearing") + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.state = ULTRA_GREED_WALK; + npc.stateFrame = 0; + } +} + +static void ultra_greed_state_set(Entity_NPC& npc, int state) +{ + npc.state = state; + npc.stateFrame = 0; + npc.i1 = 0; +} + +// The tantrum winds the dash up. +static void ultra_greed_tantrum(Entity_NPC& npc) +{ + ultra_greed_sound(SOUND_ULTRA_GREED_ROAR_1, TANTRUM_SOUND_DELAY); + npc.sprite.Play("Tantrum"); + if (npc.sprite.GetFrame() == TANTRUM_DASH_FRAME) + { + ultra_greed_state_set(npc, ULTRA_GREED_DASH); + npc.projectileDelay = 0; + } + npc.friction *= UG_SLOW_FRICTION; +} + +// A smash opens some of his doors: a random number of draws, or as many draws as doors, each door drawn firing and its +// facing door opening (only those shut). A second smash fires one drawn pair whatever they did. +static void ultra_greed_doors_open(const std::vector& doors, size_t draws, bool isForced) +{ + for (; draws > 0 && !doors.empty(); draws--) + { + auto* door = dynamic_cast(doors[Random() % doors.size()]); + Entity_NPC* opposite = door ? ultra_door_opposite(*door, doors) : nullptr; + + for (auto [opened, state] : {std::pair{door, NPC_STATE_ATTACK}, std::pair{opposite, NPC_STATE_ATTACK2}}) + { + if (!opened || (!isForced && opened->state != NPC_STATE_IDLE)) continue; + opened->state = state; + if (isForced) opened->stateFrame = 0; + } + } +} + +// 0059e730 NpcHelper::UltraGreed_Smash: a fist hits the ground with gold, a ripple and a gold blast. A single smash +// (and Greedier's break from the gold) opens doors: some by the draw (always on the break), else all of them. A +// second smash fires one pair. +static void ultra_greed_smash(Entity_NPC& npc, Vector position) +{ + std::vector doors = entity_query(ENTITY_ULTRA_DOOR, -1); + + npc.CreateGoldParticles(LAND_GOLD); + ultra_greed_sound(SOUND_POT_BREAK, 2); + ultra_greed_sound(SOUND_FORESTBOSS_STOMPS, 2, stomp_pitch()); + shockwave_make(position, STOMP_RIPPLE, STOMP_RIPPLE, UG_STOMP_RIPPLE_FRAMES); + explosion_effects({.color = ULTRA_GREED_BLAST_COLOR, + .position = position, + .source = &npc, + .damage = SMASH_DAMAGE, + .radiusMultiplier = SMASH_RADIUS_SCALE, + .isLineCheck = true}); + + if (npc.state == ULTRA_GREED_SMASH || npc.state == ULTRA_GREED_BREAK_FREE) + { + WeightedOutcomePicker picker; + picker.AddOutcomeWeight(SMASH_SOME_DOORS, SMASH_SOME_WEIGHT); + picker.AddOutcomeWeight(SMASH_ALL_DOORS, SMASH_ALL_WEIGHT); + RNG rng = ATTACK_DRAW_RNG; + rng._seed = Random() | 1; + int outcome = picker.PickOutcome(rng); + + if (outcome == SMASH_SOME_DOORS || npc.state == ULTRA_GREED_BREAK_FREE) + { + game_shake_screen(SMASH_SOME_SHAKE); + if (!doors.empty()) ultra_greed_doors_open(doors, Random() % doors.size() + 1, false); + } + else if (outcome == SMASH_ALL_DOORS) + { + game_shake_screen(SMASH_ALL_SHAKE); + ultra_greed_doors_open(doors, doors.size(), false); + } + } + if (npc.state == ULTRA_GREED_SMASH_TWICE) + { + game_shake_screen(SMASH_TWICE_SHAKE); + ultra_greed_doors_open(doors, 1, true); + } +} + +// One or two smashes, the second from the other hand. +static void ultra_greed_smash_update(Entity_NPC& npc) +{ + if (npc.i1 == 0) ultra_greed_sound(SOUND_ULTRA_GREED_ROAR_2, SMASH_SOUND_DELAY); + npc.sprite.Play("Smash"); + if (npc.sprite.IsEventTriggered("Smash")) ultra_greed_smash(npc, vector_make(npc.pos.x, npc.pos.y + SMASH_DROP)); + if (!npc.sprite.IsPlaying()) + { + if (npc.state == ULTRA_GREED_SMASH || npc.i1 > SMASH_TWICE_LAST) + ultra_greed_state_set(npc, ULTRA_GREED_IDLE); + else + { + npc.sprite.Play("Smash", PLAY_FORCED); + npc.sprite.isFlipX = !npc.sprite.isFlipX; + npc.stateFrame = 0; + npc.i1++; + } + } + npc.friction *= UG_SLOW_FRICTION; +} + +// Guarding, flashing as he is hit, while his minions fight (or the controller holds the drop button). +static void ultra_greed_guard(Entity_NPC& npc, const UltraGreedRoom& scene, const UltraGreedControl& control) +{ + if (npc.i1 == 0) + { + npc.sprite.Play("GuardStart"); + if (npc.sprite.IsFinished()) npc.i1 = 1; + } + else if (npc.i1 == 1) + { + npc.AddEntityFlags(FLAG_NO_FLASH_ON_DAMAGE); + if (npc.sprite.IsFinished("GuardFlashSlow") || npc.sprite.IsFinished("GuardStart")) npc.sprite.Play("Guarding"); + if (npc.pendingDamage > 0) npc.sprite.Play("GuardFlashSlow", PLAY_FORCED); + + bool isOver = + control.isControlled ? !npc.IsControllerActionPressed(ACTION_DROP) : scene.minions < GUARD_END_MINIONS; + if (isOver) + { + npc.i1 = 2; + npc.ClearEntityFlags(FLAG_NO_FLASH_ON_DAMAGE); + } + } + else if (npc.i1 == 2) + { + npc.sprite.Play("GuardEnd"); + if (npc.sprite.IsFinished()) ultra_greed_state_set(npc, ULTRA_GREED_WALK); + } + npc.stateFrame++; + npc.friction *= UG_SLOW_FRICTION; +} + +// Spinning knocks players and familiars (or, charmed, enemies) aside and hurts them. +static void ultra_greed_spin_hit(Entity_NPC& npc) +{ + float reach = npc.size * npc.sizeMulti.x; + bool isFriendly = npc.HasEntityFlags(FLAG_FRIENDLY); + bool isCharmed = npc.HasEntityFlags(FLAG_CHARM); + + for (Entity* entity : entity_query_radius(npc.pos, reach * SPIN_QUERY_REACH, QUERY_ALL)) + { + if (!entity || entity->entityCollisionClass == ENTCOLL_NONE) continue; + bool isVersusPlayer = g_game->deathmatchManager.is_active() && entity->type == ENTITY_PLAYER; + bool isEnemy = entity->type >= ENTITY_FIRST_ENEMY && entity->type < ENTITY_EFFECT; + bool isAlly = (entity->type == ENTITY_PLAYER || entity->type == ENTITY_FAMILIAR) && !isFriendly; + if (!isAlly && !((isVersusPlayer || isEnemy) && isCharmed)) continue; + + Vector offset = vector_sub(entity->pos, npc.pos); + if (vector_length(offset) >= reach * SPIN_HIT_REACH) continue; + Vector knock = vector_rotated(offset, npc.sprite.isFlipX ? SPIN_KNOCK_DEGREES : -SPIN_KNOCK_DEGREES); + if (vector_length(knock) > 0) knock = vector_resized(knock, SPIN_KNOCK); + if (entity->friction != 0) entity->AddVelocity_divided(knock, false); + float damage = isVersusPlayer || isEnemy ? SPIN_ENEMY_DAMAGE : SPIN_DAMAGE; + entity->TakeDamage(damage, DAMAGE_COUNTDOWN, EntityRef(&npc), SPIN_HIT_COUNTDOWN); + } + g_manager->sfxManager.SetAmbientSound(SOUND_ULTRA_GREED_SPINNING, 1, 1); +} + +// The long spin: drifting about in a circle toward a new spot every 30 frames, kicked off walls, a coin shot every 8 +// frames, for 120 frames less 60 by rage (or while the controller holds shoot left). +static bool ultra_greed_spin(Entity_NPC& npc, const UltraGreedControl& control, float rage) +{ + bool isSpinning = false; + + if (npc.i1 == 0) + { + npc.sprite.Play("SpinStart"); + ultra_greed_sound(SOUND_ULTRA_GREED_ROAR_2, TANTRUM_SOUND_DELAY); + if (npc.sprite.IsFinished()) npc.i1 = 1; + } + else if (npc.i1 == 1) + { + if (npc.stateFrame == 0 || npc.IsFrame(SPIN_SPOT_FRAMES, (int)npc.index)) + npc.targetPosition = g_game->room->GetRandomPosition(0); + npc.sprite.Play("SpinConstant"); + isSpinning = true; + + float circle = (float)npc.stateFrame / SPIN_CIRCLE_FRAMES * ((npc.index & 1) ? 1.0f : -1.0f) * TAU; + npc.AddVelocity_divided(vector_make(std::cos(circle) * SPIN_CIRCLE_PUSH, std::sin(circle) * SPIN_CIRCLE_PUSH), + false); + Vector drift = vector_resized(vector_sub(npc.targetPosition, npc.pos), 1); + if (control.isControlled) drift = control.move; + npc.AddVelocity_divided(drift, false); + if (npc.isCollidesWithGrid) + npc.AddVelocity_divided(vector_scale(npc.gridCollisionNormal, -SPIN_WALL_KICK * random_unit()), false); + + if (npc.stateFrame % SPIN_SHOT_FRAMES == 0) + { + ProjectileParams params; + params.variant = PROJECTILE_COIN; + params.heightModifier = COIN_SHOT_HEIGHT; + params.scale = COIN_SHOT_SCALE; + params.fallingAccelModifier = COIN_SHOT_FALL_ACCEL; + params.fallingSpeedModifier = COIN_SHOT_FALL_SPEED; + float angle = (float)npc.stateFrame * SPIN_SHOT_TURN * DEGREES_TO_RADIANS; + Vector velocity = vector_add( + vector_make(std::cos(angle) * UG_SPIN_SHOT_SPEED, std::sin(angle) * UG_SPIN_SHOT_SPEED), npc.velocity); + npc.FireProjectiles(npc.pos, velocity, PROJECTILES_SINGLE, params); + } + + bool isHeld = control.isControlled && npc.IsControllerActionPressed(ACTION_SHOOT_LEFT); + bool isOver = + !control.isControlled ? npc.stateFrame > (int)(UG_SPIN_FRAMES - rage * SPIN_RAGE_FRAMES) : !isHeld; + if (isOver) + { + npc.i1 = 2; + npc.stateFrame = 0; + } + npc.stateFrame++; + } + else if (npc.i1 == 2) + { + npc.sprite.Play("SpinEnd"); + if (npc.sprite.IsFinished()) + { + ultra_greed_state_set(npc, ULTRA_GREED_WALK); + npc.targetPosition = {}; + } + } + return isSpinning; +} + +// The spins: a single turn hitting from its fourth frame, or the long spin. Either hits while it spins. +static void ultra_greed_spin_update(Entity_NPC& npc, const UltraGreedControl& control, float rage) +{ + bool isSpinning = false; + + npc.friction *= UG_SPIN_FRICTION; + if (npc.state == ULTRA_GREED_SPIN) isSpinning = ultra_greed_spin(npc, control, rage); + if (npc.state == ULTRA_GREED_SPIN_ONCE) + { + npc.sprite.Play("SpinOnce"); + ultra_greed_sound(SOUND_ULTRA_GREED_ROAR_2, TANTRUM_SOUND_DELAY); + isSpinning = npc.sprite.GetFrame() > SPIN_ONCE_HIT_FRAME; + if (npc.sprite.IsFinished()) ultra_greed_state_set(npc, ULTRA_GREED_WALK); + } + if (isSpinning) ultra_greed_spin_hit(npc); +} + +// A ripple where he stomps. +static void ultra_greed_ripple(Entity_NPC& npc) +{ + shockwave_make(npc.pos, STOMP_RIPPLE, STOMP_RIPPLE, UG_STOMP_RIPPLE_FRAMES); +} + +// An Ultra Greed coin thrown out from a free spot, Greedier's bomb coins as pennies. +static Entity_NPC* ultra_coin_throw(Entity_NPC& npc, int variant) +{ + Room& room = *g_game->room; + Vector spot = room_free_pickup_position_find({.position = room.GetRandomPosition(0)}); + uint32_t seed = Random(); + float angle = random_unit() * RANDOM_HALF_TURN * 2; + + return dynamic_cast(g_game->Spawn({.position = spot, + .velocity = vector_make(std::cos(angle), std::sin(angle)), + .spawner = &npc, + .type = ENTITY_ULTRA_COIN, + .variant = variant, + .seed = seed})); +} + +// The stomps, faster with rage: each foot shakes the room, ripples and brings a Keeper (Greedier: two bomb pennies). +static void ultra_greed_stomps(Entity_NPC& npc, const UltraGreedRoom& scene, const UltraGreedControl& control, + bool isStomp, float rage) +{ + float speed = rage + 1; + + npc.sprite.Play("Tantrum"); + if (npc.stateFrame == 0) ultra_greed_sound(SOUND_ULTRA_GREED_ROAR_1, 2); + npc.stateFrame++; + npc.sprite.playbackSpeed = speed; + if (isStomp) + { + game_shake_screen(STOMPS_SHAKE); + npc.PlaySound(SOUND_FORESTBOSS_STOMPS, 1, 2, false, stomp_pitch()); + if (npc.variant == 0 && scene.keepers < KEEPERS_MAX) + g_game->Spawn({.position = vector_make(npc.pos.x, npc.size * KEEPER_DROP + npc.pos.y), + .spawner = &npc, + .type = ENTITY_KEEPER, + .seed = Random()}); + else if (npc.variant == ULTRA_GREEDIER_VARIANT) + for (int i = 0; i < GREEDIER_STOMP_COINS; i++) + if (Entity_NPC* coin = ultra_coin_throw(npc, COIN_BOMB)) + { + coin->subtype = ULTRA_COIN_PENNY_SUBTYPE; + coin->Update(); + } + ultra_greed_ripple(npc); + } + + float frame = npc.sprite.animState.file ? npc.sprite.animState.animFrame : -1; + bool isOver = control.isControlled ? !npc.IsControllerActionPressed(ACTION_PILL_CARD) + : npc.stateFrame > (int)(STOMPS_FRAMES / speed) && frame < speed; + if (isOver) + { + npc.state = ULTRA_GREED_WALK; + npc.stateFrame = 0; + npc.sprite.playbackSpeed = 1; + } + npc.friction *= UG_SLOW_FRICTION; +} + +// The jump's rise: on the target with a roar and gold, raining coin shots as he flies over (faster over 60 frames). +static void ultra_greed_jump_flight(Entity_NPC& npc) +{ + npc.AddVelocity(vector_scale(vector_normalized(vector_sub(npc.targetPosition, npc.pos)), UG_JUMP_PULL), false); + if (npc.IsFrame(JUMP_SHOT_FRAMES, 0)) + { + float ramp = std::clamp((float)npc.stateFrame / JUMP_SHOT_RAMP_FRAMES, 0.0f, 1.0f); + float speed = ramp * JUMP_SHOT_RAMP + JUMP_SHOT_SPEED; + ProjectileParams params; + params.heightModifier = JUMP_SHOT_HEIGHT; + params.fallingSpeedModifier = random_unit() * JUMP_SHOT_FALL_RANGE + JUMP_SHOT_FALL_SPEED; + params.fallingAccelModifier = JUMP_SHOT_FALL_ACCEL; + params.scale = COIN_SHOT_SCALE; + params.variant = PROJECTILE_COIN; + params.bulletFlags = PROJECTILE_EXPLODE; + Vector way = random_direction(); + npc.FireProjectiles(npc.pos, vector_scale(way, speed * random_unit()), PROJECTILES_SINGLE, params); + } + if (npc.IsFrame(1, 0)) + game_particles_spawn({.position = npc.pos, + .height = JUMP_SPARKLE_HEIGHT, + .speed = JUMP_SPARKLE_SPEED, + .count = JUMP_SPARKLES, + .variant = EFFECT_GOLD_PARTICLE}); + if (vector_length(vector_sub(npc.pos, npc.targetPosition)) < npc.size) npc.i1 = 2; + npc.stateFrame++; +} + +// The jump: up with a roar, over the target raining coins, and down with gold, a ripple and five crack waves. +static void ultra_greed_jump(Entity_NPC& npc) +{ + if (npc.i1 == 0) + { + npc.sprite.Play("JumpUp"); + if (npc.stateFrame == 0) npc.targetPosition = npc.GetPlayerTarget()->pos; + if (npc.sprite.IsEventTriggered("Jump")) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.entityGridCollisionClass = GRIDCOLL_NONE; + ultra_greed_sound(SOUND_BOSS_LITE_ROAR, 2); + npc.CreateGoldParticles(JUMP_GOLD); + game_shake_screen(JUMP_SHAKE); + } + if (npc.sprite.IsFinished("JumpUp")) npc.i1 = 1; + npc.stateFrame++; + } + if (npc.i1 == 1) ultra_greed_jump_flight(npc); + if (npc.i1 == 2) + { + npc.sprite.Play("JumpDown"); + if (npc.sprite.IsEventTriggered("Stomp")) + { + npc.entityCollisionClass = ENTCOLL_ALL; + npc.entityGridCollisionClass = GRIDCOLL_GROUND; + npc.CreateGoldParticles(LAND_GOLD); + ultra_greed_sound(SOUND_POT_BREAK, 2); + ultra_greed_sound(SOUND_FORESTBOSS_STOMPS, 2, stomp_pitch()); + ultra_greed_ripple(npc); + game_shake_screen(UG_LAND_SHAKE); + for (int i = 0; i < LAND_CRACKWAVES; i++) + { + auto* wave = static_cast(g_game->Spawn({.position = npc.pos, + .spawner = &npc, + .type = ENTITY_EFFECT, + .variant = EFFECT_CRACKWAVE, + .seed = Random()})); + wave->parent = &npc; + wave->rotation = (float)i * FULL_TURN_DEGREES / LAND_CRACKWAVES; + } + } + npc.stateFrame++; + if (npc.sprite.IsFinished("JumpDown")) + { + npc.i1 = 0; + npc.stateFrame = 0; + npc.state = ULTRA_GREED_IDLE; + } + } + npc.friction *= UG_JUMP_FRICTION; +} + +// Turning gold: gold flashes, and on Disappear a hundred gold bursts, a penny and the room turned to gold. +static void ultra_greed_turn_gold(Entity_NPC& npc) +{ + npc.sprite.Play("Death"); + npc.sprite.playbackSpeed = 1; + npc.CreateBling(); + if (npc.sprite.IsFinished()) npc.state = ULTRA_GREED_GOLD; + if (!npc.sprite.IsEventTriggered("Disappear")) return; + + ultra_greed_sound(SOUND_ULTRA_GREED_TURN_GOLD_2, 2); + ultra_greed_sound(SOUND_ULTRA_GREED_COIN_DESTROY, 2); + npc.entityCollisionClass = ENTCOLL_NONE; + npc.shadowSize = 0; + for (int i = 0; i < TURN_GOLD_BURSTS; i++) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit(); + Vector spot = vector_make(npc.size * std::cos(angle) * reach * TURN_GOLD_REACH + npc.pos.x, + npc.size * reach * std::sin(angle) * TURN_GOLD_REACH + npc.pos.y); + game_particles_spawn({.position = spot, + .height = (float)i * TURN_GOLD_BURST_STEP, + .speed = TURN_GOLD_BURST_SPEED, + .count = TURN_GOLD_BURST_PARTICLES, + .variant = EFFECT_GOLD_PARTICLE}); + } + g_game->Spawn({.position = npc.pos, + .velocity = vector_make(0, TURN_GOLD_PENNY_RISE), + .spawner = &npc, + .subType = COIN_PENNY, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = Random()}); + g_game->room->TurnGold(); +} + +// The slot machine's payout: one of its coins every so many frames until all are out, each key coin told the slot of +// the door it will open in turn. +static void ultra_greed_slots_pay(Entity_NPC& npc, const UltraGreedRoom& scene, const SlotPayout& payout, int throws) +{ + for (; throws > 0; throws--) + { + Entity_NPC* coin = ultra_coin_throw(npc, payout.coin); + if (!coin) continue; + int door = npc.stateFrame / payout.interval - 1; + if (payout.coin == COIN_KEY && door < (int)scene.doors.size()) + if (auto* doorNpc = dynamic_cast(scene.doors[door])) coin->i1 = doorNpc->i1; + coin->Update(); + } +} + +// The slot machine: pulled, spinning (shorter with rage), then the outcome's coins and its win. +static void ultra_greed_slots(Entity_NPC& npc, const UltraGreedRoom& scene, float rage) +{ + SFXManager& sfx = g_manager->sfxManager; + int next = ULTRA_GREED_SLOTS; + + if (npc.i1 == 0) + { + npc.sprite.Play("SlotStart"); + ultra_greed_sound(SOUND_ULTRA_GREED_PULL_SLOT, SLOTS_START_SOUND_DELAY); + if (npc.sprite.IsFinished()) + { + npc.i1 = 1; + npc.stateFrame = 0; + } + } + else if (npc.i1 == 1) + { + npc.sprite.Play("SlotSpinningFast"); + sfx.SetAmbientSound(SOUND_ULTRA_GREED_SLOT_SPIN_LOOP, 1, 1); + npc.stateFrame++; + if (npc.stateFrame > (int)(SLOTS_SPIN_FRAMES - rage * SLOTS_SPIN_RAGE)) + { + sfx.Stop(SOUND_ULTRA_GREED_SLOT_SPIN_LOOP); + ultra_greed_sound(SOUND_ULTRA_GREED_SLOT_STOP, SLOTS_SOUND_DELAY); + npc.i1 = 2; + npc.sprite.SetFrame("SlotSpinningOutcomes", (int)(Random() & (SLOTS_OUTCOMES - 1))); + npc.stateFrame = 0; + } + } + else if (npc.i1 == 2) + { + int outcome = npc.sprite.GetFrame(); + SlotPayout payout = (uint32_t)outcome < SLOT_PAYOUTS.size() ? SLOT_PAYOUTS[outcome] : SlotPayout{}; + int throws = 1; + int winFrames = 0; + + if (payout.coin == COIN_KEY) + { + payout.count = (int)scene.doors.size(); + if (npc.health < npc.maxHitPoints * SLOTS_LOW_HEALTH) throws = 2; + } + bool isWinning = payout.coin > 0; + if (isWinning) winFrames = (int)(SLOTS_WIN_FRAMES - rage * SLOTS_WIN_RAGE); + if (isWinning && npc.stateFrame < (int)SLOTS_WIN_FRAMES) + sfx.SetAmbientSound(SOUND_ULTRA_GREED_SLOT_WIN_LOOP, 1, 1); + else + { + sfx.Stop(SOUND_ULTRA_GREED_SLOT_WIN_LOOP); + ultra_greed_sound(SOUND_ULTRA_GREED_SLOT_WIN_LOOP_END, SLOTS_SOUND_DELAY); + } + if (npc.stateFrame == 0) ultra_greed_sound(SOUND_ULTRA_GREED_COINS_FALLING, SLOTS_SOUND_DELAY); + npc.stateFrame++; + bool isThrowFrame = npc.stateFrame % payout.interval == 0 && npc.stateFrame <= payout.count * payout.interval; + if (payout.coin != -1 && isThrowFrame) ultra_greed_slots_pay(npc, scene, payout, throws); + if (npc.stateFrame > payout.count * payout.interval && npc.stateFrame > winFrames) next = ULTRA_GREED_WALK; + } + if (next != npc.state) ultra_greed_state_set(npc, next); + npc.friction *= UG_SLOW_FRICTION; +} + +// The coin spit toward its target, in a spread drawn from i1's seed (or six boss shots), wider and exploding from +// Greedier. +static void ultra_greed_shoot(Entity_NPC& npc) +{ + static constexpr std::array SHOOT_ANIMATIONS = {"ShootLeft", "ShootUp", "ShootRight", + "ShootDown"}; + Vector aim = vector_sub(npc.targetPosition, npc.pos); + int direction = vector_to_direction(aim); + + if (direction >= 0) npc.sprite.Play(SHOOT_ANIMATIONS[direction]); + if (npc.i1 == 0) npc.i1 = (int)(Random() | 1); + + RNG rng; + rng.SetSeed((uint32_t)npc.i1, SHOT_RNG_SHIFT); + WeightedOutcomePicker picker; + for (int spread : SHOT_SPREADS) picker.AddOutcomeWeight(spread, SHOT_WEIGHT); + picker.AddOutcomeWeight(SHOT_BOSS, SHOT_WEIGHT); + int pattern = picker.PickOutcome(rng); + + if (npc.sprite.WasEventTriggered("Shoot")) + { + if (npc.stateFrame == 0) ultra_greed_sound(SOUND_ULTRA_GREED_SPIT, 2); + ProjectileParams params; + params.variant = PROJECTILE_COIN; + params.heightModifier = COIN_SHOT_HEIGHT; + params.scale = COIN_SHOT_SCALE; + if (npc.variant == ULTRA_GREEDIER_VARIANT) + { + params.spread *= GREEDIER_SPREAD; + params.bulletFlags |= PROJECTILE_EXPLODE; + } + if (npc.stateFrame == 0 && pattern == SHOT_BOSS) + npc.FireBossProjectiles(SHOT_BOSS_COUNT, npc.targetPosition, 0, params); + else if (npc.stateFrame == 0) + { + params.fallingAccelModifier = COIN_SHOT_FALL_ACCEL; + params.fallingSpeedModifier = COIN_SHOT_FALL_SPEED; + npc.FireProjectiles(npc.pos, vector_resized(aim, COIN_SHOT_SPEED), (ProjectilesMode)pattern, params); + } + npc.stateFrame++; + } + if (npc.sprite.IsFinished()) ultra_greed_state_set(npc, ULTRA_GREED_IDLE); + npc.friction *= UG_SLOW_FRICTION; +} + +// Whether a foot is down on this frame of the walk cycle, when he moves at full pace. +static bool ultra_greed_is_stepping(Entity_NPC& npc) +{ + if (!npc.sprite.animState.file) return false; + int frame = npc.sprite.GetFrame(); + bool isStepping = frame >= 0 && frame <= STEP_FIRST_END; + + if (!isStepping) isStepping = frame >= STEP_SECOND_START && frame <= STEP_SECOND_END; + return isStepping || frame >= STEP_LAST_START; +} + +// Where the walk heads: the coin worth the most for its distance, else a random spot, redrawn at least 180 away. +static Vector ultra_greed_walk_goal(Entity_NPC& npc, bool& isCoinGoal) +{ + Room& room = *g_game->room; + float best = WALK_FAR_DISTANCE; + Vector goal = npc.pos; + + for (Entity* coin : entity_query(ENTITY_PICKUP, PICKUP_COIN)) + { + auto* pickup = dynamic_cast(coin); + if (!pickup) continue; + float score = vector_length_squared(vector_sub(npc.pos, coin->pos)) / (float)pickup->GetCoinValue(); + if (score >= best || pickup->entityCollisionClass == ENTCOLL_NONE || pickup->isDead) continue; + isCoinGoal = true; + goal = coin->pos; + npc.targetPosition = {}; + best = score; + } + if (isCoinGoal) return goal; + + float margin = npc.size * npc.sizeMulti.x; + if (vector_is_zero(npc.targetPosition)) + { + npc.targetPosition = room.GetRandomPosition(margin); + for (int i = 0; i < WALK_SPOT_TRIES; i++) + { + Vector spot = room.GetRandomPosition(margin); + float spotDistance = vector_distance(spot, npc.pos); + if (vector_distance(npc.targetPosition, npc.pos) >= spotDistance) continue; + npc.targetPosition = spot; + if (spotDistance > WALK_SPOT_FAR) break; + } + } + return npc.targetPosition; +} + +// The way along the room's path toward a goal, as the pathfinder would push him, his own motion kept. +static Vector ultra_greed_path_way(Entity_NPC& npc, Vector goal) +{ + Vector velocity = npc.velocity; + float friction = npc.friction; + + npc.pathfinder.FindGridPath(goal, WALK_PATH_SPEED, WALK_PATH_THRESHOLD, DIRECT_PATH_FAR); + Vector way = vector_sub(npc.velocity, velocity); + npc.velocity = velocity; + npc.friction = friction; + return vector_length(way) > 0 ? vector_normalized(way) : way; +} + +// The walk's animation by the way he heads: sideways (flipped to the left), up, down or standing, the cycle's frame +// kept between them and its pace matching his. +static void ultra_greed_walk_animate(Entity_NPC& npc, Vector way, float rageSpeed, float pace) +{ + ANM2& sprite = npc.sprite; + float frame = 0; + + if (sprite.IsPlaying() && (sprite.GetAnimation() == "Walking" || sprite.GetAnimation() == "WalkingUp" || + sprite.GetAnimation() == "WalkingDown")) + frame = sprite.animState.animFrame; + if (sprite.IsPlaying("DashStop")) + { + sprite.playbackSpeed = 1; + return; + } + + int direction = std::abs(way.x) <= std::abs(way.y) ? (way.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP) + : (way.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT); + float push = vector_length(way); + if (push == 0) + { + sprite.playbackSpeed = 1; + sprite.Play("Idle"); + return; + } + sprite.Play(direction == DIRECTION_UP ? "WalkingUp" : direction == DIRECTION_DOWN ? "WalkingDown" : "Walking"); + if (sprite.animState.file) sprite.animState.SetFrameFloat(frame); + if (direction == DIRECTION_LEFT || direction == DIRECTION_RIGHT) sprite.isFlipX = way.x < 0; + sprite.playbackSpeed = push * rageSpeed * WALK_PLAYBACK_SCALE * pace; +} + +// Standing, walking and dashing: footfalls shake the room, and he heads for the walk's goal (the controller's way, or +// the dash's), faster with rage, at full pace on his steps. Reaching a spot he stands. +static int ultra_greed_walk(Entity_NPC& npc, const UltraGreedControl& control, float rage, bool isStomp) +{ + int next = npc.state; + bool isDash = npc.state == ULTRA_GREED_DASH; + float pace = npc.variant == ULTRA_GREEDIER_VARIANT ? GREEDIER_PACE : 1; + float acceleration = pace * WALK_ACCELERATION; + float speedCap = control.isControlled && !isDash ? control.push * WALK_SPEED_CAP : WALK_SPEED_CAP; + + if (isStomp) + { + game_shake_screen(WALK_STOMP_SHAKE); + ultra_greed_stomp_sound(npc, SOUND_FORESTBOSS_STOMPS, stomp_pitch()); + } + if (!ultra_greed_is_stepping(npc)) + { + acceleration *= WALK_STEP_SLOW; + speedCap *= WALK_CAP_SLOW; + npc.friction *= WALK_FRICTION_SLOW; + } + else + npc.friction *= UG_WALK_FRICTION; + + float rageSpeed = rage * WALK_RAGE_SPEED + 1; + float maxSpeed = (isDash ? DASH_SPEED_SCALE : rageSpeed) * speedCap; + bool isCoinGoal = false; + Vector goal = npc.state == ULTRA_GREED_WALK ? ultra_greed_walk_goal(npc, isCoinGoal) : npc.pos; + Vector way = control.move; + + if (!control.isControlled) + { + way = {}; + Vector toGoal = vector_sub(goal, npc.pos); + float distance = vector_length(vector_make(toGoal.x / npc.sizeMulti.x, toGoal.y / npc.sizeMulti.y)); + if (distance > npc.size) + way = ultra_greed_path_way(npc, goal); + else if (!isCoinGoal && npc.state == ULTRA_GREED_WALK) + { + npc.targetPosition = {}; + next = ULTRA_GREED_IDLE; + } + } + if (isDash) + way = vector_length(npc.targetPosition) > 0 ? vector_normalized(npc.targetPosition) : npc.targetPosition; + + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(way, npc.speedMultiplier * acceleration / npc.friction)); + float speed = vector_length(npc.velocity); + if (speed > maxSpeed && speed > 0) npc.velocity = vector_scale(npc.velocity, maxSpeed / speed); + ultra_greed_walk_animate(npc, way, rageSpeed, pace); + return next; +} + +// Adds an attack's weight, a new attack only when it has any. +static void attack_weight_add(WeightedOutcomePicker& picker, int attack, int weight) +{ + bool isListed = std::ranges::any_of(picker.outcomes, [attack](auto& outcome) { return outcome.id == attack; }); + if (isListed || weight > 0) picker.AddOutcomeWeight(attack, weight); +} + +// Ultra Greed's own attacks: the slots (fewer coins out, fewer minions), the dash at the target when it lines up with +// him, the single spin up close and the long spin. +static void ultra_greed_attacks_weigh(Entity_NPC& npc, const UltraGreedRoom& scene, float rage, + WeightedOutcomePicker& picker, UltraGreedPlan& plan) +{ + Room& room = *g_game->room; + Entity* target = npc.GetPlayerTarget(); + int tantrum = (int)(rage * WEIGHT_TANTRUM_RAGE + WEIGHT_TANTRUM); + int slots = scene.coinsOut < SLOTS_COIN_LIMIT ? (int)(rage * WEIGHT_SLOTS_RAGE + WEIGHT_SLOTS) : 0; + + if (scene.minions < FEW_MINIONS) slots += WEIGHT_FEW_MINIONS; + attack_weight_add(picker, ULTRA_GREED_SLOTS, slots); + + Vector lead = vector_add(npc.CalcTargetPosition(0), vector_scale(target->velocity, random_unit() * DASH_LEAD)); + Vector aim = vector_sub(room.GetClampedPositionImpl(lead, DASH_TARGET_MARGIN, DASH_TARGET_MARGIN, + DASH_TARGET_MARGIN, DASH_TARGET_MARGIN), + npc.pos); + if (std::abs(aim.x) < npc.size * npc.sizeMulti.x || std::abs(aim.y) < npc.size * npc.sizeMulti.y) + plan.dashWay = vector_cardinal(aim); + else + tantrum = 0; + attack_weight_add(picker, ULTRA_GREED_TANTRUM, tantrum); + + Vector apart = vector_make(npc.pos.x / npc.sizeMulti.x - target->pos.x / npc.sizeMulti.x, + npc.pos.y / npc.sizeMulti.y - target->pos.y / npc.sizeMulti.y); + int spinOnce = + vector_length(apart) < npc.size * SPIN_ONCE_REACH ? (int)(rage * WEIGHT_SPIN_ONCE_RAGE + WEIGHT_SPIN_ONCE) : 0; + attack_weight_add(picker, ULTRA_GREED_SPIN_ONCE, spinOnce); + attack_weight_add(picker, ULTRA_GREED_SPIN, (int)(rage * WEIGHT_SPIN_RAGE + WEIGHT_SPIN)); +} + +// Draws his next move every 15 frames: his own attacks, the coin spit from mid range, the stomps (more with few +// minions), walking on (less with few minions, much more while coins worth six lie about), and Greedier's smashes +// (twice, more with minions) and jump by the target's distance. +static int ultra_greed_attack_draw(Entity_NPC& npc, const UltraGreedRoom& scene, float rage, UltraGreedPlan& plan) +{ + WeightedOutcomePicker picker; + bool isGreedier = npc.variant == ULTRA_GREEDIER_VARIANT; + bool isFewMinions = scene.minions < FEW_MINIONS; + bool isRichFloor = scene.coinWorth >= COINS_WORTH_WALKING; + float distance = vector_distance(npc.GetPlayerTarget()->pos, npc.pos); + + if (npc.variant == 0) ultra_greed_attacks_weigh(npc, scene, rage, picker, plan); + if (distance > SHOOT_RANGE_MIN && distance < SHOOT_RANGE_MAX && (npc.variant == 0 || isGreedier)) + { + int shoot = isGreedier ? (int)(rage * WEIGHT_GREEDIER_SHOOT_RAGE + WEIGHT_GREEDIER_SHOOT) + : (int)(rage * WEIGHT_SHOOT_RAGE + WEIGHT_SHOOT); + attack_weight_add(picker, ULTRA_GREED_SHOOT, shoot); + } + + int stomps = isGreedier ? (int)(rage * WEIGHT_GREEDIER_STOMPS_RAGE + WEIGHT_GREEDIER_STOMPS) + : (int)(rage * WEIGHT_STOMPS_RAGE + WEIGHT_STOMPS); + int walk = (int)(WEIGHT_WALK - rage * (isGreedier ? WEIGHT_GREEDIER_WALK_RAGE : WEIGHT_WALK_RAGE)); + if (isFewMinions) stomps += WEIGHT_FEW_MINIONS; + if (isFewMinions && !isGreedier) walk -= WEIGHT_WALK_FEW_MINIONS; + if (isRichFloor) walk += WEIGHT_WALK_COINS; + if (npc.variant == 0 || isGreedier) + { + attack_weight_add(picker, ULTRA_GREED_STOMPS, stomps); + attack_weight_add(picker, npc.state, walk); + } + if (isGreedier) + { + float reach = npc.size * npc.sizeMulti.x; + float closeness = std::clamp((distance - reach) / SMASH_RANGE, 0.0f, 1.0f); + int smash = (int)(UG_WEIGHT_SMASH - closeness * WEIGHT_SMASH_DROP); + picker.AddOutcomeWeight(ULTRA_GREED_SMASH, smash); + picker.AddOutcomeWeight(ULTRA_GREED_SMASH_TWICE, + scene.minions > 0 ? smash * WEIGHT_SMASH_TWICE_MINIONS : smash); + float farness = std::clamp((distance - reach) / UG_JUMP_RANGE, 0.0f, 1.0f); + picker.AddOutcomeWeight(ULTRA_GREED_JUMP, (int)(farness * WEIGHT_JUMP_RANGE + WEIGHT_JUMP)); + } + + RNG rng = ATTACK_DRAW_RNG; + rng._seed = Random() | 1; + return picker.PickOutcome(rng); +} + +// The controller's attack: the dash along the stick (shoot right), the single spin (shoot down), the long spin (shoot +// left), the coin spit (shoot up), the slots (bomb), the stomps (card) or the guard (drop). +static int ultra_greed_controlled_attack(Entity_NPC& npc, const UltraGreedControl& control, int next, + UltraGreedPlan& plan) +{ + auto isPressed = [&npc](ButtonAction action) { + return input_is_action_pressed(action, npc.controllerID, &npc); + }; + + if (isPressed(ACTION_SHOOT_RIGHT) && control.push > HALF) + { + plan.dashWay = vector_cardinal(control.move); + next = ULTRA_GREED_TANTRUM; + } + if (isPressed(ACTION_SHOOT_DOWN)) next = ULTRA_GREED_SPIN_ONCE; + if (isPressed(ACTION_SHOOT_LEFT)) next = ULTRA_GREED_SPIN; + if (isPressed(ACTION_SHOOT_UP)) next = ULTRA_GREED_SHOOT; + if (isPressed(ACTION_BOMB)) next = ULTRA_GREED_SLOTS; + if (isPressed(ACTION_PILL_CARD)) next = ULTRA_GREED_STOMPS; + if (isPressed(ACTION_DROP)) next = ULTRA_GREED_GUARD; + return next; +} + +// The dash's dust behind him and its end: on a wall held for 6 frames, or once 90 ticks have passed. +static int ultra_greed_dash(Entity_NPC& npc, int next) +{ + for (int i = 0; i < DASH_DUST; i++) + { + uint32_t seed = Random(); + Vector back = vector_scale(vector_length(npc.velocity) > 0 ? vector_normalized(npc.velocity) : npc.velocity, + DASH_DUST_BACK); + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float spread = random_unit(); + Vector velocity = vector_add(vector_make(std::cos(angle) * spread, std::sin(angle) * spread), back); + Entity* dust = g_game->Spawn({.position = npc.pos, + .velocity = velocity, + .type = ENTITY_EFFECT, + .variant = EFFECT_DARK_BALL_SMOKE_PARTICLE, + .seed = seed}); + dust->Update(); + dust->sprite.scale = vector_make(DASH_DUST_SCALE, DASH_DUST_SCALE); + dust->sprite.offset = vector_make(0, DASH_DUST_LIFT - random_unit() * DASH_DUST_LIFT_RANGE); + if (npc.targetPosition.y < 0) dust->renderZOffset = DASH_DUST_RENDER_Z; + } + + npc.projectileDelay += npc_ticks_get(npc); + if (npc.projectileDelay > DASH_TICKS) npc.stateFrame = DASH_TIMED_OUT; + if (!npc.isCollidesWithGrid && npc.stateFrame < DASH_TIMED_OUT) + { + npc.stateFrame = 0; + return next; + } + if (++npc.stateFrame < DASH_WALL_FRAMES) return next; + npc.targetPosition = {}; + npc.sprite.Play("DashStop"); + return ULTRA_GREED_IDLE; +} + +// Moves on to the next state: standing turns to walking after 30 frames, the dash aims its way, the coin spit at the +// target, and every other new state but the walk's, guard's, spin's and smash's faces right. +static void ultra_greed_transition(Entity_NPC& npc, int next, const UltraGreedPlan& plan) +{ + static constexpr std::array KEEPS_FACING = {ULTRA_GREED_GUARD, ULTRA_GREED_IDLE, ULTRA_GREED_WALK, + ULTRA_GREED_SPIN_ONCE, ULTRA_GREED_SPIN, ULTRA_GREED_SMASH, + ULTRA_GREED_SMASH_TWICE}; + bool isIdleOver = npc.state == ULTRA_GREED_IDLE && ++npc.stateFrame > UG_IDLE_FRAMES; + + if (isIdleOver) + next = ULTRA_GREED_WALK; + else if (next == npc.state) + return; + else if (next == ULTRA_GREED_TANTRUM) + npc.targetPosition = plan.dashWay; + else if (next == ULTRA_GREED_SHOOT) + npc.targetPosition = npc.GetPlayerTarget()->pos; + + bool isFacingKept = isIdleOver || std::ranges::find(KEEPS_FACING, next) != KEEPS_FACING.end(); + ultra_greed_state_set(npc, next); + npc.sprite.playbackSpeed = 1; + if (!isFacingKept) npc.sprite.isFlipX = false; +} + +// Standing, walking and dashing, and what comes next: the drawn attack (guarding while six minions are out), the +// controller's, or the dash's end. +static void ultra_greed_ground_update(Entity_NPC& npc, const UltraGreedRoom& scene, const UltraGreedControl& control, + float rage, bool isStomp) +{ + UltraGreedPlan plan; + int next = ultra_greed_walk(npc, control, rage, isStomp); + bool isGrounded = npc.state == ULTRA_GREED_WALK || npc.state == ULTRA_GREED_IDLE; + + if (!control.isControlled && isGrounded) + { + if (npc.IsFrame(ATTACK_DRAW_FRAMES, 0)) next = ultra_greed_attack_draw(npc, scene, rage, plan); + if (scene.minions >= GUARD_MINIONS) next = ULTRA_GREED_GUARD; + } + else if (isGrounded) + next = ultra_greed_controlled_attack(npc, control, next, plan); + else if (npc.state == ULTRA_GREED_DASH) + next = ultra_greed_dash(npc, next); + ultra_greed_transition(npc, next, plan); +} + +// Greedier's break out of Ultra Greed's gold: gold bursts as it starts and as he breaks (with a smash), held still +// and unhurt until the animation ends. +static void ultra_greedier_break_update(Entity_NPC& npc) +{ + if (npc.sprite.IsEventTriggered("StartGibs")) + { + npc.CreateGoldParticles(BREAK_GOLD_START); + ultra_greed_sound(SOUND_POT_BREAK, 2, BREAK_PITCH); + ultra_greed_sound(SOUND_ULTRA_GREED_TURN_GOLD_1, 2); + } + if (npc.sprite.IsEventTriggered("BreakGibs")) + { + npc.CreateGoldParticles(BREAK_GOLD); + ultra_greed_sound(SOUND_ULTRA_GREED_COIN_DESTROY, 2); + ultra_greed_sound(SOUND_ULTRA_GREED_ROAR_1, 2, BREAK_PITCH); + ultra_greed_smash(npc, vector_make(npc.pos.x, npc.pos.y + SMASH_DROP)); + } +} + +// Held still, whole and unhurt where he stands (turning gold or breaking free). +static void ultra_greed_hold_still(Entity_NPC& npc) +{ + npc.isDead = false; + npc.RemoveStatusEffects(); + npc.AddEntityFlags(ULTRA_GREED_STILL_FLAGS); + npc.health = npc.maxHitPoints; + npc.isInvincible = true; + npc.collisionDamage = 0; + npc.SetSize(npc.size, vector_make(ULTRA_GREED_WIDTH, ULTRA_GREED_HEIGHT), npc.config->gridCollisionPoints); + npc.velocity = {}; + npc.pos = npc.targetPosition; + npc.stateFrame++; + npc.friction *= HANGING_FRICTION; +} + +// Breaking free, he fights on as Greedier once the animation ends, with his config's contact damage. +static void ultra_greedier_break_free(Entity_NPC& npc) +{ + npc.entityCollisionClass = ENTCOLL_ALL; + ultra_greed_hold_still(npc); + if (npc.sprite.IsPlaying()) return; + + npc.ClearEntityFlags(ULTRA_GREED_BREAK_CLEARED); + npc.health = npc.maxHitPoints; + npc.isInvincible = false; + npc.state = ULTRA_GREED_IDLE; + npc.stateFrame = 0; + npc.collisionDamage = g_manager->entityConfig.GetEntity(npc.type, npc.variant, 0)->collisionDamage; +} + +// Turned gold he stays put, his hit points bar hidden. On Greedier (and hard) Ultra Greed then breaks free as +// Greedier, with Greedier's shield (a long break the first time he is met). +static void ultra_greed_gold_hold(Entity_NPC& npc, float greedierShield) +{ + if (npc.stateFrame == 0) + { + ultra_greed_sound(SOUND_ULTRA_GREED_DEATH_SCREAM, 2); + ultra_greed_sound(SOUND_ULTRA_GREED_TURN_GOLD_1, 2); + ultra_greed_sound(SOUND_ULTRA_GREED_TURN_GOLD_2, 2); + ultra_greed_sound(SOUND_ULTRA_GREED_ROAR_1, 2, TURN_GOLD_LAST_PITCH); + } + if (npc.variant == 0) npc.entityCollisionClass = ENTCOLL_ALL; + npc.AddEntityFlags(FLAG_HIDE_HP_BAR); + ultra_greed_hold_still(npc); + + Difficulty difficulty = g_game->difficulty; + bool isBreaking = difficulty == DIFFICULTY_GREEDIER || difficulty == DIFFICULTY_HARD; + if (npc.variant != 0 || npc.sprite.IsPlaying() || !isBreaking) return; + + int encounters = + g_manager->persistentGameData.GetBestiaryEncounterCount(ENTITY_ULTRA_GREED, ULTRA_GREEDIER_VARIANT); + npc.velocity = {}; + npc.Morph(ENTITY_ULTRA_GREED, ULTRA_GREEDIER_VARIANT, 0, -1); + npc.shieldStrength = greedierShield; + npc.shieldFrames = ULTRA_GREED_SHIELD_FRAMES; + npc.state = ULTRA_GREED_BREAK_FREE; + npc.stateFrame = 0; + if (encounters == 0) log_printf(LOG_INFO, "First UG+ encounter"); + npc.sprite.Play(encounters == 0 ? "BreakFreeLong" : "BreakFreeShort"); +} + +// His collision points break the rocks they press on, bridging the pit beyond each the way he faces it. +static void ultra_greed_rocks_crush(Entity_NPC& npc) +{ + Room& room = *g_game->room; + + for (Vector point : npc.collisionPoints) + { + Vector at = vector_add(vector_scale(point, COLLISION_POINT_REACH), npc.pos); + int cell = room.GetGridIndex(at); + if (cell < 0) continue; + + GridEntity* grid = cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + uint32_t collision = room.GetGridCollision(cell); + bool isSolid = collision == COLLISION_SOLID || collision == COLLISION_OBJECT; + if (!isSolid || !grid || grid->collisionClass != COLLISION_SOLID) continue; + if (!grid->Destroy(false, EntityRef(&npc))) continue; + + Vector rock = room.GetGridPosition(grid->gridIndex); + Vector beyond = vector_add(rock, vector_scale(vector_cardinal(vector_sub(rock, npc.pos)), GRID_CELL_SIZE)); + int pitCell = room.GetGridIndex(beyond); + if (pitCell < 0) continue; + room_bridge_make(pitCell < ROOM_GRID_CELLS ? room.gridEntities[pitCell] : nullptr, grid); + } +} + +// A footfall's dust: a footprint, Greedier's gold, 16 puffs kicked up and one time in two a rock particle. +static void ultra_greed_footfall(Entity_NPC& npc, const NullFrame& foot) +{ + Vector offset = vector_make(foot.pos.x * (npc.sprite.isFlipX ? -1.0f : 1.0f), foot.pos.y); + float angle = random_unit() * RANDOM_HALF_TURN * 2; + float reach = random_unit(); + Vector scatter = vector_make(std::cos(angle) * reach * FOOT_SCATTER + offset.x / FOOT_SCALE, + reach * std::sin(angle) * FOOT_SCATTER + offset.y / FOOT_SCALE); + Vector footSpot = vector_add(offset, npc.pos); + + g_game->Spawn( + {.position = footSpot, .type = ENTITY_EFFECT, .variant = EFFECT_ULTRA_GREED_FOOTPRINT, .seed = Random()}); + if (npc.variant == ULTRA_GREEDIER_VARIANT) + game_particles_spawn({.position = footSpot, + .height = 0, + .speed = FOOT_GOLD_SPEED, + .count = FOOT_GOLD, + .variant = EFFECT_GOLD_PARTICLE}); + for (int i = 0; i < FOOT_PUFFS; i++) + { + float puffAngle = random_unit() * RANDOM_HALF_TURN * 2; + float puffReach = random_unit(); + float kickX = std::cos(puffAngle) * puffReach * FOOT_PUFF_SPEED; + float kickY = std::abs(puffReach * std::sin(puffAngle) * FOOT_PUFF_SPEED); + uint32_t seed = Random(); + Entity* puff = g_game->Spawn({.position = vector_make(scatter.x + kickX + npc.pos.x, kickY + npc.pos.y), + .velocity = vector_make(kickX + npc.velocity.x * FOOT_VELOCITY_SHARE, + kickY + npc.velocity.y * FOOT_VELOCITY_SHARE), + .type = ENTITY_EFFECT, + .variant = EFFECT_DARK_BALL_SMOKE_PARTICLE, + .seed = seed}); + puff->Update(); + puff->renderZOffset = FOOT_PUFF_RENDER_Z; + puff->sprite.offset = vector_make(0, offset.y); + puff->SetColor(FOOT_PUFF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + if (Random() & 1) return; + + uint32_t seed = Random(); + Vector base = vector_make(npc.velocity.x, npc.velocity.y + FOOT_ROCK_LIFT); + float rockAngle = random_unit() * RANDOM_HALF_TURN * 2; + Entity* rock = g_game->Spawn({.position = vector_add(scatter, npc.pos), + .velocity = vector_make(std::cos(rockAngle) + base.x, std::sin(rockAngle) + base.y), + .type = ENTITY_EFFECT, + .variant = EFFECT_ROCK_PARTICLE, + .seed = seed}); + rock->Update(); +} + +// What every state ends with: Greedier's gold and break, the gold hold, crushed rocks, the footfalls' dust, the spin +// sound fading out, and the slot machine's loops stopped. +static void ultra_greed_tail(Entity_NPC& npc, bool isLeftStomp, bool isRightStomp, float greedierShield) +{ + SFXManager& sfx = g_manager->sfxManager; + + if (npc.variant == ULTRA_GREEDIER_VARIANT) + { + npc.CreateBling(); + ultra_greedier_break_update(npc); + if (npc.state == ULTRA_GREED_BREAK_FREE) ultra_greedier_break_free(npc); + } + if (npc.state == ULTRA_GREED_TURN_GOLD || npc.state == ULTRA_GREED_GOLD) ultra_greed_gold_hold(npc, greedierShield); + ultra_greed_rocks_crush(npc); + if (isLeftStomp || isRightStomp) + { + const NullFrame* feet[] = {npc.sprite.GetNullFrame("Foot1"), npc.sprite.GetNullFrame("Foot2")}; + if (isLeftStomp && feet[0]) ultra_greed_footfall(npc, *feet[0]); + if (isRightStomp && feet[1]) ultra_greed_footfall(npc, *feet[1]); + } + + bool isSpin = npc.state == ULTRA_GREED_SPIN_ONCE || npc.state == ULTRA_GREED_SPIN; + if (sfx.IsPlaying(SOUND_ULTRA_GREED_SPINNING) && !isSpin) + sfx.SetAmbientSound(SOUND_ULTRA_GREED_SPINNING, + sfx.GetAmbientSoundVolume(SOUND_ULTRA_GREED_SPINNING) - SPIN_SOUND_FADE, 1); + if (npc.state != ULTRA_GREED_SLOTS) + { + sfx.Stop(SOUND_ULTRA_GREED_SLOT_SPIN_LOOP); + sfx.Stop(SOUND_ULTRA_GREED_SLOT_WIN_LOOP); + } +} + +// The rage's red glow. +static void ultra_greed_glow(Entity_NPC& npc, float rage) +{ + ColorMod glow = ULTRA_GREED_RAGE_COLOR; + + glow._colorize[3] = rage; + npc.color = glow; + npc.SetColor(glow, 1, 0, false, true); +} + +// (part of 006e8ae0) A coin Ultra Greed or Bumbino walks into is theirs: it heals Ultra Greed by its worth, adds to +// Bumbino's hoard (i2), and either forgets where it wandered. Anything else collides as usual. +bool greed_coin_collect(Entity_Pickup& coin, Entity* collector) +{ + Entity* owner = collector->to_npc_or_coop_player(); + auto* npc = dynamic_cast(owner); + + if (!owner) return false; + if (!npc) return true; + if (npc->type == ENTITY_ULTRA_GREED) + ultra_greed_heal(*npc, coin.GetCoinValue()); + else if (npc->type == ENTITY_BUMBINO) + npc->i2 += coin.GetCoinValue(); + if (npc->type == ENTITY_ULTRA_GREED || npc->type == ENTITY_BUMBINO) npc->pathfinder.ResetMovementTarget(); + return true; +} + +// 0059edb0 NpcAI::ENTITY_ULTRA_GREED: Ultra Greed (and Greedier) hangs until he drops into the fight, then walks to +// the coins, pulls his slot machine, dashes, spins, spits coins and stomps, guarding while his minions are many and +// raging as his health drops. Killed, he turns to gold (on Greedier breaking out as Greedier). +void npc_ultra_greed_update(Entity_NPC& npc) +{ + if (npc.variant == ULTRA_GREEDIER_VARIANT && npc.pendingDamage > 0) + npc.CreateGoldParticles( + (uint32_t)std::ceil(std::clamp(npc.pendingDamage / GOLD_SHED_DAMAGE, 0.0f, 1.0f) * GOLD_SHED_MAX)); + UltraGreedRoom scene = ultra_greed_room_read(); + bool isTough = ultra_greed_is_tough(); + float greedierShield = isTough ? ULTRA_GREEDIER_SHIELD_TOUGH : ULTRA_GREEDIER_SHIELD; + float shield = npc.variant == ULTRA_GREEDIER_VARIANT ? greedierShield + : isTough ? ULTRA_GREED_SHIELD_TOUGH + : ULTRA_GREED_SHIELD; + + if (npc.state == NPC_STATE_INIT) return ultra_greed_init(npc, scene, shield); + if (npc.isDead && npc.state != ULTRA_GREED_TURN_GOLD && npc.state != ULTRA_GREED_GOLD) ultra_greed_gold_start(npc); + + bool isAnimated = npc.sprite.animState.file; + bool isBothStomp = isAnimated && npc.sprite.IsEventTriggered("Stomp"); + bool isLeftStomp = isBothStomp || (isAnimated && npc.sprite.IsEventTriggered("Stomp1")); + bool isRightStomp = isBothStomp || (isAnimated && npc.sprite.IsEventTriggered("Stomp2")); + UltraGreedControl control = ultra_greed_control_read(npc); + + bool isShielding = + npc.state == ULTRA_GREED_GUARD || npc.state == ULTRA_GREED_SLOTS || npc.state == ULTRA_GREED_SPIN; + if (isShielding) + npc.shieldStrength = shield * 2; + else + { + if (npc.variant != ULTRA_GREEDIER_VARIANT) npc.shieldStrength = shield; + if (npc.i2 > 0 && npc.IsFrame(RAGE_DECAY_FRAMES, (int)npc.index)) npc.i2--; + } + float rage = ultra_greed_rage(npc); + ultra_greed_glow(npc, rage); + + switch (npc.state) + { + case ULTRA_GREED_HANGING: + ultra_greed_hanging(npc, isLeftStomp || isRightStomp); + break; + case ULTRA_GREED_IDLE: + case ULTRA_GREED_WALK: + case ULTRA_GREED_DASH: + ultra_greed_ground_update(npc, scene, control, rage, isLeftStomp || isRightStomp); + break; + case ULTRA_GREED_TANTRUM: + ultra_greed_tantrum(npc); + break; + case ULTRA_GREED_SMASH: + case ULTRA_GREED_SMASH_TWICE: + ultra_greed_smash_update(npc); + break; + case ULTRA_GREED_GUARD: + ultra_greed_guard(npc, scene, control); + break; + case ULTRA_GREED_SPIN_ONCE: + case ULTRA_GREED_SPIN: + ultra_greed_spin_update(npc, control, rage); + break; + case ULTRA_GREED_SHOOT: + ultra_greed_shoot(npc); + break; + case ULTRA_GREED_SLOTS: + ultra_greed_slots(npc, scene, rage); + break; + case ULTRA_GREED_STOMPS: + ultra_greed_stomps(npc, scene, control, isLeftStomp || isRightStomp, rage); + break; + case ULTRA_GREED_JUMP: + ultra_greed_jump(npc); + break; + case ULTRA_GREED_TURN_GOLD: + ultra_greed_turn_gold(npc); + break; + case ULTRA_GREED_GOLD: + npc.sprite.Play("Final"); + npc.isCanShutDoors = false; + npc.CreateBling(); + break; + default: + break; + } + ultra_greed_tail(npc, isLeftStomp, isRightStomp, greedierShield); +} diff --git a/src/npc_vis.cpp b/src/npc_vis.cpp index 0d7f556..81a8926 100644 --- a/src/npc_vis.cpp +++ b/src/npc_vis.cpp @@ -16,7 +16,6 @@ constexpr int DOUBLE_VIS = 1; constexpr int CHUBBER = 2; constexpr int SCARRED_DOUBLE_VIS = 3; -constexpr int CHUBBER_WORM = 22; constexpr int SUPER_GLUTTONY = 1; constexpr int TYPE_GLUTTONY = 49; constexpr int TYPE_VIS_VERSA = 836; diff --git a/src/npc_vis_fatty.cpp b/src/npc_vis_fatty.cpp index 721a9c0..f47ed9b 100644 --- a/src/npc_vis_fatty.cpp +++ b/src/npc_vis_fatty.cpp @@ -6,9 +6,7 @@ #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; diff --git a/src/path_finder.cpp b/src/path_finder.cpp index 99c7134..1e95626 100644 --- a/src/path_finder.cpp +++ b/src/path_finder.cpp @@ -388,8 +388,7 @@ void PathFinder::FindGridPath(const Vector& position, float speed, int pathMarke Vector targetCenter = room.GetGridPosition(room.GetGridIndex(position)); int threshold = isFriendly || isFamiliar ? GRID_PATH_FREED : 0; if (entity->entityGridCollisionClass == GRIDCOLL_WALLS) hasDirectPath = true; - else if (canCrushRocks) - reconstruction_missing("Room::CheckLine 007f0df0: the rocks a rock crusher sees through"); + // A rock crusher's flag goes to CheckLine's walls switch, which the ground mode never reads. else hasDirectPath = room_check_line(ownCenter, targetCenter, LINE_MODE_GROUND, threshold); } @@ -793,12 +792,6 @@ void PathFinder::MoveRandomlyBoss(StatusMode mode) } } -// 007e6b90 -void PathFinder::update_chase_movement() -{ - reconstruction_missing("PathFinder::update_chase_movement 007e6b90"); -} - // 007e7070 Whether the owner can walk to a position: a flood from its cell over the walkable cells (and poop, when // asked) reaches the owner's cell within half the room's cells. An owner standing in a solid cell cannot. bool PathFinder::HasPathToPos(const Vector& position, bool isIgnorePoop) diff --git a/src/pause_screen.cpp b/src/pause_screen.cpp index df7f4fe..f05e9fd 100644 --- a/src/pause_screen.cpp +++ b/src/pause_screen.cpp @@ -45,8 +45,6 @@ constexpr float DESCRIPTION_LINE_SPACING = 0.9f; constexpr float PAPER_X = 0.7f; constexpr float PAPER_BOTTOM_MARGIN = 0.025f; constexpr float SEED_LINE_HEIGHT = 15; -constexpr size_t SEED_HALF_LENGTH = 4; -constexpr size_t SEED_SECOND_HALF = 5; constexpr uint32_t PAPER_TEXT_ARGB = 0xff362f2d; constexpr float SOUND_VOLUME = 0.7f; constexpr int SOUND_PAPER_IN = 17; diff --git a/src/persistent_game_data.cpp b/src/persistent_game_data.cpp index bce67b7..f0d23ee 100644 --- a/src/persistent_game_data.cpp +++ b/src/persistent_game_data.cpp @@ -14,7 +14,6 @@ #include constexpr int ACHIEVEMENT_NEVER = -2; -constexpr int CUTSCENE_CREDITS = 2; constexpr int CUTSCENE_EPILOGUE = 3; constexpr int MOM_KILL_CUTSCENE_FIRST = 4; constexpr int MOM_KILL_CUTSCENE_COUNT = 11; diff --git a/src/persistent_game_data.h b/src/persistent_game_data.h index 1da0b27..045e06e 100644 --- a/src/persistent_game_data.h +++ b/src/persistent_game_data.h @@ -24,11 +24,18 @@ constexpr int ACHIEVEMENT_RERUN = 337; constexpr int ACHIEVEMENT_BLUE_BABY = 32; constexpr int ACHIEVEMENT_EVERYTHING_IS_TERRIBLE = 33; constexpr int ACHIEVEMENT_ANGELS = 155; +constexpr int ACHIEVEMENT_MEGA_CHEST = 601; constexpr int ACHIEVEMENT_WOODEN_CHEST = 609; constexpr int ACHIEVEMENT_HAUNTED_CHEST = 611; constexpr int ACHIEVEMENT_STRANGE_DOOR = 635; constexpr int ACHIEVEMENT_DEAD_GOD = 637; +constexpr int ACHIEVEMENT_EVERYTHING_IS_TERRIBLE_2 = 246; +constexpr int ACHIEVEMENT_STORE_UPGRADE_1 = 151; +constexpr int ACHIEVEMENT_STORE_UPGRADE_2 = 152; +constexpr int ACHIEVEMENT_STORE_UPGRADE_3 = 153; +constexpr int ACHIEVEMENT_STORE_UPGRADE_4 = 154; constexpr int ACHIEVEMENT_ITEM_INFO = 641; +constexpr int ACHIEVEMENT_LIL_SPEWER = 384; constexpr int BOSS_COUNT = 104; constexpr int CHALLENGE_COUNT = 46; constexpr int COLLECTIBLE_SEEN_COUNT = 733; diff --git a/src/platform.cpp b/src/platform.cpp index f60ae5d..dd5f6a2 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -46,7 +46,6 @@ constexpr ActionBinding EMPTY_BINDING = {-1, -1, -1, -1}; constexpr double SHORT_FRAME_RATIO = 1.1; constexpr int PACING_SWITCH_FRAMES = 30; constexpr int MESSAGE_LENGTH = 1024; -constexpr int MS_PER_SECOND = 1000; constexpr int TARGET_HZ = 60; constexpr float REFRESH_TOLERANCE = 0.04f; diff --git a/src/platform.h b/src/platform.h index 52c9cb6..9b70ff3 100644 --- a/src/platform.h +++ b/src/platform.h @@ -8,6 +8,9 @@ #include #include +constexpr uint32_t MS_PER_SECOND = 1000; +constexpr uint64_t NS_PER_MS = 1000000; + struct SDL_GLContextState; struct SDL_Window; diff --git a/src/player_hud.cpp b/src/player_hud.cpp index de9c357..b1cec00 100644 --- a/src/player_hud.cpp +++ b/src/player_hud.cpp @@ -1,5 +1,6 @@ #include "player_hud.h" #include "entity_config.h" +#include "entity_pickup.h" #include "entity_player.h" #include "game.h" #include "hud.h" @@ -260,8 +261,6 @@ constexpr ColorMod BAR_COOLDOWN = {{1, 1, 1, 1}, {1.2f, 1.2f, 1.2f, 1}, {0, 0, 0 constexpr ColorMod ICON_SHADOW = {{0, 0, 0, ACTIVE_SHADOW_ALPHA}, {0, 0, 0, 0}, {0, 0, 0}}; constexpr ColorMod ICON_OUTLINE = {{0, 0, 0, 1}, {0, 0, 0, 0}, {1, 1, 1}}; -constexpr int PICKUP_PILL = 70; -constexpr int PICKUP_TAROTCARD = 300; // A color that only tints by an alpha and adds a red offset. static ColorMod heart_color(float alpha, float redOffset) diff --git a/src/player_manager.cpp b/src/player_manager.cpp index 0c0c597..3ecf000 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -77,7 +77,6 @@ constexpr uint64_t GAME_STATE_COOP_BABIES_ONLY = 0x10; constexpr uint32_t PLAYER_RNG_SHIFT = 34; constexpr uint32_t BABY_SHUFFLE_SHIFT = 27; constexpr uint32_t OWNER_ROLL_SHIFT = 22; -constexpr uint32_t GLITCH_BABY_SHIFT = 35; // The characters co-op offers, in carousel order after the random pick, before the mods' visible ones. constexpr int COOP_CHARACTERS[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16, 18, 19, @@ -276,7 +275,7 @@ Entity_Player* PlayerManager::SpawnCoPlayerBaby(int babyId) if (!unlocked.empty()) babyId = unlocked[Random() % unlocked.size()]; } } - if (babyId == BABY_GLITCH) glitchBabyRng.SetSeed(Random(), GLITCH_BABY_SHIFT); + if (babyId == BABY_GLITCH) glitchBabyRng.SetSeed(Random(), DEFAULT_SHIFT_INDEX); uint32_t seed = rng.Next(); uint32_t extraCount = (uint32_t)babies.size() - BABY_COUNT; @@ -786,7 +785,7 @@ void PlayerManager::trigger_level_start() { for (size_t i = 0; i < playerList.size(); i++) playerList[i]->level_start(0); - for (Entity* entity : g_game->room->GetEntities()->updateEL) + for (Entity* entity : entities_live(g_game->room->GetEntities()->updateEL)) if (entity && entity->type == ENTITY_FAMILIAR) static_cast(entity)->level_start(); g_game->rewindsThisFloor = 0; } diff --git a/src/popups.cpp b/src/popups.cpp index b6a013f..f3b2905 100644 --- a/src/popups.cpp +++ b/src/popups.cpp @@ -115,8 +115,6 @@ constexpr int OVERLAY_PICTURE_LAYER = 3; constexpr float OVERLAY_SMALL_SCALE = 0.3f; constexpr float OVERLAY_SMALL_X = 0.25f; constexpr float OVERLAY_SMALL_Y = 1.75f; -constexpr int FILTER_NEAREST = 0; -constexpr int FILTER_LINEAR = 1; constexpr int UPDATE_FRAME_MASK = 1; using FrameQuad = KAGE::Graphics::ColorQuad; diff --git a/src/room.cpp b/src/room.cpp index 3ea0195..44f9fa0 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -87,7 +87,6 @@ constexpr float WATER_CURRENTS[WATER_CURRENT_COUNT][2] = {{-1, 0}, {0, -1}, {1, constexpr std::array LIGHT_BLEND = {BLEND_EQUATION_ADD, BLEND_FACTOR_ONE, BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, BLEND_FACTOR_ONE, BLEND_FACTOR_ONE_MINUS_SRC_ALPHA}; -constexpr unsigned int FILTER_LINEAR = 1; // The Ascent's golden floors and walls, and the pre-items seed's grey Flooded Caves. constexpr ColorMod ASCENT_COLOR = {{1, 1, 1, 1}, {1.2f, 1.2f, 1.2f, 0.6f}, {0.0764f, -0.0216f, -0.0884f}}; @@ -117,7 +116,6 @@ constexpr int WATER_SUBTYPE_FLOODED = 11; constexpr int WATER_SUBTYPE_DUMP = 10; // The grid path values: what an entity walking has left, and what blocks spawning. -constexpr int GRID_PATH_RESET = 900; constexpr int GRID_PATH_PIT_LAST = 3999; // Lua's GridCollisionClass values GetGridCollision returns. @@ -126,12 +124,6 @@ constexpr uint32_t GRID_COLLISION_PIT = 1; constexpr uint32_t GRID_COLLISION_SOLID = 3; constexpr uint32_t GRID_COLLISION_WALL = 4; -// A crawlspace's subtypes: Rotgut's two phases and the Beast's arena. -constexpr int DUNGEON_GIDEON = 1; -constexpr int DUNGEON_ROTGUT = 2; -constexpr int DUNGEON_ROTGUT_HEART = 3; -constexpr int DUNGEON_BEAST = 4; -constexpr int BOSS_ULTRA_GREED = 62; constexpr int BOSS_ROTGUT = 87; // The backdrops LoadBackdropGraphics picks beyond the stage's own (backdrops.xml ids), and what picks them: rooms off @@ -211,7 +203,6 @@ constexpr int SOUND_SHOP_STAIRS = 916; constexpr float DOOR_OUTLINE_OFFSET = 15; // The quest doors of the alternate path's second floors: the rooms holding them and the rooms they lead to. -constexpr int MIRROR_ROOM_SUBTYPE = 34; constexpr int MINESHAFT_ROOM_SUBTYPE = 10; constexpr int ROOM_MIRROR_IDX = -100; constexpr int ROOM_MINESHAFT_IDX = -101; @@ -250,10 +241,6 @@ constexpr int COLLECTIBLE_CARD_READING = 660; constexpr int SEED_EFFECT_PRE_ITEMS = 79; constexpr int SEED_EFFECT_NO_LAST_BOSS_DOORS = 71; constexpr int SPECIAL_DAILY_SURPRISE_MINIBOSS = 17; -constexpr int ACHIEVEMENT_SHOP_LEVEL_2 = 151; -constexpr int ACHIEVEMENT_SHOP_LEVEL_3 = 152; -constexpr int ACHIEVEMENT_SHOP_LEVEL_4 = 153; -constexpr int ACHIEVEMENT_SHOP_LEVEL_5 = 154; constexpr int ACHIEVEMENT_STORE_KEY = 379; constexpr int EVENT_ARCADES_VISITED = 9; constexpr int SHOP_VISITS_FOR_ACHIEVEMENT = 5; @@ -697,10 +684,10 @@ void Room::init_shop_level() bool isAllUnlocked = g_manager->state == MANAGER_STATE_GAME && (g_game->dailyChallenge._id != 0 || g_game->isDebug); shopLevel = 1; - if (achievements[ACHIEVEMENT_SHOP_LEVEL_5] || isAllUnlocked) shopLevel = 5; - else if (achievements[ACHIEVEMENT_SHOP_LEVEL_4]) shopLevel = 4; - else if (achievements[ACHIEVEMENT_SHOP_LEVEL_3]) shopLevel = 3; - else if (achievements[ACHIEVEMENT_SHOP_LEVEL_2]) shopLevel = 2; + if (achievements[ACHIEVEMENT_STORE_UPGRADE_4] || isAllUnlocked) shopLevel = 5; + else if (achievements[ACHIEVEMENT_STORE_UPGRADE_3]) shopLevel = 4; + else if (achievements[ACHIEVEMENT_STORE_UPGRADE_2]) shopLevel = 3; + else if (achievements[ACHIEVEMENT_STORE_UPGRADE_1]) shopLevel = 2; } // What the layout's spawns say about the room before anything spawns: water, a dump, the Heretic or Raglich, the @@ -962,7 +949,7 @@ bool Room::SpawnGridEntity(int gridIndex, GridEntityType type, int variant, uint if ((uint32_t)gridIndex >= ROOM_GRID_CELLS) return false; bool isFlat = type == GRID_TRAPDOOR || type == GRID_STAIRS || type == GRID_PRESSURE_PLATE || type == GRID_TELEPORTER; - bool isFree = isFlat ? GetGridCollision(gridIndex) == GRID_COLLISION_NONE : gridPaths[gridIndex] <= GRID_PATH_RESET; + bool isFree = isFlat ? GetGridCollision(gridIndex) == GRID_COLLISION_NONE : gridPaths[gridIndex] <= GRID_PATH_FREED; GridEntity* entity = isFree ? CreateGridEntity(type, gridIndex) : nullptr; if (!entity) return false; @@ -1804,6 +1791,18 @@ void Room::SetSlowDown(int duration) slowdownDuration = std::max(duration, slowdownDuration); } +// 007f2070 Reloads the backdrop's graphics and snaps the game's color grading to the room's own, without a lerp. +void Room::reload_backdrop() +{ + LoadBackdropGraphics(); + const FXParams& params = fxLayers.fxParams; + ColorModState color = {params.roomColor._red, params.roomColor._green, params.roomColor._blue, + params.roomColor._alpha, params.brightness, params.contrast}; + g_game->targetColorModifier = color; + g_game->currentColorModifier = color; + g_game->isColorModifierLerped = false; +} + // 00813ce0 How many frames since the room was entered, or -1 before it is initialized. int Room::GetFrameCount() { @@ -3395,12 +3394,6 @@ void Room::UpdateRedKey() } } -// 00820ac0 Turns the room's grid and pickups gold (Ultra Greedier's room). -void Room::TurnGold() -{ - reconstruction_missing("Room::TurnGold 00820ac0"); -} - // 00827bf0 Spawns Sanguine Bond's spikes. bool Room::spawn_sanguine_bond_spikes(bool) { diff --git a/src/room.h b/src/room.h index 09ca4d8..9b833c8 100644 --- a/src/room.h +++ b/src/room.h @@ -94,6 +94,19 @@ enum BrokenWatchState : int BROKEN_WATCH_FAST }; +// A crawlspace's subtypes: Gideon's, Rotgut's two phases and the Beast's arena. +enum DungeonSubtype : int +{ + DUNGEON_GIDEON = 1, + DUNGEON_ROTGUT, + DUNGEON_ROTGUT_HEART, + DUNGEON_BEAST +}; + +// The default rooms found by subtype: the mineshaft's entrance and Downpour II's mirror room. +constexpr int MINESHAFT_ENTRANCE_SUBTYPE = 10; +constexpr int MIRROR_ROOM_SUBTYPE = 34; + // Whether RemoveGridEntity leaves a decoration where it is. enum DecorationRemoval { @@ -347,18 +360,22 @@ public: int boss_music_get(); uint32_t GetBossVictoryJingle(); void TriggerBossDeath(Entity_NPC& boss); + void SpawnGreedModeWave(); + void UpdateGreedWave(); void PlayMusic(); void Update(); void on_leave(); void update_ambient_sounds(); void first_frame_update(); + void myosotis_pickups_spawn(); void grid_paths_decay(); void Render(); void render_lighting(); void update_bounds(bool isFromGridSize); void LoadBackdropGraphics(); + void reload_backdrop(); void MakeDoor(int slot); void make_walls(); void crawlspace_walls_make(); diff --git a/src/room_clear.cpp b/src/room_clear.cpp index b99de48..6d79c51 100644 --- a/src/room_clear.cpp +++ b/src/room_clear.cpp @@ -1,10 +1,14 @@ #include "room_clear.h" +#include "boss_ai.h" +#include "boss_pool.h" #include "challenge_params.h" #include "entity_effect.h" +#include "entity_effect_combat.h" #include "entity_familiar.h" #include "entity_list.h" #include "entity_pickup.h" #include "entity_player.h" +#include "entity_slot.h" #include "game_over.h" #include "game.h" #include "grid_entity_door.h" @@ -15,6 +19,7 @@ #include "loot_list.h" #include "lua_engine.h" #include "manager.h" +#include "music_manager.h" #include "npc_ai.h" #include "persistent_game_data.h" #include "player_manager.h" @@ -38,26 +43,26 @@ constexpr int COLLECTIBLE_LITTLE_GISH = 99; constexpr int COLLECTIBLE_STEVEN = 50; constexpr int TRINKET_AAA_BATTERY_CLEAR = 3; constexpr int TRINKET_ISAACS_FORK = 46; -constexpr int TRINKET_OLD_CAPACITOR = 143; constexpr int TRINKET_DINGLE_BERRY = 163; constexpr int TRINKET_POLISHED_BONE = 167; constexpr int TRINKET_CRYSTAL_KEY = 170; constexpr int TRINKET_TEMPORARY_TATTOO = 177; constexpr int NULLITEM_WAVY_CAP = 71; -constexpr int NULLITEM_AZAZELS_RAGE_1 = 96; constexpr int FAMILIAR_BLUE_FLY_CLEAR = 43; constexpr int ENTITY_ETERNALFLY_CLEAR = 96; constexpr int GRID_PATH_TRODDEN = 900; constexpr int BABY_SKIN_WISP = 64; +constexpr int WISP_BABY_ODDS = 10; constexpr int SOUND_VAMP_GULP_CLEAR = 157; constexpr int SOUND_VAMP_DOUBLE_CLEAR = 614; constexpr int ACHIEVEMENT_LITTLE_CHAD = 25; constexpr int ACHIEVEMENT_LITTLE_GISH = 23; constexpr int ACHIEVEMENT_LITTLE_STEVEN = 24; constexpr int ACHIEVEMENT_BOOK_OF_REVELATIONS = 7; -constexpr int ULTRA_GREED_BOSS = 62; constexpr int BABY_PLUM_BOSS = 84; -constexpr int GREED_WAVES = 10; +// Ultra Greed's donation machine drops this far from the player, kept this far off the column below him. +constexpr float GREED_MACHINE_REACH = 80; +constexpr float GREED_MACHINE_CLEAR = 20; constexpr int BOSS_MEGA_SATAN_ID = 55; // Mom's first kill unlocks the Womb, the Harbingers, A Cube of Meat and the Item Info, and the Void past the Dark @@ -991,17 +996,46 @@ static void womb_award_spawn(Room& room, ClearAward& award, int stage, bool isCo } // The big chest a final floor's boss leaves on the room's cleared middle, or a trophy once a challenge ends here. -static void final_chest_spawn(Room& room, ClearAward& award, bool isContinuing) +static Vector final_chest_spawn(Room& room, ClearAward& award, bool isContinuing) { Vector spot = award.reward; reward_spot_clear(room, spot); if (!isContinuing) { g_game->Spawn({.position = spot, .type = ENTITY_PICKUP, .variant = PICKUP_TROPHY, .seed = Random()}); - return; + return spot; } g_manager->achievementOverlay.isPopupBlocked = true; g_game->Spawn({.position = spot, .type = ENTITY_PICKUP, .variant = PICKUP_BIGCHEST, .seed = award.rng.Next()}); + return spot; +} + +// The secret exit's bosses: Mom in the Mausoleum or Gehenna marks Mom's Heart, Mother her own mark and her chest (or +// trophy), and after her first kill a Void portal below it on a run that may reach the Void. +static void secret_exit_award_spawn(Room& room, ClearAward& award, int stage, bool isContinuing) +{ + constexpr float MOTHER_PORTAL_DROP = 40; + constexpr float MOTHER_PORTAL_SPREAD = 80; + + PersistentGameData& data = g_manager->persistentGameData; + if (stage == STAGE_DEPTHS_II) + { + data.IncreaseEventCounter(EVENT_COUNTER_MOM_KILLS, 1); + PlayerManager::unlock_completion_mark(COMPLETION_MOMS_HEART); + return; + } + if (stage != STAGE_WOMB_II) return; + + PlayerManager::unlock_completion_mark(COMPLETION_MOTHER); + data.IncreaseEventCounter(EVENT_COUNTER_MOTHER_KILLS, 1); + Vector spot = final_chest_spawn(room, award, isContinuing); + if (!isContinuing || !is_void_reachable() || data.eventCounters[EVENT_COUNTER_MOTHER_KILLS] <= 1) return; + + Vector below = vector_make(spot.x, spot.y + MOTHER_PORTAL_DROP); + int gridIndex = room.GetGridIndex(room_free_pickup_position_find( + {.position = below, .step = MOTHER_PORTAL_SPREAD, .isAvoidActiveEntities = true})); + room_spawn_cell_clear(room, gridIndex); + room.SpawnGridEntity(gridIndex, GRID_TRAPDOOR, 0, Random(), TRAPDOOR_VOID_PORTAL); } // Opens the save for a victory lap's unlock (unless achievements are off this run), then closes it again. @@ -1136,7 +1170,7 @@ static void mega_satan_award_spawn(Room& room, ClearAward& award, bool isContinu g_manager->persistentGameData.IncreaseEventCounter(EVENT_COUNTER_MEGA_SATAN_KILLS, 1); g_manager->persistentGameData.AddBoss(BOSS_MEGA_SATAN_ID); PlayerManager::unlock_completion_mark(COMPLETION_MEGA_SATAN); - if (game.GetChallengeParams().isMegaSatan) return final_chest_spawn(room, award, false); + if (game.GetChallengeParams().isMegaSatan) return (void)final_chest_spawn(room, award, false); if (!isContinuing || !is_void_reachable()) return game_end(ENDING_MEGA_SATAN); g_manager->achievementOverlay.isPopupBlocked = true; @@ -1214,8 +1248,7 @@ static void boss_award_spawn(Room& room, ClearAward& award) bool isMomsFloor = (stage == STAGE_WOMB_II || stage == STAGE_DEPTHS_II) && !isLastBoss; bool isBossRush = room.roomType == ROOM_BOSSRUSH || (game.challenge == CHALLENGE_RED_REDEMPTION && stage < STAGE_WOMB_II); - if (isSecretExitBoss) - reconstruction_missing("Room::SpawnClearAward 007fb250: the secret exit's bosses (Mom, Mother)"); + if (isSecretExitBoss) secret_exit_award_spawn(room, award, stage, isContinuing); else if (isPlainFloor || isBossRush) { if (isLastBoss) boss_exit_spawn(room, award, stage, isContinuing); @@ -1232,6 +1265,76 @@ static void boss_award_spawn(Room& room, ClearAward& award) boss_kill_records(stage, isLastBoss); } +// A beaten Greed wave's music: the boss fights end in their own jingles and the boss room's calm after, Satan's in +// that calm at once, the shop floor's fight in the challenge outro and the shop's music after. A normal wave only +// drops the floor's layer. +static void greed_wave_music_end() +{ + MusicManager& music = g_manager->musicManager; + float volume = g_manager->optionsConfig.musicVolume; + int after = MUSIC_BOSS_OVER; + int jingle = 0; + + switch (music.currentMusicId) + { + case MUSIC_BOSS: jingle = MUSIC_JINGLE_BOSS_OVER; break; + case MUSIC_BOSS2: jingle = MUSIC_JINGLE_BOSS_OVER2; break; + case MUSIC_BOSS3: jingle = MUSIC_JINGLE_BOSS_OVER3; break; + case MUSIC_SATAN_BOSS: music.Crossfade(MUSIC_BOSS_OVER, MUSIC_FADE_RATE); return; + case MUSIC_CHALLENGE_FIGHT: + jingle = MUSIC_JINGLE_CHALLENGE_OUTRO; + after = MUSIC_SHOP_ROOM; + break; + default: music.DisableLayer(0); return; + } + music.Play(jingle, volume); + music.Queue(after); +} + +// Ultra Greed's reward: the boss room's calm, his cell kept clear, a Greed donation machine by the player (online, +// one by each main player, tinted for co-op, is not reconstructed) and the big chest below where he fell, which marks +// his kill (and Greedier's). +static void ultra_greed_award_spawn(Room& room, ClearAward& award) +{ + Game& game = *g_game; + Vector greedSpot{}; + + g_manager->musicManager.Crossfade(MUSIC_BOSS_OVER, MUSIC_FADE_RATE); + std::vector ultraGreeds = entity_query(ENTITY_ULTRA_GREED, 0); + if (!ultraGreeds.empty()) + { + greedSpot = ultraGreeds[0]->pos; + int index = room.GetGridIndex(greedSpot); + if ((uint32_t)index < ROOM_GRID_CELLS) room.gridPaths[index] = GRID_PATH_SOLID; + } + + Entity_Player* player = game.playerManager.get_main_player(0); + float angle = random_unit() * RANDOM_HALF_TURN * 2; + Vector spot = room.GetClampedPosition( + vector_add(player->pos, vector_make(std::cos(angle) * GREED_MACHINE_REACH, std::sin(angle) * GREED_MACHINE_REACH)), + GRID_CELL_SIZE); + if (std::abs(spot.x - greedSpot.x) < GREED_MACHINE_CLEAR && spot.y < greedSpot.y) + spot.x += award.reward.x - spot.x >= 0 ? GRID_CELL_SIZE : -GRID_CELL_SIZE; + reward_spot_clear(room, spot); + Entity* machine = game.Spawn( + {.position = spot, .type = ENTITY_SLOT, .variant = SLOT_GREED_DONATION_MACHINE, .seed = award.rng.Next()}); + machine->AddEntityFlags(FLAG_APPEAR); + machine->Update(); + + Vector chestSpot = award.reward; + if (greedSpot.x != 0 || greedSpot.y != 0) + { + Vector below = room.GetClampedPosition(vector_add(greedSpot, vector_make(0, GRID_CELL_SIZE)), GRID_CELL_SIZE); + chestSpot = below; + if (below.y - greedSpot.y < GREED_MACHINE_CLEAR) + chestSpot.x = below.x + (award.reward.x - below.x >= 0 ? GRID_CELL_SIZE : -GRID_CELL_SIZE); + } + reward_spot_clear(room, chestSpot); + game.Spawn({.position = chestSpot, .type = ENTITY_PICKUP, .variant = PICKUP_BIGCHEST, .seed = award.rng.Next()}); + PlayerManager::unlock_completion_mark(COMPLETION_ULTRA_GREED); + if (game.difficulty == DIFFICULTY_GREEDIER) PlayerManager::unlock_completion_mark(COMPLETION_ULTRA_GREEDIER); +} + // 007fb250 Room::SpawnClearAward: the reward of a cleared room, unless a mod's MC_PRE_SPAWN_CLEAN_AWARD takes it. // A normal room drops a pickup by the roll (none in crawlspaces and the mineshaft's second dimension), a boss room // its exit and items. Tainted Keeper and a Satanic Bible's boss turn the boss items into deals. The award's @@ -1256,11 +1359,16 @@ void room_clear_award_spawn(Room& room) bool isEmpty = room.roomType == ROOM_DUNGEON || (game.HasAbandonedMineshaft() && game.currentDimensionIdx == 1); if (game.IsGreedMode()) { - if (room.roomType == ROOM_DEFAULT || (room.roomType == ROOM_BOSS && room.bossId == ULTRA_GREED_BOSS)) - reconstruction_missing("Room::SpawnClearAward 007fb250: Greed mode's wave music and Ultra Greed's coins"); + if (room.roomType == ROOM_DEFAULT) greed_wave_music_end(); + else if (room.roomType == ROOM_BOSS && room.bossId == BOSS_ULTRA_GREED) ultra_greed_award_spawn(room, award); } else if (data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME) - reconstruction_missing("Room::SpawnClearAward 007fb250: Home's ending"); + { + g_manager->persistentGameData.IncreaseEventCounter(EVENT_COUNTER_MOM_KILLS, 1); + PlayerManager::unlock_completion_mark(COMPLETION_BEAST); + g_manager->persistentGameData.IncreaseEventCounter(EVENT_COUNTER_BEAST_KILLS, 1); + game_end(ENDING_BEAST); + } else if (isNormal && !isEmpty) room_award_spawn(room, award); else if (!isNormal) boss_award_spawn(room, award); room.descriptor->awardSeed = award.rng._seed; @@ -1326,7 +1434,7 @@ void room_clear_trigger(Room& room, ClearSound sound) int lastWave = game.difficulty == DIFFICULTY_GREEDIER ? GREED_WAVES + 1 : GREED_WAVES; if (game.playerManager.IsCoopPlay() && wave == lastWave) game.playerManager.revive_player_ghosts(); } - else if (isGreed && room.roomType == ROOM_BOSS && room.bossId == ULTRA_GREED_BOSS && + else if (isGreed && room.roomType == ROOM_BOSS && room.bossId == BOSS_ULTRA_GREED && game.playerManager.IsCoopPlay()) game.playerManager.revive_player_ghosts(); game.save_rewind_state(-1); @@ -1461,6 +1569,78 @@ static void dingle_berry_dips_throw(Entity_Player& player) } } +// Polished Bone's part of 007a8fd0: one clear in five (more often with stronger copies) a charmed bony (a black one +// one time in four) climbs out beside the player with doubled health, leaving the room's doors open, in a burst of +// bone. +static void polished_bone_raise(Entity_Player& player) +{ + constexpr int POLISHED_BONE_ODDS = 5; + constexpr int BONY_RNG_SHIFT = 4; + constexpr int BLACK_BONY_MASK = 3; + constexpr float RISE_REACH = 10; + constexpr int POLISHED_BONE_PARTICLES = 4; + constexpr float POLISHED_BONE_SPEED_RANGE = 3; + constexpr float POLISHED_BONE_SPEED_MIN = 2; + constexpr int POLISHED_BONE_GIB_SUBTYPE = 1; + constexpr float POLISHED_BONE_GIB_LIFT = 0.5f; + RNG& rng = player.GetTrinketRNG(TRINKET_POLISHED_BONE); + uint32_t odds = (uint32_t)(POLISHED_BONE_ODDS - player.GetTrinketMultiplier(TRINKET_POLISHED_BONE)); + uint32_t roll = rng.Next(); + if (odds != 0 && roll % odds != 0) return; + + RNG bonyRng = rng_make(rng.Next(), BONY_RNG_SHIFT); + uint32_t kind = bonyRng.Next(); + int type = (kind & BLACK_BONY_MASK) != 0 ? ENTITY_BONY : ENTITY_BLACK_BONY; + Vector spot = vector_add(player.pos, vector_scale(random_direction(), RISE_REACH)); + Entity* bony = g_game->Spawn({.position = spot, .spawner = &player, .type = type, .seed = bonyRng.Next()}); + // The original goes on with a null entity when the spawn is no enemy. Here nothing more happens. + if (!bony || bony->type < ENTITY_FIRST_ENEMY || bony->type > ENTITY_LAST_ENEMY) return; + bony->AddCharmed(EntityRef(), -1, false, false); + bony->Update(); + static_cast(bony)->isCanShutDoors = false; + bony->maxHitPoints += bony->maxHitPoints; + bony->health = bony->maxHitPoints; + + game_particles_spawn({.position = spot, .speed = random_unit() * POLISHED_BONE_SPEED_RANGE + POLISHED_BONE_SPEED_MIN, + .count = POLISHED_BONE_PARTICLES, .variant = EFFECT_TOOTH_PARTICLE}); + float speed = random_unit() * POLISHED_BONE_SPEED_RANGE + POLISHED_BONE_SPEED_MIN; + for (int gibs = (int)(Random() & 1) + 2; gibs > 0; gibs--) + { + uint32_t seed = Random(); + Vector direction = random_direction(); + Vector velocity = vector_make(direction.x * speed, direction.y * POLISHED_BONE_GIB_LIFT * speed); + Entity* gib = g_game->Spawn({.position = spot, .velocity = velocity, .subType = POLISHED_BONE_GIB_SUBTYPE, + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_PARTICLE, .seed = seed}); + gib->AddEntityFlags(FLAG_NO_BLOOD_SPLASH); + gib->Update(); + } +} + +// Tainted Lazarus' part of 007a8fd0: a clear flips him to his other form. Flipping back from the dead form first +// clears the room for the familiars the form leaves behind, and the waiting form gets its own clear (without the +// pocket Flip charging twice). Both forms share the pocket Flip's charge after. +static void tainted_lazarus_flip(Entity_Player& player) +{ + Entity_Player* other = player.twin_get(); + if (!other) other = player.backupPlayer; + if (other == player.backupPlayer) + { + std::vector familiars; + for (Entity* entity : g_game->room->GetEntities()->updateEL) + if (entity->type == ENTITY_FAMILIAR && static_cast(entity)->player == &player) + familiars.push_back(static_cast(entity)); + for (Entity_Familiar* familiar : familiars) familiar->TriggerRoomClear(); + } + + player.UseActiveItem({.item = COLLECTIBLE_FLIP}); + if (other == player.backupPlayer && !player.isCoopGhost) + { + other->activeItems[ACTIVE_SLOT_POCKET].item = 0; + other->TriggerRoomClear(); + } + other->activeItems[ACTIVE_SLOT_POCKET] = player.activeItems[ACTIVE_SLOT_POCKET]; +} + // 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) @@ -1484,7 +1664,8 @@ static void crystal_key_door_open(Entity_Player& player) // 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, Crystal Key's red door, Azazel's Stump, and the wisps waiting for a clear. +// Azazel's Rage, Dingle Berry, Polished Bone, Crystal Key's red door, the wisp baby's wisps, Tainted Lazarus' flip, +// Azazel's Stump, and the wisps waiting for a clear. void Entity_Player::TriggerRoomClear() { if (!HasTrinket(TRINKET_OLD_CAPACITOR) && !HasCollectible(COLLECTIBLE_4_5_VOLT)) @@ -1499,14 +1680,13 @@ void Entity_Player::TriggerRoomClear() if (HasCollectible(COLLECTIBLE_AZAZELS_RAGE)) azazels_rage_charge(*this); 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_POLISHED_BONE)) polished_bone_raise(*this); 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"); + if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_SKIN_WISP && dropRNG.Next() % WISP_BABY_ODDS == 0) + AddWisp(Entity_Familiar::GetRandomWisp(&dropRNG), pos, false, false); bool isTaintedLazarus = playerType == PLAYER_LAZARUS_B || playerType == PLAYER_LAZARUS2_B; if (isTaintedLazarus && (backupPlayer || twinPlayer) && controlsCooldown <= 0 && !hasCurseMistEffect) - reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: Tainted Lazarus's flip"); + tainted_lazarus_flip(*this); azazels_stump_update(*this); if (!proceduralItems.empty()) reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0: the TMTRAINER clear triggers " diff --git a/src/room_config.cpp b/src/room_config.cpp index a66a59e..3d83a1a 100644 --- a/src/room_config.cpp +++ b/src/room_config.cpp @@ -54,7 +54,6 @@ constexpr float PICKED_WEIGHT_SCALE = 0.1f; constexpr float PICKED_WEIGHT_MIN = 1e-7f; constexpr uint32_t ENTITY_CONSTANT_STONE_SHOOTER = 202; constexpr uint32_t ENTITY_QUAKE_GRIMACE = 804; -constexpr uint32_t ENTITY_SPIKEBALL = 852; constexpr uint32_t ENTITY_DUSTY_DEATHS_HEAD = 887; constexpr uint32_t ENTITY_ENVIRONMENT = 970; constexpr short ROOM_GRID_WIDTH = 13; diff --git a/src/room_render.cpp b/src/room_render.cpp index 48100ee..af6f0b9 100644 --- a/src/room_render.cpp +++ b/src/room_render.cpp @@ -28,8 +28,6 @@ constexpr const char* COLD_LAVA_PNG = "gfx/grid/lava_cold.png"; constexpr const char* LAVA_PNG = "gfx/grid/lava.png"; constexpr const char* PIT_MASK_PNG = "gfx/grid/grid_pit_mask.png"; constexpr int TEXEL_KEEP = -1; -constexpr int WRAP_REPEAT = 0; -constexpr int FILTER_LINEAR = 1; constexpr int ROOM_SURFACE_WIDTH = 780; // The Ashpit's dust: three cloud layers drifting with the room's frames (half a frame more on odd frames), up to 4 a @@ -230,9 +228,6 @@ constexpr int PLATE_VARIANT_REWARD = 9; constexpr int PLATE_VARIANT_ROOM_CLEAR = 3; constexpr int ROOM_IDX_BLUE_WOMB_LIGHT = -9; constexpr uint32_t ROOM_DESCRIPTOR_FLAG_LIT_DOOR = 1u << 18; -constexpr uint32_t DEBUG_FLAG_GRID_VALUES = 1 << 1; -constexpr uint32_t DEBUG_FLAG_ROOM_INFO = 1 << 4; -constexpr uint32_t DEBUG_FLAG_GRID_INDICES = 1 << 10; // The Beast's arena draws in passes around the room's: under everything, over the floor, over the entities, last. enum BeastArenaPass @@ -1132,6 +1127,16 @@ static void night_lights_render(Room& room) } } +// The light surface multiplied over the screen in a tint, leaving the multiply blend on. +static void light_surface_multiply(KColor tint) +{ + KAGE::Graphics::manager.blendMode = {KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_DST_COLOR, + KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA, KAGE::Graphics::FACTOR_DST_ALPHA, + KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA}; + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *roomSurfaces.lightOverlay); + roomSurfaces.lightOverlay->Render(screen_quad(WHITE), tint); +} + // The lighting overlay over the room: the light surface multiplied over it at the shadows' strength (less a lightning // flash), and the flash itself added in the light layers. static void lighting_overlay_render(Room& room) @@ -1142,11 +1147,7 @@ static void lighting_overlay_render(Room& room) if (alpha <= 0) return; KAGE::Graphics::BlendMode saved = graphics.blendMode; - graphics.blendMode = {KAGE::Graphics::EQUATION_ADD, KAGE::Graphics::FACTOR_DST_COLOR, - KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA, KAGE::Graphics::FACTOR_DST_ALPHA, - KAGE::Graphics::FACTOR_ONE_MINUS_SRC_ALPHA}; - apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *roomSurfaces.lightOverlay); - roomSurfaces.lightOverlay->Render(screen_quad(WHITE), kcolor_rgba(1, 1, 1, alpha)); + light_surface_multiply(kcolor_rgba(1, 1, 1, alpha)); if (g_game->lightningIntensity > 0) { float flash = std::clamp(g_game->lightningIntensity * LIGHTNING_FLASH, 0.0f, LIGHTNING_FLASH); @@ -1394,7 +1395,12 @@ static void shockwave_surface_resolve(Room& room, Vector surfaceOffset) { floor_quad_render(room, surfaceOffset); if (g_manager->optionsConfig.render.isLightingEnabled) - reconstruction_missing("Room::Render 0080f200: the Greed shop's light under a shockwave"); + { + KAGE::Graphics::BlendMode saved = graphics.blendMode; + float alpha = room.GetLightingAlpha(); + light_surface_multiply(kcolor_rgba(alpha, alpha, alpha, alpha)); + graphics.blendMode = saved; + } } if (!room.IsClear()) shockwaves_radial_render(room, room.renderScrollOffset); @@ -1477,8 +1483,8 @@ void Room::Render() depth_render(*this, isWaterShown); for (Entity_Player* extra : game.playerManager.extraPlayers) extra->Render(renderScrollOffset); night_lights_render(*this); - if (game.debugFlags & DEBUG_FLAG_GRID_VALUES) reconstruction_missing("Room::render_debug_grid_values 008128f0"); - if (game.debugFlags & DEBUG_FLAG_GRID_INDICES) reconstruction_missing("Room::render_debug_grid_indices 0081f130"); + if (game.debugFlags & DEBUG_GRID_VALUES) reconstruction_missing("Room::render_debug_grid_values 008128f0"); + if (game.debugFlags & DEBUG_GRID_INDICES) reconstruction_missing("Room::render_debug_grid_indices 0081f130"); shader_select(COLOR_OFFSET_SHADER); if (render.isLightingEnabled) lighting_overlay_render(*this); @@ -1493,7 +1499,7 @@ void Room::Render() spriteShaderParams.pixelationAmount = 0; graphics.shader_default_set(); - if (game.debugFlags & DEBUG_FLAG_ROOM_INFO) reconstruction_missing("Room::Render 0080f200: the room info text"); + if (game.debugFlags & DEBUG_ROOM_INFO) reconstruction_missing("Room::Render 0080f200: the room info text"); } // The glow of a lava pit: in a flooded Mines room orange as hot as its lava, drawn plainly. In a flooded shaft it is diff --git a/src/room_state.cpp b/src/room_state.cpp index 0aeaed3..dbbac7b 100644 --- a/src/room_state.cpp +++ b/src/room_state.cpp @@ -19,7 +19,6 @@ // The last frames of a clear's delay that leaving the room still counts the clear in. constexpr int ROOM_CLEAR_DELAY_PENDING = 8; -constexpr int GRID_PATH_RESET = 900; // The effects, slots and enemies whose saves keep more than the common fields. constexpr int HEAVEN_LIGHT_MOONLIGHT = 1; @@ -416,7 +415,7 @@ static void secret_exit_open(Room& room) GridEntity* linked = room.gridEntities[wall->gridIndex]; if (!linked || linked->type == GRID_DECORATION) continue; - room.gridPaths[wall->gridIndex] = GRID_PATH_RESET; + room.gridPaths[wall->gridIndex] = GRID_PATH_FREED; room.gridEntities[wall->gridIndex] = nullptr; delete linked; } diff --git a/src/room_update.cpp b/src/room_update.cpp index 8c14d7b..67d4016 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -1,3 +1,4 @@ +#include "npc_basement.h" #include "entity_effect.h" #include "entity_laser.h" #include "entity_npc.h" @@ -12,7 +13,9 @@ #include "manager.h" #include "room.h" #include "room_clear.h" +#include "room_grid.h" #include "room_special.h" +#include "room_state.h" #include "room_render.h" #include "seeds.h" #include @@ -24,7 +27,6 @@ // The grid paths an entity leaves: a permanent mark, the value it fades back to, and how fast it fades. constexpr int GRID_PATH_DECAY_FRAMES = 3; constexpr int GRID_PATH_PERMANENT = 3999; -constexpr int GRID_PATH_RESET = 900; constexpr int GRID_PATH_DECAY_MAX = 100; constexpr int GRID_TIMER_MAX = 99; @@ -34,8 +36,6 @@ constexpr int ROOM_CLEAR_DELAY_DUNGEON_EXIT = 20; constexpr int OUTPUT_GROUP_ROOM_CLEAR = 9; // The fireplaces the pressure plates put out: red to normal, purple to blue. constexpr std::array, 2> FIREPLACE_COOLINGS = {{{1, 0}, {3, 2}}}; -constexpr int DUNGEON_ROTGUT = 2; -constexpr int DUNGEON_ROTGUT_HEART = 3; // Entering a door: how near a player stands to its cell's edge, how near to bump a locked door open, and where each // side's door edge sits from its cell's center. Tainted Forgotten pushes doors by its speed. @@ -51,8 +51,6 @@ constexpr float DUNGEON_LADDER_Y = 110; constexpr float DUNGEON_LADDER_LEFT = 100; constexpr float DUNGEON_LADDER_RIGHT = 140; constexpr uint32_t DUNGEON_BLACK_MARKET_DOOR = 1u << DIRECTION_RIGHT; -constexpr int ROOM_PASSAGE_IDX = -14; -constexpr int ROOM_PASSAGE_EXIT_IDX = -15; constexpr uint64_t GAME_STATE_ANGEL_ROOM_SPAWNED = 1ull << 0; constexpr uint64_t GAME_STATE_DEVIL_ROOM_SPAWNED = 1ull << 5; @@ -148,10 +146,8 @@ struct CurrentSplash constexpr ColorMod POOP_FX_COLOR = {{1, 1, 1, 3}, {0.7f, 0.1f, 0.9f, 1}, {0, 0, 0}}; constexpr int NULL_EFFECT_POOP_CLOUD = 64; constexpr int CHALLENGE_SEEING_DOUBLE = 40; -constexpr int SOUND_BOSS_ROAR = 190; constexpr int SOUND_THUNDER = 472; constexpr int SOUND_ALARM = 460; -constexpr int PLAYER_THE_FORGOTTEN_B = 35; constexpr int BOSS_MIN_MIN = 91; constexpr int ROOM_IDX_DUNGEON_BEAST = -16; constexpr int GREED_LAST_STAGE = 5; @@ -287,13 +283,21 @@ void Room::grid_paths_decay() int path = gridPaths[i]; int fade = path % GRID_PATH_BAND; - if (path == GRID_PATH_PERMANENT) gridPaths[i] = GRID_PATH_RESET; - else if (fade < GRID_PATH_RESET) gridPaths[i] = path - std::min(fade, GRID_PATH_DECAY_MAX); + if (path == GRID_PATH_PERMANENT) gridPaths[i] = GRID_PATH_FREED; + else if (fade < GRID_PATH_FREED) gridPaths[i] = path - std::min(fade, GRID_PATH_DECAY_MAX); if (gridTimers[i] >= 1 && gridTimers[i] <= GRID_TIMER_MAX) gridTimers[i] = (int16_t)std::max(gridTimers[i] - 1, 0); } } -// The first frame's work: a boss room's roar on the first visit (but Greed's first boss before it spawns), and the +// Myosotis's pickups: four, six or eight with a doubled or tripled trinket, the corner pick's shifts, and how far +// from a corner the search for a free spot starts. +constexpr int MYOSOTIS_PICKUPS = 4; +constexpr int MYOSOTIS_DOUBLED = 6; +constexpr int MYOSOTIS_TRIPLED = 8; +constexpr std::array MYOSOTIS_RNG_SHIFTS = {1, 9, 29}; +constexpr float MYOSOTIS_SPOT_STEP = 24; + +// The first frame's work: a boss room's portcullis on the first visit (but Greed's first boss before it spawns), and the // Myosotis pickups carried from the last floor into the floor's first room. void Room::first_frame_update() { @@ -301,13 +305,40 @@ void Room::first_frame_update() !(g_game->levelStateFlags & 1u << LEVEL_STATE_GREED_MONSTRO_SPAWNED); if (roomType == ROOM_BOSS && descriptor->visitedCount == 1 && !isGreedBossPending && bossId != 0) { - int sound = SOUND_BOSS_ROAR; + int sound = SOUND_CASTLEPORTCULLIS; seed_fart_sound_override(&sound); g_manager->sfxManager.Play(sound); } if (g_game->levelStateFlags & 1u << LEVEL_STATE_LEVEL_START_TRIGGERED) return; g_game->levelStateFlags |= 1u << LEVEL_STATE_LEVEL_START_TRIGGERED; - if (!g_game->myosotisPickups.empty()) reconstruction_missing("Room::Update 00802980: the Myosotis pickups"); + if (!g_game->myosotisPickups.empty()) myosotis_pickups_spawn(); +} + +// Part of 00802980: Myosotis brings back up to four of the last floor's pickups (six and eight for a doubled and +// tripled trinket), drawn from the front of the list by the room's decoration seed, each near a random corner. +void Room::myosotis_pickups_spawn() +{ + std::vector pickups = g_game->myosotisPickups; + Entity_Player* owner = g_game->playerManager.FirstTrinketOwner(TRINKET_MYOSOTIS); + int multiplier = owner ? owner->GetTrinketMultiplier(TRINKET_MYOSOTIS) : 1; + int limit = multiplier == 2 ? MYOSOTIS_DOUBLED : multiplier == 3 ? MYOSOTIS_TRIPLED : MYOSOTIS_PICKUPS; + int count = std::min(limit, (int)pickups.size()); + std::array corners = {GetGridIndexByTile(1, 1), GetGridIndexByTile(gridWidth - 2, 1), + GetGridIndexByTile(1, gridHeight - 2), GetGridIndexByTile(gridWidth - 2, gridHeight - 2)}; + + RNG rng = {descriptor->decorationSeed, MYOSOTIS_RNG_SHIFTS[0], MYOSOTIS_RNG_SHIFTS[1], MYOSOTIS_RNG_SHIFTS[2]}; + for (int i = 0; i < count; i++) + { + int pick = i + (int)(rng.Next() % (uint32_t)(count - i)); + if (pick != i) std::swap(pickups[i], pickups[pick]); + Vector corner = GetGridPosition(corners[rng.Next() & 3]); + const EntitySaveState& state = pickups[i]; + Vector position = room_free_pickup_position_find({.position = corner, .step = MYOSOTIS_SPOT_STEP}); + Entity* pickup = g_game->Spawn({.position = position, .subType = state.subtype, .type = state.type, + .variant = state.variant, .seed = state.initSeed}); + entity_state_restore(*this, *pickup, state); + pickup->spawnGridIndex = -1; + } } // The floor sprite's animation, and the error room's floor kept on its looping Idle. @@ -375,7 +406,7 @@ void Room::TriggerOutput(int group) { for (int gridIndex : outputGroupGridIndices[group]) if (gridEntities[gridIndex]) gridEntities[gridIndex]->trigger_output(); - for (Entity* entity : entityList.updateEL) + for (Entity* entity : entities_live(entityList.updateEL)) { if (entity->type != ENTITY_EFFECT || entity->variant != 120 || entity->subtype != group) continue; @@ -516,7 +547,7 @@ static bool dungeon_exit(Room& room, Entity_Player& player) { bool isBlackMarket = room.descriptor->data->doors & DUNGEON_BLACK_MARKET_DOOR; request.direction = DIRECTION_RIGHT; - if (room.descriptor->gridIndex == ROOM_PASSAGE_IDX) request.roomIndex = ROOM_PASSAGE_EXIT_IDX; + if (room.descriptor->gridIndex == ROOM_ROTGUT_DUNGEON1_IDX) request.roomIndex = ROOM_ROTGUT_DUNGEON2_IDX; else if (isBlackMarket) request.roomIndex = ROOM_BLACK_MARKET_IDX; } else if (position.x < 0) request.direction = DIRECTION_LEFT; @@ -557,7 +588,7 @@ static void door_transitions_update(Room& room) bool isLockedKind = door->variant >= DOOR_LOCKED && door->variant <= DOOR_LOCKED_KEYFAMILIAR; Vector velocity = player.velocity; - if (player.playerType == PLAYER_THE_FORGOTTEN_B && + if (player.playerType == PLAYER_THEFORGOTTEN_B && velocity.x * velocity.x + velocity.y * velocity.y > DOOR_PUSH_SPEED_SQUARED) { direction = std::abs(velocity.x) > std::abs(velocity.y) ? (velocity.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT) @@ -724,7 +755,7 @@ static void water_current_update(Room& room) Vector current = room.waterCurrent; if (current.x == 0 && current.y == 0) return; - for (Entity* entity : room.entityList.updateEL) + for (Entity* entity : entities_live(room.entityList.updateEL)) { bool isWalker = entity->type == ENTITY_PLAYER || (entity->type >= ENTITY_FIRST_ENEMY && entity->type < ENTITY_EFFECT); bool isCarried = isWalker || entity->type == ENTITY_BOMB || @@ -779,7 +810,10 @@ static void walls_bleed_update(Room& room) Entity* blood = entity_spawn(ENTITY_EFFECT, EFFECT_BLOOD_PARTICLE, position, velocity, seed); if (room.backdropType == BACKDROP_CORPSE || room.backdropType == BACKDROP_CORPSE2 || room.backdropType == BACKDROP_CORPSE3) - reconstruction_missing("Room::Update 00802980: the Corpse's green blood"); + { + blood->SetColor(COLOR_GREEN_SPLAT, -1, COLOR_PRIORITY_DEFAULT, false, true); + blood->splatColor = COLOR_GREEN_SPLAT; + } blood->Update(); } } @@ -813,20 +847,6 @@ static void flood_update(Room& room) room.color_modifier_apply(); } -// 00801ee0 Greed mode's waves: the wave timer runs down to the next wave (the wait cut short once the room is empty), -// and Ultra Greed's room starts its fight once a player walks in. Not reconstructed yet past its checks. -static void greed_wave_update(Room& room) -{ - Game& game = *g_game; - - if (!is_greed()) return; - if (room.greedWaveTimer > 0) reconstruction_missing("Room::UpdateGreedWave 00801ee0: the wave timer"); - if (game.stage != STAGE_ULTRA_GREED || room.roomType != ROOM_BOSS) return; - if (game.levelStateFlags & 1u << LEVEL_STATE_GREED_MONSTRO_SPAWNED) return; - for (size_t i = 0; i < game.playerManager.playerList.size(); i++) - if (game.GetPlayer((int)i)->pos.y < 320) reconstruction_missing("Room::UpdateGreedWave 00801ee0: Ultra Greed"); -} - // Coupon in a shop: once the players are in, one of the shop's items goes on sale, picked from the decoration seed. static void coupon_update(Room& room) { @@ -945,7 +965,7 @@ void Room::Update() if (isMamaMega && isInitialized && game.frameCount - enterFrame == 1 && !game.IsPaused()) MamaMegaExplosion({}, nullptr); if (slowdownDuration > 0) slowdownDuration--; - greed_wave_update(*this); + UpdateGreedWave(); update_ambient_sounds(); if (shopRestockTimer > 0 && --shopRestockTimer < 1) @@ -961,7 +981,7 @@ void Room::Update() } if (isPickupVisionInvalid) { - for (Entity* entity : entityList.updateEL) + for (Entity* entity : entities_live(entityList.updateEL)) { if (entity->type == ENTITY_PICKUP) static_cast(entity)->UpdateLootPreview(); else if (is_npc_type(entity->type)) @@ -998,7 +1018,7 @@ static Vector players_velocity_get() int count = 0; for (Entity_Player* player : g_game->playerManager.playerList) { - if (player->variant != 0 || player->playerType == PLAYER_THE_FORGOTTEN_B || !player->IsLocalPlayer()) continue; + if (player->variant != 0 || player->playerType == PLAYER_THEFORGOTTEN_B || !player->IsLocalPlayer()) continue; sum = vector_make(sum.x + player->velocity.x, sum.y + player->velocity.y); count++; diff --git a/src/score_sheet.cpp b/src/score_sheet.cpp index 4f45d51..c3bf0ab 100644 --- a/src/score_sheet.cpp +++ b/src/score_sheet.cpp @@ -1,5 +1,7 @@ #include "score_sheet.h" +#include "entity_pickup.h" #include "entity_player.h" +#include "entity_text.h" #include "game.h" #include "log.h" #include "room.h" @@ -46,7 +48,6 @@ constexpr int DOOR_SPAWNED_BONUS = 1000; constexpr float STAGE_REPLAYED_ONCE = 0.5f; constexpr uint32_t ROOM_DESCRIPTOR_RED_ROOM = 0x400; -constexpr int PICKUP_COLLECTIBLE = 100; constexpr int SUBTYPE_ANY = -1; constexpr int G_FUEL_STAGE_OFFSET = 4; constexpr int G_FUEL_POINTS_PER_STAGE = 200; @@ -54,7 +55,6 @@ constexpr float G_FUEL_KILL_FACTOR = 10; constexpr float KILL_HEALTH_EXPONENT = 0.2f; constexpr float KILL_POINTS_FACTOR = 5; -constexpr int TEXT_SCORE = 2; constexpr float POPUP_RISE = 8; constexpr float POPUP_SPEED = -2; diff --git a/src/seeds.cpp b/src/seeds.cpp index dd42991..32d6114 100644 --- a/src/seeds.cpp +++ b/src/seeds.cpp @@ -8,7 +8,6 @@ #include #include -constexpr uint32_t DEFAULT_SHIFT_INDEX = 35; constexpr uint32_t START_SHIFT_INDEX = 27; constexpr uint32_t FORGET_SHIFT_INDEX = 39; @@ -22,7 +21,6 @@ constexpr int SEED_CODE_GAP = 4; constexpr size_t SEED_CODE_LENGTH = 9; constexpr uint32_t LABYRINTH_STAGE_END = 8; -constexpr int LANGUAGE_ENGLISH = 0; // The curse each curse seed forces, and the one each prevention seed lifts. constexpr std::pair FORCED_CURSES[] = { diff --git a/src/seeds.h b/src/seeds.h index b36de2e..f024fb9 100644 --- a/src/seeds.h +++ b/src/seeds.h @@ -156,6 +156,11 @@ struct Seeds uint32_t Random(); constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; +// The shift triple most of the game's generators are seeded with. +constexpr uint32_t DEFAULT_SHIFT_INDEX = 35; +// A seed's text: two halves of four characters, the second starting at 5. +constexpr size_t SEED_HALF_LENGTH = 4; +constexpr size_t SEED_SECOND_HALF = 5; // random_float: a random fraction of one from the global generator. inline float random_unit() @@ -163,4 +168,10 @@ inline float random_unit() return (float)Random() * RANDOM_UNIT_SCALE; } +// A random draw between a least value and a range above it. +inline float random_between(float least, float range) +{ + return random_unit() * range + least; +} + void random_seed(uint32_t seed); diff --git a/src/sfx_manager.h b/src/sfx_manager.h index d6fe82f..953efba 100644 --- a/src/sfx_manager.h +++ b/src/sfx_manager.h @@ -69,6 +69,7 @@ enum SoundId : int SOUND_TEAR_DETONATOR = 1063, SOUND_VENTRICLE_RAZOR = 1064, SOUND_DEVIL_CARD = 34, + SOUND_DOOR_HEAVY_CLOSE = 35, SOUND_DOOR_HEAVY_OPEN = 36, SOUND_FART = 37, SOUND_FETUS_JUMP = 38, @@ -145,9 +146,23 @@ enum SoundId : int SOUND_BOIL_HATCH = 181, SOUND_BOSS2_BUBBLES = 185, SOUND_ERROR_BUZZ = 187, + SOUND_CASTLEPORTCULLIS = 190, SOUND_GOLDENKEY = 204, SOUND_GOOATTACH0 = 205, SOUND_MAW_OF_VOID = 426, + SOUND_ULTRA_GREED_COIN_DESTROY = 427, + SOUND_ULTRA_GREED_COINS_FALLING = 428, + SOUND_ULTRA_GREED_DEATH_SCREAM = 429, + SOUND_ULTRA_GREED_TURN_GOLD_1 = 430, + SOUND_ULTRA_GREED_TURN_GOLD_2 = 431, + SOUND_ULTRA_GREED_ROAR_1 = 432, + SOUND_ULTRA_GREED_ROAR_2 = 433, + SOUND_ULTRA_GREED_SPIT = 434, + SOUND_ULTRA_GREED_PULL_SLOT = 435, + SOUND_ULTRA_GREED_SLOT_SPIN_LOOP = 436, + SOUND_ULTRA_GREED_SLOT_STOP = 437, + SOUND_ULTRA_GREED_SLOT_WIN_LOOP_END = 438, + SOUND_ULTRA_GREED_SLOT_WIN_LOOP = 439, SOUND_BUTTON_PRESS = 469, SOUND_PUNCH = 478, SOUND_LINGER_BEAN = 860, @@ -161,6 +176,7 @@ enum SoundId : int SOUND_LEECH = 221, SOUND_MAGGOTCHARGE = 224, SOUND_MEATHEADSHOOT = 226, + SOUND_PENNYPICKUP = 234, SOUND_METAL_BLOCKBREAK = 229, SOUND_PLOP = 237, SOUND_SATAN_APPEAR = 238, @@ -222,10 +238,17 @@ enum SoundId : int SOUND_BONE_SNAP = 462, SOUND_BONE_DROP = 467, SOUND_BONE_BREAK = 500, + SOUND_BISHOP_HIT = 501, SOUND_BONE_BOUNCE = 499, SOUND_TOOTH_AND_NAIL = 506, + SOUND_TOOTH_AND_NAIL_TICK = 507, + SOUND_THREAD_SNAP = 509, SOUND_SHOVEL_DIG = 464, SOUND_GOLD_HEART_DROP = 466, + SOUND_BONE_HEART = 461, + SOUND_GOLD_HEART = 465, + SOUND_UNHOLY = 468, + SOUND_ROTTEN_HEART = 497, SOUND_CANDLE_LIGHT = 471, SOUND_BOSS2_DIVE = 474, SOUND_BOSS2INTRO_PIPES_TURNON = 475, @@ -233,6 +256,7 @@ enum SoundId : int SOUND_WOOD_PLANK_BREAK = 481, SOUND_BULLET_SHOT = 482, SOUND_FLAME_BURST = 483, + SOUND_INFLATE = 484, SOUND_BATTERYDISCHARGE = 493, SOUND_FREEZE = 496, SOUND_FREEZE_SHATTER = 498, @@ -251,6 +275,7 @@ enum SoundId : int SOUND_POOPITEM_HOLD = 607, SOUND_VAMP_DOUBLE = 614, SOUND_GFUEL_AIR_HORN = 828, + SOUND_CRACKED_ORB = 850, SOUND_DARK_BUM_PAYOUT = 853, SOUND_DRSREMOTE_WARNING = 855, SOUND_POOP_THROW = 865, @@ -371,6 +396,7 @@ enum SoundId : int SOUND_LADDER = 1086, SOUND_POT_BREAK = 138, SOUND_SWORD_SPIN = 538, + SOUND_BABY_BRIM = 539, SOUND_CUBE_BABY_KICK = 852, SOUND_RAGMAN_1 = 392, SOUND_RAGMAN_2 = 393, @@ -413,6 +439,38 @@ enum SoundId : int SOUND_ANIMA_BREAK = 613, SOUND_DARK_ESAU_OPEN = 616, SOUND_DARK_ESAU_DEATH_OPEN = 617, + SOUND_KNIFE_PULL = 540, + SOUND_MOTHER_DEATH1 = 618, + SOUND_MOTHER_DEATH2 = 619, + SOUND_MOTHER_FISTPOUND1 = 620, + SOUND_MOTHER_FISTPOUND2 = 621, + SOUND_MOTHER_FISTPOUND3 = 622, + SOUND_MOTHER_FISTULA = 623, + SOUND_MOTHER_APPEAR1 = 624, + SOUND_MOTHER_APPEAR2 = 625, + SOUND_MOTHER_KNIFE_START = 626, + SOUND_MOTHER_KNIFE_THROW = 627, + SOUND_MOTHER_SUMMON_ISAACS_START = 628, + SOUND_MOTHER_SUMMON_ISAACS_END = 629, + SOUND_MOTHER_HAND_BOIL_START = 630, + SOUND_MOTHER_GRUNT1 = 631, + SOUND_MOTHER_GRUNT5 = 632, + SOUND_MOTHER_GRUNT6 = 633, + SOUND_MOTHER_GRUNT7 = 634, + SOUND_MOTHER_LAUGH = 635, + SOUND_MOTHER_SPIN_START = 636, + SOUND_MOTHER_WALL_SHOT_START = 637, + SOUND_MOTHER_MISC = 638, + SOUND_MOTHER_SHOOT = 639, + SOUND_MOTHER_ISAAC_RISE = 641, + SOUND_MOTHER_ISAAC_HIT = 642, + SOUND_MOTHER_WRIST_SWELL = 643, + SOUND_MOTHER_WRIST_EXPLODE = 644, + SOUND_MOTHER_DEATH_MELT = 645, + SOUND_MOTHER_ANGER_SHAKE = 646, + SOUND_MOTHER_CHARGE1 = 647, + SOUND_MOTHER_CHARGE2 = 648, + SOUND_MOTHER_LAND_SMASH = 649, SOUND_ABYSS = 834, SOUND_FLIP_POOF = 856, SOUND_GNAWED_LEAF_STONE = 858, @@ -485,6 +543,8 @@ enum SoundId : int SOUND_MINECRAFTER = 1062, SOUND_R_KEY = 904, SOUND_SUPLEX_ACTIVATE = 1030, + SOUND_SUPLEX_JUMP = 1032, + SOUND_SUPLEX_LAND = 1033, SOUND_WOODEN_NICKEL_SPAWN = 1066, SOUND_DARK_ARTS = 1045, SOUND_FORTUNE_COOKIE = 491, @@ -511,6 +571,7 @@ enum SoundId : int SOUND_GFUEL_EXPLOSION = 822, SOUND_GFUEL_EXPLOSION_BIG = 823, SOUND_GLITTER_BOMB = 866, + SOUND_BIG_LEECH = 510, SOUND_REVERSE_EXPLOSION = 511, SOUND_BEAST_LAVABALL_RISE = 814, SOUND_DOGMA_JACOBS_ZAP = 551, diff --git a/src/string_table.h b/src/string_table.h index 9da68f7..5f8b41e 100644 --- a/src/string_table.h +++ b/src/string_table.h @@ -6,6 +6,15 @@ #include #include +// The languages the game checks by id (its language column order). +enum Language : int +{ + LANGUAGE_ENGLISH = 0, + LANGUAGE_JAPANESE = 2, + LANGUAGE_KOREAN = 11, + LANGUAGE_CHINESE = 13 +}; + // A category of localized strings: each key's translations by language column, and the keys in file order. // The game's map erase (00a27c80) is the default destruction. struct StringTableCategory diff --git a/src/tainted_characters.cpp b/src/tainted_characters.cpp index b5dbc16..2e6f28c 100644 --- a/src/tainted_characters.cpp +++ b/src/tainted_characters.cpp @@ -278,23 +278,34 @@ void lemegeton_use(ItemUse& use) } // 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. +// (again) climbs out of a hole somewhere in the room, held off while Jacob cannot act. In Red Redemption the curse +// counts the waves instead: from the pocket item's count, every sixth adds one more Dark Esau. void tainted_frame_update(Entity_Player& player) { + constexpr int RED_REDEMPTION_WAVE = 6; if (player.playerType != PLAYER_JACOB_B) return; - if (g_game->challenge == CHALLENGE_RED_REDEMPTION) - reconstruction_missing("Entity_Player::update_effects 00794e50 (Red Redemption's Dark Esau waves)"); - TemporaryEffect* curse = player.temporaryEffects.GetNullEffect(NULLITEM_JACOBS_CURSE); - if (!curse || curse->cooldown > DARK_ESAU_CALL_FRAMES) return; - if (!player.isControlsEnabled) + TemporaryEffects& effects = player.temporaryEffects; + if (g_game->challenge == CHALLENGE_RED_REDEMPTION) { - curse->cooldown = DARK_ESAU_CALL_FRAMES; - return; + int start = player.activeItems[ACTIVE_SLOT_POCKET].varData; + int waves = effects.GetNullEffectNum(NULLITEM_JACOBS_CURSE); + if (waves < start || (waves - start) % RED_REDEMPTION_WAVE != 0) return; + effects.AddNullEffect(NULLITEM_JACOBS_CURSE, true, 1); + } + else + { + TemporaryEffect* curse = effects.GetNullEffect(NULLITEM_JACOBS_CURSE); + if (!curse || curse->cooldown > DARK_ESAU_CALL_FRAMES) return; + if (!player.isControlsEnabled) + { + curse->cooldown = DARK_ESAU_CALL_FRAMES; + return; + } + effects.RemoveNullEffect(NULLITEM_JACOBS_CURSE, -1); + if (player.darkEsau) player.darkEsau->Remove(); } - player.temporaryEffects.RemoveNullEffect(NULLITEM_JACOBS_CURSE, -1); - if (player.darkEsau) player.darkEsau->Remove(); Vector spot = room_pickup_position_random(true, false); Entity* esau = g_game->Spawn({spot, {}, &player, 0, ENTITY_DARK_ESAU, 0, Random()}); player.darkEsau = esau; diff --git a/src/weapon_lasers.cpp b/src/weapon_lasers.cpp index 79116e8..ad055ce 100644 --- a/src/weapon_lasers.cpp +++ b/src/weapon_lasers.cpp @@ -1,14 +1,22 @@ #include "weapon_lasers.h" #include "boss_ai.h" +#include "capsule.h" +#include "entity_bomb.h" +#include "entity_effect.h" #include "entity_familiar.h" #include "entity_laser.h" +#include "entity_pickup.h" #include "entity_player.h" +#include "entity_projectile.h" #include "entity_tear.h" #include "game.h" #include "log.h" #include "manager.h" #include "npc_ai.h" #include "npc_basement.h" +#include "npc_fireplace.h" +#include "room.h" +#include "room_grid.h" #include "sfx_manager.h" #include @@ -73,6 +81,56 @@ constexpr float TECH_X_DAMAGE_RANGE = 0.75f; constexpr float TECH_X_RANDOM_SPREAD = 50; constexpr int TECH_X_BLINK_MIN = 11; +// Hemoptysis' sneeze: the head's blink, a burst's reach past the owner, its capsule (one and a half times wider than +// long) and a cell's, its damage scale and the push, knockback and mark it gives, how fires and shots take it, the +// blue flies it may spawn, its explosive blast and poison splash, and the blood sprayed from the mouth. +constexpr int SNEEZE_BLINK = 10; +constexpr float SNEEZE_REACH = 26; +constexpr float SNEEZE_REACH_BASE = 12; +constexpr float SNEEZE_WIDTH = 1.5f; +constexpr float SNEEZE_SIZE = 20; +constexpr float SNEEZE_CELL_SIZE = 20; +constexpr float SNEEZE_DAMAGE_SCALE = 1.5f; +constexpr float SNEEZE_PUSH_MASS = 900; +constexpr float SNEEZE_PUSH_MASS_BASE = 50; +constexpr float SNEEZE_KNOCKBACK = 20; +constexpr int SNEEZE_KNOCKBACK_FRAMES = 14; +constexpr int SNEEZE_MARK_FRAMES = -150; +constexpr int SNEEZE_HIT_COUNTDOWN = 30; +constexpr float SNEEZE_FIRE_DAMAGE = 1000; +constexpr float SNEEZE_PUSH = 18; +constexpr float SNEEZE_LUDOVICO_FLING = 1.25f; +constexpr float SNEEZE_REFLECT_HEIGHT = -50; +constexpr uint32_t SNEEZE_MULLIGAN_ODDS = 6; +constexpr int SNEEZE_BLUE_FLY_MAX = 30; +constexpr float SNEEZE_BLAST_RADIUS = 30; +constexpr float SNEEZE_BLAST_DAMAGE = 10; +// The blast's damage flags: an explosion the players ignore. +constexpr uint64_t SNEEZE_BLAST_FLAGS = DAMAGE_EXPLOSION | DAMAGE_IGNORED; +constexpr ColorMod SNEEZE_POISON_SPLAT = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0, 0.33333334f, 0}}; +constexpr ColorMod SNEEZE_POISON_BURST = {{0.02f, 0.9f, 0.02f, 1}, {0, 0, 0, 0}, {0.039215688f, 0.3921569f, 0}}; +constexpr float SNEEZE_BURST_WIDTH = 0.5f; +constexpr float SNEEZE_BURST_HEIGHT = 0.2f; +constexpr float SNEEZE_BURST_DEPTH = -5; +constexpr ColorMod SNEEZE_SPLASH_COLOR = {{2, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float SNEEZE_SPLASH_SPEED = 5; +constexpr float SNEEZE_BIG_SCALE = 1.5f; +constexpr int SNEEZE_TRAILS = 6; +constexpr float SNEEZE_TRAIL_SPREAD = 60; +constexpr float SNEEZE_TRAIL_SPEED = 8; +constexpr float SNEEZE_TRAIL_PLAYBACK_MIN = 0.6f; +constexpr float SNEEZE_TRAIL_PLAYBACK_RANGE = 0.4f; + +// What a sneeze's burst hits with: who fired it and for which player, from where, its hit params and laser color. +struct SneezeHit +{ + TearParams params; + ColorMod color = COLOR_DEFAULT; + Vector ownerPosition{}; + Entity* owner = nullptr; + Entity_Player* player = nullptr; +}; + // 009f9020's makers for the laser weapons (009f94c0, 009f9640, 009f91f0): a fresh weapon of the type, or none for the // other types. Weapon* weapon_laser_make(WeaponType type) @@ -752,7 +810,8 @@ BrimstoneAim Weapon_Brimstone::aim_get(bool isShooting) // 009ff360 Charges and fires Brimstone: while shooting the head charges, on release (or once a fixed aim or Marked's // charge is enough) the beams fire. A rapid fire keeps one beam going and sweeps it, Ludovico steers a ring beam. -// C Section's fetuses and Hemoptysis' sneeze are not reconstructed yet. With C Section, the body faces the beam. +// Hemoptysis sneezes when a shot starts. C Section's fetuses are not reconstructed yet, and with it the body faces +// the beam. void Weapon_Brimstone::Fire(const Vector& shootDirection, bool isShooting, bool isInterpolated) { Weapon::Fire(shootDirection, isShooting, isInterpolated); @@ -787,7 +846,10 @@ void Weapon_Brimstone::Fire(const Vector& shootDirection, bool isShooting, bool bool isSneezing = modifiers & WEAPON_MOD_AZAZELS_SNEEZE; bool isHeldCharge = isInterpolated || charge > 0 || fireDelay >= 0; if (isSneezing && isShootingNow && !isHeldCharge && !aim.isFullyCharged) - reconstruction_missing("Weapon_Brimstone::Fire 009ff360 (Hemoptysis' sneeze, fire_hitscan 00a01020)"); + { + sneeze(shootDirection, aim); + isCharging = true; + } if (isShootingNow && !aim.isFullyCharged) charge_update(shootDirection, isCharging, isInterpolated); else release(shootDirection, aim, isInterpolated); } @@ -803,10 +865,228 @@ void Weapon_Brimstone::fire_c_section_fetuses() reconstruction_missing("Weapon_Brimstone::fire_c_section_fetuses 00a00d10"); } -// 00a01020 -void Weapon_Brimstone::fire_hitscan() +// Hemoptysis' sneeze when a shot starts with nothing held: hitscan bursts of blood along the volley (its shots, Eye +// Sore's, Mom's Eye's and Loki's Horns'), the rest dropped after the first that hits. A hit, or the boost the item's +// use left, sets the next charge halfway along, and the fire delay restarts at a full charge. +void Weapon_Brimstone::sneeze(const Vector& shootDirection, const BrimstoneAim& aim) { - reconstruction_missing("Weapon_Brimstone::fire_hitscan 00a01020"); + Vector aimDirection = IsAxisAligned() ? vector_cardinal(shootDirection) : vector_normalized(shootDirection); + Weapon_MultiShotParams params = GetMultiShotParams(); + aimAngle = vector_angle(aimDirection); + UpdateHeadChargeAnimation(COLLECTIBLE_BRIMSTONE, HEAD_CHARGE_SHOOT_ALT, aimDirection, -1); + SetBlinkTime(SNEEZE_BLINK); + + bool isHit = false; + for (int i = 0; i < params.numTears; i++) + { + PosVel shot = Entity_Player::GetMultiShotPositionVelocity(i, WEAPON_BONE, aimDirection, aim.shotSpeed, params); + if (!isHit) isHit = fire_hitscan(shot.velocity, 1); + } + for (int i = 0; i < params.numRandomDirTears; i++) + if (!isHit) isHit = fire_hitscan(random_direction(), 1); + if (params.isShootingBackwards && !isHit) isHit = fire_hitscan(vector_scale(aimDirection, -1), 1); + if (params.isShootingSideways && !isHit) + isHit = fire_hitscan(vector_make(-aimDirection.y, aimDirection.x), 1) || + fire_hitscan(vector_make(aimDirection.y, -aimDirection.x), 1); + + Entity_Player* player = aim.player; + if (isHit || (player && player->temporaryEffects.HasNullEffect(NULLITEM_HEMOPTYSIS_BOOST))) + { + charge += (GetMaxCharge() - charge) * HALF; + if (player) player->temporaryEffects.RemoveNullEffect(NULLITEM_HEMOPTYSIS_BOOST, -1); + } + fireDelay = aim.maxCharge; +} + +// The damage flags of a sneeze's hit on an enemy: a blue fly with the Guppy form (one hit in six with The Mulligan), +// while the player has under 30. +static uint64_t sneeze_damage_flags(Entity& enemy, Entity_Player* player) +{ + if (!enemy.IsVulnerableEnemy(nullptr) || !player) return 0; + bool isGuppy = !player->hasCurseMistEffect && !player->isCoopGhost && player->HasPlayerForm(PLAYER_FORM_GUPPY); + if (!isGuppy && (!player->HasCollectible(COLLECTIBLE_MULLIGAN) || Random() % SNEEZE_MULLIGAN_ODDS != 0)) return 0; + return player->numBlueFlies < SNEEZE_BLUE_FLY_MAX ? DAMAGE_SPAWN_FLY : 0; +} + +// What a sneeze's burst does to an entity it reaches: an enemy is pushed (unless it never is), hurt and marked, and +// takes the shot's tear effects. A fire other than a moving one goes out, a frozen enemy shatters on the player, a +// shopkeeper is spared. Bombs (not the player's raised Dr. Fetus bomb), loose pickups and enemy shots are knocked +// away, the player's Ludovico tear is flung. Whether an enemy was hurt. +static bool sneeze_entity_hit(Entity& target, const SneezeHit& hit) +{ + Entity_Player* player = hit.player; + Vector away = vector_normalized(vector_sub(target.pos, hit.ownerPosition)); + auto push = [&](float strength) + { + if (target.friction != 0) target.velocity = vector_add(target.velocity, vector_scale(away, strength * target.speedMultiplier / target.friction)); + }; + int type = target.type; + if (Entity::is_enemy_type(type)) + { + if (target.HasEntityFlags(FLAG_FRIENDLY) || type == ENTITY_SHOPKEEPER) return false; + if (type == ENTITY_FIREPLACE && target.variant != FIRE_COAL) + { + target.TakeDamage(SNEEZE_FIRE_DAMAGE, 0, EntityRef(hit.owner), SNEEZE_HIT_COUNTDOWN); + return false; + } + // The original lets the player of a familiar's sneeze be missing here and crashes. Here nothing collides. + if (type == ENTITY_FROZEN_ENEMY) + { + if (player) Entity::ForceCollide(player, &target, true); + return false; + } + if (target.isDead) return false; + + if (!target.HasEntityFlags(FLAG_NO_KNOCKBACK)) + { + push(SNEEZE_PUSH_MASS / (target.mass + SNEEZE_PUSH_MASS_BASE)); + target.AddKnockback(EntityRef(hit.owner), vector_scale(away, SNEEZE_KNOCKBACK), SNEEZE_KNOCKBACK_FRAMES, true); + } + uint64_t damageFlags = sneeze_damage_flags(target, player); + if (!target.TakeDamage(hit.params.tearDamage, damageFlags, EntityRef(hit.owner), SNEEZE_HIT_COUNTDOWN) || + !target.IsVulnerableEnemy(nullptr)) + return false; + Entity_Tear::ApplyTearFlagEffects(&target, hit.ownerPosition, hit.params.tearFlags, hit.owner, hit.params.tearDamage); + target.AddBrimstoneMark(EntityRef(hit.owner), SNEEZE_MARK_FRAMES); + return true; + } + + if (type == ENTITY_BOMB) + { + bool isRaisedFetus = target.parent == player && static_cast(target).isFetus && target.posOffset.y < 0; + if (!isRaisedFetus) push(SNEEZE_PUSH); + } + else if (type == ENTITY_PROJECTILE) + { + if (player && !target.isDead && static_cast(target).height > SNEEZE_REFLECT_HEIGHT) + static_cast(target).Reflect(vector_scale(away, SNEEZE_PUSH)); + } + else if (type == ENTITY_TEAR && player) + { + if (target.parent == player && static_cast(target).tearFlags[TEAR_LUDOVICO]) + target.velocity = vector_scale(away, SNEEZE_PUSH * SNEEZE_LUDOVICO_FLING); + } + else if (type == ENTITY_PICKUP && target.variant != PICKUP_COLLECTIBLE && static_cast(target).price == 0 && + !target.isDead && target.entityCollisionClass != ENTCOLL_NONE && !target.HasEntityFlags(FLAG_NO_KNOCKBACK)) + push(SNEEZE_PUSH); + return false; +} + +// An explosive sneeze (Ipecac) bursts at the tip with its tear effects and a blast that players ignore, green with +// poison, under a small blast in the laser color. +static void sneeze_blast(const SneezeHit& hit, Vector tip) +{ + const TearFlags& flags = hit.params.tearFlags; + explosion_tear_flag_effects({.tearFlags = flags, .position = tip, .source = hit.owner, .radius = SNEEZE_BLAST_RADIUS}); + explosion_damage({.tearFlags = flags, .position = tip, .source = hit.owner, .damageFlags = SNEEZE_BLAST_FLAGS, + .damage = hit.params.tearDamage * 2 + SNEEZE_BLAST_DAMAGE, .radius = SNEEZE_BLAST_RADIUS}); + if (flags[TEAR_POISON]) + { + Entity* splat = g_game->Spawn({.position = tip, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float scale = (random_unit() + 1) * HALF; + splat->sprite.scale = vector_make(scale, scale); + splat->SetColor(SNEEZE_POISON_SPLAT, -1, COLOR_PRIORITY_DEFAULT, false, true); + splat->Update(); + + Entity* burst = g_game->Spawn({.position = tip, .subType = BLOOD_EXPLOSION_SPLASH_BIG, .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()}); + burst->SetColor(SNEEZE_POISON_BURST, -1, COLOR_PRIORITY_DEFAULT, false, true); + burst->sprite.scale = vector_make(SNEEZE_BURST_WIDTH, SNEEZE_BURST_HEIGHT); + burst->renderDepthOffset = SNEEZE_BURST_DEPTH; + burst->Update(); + } + Entity* blast = g_game->Spawn({.position = tip, .type = ENTITY_EFFECT, .variant = EFFECT_BOMB_EXPLOSION, .seed = Random()}); + blast->sprite.scale = vector_scale(blast->sprite.scale, HALF); + blast->SetColor(hit.color, -1, COLOR_PRIORITY_DEFAULT, false, true); +} + +// 00a01020 One Hemoptysis burst along a direction: a short wide capsule of blood just past the owner (twice as big +// for Tainted Azazel with Birthright) hurts the grid it touches and hits what it reaches, then an explosive burst +// blasts at its tip, and blood sprays from the owner's mouth. A player's or familiar's burst takes the player's hit +// params at one and a half times the damage scale, and every burst is shielded. Whether it hurt an enemy. +bool Weapon_Brimstone::fire_hitscan(const Vector& direction, float damageScale) +{ + SneezeHit hit; + hit.color = get_laser_color(); + hit.owner = owner; + hit.player = weapon_player(owner); + Entity_Player* player = hit.player; + float scale = 1; + Vector offset{}; + if (player) + { + int displacement = (int)(Random() & 1) * 2 - 1; + hit.params = player->GetTearHitParams(WEAPON_BRIMSTONE, damageScale * SNEEZE_DAMAGE_SCALE, displacement, owner); + if (player->playerType == PLAYER_AZAZEL_B && player->HasCollectible(COLLECTIBLE_BIRTHRIGHT)) scale = 2; + if (player == owner) offset = player->tearsOffset; + } + hit.params.tearFlags.set(TEAR_SHIELDED); + hit.ownerPosition = owner ? owner->pos : Vector{}; + + Vector tip = vector_add(vector_add(hit.ownerPosition, offset), vector_scale(direction, scale * SNEEZE_REACH + SNEEZE_REACH_BASE)); + Capsule beam(tip, vector_make(SNEEZE_WIDTH, 1), vector_angle(direction), scale * SNEEZE_SIZE); + float reach = beam.halfLength + beam.radius; + // The debug mode's hit shape for the burst is drawn once DebugRenderer is taken over. + + Room& room = *g_game->room; + int center = room.GetGridIndex(beam.center); + if (center >= 0) + { + int cells = (int)std::ceil(reach / GRID_CELL_SIZE); + int centerX = center % room.gridWidth; + int centerY = center / room.gridWidth; + for (int x = std::max(centerX - cells, 0); x <= std::min(centerX + cells, room.gridWidth); x++) + for (int y = std::max(centerY - cells, 0); y <= std::min(centerY + cells, room.gridHeight); y++) + { + int gridIndex = room.GetGridIndexByTile(x, y); + GridEntity* grid = gridIndex >= 0 ? room.gridEntities[gridIndex] : nullptr; + if (!grid) continue; + Capsule cell(room.GetGridPosition(grid->gridIndex), vector_make(1, 1), 0, SNEEZE_CELL_SIZE); + if (Capsule::Collide(cell, beam)) grid->Hurt(1, EntityRef(owner)); + } + } + + bool isHit = false; + uint32_t partitions = QUERY_TEARS | QUERY_ENEMIES | QUERY_PICKUPS | QUERY_PROJECTILES; + for (Entity* target : entity_query_radius(beam.center, reach, partitions)) + { + if (target->size == 0 || target->entityCollisionClass == ENTCOLL_NONE) continue; + if (beam.halfLength > 0 && !Capsule::Collide(target->GetCollisionCapsule({}), beam)) continue; + if (target->IsDescendantOf(owner)) continue; + if (sneeze_entity_hit(*target, hit)) isHit = true; + } + if (hit.params.tearFlags[TEAR_EXPLOSIVE]) sneeze_blast(hit, tip); + + effect_sound_play(SOUND_BABY_BRIM); + Vector mouth = GetOwnerLaserOffset(LASER_OFFSET_BRIMSTONE, direction); + ColorMod splash = SNEEZE_SPLASH_COLOR; + if (player) color_multiply(splash, player->laserColor); + Vector origin = vector_add(hit.ownerPosition, offset); + + uint32_t seed = Random(); + auto* blood = static_cast(g_game->Spawn({.position = vector_add(origin, direction), + .velocity = vector_scale(direction, SNEEZE_SPLASH_SPEED), + .spawner = owner, .subType = (scale > SNEEZE_BIG_SCALE) + BLOOD_EXPLOSION_BURST, + .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = seed})); + if (player) blood->SetColor(splash, -1, COLOR_PRIORITY_DEFAULT, false, true); + blood->posOffset = mouth; + blood->rotation = random_unit() * FULL_TURN_DEGREES; + blood->Update(); + + for (int i = 0; i < SNEEZE_TRAILS; i++) + { + Vector spray = vector_rotated(direction, random_unit() * SNEEZE_TRAIL_SPREAD - SNEEZE_TRAIL_SPREAD / 2); + Vector velocity = vector_scale(spray, random_unit() * SNEEZE_TRAIL_SPEED * scale); + seed = Random(); + Entity* trail = g_game->Spawn({.position = vector_add(origin, velocity), .velocity = velocity, .spawner = owner, + .subType = 1, .type = ENTITY_EFFECT, .variant = EFFECT_HAEMO_TRAIL, .seed = seed}); + if (player) trail->SetColor(splash, -1, COLOR_PRIORITY_DEFAULT, false, true); + trail->posOffset = mouth; + trail->sprite.scale = vector_make(scale, scale); + trail->sprite.playbackSpeed = random_unit() * SNEEZE_TRAIL_PLAYBACK_RANGE + SNEEZE_TRAIL_PLAYBACK_MIN; + trail->Update(); + } + return isHit; } // 00a02890 diff --git a/src/weapon_lasers.h b/src/weapon_lasers.h index 32f11d1..bcab2cc 100644 --- a/src/weapon_lasers.h +++ b/src/weapon_lasers.h @@ -59,7 +59,8 @@ struct Weapon_Brimstone : Weapon void ludovico_update(const Vector& shootDirection, const BrimstoneAim& aim, bool isShooting, bool isInterpolated); Entity_Laser* fire_beam(const Vector& beamDirection, float damageScale, uint32_t fireFlags); void fire_c_section_fetuses(); - void fire_hitscan(); + void sneeze(const Vector& shootDirection, const BrimstoneAim& aim); + bool fire_hitscan(const Vector& direction, float damageScale); void fire(float speed, bool isStatusIgnored); };