Files
isaac-port/src/entity.cpp
T

1322 lines
50 KiB
C++

#include "entity.h"
#include "capsule.h"
#include "entity_effect.h"
#include "entity_familiar.h"
#include "entity_list.h"
#include "entity_npc.h"
#include "entity_player.h"
#include "entity_tear.h"
#include "fx_layers.h"
#include "game.h"
#include "log.h"
#include "lua_engine.h"
#include "manager.h"
#include "room.h"
#include "room_grid.h"
#include <algorithm>
#include <cmath>
#include <cstdarg>
#include <cstdio>
// classes.h declares the original's Lua imports, and its luaL_newstate differs from Lua's only in its return type.
#define luaL_newstate lua_newstate_auxiliary
extern "C"
{
#include "lauxlib.h"
#include "lua.h"
}
#undef luaL_newstate
// GetRenderZ's bands: the background layer, the door layer and the normal layer sorted by depth.
constexpr int RENDER_INDEX_MASK = 0x3ff;
constexpr int RENDER_Z_BACKGROUND_BASE = 100;
constexpr int RENDER_Z_BACKGROUND_MAX = 4999;
constexpr int RENDER_Z_DOOR_BASE = 5100;
constexpr int RENDER_Z_DOOR_MIN = 5000;
constexpr int RENDER_Z_DOOR_MAX = 9999;
constexpr int RENDER_Z_DUNGEON_BASE = 10030;
constexpr float RENDER_Z_NORMAL_MIN = 10000;
constexpr float RENDER_Z_DEPTH_SCALE = 100;
constexpr float RENDER_Z_DEPTH_BASE = 10030;
// The defaults Init and LoadEntityConfig give: slowing, the shadow without a config, and the update clock's start
// just before zero.
constexpr float SLOWING_AMOUNT_DEFAULT = 0.9f;
constexpr float SHADOW_SIZE_DEFAULT = 0.015625f;
constexpr float UPDATE_TIME_START = -1e-05f;
// The drop RNG's shift triple once an entity is initialized (4, 3, 17).
constexpr uint32_t DROP_RNG_SHIFT_INDEX = 30;
// The stage at which a config's per-stage health stops growing, and how much less it grows from the fifth stage on.
constexpr float STAGE_HP_CAP = 10;
constexpr uint32_t STAGE_HP_REDUCED_FROM = 5;
constexpr float STAGE_HP_REDUCED_SCALE = 0.8f;
constexpr float STAGE_HP_MIN = 0.001f;
// The knockback a heavy hit leaves: how it slows, and the speed under which it ends.
constexpr float KNOCKBACK_DECAY = 0.95f;
constexpr float KNOCKBACK_MIN_SPEED = 2;
// A co-op ghost floats over the room.
constexpr float GHOST_BOB_SPEED = 0.2f;
constexpr float GHOST_BOB_HEIGHT = 2;
// How long a seed's charm, confusion or fear lasts each frame, and how often the alternating fear alternates.
constexpr int SEED_STATUS_FRAMES = 2;
constexpr int ALTERNATING_FEAR_FRAMES = 60;
// Shrinking eases toward its target a sixth of the way each frame.
constexpr float SHRINK_EASE = 5 * 0.033333335f;
// Burn and bleed flicker through six colors, poison and burn hurt every twentieth frame.
constexpr int FLICKER_COLORS = 6;
constexpr int STATUS_DAMAGE_INTERVAL = 20;
constexpr int STATUS_DAMAGE_PHASE = 1;
constexpr float BLEED_FLICKER_SCALE = 0.02f;
constexpr int STATUS_COLOR_FRAMES = 2;
// A hit flashes the entity for a third of its damage in frames, from one to six.
constexpr int HIT_FLASH_DIVISOR = 3;
constexpr int HIT_FLASH_MIN = 1;
constexpr int HIT_FLASH_MAX = 6;
constexpr float POSITION_LIMIT = 10000;
// The debug flags PostRender draws for: entity positions, collision shapes and grid collision points.
// The flags an EntityRef's status flags come from, and those CopyStatusEffects hands a segment.
constexpr uint64_t SHARED_STATUS_FLAGS = FLAG_FREEZE | FLAG_POISON | FLAG_SLOW | FLAG_CHARM | FLAG_CONFUSION |
FLAG_MIDAS_FREEZE | FLAG_FEAR | FLAG_BURN | FLAG_SHRINK | FLAG_FRIENDLY |
FLAG_BLEED_OUT | FLAG_KNOCKED_BACK | FLAG_APPLY_IMPACT_DAMAGE | FLAG_ICE |
FLAG_MAGNETIZED | FLAG_BAITED | FLAG_WEAKNESS | FLAG_BRIMSTONE_MARKED;
constexpr ColorMod HIT_COLOR = {{0.5f, 0.5f, 0.5f, 1}, {0, 0, 0, 0}, {0.78431374f, 0, 0}};
constexpr ColorMod HUGE_BOSS_HIT_COLOR = {{0.5f, 0.5f, 0.33f, 1}, {0, 0, 0, 0}, {0.39215687f, 0, 0}};
constexpr ColorMod POISON_COLOR = {{0.1f, 0.5f, 0.1f, 1}, {0, 0, 0, 0}, {0, 0.5f, 0}};
constexpr ColorMod BURN_COLOR = {{0.5f, 0.3f, 0.1f, 1}, {0, 0, 0, 0}, {0.5f, 0.3f, 0}};
constexpr ColorMod BURN_COLORS[FLICKER_COLORS] = {
{{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}},
{{1, 1, 0.8039216f, 1}, {0, 0, 0, 0}, {0.17647059f, 0, 0}},
{{1, 1, 0.60784316f, 1}, {0, 0, 0, 0}, {0.3529412f, 0, 0}},
{{1, 1, 0.8039216f, 1}, {0, 0, 0, 0}, {0.27450982f, 0.09803922f, 0}},
{{1, 1, 1, 1}, {0, 0, 0, 0}, {0.19607843f, 0.19607843f, 0}},
{{1, 1, 1, 1}, {0, 0, 0, 0}, {0.09803922f, 0.09803922f, 0}},
};
constexpr ColorMod BLEED_COLORS[FLICKER_COLORS] = {
{{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}},
{{1, 0.74509805f, 0.74509805f, 1}, {0, 0, 0, 0}, {0.17647059f, 0, 0}},
{{1, 0.47058827f, 0.47058827f, 1}, {0, 0, 0, 0}, {0.3529412f, 0, 0}},
{{0.8627451f, 0.23529413f, 0.23529413f, 1}, {0, 0, 0, 0}, {0.15686275f, 0, 0}},
{{0.9411765f, 0.78431374f, 0.78431374f, 1}, {0, 0, 0, 0}, {0, 0, 0}},
{{1, 0.8039216f, 0.8039216f, 1}, {0, 0, 0, 0}, {0.27450982f, 0, 0}},
};
// The run state flags that keep a killed angel from scoring again (STATE_URIEL_SPAWNED, STATE_GABRIEL_SPAWNED).
constexpr int URIEL_SPAWNED_BIT = 25;
constexpr int GABRIEL_SPAWNED_BIT = 26;
// Formats a message for KAGE_LogMessage, whose declaration takes nothing to format with.
[[gnu::format(printf, 2, 3)]] static void log_format(uint32_t level, const char* format, ...)
{
char message[256];
va_list args;
va_start(args, format);
std::vsnprintf(message, sizeof(message), format, args);
va_end(args);
KAGE_LogMessage(level, (uint8_t*)message);
}
// 0067f310 Where a world position draws on screen, optionally snapped to the display's pixels.
Vector render_position_get(const Vector& world, RenderSnap snap)
{
float viewX = (g_screenWidth - ROOM_VIEW_WIDTH) * HALF;
float viewY = (g_screenHeight - ROOM_VIEW_HEIGHT) * HALF;
Vector screen = vector_make(viewX + (world.x - ROOM_ORIGIN_X) * ROOM_SCREEN_SCALE,
viewY + (world.y - ROOM_ORIGIN_Y) * ROOM_SCREEN_SCALE);
if (snap == RENDER_UNSNAPPED) return screen;
float pixelScale = g_displayPixelRatio * g_screenPointScale;
return vector_make(std::floor(screen.x * pixelScale + HALF) / pixelScale,
std::floor(screen.y * pixelScale + HALF) / pixelScale);
}
// 004cf1d0, 006b5b50, 00872050 Points at another entity, moving its registration from the old one to the new one.
void EntityPtr::Set(Entity* target)
{
if (entity == target) return;
if (entity) std::erase(entity->referrers, this);
entity = target;
if (entity) entity->referrers.push_back(this);
}
// 00431310 A snapshot of the entity, or an empty one for none.
EntityRef::EntityRef(Entity* source)
{
entity = source;
if (!source) return;
type = source->type;
variant = source->variant;
spawnerType = source->spawnerType;
spawnerVariant = source->spawnerVariant;
position = source->pos;
velocity = source->velocity;
if (source->HasEntityFlags(FLAG_CHARM)) flags |= ENTITY_REF_CHARMED;
if (source->HasEntityFlags(FLAG_FRIENDLY)) flags |= ENTITY_REF_FRIENDLY;
if (source->HasEntityFlags(FLAG_WEAKNESS)) flags |= ENTITY_REF_WEAKNESS;
}
// 006a8850 (006a8820) Removes the entity if it still exists and drops its Lua data.
// The original left the pointers to a destroyed entity dangling: they are nulled here.
Entity::~Entity()
{
if (isExists) Entity::Remove();
data_release();
for (EntityPtr* referrer : referrers) referrer->forget();
}
// Frees the table GetData made for Lua, if any.
void Entity::data_release()
{
if (dataRef == LUA_REF_NONE) return;
luaL_unref(static_cast<LuaEngine*>(g_luaEngine)->state, LUA_REGISTRYINDEX, dataRef);
dataRef = LUA_REF_NONE;
}
// 00499da0
Entity_Player* Entity::ToPlayer()
{
return type == ENTITY_PLAYER ? static_cast<Entity_Player*>(this) : nullptr;
}
// 00435e40
Entity_Tear* Entity::ToTear()
{
return type == ENTITY_TEAR ? static_cast<Entity_Tear*>(this) : nullptr;
}
// Whether the type is an enemy's, or a player's in a versus match.
bool Entity::is_enemy_type(int entityType)
{
if (g_game->deathmatchManager.is_active() && entityType == ENTITY_PLAYER) return true;
return entityType >= ENTITY_FIRST_ENEMY && entityType <= ENTITY_LAST_ENEMY;
}
// 00435e00 Itself if it is an enemy, or a player in a versus match.
Entity* Entity::to_npc_or_coop_player()
{
return is_enemy_type(type) ? this : nullptr;
}
// 00431450 Pushes it, scaled by its speed unless told not to.
void Entity::AddVelocity(const Vector& added, bool isIgnoreSpeedMultiplier)
{
float multiplier = isIgnoreSpeedMultiplier ? 1 : speedMultiplier;
velocity.x = multiplier * added.x + velocity.x;
velocity.y = added.y * multiplier + velocity.y;
}
// 004314b0 Pushes it against its friction, so the push survives the next slowdown.
void Entity::AddVelocity_divided(const Vector& added, bool isIgnoreSpeedMultiplier)
{
if (friction == 0) return;
float multiplier = isIgnoreSpeedMultiplier ? 1 : speedMultiplier;
velocity.x = (multiplier * added.x) / friction + velocity.x;
velocity.y = (added.y * multiplier) / friction + velocity.y;
}
// 006a9c50 Heals it up to its maximum.
void Entity::AddHealth(float amount)
{
health = std::min(amount + health, maxHitPoints);
}
// 006a9c10 The frames since it spawned.
int Entity::FrameCount()
{
return g_game->frameCount - spawnFrame;
}
// 00435db0 How many whole ticks of its own time this update covers.
int Entity::update_ticks_get()
{
return (int)updateTime - (int)prevUpdateTime;
}
// 006ac710 Whether this is one of every frequency frames, never on an interpolation update or while paused.
bool Entity::IsFrame(int frequency, int offset)
{
if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused()) return false;
return (g_game->frameCount + offset) % frequency == 0;
}
// 006ac760 How many intervals of its own time this update crossed.
int Entity::GetIntervalTicks(float interval, float offset)
{
if (HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused()) return 0;
return (int)((offset + updateTime) / interval) - (int)((offset + prevUpdateTime) / interval);
}
// 006ac8d0 The direction it moves in most, as a Direction.
int Entity::get_velocity_direction()
{
if (std::fabs(velocity.y) < std::fabs(velocity.x)) return velocity.x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
return velocity.y >= 0 ? DIRECTION_DOWN : DIRECTION_UP;
}
// 006ac2a0 Resizes its collision ellipse and lays the grid collision points around it, the even ones first.
// A -1 multiplier or point count takes the config's.
void Entity::SetSize(float newSize, Vector newSizeMulti, int gridCollisionPoints)
{
if (newSizeMulti.x == -1 && newSizeMulti.y == -1) newSizeMulti = config->collisionRadiusMulti;
if (gridCollisionPoints == -1) gridCollisionPoints = config->gridCollisionPoints;
if (size == newSize && sizeMulti.x == newSizeMulti.x && sizeMulti.y == newSizeMulti.y) return;
size = newSize;
sizeMulti = newSizeMulti;
collisionPoints.clear();
for (int first : {0, 1})
{
for (int i = first; i < gridCollisionPoints; i += 2)
{
double angle = (((float)i + (float)i) * PI_F) / (float)gridCollisionPoints;
collisionPoints.push_back(vector_make((float)std::cos(angle) * size * sizeMulti.x,
(float)std::sin(angle) * size * sizeMulti.y));
}
}
}
// 006a8990 The top of its parent chain.
Entity* Entity::GetLastParent()
{
Entity* last = this;
while (last->parent) last = last->parent;
return last;
}
// 006a89b0 The end of its child chain.
Entity* Entity::GetLastChild()
{
Entity* last = this;
while (last->child) last = last->child;
return last;
}
// 006a89d0 Whatever spawned what spawned it, as far back as it goes.
Entity* Entity::GetLastSpawner()
{
Entity* last = this;
while (last->spawnerEntity) last = last->spawnerEntity;
return last;
}
// 006a89f0 The segment that holds the status effects of a body sharing them, or itself.
Entity* Entity::GetStatusEffectTarget()
{
return DoesEntityShareStatus() ? GetLastParent() : this;
}
// 0067a720 (misnamed GetRootParent) How many frames a Ludovico water tear's bob lasts: the max fire delay of the
// player its spawners lead back to, plus 8, or 18 for anything else.
float Entity::hydrobounce_period_get()
{
constexpr float PERIOD_BASE = 8;
constexpr float PERIOD_FIRE_DELAY = 10;
Entity* root = GetLastSpawner();
float fireDelay = root->type == ENTITY_PLAYER ? static_cast<Entity_Player*>(root)->maxFireDelay : PERIOD_FIRE_DELAY;
return fireDelay + PERIOD_BASE;
}
// Follows a chain of links from start, stopping at the first entity found or where the chain loops.
template <class Next, class Found> static Entity* chain_find(Entity* start, Next next, Found isFound)
{
std::vector<Entity*> visited;
for (Entity* current = start; current; current = next(current))
{
if (isFound(current)) return current;
if (std::find(visited.begin(), visited.end(), current) != visited.end()) break;
visited.push_back(current);
}
return nullptr;
}
static Entity* parent_next(Entity* entity)
{
return entity->parent;
}
static Entity* spawner_next(Entity* entity)
{
return entity->spawnerEntity;
}
// 006a8fa0 Whether the ancestor is itself, or up its parent or spawner chains.
bool Entity::IsDescendantOf(Entity* ancestor)
{
if (!ancestor) return false;
if (ancestor == this) return true;
auto isAncestor = [ancestor](Entity* entity) { return entity == ancestor; };
return chain_find(parent, parent_next, isAncestor) || chain_find(spawnerEntity, spawner_next, isAncestor);
}
// 006a9140 The player up its parent chain, or else up its spawner chain.
Entity* Entity::GetPlayerAncestor()
{
auto isPlayer = [](Entity* entity) { return entity->type == ENTITY_PLAYER; };
Entity* player = chain_find(this, parent_next, isPlayer);
return player ? player : chain_find(this, spawner_next, isPlayer);
}
// 006a8c00 Whether both are segments of one body, never for a ring of flies.
bool Entity::HasCommonParentWithEntity(Entity* other)
{
if (other && other->type == ENTITY_RING_OF_FLIES) return false;
return (other ? other->GetLastParent() : nullptr) == GetLastParent();
}
// Whether the entity is a boss or enemy made of segments that act as one body.
static bool is_segmented(const Entity& entity)
{
switch (entity.type)
{
case ENTITY_LARRYJR:
case ENTITY_CHUB:
case ENTITY_MRMAW:
case ENTITY_PIN:
case ENTITY_BUTTLICKER:
case ENTITY_SWINGER:
case ENTITY_GRUB:
case ENTITY_SCOURGE:
case ENTITY_MOTHER:
case ENTITY_TURDLET:
return true;
case ENTITY_ROUND_WORM:
return entity.variant == 2;
default:
return false;
}
}
// 006a8c60 Whether the other is a segment of its own body, for the bosses made of segments.
bool Entity::is_same_segmented_body(Entity* other)
{
if (!is_segmented(*this)) return false;
if (!other) return true;
return other->type != ENTITY_RING_OF_FLIES && other->GetLastParent() == GetLastParent();
}
// 006a8db0 Whether its status effects belong to its whole body.
bool Entity::DoesEntityShareStatus()
{
switch (type)
{
case ENTITY_LARRYJR:
case ENTITY_CHUB:
case ENTITY_MRMAW:
case ENTITY_PIN:
case ENTITY_GEMINI:
case ENTITY_BUTTLICKER:
case ENTITY_HEART:
case ENTITY_MASK:
case ENTITY_MASK_OF_INFAMY:
case ENTITY_HEART_OF_INFAMY:
case ENTITY_SWINGER:
case ENTITY_GRUB:
case ENTITY_SCOURGE:
case ENTITY_MOTHER:
case ENTITY_TURDLET:
return true;
case ENTITY_ROUND_WORM:
return variant == 2;
default:
return false;
}
}
// 006a8a20 Hands its status effects down its child chain, the boss cooldown only between bosses.
void Entity::CopyStatusEffects()
{
if (!DoesEntityShareStatus()) return;
bool isVersusPlayer = g_game->deathmatchManager.is_active() && type == ENTITY_PLAYER;
for (Entity* segment = child; segment; segment = segment->child)
{
segment->freezeCountdown = freezeCountdown;
segment->flags = (segment->flags & ~SHARED_STATUS_FLAGS) | (flags & SHARED_STATUS_FLAGS);
segment->poisonCountdown = poisonCountdown;
segment->slowingCountdown = slowingCountdown;
segment->charmedCountdown = charmedCountdown;
segment->confusionCountdown = confusionCountdown;
segment->midasFreezeCountdown = midasFreezeCountdown;
segment->fearCountdown = fearCountdown;
segment->burnCountdown = burnCountdown;
segment->bleedingCountdown = bleedingCountdown;
segment->shrinkCountdown = shrinkCountdown;
segment->poisonTickDamage = poisonTickDamage;
segment->burnTickDamage = burnTickDamage;
segment->magnetizedCountdown = magnetizedCountdown;
segment->baitedCountdown = baitedCountdown;
segment->knockbackCountdown = knockbackCountdown;
segment->knockbackDirection = knockbackDirection;
segment->iceCountdown = iceCountdown;
segment->weaknessCountdown = weaknessCountdown;
segment->brimstoneMarkCountdown = brimstoneMarkCountdown;
segment->shrinkStatus1 = shrinkStatus1;
segment->shrinkStatus2 = shrinkStatus2;
bool isBossLike = IsBoss() || isVersusPlayer;
bool isSegmentBossLike = segment->IsBoss() || (g_game->deathmatchManager.is_active() &&
segment->type == ENTITY_PLAYER);
if (isBossLike && isSegmentBossLike) segment->bossStatusEffectCooldown = bossStatusEffectCooldown;
}
}
// Sorted insertion into a hit list, as the entities keep them.
void hit_list_insert(std::vector<uint32_t>& hitList, Entity& entity)
{
uint32_t index = entity.GetHitListIndex();
auto at = std::lower_bound(hitList.begin(), hitList.end(), index);
if (at == hitList.end() || *at != index) hitList.insert(at, index);
}
// 006b62b0 The index hits on it are recorded under: its body's for segmented bosses that share them.
uint32_t Entity::GetHitListIndex()
{
if (!is_enemy_type(type) || (g_game->deathmatchManager.is_active() && type == ENTITY_PLAYER)) return index;
if (!is_segmented(*this) || type == ENTITY_BUTTLICKER || type == ENTITY_LARRYJR) return index;
if ((type == ENTITY_CHUB && variant == 2) || (type == ENTITY_PIN && variant == 1))
{
if (child) return index;
}
return GetStatusEffectTarget()->index;
}
// 006ac530 Whether it is an enemy, or a player in a versus match.
bool Entity::IsEnemy()
{
return is_enemy_type(type);
}
// 006ac6c0 Whether its grid collision ignores everything but walls.
bool Entity::IsFlying()
{
return entityGridCollisionClass == GRIDCOLL_NONE || entityGridCollisionClass == GRIDCOLL_WALLS ||
entityGridCollisionClass == GRIDCOLL_WALLS_X || entityGridCollisionClass == GRIDCOLL_WALLS_Y;
}
// 006ac560 Whether the source can hurt it as an enemy: collidable, mortal, targetable, and not on the source's side.
bool Entity::IsVulnerableEnemy(Entity* source)
{
bool isVersus = g_game->deathmatchManager.is_active();
if (isVersus && source && source->type == ENTITY_PLAYER && IsDescendantOf(source)) return false;
if (!is_enemy_type(type)) return false;
if (entityCollisionClass == ENTCOLL_PLAYERONLY || entityCollisionClass == ENTCOLL_NONE) return false;
if (isInvincible || isDead) return false;
if (HasEntityFlags(FLAG_NO_TARGET) && type != ENTITY_BLOOD_PUPPY && type != ENTITY_DARK_ESAU) return false;
if (!source || !IsFriendly()) return true;
Entity* origin = source->GetLastSpawner();
return !origin->IsFriendly() && origin->type != ENTITY_PLAYER && origin->type != ENTITY_FAMILIAR;
}
// 006b5b90 Whether it is an enemy that counts as active, alive unless the dead are included.
bool Entity::IsActiveEnemy(DeadMode mode)
{
if (!(g_game->deathmatchManager.is_active() && type == ENTITY_PLAYER))
{
if (type < ENTITY_FIRST_ENEMY || type > ENTITY_LAST_ENEMY) return false;
if (type == ENTITY_FIREPLACE || type == ENTITY_SHOPKEEPER || type == ENTITY_MOVABLE_TNT) return false;
if (type == ENTITY_CULTIST && variant == 10) return false;
if (type == ENTITY_GENERIC_PROP || type == ENTITY_MINECART || type == ENTITY_POOP) return false;
}
return !isDead || mode == DEAD_INCLUDED;
}
// 006d7d60 Whether the other is on the opposite side: charmed and friendly entities side with the players.
bool Entity::IsHostileTo(Entity* other)
{
if (HasEntityFlags(FLAG_CHARM) && !IsFriendly()) return true;
bool isEnemySide = !IsFriendly();
bool isOtherPlayerSide = other->type == ENTITY_PLAYER || other->type == ENTITY_BOMB ||
(other->type == ENTITY_FAMILIAR && !other->HasEntityFlags(FLAG_CHARM)) ||
other->IsFriendly();
return !isOtherPlayerSide != isEnemySide;
}
// 006acd10 Whether damage from the source is the players' own, while it is friendly or charmed by a player.
bool Entity::IsDamageSourceFriendly(const EntityRef& source)
{
bool isVersus = g_game->deathmatchManager.is_active();
if (type == ENTITY_PLAYER && source.type == ENTITY_PLAYER && !isVersus) return true;
Entity* charmer = charmSource.entity;
bool isPlayerCharmed = HasEntityFlags(FLAG_CHARM) && charmer && charmer->type == ENTITY_PLAYER &&
charmedCountdown == 0;
bool isFriendly = IsFriendly() || (type == ENTITY_FAMILIAR && !HasEntityFlags(FLAG_CHARM | FLAG_FRIENDLY)) ||
isPlayerCharmed;
if (!isFriendly) return false;
bool isPlayerSource = source.spawnerType == ENTITY_PLAYER || source.type == ENTITY_PLAYER ||
source.type == ENTITY_KNIFE || source.spawnerType == ENTITY_FAMILIAR ||
source.type == ENTITY_FAMILIAR || (source.flags & ENTITY_REF_FRIENDLY) ||
(source.type == ENTITY_EFFECT && Entity_Effect::IsPlayerCreep(source.variant));
if (isVersus && !IsDescendantOf(source.entity))
{
if (!source.entity || !source.entity->IsDescendantOf(charmSource.entity)) return false;
}
return is_enemy_type(type) && isPlayerSource;
}
// 006a8f20 Whether it is an enemy that holds the room's doors shut as a living, hostile foe.
bool Entity::is_valid_boss_enemy()
{
return is_enemy_type(type) && CanShutDoors() && type != ENTITY_DARK_ESAU && !IsFriendly();
}
// 006d8990 Whether a player may take control of it: a living enemy that is not a fireplace, shopkeeper, TNT, poop,
// prop, minecart or the blood cultist's spawn, nobody controls yet and that has no FLAG_NO_PLAYER_CONTROL. A body of
// segments counts only at its root: a Ring of Flies or Swarm fly's parent NPC, an Army Fly's last enemy parent, or the
// head of a body sharing its status.
// The original reads a versus player's controller as an NPC's. Here a player has none.
bool Entity::is_valid_target()
{
bool isEnemy = is_enemy_type(type) && type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER &&
type != ENTITY_MOVABLE_TNT && type != ENTITY_GENERIC_PROP && type != ENTITY_MINECART &&
type != ENTITY_POOP && !(type == ENTITY_CULTIST && variant == CULTIST_BLOOD_SPAWN);
if (!isEnemy || isDead) return false;
Entity* root = this;
auto* npc = static_cast<Entity_NPC*>(this);
if (type == ENTITY_RING_OF_FLIES || (type == ENTITY_SWARM && npc->ParentNPC())) root = npc->ParentNPC();
else if (type == ENTITY_ARMYFLY)
{
Entity* ancestor = GetLastParent();
if (is_enemy_type(ancestor->type)) root = ancestor;
}
else if (type != ENTITY_SWARM)
{
if (DoesEntityShareStatus()) root = GetLastParent();
if (!is_enemy_type(root->type)) root = nullptr;
}
bool isControlled = type != ENTITY_PLAYER && npc->controllerID != -1;
return root == this && !isControlled && !HasEntityFlags(FLAG_NO_PLAYER_CONTROL);
}
// 006a8f80 Whether its config lists anything it can devolve into.
bool Entity::CanDevolve()
{
return config && !config->devolve.empty();
}
// 006b9740 Whether a player (or Isaac's Heart) is within radius of a position. A friendly entity never sees one.
bool Entity::IsPlayerInRadius(const Vector& center, float radius)
{
if (IsFriendly() || radius <= 0) return false;
for (Entity_Player* player : g_game->playerManager.playerList)
{
Vector delta = vector_make(center.x - player->pos.x, center.y - player->pos.y);
if (delta.x * delta.x + delta.y * delta.y < radius * radius) return true;
}
for (Entity* entity : entity_query_radius(center, radius, QUERY_FAMILIARS))
if (entity->type == ENTITY_FAMILIAR && entity->variant == Entity_Familiar::ISAACS_HEART) return true;
return false;
}
// 007e9130 The boss id its config gives, 0 without one.
int Entity::GetBossID()
{
return config ? config->bossID : 0;
}
// 006a93a0 Sets it up as a fresh entity of the type: config stats, full health, default state and no status.
void Entity::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed)
{
type = entityType;
variant = entityVariant;
subtype = entitySubType;
initSeed = seed;
dropRNG.SetSeed(seed, DROP_RNG_SHIFT_INDEX);
splatColor = COLOR_DEFAULT;
LoadEntityConfig();
friction = baseFriction;
shadowOffset = {};
pauseTimer = 0;
index = 0;
collisionIndex = 0;
spawnFrame = g_game->frameCount;
health = maxHitPoints;
spawnGridIndex = -1;
targetPosition = {};
speedMultiplier = 1;
prevUpdateTime = UPDATE_TIME_START;
updateTime = 0;
posOffset = {};
renderZOffset = 0;
renderDepthOffset = 0;
sortingLayer = SORTING_NORMAL;
isVisible = true;
isExists = true;
isDead = false;
isKillOnTouch = false;
isUnknown176 = false;
isRemovedByFactory = false;
entityCollisionClass = ENTCOLL_ALL;
isCollidesWithEntity = false;
isCollidesWithGrid = false;
gridCollisionNormal = {};
gridCollisionVelocity = {};
color = COLOR_DEFAULT;
fireDamageCountdown = 0;
damageCountdown = 0;
freezeCountdown = 0;
poisonCountdown = 0;
poisonTickDamage = STATUS_TICK_DAMAGE_DEFAULT;
burnTickDamage = STATUS_TICK_DAMAGE_DEFAULT;
slowingCountdown = 0;
slowingAmount = SLOWING_AMOUNT_DEFAULT;
charmedCountdown = 0;
confusionCountdown = 0;
midasFreezeCountdown = 0;
fearCountdown = 0;
burnCountdown = 0;
shrinkCountdown = 0;
bleedingCountdown = 0;
bleedDamageAccumulator = 0;
poisonDamageTimer = 0;
burnDamageTimer = 0;
magnetizedCountdown = 0;
baitedCountdown = 0;
knockbackCountdown = 0;
iceCountdown = 0;
weaknessCountdown = 0;
brimstoneMarkCountdown = 0;
magnetizedEffect = nullptr;
bossStatusEffectCooldown = 0;
flags = 0;
damageEvents.clear();
pendingDamage = 0;
pendingDamageFlags = 0;
isInvincible = false;
isInterpolating = false;
holdCountdown = 0;
shrinkStatus1 = 1;
shrinkStatus2 = 1;
parent = nullptr;
child = nullptr;
target = nullptr;
minecart = nullptr;
hitEffect = nullptr;
prevPosition = pos;
prevVelocity = velocity;
pitfallState = 0;
pitfallTimer = 0;
pausePosition = {};
ResetColor();
scoreMultiplier = 1;
bool isAngelKilled = (type == ENTITY_GABRIEL && (g_game->gameStateFlags >> GABRIEL_SPAWNED_BIT & 1)) ||
(type == ENTITY_URIEL && (g_game->gameStateFlags >> URIEL_SPAWNED_BIT & 1));
if (isAngelKilled) scoreMultiplier = 0;
data_release();
}
// An entity's health on the current floor: its base health, plus its stage health for each stage (to the tenth, a
// fifth less from the fifth) when it has any.
float stage_health_get(float baseHealth, float stageHealth)
{
if (stageHealth <= STAGE_HP_MIN) return baseHealth;
float stage = std::min((float)g_game->stage, STAGE_HP_CAP);
float scale = g_game->stage < STAGE_HP_REDUCED_FROM ? 1 : STAGE_HP_REDUCED_SCALE;
return stage * scale * stageHealth + baseHealth;
}
// 006a98b0 Takes its stats from its config (preloading its resources), or defaults with a log line without one.
void Entity::LoadEntityConfig()
{
EntityConfig& entityConfig = g_manager->entityConfig;
EntityConfig_Entity* found = entityConfig.GetEntity(type, variant, subtype);
if (found) entityConfig.PreloadResources(found);
config = entityConfig.GetEntity(type, variant, subtype);
if (!config)
{
size = 1;
sizeMulti = vector_make(1, 1);
shadowSize = SHADOW_SIZE_DEFAULT;
collisionDamage = 0;
maxHitPoints = 0;
mass = 0;
collisionPoints.clear();
entityGridCollisionClass = GRIDCOLL_WALLS;
baseFriction = 1;
log_format(LOG_INFO, "config for entity %d.%d is missing\n", type, variant);
return;
}
shadowSize = config->shadowSize;
collisionDamage = config->collisionDamage;
mass = config->mass;
maxHitPoints = stage_health_get(config->baseHP, config->stageHP);
size = 0;
sizeMulti = {};
SetSize(config->collisionRadius, config->collisionRadiusMulti, config->gridCollisionPoints);
baseFriction = config->friction;
const std::string& gridClass = config->gridCollisionClassString;
if (gridClass.empty()) entityGridCollisionClass = collisionPoints.empty() ? GRIDCOLL_WALLS : GRIDCOLL_GROUND;
else if (gridClass == "none") entityGridCollisionClass = GRIDCOLL_NONE;
else if (gridClass == "walls") entityGridCollisionClass = GRIDCOLL_WALLS;
else if (gridClass == "ground") entityGridCollisionClass = GRIDCOLL_GROUND;
else if (gridClass == "nopits") entityGridCollisionClass = GRIDCOLL_NOPITS;
else log_format(LOG_ASSERT, "Invalid grid collision class for entity config %d.%d.%d", type, variant, subtype);
}
// 006ae7d0 Remembers where it was and how it moved before this update.
void Entity::PreUpdate()
{
prevPosition = pos;
prevVelocity = velocity;
}
// 006ae820 Advances its sprite and its own clock, moves it under friction and knockback, then ticks its timed colors
// and status effects, applies the damage queued since the last update, and hurts it with poison and burns.
void Entity::Update()
{
if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE))
{
prevUpdateTime = updateTime;
updateTime = speedMultiplier + updateTime;
bool isHeld = HasEntityFlags(FLAG_FREEZE) || holdCountdown > 0;
if ((!isHeld || isDead) && !HasEntityFlags(FLAG_NO_SPRITE_UPDATE) && sprite.isLoaded)
{
float playbackSpeed = sprite.playbackSpeed * speedMultiplier;
sprite.animState.Update(playbackSpeed);
sprite.overlayAnimState.Update(playbackSpeed);
}
}
if (HasEntityFlags(FLAG_KNOCKED_BACK)) knockback_update();
float frameFriction = friction;
if (speedMultiplier != 1)
frameFriction = frameFriction / ((frameFriction + speedMultiplier) - frameFriction * speedMultiplier);
velocity = vector_make(frameFriction * velocity.x, frameFriction * velocity.y);
pos.y = speedMultiplier * velocity.y + pos.y;
pos.x = speedMultiplier * velocity.x + pos.x;
friction = baseFriction;
if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE))
{
color_params_update();
status_effects_update();
}
if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) damage_events_update();
if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE)) status_damage_update();
Room& room = *g_game->room;
if (!HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && room.waterAmount > 0 &&
g_manager->optionsConfig.render.isWaterSurfaceEnabled)
water_ripples_update();
if (std::fabs(pos.x) + std::fabs(pos.y) >= POSITION_LIMIT)
log_format(LOG_ASSERT, "Invalid entity position detected: %.2f, %.2f (%d.%d.%d)\n", pos.x, pos.y, type, variant,
subtype);
}
// A knockback that hurts on impact, hitting a wall: it bounces back along its motion at four fifths of its push and
// takes 10 plus twice the floor's depth (one deeper on the alternate path) once.
constexpr float WALL_IMPACT_BOUNCE = 0.8f;
constexpr float WALL_IMPACT_DAMAGE = 10;
constexpr int WALL_IMPACT_COUNTDOWN = 30;
void Entity::wall_impact_apply()
{
float push = vector_length(knockbackDirection);
knockbackDirection = vector_scale(vector_normalized(velocity), push * WALL_IMPACT_BOUNCE);
TakeDamage((float)(g_game->stage_depth_get() - 1) * 2 + WALL_IMPACT_DAMAGE, 0, EntityRef(), WALL_IMPACT_COUNTDOWN);
ClearEntityFlags(FLAG_APPLY_IMPACT_DAMAGE);
}
// A heavy knockback's push: it keeps the entity moving, slowing, until it is spent or something stops it.
void Entity::knockback_update()
{
bool isPushing = isCollidesWithGrid || vector_length(velocity) < vector_length(knockbackDirection) ||
knockbackDirection.x * velocity.x + knockbackDirection.y * velocity.y >= 0;
if (!isPushing || vector_length(knockbackDirection) < KNOCKBACK_MIN_SPEED)
{
ClearEntityFlags(FLAG_KNOCKED_BACK | FLAG_APPLY_IMPACT_DAMAGE);
knockbackCountdown = 0;
return;
}
friction = baseFriction * KNOCKBACK_DECAY;
if (!HasEntityFlags(FLAG_ICE_FROZEN))
{
knockbackDirection.x = knockbackDirection.x * KNOCKBACK_DECAY;
knockbackDirection.y = knockbackDirection.y * KNOCKBACK_DECAY;
}
if (isCollidesWithGrid)
{
if (HasEntityFlags(FLAG_APPLY_IMPACT_DAMAGE)) wall_impact_apply();
knockbackCountdown = knockbackCountdown / 2;
}
velocity = knockbackDirection;
}
// Counts down the timed colors and shows the top one, fading toward the next when it fades.
void Entity::color_params_update()
{
bool isChanged = false;
for (auto it = colorParams.begin(); it != colorParams.end();)
{
it->remaining--;
if (it->isFadeout) isChanged = true;
if (it->remaining == 0)
{
it = colorParams.erase(it);
isChanged = true;
}
else
++it;
}
if (!isChanged) return;
if (colorParams.empty()) return ResetColor();
const ColorParams& top = colorParams.front();
sprite.color = top.color;
if (!top.isFadeout) return;
const ColorMod& next = colorParams.size() < 2 ? color : colorParams[1].color;
sprite.color = color_lerp(top.color, next, 1 - (float)top.remaining / (float)top.duration);
}
// Applies the status effects the run's seeds force on enemies, then counts every status effect down.
void Entity::status_effects_update()
{
Seeds& seeds = g_game->seedEffects;
if (!HasEntityFlags(FLAG_NO_STATUS_EFFECTS) && is_enemy_type(type))
{
if (seeds.HasSeedEffect(SEED_ALWAYS_CHARMED) || seeds.HasSeedEffect(SEED_ALWAYS_CHARMED_AND_AFRAID))
{
AddEntityFlags(FLAG_CHARM);
charmedCountdown = SEED_STATUS_FRAMES;
}
if (seeds.HasSeedEffect(SEED_ALWAYS_CONFUSED))
{
AddEntityFlags(FLAG_CONFUSION);
confusionCountdown = SEED_STATUS_FRAMES;
}
bool isFearPhase = (FrameCount() / ALTERNATING_FEAR_FRAMES & 1) == 0;
if (seeds.HasSeedEffect(SEED_ALWAYS_AFRAID) || seeds.HasSeedEffect(SEED_ALWAYS_CHARMED_AND_AFRAID) ||
(seeds.HasSeedEffect(SEED_ALWAYS_ALTERNATING_FEAR) && isFearPhase))
{
AddEntityFlags(FLAG_FEAR);
fearCountdown = SEED_STATUS_FRAMES;
}
}
// A countdown that reaches zero clears its flag.
auto countdown = [this](int& frames, uint64_t flag)
{
if (frames <= 0 || --frames >= 1) return false;
ClearEntityFlags(flag);
return true;
};
if (fireDamageCountdown > 0) fireDamageCountdown--;
if (damageCountdown > 0) damageCountdown--;
countdown(freezeCountdown, FLAG_FREEZE);
if (countdown(poisonCountdown, FLAG_POISON)) poisonTickDamage = STATUS_TICK_DAMAGE_DEFAULT;
countdown(slowingCountdown, FLAG_SLOW);
if (countdown(charmedCountdown, FLAG_CHARM)) target = nullptr;
countdown(confusionCountdown, FLAG_CONFUSION);
countdown(fearCountdown, FLAG_FEAR);
if (shrinkStatus2 != shrinkStatus1) shrinkStatus1 = (shrinkStatus2 - shrinkStatus1) * SHRINK_EASE + shrinkStatus1;
if (countdown(shrinkCountdown, FLAG_SHRINK))
{
SetSize(config->collisionRadius, vector_make(-1, -1), -1);
shrinkStatus2 = 1;
}
int flicker = FrameCount() % FLICKER_COLORS;
if (burnCountdown > 0)
{
if (countdown(burnCountdown, FLAG_BURN)) burnTickDamage = STATUS_TICK_DAMAGE_DEFAULT;
SetColor(BURN_COLORS[flicker], 1, STATUS_COLOR_PRIORITY, false, true);
}
countdown(midasFreezeCountdown, FLAG_MIDAS_FREEZE);
if (bleedingCountdown > 0)
{
if (countdown(bleedingCountdown, FLAG_BLEED_OUT)) bleedDamageAccumulator = 0;
float moved = vector_length(vector_make(pos.x - prevPosition.x, pos.y - prevPosition.y));
float t = std::clamp((moved * BLEED_FLICKER_SCALE) / speedMultiplier, 0.0f, 1.0f);
uint32_t bleedFlicker = (uint32_t)FrameCount() % FLICKER_COLORS;
SetColor(color_lerp(COLOR_DEFAULT, BLEED_COLORS[bleedFlicker], t), 1, STATUS_COLOR_PRIORITY, false, true);
}
countdown(magnetizedCountdown, FLAG_MAGNETIZED);
if (countdown(baitedCountdown, FLAG_BAITED))
{
for (Entity* enemy : g_game->room->entityList.updateEL)
{
bool isLured = enemy->target.get() == this && !enemy->HasEntityFlags(FLAG_CHARM | FLAG_FRIENDLY);
if (is_enemy_type(enemy->type) && isLured) enemy->target = nullptr;
}
}
countdown(weaknessCountdown, FLAG_WEAKNESS);
if (magnetizedEffect && !HasEntityFlags(FLAG_MAGNETIZED)) magnetizedEffect->Remove();
countdown(knockbackCountdown, FLAG_KNOCKED_BACK | FLAG_APPLY_IMPACT_DAMAGE);
countdown(iceCountdown, FLAG_ICE);
countdown(brimstoneMarkCountdown, FLAG_BRIMSTONE_MARKED);
if (bossStatusEffectCooldown > 0) bossStatusEffectCooldown--;
if (holdCountdown > 0) holdCountdown--;
}
// Takes the damage queued since the last update, flashing on each hit and dying on a fatal one.
void Entity::damage_events_update()
{
if (!isInvincible)
{
bool isFatal = false;
EntityRef fatalSource;
for (const DamageEvent& event : damageEvents)
{
if (event.damage <= 0) continue;
if (g_game->debugFlags & DEBUG_DAMAGE_VALUES)
reconstruction_missing("Entity::Update 006ae820: the debug damage numbers (spawn_debug_damage_text)");
bool isHiss = (event.damageFlags & (DAMAGE_FIRE | DAMAGE_POOP)) && !(event.damageFlags & DAMAGE_EXPLOSION);
if (isHiss)
{
int sound = SOUND_FIREDEATH_HISS;
seed_fart_sound_override(&sound);
g_manager->sfxManager.Play(sound);
}
health -= event.damage;
if (health > 0 || (event.damageFlags & DAMAGE_NOKILL))
{
if (HasEntityFlags(FLAG_NO_FLASH_ON_DAMAGE)) continue;
if (health < 0) health = 0;
int frames = ((int)(event.damage + HALF) + 2) / HIT_FLASH_DIVISOR;
frames = std::clamp(frames, HIT_FLASH_MIN, HIT_FLASH_MAX);
bool isHugeBoss = type == ENTITY_HUSH || type == ENTITY_BEAST;
SetColor(isHugeBoss ? HUGE_BOSS_HIT_COLOR : HIT_COLOR, frames, 0, false, false);
}
else
{
fatalSource = event.source;
isFatal = true;
}
}
if (isFatal) Kill(fatalSource);
}
damageEvents.clear();
pendingDamage = 0;
pendingDamageFlags = 0;
}
// Poisons and burns an enemy every twentieth frame of the effect and bleeds it, then a magnetized one pulls things in.
void Entity::status_damage_update()
{
if (is_enemy_type(type))
{
if (HasEntityFlags(FLAG_POISON) && poisonDamageTimer++ % STATUS_DAMAGE_INTERVAL == STATUS_DAMAGE_PHASE)
{
SetColor(POISON_COLOR, STATUS_COLOR_FRAMES, STATUS_COLOR_PRIORITY, false, true);
TakeDamage(poisonTickDamage, DAMAGE_POISON_BURN, EntityRef(), 0);
}
if (HasEntityFlags(FLAG_BURN) && burnDamageTimer++ % STATUS_DAMAGE_INTERVAL == STATUS_DAMAGE_PHASE)
{
SetColor(BURN_COLOR, STATUS_COLOR_FRAMES, STATUS_COLOR_PRIORITY, false, true);
TakeDamage(burnTickDamage, DAMAGE_POISON_BURN, EntityRef(), 0);
}
if (HasEntityFlags(FLAG_BLEED_OUT) && !IsDescendantOf(bleedSource.entity)) bleed_update();
}
if (!isDead && HasEntityFlags(FLAG_MAGNETIZED)) magnet_pull_update();
}
// 006b0eb0 Moves it half a step for the in-between frame and resolves the grid, unless told to skip one.
void Entity::Interpolate()
{
if (HasEntityFlags(FLAG_NO_INTERPOLATE))
{
ClearEntityFlags(FLAG_NO_INTERPOLATE);
return;
}
preInterpolatePos = pos;
isInterpolating = true;
pos.x = friction * velocity.x * speedMultiplier * HALF + pos.x;
pos.y = friction * velocity.y * speedMultiplier * HALF + pos.y;
if (type != ENTITY_PLAYER) return CollideWithGrid(GRID_COLLISION_SIMULATE);
PlayerCollideWithGrid(GRID_COLLISION_SIMULATE);
if (variant != PLAYER_VARIANT_COOP_BABY) return;
pos = g_game->room->GetClampedPositionImpl(pos, size, size, size, size);
posOffset.y = GHOST_BOB_HEIGHT * std::sin(((float)g_game->frameCount + HALF) * GHOST_BOB_SPEED);
}
// 006b1000 Its place in the draw order: the background and door layers by spawn order, the normal layer by depth.
int Entity::GetRenderZ()
{
int order = (int)(index & RENDER_INDEX_MASK) + renderZOffset;
if (sortingLayer == SORTING_BACKGROUND)
return std::max(0, std::min(order + RENDER_Z_BACKGROUND_BASE, RENDER_Z_BACKGROUND_MAX));
if (sortingLayer == SORTING_DOOR)
return std::max(RENDER_Z_DOOR_MIN, std::min(order + RENDER_Z_DOOR_BASE, RENDER_Z_DOOR_MAX));
if (g_game->room->roomType == ROOM_DUNGEON)
return std::max((int)RENDER_Z_NORMAL_MIN, order + RENDER_Z_DUNGEON_BASE);
return std::max((int)RENDER_Z_NORMAL_MIN, render_z_get(renderDepthOffset + pos.y) + renderZOffset);
}
// 006a8120 The draw order of a depth on the normal layer: its y position in hundredths, after the layers below.
int render_z_get(float depth)
{
float order = std::floor(depth * RENDER_Z_DEPTH_SCALE + RENDER_Z_DEPTH_BASE + HALF);
return (int)(uint32_t)std::max(order, RENDER_Z_NORMAL_MIN);
}
// 006b10d0 Whether EntityFactory may reuse it for a new entity when its pool is full.
bool Entity::CanOverwrite()
{
return !HasEntityFlags(FLAG_DONT_OVERWRITE);
}
// 006b10f0 Draws its sprite where it stands on screen, shifted by offset.
void Entity::Render(const Vector& offset)
{
if (!isExists || !isVisible) return;
renderPosition = vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset);
sprite.Render(SpriteDraw{renderPosition, {}, {}});
}
// 006b1260 Draws the debug overlays the console turns on.
void Entity::PostRender()
{
uint32_t debugFlags = g_game->debugFlags;
bool isPositionShown = (debugFlags & DEBUG_ENTITY_POSITIONS) && type != ENTITY_LASER;
bool isGridShown = (debugFlags & DEBUG_GRID_COLLISION) && entityGridCollisionClass != GRIDCOLL_NONE;
bool isHitsphereShown = (debugFlags & DEBUG_HITSPHERES) && size > 0 && entityCollisionClass != ENTCOLL_NONE;
if (isPositionShown || isGridShown || isHitsphereShown)
reconstruction_missing("Entity::PostRender 006b1260: the debug overlays");
}
// 006b2000 Draws only its sprite's shadow layer, uncolored, under it.
bool Entity::RenderShadowLayer(const Vector& offset)
{
Vector position = vector_add(render_position_get(vector_add(pos, shadowOffset), RENDER_SNAPPED), offset);
if (sprite.shadowLayerIndex == NO_SHADOW_LAYER) return false;
LayerState* shadow = sprite.GetLayer(sprite.shadowLayerIndex);
ColorMod saved = sprite.color;
shadow->isVisible = true;
sprite.color = COLOR_DEFAULT;
sprite.RenderLayer(sprite.shadowLayerIndex, SpriteDraw{position, {}, {}});
sprite.color = saved;
shadow->isVisible = false;
return true;
}
// 006b2fa0 Lays a color over it: for good without a duration, else timed by priority. A shared color spreads to
// the rest of its body.
void Entity::SetColor(const ColorMod& newColor, int duration, int priority, bool isFadeout, bool isShared)
{
if (duration < 1)
{
color = newColor;
ResetColor();
}
else
{
ColorParams params = {newColor, duration, priority, duration, isFadeout, isShared};
auto at = std::find_if(colorParams.begin(), colorParams.end(),
[priority](const ColorParams& other) { return other.priority >= priority; });
colorParams.insert(at, params);
sprite.color = colorParams.front().color;
}
if (DoesEntityShareStatus() && isShared && child)
child->SetColor(newColor, duration, priority, isFadeout, isShared);
}
// 005ccbe0
void Entity::SetCollisionDamage(float damage)
{
collisionDamage = damage;
}
// 006ac6e0 Shows its own color again.
void Entity::ResetColor()
{
sprite.color = color;
}
// 006b63b0 The way it faces: along its motion, or down while it is still.
Vector Entity::GetForwardVector()
{
float speedSquared = velocity.x * velocity.x + velocity.y * velocity.y;
if (speedSquared <= 0.01f) return vector_make(0, 1);
float length = vector_length(velocity);
return length > 0 ? vector_make(velocity.x * (1 / length), velocity.y * (1 / length)) : velocity;
}
// 006a8ee0 Whether it may target the other: not itself, its own body, or another ring of flies.
bool Entity::IsValidTarget(Entity* other)
{
if (other == this || is_same_segmented_body(other)) return false;
return type != ENTITY_RING_OF_FLIES || other->type != ENTITY_RING_OF_FLIES;
}
// 006acb00 Takes it out of the game: it stops existing and counts as dead, and Lua forgets it.
void Entity::Remove()
{
isExists = false;
isDead = true;
ReleaseLuaRef(this);
data_release();
}
// 006acb60 Unlinks it from every entity it points to and nulls every pointer to it, removing its magnet effect.
// An entity in a list also drops its colors, damage, collision points and sprite.
void Entity::ClearReferences()
{
parent = nullptr;
child = nullptr;
target = nullptr;
spawnerEntity = nullptr;
minecart = nullptr;
hitEffect = nullptr;
if (magnetizedEffect) magnetizedEffect->Remove();
magnetizedEffect = nullptr;
for (EntityPtr* referrer : referrers) referrer->forget();
referrers.clear();
if (!isValid) return;
colorParams.clear();
damageEvents.clear();
collisionPoints.clear();
sprite.Reset();
}
// 00866060 Runs MC_POST_ENTITY_REMOVE for it, which also lets Lua forget it.
void Entity::ReleaseLuaRef(Entity* entity)
{
lua_engine_get().PostEntityRemove(entity);
}
// 006b6af0 Where its sprite's null layer sits from its position, scaled, flipped and turned with the sprite, or zero
// while the null is hidden or missing.
Vector Entity::GetNullOffset(std::string_view nullLayerName)
{
if (!sprite.animState.animData) return {};
const NullFrame* frame = sprite.animState.GetNullFrame(nullLayerName);
if (!frame || !frame->isVisible) return {};
Vector offset = vector_make((frame->pos.x / ROOM_SCREEN_SCALE) * sprite.scale.x,
(frame->pos.y / ROOM_SCREEN_SCALE) * sprite.scale.y);
if (sprite.isFlipX) offset.x = -offset.x;
if (sprite.isFlipY) offset.y = -offset.y;
if (sprite.rotation == 0) return offset;
float angle = sprite.rotation * DEGREES_TO_RADIANS;
float cosine = std::cos(angle);
float sine = std::sin(angle);
return vector_make(cosine * offset.x - sine * offset.y, cosine * offset.y + sine * offset.x);
}
// 0085dcb0 Shows a frame of an animation, stopped.
void Entity::SetSpriteFrame(std::string_view animation, int frame)
{
if (!sprite.SetAnimation(animation, SWITCH_KEEP_FRAME) || !sprite.animState.animData) return;
sprite.animState.SetFrameFloat((float)frame);
if (sprite.animState.animData) sprite.animState.isPlaying = false;
}
// 0085dd00 Shows a frame of an overlay animation.
void Entity::SetSpriteOverlayFrame(std::string_view animation, int frame)
{
if (!sprite.SetOverlayAnimation(animation, SWITCH_KEEP_FRAME) || !sprite.overlayAnimState.animData) return;
sprite.overlayAnimState.SetFrameFloat((float)frame);
}
// The rest of Entity is not reconstructed yet.
// 006b5f10
void* Entity::GetDebugShape(bool)
{
reconstruction_missing("Entity::GetDebugShape 006b5f10");
}
// 006b6c20 The capsule its sprite's null layer covers: placed and turned like GetNullOffset, four times the null's
// scale wide and tall, or a point at its position while the null is hidden or missing.
void Entity::GetNullCapsule(Capsule& outCapsule, std::string_view nullLayerName)
{
constexpr float NULL_CAPSULE_SIZE = 4;
const NullFrame* frame = sprite.animState.animData ? sprite.animState.GetNullFrame(nullLayerName) : nullptr;
if (!frame || !frame->isVisible)
{
outCapsule = Capsule(pos, Vector{}, 0, 0);
return;
}
Vector offset = vector_make(frame->pos.x / ROOM_SCREEN_SCALE * sprite.scale.x, frame->pos.y / ROOM_SCREEN_SCALE * sprite.scale.y);
Vector size = vector_make(frame->scale.x * NULL_CAPSULE_SIZE / ROOM_SCREEN_SCALE * sprite.scale.x,
frame->scale.y * NULL_CAPSULE_SIZE / ROOM_SCREEN_SCALE * sprite.scale.y);
float rotation = frame->rotation;
if (sprite.isFlipX) size.x = -size.x;
if (sprite.isFlipY) size.y = -size.y;
if (size.x < 0)
{
size.x = -size.x;
rotation = 180 - rotation;
offset.x = -offset.x;
}
if (size.y < 0)
{
size.y = -size.y;
offset.y = -offset.y;
rotation = -rotation;
}
if (sprite.rotation != 0)
{
float angle = sprite.rotation * DEGREES_TO_RADIANS;
rotation += sprite.rotation;
offset = vector_make(std::cos(angle) * offset.x - std::sin(angle) * offset.y,
std::cos(angle) * offset.y + std::sin(angle) * offset.x);
}
outCapsule = Capsule(vector_add(offset, pos), size, rotation, 1);
}
// 007079c0 Removes an entity in a pink poof, a boss's death counting for the room. Dogma stays.
void Entity::RemoveWithPoof(Entity* entity)
{
constexpr ColorMod POOF_COLOR = {{1, 0.6f, 0.9f, 1}, {0, 0, 0, 0}, {0.2f, 0.15f, 0.18f}};
if (entity->type == ENTITY_DOGMA) return;
Entity* poof =
g_game->Spawn({.position = entity->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()});
poof->SetColor(POOF_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true);
poof->Update();
bool isBossDeath = is_enemy_type(entity->type) && entity->IsBoss();
if (isBossDeath) g_game->room->TriggerBossDeath(*static_cast<Entity_NPC*>(entity));
entity->Remove();
}