Files
isaac-port/src/entity.cpp
T
shweetandClaude Opus 5.5 d8385e6c64 Curation round 10: combat, pathfinding, death and game over, items and stats, room state, Continue, Lua callbacks
Seven agents took over tear and contact collision, NPC death with blood and gibs, champions, PathFinder, the Gaper's
kin, the player's death with the game over screen, item pedestals with collectible pickup, AddCollectible and
EvaluateItems, room state save and restore, GameState::read, pressure plates, fireplaces, entity lights, ambient
sounds, and one Lua callback enum with gated runners. Integration reconstructed Room::Update's loot preview and
Entity_NPC::UpdatePickupGhosts and replaced a leftover Sacred Orb stub that stopped every pedestal roll.
Under gdb: Gapers die with blood and gibs, a cleared room opens its doors, the treasure room's item is taken (banner,
costume, stats: a Magic Mushroom gives damage 3.5 -> 6.12 and a heart), death leads to the game over diary, and a saved
run is read back on the next boot with Continue offered. 3028 functions taken over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 09:55:14 -05:00

1424 lines
50 KiB
C++

#include "entity.h"
#include "entity_effect.h"
#include "entity_list.h"
#include "entity_npc.h"
#include "entity_player.h"
#include "entity_tear.h"
#include "game.h"
#include "log.h"
#include "lua_engine.h"
#include "manager.h"
#include "room.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
// The room's play area on screen: world units from its corner shrink by ROOM_SCREEN_SCALE into a centered view.
constexpr float ROOM_ORIGIN_X = 60;
constexpr float ROOM_ORIGIN_Y = 140;
constexpr float ROOM_SCREEN_SCALE = 0.65f;
constexpr float ROOM_VIEW_HEIGHT = 182;
constexpr float ROOM_VIEW_WIDTH = 338;
constexpr float HALF = 0.5f;
constexpr float DEGREES_TO_RADIANS = 0.017453292f;
// 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: status tick damage, slowing, the shadow without a config, and the
// update clock's start just before zero.
constexpr float STATUS_TICK_DAMAGE_DEFAULT = 2;
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;
constexpr float PI_FLOAT = 3.1415927f;
// 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_PRIORITY = 255;
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 int SOUND_FIREDEATH_HISS = 43;
constexpr float POSITION_LIMIT = 10000;
// The debug flags PostRender draws for: entity positions, collision shapes and grid collision points.
constexpr uint32_t DEBUG_ENTITY_POSITIONS = 1 << 0;
constexpr uint32_t DEBUG_HITSPHERES = 1 << 5;
constexpr uint32_t DEBUG_DAMAGE_VALUES = 1 << 6;
constexpr uint32_t DEBUG_GRID_COLLISION = 1 << 12;
// The flags an EntityRef's status flags come from, and those CopyStatusEffects hands a segment.
constexpr uint64_t SHARED_STATUS_FLAGS = FLAG_FREEZE | FLAG_POISON | FLAG_SLOW | FLAG_CHARM | FLAG_CONFUSION |
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);
}
static float vector_length(Vector v)
{
return std::sqrt(v.x * v.x + v.y * v.y);
}
static Vector vector_add(Vector a, Vector b)
{
return vector_make(a.x + b.x, a.y + b.y);
}
// 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_FLOAT) / (float)gridCollisionPoints;
collisionPoints.push_back(vector_make((float)std::cos(angle) * size * sizeMulti.x,
(float)std::sin(angle) * size * sizeMulti.y));
}
}
}
// 006a9ba0
void Entity::GetCollisionCapsule(Capsule&, const Vector&)
{
reconstruction_missing("Entity::GetCollisionCapsule 006a9ba0");
}
// 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
float Entity::GetRootParent()
{
reconstruction_missing("Entity::GetRootParent 0067a720");
}
// 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;
}
}
// 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;
}
// 006ac7e0
int Entity::CountRelatedEntities(int, int, std::vector<Entity*>*)
{
reconstruction_missing("Entity::CountRelatedEntities 006ac7e0");
}
// 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
bool Entity::is_valid_target()
{
reconstruction_missing("Entity::is_valid_target 006d8990");
}
// 006a8f80 Whether its config lists anything it can devolve into.
bool Entity::CanDevolve()
{
return config && !config->devolve.empty();
}
// 006b9740
bool Entity::IsPlayerInRadius(const Vector&, float)
{
reconstruction_missing("Entity::IsPlayerInRadius 006b9740");
}
// 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();
}
// 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 = config->baseHP;
if (STAGE_HP_MIN < config->stageHP)
{
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;
maxHitPoints = stage * scale * config->stageHP + config->baseHP;
}
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)
reconstruction_missing("Entity::Update 006ae820: the water ripples it leaves (get_water_splash_variant)");
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 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))
reconstruction_missing("Entity::Update 006ae820: the damage a knocked back entity takes hitting a wall");
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, then bleeds it and pulls it in when magnetized.
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))
reconstruction_missing("Entity::Update 006ae820: the bleeding of Mom's Razor and the creep it leaves");
}
if (!isDead && HasEntityFlags(FLAG_MAGNETIZED))
reconstruction_missing("Entity::Update 006ae820: the pull of a magnetized entity");
}
// 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.
// 0060af70
Entity* Entity::AddFear(int, int, int)
{
reconstruction_missing("Entity::AddFear 0060af70");
}
// 0064bb70
void Entity::convert_shot_for_enemy_owner(Entity*)
{
reconstruction_missing("Entity::convert_shot_for_enemy_owner 0064bb70");
}
// 006ad350
int Entity::apply_second_hand_duration(int, const EntityRef&)
{
reconstruction_missing("Entity::apply_second_hand_duration 006ad350");
}
// 006ad3c0
void Entity::AddFreeze(const EntityRef&, int, bool)
{
reconstruction_missing("Entity::AddFreeze 006ad3c0");
}
// 006ad500
void Entity::AddPoison(const EntityRef&, int, float, bool)
{
reconstruction_missing("Entity::AddPoison 006ad500");
}
// 006ad750
void Entity::AddSlowing(const EntityRef&, int, float, ColorMod, bool)
{
reconstruction_missing("Entity::AddSlowing 006ad750");
}
// 006ad870
void Entity::AddCharmed(const EntityRef&, int, bool, bool)
{
reconstruction_missing("Entity::AddCharmed 006ad870");
}
// 006add70
void Entity::AddConfusion(const EntityRef&, int, bool)
{
reconstruction_missing("Entity::AddConfusion 006add70");
}
// 006adf40
void Entity::AddMidasFreeze(const EntityRef&, int, bool)
{
reconstruction_missing("Entity::AddMidasFreeze 006adf40");
}
// 006ae0a0
void Entity::AddFear(const EntityRef&, int, bool)
{
reconstruction_missing("Entity::AddFear 006ae0a0");
}
// 006ae280
void Entity::AddBurn(const EntityRef&, int, float, bool)
{
reconstruction_missing("Entity::AddBurn 006ae280");
}
// 006ae420
void Entity::AddBleeding(const EntityRef&, int)
{
reconstruction_missing("Entity::AddBleeding 006ae420");
}
// 006ae630
void Entity::RemoveStatusEffects()
{
reconstruction_missing("Entity::RemoveStatusEffects 006ae630");
}
// 006b5c10
void Entity::AddShrink(const EntityRef&, int, bool)
{
reconstruction_missing("Entity::AddShrink 006b5c10");
}
// 006b5e60
void* Entity::GetData(void*)
{
reconstruction_missing("Entity::GetData 006b5e60");
}
// 006b5f10
void* Entity::GetDebugShape(bool)
{
reconstruction_missing("Entity::GetDebugShape 006b5f10");
}
// 006b6550
Entity_Effect* Entity::MakeGroundPoof(const Vector&, const ColorMod&, float)
{
reconstruction_missing("Entity::MakeGroundPoof 006b6550");
}
// 006b66a0
Entity_Effect* Entity::MakeGroundPoofAtSelf(const ColorMod&, float)
{
reconstruction_missing("Entity::MakeGroundPoofAtSelf 006b66a0");
}
// 006b66c0
Entity_Effect* Entity::MakeBloodPoof(const Vector&, const ColorMod&, float)
{
reconstruction_missing("Entity::MakeBloodPoof 006b66c0");
}
// 006b6810
Entity_Effect* Entity::MakeBloodPoofAtPos(const ColorMod&, float)
{
reconstruction_missing("Entity::MakeBloodPoofAtPos 006b6810");
}
// 006b6c20
void Entity::GetNullCapsule(Capsule&, std::string_view)
{
reconstruction_missing("Entity::GetNullCapsule 006b6c20");
}
// 006b6ed0
int Entity::get_water_splash_variant()
{
reconstruction_missing("Entity::get_water_splash_variant 006b6ed0");
}
// 006b7280
void Entity::AddMagnetized(const EntityRef&, int)
{
reconstruction_missing("Entity::AddMagnetized 006b7280");
}
// 006b7560
void Entity::AddBaited(const EntityRef&, int)
{
reconstruction_missing("Entity::AddBaited 006b7560");
}
// 006b77d0
void Entity::AddWeakness(const EntityRef&, int)
{
reconstruction_missing("Entity::AddWeakness 006b77d0");
}
// 006b78d0
void Entity::AddBrimstoneMark(const EntityRef&, int)
{
reconstruction_missing("Entity::AddBrimstoneMark 006b78d0");
}
// 006b79d0
void Entity::AddIce(const EntityRef&, int)
{
reconstruction_missing("Entity::AddIce 006b79d0");
}
// 006b7be0
Entity_NPC* Entity::GiveMinecart(const Vector&, const Vector&)
{
reconstruction_missing("Entity::GiveMinecart 006b7be0");
}
// 007079c0
void Entity::RemoveWithPoof(Entity*)
{
reconstruction_missing("Entity::RemoveWithPoof 007079c0");
}
// 0070c000
void Entity::DestroyRockGridAt(const Vector&, GridEntityDesc*, Entity*, int)
{
reconstruction_missing("Entity::DestroyRockGridAt 0070c000");
}
// 0085e680
int Entity::IsVulnerableEnemy_lua(lua_State*)
{
reconstruction_missing("Entity::IsVulnerableEnemy_lua 0085e680");
}
// 008c5cf2
void Entity::KillWithSource()
{
reconstruction_missing("Entity::KillWithSource 008c5cf2");
}