Files
isaac-port/src/entity_laser.cpp
T

1562 lines
64 KiB
C++

#include "entity_laser.h"
#include "boss_ai.h"
#include "entity_effect.h"
#include "entity_factory.h"
#include "entity_familiar.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 "npc_ai.h"
#include "npc_basement.h"
#include "room.h"
#include "room_config.h"
#include "sfx_manager.h"
#include <algorithm>
#include <cmath>
constexpr float THIN_SCALE_THRESHOLDS[] = {1.15f, 2.2f, 4.2f};
constexpr float THIN_SCALE_DIVISORS[] = {1, 2, 4, 6};
constexpr float BEAM_REACH = 1200;
constexpr float BEAM_FAR = 10000;
constexpr float BEAM_UNBLOCKED = 1000;
constexpr float BEAM_BACKSTEP = 4;
constexpr float BEAM_MARGIN = 20;
constexpr float BEAM_MARGIN_CONTINUUM = 140;
constexpr float BEAM_MARGIN_OCCULT = 100;
constexpr float BEAM_GIANT_EXTRA = 100;
constexpr float BEAM_GIANT_MINIMUM = 88;
constexpr float BEAM_START_NUDGE = 0.1f;
constexpr float BEAM_GIANT_TIP_GAP = 50;
constexpr float PRIDE_LENGTH = 300;
constexpr float RING_RADIUS = 80;
constexpr float AXIS_SNAP = 0.0001f;
constexpr float SPRITE_ROTATION_OFFSET = 90;
constexpr float ANGLE_FULL_TURN = 360;
constexpr float ANGLE_HALF_TURN = 180;
constexpr float ROTATION_STEP_SCALE = 0.5f;
constexpr float SCALE_SMALL = 0.75f;
constexpr float SCALE_LARGE = 1.45f;
constexpr float ZAP_PITCH_MIN = 0.85f;
constexpr float ZAP_VOLUME_WEAK = 0.5f;
constexpr float RING_VOLUME_WEAK = 0.85f;
constexpr float ZAP_VOLUME_STRONG = 1.1f;
constexpr float ZAP_PITCH_RANGE = 0.3f;
constexpr float ELECTRIC_PITCH_MIN = 0.9f;
constexpr float ELECTRIC_PITCH_RANGE = 0.2f;
constexpr float ELECTRIC_VOLUME = 0.6f;
constexpr float RING_SOUND_VOLUME = 0.6f;
constexpr float OWNER_ZAP_VOLUME = 0.9f;
constexpr float BABY_ZAP_VOLUME = 0.4f;
constexpr float SHRINK_RATE = 0.895f;
constexpr int SHRINK_TIMEOUT_END = -19;
constexpr int SHAKE_GIANT = 4;
constexpr int SHAKE_STRONG = 10;
constexpr int LASER_WAIT_FRAMES = 2;
constexpr float WAIT_SCALE_THICKER = 2;
constexpr float WAIT_SCALE_GIANT = 3;
constexpr float WAIT_SCALE_BEAST = 5;
constexpr float RAINBOW_FRAMES = 30;
constexpr float RAINBOW_SATURATION = 0.9f;
constexpr float RAINBOW_STRENGTH = 4;
constexpr int CONTINUUM_PHASES = 8;
constexpr float CONTINUUM_COLORIZE = 2.5f;
constexpr float CONTINUUM_GREEN_STEP = 0.625f;
constexpr float IMPACT_DEPTH = 5;
constexpr float IMPACT_DEPTH_FOLLOW = -5;
constexpr float IMPACT_SCALE_MIN = 0.04f;
constexpr float IMPACT_SCALE_KEPT = 0.75f;
constexpr float IMPACT_SCALE_BASE = 0.25f;
constexpr float IMPACT_SCALE_GIANT = 1.5f;
constexpr float TEAR_TINT_RED = 0.85f;
constexpr float TEAR_TINT_GREEN = 0.9f;
constexpr float TEAR_COLOR_HALF = 0.5f;
constexpr float LUMINANCE_RED = 0.212671f;
constexpr float LUMINANCE_GREEN = 0.71516f;
constexpr float LUMINANCE_BLUE = 0.072169f;
constexpr float L_ROOM_ARM_WIDTH = 520;
constexpr float L_ROOM_ARM_HEIGHT = 280;
constexpr float GRID_HIT_OFFSET_SCALE = 0.4f;
constexpr float VERSUS_RING_DAMAGE = 0.5f;
constexpr int SPAWNER_CAGE = 265;
constexpr int SPAWNER_FORSAKEN = 403;
constexpr int SPAWNER_MEGA_SATAN = 274;
constexpr int SPAWNER_DOGMA = 950;
constexpr int SPAWNER_MOMS_HEART_LASER = 49;
constexpr int SPAWNER_EYE = 60;
constexpr int SPAWNER_PIN = 62;
constexpr int SPAWNER_VIS = 39;
constexpr int SPAWNER_PEEP = 68;
constexpr int SPAWNER_BABY = 201;
constexpr int SPAWNER_PATH_KEEPER_1 = 263;
constexpr int SPAWNER_PATH_KEEPER_2 = 268;
constexpr int SPAWNER_PATH_KEEPER_3 = 410;
constexpr int SPAWNER_RING_KEEPER = 260;
constexpr int EFFECT_SAMPLE_PARENT = 178;
constexpr int FAMILIAR_ANGELIC_PRISM = 123;
constexpr int WISP_DAMAGED_SUBTYPE = 427;
constexpr int EFFECT_LASER_MIRROR = 188;
constexpr int IMPACT_SUBTYPE_THIN = 0;
constexpr int IMPACT_SUBTYPE_THICK = 1;
constexpr int IMPACT_SUBTYPE_SHOOP = 2;
constexpr int IMPACT_SUBTYPE_CAGE = 3;
constexpr int IMPACT_SUBTYPE_RING = 5;
constexpr int IMPACT_SUBTYPE_GIANT = 6;
constexpr int IMPACT_SUBTYPE_BROWN = 7;
constexpr int IMPACT_SUBTYPE_GIANT_END = 4;
constexpr const char* STATIC_LASER_ANM2 = "gfx/007.001_Static Laser.anm2";
constexpr const char* CAGE_VIS_LASER_ANM2 = "gfx/007.006_CageVisLaser.anm2";
constexpr const char* STATIC_IMPACT_ANM2 = "gfx/1000.050_brimstoneimpact_static.anm2";
// Whether a tear flag set has any of some bits.
bool tear_flags_any(const TearFlags& flags, std::initializer_list<int> bits)
{
return std::any_of(bits.begin(), bits.end(), [&](int bit) { return flags[(size_t)bit]; });
}
// A random fraction of one as the game draws it.
static float random_fraction()
{
return random_unit();
}
// A colorize from a hue in degrees, a saturation and a value at a strength (hsv_to_rgb).
static ColorMod colorize_from_hue(float hue, float saturation, float value, float strength)
{
KColor color = hsv_to_rgb(hue, saturation, value, 1);
return {{1, 1, 1, 1}, {color._red * strength, color._green * strength, color._blue * strength, 1}, {0, 0, 0}};
}
// The player a laser's tears come from: its spawner, or the player of a familiar that fires the player's lasers.
static Entity_Player* laser_owner_player(Entity* spawner)
{
if (!spawner) return nullptr;
if (spawner->type == ENTITY_PLAYER) return spawner->ToPlayer();
if (spawner->type != ENTITY_FAMILIAR) return nullptr;
int familiar = spawner->variant;
bool isFiring = familiar == Entity_Familiar::INCUBUS || familiar == Entity_Familiar::TWISTED_BABY ||
familiar == Entity_Familiar::UMBILICAL_BABY || familiar == Entity_Familiar::BLOOD_BABY;
return isFiring ? static_cast<Entity_Familiar*>(spawner)->player : nullptr;
}
// Plays a sound through the fart seeds.
static void laser_sound_play(int sound, SoundPlay play)
{
seed_fart_sound_override(&sound);
g_manager->sfxManager.Play(sound, play);
}
// A color's tint, colorize and offset applied to a KColor, as Color::apply_to_kcolor does.
static KColor color_apply(const ColorMod& color, const KColor& input)
{
float red = color._tint[0] * input._red;
float green = color._tint[1] * input._green;
float blue = color._tint[2] * input._blue;
if (color._colorize[3] != 0)
{
float luminance = green * LUMINANCE_GREEN + red * LUMINANCE_RED + blue * LUMINANCE_BLUE;
red += (luminance * color._colorize[0] - red) * color._colorize[3];
green += (luminance * color._colorize[1] - green) * color._colorize[3];
blue += (luminance * color._colorize[2] - blue) * color._colorize[3];
}
return kcolor_rgba(red + color._offset[0], green + color._offset[1], blue + color._offset[2],
color._tint[3] * input._alpha);
}
// 006827a0 The shortest signed turn from one angle to another, in degrees.
float angle_difference(float from, float to)
{
from = angle_wrap(from);
to = angle_wrap(to);
if (std::abs(to - from) > ANGLE_HALF_TURN)
{
if (from < to) return to - (from + ANGLE_FULL_TURN);
to += ANGLE_FULL_TURN;
}
return to - from;
}
// 0096cb60 Points the laser's path at it.
Entity_Laser::Entity_Laser()
{
homingLaser.owner = this;
}
// 0096ced0 Sorts by its depth, ignoring the sorting layer.
int Entity_Laser::GetRenderZ()
{
return render_z_get(renderDepthOffset + pos.y);
}
// 0097e7a0 Whether EntityFactory may reuse it: never before its first update.
bool Entity_Laser::CanOverwrite()
{
return !HasEntityFlags(FLAG_DONT_OVERWRITE) && !isFirstUpdate;
}
// 005ccc20 Collides with nothing it reacts to, letting the collision through.
bool Entity_Laser::HandleCollision(Entity*, bool)
{
return true;
}
// 00435f50 Whether it is a ring laser (Tech X and the like).
bool Entity_Laser::IsCircleLaser()
{
return subtype >= LASER_SUBTYPE_RING_LUDOVICO && subtype <= LASER_SUBTYPE_RING_FOLLOW_PARENT;
}
// 0096ce30 Whether it is one of the thick beams (Brimstone's and the bosses').
bool Entity_Laser::is_thick_variant()
{
switch (variant)
{
case LASER_THICK_RED:
case LASER_SHOOP:
case LASER_GIANT_RED:
case LASER_BRIM_TECH:
case LASER_THICKER_RED:
case LASER_THICK_BROWN:
case LASER_BEAST:
case LASER_THICKER_BRIM_TECH:
case LASER_GIANT_BRIM_TECH:
return true;
default:
return false;
}
}
// The first laser of the chain this one was split from.
Entity_Laser* Entity_Laser::root_laser_get()
{
Entity_Laser* root = this;
while (root->parentLaser) root = static_cast<Entity_Laser*>(root->parentLaser.get());
return root;
}
// 0096ce70 The hit list the laser shares with the chain it was split from: its first laser's.
std::vector<uint32_t>& Entity_Laser::hit_list_get()
{
return root_laser_get()->hitList;
}
// 0096cf40 Whether the laser is the players': its parent is a player, a familiar or one of their tears or effects,
// or it was spawned by one.
bool Entity_Laser::is_players_laser()
{
Entity* owner = parent;
if (owner)
{
bool isShot = owner->type == ENTITY_TEAR || owner->type == ENTITY_EFFECT;
if (isShot && owner->spawnerType == ENTITY_PLAYER) return true;
if (owner->type == ENTITY_PLAYER || owner->type == ENTITY_FAMILIAR) return true;
}
return spawnerType == ENTITY_PLAYER || spawnerType == ENTITY_FAMILIAR;
}
// 0096cf80 Whether the laser may hurt an entity this frame: a live one that collides and has health (or a familiar
// lasers hurt), not its parent, not of its parent's kind outside a versus match, and not hit yet. The players'
// lasers hurt enemies that are not friendly and the fireplaces, poops and movable TNT. The others hurt players,
// enemies and those familiars.
bool Entity_Laser::CanDamageEntity(Entity* entity)
{
if (entity->type == ENTITY_SHOPKEEPER) return false;
Entity* owner = parent;
int parentType = owner ? owner->type : 0;
bool isCharmedParent = owner && owner->HasEntityFlags(FLAG_CHARM);
bool isVersus = g_game->deathmatchManager.is_active();
bool isDamagedFamiliar =
entity->type == ENTITY_FAMILIAR &&
(entity->variant == Entity_Familiar::ISAACS_HEART || entity->variant == Entity_Familiar::PUNCHING_BAG ||
entity->variant == Entity_Familiar::LOST_SOUL || entity->variant == Entity_Familiar::MILK ||
(entity->variant == Entity_Familiar::WISP && entity->subtype == WISP_DAMAGED_SUBTYPE));
bool isHittable =
entity != owner && !entity->isDead && entity->entityCollisionClass != ENTCOLL_NONE && entity->maxHitPoints > 0;
bool isOtherKind = (parentType == ENTITY_PLAYER && isVersus) || parentType != entity->type || isCharmedParent;
if (!(isHittable || isDamagedFamiliar) || !isOtherKind) return false;
if (EntityList::HitListContains(hit_list_get(), *entity)) return false;
bool isPlayers = is_players_laser() && !(parentType == ENTITY_FAMILIAR && isCharmedParent);
bool isEnemy = entity->IsEnemy();
bool isTarget = isEnemy || (isVersus && entity->type == ENTITY_PLAYER);
if (!isPlayers) return entity->type == ENTITY_PLAYER || isEnemy || isDamagedFamiliar;
if (isTarget && !entity->HasEntityFlags(FLAG_FRIENDLY)) return true;
bool isBreakable =
entity->type == ENTITY_FIREPLACE || entity->type == ENTITY_MOVABLE_TNT || entity->type == ENTITY_POOP;
return entity->entityCollisionClass != ENTCOLL_NONE && isBreakable;
}
// 0096f310 Spawns a laser of a variant at an angle from a position, with its timeout and offset. A source becomes
// its spawner and parent, which it keeps its offset from.
Entity_Laser* Entity_Laser::ShootAngle(const LaserShot& shot)
{
uint32_t seed = Random();
Entity* entity = game_spawn({.position = shot.position,
.spawner = shot.source,
.type = ENTITY_LASER,
.variant = shot.variant,
.seed = seed},
shot.isPoolKept ? POOL_KEEP : POOL_OVERWRITE);
if (!entity) return nullptr;
Entity_Laser* laser = static_cast<Entity_Laser*>(entity);
laser->angleDegrees = shot.angleDegrees;
laser->startAngleDegrees = shot.angleDegrees;
laser->timeout = shot.timeout;
laser->posOffset = shot.posOffset;
if (shot.source)
{
laser->spawnerEntity = shot.source;
laser->parent = shot.source;
laser->parentOffset = vector_sub(laser->pos, shot.source->pos);
}
return laser;
}
// 0096f420 Turns the laser by an angle at a speed after a delay, its timeout lasting the turn when asked.
void Entity_Laser::SetActiveRotation(int delay, float angle, float speed, bool isTimeoutComplete)
{
isActiveRotating = true;
rotationDelay = (uint32_t)delay;
rotationDegrees = angle;
rotationSpd = speed;
if (isTimeoutComplete) timeout = (int)(uint32_t)(angle / speed) + 1 + delay;
}
// 0096f470 Turns the laser toward an angle at a speed, the short way round.
void Entity_Laser::RotateToAngle(float angle, float speed)
{
isActiveRotating = true;
rotationDelay = 0;
rotationDegrees = angle_difference(angleDegrees, angle);
rotationSpd = rotationDegrees < 0 ? -speed : speed;
}
// Points the beam at an angle, keeping the angle it had. The original's 0096ce90, which the database names
// Entity_NPC::SetAimAngle.
void Entity_Laser::set_aim_angle(float angle)
{
lastAngleDegrees = angleDegrees;
startAngleDegrees = angle;
angleDegrees = angle;
sprite.rotation = angle - SPRITE_ROTATION_OFFSET;
}
// 0096f4e0 Forgets the path, and sets it up again for a ring (which ignores the grid) or a line, or a homing one.
void Entity_Laser::ClearLaserSamples()
{
homingLaser.bezier.clear();
homingLaser.samples.clear();
homingLaser.smoothedSamples.clear();
homingLaser.nonOptimizedSamples.clear();
homingLaser.isRing = IsCircleLaser();
if (homingLaser.isRing) entityGridCollisionClass = GRIDCOLL_NONE;
homingLaser.sampleNum = HOMING_LASER_SAMPLES;
homingLaser.reach = homingLaser.isRing ? HOMING_LASER_RING_REACH : HOMING_LASER_REACH;
if (homingType == LASER_HOMING_FREEZE) homingLaser.reach = HOMING_LASER_HOMING_REACH;
}
// 0096f590 Starts the laser: its sprite on its default animation, and every setting back to a plain beam.
void Entity_Laser::Init(int initType, int initVariant, int initSubType, uint32_t seed)
{
Entity::Init(initType, initVariant, initSubType, seed);
if (config)
{
sprite.Load(config->anm2Path, GRAPHICS_LOAD);
sprite.Play(sprite.GetDefaultAnimationName());
}
isPlayerParams = false;
isDisableInitSound = false;
damageMultiplier = 1;
waitFrames = 0;
parentOffset = {};
scale = 1;
angleDegrees = 0;
startAngleDegrees = 0;
lastAngleDegrees = 0;
renderDepthOffset = 0;
tearFlags.reset();
activeTearFlags.reset();
heldTearFlags.reset();
multidimensionalLasers = {};
timeout = 0;
isFirstUpdate = true;
sampleMode = SAMPLE_UNDECIDED;
isSampleLaser = false;
entityGridCollisionClass = GRIDCOLL_WALLS;
laserLength = 0;
curveStrength = 0;
isShrink = false;
isActiveRotating = false;
homingType = 0;
maxDistance = 0;
radius = RING_RADIUS;
isDisableFollowParent = false;
bounceLaser = nullptr;
isMultidimensionalTouched = false;
isPrismTouched = false;
isOneHit = false;
childLaser = nullptr;
prismLasers = {};
hitList.clear();
homingLaser.bezier.clear();
homingLaser.samples.clear();
homingLaser.smoothedSamples.clear();
homingLaser.nonOptimizedSamples.clear();
blackHpDropChance = 0;
impactDistance = INFINITY;
subLaserDistance = INFINITY;
subLaserAngle = 0;
chainedLasers = 0;
lua_engine_get().PostLaserInit(this);
}
// 0096f880 Plays the sound the beam starts with, unless it is quiet, split from another laser or hidden. A beam's
// sound grows with its scale, and some bosses' beams have their own.
void Entity_Laser::PlayInitSound()
{
if (isDisableInitSound || (parent && parent->type == ENTITY_LASER) || !isVisible) return;
int spawner = spawnerEntity ? spawnerEntity->type : 0;
bool isSmall = scale < SCALE_SMALL;
switch (variant)
{
case LASER_THICK_RED:
case LASER_LIGHT_RING:
case LASER_BRIM_TECH:
if (!spawnerEntity) return laser_sound_play(SOUND_BLOOD_LASER, {});
if (spawner == SPAWNER_EYE) return laser_sound_play(SOUND_REDLIGHTNING_ZAP_STRONG, {});
if (spawner == ENTITY_MONSTRO2 || spawner == SPAWNER_MOMS_HEART_LASER)
return laser_sound_play(SOUND_BLOOD_LASER_LARGE, {});
if (spawner == ENTITY_SATAN) return laser_sound_play(SOUND_SATAN_HAND_LASER, {});
if (spawner == SPAWNER_FORSAKEN) return laser_sound_play(SOUND_FORSAKEN_LASER, {.loop = SOUND_LOOP});
if (subtype == LASER_SUBTYPE_LINEAR)
return npc_sound_play(isSmall ? SOUND_BLOOD_LASER_SMALL : SOUND_BLOOD_LASER, 1, 2, 1);
if (subtype == LASER_SUBTYPE_RING_PROJECTILE)
{
npc_sound_play(isSmall ? SOUND_BLOOD_LASER_SMALL : SOUND_BLOOD_LASER, RING_SOUND_VOLUME, 2, 1);
npc_sound_play(isSmall ? SOUND_LASERRING : SOUND_LASERRING_STRONG, 1, 2, 1);
}
return;
case LASER_THIN_RED:
{
float pitch = random_fraction() * ZAP_PITCH_RANGE + ZAP_PITCH_MIN;
bool isRing = subtype == LASER_SUBTYPE_RING_PROJECTILE;
int sound = isRing ? SOUND_LASERRING : SOUND_REDLIGHTNING_ZAP;
float volume = 1;
if (scale < SCALE_SMALL)
{
sound = isRing ? SOUND_LASERRING_WEAK : SOUND_REDLIGHTNING_ZAP_WEAK;
volume = isRing ? RING_VOLUME_WEAK : ZAP_VOLUME_WEAK;
}
else if (scale > SCALE_LARGE)
{
sound = isRing ? SOUND_LASERRING_STRONG : SOUND_REDLIGHTNING_ZAP_STRONG;
volume = ZAP_VOLUME_STRONG;
}
if (spawner == ENTITY_PLAYER || spawner == ENTITY_FAMILIAR)
volume *= OWNER_ZAP_VOLUME;
else if (spawner == SPAWNER_BABY)
volume *= BABY_ZAP_VOLUME;
return npc_sound_play(sound, volume, 1, pitch);
}
case LASER_SHOOP:
return laser_sound_play(SOUND_BLOOD_LASER, {});
case LASER_LIGHT_BEAM:
return laser_sound_play(SOUND_ANGEL_BEAM, {});
case LASER_GIANT_RED:
case LASER_GIANT_BRIM_TECH:
return laser_sound_play(SOUND_MEGA_BLAST_START, {});
case LASER_ELECTRIC:
return npc_sound_play(SOUND_REDLIGHTNING_ZAP_WEAK, ELECTRIC_VOLUME, 2,
random_fraction() * ELECTRIC_PITCH_RANGE + ELECTRIC_PITCH_MIN);
case LASER_THICKER_RED:
case LASER_THICKER_BRIM_TECH:
if (subtype == LASER_SUBTYPE_RING_PROJECTILE)
{
laser_sound_play(SOUND_BLOOD_LASER_LARGER, {.volume = RING_SOUND_VOLUME});
return laser_sound_play(SOUND_LASERRING_STRONG, {});
}
if (subtype != LASER_SUBTYPE_RING_LUDOVICO) laser_sound_play(SOUND_BLOOD_LASER_LARGER, {});
return;
case LASER_THICK_BROWN:
return laser_sound_play(SOUND_POOP_LASER, {});
default:
return;
}
}
// 0097fc10 Sizes the sprite and collision to the laser's scale. A thin beam picks its thickness animation for the
// scale and draws it at the remaining part, starting on a frame from its seed.
void Entity_Laser::ResetSpriteScale()
{
size = scale * config->collisionRadius;
if (variant != LASER_THIN_RED)
{
sprite.scale = vector_make(scale, scale);
return;
}
int thickness = 0;
while (thickness < 3 && scale >= THIN_SCALE_THRESHOLDS[thickness]) thickness++;
std::string animation = "Laser" + std::to_string(thickness);
float divisor = THIN_SCALE_DIVISORS[thickness];
sprite.scale = vector_make(scale / divisor, scale / divisor);
if (sprite.animState.animData && sprite.animState.isPlaying && sprite.GetAnimation() == animation) return;
sprite.Play(animation);
uint32_t seed = initSeed;
if (seed == 0)
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"RNG Seed is zero!\n");
return;
}
seed ^= seed >> 4;
seed ^= seed << 3;
seed ^= seed >> 27;
int length = sprite.animState.GetAnimationLength();
if (sprite.animState.animData) sprite.animState.SetFrameFloat((float)(length == 0 ? 0 : seed % (uint32_t)length));
}
// 0097fe50 Sets the laser's scale and sizes it to it.
void Entity_Laser::set_scale(float newScale)
{
scale = newScale;
ResetSpriteScale();
}
// 0096ee00 The color a tear the laser fires takes: half its color's brightness as colorize and offset, from its
// own color for the shoop and electric beams, a red tint of it for a thin beam, a reddened one otherwise.
ColorMod Entity_Laser::CalculateTearColor()
{
const ColorMod& color = sprite.color;
float red = 0;
float green = 0;
float blue = 0;
float alpha = 0;
if (variant == LASER_SHOOP || variant == LASER_ELECTRIC)
{
red = color._tint[0] * TEAR_TINT_RED;
green = color._tint[1] * TEAR_TINT_GREEN;
blue = color._tint[2];
alpha = color._tint[3];
if (color._colorize[3] != 0)
{
float luminance = red * LUMINANCE_RED + green * LUMINANCE_GREEN + blue * LUMINANCE_BLUE;
red += (luminance * color._colorize[0] - red) * color._colorize[3];
green += (luminance * color._colorize[1] - green) * color._colorize[3];
blue += (luminance * color._colorize[2] - blue) * color._colorize[3];
}
red += color._offset[0];
green += color._offset[1];
blue += color._offset[2];
}
else
{
ColorMod tinted = color;
KColor multiplier = kcolor_rgba(TEAR_TINT_RED, TEAR_TINT_GREEN, 1, 1);
if (variant == LASER_THIN_RED)
multiplier = kcolor_rgba(1, 0, 0, 1);
else
color_multiply(tinted, {{1, 0, 0, 1}, {0, 0, 0, 0}, {0, 0, 0}});
KColor result = color_apply(tinted, multiplier);
red = result._red;
green = result._green;
blue = result._blue;
alpha = result._alpha;
}
float halfRed = red * TEAR_COLOR_HALF;
float halfGreen = green * TEAR_COLOR_HALF;
float halfBlue = blue * TEAR_COLOR_HALF;
return {{1, 1, 1, alpha}, {halfRed, halfGreen, halfBlue, 1}, {halfRed, halfGreen, halfBlue}};
}
// 0096f070 Takes a parent laser's look, damage, reach and flags (but its splitting and turning ones), and its spawn
// data (seed, homing, spawner, scale and chain) when asked. Its timeout comes along unless the laser hits once.
void Entity_Laser::copy_from_parent(Entity_Laser& source, LaserCopy copy)
{
if (copy == LASER_COPY_SPAWN)
{
dropRNG = DROP_RNG_SAVED;
dropRNG._seed = source.dropRNG._seed;
homingType = source.homingType;
spawnerType = source.spawnerType;
spawnerVariant = source.spawnerVariant;
spawnerEntity = source.spawnerEntity;
isOneHit = source.isOneHit;
isMultidimensionalTouched = source.isMultidimensionalTouched;
isPrismTouched = source.isPrismTouched;
scale = source.scale;
ResetSpriteScale();
chainedLasers = source.chainedLasers;
}
SetColor(source.sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true);
tearFlags = source.activeTearFlags;
for (int bit : {TEAR_POP, TEAR_ABSORB, TEAR_SPLIT, TEAR_TURN_HORIZONTAL}) tearFlags.reset((size_t)bit);
SetCollisionDamage(source.collisionDamage);
blackHpDropChance = source.blackHpDropChance;
maxDistance = source.maxDistance;
isVisible = source.isVisible;
renderDepthOffset = source.renderDepthOffset;
entityGridCollisionClass = source.entityGridCollisionClass;
entityCollisionClass = source.entityCollisionClass;
mass = source.mass;
if (copy == LASER_COPY_SPAWN || !isOneHit)
{
timeout = source.timeout;
isShrink = source.isShrink;
}
}
// 0096fd60 Where a beam from a start along a direction ends: 1200 away, cut by the room's edge (pushed out by a margin
// and the beam's offset, none for an infinite one) and the missing corner of an L-shaped room. In Challenge #30 an
// enemy's beam also stops at the nearest player within the margin of its line.
Vector Entity_Laser::CalculateEndPoint(const Vector& start, const Vector& direction, const Vector& positionOffset,
Entity* parent, float margin)
{
Room& room = *g_game->room;
float left = room.topLeftPos.x - positionOffset.x - margin;
float top = room.topLeftPos.y - positionOffset.y - margin;
float right = room.bottomRightPos.x - positionOffset.x + margin;
float bottom = room.bottomRightPos.y - positionOffset.y + margin;
Vector end = vector_add(start, vector_scale(direction, BEAM_REACH));
bool isPlayersParent = parent && (parent->type == ENTITY_PLAYER || parent->type == ENTITY_FAMILIAR);
if (g_game->challenge == CHALLENGE_GUARDIAN && !isPlayersParent)
{
float nearest = BEAM_REACH;
for (Entity_Player* player : g_game->playerManager.playerList)
{
Vector offset = vector_sub(player->pos, start);
float along = vector_dot(offset, direction);
float across = offset.x * direction.y - offset.y * direction.x;
if (std::abs(across) >= margin || along <= 0 || along >= nearest) continue;
end = vector_add(start, vector_scale(direction, along));
nearest = along;
}
}
if (!std::isfinite(margin)) return end;
// Shortens the beam so it stops at a boundary it crosses on one axis.
Vector beam = vector_sub(end, start);
auto clip = [&beam](float limit, float startValue, bool isX) {
float reach = limit - startValue;
float projected = (isX ? beam.x : beam.y) * reach;
if (reach * reach <= projected) beam = vector_scale(beam, reach * reach / projected);
};
if (left < start.x) clip(left, start.x, true);
if (start.x < right) clip(right, start.x, true);
if (top < start.y) clip(top, start.y, false);
if (start.y < bottom) clip(bottom, start.y, false);
end = vector_add(start, beam);
int shape = room.GetRoomShape();
if (shape < ROOMSHAPE_LTL || shape > ROOMSHAPE_LBR) return end;
Vector back = vector_sub(start, end);
auto cut = [&back](float limit, float endValue, bool isX) {
float reach = limit - endValue;
float projected = (isX ? back.x : back.y) * reach;
if (reach * reach <= projected) back = vector_scale(back, reach * reach / projected);
};
switch (shape)
{
case ROOMSHAPE_LTL:
if (end.x < left + L_ROOM_ARM_WIDTH && end.y < top + L_ROOM_ARM_HEIGHT)
{
cut(left + L_ROOM_ARM_WIDTH, end.x, true);
cut(top + L_ROOM_ARM_HEIGHT, end.y, false);
}
break;
case ROOMSHAPE_LTR:
if (end.x > right - L_ROOM_ARM_WIDTH && end.y < top + L_ROOM_ARM_HEIGHT)
{
cut(right - L_ROOM_ARM_WIDTH, end.x, true);
cut(top + L_ROOM_ARM_HEIGHT, end.y, false);
}
break;
case ROOMSHAPE_LBL:
if (end.x < left + L_ROOM_ARM_WIDTH && end.y > bottom - L_ROOM_ARM_HEIGHT)
{
cut(left + L_ROOM_ARM_WIDTH, end.x, true);
cut(bottom - L_ROOM_ARM_HEIGHT, end.y, false);
}
break;
default:
if (end.x > right - L_ROOM_ARM_WIDTH && end.y > bottom - L_ROOM_ARM_HEIGHT)
{
cut(right - L_ROOM_ARM_WIDTH, end.x, true);
cut(bottom - L_ROOM_ARM_HEIGHT, end.y, false);
}
break;
}
Vector cutEnd = vector_add(back, end);
return vector_length_squared(vector_sub(start, cutEnd)) > 0.01f ? cutEnd : end;
}
// 0096fc70 Where the laser's beam from a start ends, past the room's edge by 20, by 140 for Continuum, and without an
// edge in a room whose descriptor bit 15 is set or for a light beam (100 under Eye of the Occult).
Vector Entity_Laser::calc_end_point(const Vector& start, const Vector& direction)
{
float margin = tearFlags[TEAR_CONTINUUM] ? BEAM_MARGIN_CONTINUUM : BEAM_MARGIN;
bool isBoundless = (g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_NO_WALLS) || variant == LASER_LIGHT_BEAM;
if (isBoundless) margin = tearFlags[TEAR_OCCULT] ? BEAM_MARGIN_OCCULT : INFINITY;
return CalculateEndPoint(start, direction, posOffset, parent, margin);
}
// 0096d160 Where along the path a distance falls, and the path's direction there: at its end for a farther or
// infinite distance, at its start for none. Without a path, the laser's position along its angle. Whether the
// distance fell inside the path.
// The original measures the point from the last sample before it with the sub laser distance rather than the
// distance asked, which callers always pass as that. That is kept.
bool Entity_Laser::get_segment_start_dir(float distance, Vector& outPosition, Vector& outDirection)
{
std::vector<Vector>& samples = homingLaser.samples;
if (samples.size() < 2)
{
outPosition = pos;
outDirection = vector_from_angle(angleDegrees);
return false;
}
if (distance <= 0)
{
outPosition = samples[0];
outDirection = vector_normalized(vector_sub(samples[1], samples[0]));
return false;
}
if (std::isfinite(distance))
{
float travelled = 0;
for (size_t i = 0; i + 1 < samples.size(); i++)
{
Vector segment = vector_sub(samples[i + 1], samples[i]);
float length = vector_length(segment);
if (distance < length + travelled)
{
float along = subLaserDistance - travelled;
outPosition = vector_add(samples[i], vector_scale(segment, along / length));
outDirection = vector_scale(segment, 1 / length);
return true;
}
travelled += length;
}
}
outPosition = samples.back();
outDirection = vector_normalized(vector_sub(samples.back(), samples[samples.size() - 2]));
return false;
}
// 00973a50 Every other tick (and on the first), a laser fired with the player's stats takes the player's laser hit
// params again: its tear flags (but the waiting and held ones, and explosions for a lasting beam) and damage.
void Entity_Laser::refresh_tear_params()
{
if (!isPlayerParams || isOneHit || isInterpolating) return;
if (!isFirstUpdate && GetIntervalTicks(2, 0) == 0) return;
Entity* spawner = spawnerEntity;
Entity_Player* player = laser_owner_player(spawner);
if (!player) return;
int displacement = (int)(Random() & 1) * 2 - 1;
TearParams params = player->GetTearHitParams(WEAPON_LASER, damageMultiplier, displacement, spawner);
tearFlags = params.tearFlags;
tearFlags.reset(TEAR_WAIT);
if (timeout < 0) tearFlags.reset(TEAR_EXPLOSIVE);
tearFlags &= ~heldTearFlags;
float versusScale =
g_game->deathmatchManager.is_active() && subtype == LASER_SUBTYPE_RING_PROJECTILE ? VERSUS_RING_DAMAGE : 1;
collisionDamage = params.tearDamage * versusScale;
}
// 0097f820 Puts the right impact effect at the beam's end: none, the thin beam's, or the thick beams' of their kind
// (Dogma's static one, the Cage's Vis's). A different one in place is removed first, and the new one comes the next
// time.
void Entity_Laser::spawn_impact_effect()
{
if (!isExists) return;
int impact = -1;
if (variant == LASER_THIN_RED && subtype != LASER_SUBTYPE_NO_IMPACT)
impact = subtype != LASER_SUBTYPE_LINEAR ? IMPACT_SUBTYPE_RING : IMPACT_SUBTYPE_THIN;
else if (is_thick_variant() && spawnerType != SPAWNER_MEGA_SATAN && subtype == LASER_SUBTYPE_LINEAR)
{
Entity* owner = parent;
bool isCageVis = owner && ((owner->type == SPAWNER_VIS && owner->spawnerType == SPAWNER_CAGE) ||
(owner->type == SPAWNER_PEEP && owner->variant == 1 && owner->subtype == 1));
impact = IMPACT_SUBTYPE_THICK;
if (variant == LASER_SHOOP)
impact = IMPACT_SUBTYPE_SHOOP;
else if (isCageVis)
impact = IMPACT_SUBTYPE_CAGE;
else if (variant == LASER_THICKER_RED || variant == LASER_GIANT_RED || variant == LASER_THICKER_BRIM_TECH ||
variant == LASER_GIANT_BRIM_TECH)
impact = IMPACT_SUBTYPE_GIANT;
else if (variant == LASER_THICK_BROWN)
impact = IMPACT_SUBTYPE_BROWN;
}
if (child)
{
if (child->subtype == impact) return;
child->Remove();
if (child) return;
}
if (impact < 0) return;
Entity* effect = g_game->Spawn({.position = pos,
.spawner = this,
.subType = impact,
.type = ENTITY_EFFECT,
.variant = EFFECT_LASER_IMPACT,
.seed = Random()});
child = effect;
effect->parent = this;
if (impact == IMPACT_SUBTYPE_THIN || impact == IMPACT_SUBTYPE_RING)
{
if (subtype == LASER_SUBTYPE_RING_FOLLOW_PARENT) effect->renderDepthOffset = IMPACT_DEPTH_FOLLOW;
}
else
{
if (impact == IMPACT_SUBTYPE_THICK && spawnerType == SPAWNER_DOGMA)
{
effect->sprite.Load(STATIC_IMPACT_ANM2, GRAPHICS_LOAD);
effect->sprite.Play(effect->sprite.GetDefaultAnimationName());
effect->sprite.bitflags |= ANIM_RENDER_STATIC;
}
effect->renderDepthOffset = renderDepthOffset + IMPACT_DEPTH;
}
effect->SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true);
effect->isVisible = isVisible;
effect->Update();
}
// 0097fe60 Keeps the impact effect at the beam's end, turned along it and colored like the laser it ends (its bounce
// when it bounced). A thick beam's grows with the laser's width and hides when it is gone. At a bounce below, it
// sits at the bounce.
void Entity_Laser::update_impact_effect(bool isHidden)
{
Entity* effect = child;
if (!effect || effect->type != ENTITY_EFFECT) return;
effect->isVisible = isVisible && !isHidden;
Entity* colorSource = bounceLaser ? bounceLaser.get() : this;
effect->SetColor(colorSource->sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true);
std::vector<Vector>& samples = homingLaser.samples;
bool isPath = samples.size() >= 2;
Vector back = isPath ? vector_normalized(vector_sub(samples[samples.size() - 2], samples.back())) : Vector{};
Vector end = isPath ? samples.back() : vector_add(pos, vector_scale(vector_from_angle(angleDegrees), laserLength));
float rotation = 0;
if (effect->subtype == IMPACT_SUBTYPE_THIN)
rotation =
isPath ? angle_wrap(vector_angle(back) + SPRITE_ROTATION_OFFSET) : angleDegrees - SPRITE_ROTATION_OFFSET;
else
{
float scaleX = sprite.scale.x;
float scaleY = sprite.scale.y;
if (scaleX <= IMPACT_SCALE_MIN)
effect->isVisible = false;
else
{
scaleX = scaleX * IMPACT_SCALE_KEPT + IMPACT_SCALE_BASE;
bool isGiant = variant == LASER_GIANT_RED || variant == LASER_GIANT_BRIM_TECH;
if (isGiant && effect->subtype == IMPACT_SUBTYPE_GIANT_END)
scaleY = scaleX;
else if (isGiant)
scaleX *= IMPACT_SCALE_GIANT;
effect->isVisible = isVisible;
effect->sprite.scale = vector_make(scaleX, scaleY);
}
Entity* bounce = bounceLaser;
if (bounce && pos.y < bounce->pos.y)
{
effect->pos = bounce->pos;
effect->posOffset = posOffset;
effect->renderDepthOffset = bounce->renderDepthOffset + IMPACT_DEPTH;
effect->sprite.rotation = isPath ? angle_wrap(vector_angle(back) - SPRITE_ROTATION_OFFSET)
: angleDegrees + SPRITE_ROTATION_OFFSET;
return;
}
rotation =
isPath ? angle_wrap(vector_angle(back) - SPRITE_ROTATION_OFFSET) : angleDegrees + SPRITE_ROTATION_OFFSET;
}
effect->pos = end;
effect->posOffset = posOffset;
effect->sprite.rotation = rotation;
effect->renderDepthOffset = renderDepthOffset + IMPACT_DEPTH + pos.y - effect->pos.y;
}
// Anti-Gravity: the beam waits as a swirl (or a dot for a thin one) of its size until the swirl lets it go, taking
// its flags off it meanwhile.
void Entity_Laser::tear_wait_start()
{
tearFlags.reset(TEAR_WAIT);
heldTearFlags.set(TEAR_WAIT);
float effectScale = scale;
if (variant == LASER_THICKER_RED || variant == LASER_THICKER_BRIM_TECH)
effectScale *= WAIT_SCALE_THICKER;
else if (variant == LASER_GIANT_RED || variant == LASER_GIANT_BRIM_TECH)
effectScale *= WAIT_SCALE_GIANT;
else if (variant == LASER_BEAST)
effectScale *= WAIT_SCALE_BEAST;
int effectVariant = is_thick_variant() ? EFFECT_BRIMSTONE_SWIRL : EFFECT_TECH_DOT;
Entity* effect = g_game->Spawn(
{.position = pos, .spawner = spawnerEntity, .type = ENTITY_EFFECT, .variant = effectVariant, .seed = initSeed});
tearWaitEffect = effect;
Entity_Effect& swirl = *static_cast<Entity_Effect*>(tearWaitEffect.get());
swirl.child = this;
swirl.posOffset = posOffset;
swirl.sprite.scale = vector_make(effectScale, effectScale);
swirl.SetColor(color, -1, COLOR_PRIORITY_DEFAULT, false, true);
swirl.SetCollisionDamage(collisionDamage);
for (size_t bit = 0; bit < tearFlags.size(); bit++)
if (tearFlags[bit]) swirl.varData[bit / 32] |= 1u << (bit % 32);
if (parent && parent->type == ENTITY_LASER) swirl.isVisible = false;
swirl.Update();
parent = &swirl;
waitFrames = LASER_WAIT_FRAMES;
isVisible = false;
isDisableFollowParent = true;
}
// Rainbow and Continuum beams cycle colors: a hue round every 30 frames, or a pink pulse every 8 steps of two frames.
void Entity_Laser::color_cycle_update()
{
Entity_Laser* root = root_laser_get();
ColorMod cycle = COLOR_DEFAULT;
if (root->tearFlags[TEAR_RAINBOW])
cycle = colorize_from_hue((float)(g_game->frameCount % (int)RAINBOW_FRAMES) * ANGLE_FULL_TURN / RAINBOW_FRAMES,
RAINBOW_SATURATION, 1, RAINBOW_STRENGTH);
else if (root->tearFlags[TEAR_CONTINUUM])
{
int phase = (g_game->frameCount - spawnFrame) / 2 % CONTINUUM_PHASES;
int step = phase <= CONTINUUM_PHASES / 2 ? phase : CONTINUUM_PHASES - phase;
cycle._colorize[0] = CONTINUUM_COLORIZE;
cycle._colorize[1] = (float)step * CONTINUUM_GREEN_STEP;
cycle._colorize[2] = CONTINUUM_COLORIZE;
cycle._colorize[3] = 1;
}
else
return;
SetColor(cycle, -1, COLOR_PRIORITY_DEFAULT, false, true);
if (child) child->SetColor(cycle, -1, COLOR_PRIORITY_DEFAULT, false, true);
if (tearWaitEffect) tearWaitEffect->SetColor(cycle, -1, COLOR_PRIORITY_DEFAULT, false, true);
}
// 00977cc0 Waits out Anti-Gravity, cycles its colors, then runs the ring's or the beam's update (and The Forsaken's
// loop). Its first update sets it up instead: a static beam for Dogma, the Cage's Vis's own sprite.
void Entity_Laser::Update()
{
if (tearFlags[TEAR_WAIT] && !IsCircleLaser() && timeout > 0) tear_wait_start();
Entity* swirl = tearWaitEffect;
if (swirl && static_cast<Entity_Effect*>(swirl)->state == 0 && waitFrames < LASER_WAIT_FRAMES)
waitFrames = LASER_WAIT_FRAMES;
color_cycle_update();
if (waitFrames > 0)
{
if (--waitFrames > 0) return;
isVisible = true;
}
if (!isFirstUpdate)
{
if (IsCircleLaser())
UpdateHits();
else
update_laser();
if (variant == LASER_THICK_RED && spawnerEntity && spawnerEntity->type == SPAWNER_FORSAKEN)
{
if (isDead)
g_manager->sfxManager.Stop(SOUND_FORSAKEN_LASER);
else if (!g_manager->sfxManager.IsPlaying(SOUND_FORSAKEN_LASER))
laser_sound_play(SOUND_FORSAKEN_LASER, {.loop = SOUND_LOOP});
}
Entity::Update();
lua_engine_get().PostLaserUpdate(this);
return;
}
Entity* owner = parent;
bool isCageVis = spawnerType == SPAWNER_VIS && owner && owner->spawnerType == SPAWNER_CAGE;
bool isCagePeep = spawnerType == SPAWNER_PEEP && owner && owner->type == SPAWNER_PEEP && owner->variant == 1 &&
owner->subtype == 1;
if (isCageVis || isCagePeep)
{
sprite.Load(CAGE_VIS_LASER_ANM2, GRAPHICS_LOAD);
sprite.Play(sprite.GetDefaultAnimationName());
}
else if (spawnerType == SPAWNER_DOGMA && variant == LASER_THICK_RED)
{
sprite.Load(STATIC_LASER_ANM2, GRAPHICS_LOAD);
sprite.Play(sprite.GetDefaultAnimationName());
sprite.bitflags |= ANIM_RENDER_STATIC;
}
update_first_frame();
isFirstUpdate = false;
}
// Whether a laser's parent makes it follow a sampled path: the player's beams and a few familiars' and bosses', and
// any turning, ring or Eye of the Occult beam. The tractor beam never does.
static bool is_path_laser(Entity_Laser& laser)
{
Entity* owner = laser.parent;
if (!owner) return false;
int type = owner->type;
bool isPathParent =
type == ENTITY_PLAYER || laser.spawnerType == ENTITY_PLAYER || type == SPAWNER_PIN ||
(type == ENTITY_EFFECT && owner->variant == EFFECT_SAMPLE_PARENT) || type == SPAWNER_PATH_KEEPER_1 ||
type == SPAWNER_PATH_KEEPER_2 || type == SPAWNER_PATH_KEEPER_3 ||
(type == SPAWNER_RING_KEEPER && owner->subtype == 2) ||
(type == ENTITY_FAMILIAR && (owner->variant == Entity_Familiar::INCUBUS ||
owner->variant == Entity_Familiar::SPRINKLER || laser.tearFlags[TEAR_HOMING]));
bool isShaped = laser.isActiveRotating || laser.IsCircleLaser() || laser.tearFlags[TEAR_OCCULT];
return (isPathParent || isShaped) && laser.variant != LASER_TRACTOR_BEAM;
}
// 009704a0 The laser's first frame: its sound, flip and size, its impact effect, and whether it follows a path. A
// straight beam finds its end (through grid entities for a ground beam) within its reach and is drawn turned along
// its angle. A pride beam is a fixed 300 long.
void Entity_Laser::update_first_frame()
{
PlayInitSound();
if (variant == LASER_PRIDE)
{
sprite.rotation = angleDegrees;
laserLength = PRIDE_LENGTH;
endPoint = vector_add(vector_add(pos, posOffset), vector_scale(vector_from_angle(angleDegrees), PRIDE_LENGTH));
sampleMode = SAMPLE_STRAIGHT;
isSampleLaser = false;
return;
}
Vector direction = vector_from_angle(angleDegrees);
if (std::abs(direction.x) < AXIS_SNAP) direction.x = 0;
if (std::abs(direction.y) < AXIS_SNAP) direction.y = 0;
sprite.isFlipX = (initSeed >> 8) & 1;
ResetSpriteScale();
spawn_impact_effect();
if (sampleMode == SAMPLE_UNDECIDED) sampleMode = is_path_laser(*this) ? SAMPLE_PATH : SAMPLE_STRAIGHT;
isSampleLaser = sampleMode == SAMPLE_PATH;
if (isSampleLaser)
{
ClearLaserSamples();
if (IsCircleLaser()) return UpdateHits();
return update_laser();
}
Vector start = vector_add(pos, posOffset);
if (entityGridCollisionClass == GRIDCOLL_NOPITS)
{
Vector from = vector_sub(start, vector_scale(direction, BEAM_BACKSTEP));
LineCheck check =
room_line_check(from, vector_add(start, vector_scale(direction, BEAM_FAR)), GRIDCOLL_NOPITS, true);
endPoint = check.isClear ? vector_add(calc_end_point(start, direction), posOffset) : check.hit;
}
else if (entityGridCollisionClass == GRIDCOLL_WALLS)
endPoint = vector_add(calc_end_point(start, direction), posOffset);
else
endPoint = vector_add(start, vector_scale(direction, BEAM_UNBLOCKED));
if (maxDistance > 0 && vector_length_squared(vector_sub(start, endPoint)) > maxDistance * maxDistance)
endPoint = vector_add(start, vector_resized(vector_sub(endPoint, start), maxDistance));
laserLength = vector_length(vector_sub(endPoint, start));
if (variant == LASER_GIANT_RED || variant == LASER_GIANT_BRIM_TECH)
laserLength = spawnerType == SPAWNER_PATH_KEEPER_3 ? std::max(BEAM_GIANT_MINIMUM, laserLength)
: laserLength + BEAM_GIANT_EXTRA;
sprite.rotation = angleDegrees - SPRITE_ROTATION_OFFSET;
update_laser();
}
// 00973c60 The beam's frame: it takes the player's params again, clears its hits every other tick, follows its
// parent, shakes the screen for the big beams, turns, finds its end (a sampled path for the path lasers), hits what
// it crosses, and shrinks or dies at its timeout.
void Entity_Laser::update_laser()
{
refresh_tear_params();
bool isFirst = isFirstUpdate;
if (isFirst || !isOneHit) activeTearFlags = tearFlags;
bool isHitFrame =
variant != LASER_TRACTOR_BEAM && !isInterpolating && !isDead && (isFirst || GetIntervalTicks(2, 0) != 0);
if (isHitFrame && !parentLaser && !isOneHit) hitList.clear();
Entity* owner = parent;
if (owner && !isDisableFollowParent)
{
Vector followed = owner->pos;
if (owner->type == ENTITY_PLAYER)
followed = vector_add(vector_add(followed, parentOffset), owner->ToPlayer()->tearsOffset);
else if (spawnerType != ENTITY_PLAYER)
followed = vector_add(followed, parentOffset);
pos = followed;
}
if (!isInterpolating && timeout != 0)
{
bool isThickerStart = (variant == LASER_THICKER_RED || variant == LASER_THICKER_BRIM_TECH) &&
g_game->frameCount - spawnFrame == 1;
if (variant == LASER_GIANT_RED || variant == LASER_GIANT_BRIM_TECH)
game_shake_screen(SHAKE_GIANT);
else if (isThickerStart || variant == LASER_BEAST)
game_shake_screen(SHAKE_STRONG);
}
if (isActiveRotating)
{
if (rotationDelay != 0)
rotationDelay--;
else
{
float step = rotationSpd * ROTATION_STEP_SCALE;
float turn = rotationDegrees >= 0 ? std::min(rotationDegrees, step) : std::max(rotationDegrees, step);
if (rotationDegrees != 0)
{
angleDegrees += turn;
rotationDegrees -= turn;
sprite.rotation = angle_wrap(angleDegrees - SPRITE_ROTATION_OFFSET);
}
if (rotationDegrees == 0 || (rotationDegrees > 0) != (turn > 0)) isActiveRotating = false;
}
}
bool isSamplesRebuilt = false;
bool isRedirected = false;
bool isCut = false;
if (!isSampleLaser)
straight_update(isRedirected);
else if ((homingType != LASER_HOMING_FREEZE && !isOneHit) || isFirstUpdate)
{
isSamplesRebuilt = true;
path_update(isRedirected, isCut);
}
death_update();
if (isSamplesRebuilt) homingLaser.remove_collinear_samples(0.001f);
if (isHitFrame) update_endpoint_and_hits();
if (isSampleLaser && isExists)
{
ends_update(isSamplesRebuilt, isHitFrame, isRedirected, isCut);
chain_fire();
}
if (timeout > 0 && !isInterpolating && --timeout < 1)
{
bool isGiant = variant == LASER_GIANT_RED || variant == LASER_GIANT_BRIM_TECH;
if (isGiant && !isShrink && !isDead) npc_sound_play(SOUND_MEGA_BLAST_END, 1, 2, 1);
bool isFading = is_thick_variant() && variant != LASER_BEAST && (!isGiant || spawnerType == ENTITY_PLAYER);
if (isFading)
{
isShrink = true;
timeout = 0;
}
else
isDead = true;
}
lastAngleDegrees = angleDegrees;
}
// A straight beam's end: along its angle to the grid or the room's edge within its reach. A beam not the players'
// bounces off a mirror it meets.
void Entity_Laser::straight_update(bool& isRedirected)
{
isGridHit = false;
bool isDrawnStraight = is_thick_variant() || variant == LASER_THIN_RED || variant == LASER_ELECTRIC ||
variant == LASER_LIGHT_BEAM || variant == LASER_TRACTOR_BEAM || variant == LASER_LIGHT_RING;
if (!isDrawnStraight) return;
Vector start = vector_add(pos, posOffset);
Vector direction = vector_from_angle(angleDegrees);
if (entityGridCollisionClass == GRIDCOLL_NOPITS)
endPoint = room_laser_target_get(vector_sub(start, vector_scale(direction, BEAM_BACKSTEP)), direction);
else if (entityGridCollisionClass == GRIDCOLL_WALLS)
endPoint = vector_add(calc_end_point(pos, direction), posOffset);
else
endPoint = vector_add(start, vector_scale(direction, BEAM_UNBLOCKED));
if (maxDistance > 0 && vector_length_squared(vector_sub(endPoint, start)) > maxDistance * maxDistance)
endPoint = vector_add(start, vector_resized(vector_sub(endPoint, start), maxDistance));
bool isGiantKeeper =
(variant == LASER_GIANT_RED || variant == LASER_GIANT_BRIM_TECH) && spawnerType == SPAWNER_MEGA_SATAN;
if (isGiantKeeper || variant == LASER_BEAST)
endPoint = vector_add(endPoint, vector_resized(vector_sub(endPoint, start), BEAM_GIANT_EXTRA));
if (spawnerType != ENTITY_PLAYER && spawnerType != ENTITY_FAMILIAR)
{
if (!entity_query(ENTITY_EFFECT, EFFECT_LASER_MIRROR).empty())
reconstruction_missing("Entity_Laser::update_laser 00973c60: a beam off a mirror");
if (bounceLaser) bounceLaser->Remove();
}
laserLength = vector_length(vector_sub(endPoint, start));
update_impact_effect(isRedirected);
}
// A path laser's samples: from the tip of its start sprite to its end, along a straight path (homing and shaped by
// its tear flags), cut by the grid, then split by Multidimensional Baby and Angelic Prism, bounced by a mirror,
// wrapped by Continuum, or bounced by Rubber Cement.
void Entity_Laser::path_update(bool& isRedirected, bool& isCut)
{
isGridHit = false;
bool isAimChanged = angleDegrees != lastAngleDegrees && !is_thick_variant() && variant != LASER_LIGHT_BEAM;
if (isAimChanged)
{
homingLaser.bezier.clear();
homingLaser.samples.clear();
homingLaser.smoothedSamples.clear();
homingLaser.nonOptimizedSamples.clear();
}
Vector direction =
vector_make(std::cos(angleDegrees * DEGREES_TO_RADIANS), std::sin(angleDegrees * DEGREES_TO_RADIANS));
Vector tip{};
const AnimationFrame* tipFrame = sprite.layerStates.size() > 1 ? sprite.animState.GetLayerFrame(0) : nullptr;
if (tipFrame) tip = vector_scale(direction, (tipFrame->height + tipFrame->pos.y) * sprite.scale.y);
Vector start = vector_add(pos, tip);
Entity_Player* player = spawnerEntity && spawnerEntity->type == ENTITY_PLAYER ? spawnerEntity->ToPlayer() : nullptr;
endPoint = calc_end_point(start, direction);
if (maxDistance > 0 && vector_length_squared(vector_sub(start, endPoint)) > maxDistance * maxDistance)
endPoint = vector_add(start, vector_resized(vector_sub(endPoint, start), maxDistance));
homingLaser.bezier.clear();
bool isGiantPlayer =
(variant == LASER_GIANT_RED || variant == LASER_GIANT_BRIM_TECH) && spawnerType == ENTITY_PLAYER;
Vector reach = vector_sub(endPoint, start);
if (isGiantPlayer) reach = vector_sub(reach, vector_scale(direction, BEAM_GIANT_TIP_GAP));
if (vector_dot(reach, tip) < 0)
{
float tipLength = vector_length(tip);
Vector nudge = tipLength > 0 ? vector_scale(tip, BEAM_START_NUDGE / tipLength) : tip;
Vector base = isGiantPlayer ? vector_add(start, tip) : start;
endPoint = vector_add(base, nudge);
}
homingLaser.origin = start;
homingLaser.endPoint = endPoint;
if (tearFlags[TEAR_ORBIT]) homingLaser.build_curl_path(HOMING_LASER_RING_REACH);
if (tearFlags[TEAR_BOOMERANG])
{
homingLaser.build_wiggle_bezier();
if (!homingLaser.bezier.empty()) endPoint = homingLaser.bezier.back().point;
}
if (tearFlags[TEAR_TURN_HORIZONTAL])
{
homingLaser.trace_entities(TEAR_TURN_HORIZONTAL);
if (!homingLaser.bezier.empty()) endPoint = homingLaser.bezier.back().point;
}
BezierPathType pathType = BEZIER_PATH_STRAIGHT;
if (tearFlags[TEAR_HOMING])
pathType = BEZIER_PATH_HOMING;
else if (homingType == LASER_HOMING_FREEZE)
pathType = BEZIER_PATH_OTHER_TYPES;
else if (homingType == LASER_HOMING_PLAYER)
pathType = BEZIER_PATH_WITH_PLAYERS;
homingLaser.build_bezier_path(pathType, parent);
float blend = 0.63f;
if (variant == LASER_THIN_RED || variant == LASER_ELECTRIC)
blend = 0.7f;
else if (homingType == LASER_HOMING_PLAYER)
blend = 1;
else if (maxDistance <= 0)
blend = 0.9f;
homingLaser.CalculateSamples(blend);
float phase = (float)index;
if (tearFlags[TEAR_SQUARE] && !tearFlags[TEAR_ORBIT])
homingLaser.apply_sample_wiggle(player ? worm_multiplier_get(player, TEAR_SQUARE) : 1, phase);
if (tearFlags[TEAR_WIGGLE])
homingLaser.apply_sine_offset(player ? worm_multiplier_get(player, TEAR_WIGGLE) : 1, phase);
if (tearFlags[TEAR_BIG_SPIRAL])
update_wiggle_path(player ? worm_multiplier_get(player, TEAR_BIG_SPIRAL) * 3 : 3, phase);
else if (tearFlags[TEAR_SPIRAL])
update_wiggle_path(player ? worm_multiplier_get(player, TEAR_SPIRAL) : 1, phase);
if (tear_flags_any(tearFlags, {TEAR_POP, TEAR_ABSORB})) isCut = homingLaser.truncate_samples(HOMING_LASER_REACH);
if (entityGridCollisionClass != GRIDCOLL_NONE && !tearFlags[TEAR_SPECTRAL])
{
isGridHit =
homingLaser.clip_samples_to_grid(vector_scale(posOffset, GRID_HIT_OFFSET_SCALE), entityGridCollisionClass);
if (isGridHit) isCut = false;
if (homingType == LASER_HOMING_PLAYER) homingLaser.truncate_samples_at_obstacle(posOffset);
}
bool isPlayersParent = parent && (parent->type == ENTITY_PLAYER || parent->type == ENTITY_FAMILIAR);
if (g_game->challenge == CHALLENGE_GUARDIAN && !isPlayersParent) homingLaser.truncate_samples_at_player();
bool isMirrored = false;
path_redirects_update(isRedirected, isCut, isMirrored);
if (!isMirrored)
{
if (tearFlags[TEAR_BOUNCE] && !isRedirected)
reconstruction_missing("Entity_Laser::update_laser 00973c60: Rubber Cement's bounce");
if (bounceLaser) bounceLaser->Remove();
spawn_impact_effect();
}
if (!isGridHit)
isCut = isCut || chainedLasers > 0;
else
chainedLasers = 0;
update_impact_effect(isCut);
Entity* follow = child;
int endCollision = follow ? (int)g_game->room->GetGridCollision(
g_game->room->GetGridIndex(vector_add(follow->pos, follow->posOffset)))
: 0;
bool isDroppingVariant = variant == LASER_THICK_RED || variant == LASER_GIANT_RED || variant == LASER_BRIM_TECH ||
variant == LASER_THICKER_RED || variant == LASER_THICK_BROWN ||
variant == LASER_THICKER_BRIM_TECH || variant == LASER_GIANT_BRIM_TECH;
bool isBlockedEnd = maxDistance == 0 || (endCollision != COLLISION_NONE && endCollision != COLLISION_PIT);
if (isDroppingVariant && sprite.scale.x > 0.5f && spawnerType == ENTITY_PLAYER && isBlockedEnd &&
!isInterpolating && !HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && homingLaser.samples.size() > 1)
{
std::vector<Vector>& samples = homingLaser.samples;
float back = vector_angle(vector_sub(samples[samples.size() - 2], samples.back()));
float angle = angle_wrap(random_fraction() * ANGLE_HALF_TURN + back - SPRITE_ROTATION_OFFSET);
uint32_t seed = Random();
Vector velocity = vector_scale(vector_from_angle(angle), random_fraction() * 10 + 1);
Vector position = vector_add(samples.back(), vector_scale(random_direction(), random_fraction() * 20));
Entity* drop = g_game->Spawn({.position = position,
.velocity = velocity,
.type = ENTITY_EFFECT,
.variant = EFFECT_BLOOD_DROP,
.seed = seed});
if (child)
{
drop->sprite = child->sprite;
drop->sprite.SetFrame("Droplets", random_below(3));
}
drop->posOffset = posOffset;
drop->SetColor(sprite.color, -1, COLOR_PRIORITY_DEFAULT, false, true);
drop->Update();
}
if (tearFlags[TEAR_MYSTERIOUS_LIQUID_CREEP] && IsFrame(5, (int)index))
reconstruction_missing("Entity_Laser::update_laser 00973c60: Mysterious Liquid's creep at the beam's end");
}
// The splits a path laser meets: Multidimensional Baby doubles the players' beams through it, a mirror bounces the
// others, Angelic Prism splits the players' into four, and Continuum carries a beam on from the opposite wall. Each
// one met marks the beam redirected.
void Entity_Laser::path_redirects_update(bool& isRedirected, bool& isCut, bool& isMirrored)
{
Vector hitPosition{};
Vector hitDirection{};
bool isPlayers =
spawnerType == ENTITY_PLAYER || (spawnerType == ENTITY_FAMILIAR && spawnerVariant != FAMILIAR_ANGELIC_PRISM);
if (isPlayers && !isMultidimensionalTouched)
{
if (homingLaser.find_targets(hitPosition, hitDirection, ENTITY_FAMILIAR, Entity_Familiar::MULTIDIMENSIONAL_BABY,
nullptr))
reconstruction_missing("Entity_Laser::update_laser 00973c60: Multidimensional Baby's beams");
for (EntityPtr& split : multidimensionalLasers)
if (split) split->Remove();
impact_effect_refresh();
}
bool isOthers =
(spawnerType != ENTITY_PLAYER && spawnerType != ENTITY_FAMILIAR) || g_game->deathmatchManager.is_active();
if (isOthers)
{
Entity* mirror = homingLaser.find_targets(hitPosition, hitDirection, ENTITY_EFFECT, EFFECT_LASER_MIRROR, this);
isMirrored = mirror != nullptr;
if (isMirrored) reconstruction_missing("Entity_Laser::update_laser 00973c60: a beam off a mirror");
Entity* bounce = bounceLaser;
if (bounce && bounce->parent && bounce->parent->type == ENTITY_PLAYER) bounce->Remove();
}
bool isPrismable = spawnerType == ENTITY_PLAYER ||
(spawnerType == ENTITY_FAMILIAR && spawnerVariant != Entity_Familiar::MULTIDIMENSIONAL_BABY);
if (isPrismable && !isPrismTouched)
{
if (homingLaser.find_targets(hitPosition, hitDirection, ENTITY_FAMILIAR, FAMILIAR_ANGELIC_PRISM, nullptr))
reconstruction_missing("Entity_Laser::update_laser 00973c60: Angelic Prism's beams");
for (EntityPtr& split : prismLasers)
if (split) split->Remove();
impact_effect_refresh();
}
if (!tearFlags[TEAR_CONTINUUM] || isRedirected || isGridHit)
{
if (continuumLaser) continuumLaser->Remove();
}
else
reconstruction_missing("Entity_Laser::update_laser 00973c60: Continuum's beam from the far wall");
(void)isCut;
}
// After splits that met nothing, a missing impact effect is put back, and a giant beam's renewed after a bounce.
void Entity_Laser::impact_effect_refresh()
{
Entity* effect = child;
if (effect)
{
bool isGiant = variant == LASER_GIANT_RED || variant == LASER_GIANT_BRIM_TECH;
bool isStale = bounceLaser && effect->type == ENTITY_EFFECT && effect->variant == EFFECT_LASER_IMPACT &&
effect->subtype != IMPACT_SUBTYPE_GIANT_END && isGiant;
if (!isStale) return;
effect->Remove();
}
spawn_impact_effect();
}
// A parent that died takes its laser along (removing it at once when the parent is a laser already gone). A dying or
// shrinking beam fades: a thin beam plays its fade animation, the thick ones narrow over 19 frames.
void Entity_Laser::death_update()
{
Entity* owner = parent;
if (owner && owner->isDead && owner->type != ENTITY_EFFECT)
{
isDead = true;
if (owner->type == type && !owner->isExists) Remove();
}
if (!isDead && !isShrink) return;
if (variant == LASER_THIN_RED)
{
if (sprite.animState.IsLoopingAnimation())
{
sprite.Play(sprite.GetAnimation() + "Fade");
if (child) child->sprite.Play("End");
if (initSeed & 0x1000) sprite.SetFrame(1);
}
if (!sprite.IsFinished()) return;
}
else if (variant != LASER_ELECTRIC && variant != LASER_PRIDE)
{
timeout--;
sprite.scale.x *= SHRINK_RATE;
if (timeout > SHRINK_TIMEOUT_END) return;
}
Remove();
}
// After the hits: on a hit frame the beam's end (or wherever it was stopped) sets off its tear effects, and Pop and
// Absorb drop a tear there. The split beams of Cricket's Body follow the impact.
void Entity_Laser::ends_update(bool isSamplesRebuilt, bool isHitFrame, bool isRedirected, bool isCut)
{
bool isImpact = false;
if (isSamplesRebuilt)
{
isImpact = std::isfinite(impactDistance) || isGridHit || !(isCut || (parent && parent->type == ENTITY_TEAR));
if (isHitFrame && isImpact) impact_tear_flag_effects(impactPosition, impactDirection);
bool isEnded = std::isfinite(impactDistance) || isGridHit || chainedLasers == 0;
bool isPopped = tear_flags_any(activeTearFlags, {TEAR_POP, TEAR_ABSORB}) && !isRedirected && !isGridHit;
if (isHitFrame && isEnded && isPopped)
reconstruction_missing("Entity_Laser::update_laser 00973c60: Pop's and Absorb's tear at the beam's end");
}
if (isImpact && activeTearFlags[TEAR_SPLIT])
reconstruction_missing("Entity_Laser::update_laser 00973c60: the split beams of Cricket's Body");
for (EntityPtr& split : subLasers)
if (split) split->Remove();
subLaserDistance = INFINITY;
}
// Past its second frame a beam of a spread fires the next of its chain from its end.
void Entity_Laser::chain_fire()
{
if (g_game->frameCount - spawnFrame <= 1 || chainedLasers <= 0) return;
if (homingLaser.samples.size() > 1)
reconstruction_missing("Entity_Laser::update_laser 00973c60: the chained beams of a spread");
chainedLasers = 0;
}
// 009737b0 Finds what the beam hits: its end and direction there first, the grid along its path, then the entities
// crossing it.
void Entity_Laser::update_endpoint_and_hits()
{
impactDistance = INFINITY;
std::vector<Vector>& samples = homingLaser.samples;
if (samples.size() > 1)
{
impactPosition = samples.back();
impactDirection = vector_normalized(vector_sub(samples.back(), samples[samples.size() - 2]));
}
if (!isOneHit || isFirstUpdate) find_nearest_grid_hit(vector_scale(posOffset, GRID_HIT_OFFSET_SCALE));
update_line_hits(collisionDamage);
}
// 0097e6f0 Between updates, a beam finds its path again, and a ring moves on (Ludovico's and the flying ones by half
// their velocity) and hits.
void Entity_Laser::Interpolate()
{
if (waitFrames >= 1 || isFirstUpdate) return;
isInterpolating = true;
preInterpolatePos = pos;
if (!IsCircleLaser()) return update_laser();
if (subtype != LASER_SUBTYPE_RING_FOLLOW_PARENT)
pos = vector_add(pos, vector_scale(velocity, friction * ROTATION_STEP_SCALE));
UpdateHits();
}
// 0097e800 Lets go of the lasers it split into, bounced into or chained (removing them first when the factory took it
// back), and of its parent laser and Anti-Gravity swirl.
void Entity_Laser::ClearReferences()
{
Entity::ClearReferences();
auto release = [this](EntityPtr& laser) {
if (isRemovedByFactory && laser)
{
laser->Remove();
laser->ClearReferences();
}
laser = nullptr;
};
for (EntityPtr& laser : multidimensionalLasers) release(laser);
for (EntityPtr& laser : prismLasers) release(laser);
release(bounceLaser);
release(childLaser);
parentLaser = nullptr;
for (EntityPtr& laser : subLasers) release(laser);
release(continuumLaser);
tearWaitEffect = nullptr;
}
// 0097ea30 Removes the laser with the lasers it split into, and unless it hits once the ones it bounced into or
// chained, and its impact effect. The Forsaken's beam stops its loop.
void Entity_Laser::Remove()
{
Entity::Remove();
auto remove = [](EntityPtr& laser) {
if (laser && laser->isExists) laser->Remove();
};
for (EntityPtr& laser : multidimensionalLasers) remove(laser);
for (EntityPtr& laser : prismLasers) remove(laser);
if (!isOneHit)
{
remove(bounceLaser);
remove(childLaser);
for (EntityPtr& laser : subLasers) remove(laser);
remove(continuumLaser);
}
remove(child);
if (variant == LASER_THICK_RED && spawnerType == SPAWNER_FORSAKEN) g_manager->sfxManager.Stop(SOUND_FORSAKEN_LASER);
}
// 0099efc0 Big Spiral's and Ring Worm's path turns are not reconstructed yet.
void Entity_Laser::update_wiggle_path(float, float)
{
reconstruction_missing("Entity_Laser::update_wiggle_path 0099efc0");
}