Files
isaac-port/src/entity_npc.cpp
T

2835 lines
120 KiB
C++

#include "entity_npc.h"
#include "boss_ai.h"
#include "boss_death.h"
#include "entity_bomb.h"
#include "entity_config.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 "data.h"
#include "game.h"
#include "grid_entity.h"
#include "log.h"
#include "manager.h"
#include "npc_ai.h"
#include "npc_basement.h"
#include "persistent_game_data.h"
#include "platform.h"
#include "room.h"
#include "room_config.h"
#include "room_descriptor.h"
#include "room_grid.h"
#include "sfx_manager.h"
#include "mines.h"
#include "npc_alt.h"
#include <algorithm>
#include <cmath>
#include <filesystem>
// The frames of a controlled NPC's charge bar, empty to full.
constexpr int CHARGE_BAR_FRAMES = 100;
constexpr float POOP_THROW_HEIGHT = -20;
constexpr float POOP_THROW_LOUD_SPEED = 5;
constexpr int ENTITY_FEAR_IMMUNE = 205;
constexpr int ENTITY_NO_DECOY_TYPE = 213;
constexpr uint32_t DOPLE_PICK_SHIFT = 11;
constexpr int ENTITY_UNREACHABLE_EXEMPT = 886;
constexpr int ENTITY_DEATH_SPARK_TYPE = 882;
constexpr int ENTITY_DAMAGE_NUMBERS_TYPE = 964;
constexpr int ENTITY_ERASE_EXEMPT = 950;
constexpr int APPEAR_OVERLAY_KEPT_TYPE = 266;
constexpr float BIG_HORN_APPEAR_VOLUME = 2;
constexpr std::array<int, 4> APPEAR_EVENT_TYPES = {404, 912, 913, 917};
constexpr std::array<int, 9> FLUSH_TYPES = {217, 220, 223, 261, 402, 870, 871, 872, 914};
constexpr int FLUSH_PROP_TYPE = 237;
constexpr int FLUSH_PROP_VARIANT = 2;
constexpr int FLUSH_RENDER_Z = 5000;
constexpr int HUSH_ASH_SHAKE = 30;
// The bosses' death events: Isaac's cry, Baby Plum's last ring, Singe's blast, Mother's slam and Clutch's explosions.
constexpr int ISAAC_DEATH_CRY_FRAME = 17;
constexpr float ISAAC_DEATH_CRY_VOLUME = 2;
constexpr float PLUM_RING_FALL = 0.099f;
constexpr float PLUM_RING_SPEED = 6;
constexpr float PLUM_RING_SHOTS = 10;
constexpr float SINGE_BLAST_DAMAGE = 80;
constexpr float SINGE_BLAST_REACH = 1.5f;
constexpr int MOTHER_SLAM_VARIANT = 10;
constexpr int MOTHER_SLAM_SHAKE = 20;
constexpr float MOTHER_SLAM_PITCH = 0.5f;
constexpr int CLUTCH_BLAST_SUBTYPE = 3;
constexpr float CLUTCH_BLAST_RAISE = -20;
constexpr float CLUTCH_BLAST_SCALE = 1.5f;
constexpr float CLUTCH_BLAST_DAMAGE = 80;
constexpr float CLUTCH_BLAST_VOLUME = 1.25f;
constexpr float CLUTCH_PITCH = 0.9f;
constexpr float CLUTCH_PITCH_SPREAD = 0.2f;
constexpr int CLUTCH_BLAST_SHAKE = 14;
constexpr float CLUTCH_BLAST_SPIN = 360;
constexpr int ENTITY_FORWARD_NONE = 45;
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";
constexpr std::string_view HOLE2_LAYER = "Hole2";
constexpr std::string_view GFUEL_ISAAC_ANM2 = "gfx/promo/gfuel/102.001_g baby (true final boss).anm2";
constexpr int DIRT_SAMPLE_FRAMES = 15;
constexpr float DIRT_GREEN = 0.9f;
constexpr float DIRT_LERP = 0.1f;
constexpr int MORPH_COLOR_PRIORITY = -1000;
constexpr ColorMod COLOR_INVISIBLE = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}};
constexpr int UNREACHABLE_CHECK_FRAMES = 60;
constexpr int UNREACHABLE_GRACE_FRAMES = 900;
constexpr float MIDAS_COIN_SPEED = 3;
constexpr float TOXIC_CREEP_SCALE = 0.05f;
constexpr int TOXIC_SHOCK_POISON = -40;
constexpr int MODEM_FRAMES = 50;
constexpr int PUPPY_HIT_FRAMES = 3;
constexpr int FORCED_TARGET_BOSS_COOLDOWN = 150;
constexpr int CONFUSION_RETARGET_FRAMES = 15;
constexpr float CONFUSION_WANDER = 240;
constexpr float FEAR_WANDER = 100;
constexpr int FEAR_RETARGET_RANGE = 15;
constexpr int FEAR_RETARGET_MIN = 5;
constexpr float MOVEMENT_DEADZONE = 0.1f;
constexpr float ATTACK_PREDICT_FRAMES = 5;
constexpr int LINE_BLOCKED_MAX = 8;
// The corners of the band a line check samples around each step.
struct LineCorner
{
float x;
float y;
};
constexpr std::array<LineCorner, 4> LINE_CORNERS = {{{-5, -5}, {-5, 5}, {5, 5}, {5, -5}}};
constexpr int GRID_PATH_PIT = 3000;
constexpr uint32_t GRID_PATH_BAND = 1000;
constexpr float SHIELD_SECOND = 30;
constexpr float SHIELD_BASE = 0.09f;
constexpr float SHIELD_FALLOFF = 0.18f;
constexpr uint32_t BLACK_HEART_CHANCE = 5;
constexpr uint32_t STICKY_SPIDERS_RANGE = 3;
constexpr uint32_t STICKY_SPIDERS_BLAST_RANGE = 5;
constexpr int JAR_OF_FLIES_MAX = 20;
constexpr float HALF_SPEED = 0.5f;
constexpr float LADDER_FOOT_MARGIN = 0.5f;
constexpr float LADDER_DROP_SPEED = 3.5f;
// The kill items: Contagion's cloud, Athame's ring at a quarter plus a fortieth of the luck, and the soul wisps
// Book of Virtues takes from a captured enemy by its soul tag.
constexpr float CONTAGION_RADIUS = 85;
constexpr uint32_t ATHAME_RNG_SHIFT_INDEX = 66;
constexpr float ATHAME_BASE_CHANCE = 0.25f;
constexpr float ATHAME_LUCK_CHANCE = 0.025f;
constexpr int ATHAME_RING_TIMEOUT = 60;
constexpr int WISP_SOUL = 0x1000a;
constexpr int WISP_SOUL_EXPLOSIVE = 0x1000b;
constexpr int WISP_SOUL_HOMING = 0x1000c;
constexpr int WISP_SOUL_BRIMSTONE = 0x1000d;
// A Brimstone marked enemy's burst: its mark and statuses spread within 120 with a hit of 10.
constexpr float MARK_SPREAD_RADIUS = 120;
constexpr int MARK_SPREAD_FRAMES = 150;
constexpr int STATUS_SPREAD_FRAMES = 90;
constexpr float MARK_SPREAD_DAMAGE = 10;
constexpr int MARK_SPREAD_COUNTDOWN = 30;
constexpr ColorMod SPREAD_SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.0f, 40 / 255.0f, 40 / 255.0f}};
constexpr int SOUND_POOP_DEATH = 237;
constexpr float POOP_DEATH_VOLUME = 0.9f;
constexpr uint64_t FLAG_FRIENDLY_BALL_DYING = 1ull << 60;
// The burst effects a dead NPC leaves besides blood (Lua's EffectVariant).
enum DeathBurst : int
{
EFFECT_BURST_810 = 130,
EFFECT_BURST_853 = 131,
EFFECT_BURST_818 = 145
};
constexpr int ENTITY_SIREN_HELPER = 966;
constexpr int ENTITY_EXORCIST = 832;
constexpr int ENTITY_SHADOW_CHARGER = 23;
constexpr int ENTITY_ULTRA_GREED_DOOR = 889;
constexpr int SUCKER_VARIANT_BULB = 5;
constexpr int SHADOW_CHARGER_SUBTYPE = 1;
constexpr int TYPE_NO_TICK_A = 274;
constexpr int TYPE_NO_TICK_B = 275;
// The items and seeds whose effects the NPC update reads, by Lua id.
constexpr int COLLECTIBLE_HOURGLASS_ID = 66;
constexpr int COLLECTIBLE_GAMEKID_ID = 93;
constexpr int COLLECTIBLE_CHAMPION_BELT_ID = 208;
constexpr int COLLECTIBLE_STOP_WATCH_ID = 232;
constexpr int COLLECTIBLE_SOUL_ID = 335;
constexpr int COLLECTIBLE_TOXIC_SHOCK_ID = 350;
constexpr int COLLECTIBLE_BETRAYAL_ID = 391;
constexpr int COLLECTIBLE_SPIDER_MOD_ID = 403;
constexpr int COLLECTIBLE_BROKEN_MODEM_ID = 514;
constexpr int COLLECTIBLE_GUPPYS_EYE_ID = 665;
constexpr int COLLECTIBLE_SALVATION_ID = 696;
constexpr int COLLECTIBLE_VANISHING_TWIN_ID = 697;
constexpr int TRINKET_PURPLE_HEART_ID = 5;
constexpr int TRINKET_TICK_ID = 53;
constexpr int TRINKET_SUPER_MAGNET_ID = 68;
constexpr int TRINKET_LIGHTER_ID = 135;
constexpr int TRINKET_ICE_CUBE_ID = 188;
constexpr int ROOM_TRINKET_STATUS_FRAMES = -90;
constexpr int NULLITEM_DAMOCLES_WEAKNESS = 64;
constexpr int CHALLENGE_BEANS = 30;
constexpr int CHALLENGE_SLOW = 22;
constexpr int ACHIEVEMENT_BOSS_COLORS = 3;
constexpr int ACHIEVEMENT_MORE_BOSS_COLORS = 33;
constexpr int ACHIEVEMENT_REDIRECTS = 348;
constexpr uint32_t ROOM_CONFIG_FLAG_NO_CHAMPIONS = 1 << 2;
constexpr int GRID_CELL = 40;
constexpr float GRID_TOP = 120;
constexpr float HALF = 0.5f;
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;
constexpr int BOSS_ID_EXCLUDED_PAIR = 260;
constexpr int BOSS_ID_EXCLUDED_PAIR_VARIANT = 10;
// The champion chances: any enemy, with Champion Belt, on the Void, and a boss's color.
constexpr float CHAMPION_CHANCE = 0.05f;
constexpr float CHAMPION_CHANCE_BELT = 0.2f;
constexpr float CHAMPION_CHANCE_VOID = 0.75f;
constexpr float CHAMPION_CHANCE_LATE_SPAWN = 0.2f;
constexpr float CHAMPION_CHANCE_VICTORY_LAP = 0.25f;
constexpr float CHAMPION_CHANCE_PURPLE_HEART = 3;
// What a layer's bitflags say about it: drawn in the floor's dirt color, and wearing its champion sheet.
constexpr unsigned int LAYER_DIRT_COLORED = 1 << 0;
constexpr unsigned int LAYER_CHAMPION_SHEET = 1 << 4;
constexpr unsigned int SPRITE_UNKNOWN_FLAG_20 = 1 << 5;
constexpr unsigned int STATUS_SHARED = 1u << 31;
constexpr int TYPE_SPRITE_FLAG_A = 950;
constexpr int TYPE_SPRITE_FLAG_B = 960;
constexpr int VARIANT_SPRITE_FLAG_B = 4;
constexpr std::string_view STATUS_EFFECTS_ANM2 = "gfx/StatusEffects.anm2";
// The target search: how far enemies look for players, and what pushes a player back or pulls a twin forward.
constexpr float TARGET_RANGE = 5000;
constexpr float TARGET_INVINCIBLE_PENALTY = 400;
constexpr float TARGET_UNCONTROLLED_PENALTY = 800;
constexpr float TWIN_NEAR_SQUARED = 10000;
constexpr float BULB_CHARGE_BASE = 10000;
constexpr float BULB_CHARGE_STEP = 2000;
constexpr float BULB_DISTANCE_SCALE = 0.001f;
constexpr int TARGET_REFRESH_FRAMES = 15;
constexpr int DECOY_TIMER_MAX = 180;
// The appear poof and the sizes of poofs and blood bursts by the NPC's size.
constexpr int APPEAR_POOF_FRAME = 1;
constexpr int APPEAR_SHOW_FRAME = 4;
constexpr int APPEAR_MIN_FRAMES = 20;
constexpr float APPEAR_FRICTION = 0.01f;
constexpr float TICK_HEALTH_MIN = 60;
constexpr float TICK_HEALTH_SCALE = 0.85f;
constexpr float POOF_SMALL_SIZE = 13;
constexpr float POOF_LARGE_SIZE = 18;
constexpr float POOF_LARGE_SHADOW = 30;
constexpr float POOF_HUGE_SIZE = 40;
constexpr float POOF_HUGE_SHADOW = 50;
constexpr float BLOOD_DEPTH_OFFSET = 10;
constexpr float PAUSE_SLOWDOWN = 0.6f;
constexpr float RIPPLE_SCALE = 0.05f;
constexpr float RIPPLE_DEPTH = -10;
constexpr float RIPPLE_SPEED = 0.5f;
constexpr int RIPPLE_FRAMES = 7;
constexpr float POOF02_SCALE = 0.3f;
constexpr float POOF02_DEPTH = 10;
constexpr ColorMod POOF02_COLOR = {{1, 1, 1, 0.5f}, {0, 0, 0, 0}, {0, 0, 0}};
constexpr float SLOW_FRICTION = 0.92f;
constexpr int WEAKNESS_FRAMES = 2;
constexpr int STATUS_REFRESH = -2;
constexpr int SLOW_TIMESCALE_EFFECT_FRAMES = 30;
// The speed an NPC moves at: slowed by the stopwatch, the hourglass, its own slowing and Betrayal's charm.
constexpr float SPEED_HALF = 0.5f;
constexpr float SPEED_WEAKENED = 0.65f;
constexpr float SPEED_VANISHING_TWIN = 0.75f;
// 0043ef30 Shoots one plain shot at a random circle angle.
ProjectileParams::ProjectileParams() : circleAngle(random_unit() * PI_F) {}
// Plays a sound through the fart seeds.
void npc_sound_play(int sound, float volume, int frameDelay, float pitch)
{
seed_fart_sound_override(&sound);
g_manager->sfxManager.Play(sound, {.volume = volume, .frameDelay = frameDelay, .pitch = pitch});
}
// The size class of the poofs and blood bursts an NPC leaves: 1 small to 4 huge, the last only when isHugeAllowed.
int poof_size_get(Entity& entity, bool isHugeAllowed)
{
int poof = entity.size < POOF_SMALL_SIZE ? 1 : 2;
if (entity.size >= POOF_LARGE_SIZE || entity.shadowSize > POOF_LARGE_SHADOW) poof = 3;
if (isHugeAllowed && (entity.size >= POOF_HUGE_SIZE || entity.shadowSize > POOF_HUGE_SHADOW)) poof = 4;
return poof;
}
// Spawns an entity where an NPC stands.
Entity* spawn_at(int type, int variant, int subType, const Vector& position, Entity* spawner)
{
return g_game->Spawn({.position = position,
.spawner = spawner,
.subType = subType,
.type = type,
.variant = variant,
.seed = Random()});
}
// Whether an entity may be the nearest enemy (Game::GetNearestEnemy): a living, targetable, collidable enemy past its
// first frame that is not friendly, nor a fireplace, shopkeeper, TNT, poop, prop, minecart or the blood cultist's
// spawn. In a versus match the other players count too.
static bool is_nearest_enemy_candidate(Entity& entity, bool isVersusPlayer)
{
constexpr int CULTIST_BLOOD_SPAWN = 10;
int type = entity.type;
if (g_game->frameCount - entity.spawnFrame <= 1) return false;
if (!isVersusPlayer && (type < ENTITY_FIRST_ENEMY || type > ENTITY_LAST_ENEMY)) return false;
if (entity.entityCollisionClass == ENTCOLL_NONE || entity.entityCollisionClass == ENTCOLL_PLAYERONLY) return false;
if (entity.isInvincible || entity.isDead || entity.HasEntityFlags(FLAG_NO_TARGET | FLAG_FRIENDLY)) return false;
if (isVersusPlayer) return true;
if (type == ENTITY_CULTIST) return entity.variant != CULTIST_BLOOD_SPAWN;
return type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER && type != ENTITY_MOVABLE_TNT && type != ENTITY_POOP &&
type != ENTITY_GENERIC_PROP && type != ENTITY_MINECART;
}
// 00707370 Game::GetNearestEnemy: the enemy nearest a position within a radius that a source may target, a charmed
// one counted 400 farther. A friendly source passes over the players it may not hurt, and in a versus match over its
// own ancestors. The original's optional distance function is left out, as no caller here passes one.
Entity* game_nearest_enemy(const Vector& position, Entity* source, float radius)
{
constexpr float CHARMED_DISTANCE_SQUARED = 160000;
bool isVersus = g_game->deathmatchManager.is_active();
Entity* nearest = nullptr;
float best = radius * radius;
for (Entity* entity : g_game->room->entityList.updateEL)
{
bool isPlayer = entity->type == ENTITY_PLAYER;
if (isPlayer && source && source->HasEntityFlags(FLAG_FRIENDLY) &&
source->IsDamageSourceFriendly(EntityRef(entity)))
continue;
if (source && ((isVersus && source->IsDescendantOf(entity)) || !source->IsValidTarget(entity))) continue;
if (!is_nearest_enemy_candidate(*entity, isVersus && isPlayer)) continue;
float distance = vector_length_squared(vector_sub(position, entity->pos));
if (entity->HasEntityFlags(FLAG_CHARM)) distance += CHARMED_DISTANCE_SQUARED;
if (distance >= best) continue;
best = distance;
nearest = entity;
}
return nearest;
}
// 00703950 The player nearest a position, the first on ties.
Entity_Player* game_nearest_player(const Vector& position)
{
std::vector<Entity_Player*>& players = g_game->playerManager.playerList;
Entity_Player* nearest = g_game->GetPlayer(0);
float best = vector_length_squared(vector_sub(position, nearest->pos));
for (size_t i = 1; i < players.size(); i++)
{
float distance = vector_length_squared(vector_sub(position, players[i]->pos));
if (distance >= best) continue;
best = distance;
nearest = players[i];
}
return nearest;
}
// The charge Bulb drains a player for: one per full active, else its charges.
static int active_charges_get(Entity_Player& player)
{
int charges = 0;
for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++)
{
if (!g_manager->itemConfig.GetCollectible(player.activeItems[slot].item)) continue;
int maxCharge = player.GetActiveMaxCharge(slot);
if (maxCharge > 0) charges += maxCharge == 1 ? 1 : player.activeItems[slot].charge;
}
return charges;
}
// What a target counts as from a position: its squared distance, pushed back while its player is invincible or (for
// Baby Plum) without control, pulled to a twin walking into the other, and for Bulb led by the active charge it holds.
static float target_score_get(const Vector& position, Entity* source, Entity& target, Entity_Player* player,
bool isBulb)
{
float distance = vector_length_squared(vector_sub(target.pos, position));
if (!player) return distance;
Entity_Player* twin = player->twin_get();
if (player->HasInvincibility(0, EntityRef())) distance += TARGET_INVINCIBLE_PENALTY;
else if ((!player->isControlsEnabled || player->controlsCooldown > 0) && source && source->type == ENTITY_BABY_PLUM)
distance += TARGET_UNCONTROLLED_PENALTY;
else if (twin)
{
Vector between = vector_sub(twin->pos, player->pos);
bool isMeeting = vector_dot(vector_add(player->velocity, twin->velocity), between) < 0 &&
vector_length_squared(between) < TWIN_NEAR_SQUARED;
if (isMeeting) distance = vector_length_squared(vector_sub(twin->pos, position)) + 1;
}
if (!isBulb) return distance;
float priority = std::max(BULB_CHARGE_BASE - (float)active_charges_get(*player) * BULB_CHARGE_STEP, 0.0f);
return distance * BULB_DISTANCE_SCALE + priority;
}
// 007069a0 What an enemy at a position goes after: the nearest visible player within reach (Dark Esau only Jacob),
// else a Punching Bag or a baited enemy. An enemy forced onto a target keeps it.
// The stand-in target a player keeps at Entity_Player 0x144c waits for Entity_Player to name it.
Entity* game_nearest_target_player(const Vector& position, Entity* source, bool isPlayersOnly, bool isTargetDecoys,
float maxDistance)
{
if (!isPlayersOnly && isTargetDecoys && source && source->IsEnemy())
{
Entity* forced = static_cast<Entity_NPC*>(source)->forcedTarget;
if (forced) return forced;
}
bool isBulb = source && source->type == ENTITY_SUCKER && source->variant == SUCKER_VARIANT_BULB;
isPlayersOnly = isPlayersOnly || isBulb;
isTargetDecoys = isTargetDecoys && !isBulb;
Entity* nearest = nullptr;
float best = maxDistance * maxDistance;
for (Entity_Player* candidate : g_game->playerManager.playerList)
{
Entity_Player* twin = candidate->twin_get();
bool isTwinLed = (candidate->playerType == PLAYER_LAZARUS_B || candidate->playerType == PLAYER_LAZARUS2_B) &&
twin && twin->playerIndex != -1 && twin->playerIndex < candidate->playerIndex;
if (candidate->isCoopGhost || (candidate->isExists && isTwinLed && twin != candidate)) continue;
if (source && source->IsFriendly() && source->IsDamageSourceFriendly(EntityRef(candidate))) continue;
Entity* target = candidate;
if (!isPlayersOnly && candidate->bestFriend) target = candidate->bestFriend.get();
else if (!isPlayersOnly && candidate->darkArtsLastSnare) target = candidate->darkArtsLastSnare->GetLastParent();
Entity_Player* player = target && target->type == ENTITY_PLAYER ? static_cast<Entity_Player*>(target) : nullptr;
if (!target) continue;
bool isJacob = candidate->playerType == PLAYER_JACOB || candidate->playerType == PLAYER_JACOB_B ||
candidate->playerType == PLAYER_JACOB2_B;
if (source && source->type == ENTITY_DARK_ESAU && !isJacob) continue;
if (target->type == ENTITY_FAMILIAR)
reconstruction_missing("Game::GetNearestTargetPlayer 007069a0: a familiar standing in for its player");
if (player && player->IsInvisible()) continue;
float score = target_score_get(position, source, *target, player, isBulb);
if (score >= best) continue;
best = score;
nearest = target;
}
if (isPlayersOnly) return nearest;
if (isTargetDecoys)
{
for (Entity* decoy : g_game->room->entityList.mainEL)
{
if (decoy->type != ENTITY_FAMILIAR || decoy->variant != Entity_Familiar::PUNCHING_BAG) continue;
float distance = vector_length_squared(vector_sub(decoy->pos, position));
if (distance >= best) continue;
best = distance;
nearest = decoy;
}
}
if (g_game->room->entityList.isAnyBaited)
reconstruction_missing("Game::GetNearestTargetPlayer 007069a0: the baited enemies that draw attacks");
if (source && source->type == ENTITY_BLOOD_PUPPY)
reconstruction_missing("Game::GetNearestTargetPlayer 007069a0: the Blood Puppy's prey");
return nearest;
}
// 00703670 Shakes the screen for a time. The controllers' rumble is not wired here.
void game_shake_screen(int timeout)
{
g_game->screenShakeTimer = timeout;
}
// 006d8240 Whether the run is on Hard or Greedier.
bool game_is_hard_mode()
{
return g_game->difficulty == DIFFICULTY_HARD || g_game->difficulty == DIFFICULTY_GREEDIER;
}
// 00703470 Remembers a boss as met this run, but for the ones the boss list leaves out.
void game_encountered_boss_add(int bossType, int bossVariant)
{
std::vector<BossId>& bosses = g_game->encounteredBosses;
auto isSame = [&](const BossId& boss) {
return boss.type == bossType && boss.variant == bossVariant;
};
if (std::ranges::any_of(bosses, isSame)) return;
bool isListed = (bossType < BOSS_ID_NONE_EXCLUDED_FIRST || bossType > BOSS_ID_NONE_EXCLUDED_LAST) &&
bossType != BOSS_ID_EXCLUDED &&
(bossType != BOSS_ID_EXCLUDED_PAIR || bossVariant != BOSS_ID_EXCLUDED_PAIR_VARIANT);
if (isListed) bosses.push_back({bossType, bossVariant});
}
// 007f0780 The grid collision of the cell under a position, or of no cell outside the grid.
uint32_t room_grid_collision_at(const Vector& position)
{
Room& room = *g_game->room;
int column = (int)((position.x - GRID_CELL) / GRID_CELL + HALF);
int row = (int)((position.y - GRID_TOP) / GRID_CELL + HALF);
bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight;
return room.GetGridCollision(isInside ? room.gridWidth * row + column : -1);
}
// What a line check meets in a cell: an outside cell is a wall, an empty one by its grid path (3000 to 3999 a pit,
// 1000 up blocked), else its grid entity's collision. The Beast's crawlspace blocks nothing.
static int line_cell_collision(Room& room, int column, int row)
{
RoomConfig_Room* config = room.descriptor ? room.descriptor->data : nullptr;
if (config && config->type == ROOM_DUNGEON && config->stageId == STAGE_ID_HOME) return COLLISION_NONE;
if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return COLLISION_WALL;
int gridIndex = row * room.gridWidth + column;
if (GridEntity* grid = room.GetGridEntity(gridIndex)) return grid->collisionClass;
int path = room.GetGridPath(gridIndex);
if ((uint32_t)(path - GRID_PATH_PIT) < GRID_PATH_BAND) return COLLISION_PIT;
return path >= GRID_PATH_SOLID ? COLLISION_SOLID : COLLISION_NONE;
}
// Whether a blast stops at a cell: walls (but an unlocked lock or a door) and solid blocks.
static bool line_cell_is_blast_wall(Room& room, int cellIndex)
{
uint32_t collision = room.GetGridCollision(cellIndex);
bool isKnown = cellIndex >= 0 && cellIndex < ROOM_GRID_CELLS;
GridEntity* grid = isKnown ? room.gridEntities[cellIndex] : nullptr;
if (collision == COLLISION_NONE) return false;
if (!grid) return collision == COLLISION_WALL;
if (grid->type == GRID_ROCKB) return true;
if (grid->type == GRID_LOCK && g_game->playerManager.AnyoneHasTrinket(TRINKET_BROKEN_PADLOCK)) return false;
return grid->type != GRID_DOOR && collision == COLLISION_WALL;
}
// 007f0df0 Whether a line from start to end is clear, walked in steps of 10: mode 0 checks a 10 wide band for grid
// collision and for more than 8 cells walked past their grid path threshold, mode 1 the same on the line's own cells,
// mode 2 the line's own cells for what stops a blast, mode 3 the band for shots (which fly over pits). Crushable
// rocks and the stop position are left to come.
bool room_check_line(const Vector& start, const Vector& end, int mode, int gridPathThreshold)
{
Room& room = *g_game->room;
Vector step = vector_sub(start, end);
float length = vector_length(step);
if (length <= 0) return true;
step = vector_scale(step, LINE_STEP / length);
auto cellOf = [](float value, float origin) {
return (int)((value - origin) / GRID_CELL + HALF);
};
int startColumn = cellOf(start.x, GRID_CELL);
int startRow = cellOf(start.y, GRID_TOP);
bool isStartInside =
startColumn >= 0 && startColumn < room.gridWidth && startRow >= 0 && startRow < room.gridHeight;
int startIndex = isStartInside ? room.gridWidth * startRow + startColumn : -1;
int blocked = 0;
Vector at = start;
for (float walked = 0; walked < length; walked += LINE_STEP)
{
at = vector_sub(at, step);
if (mode == LINE_MODE_EXPLOSION)
{
int column = cellOf(at.x, GRID_CELL);
int row = cellOf(at.y, GRID_TOP);
bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight;
int cellIndex = isInside ? row * room.gridWidth + column : -1;
if (line_cell_is_blast_wall(room, cellIndex)) return false;
continue;
}
if (mode == LINE_MODE_CELL)
{
int column = cellOf(at.x, GRID_CELL);
int row = cellOf(at.y, GRID_TOP);
bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight;
int cellIndex = isInside ? row * room.gridWidth + column : -1;
if (room.GetGridCollision(cellIndex) != COLLISION_NONE) return false;
if (cellIndex != startIndex && cellIndex >= 0 && room.GetGridPath(cellIndex) > gridPathThreshold) blocked++;
continue;
}
for (const LineCorner& corner : LINE_CORNERS)
{
int column = cellOf(at.x + corner.x, GRID_CELL);
int row = cellOf(at.y + corner.y, GRID_TOP);
int collision = line_cell_collision(room, column, row);
if (mode == LINE_MODE_PROJECTILE && collision == COLLISION_PIT) continue;
if (collision != COLLISION_NONE) return false;
bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight;
int cornerIndex = isInside ? row * room.gridWidth + column : -1;
if (cornerIndex == startIndex) continue;
int path = cornerIndex >= 0 ? room.GetGridPath(cornerIndex) : 0;
if (mode == LINE_MODE_GROUND && path > gridPathThreshold) blocked++;
}
}
return blocked <= LINE_BLOCKED_MAX;
}
// The suppression the console sets so its next spawned NPC is not rolled a champion (the original's 00c71670).
bool g_isChampionRollSkipped = false;
// 006b8b20 Starts it appearing: every counter and link back to its defaults, its config loaded (Entity::Init), and
// a boss counted by the room.
void Entity_NPC::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed)
{
isChampion = false;
championColorIdx = CHAMPION_NONE;
flickerTimer = 0;
flickerState = 0;
flickerAlpha = 1;
championSpeed = 1;
bosscoloridx = -1;
isUnreachableOnce = false;
scale = 1;
shieldStrength = 0;
shieldFrames = SHIELD_FRAMES_DEFAULT;
deliriumBossType = 0;
deliriumBossVariant = 0;
deliriumTransformationTimer = 0;
deliriumRemainingAttacks = 0;
deliriumState = 0;
deliriumEntity = nullptr;
isBestiaryEncountered = false;
isDeathSoundAlt = false;
aiCallFlags = 0;
controllerID = -1;
unknownF2c = 0;
controllerMovement = {};
aimTargetEffect = nullptr;
forwardVector = {};
forcedTarget = nullptr;
forcedTargetTimer = 0;
sirenPlayerEntity = nullptr;
hitPointsMulti = 1;
scaleMulti = 1;
lastGridIndex = -1;
if (pickupGhostsEntity) pickupGhostsEntity->Remove();
pickupGhostsEntity = nullptr;
if (salvationTarget) salvationTarget->Remove();
salvationTarget = nullptr;
unknownF54 = nullptr;
killDamageEvents.clear();
killDamage = 0;
killDamageFlags = 0;
Entity::Init(entityType, entityVariant, entitySubType, seed);
AddEntityFlags(FLAG_APPEAR);
state = NPC_STATE_APPEAR;
savedState = NPC_STATE_INIT;
aiCallPhase = AI_PHASE_UPDATE;
stateFrame = 0;
aiCounter = 0;
appearFrames = 0;
decoyTargetTimer = 0;
groupIdx = -1;
targetPosition = {};
confusionTargetPos = {};
aiFloat = 1;
v1 = {};
v2 = {};
championRegenTimer = 0;
championRegenCount = 0;
holdCountdown = 0;
i1 = 0;
i2 = 0;
entityRef = nullptr;
projectileCooldown = 0;
projectileDelay = -1;
championTimer = 0;
holdPosition = {};
isUnknownC61 = false;
isUnknownC62 = false;
floorColor = {};
hitList.clear();
secondaryHitList.clear();
pathfinder.Reset();
if (isBoss) g_game->room->bossesRemaining++;
totalDamageTaken = 0;
lua_engine_get().PostNPCInit(this);
}
// The odds a boss spawns in one of its alternate colors.
static float boss_color_chance_get()
{
Game& game = *g_game;
float chance = g_manager->persistentGameData.Unlocked(ACHIEVEMENT_MORE_BOSS_COLORS) ? 0.3f : 0.1f;
if (game.difficulty == DIFFICULTY_GREEDIER) chance = 0.6f;
if (game.playerManager.AnyoneHasTrinket(TRINKET_PURPLE_HEART_ID))
chance *= (float)game.playerManager.GetTrinketMultiplier(TRINKET_PURPLE_HEART_ID) * 2;
if (game.challenge == CHALLENGE_ULTRA_HARD || game.victoryLap > 0) chance = 1;
return chance;
}
// Part of 006bb790: a boss rolls one of its alternate colors from the room's spawn seed (its subtype, 1 up), the
// Repentance stages fix Monstro's and Gurdy Jr's, and a color that loads swaps in its sheet, scale and health.
void Entity_NPC::boss_color_roll()
{
Game& game = *g_game;
int colors = (int)config->bossColors.size();
if (spawnerEntity && spawnerEntity->type == ENTITY_BIG_HORN) colors = 0;
if (g_isChampionRollSkipped)
{
colors = 0;
g_isChampionRollSkipped = false;
}
else if (colors > 0 && subtype == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_BOSS_COLORS))
{
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 (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;
EntityConfig_BossColor color = config->bossColors[subtype - 1];
bosscoloridx = subtype - 1;
sprite.scale = vector_scale(sprite.scale, color.scale);
scale = color.scale;
maxHitPoints *= color.hpMultiplier;
ResetColor();
load_graphics(true);
sprite.SetFrame(sprite.GetDefaultAnimationName(), 0);
}
// 006bb790 Loads its config and sprite, then rolls whether it spawns a champion, or a boss's alternate color.
void Entity_NPC::LoadEntityConfig()
{
RNG rng = {initSeed, 1, 5, 16};
isBoss = false;
Entity::LoadEntityConfig();
if (!config)
{
log_printf(LOG_INFO, "[warn] No entity config for NPC %d.%d\n", type, variant);
return;
}
load_graphics(true);
sprite.scale = vector_make(1, 1);
if (sprite.SetAnimation(sprite.GetDefaultAnimationName(), SWITCH_KEEP_FRAME) && sprite.animState.animData)
{
sprite.animState.SetFrameFloat(0);
sprite.animState.isPlaying = false;
}
isCanShutDoors = config->isShutDoors;
isBoss = config->isBoss;
shieldStrength = config->shieldStrength;
shieldFrames = config->shieldFrames;
Game& game = *g_game;
Room& room = *game.room;
float chance = game.playerManager.FirstCollectibleOwner(COLLECTIBLE_CHAMPION_BELT_ID, LAZARUS_SHARE_CHECK)
? CHAMPION_CHANCE_BELT
: CHAMPION_CHANCE;
if (game.stage == STAGE_VOID) chance = CHAMPION_CHANCE_VOID;
if (game.playerManager.AnyoneHasTrinket(TRINKET_PURPLE_HEART_ID))
chance *=
(float)game.playerManager.GetTrinketMultiplier(TRINKET_PURPLE_HEART_ID) * CHAMPION_CHANCE_PURPLE_HEART;
if (room.isInitialized) chance *= CHAMPION_CHANCE_LATE_SPAWN;
if (game.seedEffects.HasSeedEffect(SEED_ALL_CHAMPIONS)) chance = 1;
if (isBoss) boss_color_roll();
else
{
bool isAllowed = config->isCanBeChampion && !isChampion && !room.isInitialized &&
!room.has_room_config_flag(ROOM_CONFIG_FLAG_NO_CHAMPIONS) &&
(room.roomType != ROOM_BOSS || type != ENTITY_ULTRA_GREED_DOOR);
if (isAllowed && (rng.RandomFloat() < chance || game.challenge == CHALLENGE_ULTRA_HARD ||
(game.victoryLap > 0 && rng.RandomFloat() < CHAMPION_CHANCE_VICTORY_LAP)))
isChampion = true;
}
if (g_isChampionRollSkipped)
{
isChampion = false;
g_isChampionRollSkipped = false;
}
else if (isChampion) MakeChampion(rng.Next(), championColorIdx, true);
}
// 006b9c10 A layer's sheet with the champion suffix and the stage's floor suffix put before its extension, the first
// of (both, champion only, floor only) a mod or the resources hold, else the sheet itself. isChampionSheet says
// whether the one found has the champion suffix.
std::string sheet_path_resolve(const std::string& path, std::string_view floorSuffix, std::string_view championSuffix,
bool& isChampionSheet)
{
isChampionSheet = false;
if (path.size() < SHEET_EXTENSION_SIZE || (floorSuffix.empty() && championSuffix.empty())) return path;
std::string stem = path.substr(0, path.size() - SHEET_EXTENSION_SIZE);
std::string extension = path.substr(path.size() - SHEET_EXTENSION_SIZE);
auto isFound = [&](const std::string& candidate) {
return std::filesystem::exists(resource_path(g_manager->modManager.TryRedirectPath(candidate)));
};
std::string both = stem + std::string(championSuffix) + std::string(floorSuffix) + extension;
if (!championSuffix.empty() && !floorSuffix.empty() && isFound(both))
{
isChampionSheet = true;
return both;
}
std::string champion = stem + std::string(championSuffix) + extension;
if (!championSuffix.empty() && isFound(champion))
{
isChampionSheet = true;
return champion;
}
std::string floor = stem + std::string(floorSuffix) + extension;
return !floorSuffix.empty() && isFound(floor) ? floor : path;
}
// 006baf40 Reloads its sprite (with isReloadAnm2, from the config or its boss color's .anm2) and swaps each layer's
// sheet for its champion and floor versions, marking the layers drawn in the floor's dirt color.
void Entity_NPC::load_graphics(bool isReloadAnm2)
{
bool isBossColor = bosscoloridx >= 0 && bosscoloridx < (int)config->bossColors.size();
if (isReloadAnm2)
{
bool isColorAnm2 = isBossColor && !config->bossColors[bosscoloridx].anm2Path.empty();
sprite.Load(isColorAnm2 ? config->bossColors[bosscoloridx].anm2Path : config->anm2Path, GRAPHICS_DEFER);
if (g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && type == ENTITY_ISAAC_BOSS && variant == 1)
sprite.Load(GFUEL_ISAAC_ANM2, GRAPHICS_LOAD);
}
std::string floorSuffix;
if (isBossColor) floorSuffix = config->bossColors[bosscoloridx].suffix;
else if (config->isHasFloorAlts) floorSuffix = g_game->roomConfig.stages[Level::GetStageID()].suffix;
const ColorMod* championLook = isChampion ? champion_color_get(championColorIdx) : nullptr;
std::string_view championSuffix = championLook ? CHAMPION_SUFFIX : "";
bool isChampionSheetUsed = false;
bool isDirtUsed = false;
for (int i = 0; i < (int)sprite.layerStates.size(); i++)
{
LayerState& layer = sprite.layerStates[i];
std::string name = layer.layerData ? layer.layerData->name : "";
if (name == DIRT_LAYER || name == HOLE_LAYER)
{
layer.bitflags |= LAYER_DIRT_COLORED;
isDirtUsed = true;
}
if (name == HOLE2_LAYER) layer.bitflags |= LAYER_DIRT_COLORED;
bool isChampionSheet = false;
std::string sheet = layer.layerData ? layer.layerData->spriteSheetPath : "";
sprite.ReplaceSpritesheet(i, sheet_path_resolve(sheet, floorSuffix, championSuffix, isChampionSheet));
LayerState& replaced = sprite.layerStates[i];
replaced.bitflags =
isChampionSheet ? replaced.bitflags | LAYER_CHAMPION_SHEET : replaced.bitflags & ~LAYER_CHAMPION_SHEET;
isChampionSheetUsed = isChampionSheetUsed || isChampionSheet;
}
sprite.championColor = isChampionSheetUsed && championLook ? *championLook : ColorMod{};
bool isFlagged = type == TYPE_SPRITE_FLAG_A || (type == TYPE_SPRITE_FLAG_B && variant == VARIANT_SPRITE_FLAG_B);
sprite.bitflags = isFlagged ? sprite.bitflags | SPRITE_UNKNOWN_FLAG_20 : sprite.bitflags & ~SPRITE_UNKNOWN_FLAG_20;
sprite.LoadGraphics();
if (isDirtUsed) UpdateDirtColor(true);
}
// 006c04b0 Lerps its dirt layers toward the floor color under it (Room::GetFloorColorAt doubled), sampled every 15
// frames unless isImmediate. A green champion's dirt is green.
void Entity_NPC::UpdateDirtColor(bool isImmediate)
{
if (isImmediate || IsFrame(DIRT_SAMPLE_FRAMES, (int)index))
{
KColor floor = kcolor_rgba(0, DIRT_GREEN / 2, 0, 1);
if (!isChampion || championColorIdx != CHAMPION_GREEN) floor = room_floor_color_get(*g_game->room, pos, size);
dirtColor._tint[0] = floor._red * 2;
dirtColor._tint[1] = floor._green * 2;
dirtColor._tint[2] = floor._blue * 2;
dirtColor._tint[3] = 1;
}
for (int i = 0; i < (int)sprite.layerStates.size(); i++)
{
LayerState& layer = sprite.layerStates[i];
std::string name = layer.layerData ? layer.layerData->name : "";
if (name == DIRT_LAYER || name == HOLE_LAYER)
layer.color = color_lerp(layer.color, dirtColor, isImmediate ? 1 : DIRT_LERP);
}
}
// 006d0300 Switches to another of its boss colors, reloading its sprite on its default animation's first frame.
void Entity_NPC::SetBossColorIdx(int bossColorIdx, int)
{
if (bosscoloridx != bossColorIdx)
{
bosscoloridx = bossColorIdx;
load_graphics(true);
if (sprite.SetAnimation(sprite.GetDefaultAnimationName(), SWITCH_KEEP_FRAME) && sprite.animState.animData)
{
sprite.animState.SetFrameFloat(0);
sprite.animState.isPlaying = false;
}
}
ResetColor();
}
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}};
// The enemy a "random enemy" spawn (type 306) turns into on each stage, on Normal and on Hard.
struct StageEnemy
{
int normalType;
int normalVariant;
int hardType;
int hardVariant;
};
constexpr int REDIRECT_RANDOM_ENEMY = 306;
constexpr std::array<StageEnemy, 18> STAGE_RANDOM_ENEMIES = {{
{85, 0, 94, 0},
{10, 0, 284, 0},
{85, 0, 94, 0},
{10, 0, 284, 0},
{21, 0, 23, 0},
{26, 0, 26, 1},
{23, 0, 23, 1},
{209, 0, 227, 0},
{227, 0, 24, 1},
{24, 0, 277, 0},
{15, 0, 58, 0},
{58, 0, 39, 0},
{39, 0, 39, 1},
{297, 0, 297, 0},
{87, 0, 252, 0},
{26, 2, 55, 2},
{48, 1, 50, 1},
{267, 0, 410, 0},
}};
constexpr std::array<StageEnemy, 6> GREED_RANDOM_ENEMIES = {{
{10, 0, 284, 0},
{21, 0, 23, 0},
{209, 0, 227, 0},
{15, 0, 58, 0},
{87, 0, 252, 0},
{50, 0, 50, 1},
}};
constexpr int GREED_RANDOM_ENEMY_DEFAULT = 299;
constexpr int STAGE_RANDOM_ENEMY_BLUE_WOMB = 26;
constexpr StageEnemy BLUE_WOMB_RANDOM_ENEMY = {412, 0, 412, 0};
// Normal or Greed (the easy ones) against Hard or Greedier.
static bool is_easy_difficulty()
{
return g_game->difficulty == DIFFICULTY_NORMAL || g_game->difficulty == DIFFICULTY_GREED;
}
// 006c07e0 Swaps an enemy about to spawn for what it stands for: Bulbs (61.5) for flies until they are unlocked, the
// placeholder types (299 to 306) for their difficulty's or stage's enemy until the redirects are unlocked, and with
// G-Fuel a few enemies for their variants. True when it picked a placeholder's enemy.
bool Entity_NPC::Redirect(int* entityType, int* entityVariant)
{
PersistentGameData& data = g_manager->persistentGameData;
if (!data.Unlocked(ACHIEVEMENT_MORE_BOSS_COLORS) && *entityType == ENTITY_SUCKER &&
*entityVariant == SUCKER_VARIANT_BULB)
{
*entityType = ENTITY_FLY;
*entityVariant = 0;
}
bool isEasy = is_easy_difficulty();
auto redirect = [&](int newType, int newVariant) {
*entityType = newType;
*entityVariant = newVariant;
return true;
};
auto byDifficulty = [&](const StageEnemy& enemy) {
return isEasy ? redirect(enemy.normalType, enemy.normalVariant) : redirect(enemy.hardType, enemy.hardVariant);
};
if (!data.Unlocked(ACHIEVEMENT_REDIRECTS))
{
switch (*entityType)
{
case 303:
return isEasy ? redirect(29, 1) : redirect(250, 0);
case 300:
return redirect(27, 0);
case 305:
return redirect(29, 0);
case 231:
*entityVariant = 0;
return true;
case 301:
return redirect(32, 0);
case 302:
return redirect(isEasy ? 208 : 257, 0);
case 304:
return redirect(isEasy ? 240 : 242, 0);
case REDIRECT_RANDOM_ENEMY:
if (g_game->IsGreedMode())
{
int stage = (int)g_game->stage;
bool isListed = stage >= 1 && stage <= (int)GREED_RANDOM_ENEMIES.size();
return isListed ? byDifficulty(GREED_RANDOM_ENEMIES[stage - 1])
: redirect(GREED_RANDOM_ENEMY_DEFAULT, 0);
}
{
int stage = g_game->room->GetRoomConfigStage();
if (stage == STAGE_RANDOM_ENEMY_BLUE_WOMB) return byDifficulty(BLUE_WOMB_RANDOM_ENEMY);
if (stage >= 0 && stage < (int)STAGE_RANDOM_ENEMIES.size())
return byDifficulty(STAGE_RANDOM_ENEMIES[stage]);
}
break;
}
}
if (!g_game->seedEffects.HasSeedEffect(SEED_G_FUEL)) return false;
switch (*entityType)
{
case 27:
*entityVariant = 1;
break;
case 204:
*entityType = 247;
break;
case 859:
*entityType = 25;
*entityVariant = 1;
break;
case 221:
*entityType = 58;
break;
}
return false;
}
// 006c0f30 Turns it into another entity in place: its config and color reloaded, its health refilled, its champion
// kept only where the new one can be one. An enemy the run erased leaves in a poof.
void Entity_NPC::Morph(int entityType, int entityVariant, int entitySubType, int championId)
{
bool isSame = entityType == type && entityVariant == variant && entitySubType == subtype &&
(championId < 0 || championId == championColorIdx);
if (isSame) return;
type = entityType;
variant = entityVariant;
subtype = entitySubType;
if (championId >= 0)
{
championColorIdx = championId;
isChampion = true;
}
EntityConfig_Entity* found = g_manager->entityConfig.GetEntity(entityType, entityVariant, entitySubType);
if (found && !found->isCanBeChampion)
{
championColorIdx = CHAMPION_NONE;
isChampion = false;
}
flickerTimer = 0;
championRegenTimer = 0;
flickerState = 0;
flickerAlpha = 1;
championSpeed = 1;
championTimer = 0;
ResetColor();
scale = 1;
sprite.scale = vector_make(shrinkStatus1, shrinkStatus1);
LoadEntityConfig();
totalDamageTaken = 0;
health = hitPointsMulti * maxHitPoints;
if (!colorParams.empty()) SetColor(COLOR_DEFAULT, 1, MORPH_COLOR_PRIORITY, false, true);
pathfinder.Reset();
g_manager->persistentGameData.TryAddBestiaryEncounter(type, variant);
isBestiaryEncountered = true;
if (game_is_enemy_erased(*this)) Entity::RemoveWithPoof(this);
}
// 007078f0 Whether the run erased this kind of enemy (Eraser). A friendly enemy is never erased.
bool game_is_enemy_erased(Entity& entity)
{
if (entity.type == ENTITY_ERASE_EXEMPT || (Entity::is_enemy_type(entity.type) && entity.IsFriendly())) return false;
if (g_game->erasedEntities.empty()) return false;
reconstruction_missing("Game::ShouldEraseEnemy 007078f0: FixErasedEnemyID");
}
// 006c4ac0 Remembers where it was, and keeps the Exorcist's room in its state while it lives.
void Entity_NPC::PreUpdate()
{
prevPosition = pos;
prevVelocity = velocity;
if (type == ENTITY_EXORCIST && variant == 0 && !isDead) g_game->room->isExorcistActive = true;
}
// 006b8f00 Removes it, and the Dark Esau with it if it is the one that holds him.
void Entity_NPC::Remove()
{
if (type == ENTITY_DARK_ESAU && variant == 0 && child) child->Remove();
Entity::Remove();
}
// 006b8450 Whether it holds the doors shut: one that can, unless it became friendly.
bool Entity_NPC::CanShutDoors()
{
return isCanShutDoors && !IsFriendly();
}
// 006b8470
bool Entity_NPC::IsBoss()
{
return isBoss;
}
// 006a8240 Forgets where its pathfinder was taking it.
void Entity_NPC::ResetPathFinderTarget()
{
pathfinder.movementTarget = {};
pathfinder.moveDirection = {};
}
// 006d6610 Scales it, shrinking included.
void Entity_NPC::SetScale(float newScale)
{
scale = newScale;
sprite.scale = vector_make(newScale * shrinkStatus1, newScale * shrinkStatus1);
}
// 006b9910 Sends it after a target for a time, unless forced targets are on cooldown or the one it has is nearer.
bool Entity_NPC::TryForceTarget(Entity* newTarget, int duration)
{
if (forcedTargetTimer < 0) return false;
Entity* current = forcedTarget;
bool isKept = current == newTarget;
if (!isKept && current)
{
float currentDistance = vector_length_squared(vector_sub(pos, current->pos));
if (currentDistance <= vector_length_squared(vector_sub(pos, newTarget->pos))) return false;
}
if (!isKept) forcedTarget = newTarget;
forcedTargetTimer = duration;
return true;
}
// 006d6ba0 Plays a sound, higher for a tiny champion and lower for a giant one.
void Entity_NPC::PlaySound(int id, float volume, int frameDelay, bool isLoop, float pitch)
{
if (championColorIdx == CHAMPION_TINY) pitch += 0.5f;
else if (championColorIdx == CHAMPION_GIANT) pitch *= 0.5f;
seed_fart_sound_override(&id);
g_manager->sfxManager.Play(
id, {.volume = volume, .frameDelay = frameDelay, .loop = isLoop ? SOUND_LOOP : SOUND_ONCE, .pitch = pitch});
}
// 006b64d0 Leaves a blood splat of a size where it stands.
Entity_Effect* Entity_NPC::MakeSplat(float size)
{
Entity* splat = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, 0, pos, this);
splat->sprite.scale = vector_make(size, size);
splat->Update();
return static_cast<Entity_Effect*>(splat);
}
// 006d6c20 The enemies its side still faces: the room's living enemies, or for a friendly one the friendly enemies.
int Entity_NPC::GetAliveEnemyCount()
{
if (!IsFriendly()) return g_game->room->GetAliveEnemiesCount();
int count = 0;
for (Entity* entity : g_game->room->entityList.mainEL)
if (Entity::is_enemy_type(entity->type) && !entity->isDead && entity->IsFriendly()) count++;
return count;
}
// 006d48a0 The way it faces: the forward vector an AI set, else down for a few, else along its motion.
Vector Entity_NPC::GetForwardVector()
{
if (!vector_is_zero(forwardVector)) return forwardVector;
if (type == ENTITY_FORWARD_NONE) return {};
if (type == ENTITY_FORWARD_DOWN_A || type == ENTITY_FORWARD_DOWN_B) return vector_make(0, 1);
return Entity::GetForwardVector();
}
// Part of 006c4b30: shows the status effect it suffers on its OverlayEffect null, most important first. The
// shadow champion charger is never charmed, and Crown and Skull mark the king and death champions.
void Entity_NPC::status_overlay_update()
{
bool isShadowCharger = type == ENTITY_SHADOW_CHARGER && variant == 0 && subtype == SHADOW_CHARGER_SUBTYPE;
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);
bool isTimeImmune = (flags & (FLAG_FRIENDLY | FLAG_NO_STATUS_EFFECTS)) && type != ENTITY_DEATHS_HEAD;
std::string_view animation;
bool isShared = false;
if (championColorIdx == CHAMPION_KING) animation = "Crown";
else if (championColorIdx == CHAMPION_DEATH) animation = "Skull";
isShared = !animation.empty();
if (HasEntityFlags(FLAG_CHARM) && !isShadowCharger) animation = "Charm", isShared = true;
else if (HasEntityFlags(FLAG_BRIMSTONE_MARKED)) animation = "BrimstoneCurse", isShared = true;
else if (HasEntityFlags(FLAG_MAGNETIZED)) animation = "Magnetize", isShared = true;
else if (HasEntityFlags(FLAG_BAITED)) animation = "Bait", isShared = false;
else if (HasEntityFlags(FLAG_CONFUSION)) animation = "Confuse", isShared = true;
else if (HasEntityFlags(FLAG_BURN)) animation = "Burning", isShared = false;
else if (HasEntityFlags(FLAG_POISON)) animation = "Poison", isShared = true;
else if (HasEntityFlags(FLAG_FEAR)) animation = "Fear", isShared = true;
else if (HasEntityFlags(FLAG_BLEED_OUT)) animation = "BleedingOut", isShared = true;
else if (HasEntityFlags(FLAG_SLOW) || (isTimeSlowed && !isTimeImmune)) animation = "Slow", isShared = true;
else if (HasEntityFlags(FLAG_WEAKNESS)) animation = "Weakness", isShared = true;
else if (type == ENTITY_SIREN_HELPER) animation = "EnemyCharm", isShared = true;
else if (animation.empty())
{
if (statusEffectSprite.animState.animData) statusEffectSprite.animState.isPlaying = false;
return;
}
if (!statusEffectSprite.isLoaded) statusEffectSprite.Load(STATUS_EFFECTS_ANM2, GRAPHICS_LOAD);
if (statusEffectSprite.IsPlaying() && statusEffectSprite.isLoaded)
{
statusEffectSprite.animState.Update(statusEffectSprite.playbackSpeed);
statusEffectSprite.overlayAnimState.Update(statusEffectSprite.playbackSpeed);
}
statusEffectSprite.Play(animation);
statusEffectSprite.bitflags = isShared ? STATUS_SHARED : 0;
}
// Part of 006c4b30: stopped by a pause or held (Lil Abaddon, a hook), it stays put and slows, its AI's pre-update
// call and the base update still run (without its sprite), and it goes on with the update only if that killed it.
// False when the update stops here.
bool Entity_NPC::paused_update()
{
if (vector_is_zero(pausePosition)) pausePosition = pos;
if (pauseTimer > 0 && --pauseTimer > 0) pos = pausePosition;
velocity = vector_scale(velocity, PAUSE_SLOWDOWN);
bool wasDead = isDead;
spawn_damage_numbers();
update_damage_history();
if (aiCallFlags & AI_CALL_PRE_UPDATE) ai_call(AI_PHASE_PRE_UPDATE);
float healthBefore = health;
bool isSpriteFrozen = HasEntityFlags(FLAG_NO_SPRITE_UPDATE);
AddEntityFlags(FLAG_NO_SPRITE_UPDATE);
Entity::Update();
if (!isSpriteFrozen) ClearEntityFlags(FLAG_NO_SPRITE_UPDATE);
totalDamageTaken += std::max(healthBefore - health, 0.0f);
return wasDead != isDead;
}
// Runs the AI in a phase other than the update's own.
void Entity_NPC::ai_call(AiPhase phase)
{
aiCallPhase = phase;
npc_ai_update(*this);
aiCallPhase = AI_PHASE_UPDATE;
}
// Part of 006c4b30: the first appear frame runs the AI's init (a champion's or Tick's changes with it), the second
// poofs it in, the fourth shows it playing Appear, and once that ends (20 frames at least) its AI takes over.
void Entity_NPC::appear_update()
{
if (appearFrames == 0) appear_init();
else if (appearFrames == APPEAR_POOF_FRAME)
{
Entity* poof = spawn_at(ENTITY_EFFECT, EFFECT_POOF01, poof_size_get(*this, false), pos, this);
poof->posOffset = posOffset;
poof->renderDepthOffset = posOffset.y + 1;
if (isChampion && championColorIdx < CHAMPION_COUNT)
poof->SetColor(champion_sprite_color_get(championColorIdx), -1, COLOR_PRIORITY_DEFAULT, false, true);
int sound = isDeathSoundAlt ? SOUND_SUMMON_WAVE : SOUND_SUMMON_POOF;
g_manager->sfxManager.Stop(sound);
PlaySound(sound, 1, 2, false, 1);
if (type == ENTITY_STAIN)
{
npc_sound_play(SOUND_MAGGOT_BURST_OUT, 1, 2, 1);
PlaySound(SOUND_THE_STAIN_BURST, 1, 2, false, 1);
}
else if (type == ENTITY_FORSAKEN) PlaySound(SOUND_FORSAKEN_LAUGH, 1, 2, false, 1);
else if (type == ENTITY_BIG_HORN && variant == 0) PlaySound(SOUND_BOSS_LITE_ROAR, BIG_HORN_APPEAR_VOLUME, 2, false, 1);
}
else if (appearFrames == APPEAR_SHOW_FRAME)
{
if (type != ENTITY_PIN) isVisible = true;
if (sprite.GetAnimationData("Appear"))
{
if (type != APPEAR_OVERLAY_KEPT_TYPE) sprite.RemoveOverlay();
sprite.Play("Appear", PLAY_FORCED);
}
}
else
{
bool isAppearing =
sprite.GetAnimationData("Appear") && !sprite.IsFinished("Appear") && sprite.GetAnimation() == "Appear";
if (appearFrames >= APPEAR_MIN_FRAMES && !isAppearing)
{
state = savedState;
friction = baseFriction;
}
}
if (std::ranges::find(APPEAR_EVENT_TYPES, type) != APPEAR_EVENT_TYPES.end())
boss_appear_events(*this);
if (state == NPC_STATE_APPEAR) friction *= APPEAR_FRICTION;
appearFrames++;
}
// Part of 006c4b30: the AI's init call on the first appear frame, with what spawning does to it.
void Entity_NPC::appear_init()
{
state = NPC_STATE_INIT;
if (championColorIdx == CHAMPION_WHITE)
{
isInvincible = true;
AddEntityFlags(FLAG_NO_STATUS_EFFECTS);
}
npc_ai_update(*this);
if (championColorIdx == CHAMPION_FLY_PROTECTED || championColorIdx == CHAMPION_RAINBOW)
spawn_at(ENTITY_ETERNALFLY, 0, 0, pos, this)->parent = this;
if (HasEntityFlags(FLAG_APPEAR))
{
isVisible = false;
savedState = state;
state = NPC_STATE_APPEAR;
}
PlayerManager& players = g_game->playerManager;
if (players.AnyoneHasTrinket(TRINKET_TICK_ID) && type != TYPE_NO_TICK_A && type != TYPE_NO_TICK_B &&
health > TICK_HEALTH_MIN)
for (int i = 0; i < players.GetTrinketMultiplier(TRINKET_TICK_ID); i++) health *= TICK_HEALTH_SCALE;
auto isDirt = [](const LayerState& layer) {
return layer.layerData && (layer.layerData->name == DIRT_LAYER || layer.layerData->name == HOLE_LAYER);
};
if (std::ranges::any_of(sprite.layerStates, isDirt)) UpdateDirtColor(true);
if (IsBoss() && !parent) game_encountered_boss_add(type, variant);
}
// Rag Man keeps its head through its death only if the head shows on the frame it died on.
static void death_head_layer_keep(ANM2& sprite)
{
LayerState* head = sprite.GetLayer("Head");
if (!head) return;
const AnimationFrame* frame = sprite.animState.GetLayerFrame(head->layerData ? head->layerData->id : -1);
head->isVisible = frame && frame->isVisible;
}
// Part of 006c4b30: what the bosses with death events do as they die: Isaac's cry, Baby Plum's spit and last ring,
// Reap Creep losing its overlay, Singe's blast, Mother's slam, Clutch's explosions and Gideon's own.
static void death_events_update(Entity_NPC& npc)
{
switch (npc.type)
{
case ENTITY_ISAAC:
if (npc.variant != ISAAC_FORM_HUSH && npc.stateFrame == ISAAC_DEATH_CRY_FRAME)
npc.PlaySound(SOUND_SUPERHOLY, ISAAC_DEATH_CRY_VOLUME, 2, false, 1);
return;
case ENTITY_BABY_PLUM:
{
if (npc.sprite.IsEventTriggered("Shoot")) npc_sound_play(SOUND_MEAT_JUMPS, 1, 2, 1);
if (!npc.sprite.IsFinished() || !npc.isDead) return;
ProjectileParams params;
params.fallingAccelModifier -= PLUM_RING_FALL;
return npc.FireProjectiles(npc.pos, vector_make(PLUM_RING_SPEED, PLUM_RING_SHOTS), PROJECTILES_RING, params);
}
case ENTITY_GIDEON:
return gideon_death_update(npc);
case ENTITY_REAP_CREEP:
if (npc.sprite.overlayAnimState.animData) npc.sprite.RemoveOverlay();
return;
case ENTITY_SINGE:
if (npc.sprite.IsFinished() && npc.isDead)
explosion_effects({.position = npc.pos, .source = &npc, .damage = SINGE_BLAST_DAMAGE,
.radiusMultiplier = SINGE_BLAST_REACH});
return;
case ENTITY_MIN_MIN:
return min_min_death_update(npc);
case ENTITY_MOTHER:
if (npc.variant != MOTHER_SLAM_VARIANT || !npc.sprite.IsEventTriggered("Shoot")) return;
game_shake_screen(MOTHER_SLAM_SHAKE);
return npc.PlaySound(SOUND_DEATH_REVERSE, 1, 2, false, MOTHER_SLAM_PITCH);
case ENTITY_CLUTCH:
{
if (!npc.sprite.IsEventTriggered("Explosion")) return;
Entity* blast = spawn_at(ENTITY_EFFECT, EFFECT_ENEMY_GHOST, CLUTCH_BLAST_SUBTYPE, npc.pos, nullptr);
blast->posOffset = vector_make(0, CLUTCH_BLAST_RAISE);
blast->sprite.rotation = random_unit() * CLUTCH_BLAST_SPIN;
blast->sprite.scale = vector_make(CLUTCH_BLAST_SCALE, CLUTCH_BLAST_SCALE);
blast->SetCollisionDamage(CLUTCH_BLAST_DAMAGE);
blast->Update();
npc_sound_play(SOUND_DEMON_HIT, CLUTCH_BLAST_VOLUME, 2, random_unit() * CLUTCH_PITCH_SPREAD + CLUTCH_PITCH);
return game_shake_screen(CLUTCH_BLAST_SHAKE);
}
}
}
// Part of 006c4b30: a boss or Chub dying through its death animations, which ends it (trigger_kill_item_effects).
void Entity_NPC::death_animation_update()
{
if (state != NPC_STATE_DEATH && state != NPC_STATE_UNIQUE_DEATH) return;
friction *= APPEAR_FRICTION;
if (stateFrame == 0) death_animation_start();
stateFrame++;
death_events_update(*this);
if (const NullFrame* bloodGuide = sprite.GetNullFrame("BloodGuide")) npc_blood_guide_update(*this, *bloodGuide);
if (type == ENTITY_HUSH && sprite.IsEventTriggered("ash") && !HasEntityFlags(FLAG_DELIRIUM_FORM))
{
if (Entity* ashes = spawn_at(ENTITY_EFFECT, EFFECT_HUSH_ASHES, 0, pos, this)) ashes->Update();
game_shake_screen(HUSH_ASH_SHAKE);
npc_sound_play(SOUND_SUPERHOLY, 1, 2, 1);
}
if (sprite.IsFinished() && isExists) trigger_kill_item_effects();
}
// Part of 006c4b30: the first frame of the death states: a flushed boss plays Flush, the rest Death, or bursts
// where it has none.
void Entity_NPC::death_animation_start()
{
bool isFlushable = std::ranges::find(FLUSH_TYPES, type) != FLUSH_TYPES.end() ||
(type == FLUSH_PROP_TYPE && variant == FLUSH_PROP_VARIANT);
if (state == NPC_STATE_UNIQUE_DEATH)
{
if (!isFlushable) return;
if (sprite.GetAnimationData("Flush"))
{
sprite.Play("Flush");
renderZOffset = FLUSH_RENDER_Z;
return;
}
state = NPC_STATE_DEATH;
}
if (sprite.GetAnimationData("Death"))
{
if (type == ENTITY_BIG_HORN) return big_horn_death_play(*this);
if (type == ENTITY_RAG_MAN) death_head_layer_keep(sprite);
sprite.Play("Death");
return;
}
if (type == ENTITY_CHUB || type == ENTITY_LARRYJR || type == ENTITY_PIN || type == ENTITY_TURDLET)
return segment_death_animation_play(*this);
if (type >= DEATH_NO_BURST_FIRST && type <= DEATH_NO_BURST_LAST) return;
BloodExplode();
trigger_kill_item_effects();
}
// Part of 006c4b30: a charmed enemy's attention drifts to a Punching Bag it targets for up to 180 frames, then away
// for as long, before the bag can draw it again.
void Entity_NPC::decoy_update()
{
if (decoyTargetTimer > DECOY_TIMER_MAX) decoyTargetTimer = -1;
else if (decoyTargetTimer < -DECOY_TIMER_MAX) decoyTargetTimer = 0;
Entity* playerTarget = GetPlayerTarget();
if (playerTarget->type == ENTITY_FAMILIAR && playerTarget->variant == Entity_Familiar::PUNCHING_BAG) decoyTargetTimer++;
else if (decoyTargetTimer != 0) decoyTargetTimer--;
}
// Part of 006c4b30: in a room that checks it, an enemy no grounded player has a path to stops holding the doors
// after its second miss, checked every 60 frames once 900 frames passed.
void Entity_NPC::unreachable_update()
{
Room& room = *g_game->room;
if (!room.isUnknown11f5) return;
bool isGrounded = !isDead && !isBoss && !IsFlying() && entityGridCollisionClass != GRIDCOLL_NOPITS &&
type != ENTITY_UNREACHABLE_EXEMPT;
int frames = room.GetFrameCount();
if ((uint32_t)(frames + (int)index) % UNREACHABLE_CHECK_FRAMES != 0 || frames <= UNREACHABLE_GRACE_FRAMES ||
!isGrounded)
return;
if (room.roomType != ROOM_DEFAULT || room.IsClear() || any_player_flying()) return;
for (Entity_Player* player : g_game->playerManager.playerList)
if (!player->IsFlying() && pathfinder.HasPathToPos(player->pos, true)) return;
if (!isUnreachableOnce) isUnreachableOnce = true;
else isCanShutDoors = false;
}
// 009be9c0 Whether a living player moves over pits (its grid collision ignores them).
bool any_player_flying()
{
for (Entity_Player* player : g_game->playerManager.playerList)
if (!player->isCoopGhost && player->entityGridCollisionClass <= GRIDCOLL_WALLS) return true;
return false;
}
// Part of 006c4b30: the frame it dies: its burst, Midas' coins, its death triggers (rewards and the players' on-kill
// items), Toxic Shock's creep, then its removal, or a boss's death animation. In a crawlspace it drops off a ladder.
void Entity_NPC::dead_update()
{
PlayDeathEffects();
if (HasEntityFlags(FLAG_MIDAS_FREEZE) && !HasEntityFlags(FLAG_NO_REWARD)) midas_coins_spawn();
if (!HasEntityFlags(FLAG_NO_DEATH_TRIGGER))
{
trigger_death_rewards();
for (Entity_Player* player : g_game->playerManager.playerList) player->trigger_npc_death(this);
}
toxic_shock_creep_spawn();
if (!isBoss && type != ENTITY_CHUB) trigger_kill_item_effects();
else
{
state = NPC_STATE_DEATH;
stateFrame = 0;
}
if (g_game->room->roomType == ROOM_DUNGEON && !IsFlying()) ladder_drop();
}
// Part of 006c4b30: an enemy dying on a crawlspace ladder keeps its speed sideways and drops off it, unless a wall
// is right under it.
void Entity_NPC::ladder_drop()
{
GridEntity* cell = room_grid_entity_at(pos);
if (!cell || cell->type != GRID_GRAVITY) return;
velocity.y *= HALF_SPEED;
if (velocity.x > 0) velocity.x = vector_length(velocity);
else if (velocity.x < 0) velocity.x = -vector_length(velocity);
velocity.y = 0;
Vector below = vector_add(pos, vector_make(0, sizeMulti.y * size + LADDER_FOOT_MARGIN));
if (room_grid_collision_at(below) != COLLISION_WALL) AddVelocity_divided(vector_make(0, LADDER_DROP_SPEED), false);
}
// Part of 006c4b30: a gold enemy's coins, one to three (none to two for a coin hearted player).
void Entity_NPC::midas_coins_spawn()
{
Entity_Player* player = game_nearest_player(pos);
int coins = player && player->GetHealthType() == HEALTH_COIN ? random_below(3) : random_below(3) + 1;
for (int i = 0; i < coins; i++)
{
uint32_t seed = Random();
Vector speed = vector_scale(random_direction(), random_unit() * MIDAS_COIN_SPEED);
g_game->Spawn({.position = pos,
.velocity = speed,
.subType = COIN_PENNY,
.type = ENTITY_PICKUP,
.variant = PICKUP_COIN,
.seed = seed});
}
}
// 006d5350 Toxic Shock leaves its green creep where the enemy died, sized to it.
void Entity_NPC::toxic_shock_creep_spawn()
{
Entity_Player* owner = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_CHECK);
if (!owner) return;
Entity* creep = spawn_at(ENTITY_EFFECT, EFFECT_PLAYER_CREEP_GREEN, 0, pos, owner);
float creepScale = size * TOXIC_CREEP_SCALE;
creep->sprite.scale = vector_make(creepScale, creepScale);
creep->Update();
}
// Part of 006c4b30: the items whose aura works on enemies near a player: Super Magnet's nearest holder pulls the
// enemy in one frame in three. The Soul's push and Salvation's beam stop the game until reached.
void Entity_NPC::player_aura_update()
{
constexpr float SUPER_MAGNET_REACH_SQUARED = 1e9f;
constexpr float SUPER_MAGNET_PULL = 0.5f;
constexpr int SUPER_MAGNET_ODDS = 3;
if (state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH || IsFriendly() || !IsVulnerableEnemy(nullptr))
return;
Entity_Player* magnet = nullptr;
float magnetDistance = SUPER_MAGNET_REACH_SQUARED;
for (Entity_Player* player : g_game->playerManager.playerList)
{
if (player->HasCollectible(COLLECTIBLE_SOUL_ID) || player->HasCollectible(COLLECTIBLE_SALVATION_ID))
reconstruction_missing("Entity_NPC::Update 006c4b30: The Soul's push and Salvation's beam");
if (!player->HasTrinket(TRINKET_SUPER_MAGNET_ID)) continue;
Vector away = vector_sub(player->pos, pos);
float distance = away.x * away.x + away.y * away.y;
if (distance >= magnetDistance) continue;
magnet = player;
magnetDistance = distance;
}
if (magnet && random_below(SUPER_MAGNET_ODDS) == 0) velocity = vector_add(velocity, vector_resized(vector_sub(magnet->pos, pos), SUPER_MAGNET_PULL));
}
// Whether Lighter or Ice Cube catches an enemy entering the room: a fifth, a third or a half by strength, more with
// the owner's luck, rolled on the enemy's seed.
static bool is_room_trinket_struck(Entity_NPC& npc, Entity_Player& owner, int trinket)
{
constexpr float CHANCES[] = {0.2f, 0.33f, 0.5f};
constexpr float LUCK_CHANCE = 0.02f;
constexpr uint32_t STATUS_SHIFT_INDEX = 5;
int multiplier = owner.GetTrinketMultiplier(trinket);
float chance = CHANCES[multiplier == 2 ? 1 : multiplier == 3 ? 2 : 0];
RNG rng;
rng.SetSeed(npc.initSeed, STATUS_SHIFT_INDEX);
return rng.RandomFloat() < owner.luck * LUCK_CHANCE + chance;
}
// Part of 006c4b30: what the players' items do to enemies each frame: Toxic Shock's poison, Lighter's burn and Ice
// Cube's freeze on the room's first frame, confusion while its target is invisible, Broken Modem's stalls, Game
// Kid's fear and the time stopping items' tint.
void Entity_NPC::item_effects_update()
{
PlayerManager& players = g_game->playerManager;
if (g_game->room->GetFrameCount() == 0 && IsVulnerableEnemy(nullptr))
{
if (Entity_Player* owner = players.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_IGNORE))
AddPoison(EntityRef(owner), TOXIC_SHOCK_POISON, 0, false);
Entity_Player* toxicOwner = players.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_IGNORE);
if (Entity_Player* lighter = players.FirstTrinketOwner(TRINKET_LIGHTER_ID); lighter && is_room_trinket_struck(*this, *lighter, TRINKET_LIGHTER_ID))
AddBurn(EntityRef(lighter), ROOM_TRINKET_STATUS_FRAMES, 0, false);
// The original freezes from the Toxic Shock owner's reference, usually none.
if (Entity_Player* ice = players.FirstTrinketOwner(TRINKET_ICE_CUBE_ID); ice && is_room_trinket_struck(*this, *ice, TRINKET_ICE_CUBE_ID))
{
AddFreeze(EntityRef(toxicOwner), ROOM_TRINKET_STATUS_FRAMES, false);
AddIce(EntityRef(toxicOwner), ROOM_TRINKET_STATUS_FRAMES);
}
}
Entity_Player* targetPlayer = GetPlayerTarget()->ToPlayer();
if (targetPlayer && targetPlayer->IsInvisible()) AddConfusion(EntityRef(this), STATUS_REFRESH, false);
if (players.FirstCollectibleOwner(COLLECTIBLE_BROKEN_MODEM_ID, LAZARUS_SHARE_IGNORE))
reconstruction_missing("Entity_NPC::Update 006c4b30: Broken Modem's stalls");
if (IsActiveEnemy(DEAD_EXCLUDED) && HasEntityFlags(FLAG_FREEZE) && freezeCountdown < 1 && IsFrame(MODEM_FRAMES, 0))
reconstruction_missing("Entity_NPC::Update 006c4b30: Broken Modem's release");
if (!HasEntityFlags(FLAG_NO_TARGET))
for (Entity_Player* player : players.playerList)
if (player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_GAMEKID_ID))
reconstruction_missing("Entity_NPC::Update 006c4b30: Game Kid's fear");
TemporaryEffects& roomEffects = g_game->room->temporaryEffects;
bool isTimeSlowed = roomEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) ||
roomEffects.HasCollectibleEffect(COLLECTIBLE_HOURGLASS_ID) ||
g_game->room->GetBrokenWatchState() == BROKEN_WATCH_SLOW;
bool isTimeImmune = (flags & (FLAG_FRIENDLY | FLAG_NO_STATUS_EFFECTS)) && type != ENTITY_DEATHS_HEAD;
if (isTimeSlowed && !isTimeImmune) reconstruction_missing("Entity_NPC::Update 006c4b30: the slowed time tint");
}
// How much of a per-tick factor is left over a step of timeScale ticks (Math::timescale_factor).
static float timescale_factor(float factor, float timeScale)
{
return timeScale == 1 ? factor : factor / ((factor + timeScale) - factor * timeScale);
}
// Part of 006c4b30: a poof02 event puffs half-faded smoke at the NPC, placed and sized (a third) by the null of that
// name. The original reads the null unchecked. Here a sprite without one puffs nothing.
void Entity_NPC::poof02_spawn()
{
const NullFrame* null = sprite.GetNullFrame("poof02");
if (!null) return;
Entity* poof = g_game->Spawn({.position = pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF02, .seed = Random()});
poof->sprite.offset = null->pos;
poof->sprite.scale = vector_scale(null->scale, POOF02_SCALE);
poof->renderDepthOffset = POOF02_DEPTH;
poof->SetColor(POOF02_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true);
}
// Part of 006c4b30: a grounded enemy walking through water leaves a ripple every 7 frames.
void Entity_NPC::ripple_spawn()
{
if (IsFlying() || !isVisible || !IsActiveEnemy(DEAD_EXCLUDED) || vector_length_squared(velocity) <= 1) return;
if (!g_game->room->HasWater() || !IsFrame(RIPPLE_FRAMES, (int)index) || entityCollisionClass == ENTCOLL_NONE)
return;
Entity* ripple = spawn_at(ENTITY_EFFECT, EFFECT_WATER_SPLASH, 0, vector_add(pos, velocity), this);
float rippleScale = size * RIPPLE_SCALE * scale;
ripple->sprite.scale = vector_make(rippleScale, rippleScale);
ripple->renderDepthOffset = RIPPLE_DEPTH;
ripple->velocity = vector_scale(velocity, RIPPLE_SPEED);
ripple->Update();
}
// 006c4b30 One frame of an enemy: its speed, status overlay and pause, appearing, its AI, champion and item
// effects, dying, the base update (movement), then the seeds and debug modes that change it, and its forced target.
void Entity_NPC::Update()
{
if (!isExists) return;
speedMultiplier = compute_speed_multiplier();
UpdateChildEffectPosition(false);
if (controllerID == -1)
{
controllerMovement = {};
if (aimTargetEffect) aimTargetEffect->Remove();
aimTargetEffect = nullptr;
}
if (HasEntityFlags(FLAG_ICE_FROZEN)) return update_frozen();
bool isWeakened = g_game->room->temporaryEffects.HasNullEffect(NULLITEM_DAMOCLES_WEAKNESS);
if (IsFrame(WEAKNESS_FRAMES, 0) && !IsFriendly() && IsActiveEnemy(DEAD_EXCLUDED) && isWeakened)
AddWeakness(EntityRef(nullptr), -3);
if (salvationTarget && salvationTarget->target.get() == this)
{
salvationTarget->pos = pos;
salvationTarget->velocity = velocity;
}
status_overlay_update();
bool isDeadBefore = isDead;
if ((pauseTimer != 0 || HasEntityFlags(FLAG_HELD)))
{
if (!paused_update()) return;
isDeadBefore = isDead;
}
bool isAppearing = HasEntityFlags(FLAG_APPEAR);
if (!isAppearing && state == NPC_STATE_APPEAR) state = savedState;
else if (isAppearing && state == NPC_STATE_APPEAR) appear_update();
else death_animation_update();
bool isHeld = HasEntityFlags(FLAG_FREEZE) || HasEntityFlags(FLAG_HELD) || holdCountdown > 0;
bool isDying = state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH;
if (isDying || ((isHeld || state == NPC_STATE_APPEAR) && !isDead))
{
if (HasEntityFlags(FLAG_FREEZE) || holdCountdown > 0)
{
friction *= APPEAR_FRICTION;
if (holdCountdown > 0 && !vector_is_zero(holdPosition)) pos = holdPosition;
}
if (!isDead) player_aura_update();
}
else
{
if (!HasEntityFlags(FLAG_CHARM)) decoy_update();
if (isDead && state == NPC_STATE_APPEAR)
{
friction = baseFriction;
state = savedState;
isVisible = true;
}
if (championRegenTimer == 0) npc_ai_update(*this);
champion_update();
unreachable_update();
if (isDead && isExists) dead_update();
if (!isDead) player_aura_update();
}
item_effects_update();
if (HasEntityFlags(FLAG_BAITED)) friction *= timescale_factor(SLOW_FRICTION, speedMultiplier);
if (isChampion)
velocity = vector_scale(velocity, timescale_factor(1 - (1 - championSpeed) * (1 - friction), speedMultiplier));
if (sprite.IsEventTriggered("poof02")) poof02_spawn();
spawn_damage_numbers();
update_damage_history();
if (aiCallFlags & AI_CALL_PRE_UPDATE) ai_call(AI_PHASE_PRE_UPDATE);
if (HasEntityFlags(FLAG_PERSISTENT | FLAG_FRIENDLY_BALL_DYING))
reconstruction_missing("Entity_NPC::Update 006c4b30: a captured enemy wasting away");
float healthBefore = health;
if (type == ENTITY_MINECART) update_physics();
else Entity::Update();
totalDamageTaken += std::max(healthBefore - health, 0.0f);
if (aiCallFlags & AI_CALL_POST_UPDATE) ai_call(AI_PHASE_POST_UPDATE);
seed_effects_update();
sprite.scale = vector_make(scale * shrinkStatus1, scale * shrinkStatus1);
ripple_spawn();
pausePosition = pos;
if (!isBestiaryEncountered)
{
g_manager->persistentGameData.TryAddBestiaryEncounter(type, variant);
isBestiaryEncountered = true;
}
if (IsFrame(config->collisionInterval * 2, (int)index)) hitList.clear();
else if (type == ENTITY_BLOOD_PUPPY && state == NPC_STATE_ATTACK && sprite.animState.IsLoopingAnimation() &&
IsFrame(PUPPY_HIT_FRAMES, (int)index))
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 && state != NPC_STATE_DEATH)
{
ClearEntityFlags(FLAG_EXTRA_GORE);
ClearEntityFlags(FLAG_SPAWN_STICKY_SPIDERS);
}
forced_target_update();
}
// Part of 006c4b30: the seeds and the debug mode that change every enemy: invisible enemies, camouflage, and the
// pacifist seed and quick kill that make them waste away.
void Entity_NPC::seed_effects_update()
{
Seeds& seeds = g_game->seedEffects;
if (seeds.HasSeedEffect(SEED_INVISIBLE_ENEMIES))
{
SetColor(COLOR_INVISIBLE, -1, COLOR_PRIORITY_DEFAULT, false, true);
sprite.color = COLOR_INVISIBLE;
shadowSize = 0;
}
if (seeds.HasSeedEffect(SEED_CAMO_ENEMIES) || seeds.HasSeedEffect(SEED_CAMO_EVERYTHING))
reconstruction_missing("Entity_NPC::Update 006c4b30: the camouflage seeds");
bool isQuickKill = seeds.HasSeedEffect(SEED_PACIFIST) || (g_game->debugFlags & DEBUG_QUICK_KILL);
if (isQuickKill && IsActiveEnemy(DEAD_EXCLUDED))
reconstruction_missing("Entity_NPC::Update 006c4b30: the pacifist seed and quick kill debug mode");
}
// Part of 006c4b30: the few enemies with their own per-frame step: Hornfel, Gideon's camera, the Heart's partner and
// Big Horn's splash.
void Entity_NPC::type_update()
{
if (type == ENTITY_HORNFEL) Hornfel_UpdateFrame();
if (type == ENTITY_GIDEON && state == NPC_STATE_APPEAR) g_game->room->camera->SetFocusPosition(pos);
if (type == ENTITY_HEART)
{
targetPosition = {};
if (variant == 1 && entityRef && entityRef->IsEnemy())
{
Entity* partner = entityRef;
targetPosition = vector_sub(partner->pos, pos);
partner->targetPosition = vector_scale(targetPosition, -1);
}
}
if (type == ENTITY_BIG_HORN && sprite.IsEventTriggered(BIG_HORN_SPLASH_EVENT)) big_horn_splash(*this);
}
// Part of 006c4b30: a forced target runs out, and a boss then waits 150 frames before taking another.
void Entity_NPC::forced_target_update()
{
if (forcedTargetTimer < 0)
{
forcedTargetTimer++;
return;
}
if (forcedTargetTimer == 0 || --forcedTargetTimer != 0) return;
if (IsBoss()) forcedTargetTimer = -FORCED_TARGET_BOSS_COOLDOWN;
forcedTarget = nullptr;
}
// 006b99e0 Its speed this frame: the room's time scale for it, halved under a stopwatch or the hourglass (or, for a
// friendly enemy, the room's slowdown), slowed and weakened enemies slower, and Vanishing Twin's boss slower still.
float Entity_NPC::compute_speed_multiplier()
{
Room& room = *g_game->room;
float speed = room.GetTimeScale(this);
if (!IsFriendly())
{
if (room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) ||
(g_game->challenge != CHALLENGE_SLOW && 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;
}
else if (room.slowdownDuration > 0) speed *= SPEED_HALF;
if (HasEntityFlags(FLAG_SLOW) && state != NPC_STATE_DEATH) speed *= SPEED_HALF;
if (HasEntityFlags(FLAG_WEAKNESS)) speed *= SPEED_WEAKENED;
if (IsBoss() && !IsFriendly() && room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_VANISHING_TWIN_ID))
speed *= SPEED_VANISHING_TWIN;
return speed;
}
// 006d60a0 Takes a hit as any entity (Entity::TakeDamage) and lets the items that react to it act: a player's hit
// ends Pacifist, Betrayal turns it on its attacker, the pulsing champion spawns its flies, and a hit taken spawns
// a blue fly for a hit that spawns one, marks a player's kill for Jar of Flies, and triggers the attacker's
// on-hit procedural items.
bool Entity_NPC::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown)
{
bool isHurt = Entity::TakeDamage(damage, damageFlags, source, damageCountdown);
bool isPlayerSource = source.type == ENTITY_PLAYER || source.type == ENTITY_FAMILIAR ||
source.spawnerType == ENTITY_PLAYER || source.spawnerType == ENTITY_FAMILIAR;
if (!IsFriendly() && isPlayerSource) g_game->room->isPacifist = false;
PlayerManager& players = g_game->playerManager;
if (source.entity && players.FirstCollectibleOwner(COLLECTIBLE_BETRAYAL_ID, LAZARUS_SHARE_CHECK))
reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: Betrayal");
if (players.FirstCollectibleOwner(COLLECTIBLE_JAR_OF_FLIES, LAZARUS_SHARE_CHECK))
{
bool isBlueFly = source.type == ENTITY_FAMILIAR && source.variant == Entity_Familiar::BLUE_FLY;
bool isPlayerKill = source.type == ENTITY_PLAYER || (source.spawnerType == ENTITY_PLAYER && !isBlueFly) ||
(damageFlags & ((uint64_t)DAMAGE_ACID | DAMAGE_POISON_BURN)) ||
source.type == ENTITY_EFFECT;
if (isPlayerKill) AddEntityFlags(FLAG_ADD_JAR_FLY);
else ClearEntityFlags(FLAG_ADD_JAR_FLY);
}
bool isPlayerHit = source.type == ENTITY_PLAYER ||
(source.spawnerType == ENTITY_PLAYER &&
(source.type != ENTITY_FAMILIAR || source.variant != Entity_Familiar::BLUE_FLY));
bool isFlyDue = !isDead && pendingDamage < health && championTimer < 1 && !(damageFlags & DAMAGE_ACID);
if (championColorIdx == CHAMPION_SIZE_PULSE && isFlyDue && isPlayerHit) champion_fly_spawn();
if (!isHurt || HasEntityFlags(FLAG_NO_STATUS_EFFECTS)) return isHurt;
Entity* attacker = source.entity;
if (attacker && attacker->type != ENTITY_PLAYER) attacker = attacker->spawnerEntity;
Entity_Player* player =
attacker && attacker->type == ENTITY_PLAYER ? static_cast<Entity_Player*>(attacker) : game_nearest_player(pos);
if (damageFlags & DAMAGE_SPAWN_FLY) reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: the hit's blue fly");
if (!player->proceduralItems.empty())
reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: the attacker's on-hit procedural items");
return isHurt;
}
// 006be6f0 Keeps what killed it (the damage and its events) for the death triggers, then dies as any entity.
void Entity_NPC::Kill(const EntityRef& source)
{
killDamage = pendingDamage;
killDamageFlags = pendingDamageFlags;
killDamageEvents = damageEvents;
Entity::Kill(source);
}
// 006b8f30 Lets go of everything it points at, Gideon's chain and Mother's sounds included.
void Entity_NPC::ClearReferences()
{
auto* charmed = dynamic_cast<Entity_Familiar*>(target.get());
if (type == ENTITY_SIREN_HELPER && charmed && charmed->HasEntityFlags(FLAG_CHARM)) charmed->RemoveFromPlayer();
if (type == ENTITY_GIDEON) gideon_chain_unlink(*this);
if (type == ENTITY_MOTHER && (variant == 0 || variant == 10))
{
g_manager->sfxManager.Stop(SOUND_MOTHER_SUCTION);
g_manager->sfxManager.Stop(SOUND_ULTRA_GREED_SPINNING);
}
pickupGhostsEntity = nullptr;
unknownF54 = nullptr;
salvationTarget = nullptr;
entityRef = nullptr;
if (aimTargetEffect) aimTargetEffect->Remove();
aimTargetEffect = nullptr;
ClearDequeRefs();
forcedTarget = nullptr;
Entity::ClearReferences();
entityDeque.clear();
vectorDeque1.clear();
vectorDeque2.clear();
statusEffectSprite.Reset();
chargeBarSprite.Reset();
hitList.clear();
hitList.shrink_to_fit();
secondaryHitList.clear();
secondaryHitList.shrink_to_fit();
}
// 006d81c0 Lets go of the entities its deque holds, and the deque.
void Entity_NPC::ClearDequeRefs()
{
entityDeque.clear();
}
// 006c1100 Shows its own color again: a champion its sprite color (on its _champion sheets) or its color laid over
// it, a boss its alternate color, else its own. A friendly enemy is washed out and a frozen one iced.
void Entity_NPC::ResetColor()
{
if (isChampion)
{
bool isChampionSheet = std::ranges::any_of(sprite.layerStates, [](const LayerState& layer)
{ return layer.bitflags & LAYER_CHAMPION_SHEET; });
if (championColorIdx >= 0 && championColorIdx < CHAMPION_COUNT)
sprite.color = isChampionSheet ? champion_look_get(championColorIdx).spriteColor
: champion_sprite_color_get(championColorIdx);
}
else if (bosscoloridx < 0) sprite.color = color;
else if (bosscoloridx < (int)config->bossColors.size()) sprite.color = config->bossColors[bosscoloridx].color;
bool isShadowCharger = type == ENTITY_SHADOW_CHARGER && variant == 0 && subtype == SHADOW_CHARGER_SUBTYPE;
if (IsFriendly() && !isShadowCharger) sprite.color = FRIENDLY_COLOR;
if (type == ENTITY_FROZEN_ENEMY) sprite.color = FROZEN_COLOR;
}
// 006d4e00 Bursts it: a blood explosion its size (or a fly's, a spider's, a poop's), in its splat color, from its
// sprite's middle.
void Entity_NPC::PlayDeathEffects()
{
if (g_game->playerManager.GetGFuelCount() > 0)
reconstruction_missing("Entity_NPC::PlayDeathEffects 006d4e00: G-Fuel's explosion");
Vector offset{};
const AnimationFrame* frame = sprite.animState.animData && (type != ENTITY_SCOURGE || variant != 10)
? sprite.animState.GetLayerFrame(0)
: nullptr;
if (frame)
offset = vector_make(frame->width * HALF - frame->pivot.x + frame->pos.x,
frame->height * HALF - frame->pivot.y + frame->pos.y);
if (HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) return;
int burst = death_burst_get();
if (burst == EFFECT_BLOOD_EXPLOSION)
{
Entity* blood = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_EXPLOSION, poof_size_get(*this, true), pos, nullptr);
blood->sprite.offset = offset;
blood->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true);
blood->renderDepthOffset = BLOOD_DEPTH_OFFSET;
}
else
{
if (config->gibFlags & GIB_FLAG_POOP) npc_sound_play(SOUND_POOP_DEATH, POOP_DEATH_VOLUME, 2, 1);
Entity* burstEffect = spawn_at(ENTITY_EFFECT, burst, 0, vector_add(pos, offset), nullptr);
burstEffect->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true);
}
if (type == ENTITY_DEATH_SPARK_TYPE)
reconstruction_missing("Entity_NPC::PlayDeathEffects 006d4e00: the electric enemy's sparks");
}
// Part of 006d4e00: the burst effect a dead NPC leaves: a poop's, a fly's, a spider's, a few special ones, else
// blood.
int Entity_NPC::death_burst_get()
{
if (config->gibFlags & GIB_FLAG_POOP) return EFFECT_POOP_EXPLOSION;
switch (type)
{
case ENTITY_FLY:
case ENTITY_POOTER:
case ENTITY_ATTACKFLY:
case 214:
case 222:
case 249:
case 256:
case 281:
case 296:
case 808:
case 838:
case 868:
return EFFECT_FLY_EXPLOSION;
case ENTITY_SPIDER:
case 94:
case 215:
case 250:
case 869:
case 884:
return EFFECT_SPIDER_EXPLOSION;
case 810:
return EFFECT_BURST_810;
case 818:
return EFFECT_BURST_818;
case 853:
return EFFECT_BURST_853;
default:
return EFFECT_BLOOD_EXPLOSION;
}
}
// Part of 006be840: a Dople keeps its player, else picks one by its seed among the players no other Dople copies (a
// controlled one, its controller's). With none left it dies, mimicking the first player.
static Entity* dople_player_pick(Entity_NPC& npc)
{
if (npc.target) return npc.target.get();
std::vector<Entity*> doples = entity_query(ENTITY_DOPLE, -1);
std::vector<Entity_Player*> candidates;
for (Entity_Player* player : g_game->playerManager.playerList)
{
bool isFree = npc.controllerID != -1 ? player->controllerIndex == npc.controllerID
: std::ranges::none_of(doples, [&](Entity* dople) {
return dople != &npc && static_cast<Entity_NPC*>(dople)->target.get() == player;
});
if (isFree) candidates.push_back(player);
}
Entity* picked = nullptr;
if (!candidates.empty())
{
RNG pick = rng_make(npc.initSeed, DOPLE_PICK_SHIFT);
picked = candidates[pick.RandomInt((int)candidates.size())];
}
else
{
npc.Kill(EntityRef());
picked = g_game->GetPlayer(0);
}
npc.target = picked;
return npc.target.get();
}
// 006be840 What it goes after: a charmed enemy picks the nearest enemy, a Dople (type 53) its own player,
// the rest the nearest target player (Game::GetNearestTargetPlayer), else the first player.
Entity* Entity_NPC::GetPlayerTarget()
{
if (type == ENTITY_DOPLE) return dople_player_pick(*this);
bool isRetargeting = IsFrame(TARGET_REFRESH_FRAMES, (int)index) || !target;
if (HasEntityFlags(FLAG_CHARM) && !g_game->room->isPacifist && isRetargeting)
target = game_nearest_enemy(pos, this, TARGET_RANGE);
if (target) return target;
bool isTargetDecoys = type != ENTITY_NO_DECOY_TYPE && decoyTargetTimer >= 0;
Entity* found = game_nearest_target_player(pos, this, IsFriendly(), isTargetDecoys, TARGET_RANGE);
if (!found) return g_game->GetPlayer(0);
if (found->IsEnemy() && found->HasEntityFlags(FLAG_BAITED)) target = found;
return found;
}
// 006bec40 Where it heads for its target: a confused enemy wanders to a random spot (a new one every 15 frames),
// a feared or shrunk one runs from its target (a rare few stay put), the rest go straight for it.
Vector Entity_NPC::CalcTargetPosition(float distanceLimit)
{
Room& room = *g_game->room;
if (HasEntityFlags(FLAG_CONFUSION))
{
bool isKept =
!vector_is_zero(confusionTargetPos) && (HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused() ||
g_game->frameCount % CONFUSION_RETARGET_FRAMES != 0);
if (!isKept)
{
float angle = random_unit() * RANDOM_HALF_TURN;
angle += angle;
float scaleFirst = random_unit();
float distance = random_unit() * scaleFirst * CONFUSION_WANDER;
Vector spot = vector_make(std::cos(angle) * distance + pos.x, std::sin(angle) * distance + pos.y);
confusionTargetPos = room.GetClampedPositionImpl(spot, size, size, size, size);
}
return confusionTargetPos;
}
bool isFleeingKind = type == ENTITY_MULLIGAN ? variant == MULLIGAN_VARIANT_FLEEING
: type != ENTITY_HIVE && type != ENTITY_FEAR_IMMUNE;
bool isFleeing = HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && isFleeingKind;
if (!isFleeing) return GetPlayerTarget()->pos;
Vector away = vector_sub(GetPlayerTarget()->pos, pos);
if (distanceLimit != 0 && vector_length_squared(away) != 0) away = vector_resized(away, distanceLimit);
Vector flee = vector_sub(pos, away);
Vector clamped = room.GetClampedPositionImpl(flee, size, size, size, size);
if (clamped.x == flee.x && clamped.y == flee.y)
{
confusionTargetPos = {};
return clamped;
}
if (!vector_is_zero(confusionTargetPos) && !IsFrame((int)(Random() % FEAR_RETARGET_RANGE) + FEAR_RETARGET_MIN, 0))
return confusionTargetPos;
Vector direction = random_direction();
float distance = random_unit() * FEAR_WANDER;
Vector spot = vector_sub(pos, vector_scale(direction, distance));
confusionTargetPos = room.GetClampedPositionImpl(spot, size, size, size, size);
return confusionTargetPos;
}
// 006cae60 Whether its target is in range to attack (predicting its motion, checked every frameInterval frames)
// in a clear line, or the controlling player steers it. Confused, feared and shrunk enemies never attack.
bool Entity_NPC::IsTargetInAttackRange(float range, int frameInterval, bool isPredictVelocity)
{
if (HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return false;
if (controllerID != -1) return !vector_is_zero(GetControllerMovementInput(MOVEMENT_DEADZONE));
Entity* other = GetPlayerTarget();
if (!IsHostileTo(other)) return false;
Vector aim =
isPredictVelocity ? vector_add(other->pos, vector_scale(other->velocity, ATTACK_PREDICT_FRAMES)) : other->pos;
if (frameInterval != 0 && !IsFrame(frameInterval, (int)index)) return false;
if (vector_length_squared(vector_sub(aim, pos)) >= range * range) return false;
return room_check_line(pos, other->pos, LINE_MODE_PROJECTILE, LINE_CHECK_THRESHOLD) ||
championColorIdx == CHAMPION_TRANSPARENT;
}
// 006c1330 Walks its main animation: the vertical one stopped while slower than the threshold (half for a slow
// champion), else the one of the axis it moves most along, flipped to face left, and faces that way.
void Entity_NPC::AnimWalkFrame(std::string_view horizontalAnim, std::string_view verticalAnim, float speedThreshold)
{
if (isChampion && championSpeed < 1) speedThreshold *= HALF;
if (vector_length_squared(velocity) < speedThreshold * speedThreshold)
{
if (sprite.SetAnimation(verticalAnim, SWITCH_KEEP_FRAME) && sprite.animState.animData)
{
sprite.animState.SetFrameFloat(0);
sprite.animState.isPlaying = false;
}
forwardVector = vector_make(0, 1);
return;
}
bool isHorizontal = std::abs(velocity.x) > std::abs(velocity.y);
std::string_view walk = isHorizontal ? horizontalAnim : verticalAnim;
const AnimationData* current = sprite.animState.animData;
bool isWalking = current && current->name == walk && (!current->isLooping || sprite.animState.isPlaying);
if (!isWalking && sprite.SetAnimation(walk, SWITCH_KEEP_FRAME))
{
sprite.animState.Rewind();
sprite.animState.isPlaying = true;
}
if (isHorizontal) sprite.isFlipX = velocity.x < 0;
if (isHorizontal) forwardVector = vector_make(velocity.x >= 0 ? 1.0f : -1.0f, 0);
else forwardVector = vector_make(0, velocity.y >= 0 ? 1.0f : -1.0f);
}
// The rotation of each fan FireProjectiles shoots, as the cosine and sine the exe keeps and a speed scale.
struct ShotTurn
{
float cosine;
float sine;
float speed;
};
constexpr ShotTurn SHOT_8 = {0.99f, 0.139f, 1};
constexpr ShotTurn SHOT_12 = {0.978f, 0.208f, 1};
constexpr ShotTurn SHOT_16 = {0.961f, 0.276f, 1};
constexpr ShotTurn SHOT_16_SLOW = {0.961f, 0.276f, 0.9f};
constexpr ShotTurn SHOT_24 = {0.914f, 0.407f, 1};
constexpr ShotTurn SHOT_24_SLOW = {0.914f, 0.407f, 0.9f};
constexpr float DIAGONAL = 0.70710677f;
constexpr float PROJECTILE_DEFAULT_FALL_SPEED = -3;
constexpr float PROJECTILE_DEFAULT_FALL_ACCEL = 0.1f;
constexpr float PROJECTILE_HEIGHT_LOW = -50;
constexpr float PROJECTILE_DAMAGE_LARGE_SCALE = 1.15f;
constexpr float SHOOTER_VELOCITY_SHARE = 0.4f;
constexpr float SHOT_VELOCITY_BOOST = 1.2f;
// The shots of a fan: each turn spreads to both sides (a straight one once).
static void fan_velocities_add(std::vector<Vector>& shots, Vector velocity, float spread, const ShotTurn& turn)
{
float cosine = turn.cosine * turn.speed;
float sine = turn.sine * turn.speed * spread;
if (turn.sine == 0)
{
shots.push_back(velocity);
return;
}
shots.push_back(vector_make(velocity.x * cosine - velocity.y * sine, velocity.x * sine + velocity.y * cosine));
shots.push_back(vector_make(velocity.y * sine + velocity.x * cosine, velocity.y * cosine - velocity.x * sine));
}
// 006cb2e0 Shoots projectiles of params' variant from a position in a mode's spread, then applies params to each:
// the fans also fall at once and take on part of its motion unless params keeps their fall.
void Entity_NPC::FireProjectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode,
const ProjectileParams& params)
{
std::vector<Vector> shots;
float speed = velocity.x;
switch (mode)
{
case PROJECTILES_SINGLE:
shots.push_back(velocity);
break;
case PROJECTILES_TWO:
fan_velocities_add(shots, velocity, params.spread, SHOT_16);
break;
case PROJECTILES_THREE:
shots.push_back(velocity);
fan_velocities_add(shots, velocity, params.spread, SHOT_16_SLOW);
break;
case PROJECTILES_THREE_WIDE:
shots.push_back(velocity);
fan_velocities_add(shots, velocity, params.spread, SHOT_24);
break;
case PROJECTILES_FOUR:
fan_velocities_add(shots, velocity, params.spread, SHOT_8);
fan_velocities_add(shots, velocity, params.spread, SHOT_24_SLOW);
break;
case PROJECTILES_FIVE:
shots.push_back(velocity);
fan_velocities_add(shots, velocity, params.spread, SHOT_12);
fan_velocities_add(shots, velocity, params.spread, SHOT_24);
break;
case PROJECTILES_PLUS:
shots.insert(shots.end(), {vector_make(speed, 0), vector_make(-speed, 0), vector_make(0, speed),
vector_make(0, -speed)});
break;
case PROJECTILES_CROSS:
case PROJECTILES_EIGHT:
{
float diagonal = speed * DIAGONAL;
if (mode == PROJECTILES_EIGHT)
shots.insert(shots.end(), {vector_make(speed, 0), vector_make(-speed, 0), vector_make(0, speed),
vector_make(0, -speed)});
shots.insert(shots.end(), {vector_make(diagonal, diagonal), vector_make(-diagonal, diagonal),
vector_make(diagonal, -diagonal), vector_make(-diagonal, -diagonal)});
break;
}
case PROJECTILES_RING:
{
float angle = params.circleAngle;
int count = (int)(velocity.y + HALF);
float step = 2 * PI_F / (float)count;
for (int i = 0; i < count; i++)
{
angle += step;
Vector shot = vector_make(std::cos(angle) * speed, std::sin(angle) * speed);
bool isLimited = !vector_is_zero(params.fireDirectionLimit);
if (!isLimited ||
vector_dot(vector_normalized(shot), params.fireDirectionLimit) > params.dotProductLimit)
shots.push_back(shot);
}
break;
}
}
std::vector<Entity_Projectile*> projectiles;
Vector origin = vector_add(position, params.positionOffset);
for (const Vector& shot : shots)
{
Entity* spawned = g_game->Spawn({.position = origin,
.velocity = shot,
.spawner = this,
.type = ENTITY_PROJECTILE,
.variant = params.variant,
.seed = Random()});
if (!spawned) log_printf(LOG_ASSERT, "Failed to spawn Projectile");
projectiles.push_back(static_cast<Entity_Projectile*>(spawned));
}
bool isFan = mode < PROJECTILES_PLUS;
for (Entity_Projectile* projectile : projectiles)
{
if (!isFan || params.isFallingKept) break;
projectile->fallingSpeed = PROJECTILE_DEFAULT_FALL_SPEED;
projectile->fallingAccel = PROJECTILE_DEFAULT_FALL_ACCEL;
if (mode != PROJECTILES_THREE && mode != PROJECTILES_FOUR && mode != PROJECTILES_FIVE) continue;
projectile->fallingSpeed -= 1;
projectile->velocity = vector_add(vector_scale(this->velocity, SHOOTER_VELOCITY_SHARE),
vector_scale(projectile->velocity, SHOT_VELOCITY_BOOST));
}
for (Entity_Projectile* projectile : projectiles) projectile_params_apply(*projectile, params);
for (Entity_Projectile* projectile : projectiles) fire_projectile_from_params(projectile);
}
// Part of 006cb2e0: what params set on a shot fired.
void Entity_NPC::projectile_params_apply(Entity_Projectile& projectile, const ProjectileParams& params)
{
projectile.height += params.heightModifier;
projectile.fallingSpeed += params.fallingSpeedModifier;
projectile.fallingAccel += params.fallingAccelModifier;
projectile.scale = params.scale;
float damage = params.damage >= 0 ? params.damage : params.scale > PROJECTILE_DAMAGE_LARGE_SCALE ? 2.0f : 1.0f;
projectile.SetCollisionDamage(damage);
projectile.velocity = vector_scale(projectile.velocity, params.velocityMulti);
projectile.projectileFlags |= params.bulletFlags;
projectile.SetColor(params.color, -1, COLOR_PRIORITY_DEFAULT, false, true);
projectile.targetPosition = params.targetPosition;
projectile.homingStrength = params.homingStrength;
projectile.curvingStrength = params.curvingStrength;
projectile.acceleration = params.acceleration;
projectile.wiggleFrameOffset = params.wiggleFrameOffset;
projectile.changeFlags |= params.changeFlags;
projectile.changeVelocity = params.changeVelocity;
projectile.changeTimeout = params.changeTimeout;
projectile.isRenderedAtGround = params.isRenderedAtGround;
projectile.renderDepthOffset = params.depthOffset - params.positionOffset.y;
if (projectile.height < PROJECTILE_HEIGHT_LOW && !(projectile.projectileFlags & PROJECTILE_ANY_HEIGHT_ENTITY_HIT))
projectile.entityCollisionClass = ENTCOLL_NONE;
projectile.motionHook = params.motionHook;
}
// 006cb2a0 Hands a fired shot its shooter's champion color, scale and flags (Entity_Projectile::apply_spawn_flags).
void Entity_NPC::fire_projectile_from_params(Entity_Projectile* projectile)
{
projectile->apply_spawn_flags({this, flags, scale, isChampion ? championColorIdx : -1});
}
// Part of 006d2e50: the status effect sprite drawn on the OverlayEffect null, once on a shared body.
void Entity_NPC::status_overlay_render(const Vector& offset)
{
bool isShown =
statusEffectSprite.isLoaded && statusEffectSprite.animState.animData && statusEffectSprite.animState.isPlaying;
if (!isShown) return;
int nullIndex = sprite.null_index_get("OverlayEffect");
if (nullIndex < 0)
{
if (!config) log_printf(LOG_INFO, "[warn] No OverlayEffect Null found for Entity (%d)\n", type);
else
log_printf(LOG_INFO, "[warn] No OverlayEffect Null found for Entity %s with sprite %s\n",
config->GetName(NAME_LANGUAGE_CURRENT).c_str(), sprite.filename.c_str());
return;
}
const NullFrame* frame = sprite.GetNullFrameById(nullIndex);
bool isShared = statusEffectSprite.bitflags & STATUS_SHARED;
if (!frame || !frame->isVisible || (isShared && parent && is_same_segmented_body(nullptr))) return;
statusEffectSprite.scale = frame->scale;
Vector at =
vector_add(vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset), frame->pos);
statusEffectSprite.Render(SpriteDraw{at, {}, {}});
}
// 006d90e0 Moves the effect a controlled enemy aims with along the controller's input and keeps it in reach.
void Entity_NPC::UpdateChildEffectPosition(bool)
{
if (controllerID == -1 || !aimTargetEffect) return;
reconstruction_missing("Entity_NPC::UpdateChildEffectPosition 006d90e0");
}
// 006d7010 With Spider Mod, shows the damage each hit of this frame dealt it as a rising number.
void Entity_NPC::spawn_damage_numbers()
{
bool isShown = type == ENTITY_DAMAGE_NUMBERS_TYPE ||
(g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SPIDER_MOD_ID, LAZARUS_SHARE_CHECK) &&
IsActiveEnemy(DEAD_EXCLUDED));
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");
}
// 006d7230 A shielded boss's shield: the damage of its last frames (shieldFrames) averaged per second, and past
// maxHitPoints / shieldStrength of it this frame's hits shrink.
void Entity_NPC::update_damage_history()
{
Entity* root = this;
if (DoesEntityShareStatus())
while (root->parent) root = root->parent;
if (!Entity::is_enemy_type(root->type)) root = this;
Entity_NPC& owner = static_cast<Entity_NPC&>(*root);
if (owner.shieldStrength <= 0) return;
float frameDamage = 0;
for (const DamageEvent& event : damageEvents)
if (!(event.damageFlags & DAMAGE_INVINCIBLE)) frameDamage += event.damage;
if ((int)owner.damageHistory.size() >= owner.shieldFrames) owner.damageHistory.pop_front();
owner.damageHistory.push_back(frameDamage);
float total = 0;
for (float damage : owner.damageHistory) total += damage;
float perSecond = total / (float)owner.damageHistory.size() * SHIELD_SECOND;
float threshold = maxHitPoints / owner.shieldStrength;
float multiplier = 1;
if (threshold < perSecond)
{
float share = threshold / perSecond;
multiplier = std::max(SHIELD_BASE - share * SHIELD_FALLOFF, 0.0f) + share;
}
pendingDamage = 0;
for (DamageEvent& event : damageEvents)
{
if (!(event.damageFlags & (DAMAGE_INVINCIBLE | DAMAGE_IGNORE_ARMOR))) event.damage *= multiplier;
pendingDamage += event.damage;
}
}
// Part of 006d5400: a sticky enemy bursts into blue spiders for the nearest player, one to three (two to six when
// an explosion killed it).
void Entity_NPC::sticky_spiders_spawn()
{
int spiders = killDamageFlags & DAMAGE_EXPLOSION ? (int)(Random() % STICKY_SPIDERS_BLAST_RANGE) + 2
: (int)(Random() % STICKY_SPIDERS_RANGE) + 1;
for (int i = 0; i < spiders; i++)
{
Entity_Player* player = game_nearest_player(pos);
player->numBlueSpiders++;
spawn_blue_spider(pos, player, {});
}
}
// Part of 006d5400: the rewards of a dead enemy that gives any: one in five a black heart for Black Lipstick's
// sticky kind, and Jar of Flies' count for a fly a player killed, froze or iced.
void Entity_NPC::kill_rewards_spawn()
{
if (HasEntityFlags(FLAG_SPAWN_BLACK_HP) && dropRNG.Next() % BLACK_HEART_CHANCE == 0)
{
uint32_t seed = Random();
g_game->Spawn({.position = room_free_tile_position_find(pos, 0),
.subType = HEART_BLACK,
.type = ENTITY_PICKUP,
.variant = PICKUP_HEART,
.seed = seed});
}
PlayerManager& players = g_game->playerManager;
Entity_Player* jarOwner = players.RandomCollectibleOwner(COLLECTIBLE_JAR_OF_FLIES, dropRNG.Next(), nullptr);
if (!jarOwner || !(HasEntityFlags(FLAG_ADD_JAR_FLY | FLAG_FREEZE) || HasEntityFlags(FLAG_ICE_FROZEN))) return;
jarOwner->jarFlies = std::min(jarOwner->jarFlies + 1, JAR_OF_FLIES_MAX);
g_game->hud.refresh_request(HUD_REFRESH_PLAYER);
}
// Part of 006d5400: the items a kill wakes: Contagion's cloud on the first kill of a room or a contagious enemy's,
// spreading the contagion, Athame's ring by the players' luck, a friendly enemy's recharge of the Friendly Ball in
// challenge 33, and a captured enemy's soul wisp for Book of Virtues.
void Entity_NPC::kill_items_trigger()
{
PlayerManager& players = g_game->playerManager;
Entity_Player* contagion = players.FirstCollectibleOwner(COLLECTIBLE_CONTAGION, LAZARUS_SHARE_IGNORE);
if (contagion && (HasEntityFlags(FLAG_CONTAGIOUS) || !g_game->room->isFirstEnemyDead))
{
game_fart({.position = pos, .source = contagion, .radius = CONTAGION_RADIUS, .subType = 1});
for (Entity* enemy : entity_query_radius(pos, CONTAGION_RADIUS, QUERY_ENEMIES))
if (enemy != this && enemy->IsVulnerableEnemy(nullptr)) enemy->AddEntityFlags(FLAG_CONTAGIOUS);
}
if (Entity_Player* athame = players.FirstCollectibleOwner(COLLECTIBLE_ATHAME, LAZARUS_SHARE_IGNORE))
{
RNG rng;
rng.SetSeed(initSeed, ATHAME_RNG_SHIFT_INDEX);
float luck = 0;
for (Entity_Player* player : players.playerList)
if (player->variant == PLAYER_VARIANT_PLAYER && !player->isCoopGhost) luck += player->luck;
if (rng.RandomFloat() < luck * ATHAME_LUCK_CHANCE + ATHAME_BASE_CHANCE)
{
Entity_Laser* ring = athame->SpawnMawOfVoid(ATHAME_RING_TIMEOUT);
ring->pos = pos;
ring->isDisableFollowParent = true;
ring->Update();
}
}
bool isFriendlyKill = IsFriendly() && g_game->challenge == CHALLENGE_KILL_CHARGE &&
players.FirstCollectibleOwner(COLLECTIBLE_FRIEND_BALL, LAZARUS_SHARE_CHECK) &&
(spawnerType == ENTITY_PLAYER || spawnerType == ENTITY_FAMILIAR) && spawnerEntity &&
spawnerEntity->type == ENTITY_PLAYER;
if (isFriendlyKill)
{
auto* owner = static_cast<Entity_Player*>(spawnerEntity.get());
for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++)
{
if (owner->activeItems[slot].item != COLLECTIBLE_FRIEND_BALL) continue;
owner->FullCharge(slot, false, false);
break;
}
}
if (!HasEntityFlags(FLAG_FRIENDLY_BALL)) return;
Entity_Player* virtues = players.RandomCollectibleOwner(COLLECTIBLE_BOOK_OF_VIRTUES, dropRNG.Next(), nullptr);
EntityConfig_Entity* entry = g_manager->entityConfig.GetEntity(type, variant, 0);
if (!virtues || virtues->type != ENTITY_PLAYER || !entry) return;
int wisp = WISP_SOUL;
if (entry->tags & ENTITY_TAG_HOMING_SOUL) wisp = WISP_SOUL_HOMING;
else if (entry->tags & ENTITY_TAG_EXPLOSIVE_SOUL) wisp = WISP_SOUL_EXPLOSIVE;
else if (entry->tags & ENTITY_TAG_BRIMSTONE_SOUL) wisp = WISP_SOUL_BRIMSTONE;
virtues->AddWisp(wisp, pos, false, false);
}
// Part of 006d5400: a Brimstone marked enemy's burst marks the vulnerable enemies within 120 for 150 frames, hands
// them its statuses for 90, hits them for 10, and recharges the Hemoptysis of the players with Brimstone.
void Entity_NPC::marked_status_spread()
{
EntityRef none(nullptr);
for (Entity* enemy : entity_query_radius(pos, MARK_SPREAD_RADIUS, QUERY_ENEMIES))
{
if (enemy == this || !enemy->IsVulnerableEnemy(nullptr)) continue;
enemy->AddBrimstoneMark(none, MARK_SPREAD_FRAMES);
if (HasEntityFlags(FLAG_SLOW))
enemy->AddSlowing(none, STATUS_SPREAD_FRAMES, slowingAmount, SPREAD_SLOW_COLOR, false);
if (HasEntityFlags(FLAG_POISON)) enemy->AddPoison(none, STATUS_SPREAD_FRAMES, poisonTickDamage, false);
if (HasEntityFlags(FLAG_MIDAS_FREEZE)) enemy->AddMidasFreeze(none, STATUS_SPREAD_FRAMES, false);
else if (HasEntityFlags(FLAG_FREEZE)) enemy->AddFreeze(none, STATUS_SPREAD_FRAMES, false);
if (HasEntityFlags(FLAG_SHRINK)) enemy->AddShrink(none, STATUS_SPREAD_FRAMES, false, false);
else if (HasEntityFlags(FLAG_FEAR)) enemy->AddFear(none, STATUS_SPREAD_FRAMES, false);
if (HasEntityFlags(FLAG_CHARM)) enemy->AddCharmed(none, STATUS_SPREAD_FRAMES, false, false);
if (HasEntityFlags(FLAG_CONFUSION)) enemy->AddConfusion(none, STATUS_SPREAD_FRAMES, false);
if (HasEntityFlags(FLAG_BURN)) enemy->AddBurn(none, STATUS_SPREAD_FRAMES, 0, false);
if (HasEntityFlags(FLAG_MAGNETIZED)) enemy->AddMagnetized(none, STATUS_SPREAD_FRAMES);
if (HasEntityFlags(FLAG_ICE)) enemy->AddIce(none, STATUS_SPREAD_FRAMES);
if (HasEntityFlags(FLAG_BAITED)) enemy->AddBaited(none, STATUS_SPREAD_FRAMES);
enemy->TakeDamage(MARK_SPREAD_DAMAGE, 0, none, MARK_SPREAD_COUNTDOWN);
}
MakeBloodPoof(pos, COLOR_DEFAULT, 1);
for (Entity_Player* player : g_game->playerManager.playerList)
{
Weapon* weapon = player->weapons[0] ? player->weapons[0].get() : player->weapons[1].get();
if (!weapon || weapon->weaponType != WEAPON_BRIMSTONE) continue;
player->temporaryEffects.RemoveNullEffect(NULLITEM_HEMOPTYSIS_BOOST, -1);
player->temporaryEffects.AddNullEffect(NULLITEM_HEMOPTYSIS_BOOST, true, 1);
}
}
// 006d5400 What happens as it leaves for good: a champion's drop or a boss's death, Rotgut's death, the sticky
// spiders, its rewards, its removal (Hush stays, drawn on the floor), the items a kill wakes, its record and a
// marked enemy's spreading statuses.
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 (HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) sticky_spiders_spawn();
if (!HasEntityFlags(FLAG_NO_REWARD)) kill_rewards_spawn();
if (type == ENTITY_HUSH) AddEntityFlags(FLAG_RENDER_FLOOR);
else Remove();
kill_items_trigger();
g_game->room->isFirstEnemyDead = true;
// Room::record_killed_npc 00820d30 waits for Room to hold the list of killed enemies, which nothing reads yet.
entityRef = nullptr;
aimTargetEffect = nullptr;
if (HasEntityFlags(FLAG_BRIMSTONE_MARKED) && HasEntityFlags(FLAG_EXTRA_GORE)) marked_status_spread();
lua_engine_get().PostNPCDeath(this);
}
// 00447770 Its parent, which only NPCs are.
Entity_NPC* Entity_NPC::ParentNPC()
{
if (parent && !dynamic_cast<Entity_NPC*>(parent.get())) log_printf(LOG_ASSERT, "m_Parent invalid downcast\n");
return static_cast<Entity_NPC*>(parent.get());
}
// 004567e0 Its child, which only NPCs are.
Entity_NPC* Entity_NPC::ChildNPC()
{
if (child && !dynamic_cast<Entity_NPC*>(child.get())) log_printf(LOG_ASSERT, "m_Child invalid downcast\n");
return static_cast<Entity_NPC*>(child.get());
}
// 006d8cf0 Removes the effect a controlled enemy aims with.
void Entity_NPC::ClearChild()
{
if (!aimTargetEffect) return;
aimTargetEffect->Remove();
aimTargetEffect = nullptr;
}
// 006d0c20
void Entity_NPC::SetRef_bec(Entity* entity)
{
entityRef = entity;
}
// 0060d140
void Entity_NPC::set_entity_ptr_f54(Entity* entity)
{
unknownF54 = entity;
}
// 006b5e20 Holds it at a position for the longer of the countdowns.
void Entity_NPC::hold_set(int countdown, const Vector& position)
{
holdCountdown = std::max(countdown, holdCountdown);
holdPosition = position;
}
// 006d8260 Whether the controlling player holds an action, never without one.
bool Entity_NPC::IsControllerActionPressed(int)
{
if (controllerID == -1) return false;
reconstruction_missing("Entity_NPC::IsControllerActionPressed 006d8260");
}
// 006d8290 Whether the controlling player pressed an action this frame, never without one.
bool Entity_NPC::IsControllerActionTriggered(int buttonAction)
{
if (controllerID == -1) return false;
(void)buttonAction;
reconstruction_missing("Entity_NPC::IsControllerActionTriggered 006d8290");
}
// 006d82d0 The controlling player's shooting input, none without one.
Vector Entity_NPC::GetControllerInput(float)
{
if (controllerID == -1) return {};
reconstruction_missing("Entity_NPC::GetControllerInput 006d82d0");
}
// 006d85a0 The controlling player's movement input, none without one.
Vector Entity_NPC::GetControllerMovementInput(float)
{
if (controllerID == -1) return {};
reconstruction_missing("Entity_NPC::GetControllerMovementInput 006d85a0");
}
// 006d9050 Keeps the controlling player's last movement, or none without one.
void Entity_NPC::UpdateControllerMovement(bool)
{
if (controllerID == -1)
{
controllerMovement = {};
return;
}
reconstruction_missing("Entity_NPC::UpdateControllerMovement 006d9050");
}
// The rest of Entity_NPC is not reconstructed yet.
// 006d9440 Thrown: a poop pile flies at the throw's velocity from 20 pixels up at the throw's height, stops being kept
// across rooms, gets the thrown flag (colliding with everything when a player threw it) and splats when fast. Other
// NPCs are thrown only while held.
bool Entity_NPC::TryThrow(const EntityRef& source, const Vector& throwVelocity, float height)
{
if (type != ENTITY_POOP) return HasEntityFlags(FLAG_HELD);
v1 = vector_make(POOP_THROW_HEIGHT, -height);
velocity = throwVelocity;
flags = (flags & ~FLAG_PERSISTENT) | FLAG_THROWN;
if (source.type == ENTITY_PLAYER) entityCollisionClass = ENTCOLL_ALL;
if (vector_length_squared(throwVelocity) > POOP_THROW_LOUD_SPEED * POOP_THROW_LOUD_SPEED)
{
int sound = SOUND_POOPITEM_THROW;
seed_fart_sound_override(&sound);
g_manager->sfxManager.Play(sound);
}
return true;
}
// 004b92e0
void Entity_NPC::Hornfel_UpdateAI()
{
reconstruction_missing("Entity_NPC::Hornfel_UpdateAI 004b92e0");
}
// 004bb0e0
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
void Entity_NPC::KillUnique()
{
reconstruction_missing("Entity_NPC::KillUnique 006be760");
}
// A thrown spider: a free landing spot within 100 when none is given, a Strider instead over Downpour's and Dross's
// water, the path cost its landing cell is kept clear with, its first hop's rise and its step toward the spot.
constexpr float SPIDER_LANDING_SEARCH = 100;
constexpr float SPIDER_STRIDER_WATER = 0.1f;
constexpr int SPIDER_LANDING_PATH = 900;
constexpr int SPIDER_LANDING_PATH_LIMIT = 950;
constexpr float SPIDER_THROW_RISE = -8;
constexpr float SPIDER_THROW_STEP = 0.04f;
// 006c2750 Throws a spider (or a big one) from position to land at targetPos, marking its landing cell in the room's
// paths so others steer clear.
Entity_NPC* Entity_NPC::ThrowSpider(const Vector& position, Entity* spawner, Vector targetPos, bool isBig,
float yOffset)
{
if (vector_is_zero(targetPos))
targetPos = room_free_pickup_position_find({.position = position, .step = SPIDER_LANDING_SEARCH});
int stageId = g_game->GetStageID();
Room& room = *g_game->room;
if ((stageId == STAGE_ID_DOWNPOUR || stageId == STAGE_ID_DROSS) && room.waterAmount > SPIDER_STRIDER_WATER)
return ThrowStrider(position, spawner, targetPos);
int gridIndex = room.GetGridIndex(targetPos);
if (gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS && room.gridPaths[gridIndex] <= SPIDER_LANDING_PATH_LIMIT)
room.gridPaths[gridIndex] = SPIDER_LANDING_PATH;
auto* spider = static_cast<Entity_NPC*>(g_game->Spawn({.position = position,
.spawner = spawner,
.type = isBig ? ENTITY_BIG_SPIDER : ENTITY_SPIDER,
.seed = Random()}));
spider->state = NPC_STATE_JUMP;
spider->targetPosition = targetPos;
spider->v2.y = SPIDER_THROW_RISE;
spider->entityCollisionClass = ENTCOLL_NONE;
spider->velocity = vector_scale(vector_sub(targetPos, spider->pos), SPIDER_THROW_STEP);
spider->v1 = spider->velocity;
spider->posOffset.y = yOffset;
return spider;
}
// 006ca930
void Entity_NPC::update_frozen()
{
reconstruction_missing("Entity_NPC::update_frozen 006ca930");
}
// 006d0c60
void* Entity_NPC::QueryNPCsType(void*, int, int)
{
reconstruction_missing("Entity_NPC::QueryNPCsType 006d0c60");
}
// 006d1580
void* Entity_NPC::fireplace_get_loot(void*, bool)
{
reconstruction_missing("Entity_NPC::fireplace_get_loot 006d1580");
}
// 006d4db0 Whether a reroll may turn it into another enemy: not when its tags forbid it, for a Lil Haunt still tied
// to the Haunt, or for a boss.
bool Entity_NPC::CanReroll()
{
if ((config->tags & ENTITY_TAG_NOREROLL) || (type == ENTITY_THE_HAUNT && variant == HAUNT_LIL_VARIANT && parent))
return false;
return !IsBoss() && !config->isBoss;
}
// 006d88b0
void Entity_NPC::TransferControl(Entity_NPC*)
{
reconstruction_missing("Entity_NPC::TransferControl 006d88b0");
}
// 006d8b20 The aim target a controlled NPC steers. Without a controller and none shown yet, there is nothing to do.
void Entity_NPC::SpawnControlTarget(int inputMode, float)
{
if (!aimTargetEffect && controllerID == -1 && inputMode <= 1) return;
reconstruction_missing("Entity_NPC::SpawnControlTarget 006d8b20");
}
// 006d8d30 Where its aim target stands, or its own position without one.
Vector Entity_NPC::GetAimTargetPosition()
{
return aimTargetEffect ? aimTargetEffect->pos : pos;
}
// 006d8d80
bool Entity_NPC::is_controller_input_idle()
{
reconstruction_missing("Entity_NPC::is_controller_input_idle 006d8d80");
}
// 006d8e40 A controlled NPC's charge bar at value between start and end, hidden when full if asked.
void Entity_NPC::UpdateChargeBar(float start, float end, float value, bool isHideWhenFull)
{
if (controllerID == -1 && !chargeBarSprite.isLoaded) return;
if (controllerID != -1)
{
if (!chargeBarSprite.isLoaded) chargeBarSprite.Load("gfx/chargebar.anm2", GRAPHICS_LOAD);
chargeBarSprite.GetLayer(2)->isVisible = false;
if (start == end) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!");
int frame = (int)(std::clamp((value - start) / (end - start), 0.0f, 1.0f) * CHARGE_BAR_FRAMES);
if (!isHideWhenFull || frame < CHARGE_BAR_FRAMES)
{
if (chargeBarSprite.SetAnimation("Charging", SWITCH_KEEP_FRAME) && chargeBarSprite.animState.animData)
{
chargeBarSprite.animState.SetFrameFloat((float)frame);
chargeBarSprite.animState.isPlaying = false;
}
chargeBarSprite.color._tint[3] = 1;
return;
}
}
chargeBarSprite.color._tint[3] = 0;
}
// 006d97e0
uint8_t Entity_NPC::split(float, const EntityRef&, bool)
{
reconstruction_missing("Entity_NPC::split 006d97e0");
}
// 006da530 While a player holds Guppy's Eye, a lit fireplace or a living shopkeeper shows the loot it would drop as
// ghosts. Otherwise the ghosts shown before go.
void Entity_NPC::UpdatePickupGhosts()
{
bool isLootHolder = (type == ENTITY_FIREPLACE && health > 1) || (type == ENTITY_SHOPKEEPER && !isDead);
if (isLootHolder && g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_GUPPYS_EYE_ID, LAZARUS_SHARE_CHECK))
reconstruction_missing("Entity_NPC::UpdatePickupGhosts 006da530 (the loot ghosts)");
if (pickupGhostsEntity) pickupGhostsEntity->Remove();
}
// 009a8b90
void Entity_NPC::render_debug(float*, int)
{
reconstruction_missing("Entity_NPC::render_debug 009a8b90");
}