diff --git a/generated-src/classes.h b/generated-src/classes.h index 2cd587c..b4c19e8 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -156,6 +156,7 @@ struct CellSpace; struct ChallengeParam; struct ChallengeParams; struct Checksum; +struct CoPlayerState; struct Color; struct ColorMod; struct ColorModState; @@ -171,9 +172,11 @@ struct ConsoleScroll; struct ConsoleText; struct ConstLobby; struct ConsumableData; +struct ControlRow; struct ControllerEntry; struct CoopAward; struct CoopJoinSlot; +struct CostumeItem; struct CostumeSpriteDesc; struct CraftingRecipe; struct Cutscene; @@ -448,10 +451,12 @@ struct PathFinder; struct PathNode; struct PauseScreen; struct PauseScreen_MyStuff; +struct PersistentEffect; struct PersistentGameData; struct PersistentGameDataReader; struct PersistentGameDataWriter; struct PersistentGameData_Bestiary; +struct PickupChoice; struct PickupGhostData; struct PillEffect; struct Platform; @@ -505,6 +510,7 @@ struct Room; struct RoomClear; struct RoomConfig; struct RoomConfigMode; +struct RoomConfigRef; struct RoomConfigRoom; struct RoomConfigStage; struct RoomConfig_Curse; @@ -525,6 +531,7 @@ struct RoomTransition; struct RoomTransitionRequest; struct SFXManager; struct SaveDataManager; +struct SavedRoom; struct ScoreRecord; struct ScoreSheet; struct Seeds; @@ -552,6 +559,7 @@ struct Sprite; struct SpriteDraw; struct SpriteShaderParams; struct SpriteTrailData; +struct StageNameQuery; struct StageTransition; struct StageVisit; struct StatHUD; @@ -578,6 +586,9 @@ struct Vector; struct VectorRing; struct VentricleRazorPortal; struct VideoPlayer; +struct VoidedPassive; +struct WallDetail; +struct WallSlot; struct WaterClipInfo; struct Weapon; struct WeaponDelete; @@ -920,25 +931,6 @@ LAYOUT32(offsetof(Ambush, _maxWaves) == 0x18); LAYOUT32(offsetof(Ambush, _isActive) == 0x20); LAYOUT32(offsetof(Ambush, _currentWave) == 0x24); -struct BackwardsStageDesc { - uint8_t _bossRooms[0x170]; // RoomDescriptor[2] - uint8_t _bossRoomConfigs[0x18]; // GameStateRoomConfig[2] - uint8_t _treasureRooms[0x170]; // RoomDescriptor[2] - uint8_t _treasureRoomConfigs[0x18]; // GameStateRoomConfig[2] - uint32_t _bossRoomsCount; - uint32_t _treasureRoomsCount; - uint32_t _stageType; - bool _isXL; -}; -LAYOUT32(offsetof(BackwardsStageDesc, _bossRooms) == 0x0); -LAYOUT32(offsetof(BackwardsStageDesc, _bossRoomConfigs) == 0x170); -LAYOUT32(offsetof(BackwardsStageDesc, _treasureRooms) == 0x188); -LAYOUT32(offsetof(BackwardsStageDesc, _treasureRoomConfigs) == 0x2f8); -LAYOUT32(offsetof(BackwardsStageDesc, _bossRoomsCount) == 0x310); -LAYOUT32(offsetof(BackwardsStageDesc, _treasureRoomsCount) == 0x314); -LAYOUT32(offsetof(BackwardsStageDesc, _stageType) == 0x318); -LAYOUT32(offsetof(BackwardsStageDesc, _isXL) == 0x31c); - struct BeamRenderer { static void Begin(ANM2 *anm2, uint32_t layer, uint8_t isUseOverlay, uint8_t isUnk); // 0041e480 static void Add(Vector *point, ColorMod *color, float spritesheetCoordinate, float width); // 0041e720 @@ -1344,13 +1336,6 @@ struct EntityPartition { }; -struct EntitySaveState { - void constructor(); // 004d3080 - void copy(void *other); // 004d3130 - static void set_extra_data(uint32_t param_1); // 00827f70 -}; - - struct EntitySaveStateRef { void Set(void *state); // 006eee10 }; @@ -1361,31 +1346,6 @@ struct EntitySpawner { }; -struct FamiliarData { - int _seed; - int _variant; - int _subtype; - int _coins; - int _hearts; - int _keys; - int _state; - int _roomClearCount; - uint8_t _pad_0x20[0x8]; - float _health; - int _dropRNGSeed; -}; -LAYOUT32(offsetof(FamiliarData, _seed) == 0x0); -LAYOUT32(offsetof(FamiliarData, _variant) == 0x4); -LAYOUT32(offsetof(FamiliarData, _subtype) == 0x8); -LAYOUT32(offsetof(FamiliarData, _coins) == 0xc); -LAYOUT32(offsetof(FamiliarData, _hearts) == 0x10); -LAYOUT32(offsetof(FamiliarData, _keys) == 0x14); -LAYOUT32(offsetof(FamiliarData, _state) == 0x18); -LAYOUT32(offsetof(FamiliarData, _roomClearCount) == 0x1c); -LAYOUT32(offsetof(FamiliarData, _health) == 0x28); -LAYOUT32(offsetof(FamiliarData, _dropRNGSeed) == 0x2c); -LAYOUT32(sizeof(FamiliarData) == 0x30); - struct File { }; @@ -1465,19 +1425,6 @@ struct GameOver { LAYOUT32(offsetof(GameOver, _state) == 0x0); LAYOUT32(offsetof(GameOver, _isStopSoundsPending) == 0x11c); -struct GameStatePlayer { - ~GameStatePlayer(); // 00754d90 - void read_player_key(void *stream); // 009c86e0 - void Init(); // 009cf050 - static uint8_t read_coplayer(short *block, void *stream); // 009cff40 - void write_coplayer(void *stream); // 009d0100 - static void read_block_538(uint32_t *block, void *stream); // 009d02c0 - static void write_block_538(short *block, void *stream); // 009d0440 - uint8_t read(void *reader); // 009d05d0 - static uint32_t read_part3(); // 009d2656 -}; - - struct Game_StateSlot { void * operator_assign(void *other); // 006f8a40 }; @@ -1493,20 +1440,6 @@ struct GlitchedItemSet { }; -struct GlowingHourglassState { - bool _isUsable; - uint8_t _pad_0x1[0x3]; - uint8_t _gameState[0x1fe28]; // GameState - int _leaveDoor; - uint32_t _timeCounter; - uint8_t _eventCounters[0x4]; // int[523] -}; -LAYOUT32(offsetof(GlowingHourglassState, _isUsable) == 0x0); -LAYOUT32(offsetof(GlowingHourglassState, _gameState) == 0x4); -LAYOUT32(offsetof(GlowingHourglassState, _leaveDoor) == 0x1fe2c); -LAYOUT32(offsetof(GlowingHourglassState, _timeCounter) == 0x1fe30); -LAYOUT32(offsetof(GlowingHourglassState, _eventCounters) == 0x1fe34); - struct GraphicsWindow { int get_framebuffer_width(); // 00a19340 }; @@ -3717,32 +3650,6 @@ LAYOUT32(offsetof(PMD, pdisp) == 0x4); LAYOUT32(offsetof(PMD, vdisp) == 0x8); LAYOUT32(sizeof(PMD) == 0xc); -struct PathFinder { - int GetGridIndex(); // 00456370 - static uint32_t GetEvadeMovementCountdown(); // 00456740 - static void SetCanCrushRocks(uint8_t param_1); // 00499dc0 - uint8_t HasDirectPath(); // 004be6e0 - void Init(Entity *owner); // 007e31a0 - void Reset(); // 007e3260 - uint8_t is_entity_friendly(); // 007e3340 - void EvadeTarget(Vector *targetPos, uint8_t isIgnoreStatusEffects); // 007e4940 - void MoveRandomlyAxisAligned(float speed, uint8_t isIgnoreStatusEffects); // 007e5340 - uint8_t MoveRandomly(uint8_t isIgnoreStatusEffects); // 007e6300 - void MoveRandomlyBoss(uint8_t isIgnoreStatusEffects); // 007e6650 - static void update_chase_movement(); // 007e6b90 - void UpdateGridIndex(); // 007e6ff0 - - uint8_t _pad_0x0[0x4]; - Vector _movementTarget; - uint8_t _pad_0xc[0x720]; - bool _hasDirectPath; - uint8_t _pad_0x72d[0xf]; - int _evadeMovementCountdown; -}; -LAYOUT32(offsetof(PathFinder, _movementTarget) == 0x4); -LAYOUT32(offsetof(PathFinder, _hasDirectPath) == 0x72c); -LAYOUT32(offsetof(PathFinder, _evadeMovementCountdown) == 0x73c); - struct PathNode { PathNode(void *other); // 007e48b0 PathNode() = default; @@ -3820,58 +3727,6 @@ struct ProceduralItem { }; LAYOUT32(offsetof(ProceduralItem, item) == 0x0); -struct ProjectileParams { - ProjectileParams(); // 0043ef30 - - bool GridCollision; - uint8_t _pad_0x1[0x3]; - float HeightModifier; - float FallingSpeedModifier; - float FallingAccelModifier; - float VelocityMulti; - float Scale; - float CircleAngle; - float HomingStrength; - float CurvingStrength; - float Acceleration; - float Spread; - ColorMod Color; - uint64_t BulletFlags; - Vector PositionOffset; - Vector TargetPosition; - Vector FireDirectionLimit; - float DotProductLimit; - int32_t WiggleFrameOffset; - uint64_t ChangeFlags; - float ChangeVelocity; - uint32_t ChangeTimeout; - float DepthOffset; - uint32_t Variant; -}; -LAYOUT32(offsetof(ProjectileParams, GridCollision) == 0x0); -LAYOUT32(offsetof(ProjectileParams, HeightModifier) == 0x4); -LAYOUT32(offsetof(ProjectileParams, FallingSpeedModifier) == 0x8); -LAYOUT32(offsetof(ProjectileParams, FallingAccelModifier) == 0xc); -LAYOUT32(offsetof(ProjectileParams, VelocityMulti) == 0x10); -LAYOUT32(offsetof(ProjectileParams, Scale) == 0x14); -LAYOUT32(offsetof(ProjectileParams, CircleAngle) == 0x18); -LAYOUT32(offsetof(ProjectileParams, HomingStrength) == 0x1c); -LAYOUT32(offsetof(ProjectileParams, CurvingStrength) == 0x20); -LAYOUT32(offsetof(ProjectileParams, Acceleration) == 0x24); -LAYOUT32(offsetof(ProjectileParams, Spread) == 0x28); -LAYOUT32(offsetof(ProjectileParams, Color) == 0x2c); -LAYOUT32(offsetof(ProjectileParams, BulletFlags) == 0x58); -LAYOUT32(offsetof(ProjectileParams, PositionOffset) == 0x60); -LAYOUT32(offsetof(ProjectileParams, TargetPosition) == 0x68); -LAYOUT32(offsetof(ProjectileParams, FireDirectionLimit) == 0x70); -LAYOUT32(offsetof(ProjectileParams, DotProductLimit) == 0x78); -LAYOUT32(offsetof(ProjectileParams, WiggleFrameOffset) == 0x7c); -LAYOUT32(offsetof(ProjectileParams, ChangeFlags) == 0x80); -LAYOUT32(offsetof(ProjectileParams, ChangeVelocity) == 0x88); -LAYOUT32(offsetof(ProjectileParams, ChangeTimeout) == 0x8c); -LAYOUT32(offsetof(ProjectileParams, DepthOffset) == 0x90); -LAYOUT32(offsetof(ProjectileParams, Variant) == 0x94); - struct Quad { void rotate(Vector *pivot, float angle); // 00a10760 void scale(Vector *pivot, Vector *scale); // 00a10950 @@ -6961,8 +6816,6 @@ void FUN_006a80d0(); // 006a80d0 void FUN_006a8180(uint32_t param_1); // 006a8180 void FUN_006a8210(int param_1); // 006a8210 uint32_t FUN_006ae7a0(); // 006ae7a0 -uint32_t FUN_006b2390(); // 006b2390 -uint8_t entity_collision_classes_match(Entity *a, Entity *b); // 006b2410 void spawn_gibs(Vector *position, int amount, float spread, uint32_t *gibFlags, Entity *spawner, ColorMod *color, Vector *velocity, float scale); // 006b31b0 void FUN_006b5de0(); // 006b5de0 void FUN_006b5f40(); // 006b5f40 @@ -6979,10 +6832,7 @@ uint8_t FUN_006b8490(); // 006b8490 void FUN_006b84c0(); // 006b84c0 void FUN_006b8580(); // 006b8580 Entity * spawn_gfuel_explosion(); // 006b9450 -void Entity_NPC_UpdateAI_dispatch(Entity_NPC *npc); // 006c2990 int FUN_006c4a90(); // 006c4a90 -void FUN_006d0370(uint32_t *param_1); // 006d0370 -void FUN_006d5350(); // 006d5350 void FUN_006d6650(); // 006d6650 uint8_t is_local_player_owned(void *self); // 006d8e10 uint32_t FUN_006da6f0(); // 006da6f0 @@ -6997,7 +6847,6 @@ void FUN_006daab0(); // 006daab0 void FUN_006dac00(uint32_t *param_1, uint32_t param_2); // 006dac00 float log_precise(float value); // 006dac30 void FUN_006daca0(uint32_t param_1); // 006daca0 -uint8_t Pickup_PickVariant(uint32_t seed, uint32_t *variant, uint32_t *subType, uint8_t isAdvancePools, uint8_t isShopItem); // 006ddcd0 uint32_t FUN_006e1910(uint32_t param_1); // 006e1910 void FUN_006e2ff0(int param_1); // 006e2ff0 void FUN_006ee330(); // 006ee330 @@ -7249,7 +7098,6 @@ uint32_t FUN_007ab0e0(); // 007ab0e0 void FUN_007ad610(); // 007ad610 uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2); // 007ad720 void FUN_007ae430(short *param_1); // 007ae430 -void FUN_007b0b40(uint16_t *param_1); // 007b0b40 void FUN_007b8c00(int param_1); // 007b8c00 void FUN_007b9a60(); // 007b9a60 void FUN_007b9aa0(); // 007b9aa0 @@ -7382,7 +7230,6 @@ void FUN_007ea0c0(); // 007ea0c0 void FUN_007ea5d0(); // 007ea5d0 void FUN_007ebc40(); // 007ebc40 uint32_t FUN_007ed240(); // 007ed240 -uint8_t entity_type_is_saved(int type, int variant, uint32_t subType, int spawnerType, uint8_t isRoomFlag); // 007eed10 float get_angel_room_chance(); // 007f96f0 void FUN_007fa2a0(float *param_1); // 007fa2a0 void FUN_007fa7d0(); // 007fa7d0 @@ -7647,9 +7494,7 @@ void FUN_00864fc0(uint32_t param_1); // 00864fc0 uint32_t Catch_0086504e(); // 0086504e void FUN_008650a0(uint32_t param_1); // 008650a0 uint32_t Catch_0086512e(); // 0086512e -void FUN_00865180(); // 00865180 uint32_t Catch_00865209(); // 00865209 -void FUN_00865260(); // 00865260 uint32_t Catch_008652e9(); // 008652e9 int lua_callback_run_get_card(RNG *rng, int card, uint8_t isPlaying, uint8_t isRunes, uint8_t isOnlyRunes); // 00865340 uint8_t * Catch_00865424(); // 00865424 @@ -9765,14 +9610,6 @@ int * FUN_00930a00(int param_1); // 00930a00 uint32_t FUN_00930b20(); // 00930b20 void FUN_00930ec0(); // 00930ec0 void FUN_00930ee0(char param_1); // 00930ee0 -void FUN_00931f50(uint32_t *param_1, int param_2); // 00931f50 -void FUN_00931fc0(uint32_t *param_1, uint32_t *param_2); // 00931fc0 -void FUN_00932020(uint32_t *param_1, int param_2); // 00932020 -void grid_rect_to_quad(float *outQuad, int x, int y, int width, int height); // 00932090 -Vector * backdrop_detail_to_world_pos(Vector *outPosition, Vector *position); // 0093b480 -uint32_t FUN_0093b530(); // 0093b530 -void backdrop_wall_normal(Vector *outNormal, int isVertical, uint8_t isNegX, uint8_t isNegY); // 0093b580 -void FUN_009426b0(uint32_t param_1, uint32_t param_2); // 009426b0 void FUN_00949b70(); // 00949b70 void FUN_00949bc0(uint32_t param_1); // 00949bc0 void FUN_0094e3b0(); // 0094e3b0 @@ -9792,7 +9629,6 @@ void save_rerun_to_steam_cloud(); // 00959180 void FUN_00959500(); // 00959500 void persistent_game_data_set_writable(); // 0095a680 void unlock_completion_mark_for_player_type(int markIndex, int playerType, int difficulty); // 0095aa30 -int controller_button_to_glyph_frame(int button); // 0095aba0 void render_online_icon(int frame, Vector position, float scaleX, float scaleY); // 0095ae60 void FUN_0095be60(int param_1, int param_2); // 0095be60 void FUN_0095be90(void *param_1, int param_2); // 0095be90 @@ -9863,7 +9699,6 @@ void FUN_009b9fc0(int param_1); // 009b9fc0 void FUN_009ba9a0(); // 009ba9a0 void FUN_009baa10(char param_1); // 009baa10 int FUN_009bac00(int param_1); // 009bac00 -uint32_t FUN_009be9c0(); // 009be9c0 void entity_vector_set_flag_410(void *self, uint8_t value); // 009bea10 void FUN_009bfc00(); // 009bfc00 void FUN_009bfc20(); // 009bfc20 @@ -21981,8 +21816,6 @@ void ENTITY_DUSTY_DEATHS_HEAD(Entity_NPC *npc); // 00504a40 void ENTITY_NECRO(Entity_NPC *npc); // 005052a0 void ENTITY_STONE_EYE(Entity_NPC *npc); // 00505d00 void ENTITY_CONSTANT_STONE_SHOOTER(Entity_NPC *npc); // 00506320 -void ENTITY_FLY(Entity_NPC *npc); // 00506bd0 -void ENTITY_GAPER(Entity_NPC *npc); // 00508f40 void ENTITY_EMBRYO(Entity_NPC *npc); // 0050a6b0 void ENTITY_ETERNALFLY(Entity_NPC *npc); // 0050a8a0 void ENTITY_GUSHER(Entity_NPC *npc); // 0050af90 @@ -21994,7 +21827,6 @@ uint32_t ENTITY_BOOMFLY(Entity_NPC *npc); // 0050f280 void ENTITY_MAW(Entity_NPC *npc); // 00510ae0 Entity * ENTITY_HOST(Entity_NPC *npc); // 005111b0 void ENTITY_BRAIN(Entity_NPC *npc); // 00512110 -void ENTITY_HORF(Entity_NPC *npc); // 00513080 void ENTITY_KNIGHT(Entity_NPC *npc); // 005135d0 uint32_t * ENTITY_GUTS(Entity_NPC *npc); // 005153b0 void ENTITY_BOIL(Entity_NPC *npc); // 00517150 @@ -22026,7 +21858,6 @@ void ENTITY_BABY_LONG_LEGS(Entity_NPC *npc); // 00531ab0 void ENTITY_MOBILE_HOST(Entity_NPC *npc); // 005321d0 void ENTITY_DEATHS_HEAD(Entity_NPC *npc); // 00532cf0 void ENTITY_MOMS_HAND(Entity_NPC *npc); // 00533b80 -void ENTITY_DIP(Entity_NPC *npc); // 00534860 Entity * ENTITY_SQUIRT(Entity_NPC *npc); // 00535280 void ENTITY_SWINGER(Entity_NPC *npc); // 00536d00 void ENTITY_WIZOOB(Entity_NPC *npc); // 005374a0 diff --git a/generated-src/entity_save_state.cpp b/generated-src/entity_save_state.cpp deleted file mode 100644 index 01730a1..0000000 --- a/generated-src/entity_save_state.cpp +++ /dev/null @@ -1,122 +0,0 @@ -#include "classes.h" - -// 004d3080 -void EntitySaveState::constructor() -{ - *GHIDRA_CAST(this) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[10])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0xc)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 4)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[5])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[6])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 8)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[9])) + 0x1)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xd])) + 0x1)))) = g_vectorZero.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xe])) + 0x2)))) = g_vectorZero.y; - *GHIDRA_CAST((this + 0x10)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x11])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x12])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x14)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1e])) + 0x2)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x21])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x22])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x24)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x25])) + 0x1)))) = 0; - *GHIDRA_CAST((this + 0x18)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x19])) + 0x1)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a])) + 0x2)))) = 0x42700000; - *GHIDRA_CAST((this + 0x1c)) = 0x3f800000; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1d])) + 0x1)))) = 0x3f800000; - *GHIDRA_CAST((this + 0x20)) = 1; - return; -} - -// 004d3130 -void EntitySaveState::copy(void *other) -{ - uint32_t uVar1; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - - local_8 = 0xffffffff; - puStack_c = &LAB_00af3840; - local_10 = ExceptionList; - ExceptionList = &local_10; - *GHIDRA_CAST(this) = *GHIDRA_CAST(other); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 4)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 8)); - *GHIDRA_CAST((this + 4)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0xc)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[5])) + 0x1)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x10)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[6])) + 0x2)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x14)); - *GHIDRA_CAST((this + 8)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x18)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[9])) + 0x1)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x1c)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[10])) + 0x2)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x20)); - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0xb])) + 0x1))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x22)); - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0xb])) + 0x2))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x23)); - *GHIDRA_CAST((this + 0xc)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x24)); - uVar1 = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x2c)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xd])) + 0x1)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x28)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xe])) + 0x2)))) = uVar1; - *GHIDRA_CAST((this + 0x10)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x30)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x11])) + 0x1)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x34)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x12])) + 0x2)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x38)); - *GHIDRA_CAST((this + 0x14)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x3c)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15])) + 0x1)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x40)); - uVar1 = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x4c)); - *GHIDRA_CAST((this + 0x18)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x48)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x19])) + 0x1)))) = uVar1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a])) + 0x2)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x50)); - *GHIDRA_CAST((this + 0x1c)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x54)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1d])) + 0x1)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x58)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1e])) + 0x2)))) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x5c)); - *GHIDRA_CAST((this + 0x20)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x60)); - FUN_004d7250(GHIDRA_INT(other) + 100); - local_8 = 0; - FUN_004d7190(GHIDRA_INT(other) + 0x6c); - ExceptionList = local_10; - return; -} - -// 00827f70 -void EntitySaveState::set_extra_data(uint32_t param_1) -{ - char isLastReference; - uint32_t uVar1; - ReferenceCountBase *extraDataRef; - uint32_t *in_ECX; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - - local_8 = 0xffffffff; - puStack_c = &LAB_00af0d44; - local_10 = ExceptionList; - uVar1 = __security_cookie ^ GHIDRA_INT(register0x00000010) - 4U; - ExceptionList = &local_10; - extraDataRef = operator_new(0x18); - local_8 = 0; - if (extraDataRef == GHIDRA_CAST(0x0)) { - extraDataRef = GHIDRA_CAST(0x0); - } - else { - (GHIDRA_CAST((extraDataRef)))->ReferenceCountBase::ReferenceCountBase(); - *GHIDRA_CAST(extraDataRef) = - ReferenceCount::vftable; - *GHIDRA_CAST((extraDataRef + 0x14)) = param_1; - } - local_8 = 0xffffffff; - if (GHIDRA_CAST(in_ECX[1]) != GHIDRA_CAST(0x0)) { - isLastReference = (**(code **)(*GHIDRA_CAST(in_ECX[1]) + 0xc))(uVar1); - if ((isLastReference != '\0') && (g_entitySaveStateExtraDataReleaseFn != (void *)0x0)) { - (*g_entitySaveStateExtraDataReleaseFn)(); - } - } - in_ECX[1] = extraDataRef; - *in_ECX = param_1; - ExceptionList = local_10; - return; -} diff --git a/generated-src/game_state_player.cpp b/generated-src/game_state_player.cpp deleted file mode 100644 index 54c62ae..0000000 --- a/generated-src/game_state_player.cpp +++ /dev/null @@ -1,2755 +0,0 @@ -#include "classes.h" - -// 00754d90 -GameStatePlayer::~GameStatePlayer() -{ - uint8_t *tree; - void *ptr; - - tree = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1f1])) + 0x1))); - FID_conflict__Erase_tree_>_> - (tree,(fuzzer_allocator_> *)tree, - *(_Tree_node **)(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1f1])) + 0x1)))) + 4)); - operator_delete(*(void **)tree,0x18); - msvc::vector<52byte>::_Tidy(); - FUN_004b3950(); - FID_conflict__Tidy(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1aa])) + 0x2)))); - FUN_007dcd30(); - FUN_007dcd30(); - FUN_007dcd30(); - msvc::deque::_Tidy(); - ptr = *(void **)(this + 400); - *GHIDRA_CAST((this + 400)) = 0; - operator_delete(ptr,8); - FID_conflict__Tidy(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x161])) + 0x1)))); - FUN_004b3950(); - msvc::vector<28byte>::_Tidy(); - msvc::vector<28byte>::_Tidy(); - msvc::vector<52byte>::_Tidy(); - msvc::vector::_Tidy(); - msvc::vector::_Tidy(); - FID_conflict__Tidy(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x96])) + 0x2)))); - FID_conflict__Tidy(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x92])) + 0x2)))); - FID_conflict__Tidy(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x8e])) + 0x2)))); - FID_conflict__Tidy(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x8a])) + 0x2)))); - FID_conflict__Tidy(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x86])) + 0x2)))); - msvc::vector::_Tidy(); - FID_conflict__Tidy(this + 0x7c); - FID_conflict__Tidy(this + 0x78); - return; -} - -// 009c86e0 -void GameStatePlayer::read_player_key(void *stream) -{ - void *srcStream; - - srcStream = stream; - (**(code **)(**GHIDRA_CAST(stream) + 0x14))(this,4,1); - stream = *(void **)this; - Checksum::Update((void *)(GHIDRA_INT(srcStream) + 0xc),GHIDRA_CAST(&stream),4); - stream = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1))); - if (*GHIDRA_CAST(this) == -0x80000000) { - (**(code **)(**GHIDRA_CAST(srcStream) + 0x14))(); - stream = *(void **)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1))); - Checksum::Update((void *)(GHIDRA_INT(srcStream) + 0xc),GHIDRA_CAST(&stream),4); - (**(code **)(**GHIDRA_CAST(srcStream) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2))),2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2))))); - Checksum::Update((void *)(GHIDRA_INT(srcStream) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(srcStream) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[3])) + 0x1))),2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[3])) + 0x1))))); - Checksum::Update((void *)(GHIDRA_INT(srcStream) + 0xc),GHIDRA_CAST(&stream),2); - return; - } - (**(code **)(**GHIDRA_CAST(srcStream) + 0x14))(stream,4,1); - stream = *(void **)stream; - Checksum::Update((void *)(GHIDRA_INT(srcStream) + 0xc),GHIDRA_CAST(&stream),4); - (**(code **)(**GHIDRA_CAST(srcStream) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2))),4,1); - stream = *(void **)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2))); - Checksum::Update((void *)(GHIDRA_INT(srcStream) + 0xc),GHIDRA_CAST(&stream),4); - return; -} - -// 009cf050 -void GameStatePlayer::Init() -{ - uint8_t *puVar1; - int *piVar2; - void *owner; - void *pvVar3; - void *pvVar4; - uint32_t uVar5; - int iVar6; - void *local_3c; - uint32_t local_38; - int *tmpListHead; - void *tmpDequeMap; - int tmpDequeMapSize; - uint32_t tmpDequeOffset; - int tmpDequeSize; - uint32_t uStack_1c; - GameStatePlayer *memberField; - uint32_t oldDequeOffset; - int oldDequeSize; - - *GHIDRA_CAST(this) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 4)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[5])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[6])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 8)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[9])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[10])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0xc)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xd])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xe])) + 0x2)))) = 0x30000; - *GHIDRA_CAST((this + 0x10)) = 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0x10])) + 0x2))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x11])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x12])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x18)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x19])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x1c)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1d])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1e])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x20)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x21])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x22])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x24)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x25])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x26])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x28)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x29])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x2a])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x2c)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x2d])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x2e])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x30)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x31])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x32])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x34)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x36])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x38)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x39])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x3a])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x3c)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x3e])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x40)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x41])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x42])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x44)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x46])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x48)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x49])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x4a])) + 0x2)))) = 0; - tmpDequeSize = 0; - uStack_1c = 0; - *GHIDRA_CAST((this + 0x4c)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x4e])) + 0x2)))) = g_vectorOne.x; - *GHIDRA_CAST((this + 0x50)) = g_vectorOne.y; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x51])) + 0x1)))) = g_vectorOne.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x52])) + 0x2)))) = g_vectorOne.y; - *GHIDRA_CAST((this + 0x54)) = g_vectorOne.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x55])) + 0x1)))) = g_vectorOne.y; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xad])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xae])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x118)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x119])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x11a])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x11c)) = 0; - *GHIDRA_CAST((this + 0xb0)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xb9])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x122])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x124)) = 0; - *GHIDRA_CAST((this + 0x14)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x16])) + 0x2)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x126])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x128)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x11d])) + 0x1)))) = 0x3f800000; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x121])) + 0x1)))) = 0x3f800000; - *GHIDRA_CAST((this + 0x120)) = 0x3f800000; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x11e])) + 0x2)))) = 0x3f800000; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x56])) + 0x2)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x59])) + 0x1)))) = 0; - *GHIDRA_CAST((this + 0x58)) = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x5a])) + 0x2)))) = 1; - *GHIDRA_CAST((this + 0x5c)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x5d])) + 0x1)))) = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x5e])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x60)) = 1; - memset(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x61])) + 0x1))),0,0x44); - memberField = this + 0x78; - if (GHIDRA_CAST(&local_3c) != memberField) { - pvVar4 = *(void **)memberField; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x7a])) + 0x2)))); - *GHIDRA_CAST(memberField) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x79])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x7a])) + 0x2)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffffc; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - memberField = this + 0x7c; - if (GHIDRA_CAST(&local_3c) != memberField) { - pvVar4 = *(void **)memberField; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x7e])) + 0x2)))); - *GHIDRA_CAST(memberField) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x7d])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x7e])) + 0x2)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffffc; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - memberField = this + 0x80; - if (GHIDRA_CAST(&local_3c) != memberField) { - pvVar4 = *(void **)memberField; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x82])) + 0x2)))); - *GHIDRA_CAST(memberField) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x81])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x82])) + 0x2)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffff8; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - memberField = this + 0xa0; - if (GHIDRA_CAST(&local_3c) != memberField) { - pvVar4 = *(void **)memberField; - local_3c = *(void **)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xa2])) + 0x2))); - pvVar3 = *(void **)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xa1])) + 0x1))); - *GHIDRA_CAST(memberField) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xa1])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0xa2])) + 0x2)))) = 0; - owner = pvVar4; - if (pvVar4 != (void *)0x0) { - for (; owner != pvVar3; owner = (void *)(GHIDRA_INT(owner) + 0x78)) { - invoke_pending_callbacks(owner); - } - uVar5 = ((GHIDRA_INT(local_3c) - GHIDRA_INT(pvVar4)) / 0x78) * 0x78; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - memberField = this + 0x9c; - *GHIDRA_CAST((this + 0x84)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x9a])) + 0x2)))) = 0; - if (GHIDRA_CAST(&local_3c) != memberField) { - pvVar4 = *(void **)memberField; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x9e])) + 0x2)))); - *GHIDRA_CAST(memberField) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x9d])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x9e])) + 0x2)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffff8; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x86])) + 0x2))); - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x89])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x88)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x89])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffffc; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x8a])) + 0x2))); - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x8d])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x8c)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x8d])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffffc; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x8e])) + 0x2))); - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x91])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x90)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x91])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffffc; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x92])) + 0x2))); - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x95])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x94)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x95])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffffc; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x96])) + 0x2))); - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x99])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x98)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x99])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffffc; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x12a])) + 0x2))); - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x12d])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 300)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x12d])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = ((iVar6 - GHIDRA_INT(pvVar4)) / 0x34) * 0x34; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x12e])) + 0x2))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x129])) + 0x1)))) = 0; - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x131])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x130)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x131])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = ((iVar6 - GHIDRA_INT(pvVar4)) / 0x1c) * 0x1c; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0x132])) + 0x2))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x13d])) + 0x1)))) = 0; - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x13e])) + 0x2))); - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x141])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x140)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x141])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = ((iVar6 - GHIDRA_INT(pvVar4)) / 0x1c) * 0x1c; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x161])) + 0x1))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x142])) + 0x2)))) = 0xffffffff; - *GHIDRA_CAST((this + 0x144)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x145])) + 0x1)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x146])) + 0x2)))) = 0xffffffff; - *GHIDRA_CAST((this + 0x148)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x149])) + 0x1)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x14a])) + 0x2)))) = 0xffffffff; - *GHIDRA_CAST((this + 0x14c)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x14d])) + 0x1)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x14e])) + 0x2)))) = 0xffffffff; - *GHIDRA_CAST((this + 0x150)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x151])) + 0x1)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x152])) + 0x2)))) = 0xffffffff; - *GHIDRA_CAST((this + 0x154)) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x155])) + 0x1)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x156])) + 0x2)))) = 0xffffffff; - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST((this + 0x164)); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x162])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x164)) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffffc; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x165])) + 0x1)))) = 0; - *GHIDRA_CAST((this + 0x168)) = 0; - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1b2])) + 0x2))); - *GHIDRA_CAST((this + 0x124)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x169])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x16a])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x16c)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x16d])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x166])) + 0x2)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x172])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x174)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x175])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x176])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x178)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x17a])) + 0x2)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x16e])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x170)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x171])) + 0x1)))) = 0; - *GHIDRA_CAST((this + 0x17c)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x17d])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x17e])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x180)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x181])) + 0x1)))) = 0; - *GHIDRA_CAST((this + 0x184)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x185])) + 0x1)))) = 0; - *GHIDRA_CAST((this + 0x188)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x182])) + 0x2)))) = 0xc61c3c00; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x186])) + 0x2)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x189])) + 0x1)))) = 0xfffe7961; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x18a])) + 0x2)))) = g_vectorZero.x; - *GHIDRA_CAST((this + 0x18c)) = g_vectorZero.y; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x18d])) + 0x1)))) = 0xffffffff; - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1b5])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x1b4)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1b5])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffff0; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1b6])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x1b8)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1b9])) + 0x1)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ba])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x1bc)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x18e])) + 0x2)))) = 0; - tmpDequeMap = (void *)0x0; - tmpDequeMapSize = 0; - tmpDequeOffset = 0; - tmpDequeSize = 0; - tmpListHead = operator_new(8); - memberField = this + 400; - tmpListHead[1] = 0; - *tmpListHead = GHIDRA_INT(&tmpListHead); - if (GHIDRA_CAST(&tmpListHead) != memberField) { - piVar2 = *GHIDRA_CAST(memberField); - *GHIDRA_CAST(memberField) = tmpListHead; - if (piVar2 != GHIDRA_CAST(0x0)) { - *piVar2 = GHIDRA_INT(&tmpListHead); - tmpListHead = *GHIDRA_CAST(memberField); - } - if (tmpListHead != GHIDRA_CAST(0x0)) { - *tmpListHead = GHIDRA_INT(memberField); - } - pvVar4 = *(void **)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x191])) + 0x1))); - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x192])) + 0x2)))); - *(void **)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x191])) + 0x1))) = tmpDequeMap; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x192])) + 0x2)))) = tmpDequeMapSize; - oldDequeOffset = *GHIDRA_CAST((this + 0x194)); - *GHIDRA_CAST((this + 0x194)) = tmpDequeOffset; - oldDequeSize = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x195])) + 0x1)))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x195])) + 0x1)))) = tmpDequeSize; - tmpListHead = piVar2; - tmpDequeMap = pvVar4; - tmpDequeMapSize = iVar6; - tmpDequeOffset = oldDequeOffset; - tmpDequeSize = oldDequeSize; - } - pvVar4 = tmpDequeMap; - iVar6 = tmpDequeMapSize; - if (tmpDequeSize != 0) { - do { - tmpDequeSize = tmpDequeSize + -1; - local_3c = (void *)0x0; - } while (tmpDequeSize != 0); - tmpDequeOffset = 0; - tmpDequeSize = 0; - } - while (iVar6 != 0) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + iVar6 * 4 + -4); - iVar6 = iVar6 + -1; - if (pvVar3 != (void *)0x0) { - operator_delete(pvVar3,0x10); - pvVar4 = tmpDequeMap; - } - } - if (pvVar4 != (void *)0x0) { - uVar5 = tmpDequeMapSize * 4; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - piVar2 = tmpListHead; - tmpDequeMapSize = 0; - tmpDequeMap = (void *)0x0; - tmpListHead = GHIDRA_CAST(0x0); - operator_delete(piVar2,8); - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x196])) + 0x2))); - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x199])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x198)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x199])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4); - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x19e])) + 0x2))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x19a])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x19c)) = 0xffffffff; - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a1])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x1a0)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a1])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4); - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a2])) + 0x2))); - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a5])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x1a4)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a5])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4); - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1aa])) + 0x2))); - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a6])) + 0x2))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x19d])) + 0x1)))) = 0; - *GHIDRA_CAST((this + 0x1a8)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1a9])) + 0x1)))) = 0; - if (&local_3c != (void **)puVar1) { - pvVar4 = *(void **)puVar1; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ad])) + 0x1)))); - *GHIDRA_CAST(puVar1) = 0; - *GHIDRA_CAST((this + 0x1ac)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ad])) + 0x1)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = iVar6 - GHIDRA_INT(pvVar4) & 0xfffffffc; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) goto LAB_009cff2f; - } - operator_delete(pvVar3,uVar5); - } - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ae])) + 0x2)))) = 0; - memberField = this + 0x1c8; - *GHIDRA_CAST((this + 0x1b0)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1b1])) + 0x1)))) = 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1bc])) + 0x1))) = 0; - if (GHIDRA_CAST(&local_3c) != memberField) { - pvVar4 = *(void **)memberField; - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ca])) + 0x2)))); - *GHIDRA_CAST(memberField) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1c9])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ca])) + 0x2)))) = 0; - if (pvVar4 != (void *)0x0) { - uVar5 = ((iVar6 - GHIDRA_INT(pvVar4)) / 0x34) * 0x34; - pvVar3 = pvVar4; - if (0xfff < uVar5) { - pvVar3 = *(void **)(GHIDRA_CAST(pvVar4) + -4); - uVar5 = uVar5 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(pvVar4) + (-4 - GHIDRA_INT(pvVar3))))) { -LAB_009cff2f: - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pvVar3,uVar5); - } - } - *GHIDRA_CAST((this + 0x1cc)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1cd])) + 0x1)))) = 0; - *GHIDRA_CAST((this + 0x1d0)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ce])) + 0x2)))) = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1d1])) + 0x1)))) = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1d2])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x1d4)) = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1d5])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1d6])) + 0x2)))) = 1; - *GHIDRA_CAST((this + 0x1d8)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1d9])) + 0x1)))) = 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1da])) + 0x2))) = 0; - *GHIDRA_CAST((this + 0x1dc)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1de])) + 0x2)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1dd])) + 0x1)))) = 1; - *GHIDRA_CAST((this + 0x1e0)) = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1e1])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1e2])) + 0x2)))) = 1; - *GHIDRA_CAST((this + 0x1e4)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1e5])) + 0x1)))) = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1e6])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x1e8)) = 0; - (*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1e9])) + 0x1))) = 0xff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ea])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x1ec)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ed])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1ee])) + 0x2)))) = 0; - *GHIDRA_CAST((this + 0x1f0)) = 0; - local_38 = 0; - pvVar4 = operator_new(0x18); - puVar1 = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1f1])) + 0x1))); - *(void **)pvVar4 = pvVar4; - *(void **)(GHIDRA_CAST(pvVar4) + 4) = pvVar4; - *(void **)(GHIDRA_CAST(pvVar4) + 8) = pvVar4; - *GHIDRA_CAST((GHIDRA_CAST(pvVar4) + 0xc)) = 0x101; - local_3c = pvVar4; - if (&local_3c != (void **)puVar1) { - local_3c = *(void **)puVar1; - *(void **)puVar1 = pvVar4; - oldDequeOffset = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1f2])) + 0x2)))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x1f2])) + 0x2)))) = local_38; - local_38 = oldDequeOffset; - } - FID_conflict__Erase_tree_>_> - (&local_3c,(fuzzer_allocator_> *)&local_3c, - *(_Tree_node **)(GHIDRA_INT(local_3c) + 4)); - operator_delete(local_3c,0x18); - memberField = this + 0x15c; - *GHIDRA_CAST((this + 0x124)) = 0; - *GHIDRA_CAST((this + 0x158)) = 0; - if (GHIDRA_CAST(&local_3c) != memberField) { - iVar6 = *GHIDRA_CAST(memberField); - oldDequeSize = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15e])) + 0x2)))); - *GHIDRA_CAST(memberField) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15d])) + 0x1)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[0x15e])) + 0x2)))) = 0; - if (iVar6 != 0) { - FUN_005cbf50(iVar6,oldDequeSize - iVar6 >> 4); - } - } - *GHIDRA_CAST((this + 0x160)) = 0; - return; -} - -// 009cff40 -uint8_t GameStatePlayer::read_coplayer(short *block, void *stream) -{ - void *pvVar1; - - pvVar1 = stream; - (**(code **)(**GHIDRA_CAST(stream) + 0x14))(block,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)*block); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 1,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)block[1]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 2,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)block[2]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 3,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)block[3]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 4,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)block[4]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 5,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)block[5]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 6,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)block[6]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 7,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)block[7]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 10,4,1); - stream = *(void **)(block + 10); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),4); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 0xc,4,1); - stream = *(void **)(block + 0xc); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),4); - if (0x91 < *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 8))) { - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 9,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)block[9]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(block + 8,2,1); - stream = (void *)GHIDRA_UINT((uint16_t)block[8]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&stream),2); - } - return 1; -} - -// 009d0100 -void GameStatePlayer::write_coplayer(void *stream) -{ - void *writer; - - writer = stream; - (**(code **)(**GHIDRA_CAST(stream) + 0x1c))(this,2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST(this)); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x2))),2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x2))))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1))),2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1))))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(this + 2,2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST((this + 2))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2))),2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[2])) + 0x2))))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[3])) + 0x1))),2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[3])) + 0x1))))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(this + 4,2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST((this + 4))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[4])) + 0x2))),2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[4])) + 0x2))))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[6])) + 0x2))),4,1); - stream = *(void **)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[6])) + 0x2))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),4); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(this + 8,4,1); - stream = *(void **)(this + 8); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),4); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(this + 6,2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST((this + 6))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - (**(code **)(**GHIDRA_CAST(writer) + 0x1c))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[5])) + 0x1))),2,1); - stream = (void *)GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[5])) + 0x1))))); - Checksum::Update((void *)(GHIDRA_INT(writer) + 0xc),GHIDRA_CAST(&stream),2); - return; -} - -// 009d02c0 -void GameStatePlayer::read_block_538(uint32_t *block, void *stream) -{ - void *pvVar1; - uint32_t checksumValue; - uint16_t value [2]; - uint8_t flagsByte [4]; - - pvVar1 = stream; - (**(code **)(**GHIDRA_CAST(stream) + 0x14))(value,2,1); - checksumValue = GHIDRA_UINT(value[0]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - *block = GHIDRA_UINT(value[0]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(value,2,1); - checksumValue = GHIDRA_UINT(value[0]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - block[1] = GHIDRA_UINT(value[0]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(value,2,1); - checksumValue = GHIDRA_UINT(value[0]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - block[2] = GHIDRA_UINT(value[0]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(GHIDRA_INT(&stream) + 3,1,1); - flagsByte[0] = (*GHIDRA_CAST((GHIDRA_CAST(&(stream)) + 0x3))); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),flagsByte,1); - *GHIDRA_CAST((block + 3)) = (*GHIDRA_CAST((GHIDRA_CAST(&(stream)) + 0x3))) & 1; - *GHIDRA_CAST((GHIDRA_CAST(block) + 0xd)) = (*GHIDRA_CAST((GHIDRA_CAST(&(stream)) + 0x3))) >> 1 & 1; - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(value,2,1); - checksumValue = GHIDRA_UINT(value[0]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - block[4] = GHIDRA_UINT(value[0]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(value,2,1); - checksumValue = GHIDRA_UINT(value[0]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - block[5] = GHIDRA_UINT(value[0]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(value,2,1); - checksumValue = GHIDRA_UINT(value[0]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - block[6] = GHIDRA_UINT(value[0]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x14))(value,2,1); - checksumValue = GHIDRA_UINT(value[0]); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - block[7] = GHIDRA_UINT(value[0]); - return; -} - -// 009d0440 -void GameStatePlayer::write_block_538(short *block, void *stream) -{ - void *pvVar1; - void *pvVar2; - bool isFlagC; - uint32_t checksumValue; - uint32_t value; - uint8_t packedByte [4]; - - pvVar1 = stream; - value = GHIDRA_UINT((uint16_t)*block); - (**(code **)(**GHIDRA_CAST(stream) + 0x1c))(&value,2,1); - checksumValue = value & 0xffff; - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - value = GHIDRA_UINT((uint16_t)block[2]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x1c))(&value,2,1); - checksumValue = value & 0xffff; - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - value = GHIDRA_UINT((uint16_t)block[4]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x1c))(&value,2,1); - checksumValue = value & 0xffff; - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - pvVar2 = stream; - stream = (void *)(GHIDRA_UINT(stream) & 0xffffff); - isFlagC = (char)block[6] != '\0'; - if (isFlagC) { - (*GHIDRA_CAST((GHIDRA_CAST(&(stream)) + 0x0))) = SUB43(pvVar2,0); - stream = (void *)CONCAT13(1,(*GHIDRA_CAST((GHIDRA_CAST(&(stream)) + 0x0)))); - } - if (*GHIDRA_CAST((GHIDRA_CAST(block) + 0xd)) != '\0') { - stream = (void *)(CONCAT13(isFlagC,(*GHIDRA_CAST((GHIDRA_CAST(&(stream)) + 0x0)))) | 0x2000000); - } - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x1c))(GHIDRA_INT(&stream) + 3,1,1); - packedByte[0] = (*GHIDRA_CAST((GHIDRA_CAST(&(stream)) + 0x3))); - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),packedByte,1); - value = GHIDRA_UINT((uint16_t)block[8]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x1c))(&value,2,1); - checksumValue = value & 0xffff; - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - value = GHIDRA_UINT((uint16_t)block[10]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x1c))(&value,2,1); - checksumValue = value & 0xffff; - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - value = GHIDRA_UINT((uint16_t)block[0xc]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x1c))(&value,2,1); - checksumValue = value & 0xffff; - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - value = GHIDRA_UINT((uint16_t)block[0xe]); - (**(code **)(**GHIDRA_CAST(pvVar1) + 0x1c))(&value,2,1); - checksumValue = value & 0xffff; - Checksum::Update((void *)(GHIDRA_INT(pvVar1) + 0xc),GHIDRA_CAST(&checksumValue),2); - return; -} - -// 009d05d0 -uint8_t GameStatePlayer::read(void *reader) -{ - short sVar1; - uint8_t bVar2; - GameStatePlayer **data; - ItemConfig_Item *collectibleConfig; - uint32_t *puVar3; - void *pvVar4; - GameStatePlayer *pGVar5; - int *piVar6; - GameStatePlayer *shortField; - int iVar7; - uint32_t uVar8; - char *format; - uint32_t uVar9; - uint32_t uStack_120; - void *intVector; - int intVectorEnd; - int local_8c; - uint8_t *pocketSlotCount; - uint32_t *pocketSlot; - uint8_t local_5c [4]; - void *checksum; - GameStatePlayer *local_54; - GameStatePlayer *local_50; - GameStatePlayer *local_4c; - uint16_t checksumByte; - uint8_t readByte; - void *local_44; - uint16_t readShort [3]; - uint8_t packedFlags; - void *local_38; - GameStatePlayer *playerState; - char pocketType; - GameStatePlayer *local_2c [2]; - uint8_t *puStack_24; - uint8_t *local_20; - void *local_1c; - uint8_t *puStack_18; - GameStatePlayer *local_14; - - puStack_24 = GHIDRA_CAST((local_2c + 10)); - local_14 = GHIDRA_CAST(0xffffffff); - puStack_18 = &LAB_00b0f39e; - local_1c = ExceptionList; - uStack_120 = __security_cookie ^ GHIDRA_UINT((local_2c + 7)); - local_20 = GHIDRA_CAST(&uStack_120); - ExceptionList = &local_1c; - uVar9 = 4; - playerState = this; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(this,4,1); - local_2c[0] = *GHIDRA_CAST(this); - checksum = (void *)(GHIDRA_INT(reader) + 0xc); - local_44 = checksum; - local_38 = checksum; - Checksum::Update(checksum,GHIDRA_CAST(local_2c),4); - if (((*GHIDRA_CAST(this) < 0) || - ((GHIDRA_INT((g_manager->_entityConfig)._players._end) - - GHIDRA_INT((g_manager->_entityConfig)._players._begin)) / 0x148 <= *GHIDRA_CAST(this))) || - ((void *)(*GHIDRA_CAST(this) * 0x148 + GHIDRA_INT((g_manager->_entityConfig)._players._begin)) == - (void *)0x0)) { - format = "[warn] Invalid player type: %d\n"; - goto LAB_009d4590; - } - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 2; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 4; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 5; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 6; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 8; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 9; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 10; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0xc; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0xd; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0xe; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),1,1); - (*GHIDRA_CAST((GHIDRA_CAST(&(checksumByte)) + 0x0))) = (*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(&checksumByte),1); - shortField = playerState + 0xf; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,1,1); - checksumByte = CONCAT11((*GHIDRA_CAST((GHIDRA_CAST(&(checksumByte)) + 0x1))),*GHIDRA_CAST(shortField)); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(&checksumByte),1); - shortField = playerState; - if (*GHIDRA_CAST((GHIDRA_CAST(reader) + 8)) < 0x82) { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&local_4c,4,1); - local_2c[0] = local_4c; - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0xf])) + 0x1)))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_4c)) + 0x0))); - *GHIDRA_CAST((shortField + 0x10)) = 0; - } - else { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(playerState[0xf])) + 0x1))),2,1); - local_2c[0] = GHIDRA_CAST(GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0xf])) + 0x1)))))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),2); - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField + 0x10,2,1); - local_2c[0] = GHIDRA_CAST(GHIDRA_UINT(*GHIDRA_CAST((shortField + 0x10)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),2); - } - if (*GHIDRA_CAST((GHIDRA_CAST(reader) + 8)) < 0x79) { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x10])) + 0x2))),1,1); - checksumByte = CONCAT11((*GHIDRA_CAST((GHIDRA_CAST(&(checksumByte)) + 0x1))),(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x10])) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(&checksumByte),1); - } - else { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&packedFlags,1,1); - checksumByte = CONCAT11((*GHIDRA_CAST((GHIDRA_CAST(&(checksumByte)) + 0x1))),packedFlags); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(&checksumByte),1); - (*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x10])) + 0x2))) = packedFlags & 1; - *GHIDRA_CAST((shortField + 0x1bc)) = packedFlags >> 1 & 1; - (*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x1bc])) + 0x1))) = packedFlags >> 2 & 1; - } - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - if (uVar8 < 0x4d) { - if (0x23 < uVar8) { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&local_4c,4,1); - local_2c[0] = local_4c; - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x11])) + 0x1)))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_4c)) + 0x0))); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - } - if (0x39 < uVar8) { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&local_4c,4,1); - local_2c[0] = local_4c; - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x12])) + 0x2)))) = (*GHIDRA_CAST((GHIDRA_CAST(&(local_4c)) + 0x0))); - } - } - else { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x11])) + 0x1))),2,1); - local_2c[0] = GHIDRA_CAST(GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x11])) + 0x1)))))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),2); - shortField = playerState + 0x12; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,2,1); - local_2c[0] = GHIDRA_CAST(GHIDRA_UINT(*GHIDRA_CAST(shortField))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),2); - shortField = playerState + 0x12; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),2,1); - local_2c[0] = GHIDRA_CAST(GHIDRA_UINT(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),2); - shortField = playerState; - } - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - if (0x24 < uVar8) { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField + 0x14,4,1); - local_2c[0] = *GHIDRA_CAST((shortField + 0x14)); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - } - if (0xa4 < uVar8) { - shortField = playerState + 0x15; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - } - if (0x2c < uVar8) { - shortField = playerState + 0x16; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - } - if (uVar8 < 0x3e) { - if (0x3a < uVar8) { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(local_2c,4,1); - local_4c = local_2c[0]; - data = &local_4c; - goto LAB_009d0b19; - } - } - else { - shortField = playerState + 0x126; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x128; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - data = local_2c; -LAB_009d0b19: - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(data),4); - } - shortField = playerState + 0x18; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x19; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x1a; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x1c; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x1d; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x1e; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x20; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState; - if (0x27 < *GHIDRA_CAST((GHIDRA_CAST(reader) + 8))) { - if (*GHIDRA_CAST((GHIDRA_CAST(reader) + 8)) < 0x45) { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&local_4c,4,1); - local_2c[0] = local_4c; - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x21])) + 0x1)))) = GHIDRA_INT(((float)local_4c / 0.2)); - } - else { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(playerState[0x21])) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x21])) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - if (0xa5 < *GHIDRA_CAST((GHIDRA_CAST(reader) + 8))) { - FUN_009d84a0(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x22])) + 0x2)))); - } - } - } - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField + 0x24,4,1); - local_2c[0] = *GHIDRA_CAST((shortField + 0x24)); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x25; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x26; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x28; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x29; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x2a; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x2c; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - if (0x37 < uVar8) { - shortField = playerState + 0x2d; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - } - local_54 = GHIDRA_CAST(&DAT_00000004); - if (uVar8 < 0x3c) { - local_54 = GHIDRA_CAST(0x1); - } - else if (uVar8 < 0x66) { - local_54 = GHIDRA_CAST(0x2); - } - else if (uVar8 < 0x71) { - local_54 = GHIDRA_CAST(0x3); - } - local_50 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(playerState[0x2e])) + 0x2)))); - local_4c = GHIDRA_CAST(0x0); - do { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(local_50,4,1); - local_2c[0] = *GHIDRA_CAST(local_50); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - if ((0 < *GHIDRA_CAST(local_50)) && - (collectibleConfig = ItemConfig::GetCollectible(&g_manager->_itemConfig,*GHIDRA_CAST(local_50)), - collectibleConfig == GHIDRA_CAST(0x0))) { - format = "Invalid collectible ID: %d\n"; - uVar8 = 4; - goto LAB_009d4592; - } - if (0x98 < *GHIDRA_CAST((GHIDRA_CAST(reader) + 8))) { - shortField = local_50 + 1; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - } - shortField = local_50 + 2; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = local_50 + 4; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - if (99 < uVar8) { - shortField = local_50 + 5; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - } - if (0x6b < uVar8) { - shortField = local_50 + 6; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - } - local_4c = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_4c)) + 0x1)))); - local_50 = local_50 + 8; - } while (local_4c < local_54); - shortField = playerState + 0x4e; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x50; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x51; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x52; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - if (0x28 < uVar8) { - shortField = playerState + 0x54; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField,4,1); - local_2c[0] = *GHIDRA_CAST(shortField); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState + 0x55; - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((shortField)) + 0x1)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - } - pocketSlotCount = &DAT_00000004; - if (uVar8 < 0x66) { - pocketSlotCount = GHIDRA_CAST(0x2); - } - else if (uVar8 < 0x71) { - pocketSlotCount = GHIDRA_CAST(0x3); - } - local_4c = GHIDRA_CAST(0x0); - pocketSlot = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(playerState[0x56])) + 0x2)))); - shortField = playerState; - do { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&pocketType,1,1); - checksumByte = CONCAT11((*GHIDRA_CAST((GHIDRA_CAST(&(checksumByte)) + 0x1))),pocketType); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(&checksumByte),1); - local_54 = GHIDRA_CAST(0x0); - pocketSlot[1] = GHIDRA_INT(pocketType); - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&local_54,4,1); - local_2c[0] = local_54; - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - *pocketSlot = local_54; - if (((pocketType == '\x01') && (0 < GHIDRA_INT(local_54))) && - ((local_2c[0] = (g_manager->_itemConfig)._cards._begin, - GHIDRA_INT((g_manager->_itemConfig)._cards._end) - GHIDRA_INT(local_2c[0]) >> 2 <= GHIDRA_INT(local_54) || - (shortField = playerState, *GHIDRA_CAST((GHIDRA_INT(local_2c[0]) + GHIDRA_INT(local_54) * 4)) == 0)))) { - KAGE_LogMessage(1,GHIDRA_CAST("[warn] Invalid pocket item (type: %d, ID: %d)\n")); - ExceptionList = local_1c; - return 0; - } - pocketSlot = pocketSlot + 2; - local_4c = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_4c)) + 0x1)))); - } while (local_4c < pocketSlotCount); - iVar7 = 0x10 - GHIDRA_UINT((*GHIDRA_CAST((GHIDRA_CAST(reader) + 8)) < 0xa7)); - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x61])) + 0x1))),4,iVar7); - pvVar4 = local_44; - Checksum::Update(local_44,&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x61])) + 0x1))),iVar7 * 4); - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - if (0x4b < uVar8) { - local_54 = GHIDRA_CAST(0x0); - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&local_54,4,1); - local_2c[0] = local_54; - Checksum::Update(pvVar4,GHIDRA_CAST(local_2c),4); - local_8c = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(playerState[0x76])) + 0x2)))) = GHIDRA_UINT(local_54) & 0xffff; - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - } - shortField = playerState; - if (0x2e < uVar8) { - GameStateReader::read_int_vector(reader,GHIDRA_CAST((playerState + 0x78))); - if (GHIDRA_UINT((GHIDRA_INT((g_manager->_itemConfig)._collectibles._end) - - GHIDRA_INT((g_manager->_itemConfig)._collectibles._begin) >> 2)) < - GHIDRA_UINT((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x79])) + 0x1)))) - *GHIDRA_CAST((shortField + 0x78)) >> 2))) { - bVar2 = FUN_009d459a(uVar9); - return bVar2; - } - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - if (uVar8 < 0x4d) { - sVar1 = *GHIDRA_CAST((*GHIDRA_CAST((shortField + 0x78)) + 0x144)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0xaf])) + 0x1)))) = sVar1; - *GHIDRA_CAST((*GHIDRA_CAST((shortField + 0x78)) + 0x144)) = (sVar1 + 8) / 9; - *GHIDRA_CAST((shortField + 0x12)) = *GHIDRA_CAST((*GHIDRA_CAST((shortField + 0x78)) + 0x768)); - *GHIDRA_CAST((*GHIDRA_CAST((shortField + 0x78)) + 0x768)) = 0; - uVar8 = *GHIDRA_CAST((GHIDRA_CAST(reader) + 8)); - } - } - if (0x26 < uVar8) { - GameStateReader::read_int_vector(reader,GHIDRA_CAST((shortField + 0x7c))); - piVar6 = *GHIDRA_CAST((shortField + 0x7c)); - local_2c[0] = GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x7d])) + 0x1)))) - GHIDRA_INT(piVar6) >> 2)); - local_4c = GHIDRA_CAST(0x0); - if (local_2c[0] != GHIDRA_CAST(0x0)) { - do { - iVar7 = *piVar6; - if ((0 < iVar7) && - ((pvVar4 = (g_manager->_itemConfig)._collectibles._begin, - GHIDRA_INT((g_manager->_itemConfig)._collectibles._end) - GHIDRA_INT(pvVar4) >> 2 <= iVar7 || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar4) + iVar7 * 4)) == 0)))) { - format = "[warn] Invalid voided active item %d\n"; - goto LAB_009d4590; - } - local_4c = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_4c)) + 0x1)))); - piVar6 = piVar6 + 1; - } while (local_4c < local_2c[0]); - } - } - if (*GHIDRA_CAST((GHIDRA_CAST(reader) + 8)) < 0x8b) { - shortField = playerState; - } - else { - if (*GHIDRA_CAST((GHIDRA_CAST(reader) + 8)) < 0x97) { - intVector = (void *)0x0; - intVectorEnd = 0; - local_8c = 0; - local_14 = GHIDRA_CAST(0x0); - GameStateReader::read_int_vector(reader,GHIDRA_CAST(&intVector)); - shortField = playerState; - uVar8 = 0; - local_2c[0] = GHIDRA_CAST((intVectorEnd - GHIDRA_INT(intVector) >> 2)); - if (local_2c[0] != GHIDRA_CAST(0x0)) { - do { - iVar7 = *GHIDRA_CAST((playerState + 0x80)); - *GHIDRA_CAST((iVar7 + uVar8 * 8)) = *GHIDRA_CAST((GHIDRA_CAST(intVector) + uVar8 * 4)); - *GHIDRA_CAST((iVar7 + 4 + uVar8 * 8)) = 0; - uVar8 = uVar8 + 1; - } while (uVar8 < local_2c[0]); - } - local_14 = GHIDRA_CAST(0xffffffff); - if (intVector != (void *)0x0) { - uVar8 = (local_8c - GHIDRA_INT(intVector) >> 2) * 4; - pvVar4 = intVector; - if (0xfff < uVar8) { - pvVar4 = *(void **)(GHIDRA_CAST(intVector) + -4); - uVar8 = uVar8 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(intVector) + (-4 - GHIDRA_INT(pvVar4))))) { - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(pvVar4,uVar8); - } - } - else { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&local_50,4,1); - local_2c[0] = local_50; - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - shortField = playerState; - local_4c = playerState + 0x80; - puVar3 = *GHIDRA_CAST(local_4c); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(playerState[0x81])) + 0x1)))) = puVar3; - if (local_50 != GHIDRA_CAST(0x0)) { - pGVar5 = local_50; - if (GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(playerState[0x82])) + 0x2)))) - GHIDRA_INT(puVar3) >> 3)) < local_50) - { - msvc::vector<8byte_0_m1>::_Resize_reallocate(local_50,puVar3); - } - else { - do { - *puVar3 = 0; - puVar3[1] = 0xffffffff; - puVar3 = puVar3 + 2; - pGVar5 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(pGVar5[-1])) + 0x2)))); - } while (pGVar5 != GHIDRA_CAST(0x0)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(playerState[0x81])) + 0x1)))) = puVar3; - } - } - local_54 = GHIDRA_CAST(0x0); - if (local_50 != GHIDRA_CAST(0x0)) { - do { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&checksumByte,2,1); - local_2c[0] = GHIDRA_CAST(GHIDRA_UINT(checksumByte)); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),2); - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(readShort,2,1); - local_2c[0] = GHIDRA_CAST(GHIDRA_UINT(readShort[0])); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),2); - iVar7 = *GHIDRA_CAST(local_4c); - *GHIDRA_CAST((iVar7 + GHIDRA_INT(local_54) * 8)) = GHIDRA_UINT(checksumByte); - *GHIDRA_CAST((iVar7 + 4 + GHIDRA_INT(local_54) * 8)) = GHIDRA_UINT(readShort[0]); - local_54 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_54)) + 0x1)))); - } while (local_54 < local_50); - shortField = playerState; - } - } - piVar6 = *GHIDRA_CAST((shortField + 0x80)); - local_2c[0] = GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x81])) + 0x1)))) - GHIDRA_INT(piVar6) >> 3)); - local_4c = GHIDRA_CAST(0x0); - if (local_2c[0] != GHIDRA_CAST(0x0)) { - do { - iVar7 = *piVar6; - if ((0 < iVar7) && - ((GHIDRA_INT((g_manager->_itemConfig)._collectibles._end) - - GHIDRA_INT((g_manager->_itemConfig)._collectibles._begin) >> 2 <= iVar7 || - (shortField = playerState, - *GHIDRA_CAST((GHIDRA_INT((g_manager->_itemConfig)._collectibles._begin) + iVar7 * 4)) == 0)))) { - format = "[warn] Invalid voided passive item %d\n"; - goto LAB_009d4590; - } - local_4c = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_4c)) + 0x1)))); - piVar6 = piVar6 + 2; - } while (local_4c < local_2c[0]); - } - } - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(shortField + 0x84,4,2); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST((shortField + 0x84)),8); - pGVar5 = shortField + 0x84; - local_4c = GHIDRA_CAST(0x0); - while( true ) { - local_2c[0] = *GHIDRA_CAST(pGVar5); - if ((0 < GHIDRA_INT(local_2c[0])) && - ((GHIDRA_INT((g_manager->_itemConfig)._trinkets._end) - - GHIDRA_INT((g_manager->_itemConfig)._trinkets._begin) >> 2 <= GHIDRA_INT((GHIDRA_UINT(local_2c[0]) & 0x7fff)) || - (shortField = playerState, - *GHIDRA_CAST((GHIDRA_INT((g_manager->_itemConfig)._trinkets._begin) + (GHIDRA_UINT(local_2c[0]) & 0x7fff) * 4)) - == 0)))) break; - local_4c = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_4c)) + 0x1)))); - pGVar5 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(pGVar5[1])) + 0x1)))); - if (GHIDRA_CAST(0x1) < local_4c) { - if (*GHIDRA_CAST((GHIDRA_CAST(reader) + 8)) - 0x2fU < 0x62) { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&local_54,4,1); - local_2c[0] = local_54; - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - local_4c = GHIDRA_CAST(0x0); - if (local_54 != GHIDRA_CAST(0x0)) { - do { - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&readByte,1,1); - local_5c[0] = readByte; - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),local_5c,1); - local_4c = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((local_4c)) + 0x1)))); - } while (local_4c < local_54); - shortField = playerState; - } - } - (**(code **)(**GHIDRA_CAST(reader) + 0x14))(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x9a])) + 0x2))),4,1); - local_2c[0] = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x9a])) + 0x2)))); - Checksum::Update((void *)(GHIDRA_INT(reader) + 0xc),GHIDRA_CAST(local_2c),4); - local_14 = GHIDRA_CAST(0x1); - msvc::vector<8byte>::resize(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(shortField[0x9a])) + 0x2))))); - local_14 = GHIDRA_CAST(0xffffffff); - bVar2 = Entity_Player::restore_save_state_part2(); - return bVar2; - } - } - format = "[warn] Invalid trinket %d\n"; -LAB_009d4590: - uVar8 = 1; -LAB_009d4592: - KAGE_LogMessage(uVar8,GHIDRA_CAST(format)); - ExceptionList = local_1c; - return 0; -} - -// 009d2656 -uint32_t GameStatePlayer::read_part3() -{ - void *pvVar1; - int iVar2; - uint32_t uVar3; - uint32_t uVar4; - uint32_t uVar5; - char cVar6; - uint8_t bVar7; - uint32_t uVar8; - void *pvVar9; - ItemConfig_Item *collectibleConfig; - uint8_t uVar10; - uint32_t extraout_ECX; - uint32_t uVar11; - int iVar12; - uint32_t extraout_ECX_00; - uint32_t extraout_ECX_01; - int iVar13; - void *this; - uint8_t bVar14; - uint32_t uVar15; - uint32_t *puVar16; - int unaff_EBX; - int unaff_EBP; - int unaff_ESI; - char *pcVar17; - uint16_t *puVar18; - uint32_t *puVar19; - uint8_t *shortArrayDest; - uint32_t *readDest; - int *piVar20; - uint8_t *puVar21; - Manager *manager; - uint32_t *unaff_EDI; - int iVar22; - - *GHIDRA_CAST((unaff_EBP + -0x29)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x1d)) != '\0') { - do { - cVar6 = (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x10))(); - if (cVar6 != '\0') { - KAGE_LogMessage(1,(uint8_t *) - "[warn] Invalid co-player count %d. Save file %s might be corrupt.\n"); - goto code_r0x009d459a; - } - bVar7 = read_coplayer(GHIDRA_CAST((*GHIDRA_CAST((unaff_ESI + 0x38c)) + - GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x29))) * 0x1c)),unaff_EDI); - if (bVar7 == 0) goto LAB_009d26db; - bVar7 = *GHIDRA_CAST((unaff_EBP + -0x29)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x29)) = bVar7; - } while (bVar7 < *GHIDRA_CAST((unaff_EBP + -0x1d))); - } - pcVar17 = GHIDRA_CAST((unaff_ESI + 0x398)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(pcVar17,1,1); - *GHIDRA_CAST((unaff_EBP + -0x38)) = *pcVar17; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x38)),1); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - if ((*pcVar17 != '\0') && (bVar7 = read_coplayer(GHIDRA_CAST((iVar13 + 0x39c)),unaff_EDI), bVar7 == 0) - ) { -LAB_009d26db: - uVar8 = FUN_009d459a(); - return uVar8; - } - if (GHIDRA_UINT(unaff_EDI[2]) < 0x41) { - uVar8 = *GHIDRA_CAST((unaff_EBP + -0x34)); - *GHIDRA_CAST((unaff_EBP + -0x34)) = uVar8; -LAB_009d29c0: - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - *GHIDRA_CAST((unaff_EBP + -0x28)) = uVar8; - } - else { - puVar18 = GHIDRA_CAST((iVar13 + 0x3b8)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar18,2,1); - pvVar9 = *(void **)(unaff_EBP + -0x28); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = GHIDRA_UINT(*puVar18); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),2); - uVar11 = unaff_EDI[2]; - if (0x57 < uVar11) { - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x430)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - pvVar9 = *(void **)(unaff_EBP + -0x28); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = unaff_EDI[2]; - } - if (uVar11 < 0x72) { - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - } - else { - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(unaff_EBP + -0x30,2,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x30))); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),2); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - *GHIDRA_CAST((iVar13 + 0x434)) = GHIDRA_INT(*GHIDRA_CAST((unaff_EBP + -0x30))); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(unaff_EBP + -0x30,2,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x30))); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),2); - *GHIDRA_CAST((iVar13 + 0x438)) = *GHIDRA_CAST((unaff_EBP + -0x30)); - uVar11 = unaff_EDI[2]; - } - *GHIDRA_CAST((unaff_EBP + -0x28)) = *GHIDRA_CAST((unaff_EBP + -0x34)); - if (uVar11 < 0x4f) { - pvVar9 = *(void **)(unaff_EBP + -0x34); - } - else { - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(GHIDRA_CAST((iVar13 + 0x43c)),4,1); - pvVar9 = *(void **)(unaff_EBP + -0x34); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((iVar13 + 0x43c)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = unaff_EDI[2]; - } - if (0x4f < uVar11) { - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x440)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x444)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - pvVar9 = *(void **)(unaff_EBP + -0x34); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = unaff_EDI[2]; - } - if (0x51 < uVar11) { - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x448)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - pvVar9 = *(void **)(unaff_EBP + -0x34); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = unaff_EDI[2]; - } - if (0x5a < uVar11) { - shortArrayDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x458)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(shortArrayDest,2,6); - Checksum::Update(*(void **)(unaff_EBP + -0x34),shortArrayDest,0xc); - shortArrayDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x464)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(shortArrayDest,2,6); - Checksum::Update(*(void **)(unaff_EBP + -0x34),shortArrayDest,0xc); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x470)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - pvVar9 = *(void **)(unaff_EBP + -0x34); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = unaff_EDI[2]; - } - uVar8 = *GHIDRA_CAST((unaff_EBP + -0x34)); - *GHIDRA_CAST((unaff_EBP + -0x3c)) = uVar8; - *(void **)(unaff_EBP + -0x48) = pvVar9; - if (uVar11 < 0x5d) { - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - *(void **)(unaff_EBP + -0x34) = pvVar9; - *GHIDRA_CAST((unaff_EBP + -0x28)) = uVar8; - if (0x5b < uVar11) { - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(GHIDRA_CAST((iVar13 + 0x44c)),4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((iVar13 + 0x44c)); - Checksum::Update(*(void **)(unaff_EBP + -0x48),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar8 = *GHIDRA_CAST((unaff_EBP + -0x3c)); - *GHIDRA_CAST((unaff_EBP + -0x34)) = extraout_ECX; - goto LAB_009d29c0; - } - } - else { - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(unaff_EBP + -0x1d,1,1); - *GHIDRA_CAST((unaff_EBP + -0x38)) = *GHIDRA_CAST((unaff_EBP + -0x1d)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x38)),1); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - *GHIDRA_CAST((iVar13 + 0x44c)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x1d))); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(unaff_EBP + -0x1d,1,1); - *GHIDRA_CAST((unaff_EBP + -0x38)) = *GHIDRA_CAST((unaff_EBP + -0x1d)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x38)),1); - *GHIDRA_CAST((iVar13 + 0x454)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x1d))); - } - } - uVar11 = unaff_EDI[2]; - if (0x62 < uVar11) { - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(unaff_EBP + -0x29,1,1); - *GHIDRA_CAST((unaff_EBP + -0x38)) = *GHIDRA_CAST((unaff_EBP + -0x29)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x38)),1); - *GHIDRA_CAST((iVar13 + 0x450)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x29))); - uVar11 = unaff_EDI[2]; - } - uVar8 = *GHIDRA_CAST((unaff_EBP + -0x28)); - if (0x5e < uVar11) { - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(GHIDRA_CAST((iVar13 + 0x474)),4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((iVar13 + 0x474)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x478)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x47c)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x480)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x484)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x488)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = unaff_EDI[2]; - uVar8 = *GHIDRA_CAST((unaff_EBP + -0x28)); - } - *GHIDRA_CAST((unaff_EBP + -0x40)) = uVar8; - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar8; - if (uVar11 < 0x60) { -LAB_009d2c5b: - puVar19 = *GHIDRA_CAST((unaff_EBX + 8)); - uVar11 = puVar19[2]; - if (uVar11 < 0x61) { - pvVar9 = *(void **)(unaff_EBP + -0x28); - } - else { - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x490)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - pvVar9 = *(void **)(unaff_EBP + -0x28); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - } - if (0x61 < uVar11) { - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x494)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - pvVar9 = *(void **)(unaff_EBP + -0x28); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - } - if (uVar11 < 100) { - uVar8 = *GHIDRA_CAST((unaff_EBP + -0x40)); - *GHIDRA_CAST((unaff_EBP + -0x40)) = uVar8; - } - else { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x30,2,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x30))); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),2); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - *GHIDRA_CAST((iVar13 + 0x498)) = GHIDRA_INT(*GHIDRA_CAST((unaff_EBP + -0x30))); - uVar11 = puVar19[2]; - if (0x69 < uVar11) { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(GHIDRA_CAST((iVar13 + 0x49c)),4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((iVar13 + 0x49c)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4a0)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4a4)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4a8)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - } - if (0x6b < uVar11) { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(GHIDRA_CAST((iVar13 + 0x4ac)),4,1); - pvVar9 = *(void **)(unaff_EBP + -0x28); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((iVar13 + 0x4ac)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - if (GHIDRA_UINT(puVar19[2]) < 0x90) { - *GHIDRA_CAST((unaff_EBP + -100)) = 0; - *GHIDRA_CAST((unaff_EBP + -0x60)) = 0; - *GHIDRA_CAST((unaff_EBP + -0x5c)) = 0; - *GHIDRA_CAST((unaff_EBP + -0x58)) = 0; - *GHIDRA_CAST((unaff_EBP + -4)) = 0xc; - *GHIDRA_CAST((unaff_EBP + -0x88)) = 0; - *GHIDRA_CAST((unaff_EBP + -0x84)) = 0; - *GHIDRA_CAST((unaff_EBP + -0x80)) = 0; - *GHIDRA_CAST((unaff_EBP + -0x7c)) = 0; - *GHIDRA_CAST((unaff_EBP + -4)) = 0xd; - GameStateReader::read_bool_vector(puVar19,(void *)(unaff_EBP + -100),0); - GameStateReader::read_bool_vector(puVar19,(void *)(unaff_EBP + -0x88),0); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - uVar11 = 0; - *GHIDRA_CAST((unaff_EBP + -0x34)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x58)) != 0) { - do { - if (2 < *GHIDRA_CAST((iVar13 + 0x4c0))) break; - if ((*GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -100)) + (uVar11 >> 5) * 4)) & - 1 << ((uint8_t)uVar11 & 0x1f)) == 0) { - iVar12 = *GHIDRA_CAST((unaff_EBP + -0x34)); - } - else { - uVar11 = *GHIDRA_CAST((iVar13 + 0x4bc)); - *GHIDRA_CAST((unaff_EBP + -0x44)) = uVar11; - if (((uVar11 & 1) == 0) && - (*GHIDRA_CAST((unaff_EBP + -0x44)) = uVar11, - *GHIDRA_CAST((iVar13 + 0x4b8)) <= *GHIDRA_CAST((iVar13 + 0x4c0)) + 2U >> 1)) { - msvc::deque::_Growmap(*GHIDRA_CAST((unaff_EBP + -100))); - *GHIDRA_CAST((unaff_EBP + -0x44)) = *GHIDRA_CAST((iVar13 + 0x4bc)); - } - iVar12 = *GHIDRA_CAST((iVar13 + 0x4b8)); - uVar11 = iVar12 * 2; - uVar15 = uVar11 - 1 & *GHIDRA_CAST((unaff_EBP + -0x44)); - *GHIDRA_CAST((iVar13 + 0x4bc)) = uVar15; - if (uVar15 == 0) { - uVar15 = uVar11; - } - *GHIDRA_CAST((unaff_EBP + -0x50)) = uVar15; - *GHIDRA_CAST((unaff_EBP + -0x50)) = uVar15 - 1; - uVar11 = uVar15 - 1 >> 1 & iVar12 - 1U; - iVar12 = *GHIDRA_CAST((iVar13 + 0x4b4)); - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - iVar22 = iVar13; - if (*GHIDRA_CAST((iVar12 + uVar11 * 4)) == 0) { - pvVar9 = operator_new(0x10); - *(void **)(*GHIDRA_CAST((iVar13 + 0x4b4)) + uVar11 * 4) = pvVar9; - iVar22 = *GHIDRA_CAST((unaff_EBP + -0x24)); - } - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x50)) & 1; - iVar2 = *GHIDRA_CAST((*GHIDRA_CAST((iVar13 + 0x4b4)) + *GHIDRA_CAST((unaff_EBP + -0x48)) * 4)); - iVar12 = *GHIDRA_CAST((unaff_EBP + -0x34)); - *GHIDRA_CAST((iVar2 + uVar11 * 8)) = iVar12; - *GHIDRA_CAST((iVar2 + 4 + uVar11 * 8)) = 1; - *GHIDRA_CAST((iVar13 + 0x4c0)) = *GHIDRA_CAST((iVar13 + 0x4c0)) + 1; - puVar19 = *GHIDRA_CAST((unaff_EBX + 8)); - *GHIDRA_CAST((iVar13 + 0x4bc)) = *GHIDRA_CAST((unaff_EBP + -0x50)); - iVar13 = iVar22; - if ((0 < iVar12) && - ((pvVar9 = (g_manager->_itemConfig)._cards._begin, - GHIDRA_INT((g_manager->_itemConfig)._cards._end) - GHIDRA_INT(pvVar9) >> 2 <= iVar12 || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar9) + iVar12 * 4)) == 0)))) { - KAGE_LogMessage(1,GHIDRA_CAST("[warn] Invalid pocket item (type: %d, ID: %d)\n")); - pvVar9 = *(void **)(unaff_EBP + -0x88); - if (pvVar9 != (void *)0x0) { - deallocate(pvVar9,*GHIDRA_CAST((unaff_EBP + -0x80)) - GHIDRA_INT(pvVar9) >> 2); - } - pvVar9 = *(void **)(unaff_EBP + -100); - if (pvVar9 == (void *)0x0) goto LAB_009d26db; - deallocate(pvVar9,*GHIDRA_CAST((unaff_EBP + -0x5c)) - GHIDRA_INT(pvVar9) >> 2); - goto code_r0x009d459a; - } - } - uVar11 = iVar12 + 1; - *GHIDRA_CAST((unaff_EBP + -0x34)) = uVar11; - } while (uVar11 < *GHIDRA_CAST((unaff_EBP + -0x58))); - } - uVar11 = 0; - *GHIDRA_CAST((unaff_EBP + -0x44)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x7c)) != 0) { - do { - if (2 < *GHIDRA_CAST((iVar13 + 0x4c0))) break; - if ((*GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x88)) + (uVar11 >> 5) * 4)) & - 1 << ((uint8_t)uVar11 & 0x1f)) != 0) { - uVar11 = *GHIDRA_CAST((iVar13 + 0x4bc)); - *GHIDRA_CAST((unaff_EBP + -0x34)) = uVar11; - if (((uVar11 & 1) == 0) && - (*GHIDRA_CAST((unaff_EBP + -0x34)) = uVar11, - *GHIDRA_CAST((iVar13 + 0x4b8)) <= *GHIDRA_CAST((iVar13 + 0x4c0)) + 2U >> 1)) { - msvc::deque::_Growmap(iVar13 + 0x4b0); - *GHIDRA_CAST((unaff_EBP + -0x34)) = *GHIDRA_CAST((iVar13 + 0x4bc)); - } - iVar12 = *GHIDRA_CAST((iVar13 + 0x4b8)); - iVar2 = iVar12 * 2; - puVar16 = GHIDRA_CAST((unaff_EBP + -0x34)); - *puVar16 = *puVar16 & iVar2 - 1U; - uVar11 = *puVar16; - iVar22 = *GHIDRA_CAST((unaff_EBP + -0x34)); - *GHIDRA_CAST((iVar13 + 0x4bc)) = iVar22; - if (uVar11 == 0) { - iVar22 = iVar2; - } - *GHIDRA_CAST((unaff_EBP + -0x34)) = iVar22 - 1U; - uVar11 = iVar22 - 1U >> 1 & iVar12 - 1U; - iVar12 = *GHIDRA_CAST((iVar13 + 0x4b4)); - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - if (*GHIDRA_CAST((iVar12 + uVar11 * 4)) == 0) { - pvVar9 = operator_new(0x10); - *(void **)(*GHIDRA_CAST((iVar13 + 0x4b4)) + *GHIDRA_CAST((unaff_EBP + -0x48)) * 4) = pvVar9; - } - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x34)); - uVar15 = uVar11 & 1; - iVar12 = *GHIDRA_CAST((*GHIDRA_CAST((iVar13 + 0x4b4)) + *GHIDRA_CAST((unaff_EBP + -0x48)) * 4)); - *GHIDRA_CAST((iVar12 + uVar15 * 8)) = *GHIDRA_CAST((unaff_EBP + -0x44)); - puVar19 = *GHIDRA_CAST((unaff_EBX + 8)); - *GHIDRA_CAST((iVar12 + 4 + uVar15 * 8)) = 0; - *GHIDRA_CAST((iVar13 + 0x4c0)) = *GHIDRA_CAST((iVar13 + 0x4c0)) + 1; - *GHIDRA_CAST((iVar13 + 0x4bc)) = uVar11; - } - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x44)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x44)) = uVar11; - } while (uVar11 < *GHIDRA_CAST((unaff_EBP + -0x7c))); - } - pvVar9 = *(void **)(unaff_EBP + -0x88); - if (pvVar9 != (void *)0x0) { - deallocate(pvVar9,*GHIDRA_CAST((unaff_EBP + -0x80)) - GHIDRA_INT(pvVar9) >> 2); - } - *GHIDRA_CAST((unaff_EBP + -4)) = 0xffffffff; - pvVar9 = *(void **)(unaff_EBP + -100); - if (pvVar9 != (void *)0x0) { - deallocate(pvVar9,*GHIDRA_CAST((unaff_EBP + -0x5c)) - GHIDRA_INT(pvVar9) >> 2); - } - } - else { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x29,1,1); - *GHIDRA_CAST((unaff_EBP + -0x38)) = *GHIDRA_CAST((unaff_EBP + -0x29)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x38)),1); - *GHIDRA_CAST((unaff_EBP + -0x35)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x29)) != '\0') { - do { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x4c,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((unaff_EBP + -0x4c)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x30)),1); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x48,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x48)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - if (((*GHIDRA_CAST((unaff_EBP + -0x4c)) == '\x01') && - (iVar13 = *GHIDRA_CAST((unaff_EBP + -0x48)), 0 < iVar13)) && - ((pvVar1 = (g_manager->_itemConfig)._cards._begin, - GHIDRA_INT((g_manager->_itemConfig)._cards._end) - GHIDRA_INT(pvVar1) >> 2 <= iVar13 || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + iVar13 * 4)) == 0)))) { - KAGE_LogMessage(1,GHIDRA_CAST("[warn] Invalid pocket item (type: %d, ID: %d)\n")); - goto code_r0x009d459a; - } - bVar7 = *GHIDRA_CAST((unaff_EBP + -0x35)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x35)) = bVar7; - } while (bVar7 < *GHIDRA_CAST((unaff_EBP + -0x29))); - } - } - piVar20 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4c4)); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = piVar20; - FUN_007dccd0(8); - uVar11 = 0; - *GHIDRA_CAST((unaff_EBP + -0x48)) = 0; - do { - iVar13 = *piVar20; - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(GHIDRA_CAST((iVar13 + uVar11)),1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((iVar13 + uVar11)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x30)),1); - piVar20 = *GHIDRA_CAST((unaff_EBP + -0x1c)); - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x48)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - } while (uVar11 < 8); - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4d0)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - if (0x98 < GHIDRA_UINT(puVar19[2])) { - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4d4)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - } - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4dc; - FUN_007dccd0(6); - uVar11 = 0; - *GHIDRA_CAST((unaff_EBP + -0x48)) = 0; - do { - puVar21 = GHIDRA_CAST((**GHIDRA_CAST((unaff_EBP + -0x1c)) + uVar11)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(puVar21,1,1); - pvVar9 = *(void **)(unaff_EBP + -0x28); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *puVar21; - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x30)),1); - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x48)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - } while (uVar11 < 6); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x1d,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((unaff_EBP + -0x1d)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x30)),1); - uVar10 = *GHIDRA_CAST((unaff_EBP + -0x1d)); - if (0x14 < *GHIDRA_CAST((unaff_EBP + -0x1d))) { - uVar10 = 0x14; - } - piVar20 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4e8)); - *GHIDRA_CAST((unaff_EBP + -0x1d)) = uVar10; - *GHIDRA_CAST((unaff_EBP + -0x1c)) = piVar20; - FUN_007dccd0(uVar10); - uVar11 = 0; - *GHIDRA_CAST((unaff_EBP + -0x48)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x1d)) != '\0') { - do { - iVar13 = *piVar20; - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(GHIDRA_CAST((iVar13 + uVar11)),1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((iVar13 + uVar11)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x30)),1); - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x48)) + 1; - piVar20 = *GHIDRA_CAST((unaff_EBP + -0x1c)); - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - } while (uVar11 < *GHIDRA_CAST((unaff_EBP + -0x1d))); - } - puVar21 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4f4)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(puVar21,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *puVar21; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x30)),1); - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4d8)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4f8)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x4fc)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x528)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - } - uVar8 = *GHIDRA_CAST((unaff_EBP + -0x40)); - } - uVar11 = puVar19[2]; - *GHIDRA_CAST((unaff_EBP + -0x34)) = uVar8; - if (0x74 < uVar11) { - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x52c)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - *GHIDRA_CAST((unaff_EBP + -0x40)) = extraout_ECX_00; - } - if (0x75 < uVar11) { - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x514)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - } - if (0x77 < uVar11) { - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x530)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - } - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - if (0x7d < uVar11) { - read_block_538(GHIDRA_CAST((iVar13 + 0x538)),puVar19); - uVar11 = puVar19[2]; - } - if (uVar11 < 0xa4) { - *GHIDRA_CAST((iVar13 + 0x564)) = *GHIDRA_CAST((iVar13 + 4)); - } - else { - piVar20 = GHIDRA_CAST(*puVar19); - *GHIDRA_CAST((unaff_EBP + -0x38)) = 0; - (**(code **)(*piVar20 + 0x14))(unaff_EBP + -0x38,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x38)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - *GHIDRA_CAST((unaff_EBP + -4)) = 0xe; - *GHIDRA_CAST((unaff_EBP + -0x40)) = iVar13 + 0x558; - msvc::vector<52byte>::resize(*GHIDRA_CAST((unaff_EBP + -0x38))); - *GHIDRA_CAST((unaff_EBP + -4)) = 0xffffffff; - *GHIDRA_CAST((unaff_EBP + -0x48)) = 0; - if (0 < *GHIDRA_CAST((unaff_EBP + -0x38))) { - *GHIDRA_CAST((unaff_EBP + -0x28)) = 0; - do { - cVar6 = (**(code **)(*GHIDRA_CAST(*puVar19) + 0x10))(); - if (cVar6 != '\0') { - KAGE_LogMessage(1,(uint8_t *) - "[warn] Invalid familiar count %d. Save file %s might be corrupt.\n"); - goto code_r0x009d459a; - } - readDest = GHIDRA_CAST((**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)))); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = GHIDRA_CAST((**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 4)) - ; - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = GHIDRA_CAST((**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 8)) - ; - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = (uint32_t *) - (**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 0xc); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = (uint32_t *) - (**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 0x10); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = (uint32_t *) - (**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 0x14); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = (uint32_t *) - (**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 0x18); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = (uint32_t *) - (**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 0x1c); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = (uint32_t *) - (**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 0x20); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = (uint32_t *) - (**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 0x24); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = (uint32_t *) - (**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 0x28); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = (uint32_t *) - (**GHIDRA_CAST((unaff_EBP + -0x40)) + *GHIDRA_CAST((unaff_EBP + -0x28)) + 0x2c); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - pvVar9 = *(void **)(unaff_EBP + -0x34); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - piVar20 = GHIDRA_CAST(*puVar19); - *GHIDRA_CAST((unaff_EBP + -0x29)) = 0; - (**(code **)(*piVar20 + 0x14))(unaff_EBP + -0x29,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((unaff_EBP + -0x29)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x30)),1); - *GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x28)) + 0x30 + **GHIDRA_CAST((unaff_EBP + -0x40)))) = - *GHIDRA_CAST((unaff_EBP + -0x29)) != '\0'; - piVar20 = GHIDRA_CAST(*puVar19); - *GHIDRA_CAST((unaff_EBP + -0x1d)) = 0; - (**(code **)(*piVar20 + 0x14))(unaff_EBP + -0x1d,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((unaff_EBP + -0x1d)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x30)),1); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x28)); - *GHIDRA_CAST((iVar13 + 0x31 + **GHIDRA_CAST((unaff_EBP + -0x40)))) = - *GHIDRA_CAST((unaff_EBP + -0x1d)) != '\0'; - iVar12 = *GHIDRA_CAST((unaff_EBP + -0x48)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x28)) = iVar13 + 0x34; - *GHIDRA_CAST((unaff_EBP + -0x48)) = iVar12; - } while (iVar12 < *GHIDRA_CAST((unaff_EBP + -0x38))); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - } - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(GHIDRA_CAST((iVar13 + 0x564)),4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((iVar13 + 0x564)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - *GHIDRA_CAST((unaff_EBP + -0x40)) = extraout_ECX_01; - } - uVar11 = puVar19[2]; - if (0x7f < uVar11) { - *GHIDRA_CAST((unaff_EBP + -0x48)) = 0; - *GHIDRA_CAST((unaff_EBP + -0x50)) = iVar13 + 0x568; - do { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x29,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((unaff_EBP + -0x29)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x30)),1); - *GHIDRA_CAST((unaff_EBP + -0x44)) = 0; - *GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x50)) + 4)) = GHIDRA_INT(*GHIDRA_CAST((unaff_EBP + -0x29))); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x44,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x44)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - cVar6 = *GHIDRA_CAST((unaff_EBP + -0x29)); - piVar20 = *GHIDRA_CAST((unaff_EBP + -0x50)); - iVar12 = *GHIDRA_CAST((unaff_EBP + -0x44)); - *piVar20 = iVar12; - if ((cVar6 == '\x01') && (0 < iVar12)) { - pvVar9 = (g_manager->_itemConfig)._cards._begin; - pvVar1 = (g_manager->_itemConfig)._cards._end; - *(void **)(unaff_EBP + -0x1c) = pvVar9; - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - if ((GHIDRA_INT(pvVar1) - GHIDRA_INT(pvVar9) >> 2 <= iVar12) || - (*GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x1c)) + iVar12 * 4)) == 0)) { - KAGE_LogMessage(1,GHIDRA_CAST("[warn] Invalid pre curse pocket item (type: %d, ID: %d)\n")); - goto code_r0x009d459a; - } - } - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x48)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x50)) = piVar20 + 2; - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - } while (uVar11 < *GHIDRA_CAST((unaff_EBP + -0x74))); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(iVar13 + 0x588,4,2); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((iVar13 + 0x588)),8); - uVar11 = 0; - puVar16 = GHIDRA_CAST((iVar13 + 0x588)); - *GHIDRA_CAST((unaff_EBP + -0x48)) = 0; - do { - uVar15 = *puVar16; - *GHIDRA_CAST((unaff_EBP + -0x1c)) = uVar15; - if (0 < GHIDRA_INT(uVar15)) { - puVar19 = *GHIDRA_CAST((unaff_EBX + 8)); - if ((GHIDRA_INT((g_manager->_itemConfig)._trinkets._end) - - GHIDRA_INT((g_manager->_itemConfig)._trinkets._begin) >> 2 <= GHIDRA_INT((uVar15 & 0x7fff))) || - (iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)), - *GHIDRA_CAST((GHIDRA_INT((g_manager->_itemConfig)._trinkets._begin) + (uVar15 & 0x7fff) * 4)) == 0)) - { - pcVar17 = "[warn] Invalid pre curse trinket %d\n"; - goto LAB_009d4590; - } - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x48)); - } - uVar11 = uVar11 + 1; - puVar16 = puVar16 + 1; - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - } while (uVar11 < 2); - uVar11 = puVar19[2]; - } - if (0x81 < uVar11) { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(iVar13 + 0x590,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((iVar13 + 0x590)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x30)),1); - *GHIDRA_CAST((unaff_EBP + -0x48)) = 0; - *GHIDRA_CAST((unaff_EBP + -0x50)) = iVar13 + 0x598; - do { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x35,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((unaff_EBP + -0x35)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x30)),1); - *GHIDRA_CAST((unaff_EBP + -0x44)) = 0; - **GHIDRA_CAST((unaff_EBP + -0x50)) = GHIDRA_INT(*GHIDRA_CAST((unaff_EBP + -0x35))); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x44,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x44)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - piVar20 = *GHIDRA_CAST((unaff_EBP + -0x50)); - iVar12 = *GHIDRA_CAST((unaff_EBP + -0x44)); - piVar20[-1] = iVar12; - if (((*GHIDRA_CAST((iVar13 + 0x590)) != '\0') && - (iVar22 = *piVar20, *GHIDRA_CAST((unaff_EBP + -0x3c)) = iVar22, iVar22 == 1)) && (0 < iVar12)) - { - pvVar9 = (g_manager->_itemConfig)._cards._begin; - pvVar1 = (g_manager->_itemConfig)._cards._end; - *(void **)(unaff_EBP + -0x1c) = pvVar9; - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - if ((GHIDRA_INT(pvVar1) - GHIDRA_INT(pvVar9) >> 2 <= iVar12) || - (*GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x1c)) + iVar12 * 4)) == 0)) { - KAGE_LogMessage(1,(uint8_t *) - "[warn] Invalid pre coop ghost pocket item (type: %d, ID: %d)\n"); - goto code_r0x009d459a; - } - } - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x48)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x50)) = piVar20 + 2; - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - } while (uVar11 < *GHIDRA_CAST((unaff_EBP + -0x74))); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(iVar13 + 0x5b4,4,2); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((iVar13 + 0x5b4)),8); - cVar6 = *GHIDRA_CAST((iVar13 + 0x590)); - puVar16 = GHIDRA_CAST((iVar13 + 0x5b4)); - uVar11 = 0; - *GHIDRA_CAST((unaff_EBP + -0x35)) = cVar6; - *GHIDRA_CAST((unaff_EBP + -0x48)) = 0; - do { - if (cVar6 != '\0') { - uVar15 = *puVar16; - *GHIDRA_CAST((unaff_EBP + -0x1c)) = uVar15; - if (0 < GHIDRA_INT(uVar15)) { - puVar19 = *GHIDRA_CAST((unaff_EBX + 8)); - if ((GHIDRA_INT((g_manager->_itemConfig)._trinkets._end) - - GHIDRA_INT((g_manager->_itemConfig)._trinkets._begin) >> 2 <= GHIDRA_INT((uVar15 & 0x7fff))) || - (iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)), - *GHIDRA_CAST((GHIDRA_INT((g_manager->_itemConfig)._trinkets._begin) + (uVar15 & 0x7fff) * 4)) == 0 - )) { - pcVar17 = "[warn] Invalid pre coop ghost trinket %d\n"; - goto LAB_009d4590; - } - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x48)); - } - cVar6 = *GHIDRA_CAST((unaff_EBP + -0x35)); - } - uVar11 = uVar11 + 1; - puVar16 = puVar16 + 1; - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - } while (uVar11 < 2); - uVar11 = puVar19[2]; - } - if (0x80 < uVar11) { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(GHIDRA_CAST((iVar13 + 0x5c8)),4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((iVar13 + 0x5c8)); - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - } - if (uVar11 < 0x82) { - pvVar9 = *(void **)(unaff_EBP + -0x40); - *(void **)(unaff_EBP + -0x28) = pvVar9; - } - else { - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x5cc)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x40),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - if (0xa7 < uVar11) { - puVar21 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x5d0)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(puVar21,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *puVar21; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x30)),1); - uVar11 = puVar19[2]; - } - if (0xa8 < uVar11) { - puVar21 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x5d1)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(puVar21,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *puVar21; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x30)),1); - uVar11 = puVar19[2]; - } - pvVar9 = *(void **)(unaff_EBP + -0x40); - *(void **)(unaff_EBP + -0x28) = pvVar9; - if (0x82 < uVar11) { - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x524)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x34),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - pvVar9 = *(void **)(unaff_EBP + -0x28); - } - } - if (uVar11 < 0x6e) { -LAB_009d3eb4: - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - } - else { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x1d,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((unaff_EBP + -0x1d)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x30)),1); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - *GHIDRA_CAST((unaff_EBP + -0x48)) = iVar13 + 0x500; - msvc::vector<4byte>::resize(*GHIDRA_CAST((unaff_EBP + -0x1d))); - uVar11 = 0; - *GHIDRA_CAST((unaff_EBP + -0x35)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x1d)) != '\0') { - iVar13 = **GHIDRA_CAST((unaff_EBP + -0x48)); - do { - puVar19 = GHIDRA_CAST((iVar13 + uVar11 * 4)); - (**(code **)(*GHIDRA_CAST(**GHIDRA_CAST((unaff_EBX + 8))) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - iVar13 = **GHIDRA_CAST((unaff_EBP + -0x48)); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = iVar13; - iVar12 = *GHIDRA_CAST((iVar13 + uVar11 * 4)); - if (0 < iVar12) { - collectibleConfig = ItemConfig::GetCollectible(&g_manager->_itemConfig,iVar12); - if (collectibleConfig == GHIDRA_CAST(0x0)) { - pcVar17 = "[warn] Invalid item card %d\n"; - goto LAB_009d4590; - } - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x1c)); - } - bVar7 = *GHIDRA_CAST((unaff_EBP + -0x35)) + 1; - uVar11 = GHIDRA_UINT(bVar7); - *GHIDRA_CAST((unaff_EBP + -0x35)) = bVar7; - } while (bVar7 < *GHIDRA_CAST((unaff_EBP + -0x1d))); - puVar19 = *GHIDRA_CAST((unaff_EBX + 8)); - goto LAB_009d3eb4; - } - } - if (GHIDRA_UINT(puVar19[2]) < 0x6f) { -LAB_009d3f14: - uVar11 = puVar19[2]; - if (0x72 < uVar11) { - readDest = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x510)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(readDest,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *readDest; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = puVar19[2]; - } - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - if (0x7e < uVar11) { - iVar12 = *GHIDRA_CAST(*puVar19); - *GHIDRA_CAST((unaff_EBP + -0x3c)) = iVar13 + 0x5bc; - (**(code **)(iVar12 + 0x14))(iVar13 + 0x5bc,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((iVar13 + 0x5bc)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x30)),1); - if (*GHIDRA_CAST((iVar13 + 0x5bc)) != -1) { - iVar12 = *GHIDRA_CAST(*puVar19); - *GHIDRA_CAST((unaff_EBP + -0x48)) = iVar13 + 0x5c0; - (**(code **)(iVar12 + 0x14))(iVar13 + 0x5c0,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((iVar13 + 0x5c0)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(GHIDRA_CAST((iVar13 + 0x5c4)),4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((iVar13 + 0x5c4)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - cVar6 = **GHIDRA_CAST((unaff_EBP + -0x3c)); - *GHIDRA_CAST((unaff_EBP + -0x2d)) = cVar6; - if (cVar6 == '\x02') { - iVar13 = **GHIDRA_CAST((unaff_EBP + -0x48)); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = iVar13; - manager = g_manager; - if (0 < iVar13) { - collectibleConfig = ItemConfig::GetCollectible(&g_manager->_itemConfig,iVar13); - if (collectibleConfig == GHIDRA_CAST(0x0)) { - pcVar17 = "[warn] Invalid active item wildcard effect %d\n"; - goto LAB_009d4590; - } - goto LAB_009d4022; - } - } - else { - manager = g_manager; -LAB_009d4022: - iVar13 = **GHIDRA_CAST((unaff_EBP + -0x48)); - if (((*GHIDRA_CAST((unaff_EBP + -0x2d)) == '\x01') && (0 < iVar13)) && - ((pvVar9 = (manager->_itemConfig)._cards._begin, - GHIDRA_INT((manager->_itemConfig)._cards._end) - GHIDRA_INT(pvVar9) >> 2 <= iVar13 || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar9) + iVar13 * 4)) == 0)))) { - KAGE_LogMessage(1,(uint8_t *) - "[warn] Invalid pocket item wildcard effect (type: %d, id: %d)\n"); - goto code_r0x009d459a; - } - } - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - } - } - if (0x42 < GHIDRA_UINT(puVar19[2])) { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x44,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x44)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - *GHIDRA_CAST((unaff_EBP + -0x48)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x44)) != 0) { - do { - cVar6 = (**(code **)(*GHIDRA_CAST(*puVar19) + 0x10))(); - if (cVar6 != '\0') { - KAGE_LogMessage(1,(uint8_t *) - "[warn] Invalid history count %d. Save file %s might be corrupt.\n") - ; - } - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x3c,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x3c)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x74,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x74)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x34,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x34)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x30,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x30)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x50,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x50)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x38,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x38)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x3c)); - uVar15 = uVar11 & 0xffffff; - *GHIDRA_CAST((unaff_EBP + -0x1c)) = uVar15; - *GHIDRA_CAST((unaff_EBP + -0x3c)) = uVar15; - cVar6 = (char)(uVar11 >> 0x18); - if (cVar6 == '\x03') { - *GHIDRA_CAST((unaff_EBP + -0x6c)) = 1; - uVar15 = -uVar15; - } - else { - if (cVar6 == '\x02') { - uVar15 = -uVar15; - } - else { - if (cVar6 == '\x01') { - if (uVar15 != 0) { - pvVar9 = (g_manager->_itemConfig)._trinkets._begin; - pvVar1 = (g_manager->_itemConfig)._trinkets._end; - *(void **)(unaff_EBP + -0x1c) = pvVar9; - puVar19 = *GHIDRA_CAST((unaff_EBX + 8)); - if ((GHIDRA_INT(pvVar1) - GHIDRA_INT(pvVar9) >> 2 <= GHIDRA_INT((uVar11 & 0x7fff))) || - (*GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x1c)) + (uVar11 & 0x7fff) * 4)) == 0)) { - pcVar17 = "[warn] Invalid history trinket %d\n"; - goto LAB_009d4590; - } - } - *GHIDRA_CAST((unaff_EBP + -0x6c)) = 1; - goto LAB_009d422f; - } - if (uVar15 != 0) { - collectibleConfig = ItemConfig::GetCollectible(&g_manager->_itemConfig,uVar15); - if (collectibleConfig == GHIDRA_CAST(0x0)) { - pcVar17 = "[warn] Invalid history collectible %d\n"; - goto LAB_009d4590; - } - uVar15 = *GHIDRA_CAST((unaff_EBP + -0x1c)); - } - } - *GHIDRA_CAST((unaff_EBP + -0x6c)) = 0; - } -LAB_009d422f: - *GHIDRA_CAST((unaff_EBP + -100)) = *GHIDRA_CAST((unaff_EBP + -0x74)); - *GHIDRA_CAST((unaff_EBP + -0x60)) = *GHIDRA_CAST((unaff_EBP + -0x34)); - *GHIDRA_CAST((unaff_EBP + -0x5c)) = *GHIDRA_CAST((unaff_EBP + -0x30)); - *GHIDRA_CAST((unaff_EBP + -0x68)) = uVar15; - uVar8 = *GHIDRA_CAST((unaff_EBP + -0x50)); - *GHIDRA_CAST((unaff_EBP + -0x58)) = uVar8; - *GHIDRA_CAST((unaff_EBP + -0x70)) = *GHIDRA_CAST((unaff_EBP + -0x38)); - if (*GHIDRA_CAST((unaff_EBP + -0x38)) < 0) { - *GHIDRA_CAST((unaff_EBP + -0x70)) = g_game->_frameCount; - } - readDest = *GHIDRA_CAST((iVar13 + 0x3c0)); - if (readDest == *GHIDRA_CAST((iVar13 + 0x3c4))) { - msvc::vector<28byte>::_Emplace_reallocate(readDest,unaff_EBP + -0x70); - } - else { - uVar3 = *GHIDRA_CAST((unaff_EBP + -0x6c)); - uVar4 = *GHIDRA_CAST((unaff_EBP + -0x68)); - uVar5 = *GHIDRA_CAST((unaff_EBP + -100)); - *readDest = *GHIDRA_CAST((unaff_EBP + -0x70)); - readDest[1] = uVar3; - readDest[2] = uVar4; - readDest[3] = uVar5; - uVar3 = *GHIDRA_CAST((unaff_EBP + -0x5c)); - readDest[4] = *GHIDRA_CAST((unaff_EBP + -0x60)); - readDest[5] = uVar3; - readDest[6] = uVar8; - *GHIDRA_CAST((iVar13 + 0x3c0)) = *GHIDRA_CAST((iVar13 + 0x3c0)) + 0x1c; - } - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x48)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x48)) = uVar11; - } while (uVar11 < *GHIDRA_CAST((unaff_EBP + -0x44))); - } - if (100 < GHIDRA_UINT(puVar19[2])) { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x29,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((unaff_EBP + -0x29)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x30)),1); - *GHIDRA_CAST((unaff_EBP + -0x35)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x29)) != '\0') { - do { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x30,2,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x30))); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),2); - bVar7 = *GHIDRA_CAST((unaff_EBP + -0x35)); - bVar14 = bVar7 + 1; - *GHIDRA_CAST((unaff_EBP + -0x35)) = bVar14; - *GHIDRA_CAST((iVar13 + 0x3c8 + GHIDRA_UINT(bVar7) * 4)) = GHIDRA_INT(*GHIDRA_CAST((unaff_EBP + -0x30))); - } while (bVar14 < *GHIDRA_CAST((unaff_EBP + -0x29))); - } - } - } - if (0x50 < GHIDRA_UINT(puVar19[2])) { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x1d,1,1); - *GHIDRA_CAST((unaff_EBP + -0x30)) = *GHIDRA_CAST((unaff_EBP + -0x1d)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x30)),1); - FUN_0042c820(*GHIDRA_CAST((unaff_EBP + -0x1d))); - *GHIDRA_CAST((unaff_EBP + -0x35)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x1d)) != '\0') { - do { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x50,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x50)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - readDest = *GHIDRA_CAST((iVar13 + 0x428)); - if (readDest == *GHIDRA_CAST((iVar13 + 0x42c))) { - msvc::vector::_Emplace_reallocate(readDest,unaff_EBP + -0x50); - } - else { - *readDest = *GHIDRA_CAST((unaff_EBP + -0x50)); - *GHIDRA_CAST((iVar13 + 0x428)) = *GHIDRA_CAST((iVar13 + 0x428)) + 4; - } - if ((0 < *GHIDRA_CAST((unaff_EBP + -0x50))) && - (collectibleConfig = - ItemConfig::GetCollectible(&g_manager->_itemConfig,*GHIDRA_CAST((unaff_EBP + -0x50))) - , collectibleConfig == GHIDRA_CAST(0x0))) { - pcVar17 = "[warn] Invalid Monster Manual collectible %d\n"; - goto LAB_009d4590; - } - bVar7 = *GHIDRA_CAST((unaff_EBP + -0x35)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x35)) = bVar7; - } while (bVar7 < *GHIDRA_CAST((unaff_EBP + -0x1d))); - } - } - if (0x89 < GHIDRA_UINT(puVar19[2])) { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x3c,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x3c)); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x3c)) != 0) { - *GHIDRA_CAST((unaff_EBP + -0x44)) = iVar13 + 0x5d4; - do { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x38,2,1); - *GHIDRA_CAST((unaff_EBP + -0x48)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x38))); - Checksum::Update(this,GHIDRA_CAST((unaff_EBP + -0x48)),2); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x30,2,1); - *GHIDRA_CAST((unaff_EBP + -0x48)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x30))); - Checksum::Update(this,GHIDRA_CAST((unaff_EBP + -0x48)),2); - *GHIDRA_CAST((unaff_EBP + -0x54)) = GHIDRA_INT(*GHIDRA_CAST((unaff_EBP + -0x38))); - *GHIDRA_CAST((unaff_EBP + -0x50)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x30))); - std_map_int_insert(*(void **)(unaff_EBP + -0x44),(void *)(unaff_EBP + -0x78), - GHIDRA_CAST((unaff_EBP + -0x54))); - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x1c)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x1c)) = uVar11; - } while (uVar11 < *GHIDRA_CAST((unaff_EBP + -0x3c))); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - } - } - *GHIDRA_CAST((unaff_EBP + -0x3c)) = iVar13 + 0x4b0; - msvc::deque::_Tidy(); - if (0x9c < GHIDRA_UINT(puVar19[2])) { - piVar20 = GHIDRA_CAST(*puVar19); - *GHIDRA_CAST((unaff_EBP + -0x28)) = 0; - (**(code **)(*piVar20 + 0x14))(unaff_EBP + -0x28,4,1); - pvVar9 = *(void **)(unaff_EBP + -0x40); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *GHIDRA_CAST((unaff_EBP + -0x28)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x1c)),4); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x28)) != 0) { - do { - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x80,4,1); - *GHIDRA_CAST((unaff_EBP + -0x48)) = *GHIDRA_CAST((unaff_EBP + -0x80)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x48)),4); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(unaff_EBP + -0x7c,4,1); - *GHIDRA_CAST((unaff_EBP + -0x48)) = *GHIDRA_CAST((unaff_EBP + -0x7c)); - Checksum::Update(pvVar9,GHIDRA_CAST((unaff_EBP + -0x48)),4); - msvc::deque::push_back(unaff_EBP + -0x80); - uVar11 = *GHIDRA_CAST((unaff_EBP + -0x1c)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x1c)) = uVar11; - } while (uVar11 < *GHIDRA_CAST((unaff_EBP + -0x28))); - } - } - uVar8 = 1; - goto LAB_009d459c; - } - piVar20 = GHIDRA_CAST((iVar13 + 0x50c)); - (**(code **)(*GHIDRA_CAST(*puVar19) + 0x14))(piVar20,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *piVar20; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - if ((*piVar20 < 1) || - (collectibleConfig = ItemConfig::GetCollectible(&g_manager->_itemConfig,*piVar20), - collectibleConfig != GHIDRA_CAST(0x0))) goto LAB_009d3f14; - pcVar17 = "[warn] Invalid modeling clay effect %d\n"; -LAB_009d4590: - KAGE_LogMessage(1,GHIDRA_CAST(pcVar17)); - } - else { - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x48c)); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - (**(code **)(*GHIDRA_CAST(*unaff_EDI) + 0x14))(unaff_EBP + -0x30,2,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x30))); - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),2); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - *GHIDRA_CAST((unaff_EBP + -4)) = 10; - uVar11 = GHIDRA_UINT(*GHIDRA_CAST((unaff_EBP + -0x30))); - iVar12 = *GHIDRA_CAST((iVar13 + 0x51c)); - iVar22 = *GHIDRA_CAST((iVar13 + 0x518)); - *GHIDRA_CAST((unaff_EBP + -0x44)) = iVar12; - uVar15 = iVar12 - iVar22 >> 4; - *GHIDRA_CAST((unaff_EBP + -0x1c)) = iVar22; - puVar19 = *GHIDRA_CAST((unaff_EBX + 8)); - if (uVar11 < uVar15) { - iVar12 = uVar11 * 0x10 + *GHIDRA_CAST((iVar13 + 0x518)); -LAB_009d2c3f: - *GHIDRA_CAST((iVar13 + 0x51c)) = iVar12; - } - else if (uVar15 < uVar11) { - if (uVar11 <= GHIDRA_UINT((*GHIDRA_CAST((iVar13 + 0x520)) - *GHIDRA_CAST((unaff_EBP + -0x1c)) >> 4))) { - iVar12 = uVar11 - uVar15; - *GHIDRA_CAST((unaff_EBP + -0x1c)) = iVar12; - if (iVar12 == 0) { - iVar12 = *GHIDRA_CAST((unaff_EBP + -0x44)); - } - else { - memset(*(void **)(unaff_EBP + -0x44),0,iVar12 * 0x10); - iVar12 = *GHIDRA_CAST((unaff_EBP + -0x44)) + *GHIDRA_CAST((unaff_EBP + -0x1c)) * 0x10; - } - goto LAB_009d2c3f; - } - msvc::vector<16byte>::_Resize_reallocate(uVar11,uVar11); - } - *GHIDRA_CAST((unaff_EBP + -4)) = 0xffffffff; - *GHIDRA_CAST((unaff_EBP + -0x44)) = 0; - if (*GHIDRA_CAST((unaff_EBP + -0x30)) == 0) goto LAB_009d2c5b; - while (cVar6 = (**(code **)(*GHIDRA_CAST(*puVar19) + 0x10))(), cVar6 == '\0') { - iVar22 = (*GHIDRA_CAST((unaff_EBP + -0x44)) & 0xffff) * 0x10; - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((iVar13 + 0x518)) + iVar22)); - (**(code **)(*GHIDRA_CAST(**GHIDRA_CAST((unaff_EBX + 8))) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x518)) + 4 + iVar22)); - (**(code **)(*GHIDRA_CAST(**GHIDRA_CAST((unaff_EBX + 8))) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x518)) + 8 + iVar22)); - (**(code **)(*GHIDRA_CAST(**GHIDRA_CAST((unaff_EBX + 8))) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - puVar19 = GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((unaff_EBP + -0x24)) + 0x518)) + 0xc + iVar22)); - (**(code **)(*GHIDRA_CAST(**GHIDRA_CAST((unaff_EBX + 8))) + 0x14))(puVar19,4,1); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = *puVar19; - Checksum::Update(*(void **)(unaff_EBP + -0x28),GHIDRA_CAST((unaff_EBP + -0x1c)),4); - iVar13 = *GHIDRA_CAST((unaff_EBP + -0x24)); - iVar12 = *GHIDRA_CAST((iVar22 + 4 + *GHIDRA_CAST((iVar13 + 0x518)))); - iVar22 = *GHIDRA_CAST((iVar22 + *GHIDRA_CAST((iVar13 + 0x518)))); - *GHIDRA_CAST((unaff_EBP + -0x1c)) = iVar12; - bVar7 = is_valid_item_config_id(iVar22,iVar12); - if (bVar7 == 0) { - KAGE_LogMessage(1,GHIDRA_CAST("[warn] Invalid temporary effect (type: %d, ID: %d)\n")); - goto code_r0x009d459a; - } - iVar12 = *GHIDRA_CAST((unaff_EBP + -0x44)) + 1; - *GHIDRA_CAST((unaff_EBP + -0x44)) = iVar12; - if (*GHIDRA_CAST((unaff_EBP + -0x30)) <= (uint16_t)iVar12) goto LAB_009d2c5b; - puVar19 = *GHIDRA_CAST((unaff_EBX + 8)); - } - KAGE_LogMessage(1,GHIDRA_CAST("[warn] Invalid costume count %d. Save file %s might be corrupt.\n")); - } -code_r0x009d459a: - uVar8 = 0; -LAB_009d459c: - ExceptionList = *(void **)(unaff_EBP + -0xc); - return uVar8; -} diff --git a/generated-src/game_state_slot.cpp b/generated-src/game_state_slot.cpp deleted file mode 100644 index bb729c6..0000000 --- a/generated-src/game_state_slot.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include "classes.h" - -// 006f8a40 -void * Game_StateSlot::operator_assign(void *other) -{ - int *piVar1; - int *dst; - uint32_t *src; - RoomDescriptor *roomList; - size_t copySize; - int iVar2; - int blocksLeft; - void *dstBegin; - void *srcBegin; - - src = GHIDRA_CAST((GHIDRA_INT(other) + 0x8c)); - dst = GHIDRA_CAST((GHIDRA_INT(this) + 0x6c)); - blocksLeft = 2; - do { - dst[-0x1b] = src[-0x23]; - dst[-0x1a] = src[-0x22]; - dst[-0x19] = src[-0x21]; - dst[-0x18] = src[-0x20]; - dst[-0x17] = src[-0x1f]; - dst[-0x16] = src[-0x1e]; - dst[-0x15] = src[-0x1d]; - dst[-0x14] = src[-0x1c]; - dst[-0x13] = src[-0x1b]; - dst[-0x12] = src[-0x1a]; - dst[-0x11] = src[-0x19]; - dst[-0x10] = src[-0x18]; - dst[-0xf] = src[-0x17]; - dst[-0xe] = src[-0x16]; - dst[-0xd] = src[-0x15]; - dst[-0xc] = src[-0x14]; - dst[-0xb] = src[-0x13]; - dst[-10] = src[-0x12]; - *GHIDRA_CAST((dst + -9)) = *GHIDRA_CAST((src + -0x11)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + -0x22)) = *GHIDRA_CAST((GHIDRA_CAST(src) + -0x42)); - dst[-8] = src[-0x10]; - *GHIDRA_CAST((dst + -7)) = *GHIDRA_CAST((src + -0xf)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + -0x1a)) = *GHIDRA_CAST((GHIDRA_CAST(src) + -0x3a)); - dst[-6] = src[-0xe]; - dst[-5] = src[-0xd]; - dst[-4] = src[-0xc]; - dst[-3] = src[-0xb]; - dst[-2] = src[-10]; - if (dst != src + -8) { - srcBegin = (void *)src[-9]; - copySize = *GHIDRA_CAST(((GHIDRA_INT(other) - GHIDRA_INT(this)) + GHIDRA_INT(dst))) - GHIDRA_INT(srcBegin); - dstBegin = (void *)dst[-1]; - if (GHIDRA_UINT((dst[1] - GHIDRA_INT(dstBegin) >> 5)) < GHIDRA_UINT((GHIDRA_INT(copySize) >> 5))) { - msvc::vector<32byte>::_Clear_and_reserve_geometric(GHIDRA_INT(copySize) >> 5); - dstBegin = (void *)dst[-1]; - } - memmove(dstBegin,srcBegin,copySize); - *dst = GHIDRA_INT(dstBegin) + copySize; - } - if (dst + 2 != src + -6) { - msvc::vector::assign(src[-6],src[-5],other); - } - piVar1 = dst + 5; - if (piVar1 != src + -3) { - iVar2 = *piVar1; - FID_conflict__Erase_tree_>_> - (piVar1,(fuzzer_allocator_> *)piVar1, - *(_Tree_node **)(iVar2 + 4)); - *GHIDRA_CAST((iVar2 + 4)) = iVar2; - *GHIDRA_CAST(iVar2) = iVar2; - *GHIDRA_CAST((iVar2 + 8)) = iVar2; - dst[6] = 0; - std_set_uint_copy(dst + 5,src + -3,GHIDRA_INT(other)); - } - if (dst + 7 != src + -1) { - msvc::vector::assign(src[-1],*src,other); - } - *GHIDRA_CAST((dst + 10)) = *GHIDRA_CAST((src + 2)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x2a)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 10)); - *GHIDRA_CAST((dst + 0xb)) = *GHIDRA_CAST((src + 3)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x2e)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0xe)); - *GHIDRA_CAST((dst + 0xc)) = *GHIDRA_CAST((src + 4)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x32)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0x12)); - *GHIDRA_CAST((dst + 0xd)) = *GHIDRA_CAST((src + 5)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x36)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0x16)); - *GHIDRA_CAST((dst + 0xe)) = *GHIDRA_CAST((src + 6)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x39)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0x19)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x3a)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0x1a)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x3b)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0x1b)); - *GHIDRA_CAST((dst + 0xf)) = *GHIDRA_CAST((src + 7)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x3d)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0x1d)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x3e)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0x1e)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x3f)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0x1f)); - *GHIDRA_CAST((dst + 0x10)) = *GHIDRA_CAST((src + 8)); - *GHIDRA_CAST((GHIDRA_CAST(dst) + 0x42)) = *GHIDRA_CAST((GHIDRA_CAST(src) + 0x22)); - dst[0x11] = src[9]; - piVar1 = src + 10; - src = src + 0x2e; - dst[0x12] = *piVar1; - dst = dst + 0x2e; - blocksLeft = blocksLeft + -1; - } while (blocksLeft != 0); - iVar2 = 2; - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x170)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x170)); - roomList = GHIDRA_CAST((GHIDRA_INT(this) + 0x188)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x178)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x178)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x17c)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x17c)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x184)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x184)); - do { - GameState::copy_room_list(roomList,GHIDRA_CAST(((GHIDRA_INT(other) - GHIDRA_INT(this)) + GHIDRA_INT(roomList)))) - ; - roomList = roomList + 1; - iVar2 = iVar2 + -1; - } while (iVar2 != 0); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x2f8)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x2f8)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x300)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x300)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x304)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x304)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x30c)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x30c)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x310)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x310)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x314)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x314)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x318)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x318)); - *GHIDRA_CAST((GHIDRA_CAST(this) + 0x31c)) = *GHIDRA_CAST((GHIDRA_CAST(other) + 0x31c)); - return this; -} diff --git a/generated-src/npc_helper.cpp b/generated-src/npc_helper.cpp index 060e5da..715892e 100644 --- a/generated-src/npc_helper.cpp +++ b/generated-src/npc_helper.cpp @@ -18,7 +18,7 @@ void NpcHelper::the_lamb_pattern(Entity_NPC *npc, int pattern, int frame) Manager *manager; local_8 = (float)(__security_cookie ^ GHIDRA_UINT(&(¶ms)[1].CircleAngle)); - (GHIDRA_CAST((¶ms)))->ProjectileParams::ProjectileParams(); + ProjectileParams::ProjectileParams(¶ms); (*GHIDRA_CAST((GHIDRA_CAST(&(params)) + 0x4))) = 0x40a00000; params.Scale = 1.8; params.FallingAccelModifier = -0.06; @@ -5590,7 +5590,7 @@ void NpcHelper::moms_heart_attack_pattern(Entity_NPC *npc, int pattern, int stat uint32_t stackCookie; stackCookie = __security_cookie ^ GHIDRA_UINT(auStack_f8); - (GHIDRA_CAST((&projParams)))->ProjectileParams::ProjectileParams(); + ProjectileParams::ProjectileParams(&projParams); (*GHIDRA_CAST((GHIDRA_CAST(&(projParams)) + 0x4))) = 0x40a00000; projParams.Scale = 1.5; projParams.FallingAccelModifier = -0.06; @@ -7442,7 +7442,7 @@ LAB_00548a4b: } local_d4.x = (float)pbVar5 * 10.0; local_d4.y = fVar8 * 10.0; - (GHIDRA_CAST((&projParams)))->ProjectileParams::ProjectileParams(); + ProjectileParams::ProjectileParams(&projParams); projParams.Color._offset[2] = 0.0; projParams.Color._tint[0] = 1.0; projParams.Color._tint[1] = 1.0; @@ -8001,7 +8001,7 @@ void NpcHelper::willo_attack(Entity_NPC *npc) seed_fart_sound_override(GHIDRA_CAST(&local_bc)); (GHIDRA_CAST((&manager->_sfxManager)))->SoundEffects::Play(GHIDRA_INT(local_bc),1.0,2,0,local_b8,0.0); target = Entity_NPC::GetPlayerTarget(npc); - (GHIDRA_CAST((&projParams)))->ProjectileParams::ProjectileParams(); + ProjectileParams::ProjectileParams(&projParams); local_bc = ((target->_pos).x + (target->_velocity).x) - (npc->_pos).x; local_b8 = ((target->_pos).y + (target->_velocity).y) - (npc->_pos).y; distance = sqrtf(local_bc * local_bc + local_b8 * local_b8); @@ -12419,7 +12419,7 @@ void NpcHelper::ChampionDrop(Entity_NPC *npc) (nearestPlayer = Game::GetNearestPlayer(g_game,dropDir), fVar3 = (npc->_pos).y - (nearestPlayer->_pos).y, fVar7 = dropDir->x - (nearestPlayer->_pos).x, 6400.0 < fVar3 * fVar3 + fVar7 * fVar7)))) { - params = (GHIDRA_CAST((&projParams)))->ProjectileParams::ProjectileParams(); + params = ProjectileParams::ProjectileParams(&projParams); local_11c.x = 7.0; local_11c.y = 0.0; Entity_NPC::FireProjectiles(npc,dropDir,&local_11c,8,params); @@ -12737,7 +12737,7 @@ LAB_006c0128: (nearestPlayer = Game::GetNearestPlayer(g_game,dropDir), fVar3 = (npc->_pos).y - (nearestPlayer->_pos).y, fVar7 = dropDir->x - (nearestPlayer->_pos).x, 6400.0 < fVar3 * fVar3 + fVar7 * fVar7)))) { - params = (GHIDRA_CAST((&projParams)))->ProjectileParams::ProjectileParams(); + params = ProjectileParams::ProjectileParams(&projParams); local_c8._seed = 0x40e00000; (*GHIDRA_CAST((GHIDRA_CAST(&(local_c8)) + 0x4))) = (uint64_t)GHIDRA_UINT(local_c8._shift2) << 0x20; Entity_NPC::FireProjectiles(npc,dropDir,GHIDRA_CAST(&local_c8),8,params); diff --git a/generated-src/npcai_pathfinder.cpp b/generated-src/npcai_pathfinder.cpp deleted file mode 100644 index a5ba62a..0000000 --- a/generated-src/npcai_pathfinder.cpp +++ /dev/null @@ -1,495 +0,0 @@ -#include "classes.h" - -// 007e6fa0 -void NPCAI_Pathfinder::ResetMovementTarget() -{ - (this->_movementTarget).x = g_vectorZero.x; - (this->_movementTarget).y = g_vectorZero.y; - (this->_moveDirection).x = g_vectorZero.x; - (this->_moveDirection).y = g_vectorZero.y; - return; -} - -// 007e7070 -uint8_t NPCAI_Pathfinder::HasPathToPos(Vector *position, uint8_t isIgnorePoop) -{ - KColor color; - KColor color_00; - uint8_t *node; - uint32_t uVar2; - int iVar3; - uint8_t *pathCopyBegin; - uint8_t *puVar4; - int nodeRow; - void *pvVar5; - uint32_t uVar6; - int column; - uint32_t unaff_EBX; - int iVar7; - uint32_t *puVar8; - uint32_t unaff_ESI; - int *srcCollision; - uint32_t *nodesBegin; - uint32_t unaff_EDI; - int *dstCollision; - size_t _Size; - uint32_t allocSize; - uint8_t auStackY_83c [128]; - void *unused_1; - uint8_t *pbVar9; - uint8_t *pbVar10; - uint8_t *pbVar11; - size_t in_stack_fffff874; - uint8_t *currentPathCopyEnd; - uint32_t nodeGridIndex; - uint32_t nodeCost; - void *nodePathBegin; - uint32_t nodePathEnd; - uint8_t *nodePathCapacity; - uint32_t *openBegin; - uint32_t *openEnd; - uint32_t *openCapacity; - uint32_t local_754; - void *local_750; - void *emptyPathBegin; - void *emptyPathEnd; - int emptyPathCapacity; - uint8_t *local_740; - uint32_t startGridIndex; - uint32_t currentCost; - void *local_734; - uint8_t *local_730; - uint8_t *local_72c; - uint8_t isFound; - int gridCollision [448]; - uint32_t neighbors [4]; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - uint8_t local_8; - uint8_t auStack_7 [3]; - uint8_t *currentPathCopy; - uint32_t *node; - - puStack_c = &LAB_00b00a71; - local_10 = ExceptionList; - uVar2 = __security_cookie ^ GHIDRA_UINT((auStack_7 + 3)); - pvVar5 = g_game->_room; - iVar3 = GHIDRA_INT(((*GHIDRA_CAST((GHIDRA_CAST(this->_entity) + 0x33c)) - 40.0) / 40.0 + 0.5)); - iVar7 = GHIDRA_INT(((*GHIDRA_CAST((GHIDRA_CAST(this->_entity) + 0x340)) - 120.0) / 40.0 + 0.5)); - if ((((iVar3 < 0) || (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0xc)) <= iVar3)) || (iVar7 < 0)) || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0x10)) <= iVar7)) { - startGridIndex = 0xffffffff; - } - else { - startGridIndex = iVar7 * *GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0xc)) + iVar3; - if ((startGridIndex < 0x1c0) && (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + startGridIndex * 4 + 0x76c)) == 1000)) { - return 0; - } - } - openBegin = GHIDRA_CAST(0x0); - openEnd = GHIDRA_CAST(0x0); - openCapacity = GHIDRA_CAST(0x0); - emptyPathBegin = (void *)0x0; - emptyPathEnd = (void *)0x0; - emptyPathCapacity = 0; - iVar7 = GHIDRA_INT(((position->x - 40.0) / 40.0 + 0.5)); - iVar3 = GHIDRA_INT(((position->y - 120.0) / 40.0 + 0.5)); - if (((iVar7 < 0) || (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0xc)) <= iVar7)) || - ((iVar3 < 0 || (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0x10)) <= iVar3)))) { - nodeGridIndex = 0xffffffff; - } - else { - nodeGridIndex = iVar3 * *GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0xc)) + iVar7; - } - nodePathBegin = (void *)0x0; - nodePathEnd = 0; - nodePathCapacity = GHIDRA_CAST(0x0); - nodeCost = 0; - local_8 = 1; - auStack_7 = (uint8_t [3])0x0; - ExceptionList = &local_10; - local_14 = uVar2; - vector_PathNode_emplace_reallocate_copy(&openBegin,(void *)0x0,&nodeGridIndex); - pvVar5 = emptyPathBegin; - local_730 = auStackY_83c + 0x8c; - pbVar9 = GHIDRA_CAST(0x0); - pbVar10 = GHIDRA_CAST(0x0); - pbVar11 = GHIDRA_CAST(0x0); - uVar6 = local_754; - unused_1 = local_750; - puVar4 = auStackY_83c + 0x8c; - if (emptyPathBegin != emptyPathEnd) { - local_72c = GHIDRA_CAST((GHIDRA_INT(emptyPathEnd) - GHIDRA_INT(emptyPathBegin))); - puVar4 = local_740; - node = auStackY_83c + 0x8c; - if (0x3fffffff < GHIDRA_UINT((GHIDRA_INT(local_72c) >> 2))) { -LAB_007e780c: - local_730 = node; - local_740 = puVar4; - /* WARNING: Subroutine does not return */ - FUN_0040cee0(); - } - allocSize = (GHIDRA_INT(local_72c) >> 2) * 4; - pathCopyBegin = msvc::_Allocate(allocSize); - pbVar11 = pathCopyBegin + allocSize; - pbVar9 = pathCopyBegin; - pbVar10 = pathCopyBegin; - memmove(pathCopyBegin,pvVar5,(size_t)local_72c); - *GHIDRA_CAST((local_730 + 0xc)) = pathCopyBegin + allocSize; - puVar4 = local_730; - } - local_730 = puVar4; - puVar8 = openEnd; - color._green = (float)unaff_EDI; - color._red = (float)uVar2; - color._blue = (float)unaff_ESI; - color._alpha = (float)unaff_EBX; - color._unk = in_stack_fffff874; - KAGE_Graphics_ImageManager::CreateProceduralImage_Internal - (openBegin,GHIDRA_UINT(openEnd),uVar6,unused_1,pbVar9,GHIDRA_UINT(pbVar10),GHIDRA_UINT(pbVar11),color); - local_8 = 0; - if (nodePathBegin != (void *)0x0) { - uVar6 = (GHIDRA_INT(nodePathCapacity) - GHIDRA_INT(nodePathBegin) >> 2) * 4; - pvVar5 = nodePathBegin; - if (0xfff < uVar6) { - pvVar5 = *(void **)(GHIDRA_CAST(nodePathBegin) + -4); - uVar6 = uVar6 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(nodePathBegin) + (-4 - GHIDRA_INT(pvVar5))))) goto LAB_007e77d8; - } - operator_delete(pvVar5,uVar6); - } - isFound = 0; - srcCollision = GHIDRA_CAST((GHIDRA_INT(g_game->_room) + 0x76c)); - dstCollision = gridCollision; - for (iVar3 = 0x1c0; iVar3 != 0; iVar3 = iVar3 + -1) { - *dstCollision = *srcCollision; - srcCollision = srcCollision + 1; - dstCollision = dstCollision + 1; - } - nodesBegin = openBegin; - if (openBegin != puVar8) { - while (nodesBegin = openBegin, isFound == 0) { - local_734 = (void *)*openBegin; - local_730 = GHIDRA_CAST(openBegin[2]); - currentCost = openBegin[1]; - currentPathCopyEnd = GHIDRA_CAST(0x0); - local_72c = GHIDRA_CAST(0x0); - if (local_730 != GHIDRA_CAST(openBegin[3])) { - _Size = openBegin[3] - GHIDRA_INT(local_730); - uVar6 = GHIDRA_INT(_Size) >> 2; - puVar4 = local_740; - node = local_730; - if (0x3fffffff < uVar6) goto LAB_007e780c; - uVar6 = uVar6 * 4; - puVar4 = msvc::_Allocate(uVar6); - currentPathCopyEnd = puVar4 + uVar6; - memmove(puVar4,local_730,_Size); - local_72c = puVar4; - } - currentPathCopy = local_72c; - nodesBegin = openBegin; - local_8 = 2; - if ((*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x10)) * *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc))) / 2 <= - GHIDRA_INT(currentCost)) { - if (local_72c != GHIDRA_CAST(0x0)) { - uVar2 = GHIDRA_INT(currentPathCopyEnd) - GHIDRA_INT(local_72c) & 0xfffffffc; - puVar4 = local_72c; - if (0xfff < uVar2) { - puVar4 = *GHIDRA_CAST((local_72c + -4)); - uVar2 = uVar2 + 0x23; - if (GHIDRA_CAST(0x1f) < local_72c + (-4 - GHIDRA_INT(puVar4))) goto LAB_007e77d8; - } - operator_delete(puVar4,uVar2); - } - break; - } - msvc::priority_queue::pop(); - pvVar5 = g_game->_room; - iVar7 = *GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0xc)); - column = GHIDRA_INT(local_734) % iVar7; - nodeRow = GHIDRA_INT(local_734) / iVar7; - iVar3 = column + -1; - if ((((iVar3 < 0) || (iVar7 <= iVar3)) || (nodeRow < 0)) || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0x10)) <= nodeRow)) { - neighbors[0] = 0xffffffff; - if (-1 < column) goto LAB_007e7462; -LAB_007e7478: - neighbors[1] = -1; - } - else { - neighbors[0] = iVar7 * nodeRow + iVar3; -LAB_007e7462: - iVar3 = nodeRow + -1; - if (((iVar7 <= column) || (iVar3 < 0)) || (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0x10)) <= iVar3)) - goto LAB_007e7478; - neighbors[1] = iVar7 * iVar3 + column; - } - iVar3 = column + 1; - if (((iVar3 < 0) || (iVar7 <= iVar3)) || - ((nodeRow < 0 || (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0x10)) <= nodeRow)))) { - neighbors[2] = -1; - } - else { - neighbors[2] = iVar7 * nodeRow + iVar3; - } - nodeRow = nodeRow + 1; - if ((((column < 0) || (iVar7 <= column)) || (nodeRow < 0)) || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar5) + 0x10)) <= nodeRow)) { - neighbors[3] = -1; - } - else { - neighbors[3] = iVar7 * nodeRow + column; - } - local_72c = GHIDRA_CAST(0x0); - puVar8 = openEnd; - do { - nodeGridIndex = neighbors[GHIDRA_INT(local_72c)]; - local_734 = (void *)0x0; - nodePathBegin = (void *)0x0; - nodePathEnd = 0; - local_730 = GHIDRA_CAST(0x0); - nodePathCapacity = GHIDRA_CAST(0x0); - nodeCost = currentCost; - local_8 = 3; - if ((-1 < GHIDRA_INT(nodeGridIndex)) && - (((iVar3 = gridCollision[nodeGridIndex], -1 < iVar3 && (iVar3 < 0x3b6)) || - ((isIgnorePoop != 0 && (iVar3 == 0x5dc)))))) { - nodeCost = currentCost + 1; - gridCollision[nodeGridIndex] = -nodeCost; - if (nodeGridIndex == startGridIndex) { - isFound = 1; - break; - } - if (puVar8 == openCapacity) { - vector_PathNode_emplace_reallocate(&openBegin,puVar8,&nodeGridIndex); - local_730 = nodePathCapacity; - local_734 = nodePathBegin; - } - else { - *puVar8 = nodeGridIndex; - puVar8[1] = nodeCost; - puVar8[2] = 0; - puVar8[3] = 0; - puVar8[4] = 0; - openEnd = puVar8 + 5; - } - puVar8 = openEnd; - local_740 = auStackY_83c + 0x8c; - pbVar9 = GHIDRA_CAST(0x0); - pbVar10 = GHIDRA_CAST(0x0); - pbVar11 = GHIDRA_CAST(0x0); - uVar6 = local_754; - pvVar5 = local_750; - nodePathBegin = local_734; - nodePathCapacity = local_730; - puVar4 = auStackY_83c + 0x8c; - if (emptyPathBegin != emptyPathEnd) { - in_stack_fffff874 = GHIDRA_INT(emptyPathEnd) - GHIDRA_INT(emptyPathBegin); - puVar4 = auStackY_83c + 0x8c; - node = local_730; - if (0x3fffffff < GHIDRA_UINT((GHIDRA_INT(in_stack_fffff874) >> 2))) goto LAB_007e780c; - allocSize = (GHIDRA_INT(in_stack_fffff874) >> 2) * 4; - pathCopyBegin = msvc::_Allocate(allocSize); - pbVar11 = pathCopyBegin + allocSize; - pbVar9 = pathCopyBegin; - pbVar10 = pathCopyBegin; - memmove(pathCopyBegin,emptyPathBegin,in_stack_fffff874); - *GHIDRA_CAST((local_740 + 0xc)) = pathCopyBegin + allocSize; - puVar4 = local_740; - } - local_740 = puVar4; - color_00._green = (float)unaff_EDI; - color_00._red = (float)uVar2; - color_00._blue = (float)unaff_ESI; - color_00._alpha = (float)unaff_EBX; - color_00._unk = in_stack_fffff874; - KAGE_Graphics_ImageManager::CreateProceduralImage_Internal - (openBegin,GHIDRA_UINT(puVar8),uVar6,pvVar5,pbVar9,GHIDRA_UINT(pbVar10),GHIDRA_UINT(pbVar11),color_00 - ); - } - puVar4 = local_72c; - local_8 = 2; - if (local_734 != (void *)0x0) { - uVar6 = GHIDRA_INT(local_730) - GHIDRA_INT(local_734) & 0xfffffffc; - pvVar5 = local_734; - if (0xfff < uVar6) { - pvVar5 = *(void **)(GHIDRA_CAST(local_734) + -4); - uVar6 = uVar6 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(local_734) + (-4 - GHIDRA_INT(pvVar5))))) goto LAB_007e77d8; - } - operator_delete(pvVar5,uVar6); - } - local_72c = puVar4 + 1; - } while (local_72c < &DAT_00000004); - local_8 = 0; - if (currentPathCopy != GHIDRA_CAST(0x0)) { - uVar6 = GHIDRA_INT(currentPathCopyEnd) - GHIDRA_INT(currentPathCopy) & 0xfffffffc; - puVar4 = currentPathCopy; - if (0xfff < uVar6) { - puVar4 = *GHIDRA_CAST((currentPathCopy + -4)); - uVar6 = uVar6 + 0x23; - if (GHIDRA_CAST(0x1f) < currentPathCopy + (-4 - GHIDRA_INT(puVar4))) goto LAB_007e77d8; - } - operator_delete(puVar4,uVar6); - } - nodesBegin = openBegin; - if (openBegin == puVar8) break; - } - } - if (emptyPathBegin != (void *)0x0) { - uVar2 = emptyPathCapacity - GHIDRA_INT(emptyPathBegin) & 0xfffffffc; - pvVar5 = emptyPathBegin; - if (0xfff < uVar2) { - pvVar5 = *(void **)(GHIDRA_CAST(emptyPathBegin) + -4); - uVar2 = uVar2 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(emptyPathBegin) + (-4 - GHIDRA_INT(pvVar5))))) goto LAB_007e77d8; - } - operator_delete(pvVar5,uVar2); - } - node = nodesBegin; - if (nodesBegin != GHIDRA_CAST(0x0)) { - for (; node != puVar8; node = node + 5) { - FID_conflict__Tidy(node + 2); - } - uVar2 = ((GHIDRA_INT(openCapacity) - GHIDRA_INT(nodesBegin)) / 0x14) * 0x14; - puVar8 = nodesBegin; - if (0xfff < uVar2) { - puVar8 = GHIDRA_CAST(nodesBegin[-1]); - uVar2 = uVar2 + 0x23; - if (0x1f < GHIDRA_UINT((GHIDRA_INT(nodesBegin) + (-4 - GHIDRA_INT(puVar8))))) { -LAB_007e77d8: - /* WARNING: Subroutine does not return */ - _invalid_parameter_noinfo_noreturn(); - } - } - operator_delete(puVar8,uVar2); - } - ExceptionList = local_10; - return isFound; -} - -// 007e8010 -void NPCAI_Pathfinder::SimulatePlayerMovement(float *param_2) -{ - int *piVar1; - int gridCollisionClass; - uint8_t isClamped; - uint32_t uVar3; - float fVar4; - float accelFactor; - float fVar5; - float fVar6; - float accelFactor; - float fVar8; - float fVar9; - float in_XMM2_Da; - float moveY; - float velocityY; - float local_54; - float moveTimeFactor; - float inputX; - int stepsLeft; - void *entity; - int gridCollisionClass; - - inputX = *param_2; - local_54 = param_2[1]; - gridCollisionClass = *GHIDRA_CAST((GHIDRA_CAST(this->_entity) + 0x184)); - if (((*GHIDRA_CAST((GHIDRA_CAST(this->_entity) + 0x168)) & 0x8000) != 0) && (gridCollisionClass == 5)) { - local_54 = 0.0; - } - fVar4 = sqrtf(local_54 * local_54 + inputX * inputX); - if ((1.0 < fVar4) && (0.0 < fVar4)) { - inputX = *param_2 * (1.0 / fVar4); - local_54 = local_54 * (1.0 / fVar4); - } - fVar4 = in_XMM2_Da * 0.25 + 0.75; - moveY = fVar4 * local_54; - fVar4 = fVar4 * inputX; - (this->_moveDirection).y = moveY; - (this->_moveDirection).x = fVar4; - this->_direction = -1; - if (ABS(fVar4) <= ABS(moveY)) { - if (moveY < 0.0) { - this->_direction = 1; - goto LAB_007e813f; - } - gridCollisionClass = this->_direction; - if (0.0 < moveY) { - gridCollisionClass = 3; - } - } - else { - gridCollisionClass = 0; - if (0.0 <= fVar4) { - gridCollisionClass = 2; - } - } - this->_direction = gridCollisionClass; -LAB_007e813f: - entity = this->_entity; - if ((*GHIDRA_CAST((GHIDRA_CAST(entity) + 0x168)) & 0x8000000) == 0) { - piVar1 = &this->_moveCountdown; - *piVar1 = *piVar1 + -1; - gridCollisionClass = this->_moveCountdown; - if (*piVar1 < 0) { - this->_moveCountdown = 0; - gridCollisionClass = 0; - } - } - else { - this->_moveCountdown = 0x3c; - gridCollisionClass = 0x3c; - } - uVar3 = *GHIDRA_CAST((GHIDRA_CAST(entity) + 0x168)); - moveTimeFactor = ((float)gridCollisionClass - 0.0) / 60.0; - if ((uVar3 & 0x80) != 0) { - moveTimeFactor = 0.0; - } - velocityY = *GHIDRA_CAST((GHIDRA_CAST(entity) + 0x364)) * 0.5; - local_54 = *GHIDRA_CAST((GHIDRA_CAST(entity) + 0x360)) * 0.5; - fVar5 = moveTimeFactor; - accelFactor = Math::lerp(-0.2,0.5,moveTimeFactor,0); - fVar5 = Math::lerp(0.775,0.96,fVar5,isClamped); - fVar5 = sqrtf(fVar5); - uVar3 = uVar3 & 0x8000; - stepsLeft = 2; - do { - if (((fVar4 != 0.0) || (moveY != 0.0)) && ((uVar3 == 0 || (gridCollisionClass != 5)))) { - fVar8 = velocityY * moveY + local_54 * fVar4; - fVar9 = fVar8 * moveY; - fVar8 = fVar8 * fVar4; - fVar6 = Math::lerp(0.8,1.0,moveTimeFactor,0); - fVar6 = sqrtf(fVar6); - local_54 = (local_54 - fVar8) * fVar6 + fVar8; - velocityY = (velocityY - fVar9) * fVar6 + fVar9; - } - fVar8 = accelFactor * (velocityY * moveY + local_54 * fVar4); - if (fVar8 <= 0.0) { - fVar8 = 0.0; - } - fVar8 = (fVar8 / in_XMM2_Da + 3.0) * 0.4; - fVar8 = (fVar8 * 0.25 - fVar8) * moveTimeFactor + fVar8; - fVar6 = local_54 + fVar4 * 0.5 * fVar8; - fVar8 = velocityY + moveY * 0.5 * fVar8; - if (((0.0 < moveTimeFactor) && - (fVar9 = fVar6 * fVar6 + fVar8 * fVar8, in_XMM2_Da * 4.41 * in_XMM2_Da * 4.41 < fVar9)) && - (fVar9 = sqrtf(fVar9), 0.0 < fVar9)) { - accelFactor = sqrtf(velocityY * velocityY + local_54 * local_54); - fVar8 = (accelFactor / fVar9) * fVar8; - fVar6 = (accelFactor / fVar9) * fVar6; - } - local_54 = fVar6 * fVar5; - if ((uVar3 == 0) || (gridCollisionClass != 5)) { - velocityY = fVar8 * fVar5; - } - else { - velocityY = fVar8 + 0.225; - } - stepsLeft = stepsLeft + -1; - } while (stepsLeft != 0); - *GHIDRA_CAST((GHIDRA_CAST(entity) + 0x360)) = local_54 + local_54; - *GHIDRA_CAST((GHIDRA_CAST(entity) + 0x364)) = velocityY + velocityY; - return; -} diff --git a/generated-src/path_finder.cpp b/generated-src/path_finder.cpp deleted file mode 100644 index 0f7b629..0000000 --- a/generated-src/path_finder.cpp +++ /dev/null @@ -1,1352 +0,0 @@ -#include "classes.h" - -// 00456370 -int PathFinder::GetGridIndex() -{ - return *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x20)))); -} - -// 00456740 -uint32_t PathFinder::GetEvadeMovementCountdown() -{ - int in_ECX; - - return *GHIDRA_CAST((in_ECX + 0x73c)); -} - -// 00499dc0 -void PathFinder::SetCanCrushRocks(uint8_t param_1) -{ - int in_ECX; - - *GHIDRA_CAST((in_ECX + 0x738)) = param_1; - return; -} - -// 004be6e0 -uint8_t PathFinder::HasDirectPath() -{ - return this->_hasDirectPath; -} - -// 007e31a0 -void PathFinder::Init(Entity *owner) -{ - void *nodeMapHead; - - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) = 0; - *GHIDRA_CAST(this) = owner; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x734)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x730)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0xc)))) = 0; - nodeMapHead = operator_new(0x14); - *(void **)nodeMapHead = nodeMapHead; - *(void **)(GHIDRA_CAST(nodeMapHead) + 4) = nodeMapHead; - *(void **)(GHIDRA_CAST(nodeMapHead) + 8) = nodeMapHead; - *GHIDRA_CAST((GHIDRA_CAST(nodeMapHead) + 0xc)) = 0x101; - *(void **)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8))) = nodeMapHead; - Reset(this); - return; -} - -// 007e3260 -void PathFinder::Reset() -{ - int iVar1; - _Tree_node *root; - float zeroY; - - iVar1 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x20)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x24)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x28)))) = 0; - *GHIDRA_CAST(&this->_hasDirectPath) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x730)))) = g_vectorZero.x; - zeroY = g_vectorZero.y; - this->_evadeMovementCountdown = 0; - *GHIDRA_CAST((this + 1)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) = 0; - root = *(_Tree_node **)(iVar1 + 4); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x734)))) = zeroY; - FID_conflict__Erase_tree_>_> - (&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8))), - (fuzzer_allocator_> *)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8))),root); - *GHIDRA_CAST((iVar1 + 4)) = iVar1; - *GHIDRA_CAST(iVar1) = iVar1; - *GHIDRA_CAST((iVar1 + 8)) = iVar1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0xc)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x14)))) = 0xffffffff; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x18)))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x1c)))) = 0xffffffff; - (*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x738))) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = g_vectorZero.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = g_vectorZero.y; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) = g_vectorZero.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = g_vectorZero.y; - return; -} - -// 007e3340 -uint8_t PathFinder::is_entity_friendly() -{ - int iVar1; - uint8_t isTargetFriendly; - int entityType; - - iVar1 = *GHIDRA_CAST(this); - if (iVar1 == 0) { - return 0; - } - if (((*GHIDRA_CAST((iVar1 + 0x168)) & 0x100) == 0) && - (entityType = *GHIDRA_CAST((iVar1 + 0x28)), entityType != 0x322)) { - if ((*GHIDRA_CAST((iVar1 + 0x3c4)) != GHIDRA_CAST(0x0)) && - (isTargetFriendly = Entity::HasEntityFlags(*GHIDRA_CAST((iVar1 + 0x3c4)),0x10000000000000), - isTargetFriendly != 0)) { - return 1; - } - if (entityType < 10) { - return 0; - } - if (999 < entityType) { - return 0; - } - if ((*GHIDRA_CAST((iVar1 + 0xf1c)) == -1) && (*GHIDRA_CAST((iVar1 + 0xf38)) == 0)) { - return 0; - } - } - return 1; -} - -// 007e4940 -void PathFinder::EvadeTarget(Vector *targetPos, uint8_t isIgnoreStatusEffects) -{ - float *pfVar1; - uint8_t *puVar2; - uint8_t bVar3; - uint32_t uVar4; - Entity_NPC *npc; - Entity *playerTarget; - Vector **ppVVar5; - int iVar6; - uint64_t *foundNode; - int *newNode; - Vector *targetPos_00; - int iVar7; - int iVar8; - float gridIndex; - float fVar9; - float fVar10; - Room *pRVar11; - float fVar12; - uint8_t local_90 [12]; - uint8_t local_84 [8]; - Room *local_7c; - uint64_t insertPos; - Vector npcPosCopy; - Vector npcPos; - uint8_t *local_5c; - uint32_t local_58; - Vector scratchPos; - float local_4c; - float local_48; - float local_44; - float local_40; - Vector *local_3c; - float *local_38; - PathFinder *local_34; - float distToTarget; - float local_2c; - Room *local_28; - float attempt; - uint8_t *puStack_20; - void *local_1c; - uint8_t *puStack_18; - uint32_t local_14; - Game *game; - - puStack_20 = local_84 + 0x80; - local_14 = 0xffffffff; - puStack_18 = &LAB_00b00a1d; - local_1c = ExceptionList; - uVar4 = __security_cookie ^ GHIDRA_UINT((local_84 + 0x74)); - ExceptionList = &local_1c; - local_34 = this; - puVar2 = local_84 + 0x80; - if (isIgnoreStatusEffects == 0) { - bVar3 = is_entity_friendly(this); - puVar2 = puStack_20; - if (bVar3 != 0) { - npc = (Entity_NPC *) - __RTDynamicCast(*GHIDRA_CAST(this),0,&IsaacRepentancePlus::Entity::RTTI_Type_Descriptor - ,&IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0,uVar4); - playerTarget = Entity_NPC::GetPlayerTarget(npc); - scratchPos.x = (playerTarget->_pos).x; - scratchPos.y = (playerTarget->_pos).y; - FindGridPath(this,&scratchPos,1.079,0,1); - ExceptionList = local_1c; - return; - } - } - puStack_20 = puVar2; - iVar6 = *GHIDRA_CAST(this); - local_38 = GHIDRA_CAST((iVar6 + 0x33c)); - local_40 = targetPos->x - *local_38; - local_44 = targetPos->y - *GHIDRA_CAST((iVar6 + 0x340)); - distToTarget = sqrtf(local_40 * local_40 + local_44 * local_44); - local_3c = GHIDRA_CAST(0x41a00000); - ppVVar5 = &local_3c; - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) <= 20.0) { - ppVVar5 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))); - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) = *ppVVar5; - local_3c = *GHIDRA_CAST((iVar6 + 0x20)); - if ((((*GHIDRA_CAST((iVar6 + 0x168)) & 0x4000) == 0) && (bVar3 = Game::IsPaused(g_game), bVar3 == 0)) - && (pfVar1 = &local_3c->x, local_3c = GHIDRA_CAST(0xe), - (GHIDRA_INT(pfVar1) + g_game->_frameCount) % 0xe == 0)) { - scratchPos.x = *local_38; - scratchPos.y = local_38[1]; - bVar3 = Room::CheckLine(g_game->_room,&scratchPos,targetPos,1,0,0,0,GHIDRA_CAST(0x0)); - if (bVar3 == 0) { - fVar9 = 170.0; - } - else { - fVar9 = 250.0; - } - if (fVar9 <= distToTarget) { - iVar6 = *GHIDRA_CAST(this); - this->_evadeMovementCountdown = - this->_evadeMovementCountdown - - (GHIDRA_INT(*GHIDRA_CAST((iVar6 + 0x3a4))) - GHIDRA_INT(*GHIDRA_CAST((iVar6 + 0x3a0)))); - } - else { - if (this->_evadeMovementCountdown < 1) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = g_vectorZero.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = g_vectorZero.y; - } - iVar6 = *GHIDRA_CAST(this); - this->_evadeMovementCountdown = 3; - } - } - game = g_game; - local_3c = *GHIDRA_CAST((iVar6 + 0x20)); - if ((((*GHIDRA_CAST((iVar6 + 0x168)) & 0x4000) == 0) && (bVar3 = Game::IsPaused(g_game), bVar3 == 0)) - && ((GHIDRA_INT(&local_3c->x) + game->_frameCount) % 0x1e == 0)) { - iVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))); - FID_conflict__Erase_tree_>_> - (&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8))), - (fuzzer_allocator_> *)&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8))), - *(_Tree_node **)(iVar6 + 4)); - *GHIDRA_CAST((iVar6 + 4)) = iVar6; - *GHIDRA_CAST(iVar6) = iVar6; - *GHIDRA_CAST((iVar6 + 8)) = iVar6; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0xc)))) = 0; - this = local_34; - } - if (this->_evadeMovementCountdown < 1) { - fVar9 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))); - *GHIDRA_CAST((this + 1)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) = fVar9 * 0.9; - MoveRandomly(this,1); - *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x36c)) = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x36c)) * 0.9; - ExceptionList = local_1c; - return; - } - local_3c = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))); - if (((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) == g_vectorZero.x) && - (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) == g_vectorZero.y)) || (20.0 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))))) { - local_2c = g_vectorZero.x; - local_28 = GHIDRA_CAST(g_vectorZero.y); - attempt = 0.0; - if (0.0 < distToTarget) { - local_2c = local_40 / -distToTarget; - local_28 = GHIDRA_CAST((local_44 / -distToTarget)); - } - fVar9 = local_2c; - pRVar11 = local_28; - if (ABS(ABS(local_2c) - ABS((float)local_28)) < 0.25) { - uVar4 = Random(); - if ((uVar4 & 1) == 0) { - fVar9 = local_2c * 0.5; - pRVar11 = local_28; - } - else { - pRVar11 = GHIDRA_CAST(((float)local_28 * 0.5)); - fVar9 = local_2c; - } - } - iVar6 = *GHIDRA_CAST(this); - fVar10 = *GHIDRA_CAST((iVar6 + 0x36c)); - if (fVar10 != 0.0) { - *GHIDRA_CAST((iVar6 + 0x360)) = - (fVar9 * 1.5 * *GHIDRA_CAST((iVar6 + 0x39c))) / fVar10 + *GHIDRA_CAST((iVar6 + 0x360)); - *GHIDRA_CAST((iVar6 + 0x364)) = - ((float)pRVar11 * 1.5 * *GHIDRA_CAST((iVar6 + 0x39c))) / fVar10 + *GHIDRA_CAST((iVar6 + 0x364)); - iVar6 = *GHIDRA_CAST(this); - } - local_48 = *GHIDRA_CAST((iVar6 + 0x33c)) + fVar9 * 30.0; - local_4c = *GHIDRA_CAST((iVar6 + 0x340)) + (float)pRVar11 * 30.0; - if (0.0 < 7.0 - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) * 0.3) { - do { - uVar4 = Random(); - local_34 = (PathFinder *) - ((float)((double)GHIDRA_INT(uVar4) + __uint_to_double_fixup[-(GHIDRA_INT(uVar4) >> 0x1f)]) * - 2.3283064e-10 * 450.0 + 30.0); - uVar4 = Random(); - local_44 = (float)((double)GHIDRA_INT(uVar4) + __uint_to_double_fixup[-(GHIDRA_INT(uVar4) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_44 = local_44 + local_44; - local_40 = sin(local_44); - fVar9 = cos(local_44); - fVar10 = 0.5; - scratchPos.x = fVar9 * (float)local_34 + local_48; - fVar9 = 40.0; - fVar12 = 120.0; - scratchPos.y = local_40 * 0.5 * (float)local_34 + local_4c; - iVar7 = GHIDRA_INT(((scratchPos.x - 40.0) / 40.0 + 0.5)); - iVar6 = GHIDRA_INT(((scratchPos.y - 120.0) / 40.0 + 0.5)); - if ((((iVar7 < 0) || (iVar8 = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc)), iVar8 <= iVar7)) || - (iVar6 < 0)) || (*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x10)) <= iVar6)) { - gridIndex = -NAN; - } - else { - gridIndex = (float)(iVar8 * iVar6 + iVar7); - } - local_2c = gridIndex; - msvc::set::find_node(local_84,&local_2c); - if ((*GHIDRA_CAST((GHIDRA_INT(&local_7c->_gridWidth) + 1)) == '\0') && - (local_7c->_gridHeight <= GHIDRA_INT(gridIndex))) { - local_28 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))); - if (local_7c == local_28) goto LAB_007e4e8c; - attempt = attempt - 0.7; - } - else { - local_28 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8)))); -LAB_007e4e8c: - foundNode = GHIDRA_CAST(std)::set::find_node(local_90,&local_2c); - insertPos = *foundNode; - if ((*GHIDRA_CAST((*GHIDRA_CAST((foundNode + 1)) + 0xd)) != '\0') || - (GHIDRA_INT(gridIndex) < *GHIDRA_CAST((*GHIDRA_CAST((foundNode + 1)) + 0x10)))) { - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0xc)))) == 0xccccccc) { - /* WARNING: Subroutine does not return */ - FUN_004170d0(); - } - local_14 = 0; - local_58 = 0; - local_5c = &(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8))); - newNode = operator_new(0x14); - local_14 = 0xffffffff; - local_58 = 0; - newNode[4] = GHIDRA_INT(gridIndex); - *newNode = GHIDRA_INT(local_28); - newNode[1] = GHIDRA_INT(local_28); - newNode[2] = GHIDRA_INT(local_28); - *GHIDRA_CAST((newNode + 3)) = 0; - (GHIDRA_CAST((&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x8))))))->msvc::_Tree::_Insert_node((void *)insertPos,(*GHIDRA_CAST((GHIDRA_CAST(&(insertPos)) + 0x4))),newNode); - fVar9 = 40.0; - fVar10 = 0.5; - fVar12 = 120.0; - } - pRVar11 = g_game->_room; - iVar6 = pRVar11->_gridWidth; - scratchPos.x = (float)(GHIDRA_INT(gridIndex) % iVar6) * fVar9 + fVar9; - scratchPos.y = (float)(GHIDRA_INT(gridIndex) / iVar6) * fVar9 + fVar12; - iVar8 = GHIDRA_INT(((scratchPos.x - fVar9) / fVar9 + fVar10)); - iVar7 = GHIDRA_INT(((scratchPos.y - fVar12) / fVar9 + fVar10)); - if ((((iVar8 < 0) || (iVar6 <= iVar8)) || (iVar7 < 0)) || (pRVar11->_gridHeight <= iVar7)) - { - iVar8 = -1; - } - else { - iVar8 = iVar6 * iVar7 + iVar8; - } - local_38 = GHIDRA_CAST(scratchPos.y); - local_2c = scratchPos.x; - local_28 = pRVar11; - uVar4 = Room::GetGridCollision(pRVar11,iVar8); - if (uVar4 == 0) { - npcPos.x = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x33c)); - npcPos.y = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x340)); - bVar3 = Room::CheckLine(pRVar11,&npcPos,&scratchPos,1,0,(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x738))),0, - GHIDRA_CAST(0x0)); - if (bVar3 != 0) { - npcPosCopy.x = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x33c)); - npcPosCopy.y = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x340)); - bVar3 = Room::CheckLine(g_game->_room,targetPos,&npcPosCopy,1,0,(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x738))),0, - GHIDRA_CAST(0x0)); - if ((bVar3 == 0) || (20.0 <= *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))))) { - local_44 = *GHIDRA_CAST((this + 1)); - fVar9 = targetPos->y - (float)local_38; - fVar10 = targetPos->x - local_2c; - fVar9 = sqrtf(fVar9 * fVar9 + fVar10 * fVar10); - if (((float)local_34 / 3.0 + distToTarget + 100.0 + *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4))))) - - local_44 <= fVar9) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = local_2c; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = local_38; - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) < 20.0) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) * 0.5; - } - break; - } - *GHIDRA_CAST((this + 1)) = local_44 + 10.0; - } - else { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) + 0.35; - } - } - } - } - attempt = attempt + 1.0; - } while (attempt < 7.0 - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) * 0.3); - } - } - game = g_game; - local_48 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))); - if ((local_48 == g_vectorZero.x) && (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) == g_vectorZero.y)) { - ExceptionList = local_1c; - return; - } - local_4c = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x20)); - targetPos_00 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))); - fVar9 = local_48; - if ((*GHIDRA_CAST((*GHIDRA_CAST(this) + 0x168)) & 0x4000) == 0) { - bVar3 = Game::IsPaused(g_game); - if (bVar3 == 0) { - iVar6 = game->_frameCount + GHIDRA_INT(local_4c); - local_4c = 1.4013e-44; - targetPos_00 = local_3c; - fVar9 = local_3c->x; - if (iVar6 % 10 == 0) { - bVar3 = Room::CheckLine(game->_room,targetPos,local_3c,1,0,(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x738))),0,GHIDRA_CAST(0x0) - ); - if ((bVar3 == 0) || - (20.0 < *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) || *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) == 20.0)) { - fVar10 = targetPos->x - local_3c->x; - fVar9 = targetPos->y - local_3c->y; - targetPos_00 = local_3c; - if ((40000.0 <= fVar9 * fVar9 + fVar10 * fVar10) && - ((20.0 <= ABS(fVar10) && - (fVar9 = local_3c->x, 20.0 <= ABS(targetPos->y - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8))))))))) - goto LAB_007e529c; - } - else { - targetPos_00 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))); - } - targetPos_00->x = g_vectorZero.x; - targetPos_00->y = g_vectorZero.y; - fVar9 = targetPos_00->x; - } - } - else { - targetPos_00 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))); - fVar9 = local_48; - } - } -LAB_007e529c: - if ((fVar9 != g_vectorZero.x) || (targetPos_00->y != g_vectorZero.y)) { - FindGridPath(this,targetPos_00,1.079,0,1); - } - ExceptionList = local_1c; - return; -} - -// 007e5340 -void PathFinder::MoveRandomlyAxisAligned(float speed, uint8_t isIgnoreStatusEffects) -{ - void *pvVar1; - uint8_t isFriendly; - Entity_NPC *npc; - Entity *playerTarget; - Vector *pVVar2; - uint32_t uVar3; - uint32_t uVar4; - uint32_t uVar5; - uint32_t *velocityX; - float *clampedY; - uint32_t gridPath; - uint32_t uVar6; - uint32_t uVar7; - int iVar8; - int iVar9; - int iVar10; - float fVar11; - float fVar12; - float fVar13; - float fVar14; - float toPlayerDirX; - float fVar15; - uint32_t local_a0; - int local_9c; - int local_94; - uint32_t *local_8c; - Vector *local_80; - Vector scratchVec; - Vector local_74; - int attemptsLeft; - float roomMinX; - float roomMaxX; - Vector dirVec; - Vector chosenDirVec; - uint32_t dirDistances [7]; - Vector axisDirs [4]; - Room *room; - uint32_t candidateDir; - Game *game; - Room *gridRoom; - uint8_t *movementTargetY; - int *roomConfig; - - iVar8 = *GHIDRA_CAST(this); - if (*GHIDRA_CAST((iVar8 + 0x3d4)) == 0) { - if ((isIgnoreStatusEffects == 0) && (isFriendly = is_entity_friendly(this), isFriendly != 0)) { - npc = (Entity_NPC *) - __RTDynamicCast(iVar8,0,&IsaacRepentancePlus::Entity::RTTI_Type_Descriptor, - &IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0); - Entity_NPC::CalcTargetPosition(npc,&scratchVec,0.0); - if (((*GHIDRA_CAST((*GHIDRA_CAST(this) + 0x168)) & 0x20000000) != 0) && - ((playerTarget = Entity_NPC::GetPlayerTarget(npc), playerTarget->_type == 1 && - (scratchVec.x = (npc->_pos).x - scratchVec.x, scratchVec.y = (npc->_pos).y - scratchVec.y, - scratchVec.y * scratchVec.y + scratchVec.x * scratchVec.x < 1600.0)))) { - *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x36c)) = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x36c)) * 0.8; - return; - } - pVVar2 = Entity_NPC::CalcTargetPosition(npc,&scratchVec,0.0); - FindGridPath(this,pVVar2,speed,0,1); - scratchVec.y = (npc->_velocity).y; - scratchVec.x = (npc->_velocity).x; - pVVar2 = Vector::ToCardinal(&local_74,&scratchVec); - fVar15 = (npc->_velocity).y; - fVar11 = (npc->_velocity).x; - fVar11 = sqrtf(fVar11 * fVar11 + fVar15 * fVar15); - fVar15 = pVVar2->x; - (npc->_velocity).y = fVar11 * pVVar2->y; - (npc->_velocity).x = fVar11 * fVar15; - return; - } - game = g_game; - axisDirs[0].x = (float)&DAT_bf800000; - axisDirs[0].y = 0.0; - axisDirs[1].x = 0.0; - axisDirs[1].y = (float)&DAT_bf800000; - iVar8 = g_game->_frameCount; - iVar10 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x1c)))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x1c)))) = iVar8; - room = game->_room; - axisDirs[2].x = 1.0; - axisDirs[2].y = 0.0; - axisDirs[3].x = 0.0; - axisDirs[3].y = 1.0; - local_74.x = (float)(iVar8 - iVar10); - roomMinX = (room->_topLeftPos).x; - scratchVec.x = roomMinX; - fVar15 = (room->_topLeftPos).y; - roomMaxX = (room->_bottomRightPos).x; - fVar11 = (room->_bottomRightPos).y; - scratchVec.y = fVar15; - iVar8 = 10; -LAB_007e5558: - do { - fVar14 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))); - if (((fVar14 != g_vectorZero.x) || (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) != g_vectorZero.y)) || - (iVar8 < 1)) goto LAB_007e5f59; - local_8c = dirDistances; - local_a0 = 1; - attemptsLeft = iVar8 + -1; - local_80 = axisDirs; - dirDistances[0] = 0; - dirDistances[1] = 0; - dirDistances[2] = 0; - dirDistances[3] = 0; - local_9c = 4; - do { - uVar3 = Random(); - uVar3 = uVar3 % 0xc; - iVar8 = *GHIDRA_CAST(this); - if ((*GHIDRA_CAST((iVar8 + 0x168)) & 0x1000800) != 0) { - uVar3 = Random(); - iVar8 = *GHIDRA_CAST(this); - uVar3 = (uVar3 & 3) + 1; - } - clampedY = GHIDRA_CAST((iVar8 + 0x340)); - fVar14 = local_80->x; - fVar13 = (float)(uVar3 * 0x28) * fVar14 + *GHIDRA_CAST((iVar8 + 0x33c)); - fVar12 = (float)(uVar3 * 0x28) * local_80->y + *GHIDRA_CAST((iVar8 + 0x340)); - if (((roomMaxX < fVar13) || (fVar13 < roomMinX)) || (fVar11 < fVar12)) { -LAB_007e5667: - fVar12 = g_vectorZero.y; - fVar13 = g_vectorZero.x; - } - else if (fVar12 < fVar15) goto LAB_007e5667; - if ((fVar13 != g_vectorZero.x) || (fVar12 != g_vectorZero.y)) { - iVar10 = 1; - if (1 < uVar3) { - local_94 = 0x28; - pvVar1 = g_game->_room; - do { - fVar12 = ((fVar14 * (float)local_94 + *GHIDRA_CAST((iVar8 + 0x33c))) - 40.0) / 40.0 + 0.5; - iVar8 = GHIDRA_INT(fVar12); - if ((((iVar8 < 0) || (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)) <= iVar8)) || - (iVar8 = GHIDRA_INT((((local_80->y * (float)local_94 + *clampedY) - 120.0) / 40.0 + 0.5)) - , iVar8 < 0)) || - ((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x10)) <= iVar8 || - (uVar6 = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)) * iVar8 + GHIDRA_INT(fVar12), 0x1bf < uVar6)))) { - uVar6 = 0; - } - else { - uVar6 = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + uVar6 * 4 + 0x76c)); - } - iVar8 = *GHIDRA_CAST(this); - if (*GHIDRA_CAST((iVar8 + 0x184)) == 6) { - uVar4 = uVar6 - 3000; - if (999 < uVar6 - 3000) { - uVar4 = uVar6; - } - uVar6 = uVar4; - } - else if (*GHIDRA_CAST((iVar8 + 0x184)) != 5) { - if (uVar6 - 1000 < 1000) { - uVar6 = uVar6 - 1000; - } - if (uVar6 - 3000 < 1000) { - uVar6 = uVar6 - 3000; - } - } - if (((300 < GHIDRA_INT(uVar6)) && ((0 < attemptsLeft || (0x3e6 < GHIDRA_INT(uVar6))))) && - (((*GHIDRA_CAST((iVar8 + 0x168)) & 0x1000800) == 0 || (800 < GHIDRA_INT(uVar6))))) { - uVar3 = iVar10 - 1; - break; - } - iVar10 = iVar10 + 1; - local_94 = local_94 + 0x28; - } while (iVar10 < GHIDRA_INT(uVar3)); - } - iVar8 = *GHIDRA_CAST(this); - fVar12 = (float)GHIDRA_INT((uVar3 * 0x28)) * local_80->y + *GHIDRA_CAST((iVar8 + 0x340)); - fVar14 = (float)GHIDRA_INT((uVar3 * 0x28)) * fVar14 + *GHIDRA_CAST((iVar8 + 0x33c)); - uVar6 = local_a0 + 2 & 0x80000003; - if (GHIDRA_INT(uVar6) < 0) { - uVar6 = (uVar6 - 1 | 0xfffffffc) + 1; - } - uVar4 = local_a0 & 0x80000003; - if (GHIDRA_INT(uVar4) < 0) { - uVar4 = (uVar4 - 1 | 0xfffffffc) + 1; - } - pvVar1 = g_game->_room; - iVar10 = GHIDRA_INT((((axisDirs[uVar6].x * 40.0 + fVar14) - 40.0) / 40.0 + 0.5)); - if ((((iVar10 < 0) || (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)) <= iVar10)) || - (iVar9 = GHIDRA_INT((((axisDirs[uVar6].y * 40.0 + fVar12) - 120.0) / 40.0 + 0.5)), iVar9 < 0) - ) || ((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x10)) <= iVar9 || - (uVar6 = iVar9 * *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)) + iVar10, 0x1bf < uVar6)))) { - uVar6 = 0; - } - else { - uVar6 = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + uVar6 * 4 + 0x76c)); - } - if (iVar8 != 0) { - if (*GHIDRA_CAST((iVar8 + 0x184)) == 6) { - if (uVar6 - 3000 < 1000) { - uVar6 = uVar6 - 3000; - } - } - else if (*GHIDRA_CAST((iVar8 + 0x184)) != 5) { - if (uVar6 - 1000 < 1000) { - uVar6 = uVar6 - 1000; - } - if (uVar6 - 3000 < 1000) { - uVar6 = uVar6 - 3000; - } - } - } - iVar10 = GHIDRA_INT((((axisDirs[uVar4].x * 40.0 + fVar14) - 40.0) / 40.0 + 0.5)); - iVar9 = GHIDRA_INT((((axisDirs[uVar4].y * 40.0 + fVar12) - 120.0) / 40.0 + 0.5)); - if (((iVar10 < 0) || (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)) <= iVar10)) || - ((iVar9 < 0 || - ((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x10)) <= iVar9 || - (uVar4 = iVar9 * *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)) + iVar10, 0x1bf < uVar4)))))) { - uVar4 = 0; - } - else { - uVar4 = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + uVar4 * 4 + 0x76c)); - } - if (iVar8 != 0) { - if (*GHIDRA_CAST((iVar8 + 0x184)) == 6) { - if (uVar4 - 3000 < 1000) { - uVar4 = uVar4 - 3000; - } - } - else if (*GHIDRA_CAST((iVar8 + 0x184)) != 5) { - if (uVar4 - 1000 < 1000) { - uVar4 = uVar4 - 1000; - } - if (uVar4 - 3000 < 1000) { - uVar4 = uVar4 - 3000; - } - } - } - if (((GHIDRA_INT(uVar6) < 200) || (GHIDRA_INT(uVar4) < 200)) || (uVar6 = Random(), uVar6 % 10 == 0)) { - *local_8c = uVar3; - } - } - local_80 = local_80 + 1; - local_a0 = local_a0 + 1; - local_8c = local_8c + 1; - local_9c = local_9c + -1; - } while (local_9c != 0); - uVar6 = 0; - uVar3 = 0xffffffff; - npc = (Entity_NPC *) - __RTDynamicCast(*GHIDRA_CAST(this),0,&IsaacRepentancePlus::Entity::RTTI_Type_Descriptor - ,&IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0); - uVar4 = Random(); - uVar4 = uVar4 & 3; - if (((*GHIDRA_CAST((*GHIDRA_CAST(this) + 0x168)) & 0x1000800) == 0) || (npc == GHIDRA_CAST(0x0))) { -LAB_007e5b55: - iVar8 = uVar4 + 4; - uVar7 = uVar6; - do { - uVar5 = uVar4 & 0x80000003; - if (GHIDRA_INT(uVar5) < 0) { - uVar5 = (uVar5 - 1 | 0xfffffffc) + 1; - } - uVar6 = dirDistances[uVar5]; - if (GHIDRA_INT(dirDistances[uVar5]) <= GHIDRA_INT(uVar7)) { - uVar6 = uVar7; - uVar5 = uVar3; - } - uVar3 = uVar5; - uVar4 = uVar4 + 1; - uVar7 = uVar6; - } while (GHIDRA_INT(uVar4) < iVar8); - } - else { - playerTarget = Entity_NPC::GetPlayerTarget(npc); - fVar14 = (playerTarget->_pos).x - *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x33c)); - fVar12 = (playerTarget->_pos).y - *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x340)); - uVar7 = uVar4; - do { - uVar5 = uVar7 & 0x80000003; - if (GHIDRA_INT(uVar5) < 0) { - uVar5 = (uVar5 - 1 | 0xfffffffc) + 1; - } - pVVar2 = Isaac::GetAxisAlignedUnitVectorFromDir(&dirVec,uVar5); - if (fVar12 * pVVar2->y + fVar14 * pVVar2->x <= 0.0) { - if (GHIDRA_INT(uVar6) < GHIDRA_INT(dirDistances[uVar5])) { - uVar6 = dirDistances[uVar5]; - uVar3 = uVar5; - } - } - uVar7 = uVar7 + 1; - } while (GHIDRA_INT(uVar7) < GHIDRA_INT((uVar4 + 4))); - if (uVar6 == 0) { - if (ABS(fVar12) <= ABS(fVar14)) { - uVar5 = 1; - uVar7 = uVar6; - do { - uVar6 = dirDistances[uVar5]; - candidateDir = uVar5; - if (GHIDRA_INT(dirDistances[uVar5]) <= GHIDRA_INT(uVar7)) { - uVar6 = uVar7; - candidateDir = uVar3; - } - uVar3 = candidateDir; - uVar5 = uVar5 + 2; - uVar7 = uVar6; - } while (GHIDRA_INT(uVar5) < 4); - } - else { - uVar5 = 0; - uVar7 = uVar6; - do { - uVar6 = dirDistances[uVar5]; - candidateDir = uVar5; - if (GHIDRA_INT(dirDistances[uVar5]) <= GHIDRA_INT(uVar7)) { - uVar6 = uVar7; - candidateDir = uVar3; - } - uVar3 = candidateDir; - uVar5 = uVar5 + 2; - uVar7 = uVar6; - } while (GHIDRA_INT(uVar5) < 4); - } - if (uVar6 == 0) goto LAB_007e5b55; - } - } - if (((GHIDRA_INT(uVar6) < 2) && (uVar4 = Random(), uVar4 % 10 != 0)) && - ((*GHIDRA_CAST((*GHIDRA_CAST(this) + 0x168)) & 0x1000800) == 0)) { - uVar3 = 0xffffffff; - } - uVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x14)))) - uVar3; - uVar7 = GHIDRA_INT(uVar4) >> 0x1f; - if (((((uVar4 ^ uVar7) - uVar7 != 2) || (uVar4 = Random(), uVar4 % 5 == 0)) || - ((*GHIDRA_CAST((*GHIDRA_CAST(this) + 0x168)) & 0x1000800) != 0)) && (-1 < GHIDRA_INT(uVar3))) { - if ((*GHIDRA_CAST((*GHIDRA_CAST(this) + 0x168)) & 0x1000800) != 0) { - pVVar2 = Isaac::GetAxisAlignedUnitVectorFromDir(&chosenDirVec,uVar3); - playerTarget = Entity_NPC::GetPlayerTarget(npc); - fVar14 = (playerTarget->_pos).y - *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x340)); - toPlayerDirX = (playerTarget->_pos).x - *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x33c)); - fVar12 = sqrtf(fVar14 * fVar14 + toPlayerDirX * toPlayerDirX); - if (0.0 < fVar12) { - toPlayerDirX = toPlayerDirX * (1.0 / fVar12); - fVar14 = fVar14 * (1.0 / fVar12); - } - if (0.95 < fVar14 * pVVar2->y + toPlayerDirX * pVVar2->x) goto LAB_007e5bf0; - } - fVar14 = axisDirs[uVar3].x; - pvVar1 = g_game->_room; - fVar12 = ((fVar14 * (float)GHIDRA_INT((uVar6 * 0x28)) + *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x33c))) - 40.0) / - 40.0 + 0.5; - iVar8 = GHIDRA_INT(fVar12); - if (((iVar8 < 0) || (iVar10 = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)), iVar10 <= iVar8)) || - ((iVar8 = GHIDRA_INT(((((float)GHIDRA_INT((uVar6 * 0x28)) * axisDirs[uVar3].y + - *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x340))) - 120.0) / 40.0 + 0.5)), iVar8 < 0 || - (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x10)) <= iVar8)))) { - iVar10 = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)); - iVar8 = -1; - } - else { - iVar8 = iVar8 * iVar10 + GHIDRA_INT(fVar12); - } - fVar12 = (float)(iVar8 % iVar10) * 40.0 + 40.0; - fVar13 = (float)(iVar8 / iVar10) * 40.0 + 120.0; - iVar8 = GHIDRA_INT(((fVar12 - 40.0) / 40.0 + 0.5)); - if (((iVar8 < 0) || (iVar10 <= iVar8)) || - ((iVar9 = GHIDRA_INT(((fVar13 - 120.0) / 40.0 + 0.5)), iVar9 < 0 || - (((*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x10)) <= iVar9 || - (uVar6 = iVar9 * iVar10 + iVar8, 0x1bf < uVar6)) || - (*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + uVar6 * 4 + 0x76c)) != 999)))))) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x14)))) = uVar3; - gridRoom = g_game->_room; - iVar10 = GHIDRA_INT(((fVar13 - 120.0) / 40.0 + 0.5)); - if ((((iVar8 < 0) || (gridRoom->_gridWidth <= iVar8)) || (iVar10 < 0)) || - (gridRoom->_gridHeight <= iVar10)) { - iVar9 = -1; - } - else { - iVar9 = iVar10 * gridRoom->_gridWidth + iVar8; - } - roomConfig = *GHIDRA_CAST((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((gridRoom)) + 0x4)))) + 0x10)); - if (((roomConfig != GHIDRA_CAST(0x0)) && (roomConfig[2] == 0x10)) && (*roomConfig == 0x23)) - goto LAB_007e5ee3; - if (-1 < iVar9) { - if (gridRoom->_gridEntities[iVar9] == (void *)0x0) { - if ((2999 < gridRoom->_gridPaths[iVar9]) || (999 < gridRoom->_gridPaths[iVar9])) - goto LAB_007e5e93; - } - else if (*GHIDRA_CAST((GHIDRA_INT(gridRoom->_gridEntities[iVar9]) + 0x3c)) != 0) goto LAB_007e5e93; -LAB_007e5ee3: - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = fVar12; - fVar12 = axisDirs[uVar3].y; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = fVar13; - iVar10 = *GHIDRA_CAST(this); - velocityX = GHIDRA_CAST((iVar10 + 0x360)); - iVar8 = attemptsLeft; - if (ABS(fVar14) <= ABS(fVar12)) { - *velocityX = 0; - *GHIDRA_CAST((iVar10 + 0x364)) = *GHIDRA_CAST((iVar10 + 0x364)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x18)))) = 0; - } - else { - *velocityX = *velocityX; - *GHIDRA_CAST((iVar10 + 0x364)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x18)))) = 0; - } - goto LAB_007e5558; - } -LAB_007e5e93: - if (npc->_entityGridCollisionClass == 3) { - if ((((iVar8 < 0) || (gridRoom->_gridWidth <= iVar8)) || (iVar10 < 0)) || - (gridRoom->_gridHeight <= iVar10)) { - iVar8 = -1; - } - else { - iVar8 = gridRoom->_gridWidth * iVar10 + iVar8; - } - uVar6 = Room::GetGridCollision(gridRoom,iVar8); - if (uVar6 != 4) goto LAB_007e5ee3; - } - } - } -LAB_007e5bf0: - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x18)))) = 0; - iVar8 = attemptsLeft; - } while( true ); - } -LAB_007e62e0: - return; -LAB_007e5f59: - if ((fVar14 != g_vectorZero.x) || (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) != g_vectorZero.y)) { - if (1 < GHIDRA_INT(local_74.x)) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = g_vectorZero.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = g_vectorZero.y; - return; - } - pVVar2 = &scratchVec; - if (roomMinX < fVar14) { - pVVar2 = GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))); - } - fVar14 = pVVar2->x; - if (roomMaxX <= fVar14) { - fVar14 = roomMaxX; - } - movementTargetY = &(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = fVar14; - clampedY = &scratchVec.y; - if (fVar15 < *GHIDRA_CAST(movementTargetY)) { - clampedY = GHIDRA_CAST(movementTargetY); - } - fVar15 = *clampedY; - if (fVar11 <= fVar15) { - fVar15 = fVar11; - } - iVar8 = *GHIDRA_CAST(this); - *GHIDRA_CAST(movementTargetY) = fVar15; - fVar14 = (*GHIDRA_CAST((iVar8 + 0x33c)) + *GHIDRA_CAST((iVar8 + 0x360))) - fVar14; - fVar15 = (*GHIDRA_CAST((iVar8 + 0x340)) + *GHIDRA_CAST((iVar8 + 0x364))) - fVar15; - local_74.x = fVar15 * fVar15 + fVar14 * fVar14; - fVar11 = sqrtf(local_74.x); - if (5.0 <= fVar11) { - fVar11 = sqrtf(*GHIDRA_CAST((iVar8 + 0x360)) * *GHIDRA_CAST((iVar8 + 0x360)) + - *GHIDRA_CAST((iVar8 + 0x364)) * *GHIDRA_CAST((iVar8 + 0x364))); - if ((fVar11 < 0.6) && - (iVar8 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x18)))) + 1, *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x18)))) = iVar8, 10 < iVar8)) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = g_vectorZero.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = g_vectorZero.y; - } - } - else { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = g_vectorZero.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = g_vectorZero.y; - } - fVar11 = sqrtf(local_74.x); - if (0.0 < fVar11) { - fVar15 = fVar15 * (1.0 / fVar11); - fVar14 = fVar14 * (1.0 / fVar11); - } - iVar8 = *GHIDRA_CAST(this); - fVar11 = *GHIDRA_CAST((iVar8 + 0x36c)); - if (fVar11 != 0.0) { - *GHIDRA_CAST((iVar8 + 0x364)) = - (*GHIDRA_CAST((iVar8 + 0x39c)) * -fVar15 * speed) / fVar11 + *GHIDRA_CAST((iVar8 + 0x364)); - *GHIDRA_CAST((iVar8 + 0x360)) = - (*GHIDRA_CAST((iVar8 + 0x39c)) * -fVar14 * speed) / fVar11 + *GHIDRA_CAST((iVar8 + 0x360)); - iVar8 = *GHIDRA_CAST(this); - } - fVar15 = *GHIDRA_CAST((iVar8 + 0x33c)); - fVar11 = *GHIDRA_CAST((iVar8 + 0x360)); - local_74.x = *GHIDRA_CAST((iVar8 + 0x364)); - fVar14 = *GHIDRA_CAST((iVar8 + 0x340)); - fVar12 = sqrtf(fVar11 * fVar11 + local_74.x * local_74.x); - if (fVar12 <= 0.0) { - fVar12 = local_74.x; - } - else { - fVar11 = *GHIDRA_CAST((iVar8 + 0x360)) * (1.0 / fVar12); - fVar12 = *GHIDRA_CAST((iVar8 + 0x364)) * (1.0 / fVar12); - } - pvVar1 = g_game->_room; - iVar8 = GHIDRA_INT((((fVar11 * 40.0 + fVar15) - 40.0) / 40.0 + 0.5)); - if ((((iVar8 < 0) || (*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)) <= iVar8)) || - (iVar10 = GHIDRA_INT((((fVar12 * 40.0 + fVar14) - 120.0) / 40.0 + 0.5)), iVar10 < 0)) || - ((*GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0x10)) <= iVar10 || - (uVar3 = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + 0xc)) * iVar10 + iVar8, 0x1bf < uVar3)))) { - gridPath = 0; - } - else { - gridPath = *GHIDRA_CAST((GHIDRA_CAST(pvVar1) + uVar3 * 4 + 0x76c)); - } - iVar8 = FUN_007e7fb0(gridPath); - if (((700 < iVar8) && - (fVar15 = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x360)), fVar11 = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x364)), - fVar15 = sqrtf(fVar11 * fVar11 + fVar15 * fVar15), 3.0 < fVar15)) && - (iVar8 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x18)))) + 1, *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x18)))) = iVar8, 2 < iVar8)) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = g_vectorZero.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = g_vectorZero.y; - } - } - goto LAB_007e62e0; -} - -// 007e6300 -uint8_t PathFinder::MoveRandomly(uint8_t isIgnoreStatusEffects) -{ - Vector pos; - uint8_t bVar1; - Entity_NPC *npc; - Vector *targetPos; - Entity *target; - uint32_t rngValue; - float fVar2; - float fVar3; - float fVar4; - int iVar5; - Vector local_10; - - iVar5 = *GHIDRA_CAST(this); - if (*GHIDRA_CAST((iVar5 + 0x3d4)) != 0) { - return 1; - } - if (isIgnoreStatusEffects == 0) { - bVar1 = is_entity_friendly(this); - if (bVar1 != 0) { - npc = (Entity_NPC *) - __RTDynamicCast(iVar5,0,&IsaacRepentancePlus::Entity::RTTI_Type_Descriptor, - &IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0); - bVar1 = 1; - iVar5 = 0; - fVar4 = 0.5; - targetPos = Entity_NPC::CalcTargetPosition(npc,&local_10,0.0); - FindGridPath(this,targetPos,fVar4,iVar5,bVar1); - return 1; - } - if ((*GHIDRA_CAST((iVar5 + 0x168)) & 0x1000800) != 0) { - npc = (Entity_NPC *) - __RTDynamicCast(iVar5,0,&IsaacRepentancePlus::Entity::RTTI_Type_Descriptor, - &IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0); - target = Entity_NPC::GetPlayerTarget(npc); - local_10.x = (target->_pos).x; - local_10.y = (target->_pos).y; - EvadeTarget(this,&local_10,0); - return 1; - } - } - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) == g_vectorZero.x) && - (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) == g_vectorZero.y)) { - fVar4 = *GHIDRA_CAST((iVar5 + 0x33c)); - local_10.x = *GHIDRA_CAST((iVar5 + 0x340)); - rngValue = Random(); - fVar2 = (float)((double)GHIDRA_INT(rngValue) + __uint_to_double_fixup[-(GHIDRA_INT(rngValue) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - fVar2 = fVar2 + fVar2; - fVar3 = cos(fVar2); - fVar4 = fVar3 * 40.0 + fVar4; - fVar2 = sin(fVar2); - local_10.x = fVar2 * 40.0 + local_10.x; - pos.y = local_10.x; - pos.x = fVar4; - iVar5 = Room::GetGridCollisionAtPos(g_game->_room,pos); - if (iVar5 == 0) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = fVar4; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = local_10.x; - } - } - if ((*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) == g_vectorZero.x) && - (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) == g_vectorZero.y)) { - return 0; - } - iVar5 = *GHIDRA_CAST(this); - fVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) - *GHIDRA_CAST((iVar5 + 0x340)); - fVar2 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) - *GHIDRA_CAST((iVar5 + 0x33c)); - local_10.x = sqrtf(fVar4 * fVar4 + fVar2 * fVar2); - if (((3.0 <= local_10.x) && (*GHIDRA_CAST((iVar5 + 400)) == '\0')) && - ((0.1 <= *GHIDRA_CAST((iVar5 + 0x364)) * *GHIDRA_CAST((iVar5 + 0x364)) + - *GHIDRA_CAST((iVar5 + 0x360)) * *GHIDRA_CAST((iVar5 + 0x360)) || - (rngValue = Random(), rngValue % 10 != 0)))) { - if (0.0 < local_10.x) { - iVar5 = *GHIDRA_CAST(this); - fVar3 = *GHIDRA_CAST((iVar5 + 0x36c)); - if (fVar3 != 0.0) { - *GHIDRA_CAST((iVar5 + 0x360)) = - ((fVar2 / local_10.x) * 0.5 * *GHIDRA_CAST((iVar5 + 0x39c))) / fVar3 + - *GHIDRA_CAST((iVar5 + 0x360)); - *GHIDRA_CAST((iVar5 + 0x364)) = - ((fVar4 / local_10.x) * 0.5 * *GHIDRA_CAST((iVar5 + 0x39c))) / fVar3 + - *GHIDRA_CAST((iVar5 + 0x364)); - } - } - return 0; - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = g_vectorZero.x; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x8)))) = g_vectorZero.y; - return 1; -} - -// 007e6650 -void PathFinder::MoveRandomlyBoss(uint8_t isIgnoreStatusEffects) -{ - uint8_t bVar1; - Entity_NPC *npc; - Vector *pVVar2; - Entity *playerTarget; - uint32_t uVar3; - int gridY; - float fVar4; - float fVar5; - float fVar6; - int iVar7; - int triesLeft; - Vector local_18; - Vector local_10; - Room *room; - - iVar7 = *GHIDRA_CAST(this); - if (*GHIDRA_CAST((iVar7 + 0x3d4)) == 0) { - if (isIgnoreStatusEffects == 0) { - bVar1 = is_entity_friendly(this); - if (bVar1 != 0) { - npc = (Entity_NPC *) - __RTDynamicCast(iVar7,0,&IsaacRepentancePlus::Entity::RTTI_Type_Descriptor, - &IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0); - bVar1 = 1; - iVar7 = 0; - fVar6 = 0.5; - pVVar2 = Entity_NPC::CalcTargetPosition(npc,&local_10,0.0); - FindGridPath(this,pVVar2,fVar6,iVar7,bVar1); - return; - } - if ((*GHIDRA_CAST((iVar7 + 0x168)) & 0x1000800) != 0) { - npc = (Entity_NPC *) - __RTDynamicCast(iVar7,0,&IsaacRepentancePlus::Entity::RTTI_Type_Descriptor, - &IsaacRepentancePlus::Entity_NPC::RTTI_Type_Descriptor,0); - playerTarget = Entity_NPC::GetPlayerTarget(npc); - local_10.x = (playerTarget->_pos).x; - local_10.y = (playerTarget->_pos).y; - EvadeTarget(this,&local_10,0); - return; - } - } - fVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))); - if ((fVar6 == g_vectorZero.x) && (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) == g_vectorZero.y)) { - uVar3 = Random(); - fVar4 = (float)((double)GHIDRA_INT(uVar3) + __uint_to_double_fixup[-(GHIDRA_INT(uVar3) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - fVar4 = fVar4 + fVar4; - fVar6 = cos(fVar4); - fVar4 = sin(fVar4); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) = fVar6; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = fVar4; - iVar7 = *GHIDRA_CAST(this); - } - else { - fVar4 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))); - } - fVar5 = *GHIDRA_CAST((iVar7 + 0x36c)); - if (fVar5 != 0.0) { - *GHIDRA_CAST((iVar7 + 0x364)) = - (*GHIDRA_CAST((iVar7 + 0x39c)) * fVar4 * 0.5) / fVar5 + *GHIDRA_CAST((iVar7 + 0x364)); - *GHIDRA_CAST((iVar7 + 0x360)) = - (*GHIDRA_CAST((iVar7 + 0x39c)) * fVar6 * 0.5) / fVar5 + *GHIDRA_CAST((iVar7 + 0x360)); - iVar7 = *GHIDRA_CAST(this); - } - local_10.x = (GHIDRA_CAST((iVar7 + 0x33c)))->x; - local_10.y = *GHIDRA_CAST((iVar7 + 0x340)); - iVar7 = Room::GetGridCollisionAtPos(g_game->_room,*GHIDRA_CAST((iVar7 + 0x33c))); - if (iVar7 == 0) { - uVar3 = Random(); - if (uVar3 % 0x1e == 0) { - pVVar2 = MusicManager::RandomVector(&local_10); - fVar5 = pVVar2->x + *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) = fVar5; - fVar4 = pVVar2->y + *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = fVar4; - fVar6 = sqrtf(fVar4 * fVar4 + fVar5 * fVar5); - if (0.0 < fVar6) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) = (1.0 / fVar6) * fVar5; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = fVar4 * (1.0 / fVar6); - } - } - if (((*GHIDRA_CAST(this))->_collidesWithGrid != 0) && - (bVar1 = Entity::IsFrame(*GHIDRA_CAST(this),5,0), bVar1 != 0)) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) ^ 0x80000000; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) ^ 0x80000000; - } - triesLeft = 5; - while( true ) { - fVar6 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))); - local_10.x = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))); - room = g_game->_room; - iVar7 = GHIDRA_INT((((fVar6 * 10.0 + *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x33c))) - 40.0) / 40.0 + 0.5)); - gridY = GHIDRA_INT((((local_10.x * 10.0 + *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x340))) - 120.0) / 40.0 + 0.5)) - ; - if ((((iVar7 < 0) || (room->_gridWidth <= iVar7)) || (gridY < 0)) || - (room->_gridHeight <= gridY)) { - iVar7 = -1; - } - else { - iVar7 = room->_gridWidth * gridY + iVar7; - } - uVar3 = Room::GetGridCollision(room,iVar7); - if ((uVar3 == 0) || (triesLeft < 1)) break; - uVar3 = Random(); - local_18.x = (float)((double)GHIDRA_INT(uVar3) + __uint_to_double_fixup[-(GHIDRA_INT(uVar3) >> 0x1f)]) * - 2.3283064e-10 * 3.14; - local_18.x = local_18.x + local_18.x; - fVar4 = cos(local_18.x); - fVar4 = fVar4 - fVar6; - fVar6 = sin(local_18.x); - fVar6 = fVar6 - local_10.x; - fVar5 = sqrtf(fVar6 * fVar6 + fVar4 * fVar4); - if (0.0 < fVar5) { - fVar4 = fVar4 * (1.0 / fVar5); - fVar6 = fVar6 * (1.0 / fVar5); - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) = fVar4; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = fVar6; - iVar7 = *GHIDRA_CAST(this); - *GHIDRA_CAST((iVar7 + 0x360)) = g_vectorZero.x; - *GHIDRA_CAST((iVar7 + 0x364)) = g_vectorZero.y; - triesLeft = triesLeft + -1; - } - } - else { - uVar3 = Random(); - if (uVar3 % 0x1e == 0) { - local_10.x = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x33c)); - local_10.y = *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x340)); - Room::FindFreePickupSpawnPosition(g_game->_room,&local_18,&local_10,0.0,0,0,0); - fVar4 = local_18.y - *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x340)); - fVar5 = local_18.x - *GHIDRA_CAST((*GHIDRA_CAST(this) + 0x33c)); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = fVar4; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) = fVar5; - fVar6 = sqrtf(fVar4 * fVar4 + fVar5 * fVar5); - if (0.0 < fVar6) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0xc)))) = fVar5 * (1.0 / fVar6); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x10)))) = fVar4 * (1.0 / fVar6); - return; - } - } - } - } - return; -} - -// 007e6b90 -void PathFinder::update_chase_movement() -{ - Entity_NPC *pEVar1; - int iVar2; - uint8_t isFrame; - Vector *controllerInput; - uint32_t rngResult; - Entity *target; - PathFinder *in_ECX; - float fVar3; - float fVar4; - float fVar5; - Vector local_20; - float local_14; - uint64_t npcFlags; - - pEVar1 = *GHIDRA_CAST(in_ECX); - if ((pEVar1 == GHIDRA_CAST(0x0)) || - (((*GHIDRA_CAST(&g_game->_deathmatchManager) < 2 || (pEVar1->_type != 1)) && - (0x3dd < pEVar1->_type - 10U)))) { - local_20.y = 0.0; - } - else { - local_20.y = (float)pEVar1; - if (pEVar1->_controllerID != -1) { - pEVar1->_friction = pEVar1->_friction * 0.6; - controllerInput = Entity_NPC::GetControllerInput(pEVar1,&local_20,0.0); - fVar3 = pEVar1->_speedMultiplier; - fVar4 = controllerInput->y; - (pEVar1->_velocity).x = controllerInput->x * 1.2 * 1.25 * fVar3 + (pEVar1->_velocity).x; - (pEVar1->_velocity).y = fVar4 * 1.2 * 1.25 * fVar3 + (pEVar1->_velocity).y; - return; - } - } - fVar3 = local_20.y; - pEVar1->_friction = pEVar1->_friction * 0.6; - local_14 = (float)(GHIDRA_INT(pEVar1->_updateTime) - GHIDRA_INT(pEVar1->_prevUpdateTime)); - if ((pEVar1->_flags & 0x1000b00) != 0) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x28)))) = 10; - } - if (GHIDRA_CAST(local_20.y) != GHIDRA_CAST(0x0)) { - pEVar1 = *GHIDRA_CAST((GHIDRA_INT((GHIDRA_INT(local_20.y) + 0x168)) + 4)); - npcFlags = *GHIDRA_CAST((GHIDRA_CAST(local_20.y) + 0x168)); - local_20.y = (float)pEVar1; - if ((npcFlags & 0x200) == 0) { - if ((npcFlags & 0x100) == 0) { - if ((npcFlags & 0x1000800) == 0) goto LAB_007e6de9; - target = Entity_NPC::GetPlayerTarget(GHIDRA_CAST(fVar3)); - fVar4 = (GHIDRA_CAST((GHIDRA_INT(fVar3) + 0x33c)))->x - (target->_pos).x; - fVar3 = (GHIDRA_CAST((GHIDRA_INT(fVar3) + 0x33c)))->y - (target->_pos).y; - } - else { - local_20.y = (float)Entity_NPC::GetPlayerTarget(GHIDRA_CAST(fVar3)); - isFrame = Entity::IsFrame(GHIDRA_CAST(fVar3),5,*GHIDRA_CAST((GHIDRA_CAST(fVar3) + 0x20))); - if (isFrame == 0) goto LAB_007e6de9; - Reset(in_ECX); - local_20.x = (GHIDRA_CAST((GHIDRA_INT(local_20.y) + 0x33c)))->x; - local_20.y = (GHIDRA_CAST((GHIDRA_INT(local_20.y) + 0x33c)))->y; - FindGridPath(in_ECX,&local_20,1.0,900,1); - fVar4 = (GHIDRA_CAST((GHIDRA_INT(fVar3) + 0x360)))->x; - fVar3 = (GHIDRA_CAST((GHIDRA_INT(fVar3) + 0x360)))->y; - } - fVar3 = atan2f(fVar3,fVar4); - fVar3 = fVar3 * 57.295776; - } - else { - rngResult = Random(); - if (rngResult % 5 != 0) goto LAB_007e6de9; - rngResult = Random(); - fVar3 = normalize_angle_degrees - ((float)((double)GHIDRA_INT(rngResult) + - __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * 2.3283064e-10 * - 360.0); - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x4)))) = fVar3; - } -LAB_007e6de9: - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x28)))) = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x28)))) - GHIDRA_INT(local_14); - local_14 = *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x8)))) * 0.017453292; - local_20.y = cos(local_14); - local_14 = sin(local_14); - iVar2 = *GHIDRA_CAST(in_ECX); - *GHIDRA_CAST((iVar2 + 0x360)) = - local_20.y * 1.2 * *GHIDRA_CAST((iVar2 + 0x39c)) + *GHIDRA_CAST((iVar2 + 0x360)); - *GHIDRA_CAST((iVar2 + 0x364)) = local_14 * 1.2 * *GHIDRA_CAST((iVar2 + 0x39c)) + *GHIDRA_CAST((iVar2 + 0x364)) - ; - fVar3 = approach_angle(*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x8)))),*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x4)))),10.0); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x8)))) = fVar3; - if (*GHIDRA_CAST((*GHIDRA_CAST(in_ECX) + 400)) != '\0') { - rngResult = Random(); - if ((rngResult & 3) == 0) { - fVar3 = *GHIDRA_CAST((*GHIDRA_CAST(in_ECX) + 0x19c)); - fVar4 = *GHIDRA_CAST((*GHIDRA_CAST(in_ECX) + 0x1a0)); - fVar5 = local_14 * fVar4 + local_20.y * fVar3; - fVar3 = atan2f(local_14 - (fVar4 + fVar4) * fVar5,local_20.y - (fVar3 + fVar3) * fVar5); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x4)))) = fVar3 * 57.295776; - } - } - if (*GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x28)))) < 1) { - rngResult = Random(); - fVar3 = (float)((double)GHIDRA_INT(rngResult) + __uint_to_double_fixup[-(GHIDRA_INT(rngResult) >> 0x1f)]) * - 2.3283064e-10 * 360.0; - if (360.0 < ABS(fVar3)) { - fVar3 = fmodf(fVar3,360.0); - } - if (fVar3 <= 180.0) { - if (fVar3 < -180.0) { - fVar3 = fVar3 + 360.0; - } - } - else { - fVar3 = fVar3 - 360.0; - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x4)))) = fVar3; - rngResult = Random(); - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((in_ECX)) + 0x28)))) = rngResult % 0x78 + 0x2d; - } - return; -} - -// 007e6ff0 -void PathFinder::UpdateGridIndex() -{ - int gridY; - int gridX; - int gridWidth; - - gridX = GHIDRA_INT(((*GHIDRA_CAST((*GHIDRA_CAST(this) + 0x33c)) - 40.0) / 40.0 + 0.5)); - if ((((gridX < 0) || (gridWidth = *GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0xc)), gridWidth <= gridX)) || - (gridY = GHIDRA_INT(((*GHIDRA_CAST((*GHIDRA_CAST(this) + 0x340)) - 120.0) / 40.0 + 0.5)), gridY < 0)) || - (*GHIDRA_CAST((GHIDRA_CAST(g_game->_room) + 0x10)) <= gridY)) { - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x20)))) = 0xffffffff; - return; - } - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x20)))) = gridWidth * gridY + gridX; - return; -} diff --git a/generated-src/projectile_params.cpp b/generated-src/projectile_params.cpp deleted file mode 100644 index 258a6f8..0000000 --- a/generated-src/projectile_params.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "classes.h" - -// 0043ef30 -ProjectileParams::ProjectileParams() -{ - uint32_t rngValue; - - *GHIDRA_CAST(this) = 1; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST((this)) + 0x4)))) = 0; - this->FallingSpeedModifier = 0.0; - this->FallingAccelModifier = 0.0; - this->VelocityMulti = 1.0; - this->Scale = 1.0; - rngValue = Random(); - this->HomingStrength = 1.0; - this->CurvingStrength = 0.005; - this->Acceleration = 1.01; - this->Spread = 1.0; - this->CircleAngle = - (float)((double)GHIDRA_INT(rngValue) + __uint_to_double_fixup[-(GHIDRA_INT(rngValue) >> 0x1f)]) * - 2.3283064e-10 * 3.1415927; - (this->Color)._tint[0] = 1.0; - (this->Color)._tint[1] = 1.0; - (this->Color)._tint[2] = 1.0; - (this->Color)._tint[3] = 1.0; - (this->Color)._colorize[0] = 0.0; - (this->Color)._colorize[1] = 0.0; - (this->Color)._colorize[2] = 0.0; - (this->Color)._colorize[3] = 0.0; - (this->Color)._offset[0] = 0.0; - (this->Color)._offset[1] = 0.0; - (this->Color)._offset[2] = 0.0; - *GHIDRA_CAST(&this->BulletFlags) = 0; - *GHIDRA_CAST((GHIDRA_INT(&this->BulletFlags) + 4)) = 0; - (this->PositionOffset).x = g_vectorZero.x; - (this->PositionOffset).y = g_vectorZero.y; - (this->TargetPosition).x = g_vectorZero.x; - (this->TargetPosition).y = g_vectorZero.y; - (this->FireDirectionLimit).x = g_vectorZero.x; - (this->FireDirectionLimit).y = g_vectorZero.y; - this->DotProductLimit = -1000.0; - this->WiggleFrameOffset = 0; - *GHIDRA_CAST(&this->ChangeFlags) = 0; - *GHIDRA_CAST((GHIDRA_INT(&this->ChangeFlags) + 4)) = 0; - this->ChangeVelocity = 0.0; - this->ChangeTimeout = 0x1e; - this->DepthOffset = 0.0; - this->Variant = 0; - *GHIDRA_CAST((this + 1)) = 0; - *GHIDRA_CAST(&(*GHIDRA_CAST((GHIDRA_CAST(&(this[1])) + 0x4)))) = &DAT_bf800000; - this[1].FallingSpeedModifier = 0.0; - *GHIDRA_CAST(&this[1].FallingAccelModifier) = 0; - return this; -} diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index 2aa789a..33ccc5e 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8388,9 +8388,6 @@ uint8_t Vector::operator_eq(Vector *other) { generated_stub("Vector::operator_eq uint8_t Vector::operator_ne(Vector *other) { generated_stub("Vector::operator_ne 00a10630"); } Vector * Vector::__unm(Vector *outResult) { generated_stub("Vector::__unm 00a10660"); } EntityList_Query::~EntityList_Query() { generated_stub("EntityList_Query::~EntityList_Query 004175b0"); } -void EntitySaveState::constructor() { generated_stub("EntitySaveState::constructor 004d3080"); } -void EntitySaveState::copy(void *other) { generated_stub("EntitySaveState::copy 004d3130"); } -void EntitySaveState::set_extra_data(uint32_t param_1) { generated_stub("EntitySaveState::set_extra_data 00827f70"); } void EntitySaveStateRef::Set(void *state) { generated_stub("EntitySaveStateRef::Set 006eee10"); } void * FileSystem::GetMountPrefixes(void *outPrefixes) { generated_stub("FileSystem::GetMountPrefixes 00a16060"); } void FileSystem::load_mount_points() { generated_stub("FileSystem::load_mount_points 00a167d0"); } @@ -8404,16 +8401,6 @@ FriendEntry::~FriendEntry() { generated_stub("FriendEntry::~FriendEntry 008e1f30 void GameOver::RenderItemSprite(int memberIndex) { generated_stub("GameOver::RenderItemSprite 008ebfb0"); } void GameOver::Render() { generated_stub("GameOver::Render 00998880"); } void GameOver::Show() { generated_stub("GameOver::Show 009997c0"); } -GameStatePlayer::~GameStatePlayer() { generated_stub("GameStatePlayer::~GameStatePlayer 00754d90"); } -void GameStatePlayer::read_player_key(void *stream) { generated_stub("GameStatePlayer::read_player_key 009c86e0"); } -void GameStatePlayer::Init() { generated_stub("GameStatePlayer::Init 009cf050"); } -uint8_t GameStatePlayer::read_coplayer(short *block, void *stream) { generated_stub("GameStatePlayer::read_coplayer 009cff40"); } -void GameStatePlayer::write_coplayer(void *stream) { generated_stub("GameStatePlayer::write_coplayer 009d0100"); } -void GameStatePlayer::read_block_538(uint32_t *block, void *stream) { generated_stub("GameStatePlayer::read_block_538 009d02c0"); } -void GameStatePlayer::write_block_538(short *block, void *stream) { generated_stub("GameStatePlayer::write_block_538 009d0440"); } -uint8_t GameStatePlayer::read(void *reader) { generated_stub("GameStatePlayer::read 009d05d0"); } -uint32_t GameStatePlayer::read_part3() { generated_stub("GameStatePlayer::read_part3 009d2656"); } -void * Game_StateSlot::operator_assign(void *other) { generated_stub("Game_StateSlot::operator_assign 006f8a40"); } void * GlitchedCollectibleGfx::constructor() { generated_stub("GlitchedCollectibleGfx::constructor 009dc6e0"); } void GlitchedItemSet::recalculate() { generated_stub("GlitchedItemSet::recalculate 009e0500"); } void HallucinationOverlay::Render(Vector *offset) { generated_stub("HallucinationOverlay::Render 00839550"); } @@ -9247,9 +9234,6 @@ void * Multiplayer::get_lobby(void *outLobby) { generated_stub("Multiplayer::get void Multiplayer::handle_member_status(void *lobby, uint64_t *userId, int status) { generated_stub("Multiplayer::handle_member_status 00a2a0b0"); } void Mutex::lock() { generated_stub("Mutex::lock 00aaaf50"); } Mutex::ScopeLock::~ScopeLock() { generated_stub("Mutex::ScopeLock::~ScopeLock 00aaae20"); } -void NPCAI_Pathfinder::ResetMovementTarget() { generated_stub("NPCAI_Pathfinder::ResetMovementTarget 007e6fa0"); } -uint8_t NPCAI_Pathfinder::HasPathToPos(Vector *position, uint8_t isIgnorePoop) { generated_stub("NPCAI_Pathfinder::HasPathToPos 007e7070"); } -void NPCAI_Pathfinder::SimulatePlayerMovement(float *param_2) { generated_stub("NPCAI_Pathfinder::SimulatePlayerMovement 007e8010"); } void NetDesyncHandler::Update() { generated_stub("NetDesyncHandler::Update 008fd900"); } void NetDesyncHandler::receive_messages() { generated_stub("NetDesyncHandler::receive_messages 008fed60"); } void NetDesyncHandler::write_desync_diff() { generated_stub("NetDesyncHandler::write_desync_diff 008ffc70"); } @@ -9393,19 +9377,6 @@ void OnlineChat::broadcast_message(std_string *text) { generated_stub("OnlineCha uint8_t OnlineChat::is_key_repeating(int keyCode) { generated_stub("OnlineChat::is_key_repeating 0091ee00"); } void OnlineChat::apply_roll_command(std_string *message) { generated_stub("OnlineChat::apply_roll_command 0091f5d0"); } void OnlineChatMessage::constructor() { generated_stub("OnlineChatMessage::constructor 0091cec0"); } -int PathFinder::GetGridIndex() { generated_stub("PathFinder::GetGridIndex 00456370"); } -uint32_t PathFinder::GetEvadeMovementCountdown() { generated_stub("PathFinder::GetEvadeMovementCountdown 00456740"); } -void PathFinder::SetCanCrushRocks(uint8_t param_1) { generated_stub("PathFinder::SetCanCrushRocks 00499dc0"); } -uint8_t PathFinder::HasDirectPath() { generated_stub("PathFinder::HasDirectPath 004be6e0"); } -void PathFinder::Init(Entity *owner) { generated_stub("PathFinder::Init 007e31a0"); } -void PathFinder::Reset() { generated_stub("PathFinder::Reset 007e3260"); } -uint8_t PathFinder::is_entity_friendly() { generated_stub("PathFinder::is_entity_friendly 007e3340"); } -void PathFinder::EvadeTarget(Vector *targetPos, uint8_t isIgnoreStatusEffects) { generated_stub("PathFinder::EvadeTarget 007e4940"); } -void PathFinder::MoveRandomlyAxisAligned(float speed, uint8_t isIgnoreStatusEffects) { generated_stub("PathFinder::MoveRandomlyAxisAligned 007e5340"); } -uint8_t PathFinder::MoveRandomly(uint8_t isIgnoreStatusEffects) { generated_stub("PathFinder::MoveRandomly 007e6300"); } -void PathFinder::MoveRandomlyBoss(uint8_t isIgnoreStatusEffects) { generated_stub("PathFinder::MoveRandomlyBoss 007e6650"); } -void PathFinder::update_chase_movement() { generated_stub("PathFinder::update_chase_movement 007e6b90"); } -void PathFinder::UpdateGridIndex() { generated_stub("PathFinder::UpdateGridIndex 007e6ff0"); } PathNode::PathNode(void *other) { generated_stub("PathNode::PathNode 007e48b0"); } void PersistentGameDataReader::read(PersistentGameData *data) { generated_stub("PersistentGameDataReader::read 0091adf0"); } void * PersistentGameDataWriter::compress(uint32_t *outSize) { generated_stub("PersistentGameDataWriter::compress 0091acc0"); } @@ -9417,7 +9388,6 @@ void Point::UpdateNormal(Vector *unk) { generated_stub("Point::UpdateNormal 0041 uint8_t ProceduralEffect::roll_trigger_target(uint32_t *outTarget, float *outChance, RNG *rng) { generated_stub("ProceduralEffect::roll_trigger_target 009e0700"); } uint8_t ProceduralEffect::roll_spawn_target(uint32_t *outTarget, float *outChance, RNG *rng) { generated_stub("ProceduralEffect::roll_spawn_target 009e0ad0"); } void ProceduralEffect::roll_params(int conditionType, int actionType, uint32_t seed) { generated_stub("ProceduralEffect::roll_params 009e0f60"); } -ProjectileParams::ProjectileParams() { generated_stub("ProjectileParams::ProjectileParams 0043ef30"); } void Quad::rotate(Vector *pivot, float angle) { generated_stub("Quad::rotate 00a10760"); } void Quad::scale(Vector *pivot, Vector *scale) { generated_stub("Quad::scale 00a10950"); } void RebirthSaveData::Clear() { generated_stub("RebirthSaveData::Clear 009e3dc0"); } @@ -10498,8 +10468,6 @@ int FUN_00505ca0() { generated_stub("FUN_00505ca0 00505ca0"); } uint32_t * FUN_00505ce0() { generated_stub("FUN_00505ce0 00505ce0"); } void NpcAI::ENTITY_STONE_EYE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_STONE_EYE 00505d00"); } void NpcAI::ENTITY_CONSTANT_STONE_SHOOTER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_CONSTANT_STONE_SHOOTER 00506320"); } -void NpcAI::ENTITY_FLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FLY 00506bd0"); } -void NpcAI::ENTITY_GAPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GAPER 00508f40"); } void NpcAI::ENTITY_EMBRYO(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_EMBRYO 0050a6b0"); } void NpcAI::ENTITY_ETERNALFLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ETERNALFLY 0050a8a0"); } void NpcAI::ENTITY_GUSHER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_GUSHER 0050af90"); } @@ -10511,7 +10479,6 @@ uint32_t NpcAI::ENTITY_BOOMFLY(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_ void NpcAI::ENTITY_MAW(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MAW 00510ae0"); } Entity * NpcAI::ENTITY_HOST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HOST 005111b0"); } void NpcAI::ENTITY_BRAIN(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_BRAIN 00512110"); } -void NpcAI::ENTITY_HORF(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_HORF 00513080"); } void NpcAI::ENTITY_KNIGHT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_KNIGHT 005135d0"); } uint32_t FUN_00515010() { generated_stub("FUN_00515010 00515010"); } Vector * room_grid_line_direction(Vector *outDirection, Vector *from, Vector *to) { generated_stub("room_grid_line_direction 005150b0"); } @@ -10546,7 +10513,6 @@ void NpcAI::ENTITY_BABY_LONG_LEGS(Entity_NPC *npc) { generated_stub("NpcAI::ENTI void NpcAI::ENTITY_MOBILE_HOST(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOBILE_HOST 005321d0"); } void NpcAI::ENTITY_DEATHS_HEAD(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DEATHS_HEAD 00532cf0"); } void NpcAI::ENTITY_MOMS_HAND(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOMS_HAND 00533b80"); } -void NpcAI::ENTITY_DIP(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_DIP 00534860"); } Entity * NpcAI::ENTITY_SQUIRT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SQUIRT 00535280"); } void NpcAI::ENTITY_SWINGER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SWINGER 00536d00"); } void NpcAI::ENTITY_WIZOOB(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_WIZOOB 005374a0"); } @@ -11182,8 +11148,6 @@ void FUN_006a80d0() { generated_stub("FUN_006a80d0 006a80d0"); } void FUN_006a8180(uint32_t param_1) { generated_stub("FUN_006a8180 006a8180"); } void FUN_006a8210(int param_1) { generated_stub("FUN_006a8210 006a8210"); } uint32_t FUN_006ae7a0() { generated_stub("FUN_006ae7a0 006ae7a0"); } -uint32_t FUN_006b2390() { generated_stub("FUN_006b2390 006b2390"); } -uint8_t entity_collision_classes_match(Entity *a, Entity *b) { generated_stub("entity_collision_classes_match 006b2410"); } void spawn_gibs(Vector *position, int amount, float spread, uint32_t *gibFlags, Entity *spawner, ColorMod *color, Vector *velocity, float scale) { generated_stub("spawn_gibs 006b31b0"); } void FUN_006b5de0() { generated_stub("FUN_006b5de0 006b5de0"); } void FUN_006b5f40() { generated_stub("FUN_006b5f40 006b5f40"); } @@ -11203,11 +11167,8 @@ void FUN_006b8580() { generated_stub("FUN_006b8580 006b8580"); } Entity * spawn_gfuel_explosion() { generated_stub("spawn_gfuel_explosion 006b9450"); } uint32_t _NpcHelper::spider_load_graphics(uint8_t *param_1) { generated_stub("_NpcHelper::spider_load_graphics 006baa70"); } void NpcAI::ENTITY_SHOPKEEPER(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_SHOPKEEPER 006c2220"); } -void Entity_NPC_UpdateAI_dispatch(Entity_NPC *npc) { generated_stub("Entity_NPC_UpdateAI_dispatch 006c2990"); } int FUN_006c4a90() { generated_stub("FUN_006c4a90 006c4a90"); } -void FUN_006d0370(uint32_t *param_1) { generated_stub("FUN_006d0370 006d0370"); } void NpcAI::ENTITY_FIREPLACE(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_FIREPLACE 006d18d0"); } -void FUN_006d5350() { generated_stub("FUN_006d5350 006d5350"); } void FUN_006d6650() { generated_stub("FUN_006d6650 006d6650"); } void NpcAI::ENTITY_MOVABLE_TNT(Entity_NPC *npc) { generated_stub("NpcAI::ENTITY_MOVABLE_TNT 006d6690"); } uint8_t is_local_player_owned(void *self) { generated_stub("is_local_player_owned 006d8e10"); } @@ -11223,7 +11184,6 @@ void FUN_006daab0() { generated_stub("FUN_006daab0 006daab0"); } void FUN_006dac00(uint32_t *param_1, uint32_t param_2) { generated_stub("FUN_006dac00 006dac00"); } float log_precise(float value) { generated_stub("log_precise 006dac30"); } void FUN_006daca0(uint32_t param_1) { generated_stub("FUN_006daca0 006daca0"); } -uint8_t Pickup_PickVariant(uint32_t seed, uint32_t *variant, uint32_t *subType, uint8_t isAdvancePools, uint8_t isShopItem) { generated_stub("Pickup_PickVariant 006ddcd0"); } uint32_t FUN_006e1910(uint32_t param_1) { generated_stub("FUN_006e1910 006e1910"); } void FUN_006e2ff0(int param_1) { generated_stub("FUN_006e2ff0 006e2ff0"); } void FUN_006ee330() { generated_stub("FUN_006ee330 006ee330"); } @@ -11477,7 +11437,6 @@ uint32_t FUN_007ab0e0() { generated_stub("FUN_007ab0e0 007ab0e0"); } void FUN_007ad610() { generated_stub("FUN_007ad610 007ad610"); } uint32_t FUN_007ad720(uint32_t param_1, uint8_t *param_2) { generated_stub("FUN_007ad720 007ad720"); } void FUN_007ae430(short *param_1) { generated_stub("FUN_007ae430 007ae430"); } -void FUN_007b0b40(uint16_t *param_1) { generated_stub("FUN_007b0b40 007b0b40"); } void FUN_007b8c00(int param_1) { generated_stub("FUN_007b8c00 007b8c00"); } void FUN_007b9a60() { generated_stub("FUN_007b9a60 007b9a60"); } void FUN_007b9aa0() { generated_stub("FUN_007b9aa0 007b9aa0"); } @@ -11611,7 +11570,6 @@ void FUN_007ea0c0() { generated_stub("FUN_007ea0c0 007ea0c0"); } void FUN_007ea5d0() { generated_stub("FUN_007ea5d0 007ea5d0"); } void FUN_007ebc40() { generated_stub("FUN_007ebc40 007ebc40"); } uint32_t FUN_007ed240() { generated_stub("FUN_007ed240 007ed240"); } -uint8_t entity_type_is_saved(int type, int variant, uint32_t subType, int spawnerType, uint8_t isRoomFlag) { generated_stub("entity_type_is_saved 007eed10"); } float get_angel_room_chance() { generated_stub("get_angel_room_chance 007f96f0"); } void FUN_007fa2a0(float *param_1) { generated_stub("FUN_007fa2a0 007fa2a0"); } void FUN_007fa7d0() { generated_stub("FUN_007fa7d0 007fa7d0"); } @@ -11885,9 +11843,7 @@ void FUN_00864fc0(uint32_t param_1) { generated_stub("FUN_00864fc0 00864fc0"); } uint32_t Catch_0086504e() { generated_stub("Catch_0086504e 0086504e"); } void FUN_008650a0(uint32_t param_1) { generated_stub("FUN_008650a0 008650a0"); } uint32_t Catch_0086512e() { generated_stub("Catch_0086512e 0086512e"); } -void FUN_00865180() { generated_stub("FUN_00865180 00865180"); } uint32_t Catch_00865209() { generated_stub("Catch_00865209 00865209"); } -void FUN_00865260() { generated_stub("FUN_00865260 00865260"); } uint32_t Catch_008652e9() { generated_stub("Catch_008652e9 008652e9"); } int lua_callback_run_get_card(RNG *rng, int card, uint8_t isPlaying, uint8_t isRunes, uint8_t isOnlyRunes) { generated_stub("lua_callback_run_get_card 00865340"); } uint8_t * Catch_00865424() { generated_stub("Catch_00865424 00865424"); } @@ -14090,14 +14046,6 @@ int * FUN_00930a00(int param_1) { generated_stub("FUN_00930a00 00930a00"); } uint32_t FUN_00930b20() { generated_stub("FUN_00930b20 00930b20"); } void FUN_00930ec0() { generated_stub("FUN_00930ec0 00930ec0"); } void FUN_00930ee0(char param_1) { generated_stub("FUN_00930ee0 00930ee0"); } -void FUN_00931f50(uint32_t *param_1, int param_2) { generated_stub("FUN_00931f50 00931f50"); } -void FUN_00931fc0(uint32_t *param_1, uint32_t *param_2) { generated_stub("FUN_00931fc0 00931fc0"); } -void FUN_00932020(uint32_t *param_1, int param_2) { generated_stub("FUN_00932020 00932020"); } -void grid_rect_to_quad(float *outQuad, int x, int y, int width, int height) { generated_stub("grid_rect_to_quad 00932090"); } -Vector * backdrop_detail_to_world_pos(Vector *outPosition, Vector *position) { generated_stub("backdrop_detail_to_world_pos 0093b480"); } -uint32_t FUN_0093b530() { generated_stub("FUN_0093b530 0093b530"); } -void backdrop_wall_normal(Vector *outNormal, int isVertical, uint8_t isNegX, uint8_t isNegY) { generated_stub("backdrop_wall_normal 0093b580"); } -void FUN_009426b0(uint32_t param_1, uint32_t param_2) { generated_stub("FUN_009426b0 009426b0"); } void FUN_00949b70() { generated_stub("FUN_00949b70 00949b70"); } void FUN_00949bc0(uint32_t param_1) { generated_stub("FUN_00949bc0 00949bc0"); } void FUN_0094e3b0() { generated_stub("FUN_0094e3b0 0094e3b0"); } @@ -14117,7 +14065,6 @@ void save_rerun_to_steam_cloud() { generated_stub("save_rerun_to_steam_cloud 009 void FUN_00959500() { generated_stub("FUN_00959500 00959500"); } void persistent_game_data_set_writable() { generated_stub("persistent_game_data_set_writable 0095a680"); } void unlock_completion_mark_for_player_type(int markIndex, int playerType, int difficulty) { generated_stub("unlock_completion_mark_for_player_type 0095aa30"); } -int controller_button_to_glyph_frame(int button) { generated_stub("controller_button_to_glyph_frame 0095aba0"); } void render_online_icon(int frame, Vector position, float scaleX, float scaleY) { generated_stub("render_online_icon 0095ae60"); } void FUN_0095be60(int param_1, int param_2) { generated_stub("FUN_0095be60 0095be60"); } void FUN_0095be90(void *param_1, int param_2) { generated_stub("FUN_0095be90 0095be90"); } @@ -14189,7 +14136,6 @@ void FUN_009b9fc0(int param_1) { generated_stub("FUN_009b9fc0 009b9fc0"); } void FUN_009ba9a0() { generated_stub("FUN_009ba9a0 009ba9a0"); } void FUN_009baa10(char param_1) { generated_stub("FUN_009baa10 009baa10"); } int FUN_009bac00(int param_1) { generated_stub("FUN_009bac00 009bac00"); } -uint32_t FUN_009be9c0() { generated_stub("FUN_009be9c0 009be9c0"); } void entity_vector_set_flag_410(void *self, uint8_t value) { generated_stub("entity_vector_set_flag_410 009bea10"); } void FUN_009bfc00() { generated_stub("FUN_009bfc00 009bfc00"); } void FUN_009bfc20() { generated_stub("FUN_009bfc20 009bfc20"); } diff --git a/src/backdrop.cpp b/src/backdrop.cpp index 9e1e8a9..b23dadb 100644 --- a/src/backdrop.cpp +++ b/src/backdrop.cpp @@ -1,11 +1,24 @@ #include "backdrop.h" #include "data.h" +#include "entity.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "fx_layers.h" #include "game.h" +#include "grid_entity.h" +#include "kage_input.h" +#include "key_configs.h" #include "log.h" #include "manager.h" +#include "menu_manager.h" #include "platform.h" +#include "render_passes.h" #include "room.h" #include "room_config.h" +#include "seeds.h" +#include +#include #include constexpr std::string_view DEFAULT_PROPS = "gfx/grid/props_01_basement.anm2"; @@ -23,25 +36,259 @@ constexpr int SURFACE_HEIGHT = 468; constexpr const char* SURFACE_NAMES[] = {"Floor Surface", "Wall Surface", "Floor Surface 2", "Temp Backdrop Surface"}; constexpr uint32_t BACKDROP_SEED_DEFAULT = 0x11111111; -// The xorshift triples (5, 9, 7) and (4, 3, 27). +// The xorshift triples (5, 9, 7), (4, 3, 27) and (5, 15, 17). constexpr uint32_t RNG_SHIFT_DEFAULT = 35; constexpr uint32_t RNG_SHIFT_LEVEL_FLOOR = 31; +constexpr uint32_t RNG_SHIFT_CONTROLS = 39; -// A room's grid cells, and the walls a cell thick that frame its floor. +// A room's grid cells on the surfaces, and the walls two cells thick that frame its floor. constexpr float GRID_SIZE = 26; constexpr int WALL_CELLS = 2; -constexpr float ROOM_OFFSET = WALL_CELLS * GRID_SIZE; +constexpr float WALL_SIZE = WALL_CELLS * GRID_SIZE; -// The backdrops whose floor variant depends on the room: Dross and Mausoleum's large rooms leave out the last floor, -// Ashpit keeps one floor per level and shows the second in flagged rooms. Gehenna keeps one floor per level. +// The backdrops (Lua's BackdropType) drawn or decorated their own way. +constexpr uint32_t BACKDROP_BASEMENT = 1; +constexpr uint32_t BACKDROP_BURNING_BASEMENT = 3; +constexpr uint32_t BACKDROP_DANK_DEPTHS = 9; +constexpr uint32_t BACKDROP_CATHEDRAL = 15; +constexpr uint32_t BACKDROP_DARK_ROOM = 16; +constexpr uint32_t BACKDROP_MEGA_SATAN = 18; +constexpr uint32_t BACKDROP_SHOP = 20; +constexpr uint32_t BACKDROP_ERROR_ROOM = 26; +constexpr uint32_t BACKDROP_GREED_SHOP = 28; +constexpr uint32_t BACKDROP_SACRIFICE = 30; +constexpr uint32_t BACKDROP_DOWNPOUR = 31; +constexpr uint32_t BACKDROP_MINES = 32; constexpr uint32_t BACKDROP_MAUSOLEUM = 33; +constexpr uint32_t BACKDROP_PLANETARIUM = 35; +constexpr uint32_t BACKDROP_CORPSE_ENTRANCE = 39; constexpr uint32_t BACKDROP_MAUSOLEUM2 = 40; +constexpr uint32_t BACKDROP_MAUSOLEUM3 = 41; +constexpr uint32_t BACKDROP_MAUSOLEUM4 = 42; constexpr uint32_t BACKDROP_DROSS = 45; constexpr uint32_t BACKDROP_ASHPIT = 46; constexpr uint32_t BACKDROP_GEHENNA = 47; +constexpr uint32_t BACKDROP_CLOSET = 52; +constexpr uint32_t BACKDROP_CLOSET_B = 53; +constexpr uint32_t BACKDROP_DOGMA = 54; +constexpr uint32_t BACKDROP_MINES_SHAFT = 58; constexpr uint32_t BACKDROP_ASHPIT_SHAFT = 59; -constexpr int32_t ROOM_FLAG_ALT_FLOOR = 0x1000; + constexpr uint32_t FLOOR_SECOND = 1; +constexpr uint32_t HOME_CLOSET_FIRST_SUBTYPE = 10; +constexpr int BOSS_MOM_MAUSOLEUM = 89; + +// Where Mega Satan's floor sprite draws past the room's corner, and the half cell its surface reaches past the walls. +constexpr float MEGA_SATAN_FLOOR_X = 0; +constexpr float MEGA_SATAN_FLOOR_Y = 130; +constexpr float MEGA_SATAN_BORDER = GRID_SIZE / 2; +constexpr std::string_view MEGA_SATAN_CLOSED_ANIMATION = "Idle2"; +constexpr std::string_view MEGA_SATAN_OPEN_ANIMATION = "Idle1"; + +// The sheets cut into blocks of 9 by 6 cells, two to a row: a corner, the walls, and a quarter of a floor, each block +// one variant. +constexpr int BLOCK_WIDTH = 9; +constexpr int BLOCK_HEIGHT = 6; +constexpr int BLOCK_FLOOR = 2; +constexpr int TILE_WIDTH = 7; +constexpr int TILE_HEIGHT = 4; +constexpr int TILE_STEP_X = 6; +constexpr int TILE_STEP_Y = 3; +constexpr size_t FLOOR_TILES_MIN = 32; + +// The Dark Room's and Mega Satan's fixed tiles, in texels: four floor tiles, then two for the bottom row. +constexpr int DARK_FLOOR_TILES = 4; +constexpr int DARK_EDGE_TILES = 2; +constexpr float DARK_TILES[DARK_FLOOR_TILES + DARK_EDGE_TILES][4] = {{52, 52, 234, 156}, {286, 52, 468, 156}, + {52, 208, 234, 312}, {286, 208, 468, 312}, + {52, 312, 234, 468}, {286, 312, 468, 468}}; + +// The Cathedral's big rooms: their floor in tiles of 2 by 2 cells, one of four at random, and the cell set in each +// corner of the floor. +constexpr int CATHEDRAL_TILES[4][2] = {{11, 14}, {13, 14}, {13, 16}, {11, 16}}; +constexpr int CATHEDRAL_CORNER[2] = {15, 14}; +constexpr float CATHEDRAL_TILE = 2 * GRID_SIZE; +constexpr float EDGE_EPSILON = 0.001f; + +// A 1x1 room's floor in cells, which an L room has three of and a narrow room one row or column of. +constexpr int ROOM_FLOOR_COLUMNS = 13; +constexpr int ROOM_FLOOR_ROWS = 7; + +// The L floor sheets: three quarters of the room in pieces the size of a 1x1 room's floor, two variants one under the +// other, and where each piece goes (in cells from the floor's corner) with its mirroring, by the missing quarter. +struct LFloorLayout +{ + int cells[3][2]; + Flip flip; +}; +constexpr LFloorLayout L_FLOOR_LAYOUTS[4] = {{{{0, 7}, {13, 7}, {13, 0}}, FLIP_Y}, + {{{13, 7}, {0, 7}, {0, 0}}, FLIP_XY}, + {{{0, 0}, {13, 0}, {13, 7}}, FLIP_NONE}, + {{{13, 0}, {0, 0}, {0, 7}}, FLIP_X}}; + +// The narrow floor sheets: a horizontal room's floor in rows of 3 cells under 7 rows of a vertical room's in columns +// of 5. +constexpr int NARROW_ROW_HEIGHT = 3; +constexpr int NARROW_ROW_SHEET_Y = 7; +constexpr int NARROW_COLUMN_WIDTH = 5; + +// The start room's controls picture: how far under the top wall it sits, and the Burning Basement's darker tint. +constexpr float CONTROLS_Y = 91; +constexpr std::array CONTROLS_BURNT_TINT = {0.7f, 0.6f, 0.6f, 1}; +constexpr std::array CONTROLS_TINT = {1, 1, 1, 1}; +constexpr std::string_view CONTROLS_ANIMATION = "Controls"; +constexpr std::string_view KEYBOARD_ANIMATION = "Keyboard"; +constexpr std::string_view GAMEPAD_ANIMATION = "XboxOne"; +constexpr int KEYBOARD_CONTROLLER = 0; +constexpr int ACTION_NONE = -1; +constexpr int KEY_SPACE = 32; +constexpr float SPACE_KEY_PADDING = 4; +constexpr float ICON_PADDING = 4; +constexpr float ICON_WIDTH = 8; +constexpr int GLYPH_JITTER = 3; +constexpr int JACOB_ESAU_SPLIT_CONTROLS = 1; +constexpr int ASCENT_START_ROOM = 84; +constexpr uint32_t ASCENT_STAGE_LAST = 6; +constexpr uint32_t STAGE_FIRST = 1; +constexpr uint32_t STAGE_CATHEDRAL = 10; + +// The control icons the start room shows, a row to each of the controls picture's nulls: moving, shooting, then the +// bomb, item, card, drop and card buttons, and shooting again. +constexpr int CONTROL_ROW_COUNT = 8; +constexpr int CONTROL_ROW_ICONS = 5; +constexpr int CONTROL_ROWS[CONTROL_ROW_COUNT][CONTROL_ROW_ICONS] = { + {ACTION_UP, ACTION_LEFT, ACTION_DOWN, ACTION_RIGHT, ACTION_NONE}, + {ACTION_SHOOT_UP, ACTION_SHOOT_LEFT, ACTION_SHOOT_DOWN, ACTION_SHOOT_RIGHT, ACTION_NONE}, + {ACTION_BOMB, ACTION_NONE}, + {ACTION_ITEM, ACTION_NONE}, + {ACTION_PILL_CARD, ACTION_NONE}, + {ACTION_DROP, ACTION_NONE}, + {ACTION_PILL_CARD, ACTION_NONE}, + {ACTION_SHOOT_UP, ACTION_SHOOT_LEFT, ACTION_SHOOT_DOWN, ACTION_SHOOT_RIGHT, ACTION_NONE}}; + +// The walls: one cell in three shows a variant other than its row's first, fewer in the better shops. +constexpr int WALL_VARIANT_CHANCE = 3; +constexpr int SHOP_LEVEL_FIRST_CHANCE = 2; +constexpr int SHOP_WALL_CHANCES[4] = {4, 3, 2, 1}; +constexpr int CORNER_COUNT = 4; +constexpr int WALL_EDGE_COLUMNS = 7; +constexpr int WALL_EDGE_ROWS = 4; +constexpr int WALL_MIDDLE_COLUMN = 7; +constexpr int WALL_MIDDLE_ROW = 4; +constexpr int NARROW_COLUMN_INSET = 4; +constexpr int NARROW_ROW_INSET = 2; +constexpr int L_CORNER_SHEET_X = 18; + +// The blood splats a room may start with: on world cells 40 apart, kept 20 from the walls or 100 from the middle. +constexpr int EFFECT_BLOOD_SPLAT = 7; +constexpr int EFFECT_LIGHT = 121; +constexpr int EFFECT_BACKDROP_DECORATION = 140; +constexpr float WORLD_CELL = 40; +constexpr float WORLD_ORIGIN_X = 40; +constexpr float WORLD_ORIGIN_Y = 120; +constexpr float SPLAT_MARGIN = 20; +constexpr float SPLAT_RADIUS = 100; +constexpr float SPLAT_SQUASH = 0.6f; +constexpr float SPLAT_SCALE_MIN = 0.5f; +constexpr float SPLAT_SCALE_RANGE = 2.5f; +constexpr ColorMod CORPSE_SPLAT_COLOR = {{0.7f, 0.7f, 0.7f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; + +// The wall surface is the world at 0.65 scale, two world cells out from the room's corner. +constexpr float SURFACE_SCALE = 0.65f; +constexpr float SURFACE_ORIGIN = 80; +constexpr float NARROW_SHIFT_X = 160; +constexpr float NARROW_SHIFT_Y = 80; +constexpr float WALL_DETAIL_CHANCE = 0.18f; +constexpr float ASHPIT_DETAIL_CHANCE = 0.45f; +constexpr int ASHPIT_DARK_WALLS = 2; +constexpr float LIGHT_SCALE = 3; +constexpr int DETAIL_RENDER_Z = 1 << 30; +constexpr int COLOR_DURATION_FOREVER = -1; +constexpr float WALL_LIGHT_OUT = 20; +constexpr ColorMod EMBER_COLOR = {{1, 0.7f, 0.5f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float BURNING_EMBER_DRAW_BACK = -8; +constexpr float BURNING_EMBER_MIN = 0.5f; +constexpr float BURNING_EMBER_RANGE = 0.3f; +constexpr float ASHPIT_EMBER_DRAW_BACK = 16; +constexpr float ASHPIT_EMBER_MIN = 0.2f; +constexpr float ASHPIT_EMBER_RANGE = 0.1f; +constexpr int CATHEDRAL_WINDOW_SLOT = 5; +constexpr int CATHEDRAL_PLAIN_VARIANT = 2; +constexpr float CATHEDRAL_LIGHT_X = 10; +constexpr float CATHEDRAL_LIGHT_Y = 20; +constexpr float CATHEDRAL_LIGHT_ANGLE = -20; +constexpr float CATHEDRAL_LIGHT_SCALE_X = 0.15f; +constexpr float CATHEDRAL_LIGHT_SCALE_Y = 0.2f; +constexpr ColorMod CATHEDRAL_LIGHT_COLOR = {{1, 0.8f, 0.7f, 0.8f}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr std::string_view DANK_DETAILS = "gfx/backdrop/15_The Dank Depths_details.anm2"; +constexpr int DANK_PILLAR_SLOT = 3; +constexpr int DANK_DETAIL_VARIANT = 3; +constexpr ColorMod TAR_COLOR = {{0, 0, 0, 0.8f}, {0, 0, 0, 0}, {0x1.010102p-4f, 0x1.e1e1e4p-5f, 0x1.515152p-4f}}; +constexpr float TAR_OUT_MIN = 20; +constexpr float TAR_OUT_RANGE = 40; +constexpr float TAR_SHIFT_RANGE = 10; +constexpr float TAR_SCALE_RANGE = 4; +constexpr float HALF_TURN = 1.5707964f; +constexpr float SPLAT_SCALE_STEP = 2.3283064e-10f; +constexpr int DROSS_LIGHT_FIRST = 3; +constexpr int DROSS_LIGHT_ODDS = 40; +constexpr float DROSS_LIGHT_SCALE = 0.5f; +constexpr ColorMod DROSS_LIGHT_COLOR = {{0.9f, 0.9f, 1, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr float DROSS_PIPE_REACH = 40; +constexpr GridEntityType DROSS_PIPE_BLOCKERS[] = {GRID_ROCK, GRID_ROCKB, GRID_ROCKT, GRID_ROCK_BOMB, + GRID_ROCK_ALT, GRID_LOCK, GRID_TNT, GRID_POOP}; +constexpr float DROSS_LEAK_SIDE[2] = {6, 28}; +constexpr float DROSS_LEAK_TOP[2] = {10, 24}; +constexpr float DROSS_LEAK_RANGE = 0.4f; +constexpr ColorMod DROSS_LEAK_COLOR = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; +constexpr int DOOR_SIDE_SLOT = 2; +constexpr int MINES_LANTERN_ODDS = 4; +constexpr int MAUSOLEUM_TORCH_ODDS = 3; +constexpr int GEHENNA_CHAIN_ODDS = 3; +constexpr int COLOR_PRIORITY_TOP = 255; + +// RenderFloor: the Error room's floor sprite repeats every 100 pixels. +constexpr float ERROR_TILE = 100; + +// render_wall_borders: black over everything outside the room, and the corner an L room lacks. +constexpr KColor BORDER_COLOR = kcolor_rgba(0, 0, 0, 1); +constexpr float NARROW_BORDER_X = 104; +constexpr float NARROW_BORDER_Y = 52; +constexpr float L_BORDER_WIDTH = 364; +constexpr float L_BORDER_HEIGHT = 208; +constexpr KColor WHITE = kcolor_rgba(1, 1, 1, 1); + +constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; + +constexpr Flip operator|(Flip first, Flip second) +{ + return Flip((int)first | (int)second); +} + +static bool is_l_shape(int shape) +{ + return shape >= ROOMSHAPE_LTL && shape <= ROOMSHAPE_LBR; +} + +static bool is_narrow_shape(int shape) +{ + return shape == ROOMSHAPE_IH || shape == ROOMSHAPE_IV || shape == ROOMSHAPE_IIV || shape == ROOMSHAPE_IIH; +} + +static bool is_horizontal_narrow(int shape) +{ + return shape == ROOMSHAPE_IH || shape == ROOMSHAPE_IIH; +} + +static bool is_vertical_narrow(int shape) +{ + return shape == ROOMSHAPE_IV || shape == ROOMSHAPE_IIV; +} + +static bool is_ashpit(uint32_t id) +{ + return id == BACKDROP_ASHPIT || id == BACKDROP_ASHPIT_SHAFT; +} // 009321c0 An empty backdrop with its four surfaces made and its generator seeded. Backdrop::Backdrop() @@ -158,13 +405,15 @@ void Backdrop::Init(uint32_t id, bool isLoadGraphics) Room& room = *g_game->room; backdropId = (int)id < 0 || (int)id >= BACKDROP_COUNT ? 1 : id; - roomTopLeft = vector_make(ROOM_OFFSET, ROOM_OFFSET); - roomBottomRight = vector_make((float)((int)room.gridWidth - WALL_CELLS) * GRID_SIZE + ROOM_OFFSET, - (float)((int)room.gridHeight - WALL_CELLS) * GRID_SIZE + ROOM_OFFSET); + roomTopLeft = vector_make(WALL_SIZE, WALL_SIZE); + roomBottomRight = vector_make((float)((int)room.gridWidth - WALL_CELLS) * GRID_SIZE + WALL_SIZE, + (float)((int)room.gridHeight - WALL_CELLS) * GRID_SIZE + WALL_SIZE); if (isLoadGraphics) load_details(); } // 00935270 A floor variant for the room: one of the backdrop's floors at random, with exceptions by backdrop and room. +// Dross and Mausoleum's large rooms leave out the last floor, Ashpit keeps one floor per level and shows the second in +// rooms with the alternate backdrop, Gehenna keeps one floor per level. uint32_t Backdrop::get_random_floor_variant() { RoomDescriptor* descriptor = g_game->room->descriptor; @@ -175,65 +424,97 @@ uint32_t Backdrop::get_random_floor_variant() switch (backdropId) { case BACKDROP_DROSS: - if (descriptor->flags & ROOM_FLAG_ALT_FLOOR) return rng.RandomInt(floors - 1); + if (descriptor->flags & ROOM_DESCRIPTOR_FLAG_USE_ALTERNATE_BACKDROP) return rng.RandomInt(floors - 1); break; case BACKDROP_ASHPIT: case BACKDROP_ASHPIT_SHAFT: - return descriptor->flags & ROOM_FLAG_ALT_FLOOR ? FLOOR_SECOND : levelRng.RandomInt(floors); + return descriptor->flags & ROOM_DESCRIPTOR_FLAG_USE_ALTERNATE_BACKDROP ? FLOOR_SECOND + : levelRng.RandomInt(floors); case BACKDROP_MAUSOLEUM: case BACKDROP_MAUSOLEUM2: if (descriptor && descriptor->data && descriptor->data->shape != ROOMSHAPE_1x1) return rng.RandomInt(floors - 1); break; - case BACKDROP_GEHENNA: - return levelRng.RandomInt(floors); + case BACKDROP_GEHENNA: return levelRng.RandomInt(floors); } return rng.RandomInt(floors); } -// 00932120 The quad of a rectangle of grid cells in the room, in white. -KAGE::Graphics::ColorQuad Backdrop::render_grid_rect(int x, int y, int width, int height) +// A quad by its edges, corners in KAGE's order. +static DestinationQuad quad_edges(float left, float top, float right, float bottom) { - KColor white = {}; - white._red = white._green = white._blue = white._alpha = 1; - Vector position = vector_make((float)x * GRID_SIZE + roomTopLeft.x, (float)y * GRID_SIZE + roomTopLeft.y); - return KAGE::Graphics::color_quad_rect(position, vector_make((float)width * GRID_SIZE, (float)height * GRID_SIZE), - white); + DestinationQuad quad; + + quad._topLeft = vector_make(left, top); + quad._topRight = vector_make(right, top); + quad._bottomLeft = vector_make(left, bottom); + quad._bottomRight = vector_make(right, bottom); + return quad; } -// The backdrops whose floor is one sprite, and the backdrops with wall details. -constexpr uint32_t BACKDROP_MEGA_SATAN = 18; -constexpr uint32_t BACKDROP_ERROR_ROOM = 26; -constexpr uint32_t BACKDROP_DOWNPOUR = 31; -constexpr uint32_t BACKDROP_MINES = 32; -constexpr uint32_t BACKDROP_PLANETARIUM = 35; -constexpr uint32_t BACKDROP_MAUSOLEUM4 = 42; -constexpr uint32_t BACKDROP_CLOSET = 52; -constexpr uint32_t BACKDROP_CLOSET_B = 53; -constexpr uint32_t BACKDROP_DOGMA = 54; -constexpr uint32_t BACKDROP_MINES_SHAFT = 58; -constexpr uint32_t HOME_CLOSET_FIRST_SUBTYPE = 10; -constexpr uint32_t ROOM_FLAG_PITCH_BLACK = 1 << 9; - -// Where Mega Satan's floor sprite draws past the room's corner. -constexpr float MEGA_SATAN_FLOOR_X = 0; -constexpr float MEGA_SATAN_FLOOR_Y = 130; - -static bool is_l_shape(RoomShape shape) +// A rectangle of texels by its edges, mirrored as asked. +static SourceQuad source_edges(float left, float top, float right, float bottom, Flip flip) { - return shape >= ROOMSHAPE_LTL && shape <= ROOMSHAPE_LBR; + SourceQuad source; + bool isFlipX = flip & FLIP_X; + bool isFlipY = flip & FLIP_Y; + + static_cast(source) = + quad_edges(isFlipX ? right : left, isFlipY ? bottom : top, isFlipX ? left : right, isFlipY ? top : bottom); + source._coordinateSpace = KAGE::Graphics::COORDINATES_PIXEL; + return source; } -static bool is_narrow_shape(RoomShape shape) +// 00932090 The texels of a rectangle of a sheet's cells, mirrored as asked. +static SourceQuad source_cells(int x, int y, int width, int height, Flip flip = FLIP_NONE) { - return shape == ROOMSHAPE_IH || shape == ROOMSHAPE_IV || shape == ROOMSHAPE_IIV || shape == ROOMSHAPE_IIH; + return source_edges((float)x * GRID_SIZE, (float)y * GRID_SIZE, (float)(x + width) * GRID_SIZE, + (float)(y + height) * GRID_SIZE, flip); } -// The wall details of a backdrop with them: the Downpour's pipes, the Mines' and Ashpit's (dark in a pitch black room or -// the abandoned mineshaft), Mausoleum's chains and Gehenna's. None for the others. +// (00931f50, 00931fc0, 00932020) A source rectangle mirrored across x, y or both. +static SourceQuad source_flip(const SourceQuad& source, Flip flip) +{ + return source_edges(source._topLeft.x, source._topLeft.y, source._bottomRight.x, source._bottomRight.y, flip); +} + +// The cells of a rectangle inside a variant's block of a sheet. +static SourceQuad block_cells(uint32_t block, int x, int y, int width, int height, Flip flip) +{ + return source_cells((int)(block & 1) * BLOCK_WIDTH + x, (int)(block >> 1) * BLOCK_HEIGHT + y, width, height, flip); +} + +// Draws a rectangle of an image into a quad, in its own colors. Returns the vertices, as ImageBase::Render does. +static float* image_draw(KAGE::Graphics::ImageBase& image, const SourceQuad& source, const DestinationQuad& quad) +{ + return image.Render(source, KAGE::Graphics::ColorQuad(quad, WHITE), WHITE); +} + +// Makes the ColorOffset shader current, when it is loaded. +static void color_offset_shader_select() +{ + if (KAGE::Graphics::Shader* shader = KAGE::Graphics::manager.shader_find(COLOR_OFFSET_SHADER)) + KAGE::Graphics::manager.currentShader = shader; +} + +// Turns the screen shake off for the sprites drawn into a surface, or back on. +static void screen_shake_set(bool isApplied) +{ + DAT_00c33910 = isApplied; +} + +// 00932120 The quad of a rectangle of grid cells, in surface pixels from the room's floor corner. +DestinationQuad Backdrop::render_grid_rect(int x, int y, int width, int height) +{ + return quad_edges((float)x * GRID_SIZE + roomTopLeft.x, (float)y * GRID_SIZE + roomTopLeft.y, + (float)(width + x) * GRID_SIZE + roomTopLeft.x, (float)(height + y) * GRID_SIZE + roomTopLeft.y); +} + +// The wall details of a backdrop with them: the Downpour's pipes, the Mines' and Ashpit's (dark in a pitch black room +// or the abandoned mineshaft), Mausoleum's chains and Gehenna's. None for the others. static std::string_view wall_details_path_get(uint32_t backdropId) { - bool isDark = g_game->room->descriptor->flags & ROOM_FLAG_PITCH_BLACK; + bool isDark = g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK; switch (backdropId) { @@ -252,7 +533,7 @@ static std::string_view wall_details_path_get(uint32_t backdropId) } } -// Mega Satan's floor, drawn once into the floor surface from its second idle animation, then left on the first. +// Mega Satan's floor, drawn once into the floor surface from its closed animation, then left on the open one. static void mega_satan_floor_render(Backdrop& backdrop) { KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; @@ -261,14 +542,14 @@ static void mega_satan_floor_render(Backdrop& backdrop) graphics.Clear(); KAGE::Graphics::BlendMode savedBlend = graphics.blendMode; graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); - backdrop.floorSprite.Play("Idle2"); + backdrop.floorSprite.Play(MEGA_SATAN_CLOSED_ANIMATION); graphics.isCullOffscreen = false; backdrop.floorSprite.Render({.position = vector_make(MEGA_SATAN_FLOOR_X + backdrop.roomTopLeft.x, MEGA_SATAN_FLOOR_Y + backdrop.roomTopLeft.y)}); graphics.isCullOffscreen = true; graphics.blendMode = savedBlend; graphics.Present(KAGE::Graphics::PRESENT_FINISH); - backdrop.floorSprite.Play("Idle1"); + backdrop.floorSprite.Play(MEGA_SATAN_OPEN_ANIMATION); } // 0093da00 Loads the room's backdrop graphics and draws its surfaces: the controls sprites once, then the one sprite @@ -286,7 +567,8 @@ void Backdrop::load_details() floorSprite.Reset(); wallDetailSprite.Reset(); if (!controlsSprite.isLoaded) controlsSprite.Load("gfx/backdrop/controls.anm2", GRAPHICS_LOAD); - if (!controlsButtonsSprite.isLoaded) controlsButtonsSprite.Load("gfx/backdrop/controls_buttons.anm2", GRAPHICS_LOAD); + if (!controlsButtonsSprite.isLoaded) + controlsButtonsSprite.Load("gfx/backdrop/controls_buttons.anm2", GRAPHICS_LOAD); auto size = graphics.isScreenTarget ? KAGE::Graphics::TARGET_SCREEN_SIZE : KAGE::Graphics::TARGET_OWN_SIZE; graphics.render_target_push(graphics.renderTarget, size, KAGE::Graphics::PRESENT_FLUSH); waterGfx.reset(); @@ -301,13 +583,15 @@ void Backdrop::load_details() case BACKDROP_PLANETARIUM: floorSprite.Load(config.gfx, GRAPHICS_LOAD); floorSprite.SetFrame("Idle", 0); - for (int i = 0; i < (int)floorSprite.layerStates.size(); i++) floorSprite.GetLayer(i)->isVisible = i + 1 == shape; + for (int i = 0; i < (int)floorSprite.layerStates.size(); i++) + floorSprite.GetLayer(i)->isVisible = i + 1 == shape; break; case BACKDROP_CLOSET: case BACKDROP_CLOSET_B: case BACKDROP_DOGMA: floorSprite.Load(config.gfx, GRAPHICS_LOAD); - floorSprite.SetFrame("Idle", backdropId == BACKDROP_DOGMA ? 0 : data->subtype - (int)HOME_CLOSET_FIRST_SUBTYPE); + floorSprite.SetFrame("Idle", + backdropId == BACKDROP_DOGMA ? 0 : data->subtype - (int)HOME_CLOSET_FIRST_SUBTYPE); graphics.isCullOffscreen = false; render_ashpit_ash(); graphics.isCullOffscreen = true; @@ -322,7 +606,7 @@ void Backdrop::load_details() } if (is_l_shape(g_game->room->descriptor->data->shape) && !config.lFloorGfx.empty()) nlFloorGfx = Manager::LoadImage(config.lFloorGfx); - else if (!config.nFloorGfx.empty() && is_narrow_shape((RoomShape)g_game->room->GetRoomShape())) + else if (!config.nFloorGfx.empty() && is_narrow_shape(g_game->room->GetRoomShape())) nlFloorGfx = Manager::LoadImage(config.nFloorGfx); std::string_view detailsPath = wall_details_path_get(backdropId); @@ -343,22 +627,1634 @@ void Backdrop::load_details() } graphics.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); } -void Backdrop::pre_render_walls() { reconstruction_missing("Backdrop::pre_render_walls 00937420"); } -void Backdrop::PreRenderControls() { reconstruction_missing("Backdrop::PreRenderControls 00934770"); } -void Backdrop::render_control_icon() { reconstruction_missing("Backdrop::render_control_icon 00935010"); } -void Backdrop::render_ashpit_ash() { reconstruction_missing("Backdrop::render_ashpit_ash 009353b0"); } -void Backdrop::render_floor_to_target() { reconstruction_missing("Backdrop::render_floor_to_target 009356a0"); } -void Backdrop::spawn_detail_effects(Vector, bool, bool) + +// 009353b0 Draws the floor surface: Ashpit's ash floor in rooms with the alternate backdrop (with its L or narrow +// overlay), the closets' and Dogma's floor sprite, or the backdrop's own floor sheets. The floor variant is drawn +// first, and drawn again for the backdrop's own sheets. +void Backdrop::render_ashpit_ash() { - reconstruction_missing("Backdrop::spawn_detail_effects 0093b620"); + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + Room& room = *g_game->room; + uint32_t variant = get_random_floor_variant(); + + if (is_ashpit(backdropId) && (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_USE_ALTERNATE_BACKDROP)) + { + KAGE::Graphics::ImagePtr ash = Manager::LoadImage("gfx/backdrop/04x_ashpit_ash.png"); + KAGE::Graphics::ImagePtr overlay; + if (is_l_shape(room.descriptor->data->shape)) + overlay = Manager::LoadImage("gfx/backdrop/04x_ashpit_ash_Lfloor.png"); + else if (is_narrow_shape(room.GetRoomShape())) + overlay = Manager::LoadImage("gfx/backdrop/04x_ashpit_ash_Nfloor.png"); + render_floor_to_target(variant, ash, overlay); + return; + } + if (backdropId == BACKDROP_CLOSET || backdropId == BACKDROP_CLOSET_B || backdropId == BACKDROP_DOGMA) + { + graphics.SetRenderTarget(floorBuffer.get(), KAGE::Graphics::TARGET_OWN_SIZE); + graphics.Clear(); + screen_shake_set(false); + floorSprite.RenderLayer(0, {}); + screen_shake_set(true); + graphics.Present(KAGE::Graphics::PRESENT_FINISH); + return; + } + render_floor_to_target(get_random_floor_variant(), gfx, nlFloorGfx); } -void Backdrop::spawn_wall_details() { reconstruction_missing("Backdrop::spawn_wall_details 0093b760"); } -void Backdrop::render_wall_detail() { reconstruction_missing("Backdrop::render_wall_detail 0093d510"); } -void Backdrop::render_wall_borders(Vector, Vector) { reconstruction_missing("Backdrop::render_wall_borders 0093e770"); } -void Backdrop::RenderFloor(Vector, ColorMod) { reconstruction_missing("Backdrop::RenderFloor 0093ea00"); } -void Backdrop::render_floor_surface(Vector, ColorMod) + +// Whether a floor tile at a cell falls in the quarter an L room lacks, the middle being past cell 7 across and 4 down. +static bool is_tile_cut(int shape, int x, int y) { - reconstruction_missing("Backdrop::render_floor_surface 0093f000"); + if (!is_l_shape(shape)) return false; + + int missing = shape - ROOMSHAPE_LTL; + return (x > WALL_MIDDLE_COLUMN) == (bool)(missing & FLIP_X) && (y > WALL_MIDDLE_ROW) == (bool)(missing & FLIP_Y); +} + +// The cells floor tiles start at along a floor: every 6, the second moved to 7 when there is room. +static std::vector tile_origins(int end, int step, int moved) +{ + std::vector origins; + + for (int cell = 0; cell < end; cell += step) + { + if (cell == step && end > moved) cell = moved; + origins.push_back(cell); + } + return origins; +} + +// The floor of 7 by 4 cell tiles: the backdrop's variants of the floor shuffled (repeated up to 32 first), the Dark +// Room's and Mega Satan's four drawn at random. Each tile past the first row or column is mirrored, and a last row +// and column (and their corner) meet the far walls. An L room skips the tiles of its missing quarter. +static void floor_tiles_render(Backdrop& backdrop, uint32_t variant, KAGE::Graphics::ImageBase& sheet, int shape) +{ + Room& room = *g_game->room; + BackdropConfig& config = backdrop.configs[backdrop.backdropId]; + bool isDark = backdrop.backdropId == BACKDROP_DARK_ROOM || backdrop.backdropId == BACKDROP_MEGA_SATAN; + std::vector tiles; + + if (isDark) + for (const float (&edges)[4] : DARK_TILES) + tiles.push_back(source_edges(edges[0], edges[1], edges[2], edges[3], FLIP_NONE)); + else + { + uint32_t first = (uint32_t)config.floorVariants * variant; + for (uint32_t i = first; i < first + (uint32_t)config.floorVariants; i++) + tiles.push_back(block_cells(i, BLOCK_FLOOR, BLOCK_FLOOR, TILE_WIDTH, TILE_HEIGHT, FLIP_NONE)); + // The original repeats an empty list forever. A backdrop without floor variants draws no floor. + if (tiles.empty()) return; + + while (tiles.size() < FLOOR_TILES_MIN) + { + std::vector copy = tiles; + tiles.insert(tiles.end(), copy.begin(), copy.end()); + } + for (size_t i = tiles.size() - 1; i > 0; i--) std::swap(tiles[i], tiles[backdrop.rng.Next() % (i + 1)]); + } + + int endX = room.gridWidth - WALL_CELLS - TILE_WIDTH; + int endY = room.gridHeight - (isDark ? WALL_CELLS + TILE_HEIGHT - 1 : WALL_CELLS + TILE_HEIGHT); + std::vector columns = tile_origins(endX, TILE_STEP_X, WALL_MIDDLE_COLUMN); + std::vector rows = tile_origins(endY, TILE_STEP_Y, WALL_MIDDLE_ROW); + int tile = -1; + auto tile_next = [&](uint32_t mask, uint32_t base) { + tile = isDark ? (int)((backdrop.rng.Next() & mask) + base) : tile + 1; + }; + auto tile_draw = [&](int x, int y) { + Flip flip = (x >= 1 ? FLIP_X : FLIP_NONE) | (y >= 1 ? FLIP_Y : FLIP_NONE); + image_draw(sheet, source_flip(tiles[tile], flip), backdrop.render_grid_rect(x, y, TILE_WIDTH, TILE_HEIGHT)); + }; + + for (int y : rows) + for (int x : columns) + { + if (is_tile_cut(shape, x, y)) continue; + tile_next(DARK_FLOOR_TILES - 1, 0); + tile_draw(x, y); + } + for (int y : rows) + { + if (is_tile_cut(shape, endX, y)) continue; + tile_next(DARK_FLOOR_TILES - 1, 0); + tile_draw(endX, y); + } + for (int x : columns) + { + if (is_tile_cut(shape, x, endY)) continue; + tile_next(DARK_EDGE_TILES - 1, DARK_FLOOR_TILES); + tile_draw(x, endY); + } + // The original reads before the tiles when none was drawn. Then the corner stays empty. + if (!is_tile_cut(shape, endX, endY) && tile >= 0) tile_draw(endX, endY); +} + +// The Cathedral's big rooms: 2 by 2 cell tiles of four kinds at random across the floor, and a cell in each corner. +static void cathedral_floor_render(Backdrop& backdrop, KAGE::Graphics::ImageBase& sheet) +{ + Room& room = *g_game->room; + float x = backdrop.roomTopLeft.x; + float y = backdrop.roomTopLeft.y; + + while (y < backdrop.roomBottomRight.y - EDGE_EPSILON) + { + const int (&cells)[2] = CATHEDRAL_TILES[backdrop.rng.Next() & 3]; + image_draw(sheet, source_cells(cells[0], cells[1], 2, 2), + quad_edges(x, y, x + CATHEDRAL_TILE, y + CATHEDRAL_TILE)); + x += CATHEDRAL_TILE; + if (backdrop.roomBottomRight.x - EDGE_EPSILON < x) + { + x = backdrop.roomTopLeft.x; + y += CATHEDRAL_TILE; + } + } + + int farX = room.gridWidth - WALL_CELLS - 1; + int farY = room.gridHeight - WALL_CELLS - 1; + for (int corner = 0; corner < CORNER_COUNT; corner++) + image_draw(sheet, source_cells(CATHEDRAL_CORNER[0], CATHEDRAL_CORNER[1], 1, 1, Flip(corner)), + backdrop.render_grid_rect(corner & FLIP_X ? farX : 0, corner & FLIP_Y ? farY : 0, 1, 1)); +} + +// An L room's floor from its L sheet: three 13 by 7 cell pieces of one of two variants (Ashpit's by its floor variant) +// placed and mirrored by the missing quarter. +static void l_floor_render(Backdrop& backdrop, uint32_t variant, KAGE::Graphics::ImageBase& sheet, int shape) +{ + uint32_t row = backdrop.rng.RandomInt(2); + if (is_ashpit(backdrop.backdropId)) row = variant == FLOOR_SECOND; + + const LFloorLayout& layout = L_FLOOR_LAYOUTS[shape - ROOMSHAPE_LTL]; + for (int piece = 0; piece < 3; piece++) + image_draw(sheet, + source_cells(piece * ROOM_FLOOR_COLUMNS, (int)row * ROOM_FLOOR_ROWS, ROOM_FLOOR_COLUMNS, + ROOM_FLOOR_ROWS, layout.flip), + backdrop.render_grid_rect(layout.cells[piece][0], layout.cells[piece][1], ROOM_FLOOR_COLUMNS, + ROOM_FLOOR_ROWS)); +} + +// A narrow room's floor from its narrow sheet: one of two strips (Ashpit's by its floor variant), the far end mirrored. +static void narrow_floor_render(Backdrop& backdrop, uint32_t variant, KAGE::Graphics::ImageBase& sheet, int shape) +{ + uint32_t pick = backdrop.rng.RandomInt(2); + if (is_ashpit(backdrop.backdropId)) pick = variant == FLOOR_SECOND; + + int row = (int)pick * NARROW_ROW_HEIGHT + NARROW_ROW_SHEET_Y; + int column = (int)pick * NARROW_COLUMN_WIDTH; + int width = ROOM_FLOOR_COLUMNS; + int height = ROOM_FLOOR_ROWS; + + switch (shape) + { + case ROOMSHAPE_IH: + image_draw(sheet, source_cells(0, row, width - 1, NARROW_ROW_HEIGHT), + backdrop.render_grid_rect(0, WALL_CELLS, width - 1, NARROW_ROW_HEIGHT)); + image_draw(sheet, source_cells(0, row, 1, NARROW_ROW_HEIGHT, FLIP_X), + backdrop.render_grid_rect(width - 1, WALL_CELLS, 1, NARROW_ROW_HEIGHT)); + break; + case ROOMSHAPE_IIH: + image_draw(sheet, source_cells(0, row, width, NARROW_ROW_HEIGHT), + backdrop.render_grid_rect(0, WALL_CELLS, width, NARROW_ROW_HEIGHT)); + image_draw(sheet, source_cells(0, row, width, NARROW_ROW_HEIGHT, FLIP_X), + backdrop.render_grid_rect(width, WALL_CELLS, width, NARROW_ROW_HEIGHT)); + break; + case ROOMSHAPE_IV: + image_draw(sheet, source_cells(column, 0, NARROW_COLUMN_WIDTH, height - 1), + backdrop.render_grid_rect(NARROW_COLUMN_INSET, 0, NARROW_COLUMN_WIDTH, height - 1)); + image_draw(sheet, source_cells(column, 0, NARROW_COLUMN_WIDTH, 1, FLIP_Y), + backdrop.render_grid_rect(NARROW_COLUMN_INSET, height - 1, NARROW_COLUMN_WIDTH, 1)); + break; + case ROOMSHAPE_IIV: + image_draw(sheet, source_cells(column, 0, NARROW_COLUMN_WIDTH, height), + backdrop.render_grid_rect(NARROW_COLUMN_INSET, 0, NARROW_COLUMN_WIDTH, height)); + image_draw(sheet, source_cells(column, 0, NARROW_COLUMN_WIDTH, height, FLIP_Y), + backdrop.render_grid_rect(NARROW_COLUMN_INSET, height, NARROW_COLUMN_WIDTH, height)); + break; + } +} + +// Whether the room is the start room of the Basement, or the Ascent's first room, where the controls show. +static bool is_controls_room() +{ + Game& game = *g_game; + int startRoom = game.startingRoomIdx; + + if (game.stage - 1 < ASCENT_STAGE_LAST && (game.gameStateFlags & 1ull << GAME_STATE_BACKWARDS_PATH)) + startRoom = ASCENT_START_ROOM; + return game.stage == STAGE_FIRST && game.stageType != STAGETYPE_REPENTANCE && + game.stageType != STAGETYPE_REPENTANCE_B && startRoom == game.currentRoomIdx; +} + +// 009356a0 Draws the floor surface from the floor sheet (and the L or narrow sheet when the room has one): the +// Cathedral's big rooms in small tiles, a full image as it is, or the floor tiles, then the controls in the start +// room. Backdrop 0 leaves the surface empty. +void Backdrop::render_floor_to_target(uint32_t variant, const KAGE::Graphics::ImagePtr& sheet, + const KAGE::Graphics::ImagePtr& alternate) +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + Room& room = *g_game->room; + int shape = room.GetRoomShape(); + + graphics.SetRenderTarget(floorBuffer.get(), KAGE::Graphics::TARGET_OWN_SIZE); + graphics.Clear(); + if (backdropId == BACKDROP_CATHEDRAL && shape != ROOMSHAPE_1x1 && !is_l_shape(shape) && !is_narrow_shape(shape)) + cathedral_floor_render(*this, *sheet); + else if (backdropId != 0 && configs[backdropId].isFullImage) sheet->Render(Vector{}, WHITE); + else if (backdropId != 0 && is_l_shape(shape) && alternate) l_floor_render(*this, variant, *alternate, shape); + else if (backdropId != 0 && is_narrow_shape(shape) && alternate) + narrow_floor_render(*this, variant, *alternate, shape); + else if (backdropId != 0) floor_tiles_render(*this, variant, *sheet, shape); + + if (is_controls_room()) PreRenderControls(); + graphics.Present(KAGE::Graphics::PRESENT_FINISH); +} + +// 0095aba0 The frame of the controller glyph sheet that shows a gamepad button or stick direction, or -1. +int controller_button_to_glyph_frame(int button) +{ + constexpr int BUTTON_FRAMES[] = {7, 6, 5, 4, 3, 2, 0, 1, 10, 12, 8, 11, 13, 9, 15, 14}; + constexpr int STICK_FRAMES[] = {19, 18, 17, 16, 23, 22, 21, 20}; + constexpr int BUTTON_MENU_CONFIRM = 17; + constexpr int BUTTON_MENU_BACK = 18; + + if (button == BUTTON_MENU_CONFIRM) button = KAGE::Input::BUTTON_FACE_DOWN; + else if (button == BUTTON_MENU_BACK) button = KAGE::Input::BUTTON_FACE_RIGHT; + if (button >= 0 && button < (int)std::size(BUTTON_FRAMES)) return BUTTON_FRAMES[button]; + if (button >= KAGE::Input::STICK_LEFT_LEFT && button < KAGE::Input::STICK_END) + return STICK_FRAMES[button - KAGE::Input::STICK_LEFT_LEFT]; + return -1; +} + +// 00935010 Lays out the next icon of a row of controls: the button frame of the key or button the controller has the +// action on, and its place after the icons before it (the button frame's width, spaced from the one before). The +// space bar on a keyboard moves the row right to stay centered. +void Backdrop::render_control_icon(ControlRow& row, int action) +{ + std::shared_ptr device = KAGE::Input::manager.device_find(row.controllerIndex); + bool isPadded = !row.frames.empty(); + int frame = device ? g_manager->keyConfigs.binding_get(*device, action)[0] : -1; + + if (row.controllerIndex != KEYBOARD_CONTROLLER) frame = controller_button_to_glyph_frame(frame); + else if (isPadded && frame == KEY_SPACE) row.cursorX += SPACE_KEY_PADDING; + + AnimationState& state = controlsButtonsSprite.animState; + if (state.animData) state.SetFrameFloat((float)frame); + else log_printf(LOG_ASSERT, "AnimationData is NULL\n"); + + const AnimationFrame* glyph = state.GetLayerFrame(0); + float iconX; + if (glyph && glyph->isVisible) + { + if (isPadded) + { + row.x += glyph->pivot.x; + row.cursorX -= glyph->pivot.x; + } + iconX = row.x; + row.x = glyph->width - glyph->pivot.x + iconX; + } + else + { + if (isPadded) + { + row.x += ICON_PADDING; + row.cursorX -= ICON_PADDING; + } + iconX = row.x; + frame = 0; + row.x = iconX + ICON_WIDTH; + } + row.frames.push_back(frame); + row.positions.push_back(iconX); +} + +// The controls picture of the run's character: the vanilla one's frame, a modded character's own picture, or the +// first frame for a modded character without one. +static ANM2& controls_picture_pick(Backdrop& backdrop, int playerType) +{ + if (playerType < PLAYER_TYPE_COUNT) + { + backdrop.controlsSprite.SetFrame(CONTROLS_ANIMATION, playerType); + return backdrop.controlsSprite; + } + + std::vector& players = g_manager->entityConfig.players; + EntityConfig_Player* config = playerType < (int)players.size() ? &players[playerType] : nullptr; + ANM2* modded = config ? config->moddedSprites[PLAYER_SPRITE_CONTROLS] : nullptr; + if (modded) + { + modded->SetFrame(config->GetDisplayName(), 0); + return *modded; + } + backdrop.controlsSprite.SetFrame(CONTROLS_ANIMATION, 0); + return backdrop.controlsSprite; +} + +// 00934770 Draws the controls into the start room's floor: the character's controls picture, then on each of its +// visible nulls a row of the first player's keys or gamepad buttons, each a pixel up or down at random. A gamepad the +// game cannot show buttons of shows none. Online play is not part of this build, so netplay's player type and +// controller are never read. +void Backdrop::PreRenderControls() +{ + int playerType = g_manager->startPlayerType; + ANM2& controls = controls_picture_pick(*this, playerType); + Vector position = vector_make((roomBottomRight.x + roomTopLeft.x) * 0.5f, roomTopLeft.y + CONTROLS_Y); + + const std::array& tint = backdropId == BACKDROP_BURNING_BASEMENT ? CONTROLS_BURNT_TINT : CONTROLS_TINT; + std::copy(tint.begin(), tint.end(), controls.color._tint); + controls.Render({.position = position}); + controlsButtonsSprite.color = controls.color; + + int controller = g_game->playerManager.GetPlayer(0)->controllerIndex; + if (controller == KEYBOARD_CONTROLLER) controlsButtonsSprite.SetFrame(KEYBOARD_ANIMATION, 0); + else + { + std::shared_ptr device = KAGE::Input::manager.device_find(controller); + if (!device || device->type != KAGE::Input::DEVICE_GAMEPAD) return; + controlsButtonsSprite.SetFrame(GAMEPAD_ANIMATION, 0); + } + + bool isSplitJacob = + playerType == PLAYER_JACOB && g_manager->optionsConfig.jacobEsauControls == JACOB_ESAU_SPLIT_CONTROLS; + RNG jitter = {}; + jitter.SetSeed(rng._seed, RNG_SHIFT_CONTROLS); + for (int rowIndex = 0; rowIndex < CONTROL_ROW_COUNT; rowIndex++) + { + const NullFrame* null = controls.animState.animData ? controls.animState.GetNullFrameById(rowIndex) : nullptr; + if (!null || !null->isVisible) continue; + + ControlRow row; + row.controllerIndex = controller; + for (int action : CONTROL_ROWS[rowIndex]) + { + if (action == ACTION_NONE) break; + if (isSplitJacob && action == ACTION_PILL_CARD) + { + row.cursorX -= ICON_PADDING; + render_control_icon(row, ACTION_DROP); + action = ACTION_ITEM; + } + render_control_icon(row, action); + } + + for (size_t i = 0; i < row.frames.size(); i++) + { + Vector glyph; + glyph.y = position.y + null->pos.y + (float)((int)(jitter.Next() % GLYPH_JITTER) - 1); + glyph.x = row.cursorX + row.positions[i] + position.x + null->pos.x; + if (controlsButtonsSprite.animState.animData) + controlsButtonsSprite.animState.SetFrameFloat((float)row.frames[i]); + controlsButtonsSprite.Render({.position = glyph}); + } + } +} + +// The wall sheet a room draws its walls from: its row of variants, how many variants the row has, and one cell in +// how many shows a variant other than the row's first. +struct WallSheet +{ + int chance = WALL_VARIANT_CHANCE; + int row = 0; + int variants = 0; +}; + +// A rectangle of floor cells by its corners, both included, as the shape tables give them. +struct CellRect +{ + int minX; + int minY; + int maxX; + int maxY; +}; + +// The wall row: one at random, Ashpit's and Gehenna's one per level (Ashpit's second in rooms with the alternate +// backdrop), the Basement boss rooms' own row past the variants, the Dross's last with a water current. The shop's +// walls show their variants more the better the shop. +static WallSheet wall_sheet_pick(Backdrop& backdrop) +{ + Room& room = *g_game->room; + uint32_t id = backdrop.backdropId; + BackdropConfig& config = backdrop.configs[id]; + WallSheet sheet{.variants = config.wallVariants}; + RNG levelRng = {}; + levelRng.SetSeed(backdrop.seed, RNG_SHIFT_LEVEL_FLOOR); + + if (id == BACKDROP_SHOP && (room.roomType == ROOM_SHOP || g_game->IsGreedMode())) + { + int level = room.shopLevel - SHOP_LEVEL_FIRST_CHANCE; + if (level >= 0 && level < (int)std::size(SHOP_WALL_CHANCES)) sheet.chance = SHOP_WALL_CHANCES[level]; + else sheet.variants = 1; + sheet.row = (int)backdrop.rng.RandomInt(config.walls); + } + else if (is_ashpit(id) && (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_USE_ALTERNATE_BACKDROP)) sheet.row = 1; + else if (is_ashpit(id) || id == BACKDROP_GEHENNA) sheet.row = (int)levelRng.RandomInt(config.walls); + else sheet.row = (int)backdrop.rng.RandomInt(config.walls); + + if (id == BACKDROP_BASEMENT && room.roomType == ROOM_BOSS) + { + sheet.row = sheet.variants; + sheet.variants = 1; + } + else if (id == BACKDROP_DROSS && (room.waterCurrent.x != 0 || room.waterCurrent.y != 0)) sheet.row = config.walls; + return sheet; +} + +// A coordinate pushed onto a range, its low end first. +static float clamp_edge(float value, float low, float high) +{ + if (value <= low) value = low; + if (high <= value) value = high; + return value; +} + +// Whether the room is Mom's in the Mausoleum before the Ascent. +static bool is_pre_ascent_mom_room(Room& room) +{ + return room.roomType == ROOM_BOSS && room.descriptor->data->subtype == BOSS_MOM_MAUSOLEUM && g_game->IsPreAscent(); +} + +// A blood splat of a random size from the backdrop's generator, darker in the Corpse's entrance. +static void blood_splat_spawn(Backdrop& backdrop, Vector position, bool isDarkened) +{ + Entity* splat = + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = Random()}); + float scale = backdrop.rng.RandomFloat() * SPLAT_SCALE_RANGE + SPLAT_SCALE_MIN; + + splat->sprite.scale = vector_make(scale, scale); + if (isDarkened) splat->SetColor(CORPSE_SPLAT_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + splat->Update(); +} + +// The blood a room starts with: on half the cells of a Basement boss room (those away from the walls), and on half the +// cells near the middle of the Sacrifice room, the Corpse's entrance, and Mom's room before the Ascent. +static void blood_splats_spawn(Backdrop& backdrop) +{ + Room& room = *g_game->room; + uint32_t id = backdrop.backdropId; + int cells = room.gridHeight * room.gridWidth; + auto cell_position = [&](int cell) { + return vector_make((float)(cell % room.gridWidth) * WORLD_CELL + WORLD_ORIGIN_X, + (float)(cell / room.gridWidth) * WORLD_CELL + WORLD_ORIGIN_Y); + }; + + if (id == BACKDROP_BASEMENT && room.roomType == ROOM_BOSS) + for (int cell = 0; cell < cells; cell++) + { + if (!(backdrop.rng.Next() & 1)) continue; + + Vector position = cell_position(cell); + float y = clamp_edge(position.y, room.topLeftPos.y + SPLAT_MARGIN, room.bottomRightPos.y - SPLAT_MARGIN); + float x = clamp_edge(position.x, room.topLeftPos.x + SPLAT_MARGIN, room.bottomRightPos.x - SPLAT_MARGIN); + if (x == position.x && y == position.y) blood_splat_spawn(backdrop, position, false); + } + + bool isCentered = id == BACKDROP_SACRIFICE || id == BACKDROP_CORPSE_ENTRANCE || + (is_pre_ascent_mom_room(room) && !g_game->IsAscent()); + if (!isCentered) return; + + Vector center = Room::GetCenterPos(); + int shape = room.GetRoomShape(); + for (int cell = 0; cell < cells; cell++) + { + Vector position = cell_position(cell); + float dy = position.y - center.y; + float dx = (position.x - center.x) * SPLAT_SQUASH; + if (is_horizontal_narrow(shape)) dy += dy; + if (is_vertical_narrow(shape)) dx += dx; + if ((backdrop.rng.Next() & 1) && std::sqrt(dy * dy + dx * dx) < SPLAT_RADIUS) + blood_splat_spawn(backdrop, position, id == BACKDROP_CORPSE_ENTRANCE); + } +} + +// The variant of the row's a cell of wall shows, past the row's first: none, or one at random when the chance hits. +static int wall_variant_pick(RNG& rng, const WallSheet& sheet) +{ + return rng.RandomInt(sheet.chance) == 0 ? (int)rng.RandomInt(sheet.variants) : 0; +} + +static CellRect cell_rect_a(const LRoomTileDesc& tiles) +{ + return {tiles.topLeftAX, tiles.topLeftAY, tiles.bottomRightAX, tiles.bottomRightAY}; +} + +static CellRect cell_rect_b(const LRoomTileDesc& tiles) +{ + return {tiles.topLeftBX, tiles.topLeftBY, tiles.bottomRightBX, tiles.bottomRightBY}; +} + +// The quad of a corner piece of wall outside a rectangle of floor cells (corner bit 1 the right, bit 2 the bottom). +static DestinationQuad corner_quad(Backdrop& backdrop, const CellRect& rect, int corner) +{ + int x = corner & FLIP_X ? rect.maxX : rect.minX - WALL_CELLS - 1; + int y = corner & FLIP_Y ? rect.maxY : rect.minY - WALL_CELLS - 1; + return backdrop.render_grid_rect(x, y, WALL_CELLS, WALL_CELLS); +} + +// The four corners of the walls, each a variant's corner mirrored to its side. An L room draws the corner of its +// missing quarter twice, at its two inner rooms' corners. +static void wall_corners_render(Backdrop& backdrop, const WallSheet& sheet, int shape, const LRoomTileDesc& tiles) +{ + CellRect a = cell_rect_a(tiles); + CellRect b = cell_rect_b(tiles); + CellRect bounds = {std::min(a.minX, b.minX), std::min(a.minY, b.minY), std::max(a.maxX, b.maxX), + std::max(a.maxY, b.maxY)}; + int missing = is_l_shape(shape) ? shape - ROOMSHAPE_LTL : -1; + + for (int corner = 0; corner < CORNER_COUNT; corner++) + { + int variant = sheet.row * sheet.variants + wall_variant_pick(backdrop.rng, sheet); + SourceQuad source = block_cells((uint32_t)variant, 0, 0, WALL_CELLS, WALL_CELLS, Flip(corner)); + DestinationQuad quad = corner_quad(backdrop, bounds, corner); + if (corner == missing) + { + bool isBottom = corner & FLIP_Y; + image_draw(*backdrop.gfx, source, corner_quad(backdrop, isBottom ? b : a, corner)); + quad = corner_quad(backdrop, isBottom ? a : b, corner); + } + image_draw(*backdrop.gfx, source, quad); + backdrop.spawn_wall_details({.quad = quad, .variant = variant, .wallRow = sheet.row, .flip = Flip(corner)}); + } +} + +// Where a line of wall cells sits for a cell along it: how far in the near wall (the top or left) is moved and the far +// wall (the bottom or right), and whether the cell has walls at all. L rooms move the walls of their missing quarter, +// narrow rooms their long walls, and draw their short walls only across the floor. +struct WallPlace +{ + int near = 0; + int far = 0; + bool isDrawn = true; +}; + +// The top and bottom walls over a column of the floor. +static WallPlace wall_column_place(int shape, int x, const LRoomTileDesc& tiles) +{ + switch (shape) + { + case ROOMSHAPE_LTL: return x < ROOM_FLOOR_COLUMNS ? WallPlace{.near = ROOM_FLOOR_ROWS} : WallPlace{}; + case ROOMSHAPE_LTR: return x >= ROOM_FLOOR_COLUMNS ? WallPlace{.near = ROOM_FLOOR_ROWS} : WallPlace{}; + case ROOMSHAPE_LBL: return x < ROOM_FLOOR_COLUMNS ? WallPlace{.far = -ROOM_FLOOR_ROWS} : WallPlace{}; + case ROOMSHAPE_LBR: return x >= ROOM_FLOOR_COLUMNS ? WallPlace{.far = -ROOM_FLOOR_ROWS} : WallPlace{}; + case ROOMSHAPE_IH: + case ROOMSHAPE_IIH: return {.near = NARROW_ROW_INSET, .far = -NARROW_ROW_INSET}; + case ROOMSHAPE_IV: + case ROOMSHAPE_IIV: return {.isDrawn = tiles.topLeftAX - 1 <= x && x <= tiles.bottomRightAX - 1}; + default: return {}; + } +} + +// The side walls beside a row of the floor. +static WallPlace wall_row_place(int shape, int y, const LRoomTileDesc& tiles) +{ + switch (shape) + { + case ROOMSHAPE_LTL: return y < ROOM_FLOOR_ROWS ? WallPlace{.near = ROOM_FLOOR_COLUMNS} : WallPlace{}; + case ROOMSHAPE_LTR: return y < ROOM_FLOOR_ROWS ? WallPlace{.far = -ROOM_FLOOR_COLUMNS} : WallPlace{}; + case ROOMSHAPE_LBL: return y >= ROOM_FLOOR_ROWS ? WallPlace{.near = ROOM_FLOOR_COLUMNS} : WallPlace{}; + case ROOMSHAPE_LBR: return y >= ROOM_FLOOR_ROWS ? WallPlace{.far = -ROOM_FLOOR_COLUMNS} : WallPlace{}; + case ROOMSHAPE_IV: + case ROOMSHAPE_IIV: return {.near = NARROW_COLUMN_INSET, .far = -NARROW_COLUMN_INSET}; + case ROOMSHAPE_IH: + case ROOMSHAPE_IIH: return {.isDrawn = tiles.topLeftAY - 1 <= y && y <= tiles.bottomRightAY - 1}; + default: return {}; + } +} + +// The cell of a variant's block a line of wall shows at a cell along it: the block's own cells near the start, the +// two middle cells taking turns across the middle, and near the end the block's cells again, mirrored. +static int wall_piece(int cell, int count, int edgeCells, int middle, Flip mirror, Flip& flip) +{ + flip = FLIP_NONE; + if (cell < edgeCells) return cell + WALL_CELLS; + if (cell < count - edgeCells - 1) return middle + (cell & 1); + + flip = mirror; + return count - 1 - cell; +} + +// One cell of wall: the sheet's piece for its variant drawn into the wall surface, and the backdrop's effects there. +static void wall_cell_draw(Backdrop& backdrop, const WallSlot& slot, const SourceQuad& source) +{ + image_draw(*backdrop.gfx, source, slot.quad); + backdrop.spawn_wall_details(slot); +} + +// The top and bottom walls, a column at a time from the left, and the side walls, a row at a time from the top. +static void wall_lines_render(Backdrop& backdrop, const WallSheet& sheet, int shape, const LRoomTileDesc& tiles) +{ + Room& room = *g_game->room; + Flip flip; + + for (int x = 0; x < room.gridWidth - WALL_CELLS; x++) + { + WallPlace place = wall_column_place(shape, x, tiles); + if (!place.isDrawn) continue; + + int top = wall_variant_pick(backdrop.rng, sheet); + int bottom = wall_variant_pick(backdrop.rng, sheet); + int slotX = wall_piece(x, room.gridWidth, WALL_EDGE_COLUMNS, WALL_MIDDLE_COLUMN, FLIP_X, flip); + uint32_t first = (uint32_t)(sheet.row * sheet.variants); + wall_cell_draw(backdrop, + {.quad = backdrop.render_grid_rect(x, place.near - WALL_CELLS, 1, WALL_CELLS), + .slotX = slotX, + .variant = top, + .wallRow = sheet.row, + .flip = flip}, + block_cells(first + top, slotX, 0, 1, WALL_CELLS, flip)); + wall_cell_draw(backdrop, + {.quad = backdrop.render_grid_rect(x, room.gridHeight + place.far - WALL_CELLS, 1, WALL_CELLS), + .slotX = slotX, + .variant = bottom, + .wallRow = sheet.row, + .flip = flip | FLIP_Y}, + block_cells(first + bottom, slotX, 0, 1, WALL_CELLS, flip | FLIP_Y)); + } + + for (int y = 0; y < room.gridHeight - WALL_CELLS; y++) + { + WallPlace place = wall_row_place(shape, y, tiles); + if (!place.isDrawn) continue; + + int left = wall_variant_pick(backdrop.rng, sheet); + int right = wall_variant_pick(backdrop.rng, sheet); + int slotY = wall_piece(y, room.gridHeight, WALL_EDGE_ROWS, WALL_MIDDLE_ROW, FLIP_Y, flip); + uint32_t first = (uint32_t)(sheet.row * sheet.variants); + wall_cell_draw(backdrop, + {.quad = backdrop.render_grid_rect(place.near - WALL_CELLS, y, WALL_CELLS, 1), + .slotY = slotY, + .variant = left, + .wallRow = sheet.row, + .flip = flip}, + block_cells(first + left, 0, slotY, WALL_CELLS, 1, flip)); + wall_cell_draw(backdrop, + {.quad = backdrop.render_grid_rect(room.gridWidth + place.far - WALL_CELLS, y, WALL_CELLS, 1), + .slotY = slotY, + .variant = right, + .wallRow = sheet.row, + .flip = flip | FLIP_X}, + block_cells(first + right, 0, slotY, WALL_CELLS, 1, flip | FLIP_X)); + } +} + +// An L room's inner corner: the sheet's corner piece of the wall row, mirrored toward the missing quarter. +static void l_corner_render(Backdrop& backdrop, const WallSheet& sheet, int shape) +{ + if (!is_l_shape(shape)) return; + + int missing = shape - ROOMSHAPE_LTL; + int x = missing & FLIP_X ? ROOM_FLOOR_COLUMNS : ROOM_FLOOR_COLUMNS - WALL_CELLS; + int y = missing & FLIP_Y ? ROOM_FLOOR_ROWS : ROOM_FLOOR_ROWS - WALL_CELLS; + image_draw(*backdrop.gfx, + source_cells(L_CORNER_SHEET_X, sheet.row * WALL_CELLS, WALL_CELLS, WALL_CELLS, Flip(missing)), + backdrop.render_grid_rect(x, y, WALL_CELLS, WALL_CELLS)); +} + +// The Cathedral's narrow and L rooms: its pillars where the walls turn, from the sheet's first block (a side piece, its +// end, and a top piece) mirrored to each place. +static void cathedral_pieces_render(Backdrop& backdrop, int shape, const LRoomTileDesc& tiles) +{ + if (g_game->stage != STAGE_CATHEDRAL || g_game->stageType != STAGETYPE_WOTL) return; + + SourceQuad side = source_cells(0, WALL_CELLS, WALL_CELLS, 1); + SourceQuad sideEnd = source_cells(0, WALL_CELLS, WALL_CELLS, WALL_CELLS, FLIP_Y); + SourceQuad top = source_cells(WALL_CELLS, 0, 1, WALL_CELLS); + CellRect a = cell_rect_a(tiles); + CellRect b = cell_rect_b(tiles); + int wall = WALL_CELLS + 1; + auto draw = [&](const SourceQuad& source, Flip flip, int x, int y, int width, int height) { + image_draw(*backdrop.gfx, source_flip(source, flip), backdrop.render_grid_rect(x, y, width, height)); + }; + + switch (shape) + { + case ROOMSHAPE_IH: + case ROOMSHAPE_IIH: + case ROOMSHAPE_IV: + case ROOMSHAPE_IIV: + draw(side, FLIP_NONE, a.minX - wall, a.minY - 1, WALL_CELLS, 1); + draw(sideEnd, FLIP_NONE, a.minX - wall, a.maxY - WALL_CELLS, WALL_CELLS, WALL_CELLS); + draw(side, FLIP_X, a.maxX, a.minY - 1, WALL_CELLS, 1); + draw(sideEnd, FLIP_X, a.maxX, a.maxY - WALL_CELLS, WALL_CELLS, WALL_CELLS); + draw(top, FLIP_NONE, a.minX - 1, a.minY - wall, 1, WALL_CELLS); + draw(top, FLIP_Y, a.minX - 1, a.maxY, 1, WALL_CELLS); + draw(top, FLIP_X, a.maxX - 1, a.minY - wall, 1, WALL_CELLS); + draw(top, FLIP_XY, a.maxX - 1, a.maxY, 1, WALL_CELLS); + break; + case ROOMSHAPE_LBL: + draw(side, FLIP_Y, a.minX - wall, a.maxY - 1, WALL_CELLS, 1); + draw(top, FLIP_Y, b.minX - 1, b.maxY, 1, WALL_CELLS); + break; + case ROOMSHAPE_LBR: + draw(side, FLIP_XY, a.maxX, a.maxY - 1, WALL_CELLS, 1); + draw(top, FLIP_XY, b.maxX - 1, b.maxY, 1, WALL_CELLS); + break; + case ROOMSHAPE_LTL: + draw(top, FLIP_NONE, a.minX - 1, a.minY - wall, 1, WALL_CELLS); + draw(side, FLIP_NONE, b.minX - wall, b.minY - 1, WALL_CELLS, 1); + break; + case ROOMSHAPE_LTR: + draw(top, FLIP_X, a.maxX - 1, a.minY - wall, 1, WALL_CELLS); + draw(side, FLIP_X, b.maxX, b.minY - 1, WALL_CELLS, 1); + break; + } +} + +// Whether the backdrop's wall details show with this wall row: the Downpour's and the Dross's pipes with the second, +// the Mines' with the first, Ashpit's but with the second, Mausoleum's chains and Gehenna's always. +static bool is_wall_details_shown(uint32_t id, int row) +{ + if ((id == BACKDROP_DOWNPOUR || id == BACKDROP_DROSS) && row == 1) return true; + if (id == BACKDROP_MINES || id == BACKDROP_MINES_SHAFT) return row == 0; + if (is_ashpit(id)) return row != 1; + return id == BACKDROP_MAUSOLEUM4 || id == BACKDROP_GEHENNA; +} + +// The wall detail sprite at each outer corner of the walls, mirrored to it. An L room shows it at both corners of its +// missing quarter's inner rooms, and narrow rooms keep it on their long walls. +static void wall_details_render(Backdrop& backdrop, const WallSheet& sheet, int shape) +{ + if (!backdrop.wallDetailSprite.isLoaded) return; + + Room& room = *g_game->room; + uint32_t id = backdrop.backdropId; + screen_shake_set(false); + if (is_wall_details_shown(id, sheet.row)) + { + int width = room.gridWidth; + int height = room.gridHeight; + int left = -WALL_CELLS; + int top = -WALL_CELLS; + if (is_vertical_narrow(shape)) + { + width -= NARROW_COLUMN_INSET; + left = WALL_CELLS; + } + else if (is_horizontal_narrow(shape)) + { + height -= WALL_CELLS; + top = 0; + } + + WallDetail detail; + detail.chance = is_ashpit(id) && sheet.row == ASHPIT_DARK_WALLS ? ASHPIT_DETAIL_CHANCE : WALL_DETAIL_CHANCE; + detail.sides = WallSides((is_vertical_narrow(shape) ? WALL_SIDES_NONE : WALL_SIDES_HORIZONTAL) | + (is_horizontal_narrow(shape) ? WALL_SIDES_NONE : WALL_SIDES_VERTICAL)); + int missing = is_l_shape(shape) ? shape - ROOMSHAPE_LTL : -1; + auto render_at = [&](int x, int y, int corner) { + detail.position = vector_make((float)x * GRID_SIZE + backdrop.roomTopLeft.x, + (float)y * GRID_SIZE + backdrop.roomTopLeft.y); + detail.flip = Flip(corner); + backdrop.render_wall_detail(detail); + }; + + for (int corner = 0; corner < CORNER_COUNT; corner++) + { + bool isRight = corner & FLIP_X; + bool isBottom = corner & FLIP_Y; + int x = isRight ? width : left; + int y = isBottom ? height : top; + if (corner != missing) + { + render_at(x, y, corner); + continue; + } + render_at(isRight ? x - ROOM_FLOOR_COLUMNS : x + ROOM_FLOOR_COLUMNS, y, corner); + render_at(x, isBottom ? y - ROOM_FLOOR_ROWS : y + ROOM_FLOOR_ROWS, corner); + } + } + screen_shake_set(true); +} + +// 00937420 Draws the wall surface from the wall sheet: first the blood some rooms start with, then the corners, the top +// and bottom walls and the side walls cell by cell (each cell a variant of the room's wall row now and then, the +// backdrop's effects spawned on it), an L room's inner corner, the Cathedral's pillars and the wall details. +// A backdrop without walls leaves the surface alone, backdrop 0 and full images leave it empty. +void Backdrop::pre_render_walls() +{ + BackdropConfig& config = configs[backdropId]; + if (config.walls == 0) return; + + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + Room& room = *g_game->room; + int shape = room.GetRoomShape(); + LRoomTileDesc tiles = room.GetLRoomTileDesc(); + + graphics.SetRenderTarget(wallsBuffer.get(), KAGE::Graphics::TARGET_OWN_SIZE); + graphics.Clear(); + if (backdropId != 0 && !config.isFullImage) + { + WallSheet sheet = wall_sheet_pick(*this); + blood_splats_spawn(*this); + wall_corners_render(*this, sheet, shape, tiles); + wall_lines_render(*this, sheet, shape, tiles); + l_corner_render(*this, sheet, shape); + cathedral_pieces_render(*this, shape, tiles); + wall_details_render(*this, sheet, shape); + } + graphics.Present(KAGE::Graphics::PRESENT_FINISH); +} + +// 0093b480 A point of the wall surface in the world: the surface is the world at 0.65 scale from two cells out of the +// room's corner, narrow rooms' surfaces moved to their walls. +Vector backdrop_detail_to_world_pos(Vector position) +{ + Room& room = *g_game->room; + Vector world = vector_make((room.topLeftPos.x - SURFACE_ORIGIN) + position.x / SURFACE_SCALE, + (room.topLeftPos.y - SURFACE_ORIGIN) + position.y / SURFACE_SCALE); + int shape = room.GetRoomShape(); + + if (is_horizontal_narrow(shape)) world.y -= NARROW_SHIFT_Y; + else if (is_vertical_narrow(shape)) world.x -= NARROW_SHIFT_X; + return world; +} + +// 0093b580 The direction out of the room a wall cell faces: down or up for the top and bottom walls (slot past 0), +// right or left for the side walls, by its mirroring. +Vector backdrop_wall_normal(int slotX, Flip flip) +{ + if (slotX != 0) return vector_make(0, flip & FLIP_Y ? -1 : 1); + return vector_make(flip & FLIP_X ? -1 : 1, 0); +} + +// 0093b530 The middle of a cell of wall in the world. +static Vector wall_center(const DestinationQuad& quad) +{ + return backdrop_detail_to_world_pos( + vector_make((quad._topLeft.x + quad._bottomRight.x) * 0.5f, (quad._bottomRight.y + quad._topLeft.y) * 0.5f)); +} + +// The animation of a wall detail sprite for a slot: "h" and the column along the top wall, "v" and the row down the +// side wall. +static std::string slot_animation(const WallSlot& slot) +{ + bool isSide = slot.slotX == 0; + return {isSide ? 'v' : 'h', (char)('0' + (isSide ? slot.slotY : slot.slotX))}; +} + +// A point of the world a null's frame of a surface sprite is at, mirrored with the sprite. +static Vector null_world_pos(const NullFrame& frame, Vector base, Flip flip) +{ + float x = frame.pos.x / SURFACE_SCALE; + float y = frame.pos.y / SURFACE_SCALE; + return vector_make((flip & FLIP_X ? -x : x) + base.x, (flip & FLIP_Y ? -y : y) + base.y); +} + +// A light (1000.121) on a backdrop detail, in a null frame's color and scale. +static Entity* null_light_spawn(Vector position, const NullFrame& frame) +{ + Entity* light = + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_LIGHT, .seed = Random()}); + + light->flags |= FLAG_BACKDROP_DETAIL; + static_cast(light)->scale = LIGHT_SCALE; + light->SetColor(frame.color, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + light->sprite.scale = frame.scale; + return light; +} + +// 0093b620 A light on every visible null of a backdrop decoration shown at a world position, drawn over the room. +static void detail_lights_spawn(const ANM2& sprite, Vector position, Flip flip) +{ + int count = sprite.file ? (int)sprite.file->nullLayerNames.size() : 0; + + for (int nullId = 0; nullId < count; nullId++) + { + const NullFrame* frame = sprite.animState.animData ? sprite.animState.GetNullFrameById(nullId) : nullptr; + if (frame && frame->isVisible) + null_light_spawn(null_world_pos(*frame, position, flip), *frame)->renderZOffset = DETAIL_RENDER_Z; + } +} + +// A light on a cell of wall: 20 pixels out of it into the room, drawn back toward the wall. +static Entity* wall_light_spawn(const WallSlot& slot, float drawBack, int subType) +{ + Vector normal = backdrop_wall_normal(slot.slotX, slot.flip); + Vector center = wall_center(slot.quad); + Vector position = vector_make(normal.x * WALL_LIGHT_OUT + center.x, normal.y * WALL_LIGHT_OUT + center.y); + Entity* light = g_game->Spawn( + {.position = position, .subType = subType, .type = ENTITY_EFFECT, .variant = EFFECT_LIGHT, .seed = Random()}); + + light->flags |= FLAG_BACKDROP_DETAIL; + light->posOffset = vector_make(normal.x * drawBack, normal.y * drawBack); + return light; +} + +// An ember glowing on a cell of wall, of a random size from the backdrop's generator. +static void ember_spawn(Backdrop& backdrop, const WallSlot& slot, float drawBack, bool isFlattened) +{ + Vector normal = backdrop_wall_normal(slot.slotX, slot.flip); + Entity* ember = wall_light_spawn(slot, drawBack, 0); + + static_cast(ember)->scale = LIGHT_SCALE; + ember->SetColor(EMBER_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + if (!isFlattened) + { + float scale = backdrop.rng.RandomFloat() * BURNING_EMBER_RANGE + BURNING_EMBER_MIN; + ember->sprite.scale = vector_make(scale, scale); + return; + } + float scale = backdrop.rng.RandomFloat() * ASHPIT_EMBER_RANGE + ASHPIT_EMBER_MIN; + ember->sprite.scale = vector_make((std::fabs(normal.y) + 1) * scale, (std::fabs(normal.x) + 1) * scale); +} + +// A backdrop decoration (1000.140) showing a wall detail sprite in the walls' color. +static Entity* decoration_spawn(Vector position, std::string_view path) +{ + Entity* decoration = g_game->Spawn( + {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BACKDROP_DECORATION, .seed = Random()}); + + decoration->sprite.Load(path, GRAPHICS_LOAD); + decoration->sprite.color = g_game->room->wallColor; + return decoration; +} + +// A decoration on a cell of wall playing its slot's animation, mirrored with the wall. +static Entity* slot_decoration_spawn(Vector position, std::string_view path, const WallSlot& slot, + std::string_view name) +{ + Entity* decoration = decoration_spawn(position, path); + + decoration->sprite.Play(name, PLAY_FORCED); + decoration->sprite.isFlipX = slot.flip & FLIP_X; + decoration->sprite.isFlipY = slot.flip & FLIP_Y; + return decoration; +} + +// Where a decoration hangs beside a top wall's door column: a cell out from the column, in the world. +static Vector hanging_position(const WallSlot& slot) +{ + bool isFlipX = slot.flip & FLIP_X; + return backdrop_detail_to_world_pos(isFlipX + ? vector_make(slot.quad._topRight.x + WALL_SIZE, slot.quad._topRight.y + 0) + : vector_make(slot.quad._topLeft.x - WALL_SIZE, slot.quad._topLeft.y - 0)); +} + +// A decoration hung beside a top wall's door column, mirrored with the wall, drawn over the room. +static Entity* hanging_decoration_spawn(const WallSlot& slot, Vector position, std::string_view path) +{ + bool isFlipX = slot.flip & FLIP_X; + Entity* decoration = decoration_spawn(position, path); + + decoration->flags |= FLAG_BACKDROP_DETAIL; + decoration->sprite.SetFrame(decoration->sprite.GetDefaultAnimationName(), 0); + decoration->sprite.isFlipX = isFlipX; + decoration->sprite.isFlipY = false; + decoration->renderZOffset = DETAIL_RENDER_Z; + return decoration; +} + +// A blood splat colored as asked, a random size from the global generator, its seed from the backdrop's. +static void colored_splat_spawn(Backdrop& backdrop, Vector position, const ColorMod& color, float range) +{ + float scale = (float)Random() * SPLAT_SCALE_STEP * range + 1; + Entity* splat = g_game->Spawn( + {.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT, .seed = backdrop.rng.Next()}); + + splat->sprite.scale = vector_make(scale, scale); + splat->SetColor(color, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + splat->Update(); +} + +// The Cathedral's light through the top walls' windows, slanted with the corner. +static void cathedral_light_spawn(const WallSlot& slot) +{ + if (slot.slotY != 0 || slot.slotX != CATHEDRAL_WINDOW_SLOT || slot.variant == CATHEDRAL_PLAIN_VARIANT) return; + + float xSign = slot.flip & FLIP_X ? -1.0f : 1.0f; + float ySign = slot.flip & FLIP_Y ? -1.0f : 1.0f; + Vector center = wall_center(slot.quad); + Vector position = vector_make(xSign * CATHEDRAL_LIGHT_X + center.x, ySign * CATHEDRAL_LIGHT_Y + center.y); + Entity* light = + g_game->Spawn({.position = position, .type = ENTITY_EFFECT, .variant = EFFECT_LIGHT, .seed = Random()}); + + light->flags |= FLAG_BACKDROP_DETAIL; + light->SetColor(CATHEDRAL_LIGHT_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + light->sprite.scale = vector_make(CATHEDRAL_LIGHT_SCALE_X, CATHEDRAL_LIGHT_SCALE_Y); + light->sprite.rotation = ySign * xSign * CATHEDRAL_LIGHT_ANGLE; +} + +// The Dank Depths: tar dripped off each cell of wall but the corners, a pillar on the fourth column, and the sheet's +// details on the variants that have them. +static void dank_details_spawn(Backdrop& backdrop, const WallSlot& slot) +{ + if (slot.slotX != 0 || slot.slotY != 0) + { + Vector normal = backdrop_wall_normal(slot.slotX, slot.flip); + Vector center = wall_center(slot.quad); + float out = backdrop.rng.RandomFloat() * TAR_OUT_RANGE + TAR_OUT_MIN; + Vector position = vector_make(normal.x * out + center.x, normal.y * out + center.y); + float cosine = std::cos(HALF_TURN); + float sine = std::sin(HALF_TURN); + Vector along = vector_make(normal.x * cosine - normal.y * sine, normal.y * cosine + normal.x * sine); + float shift = backdrop.rng.RandomFloat() * TAR_SHIFT_RANGE - TAR_SHIFT_RANGE; + position.x += shift * along.x; + position.y += shift * along.y; + colored_splat_spawn(backdrop, position, TAR_COLOR, TAR_SCALE_RANGE); + + if (slot.slotX == DANK_PILLAR_SLOT) + slot_decoration_spawn(wall_center(slot.quad), DANK_DETAILS, slot, "pillar")->flags |= FLAG_RENDER_FLOOR; + } + if (slot.wallRow != 0 || (slot.variant != 1 && slot.variant != DANK_DETAIL_VARIANT)) return; + + std::string name = slot.slotX == 0 && slot.slotY == 0 ? "0" : slot_animation(slot); + slot_decoration_spawn(wall_center(slot.quad), DANK_DETAILS, slot, name)->flags |= + FLAG_RENDER_FLOOR | FLAG_RENDER_WALL; +} + +// The Dross: lights on the second row's every other cell (one in 40 another kind), and on the first row's second +// variant pipes out of the walls (but into rocks, locks, TNT and poop), leaking in rooms with the alternate backdrop. +static void dross_details_spawn(Backdrop& backdrop, const WallSlot& slot, bool isDark) +{ + if (slot.wallRow == 1) + { + bool isLit = (slot.slotX >= DROSS_LIGHT_FIRST && slot.slotX % 2 == 1) || + (slot.slotY >= DROSS_LIGHT_FIRST && slot.slotY % 2 == 1); + if (!isLit || isDark) return; + + int subType = backdrop.rng.RandomInt(DROSS_LIGHT_ODDS) == 0; + Entity* light = wall_light_spawn(slot, -WALL_LIGHT_OUT, subType); + light->SetColor(DROSS_LIGHT_COLOR, COLOR_DURATION_FOREVER, COLOR_PRIORITY_TOP, false, true); + light->sprite.scale = vector_make(DROSS_LIGHT_SCALE, DROSS_LIGHT_SCALE); + return; + } + bool isPipeSlot = slot.slotX == 3 || slot.slotX == 5 || slot.slotX == 7 || slot.slotY == 3 || slot.slotY == 5; + if (slot.wallRow != 0 || slot.variant != 1 || !isPipeSlot) return; + + Room& room = *g_game->room; + Vector normal = backdrop_wall_normal(slot.slotX, slot.flip); + Vector center = wall_center(slot.quad); + Vector position = vector_make(normal.x * WALL_LIGHT_OUT + center.x, normal.y * WALL_LIGHT_OUT + center.y); + Vector inside = vector_make(position.x + normal.x * DROSS_PIPE_REACH, normal.y * DROSS_PIPE_REACH + position.y); + GridEntity* grid = room.GetGridEntity((uint32_t)room.GetGridIndex(inside)); + if (grid && std::find(std::begin(DROSS_PIPE_BLOCKERS), std::end(DROSS_PIPE_BLOCKERS), grid->type) != + std::end(DROSS_PIPE_BLOCKERS)) + return; + + Entity* pipe = slot_decoration_spawn(position, "gfx/backdrop/02x_dross_pipes.anm2", slot, slot_animation(slot)); + pipe->flags |= FLAG_BACKDROP_DETAIL; + pipe->posOffset = vector_make(-normal.x * WALL_LIGHT_OUT, -normal.y * WALL_LIGHT_OUT); + if (!(room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_USE_ALTERNATE_BACKDROP)) return; + + const float (&leak)[2] = slot.slotX == 0 ? DROSS_LEAK_SIDE : DROSS_LEAK_TOP; + Vector drip = vector_make(normal.y * leak[0] + normal.x * leak[1] + position.x, + -normal.x * leak[0] + normal.y * leak[1] + position.y); + colored_splat_spawn(backdrop, drip, DROSS_LEAK_COLOR, DROSS_LEAK_RANGE); +} + +// The Mines: the background details on the second and third rows' first corner (the second's with their lights), and +// one lantern in four beside the first row's top wall doors, with its lights. +static void mines_details_spawn(Backdrop& backdrop, const WallSlot& slot, bool isDark) +{ + std::string_view background = + isDark ? "gfx/backdrop/03x_mines_bg_details_dark.anm2" : "gfx/backdrop/03x_mines_bg_details.anm2"; + + if (slot.wallRow == 1 || slot.wallRow == 2) + { + if (slot.slotX != 0 || slot.slotY != 0) return; + + Vector center = wall_center(slot.quad); + Entity* details = slot_decoration_spawn(center, background, slot, slot.wallRow == 1 ? "0" : "1"); + if (slot.wallRow == 2) + { + details->flags |= FLAG_RENDER_FLOOR; + return; + } + detail_lights_spawn(details->sprite, center, slot.flip); + details->flags |= FLAG_RENDER_FLOOR | FLAG_RENDER_WALL; + return; + } + if (slot.wallRow != 0 || slot.slotX != DOOR_SIDE_SLOT || (slot.flip & FLIP_Y)) return; + if (backdrop.rng.RandomInt(MINES_LANTERN_ODDS) != 0) return; + + Vector position = hanging_position(slot); + Entity* lantern = hanging_decoration_spawn( + slot, position, isDark ? "gfx/backdrop/03x_mines_lanterns_dark.anm2" : "gfx/backdrop/03x_mines_lanterns.anm2"); + detail_lights_spawn(lantern->sprite, position, Flip(slot.flip & FLIP_X)); +} + +// Mausoleum's torches on every other top wall cell and the side walls' middle, one in three out. +static void mausoleum_torch_spawn(Backdrop& backdrop, const WallSlot& slot) +{ + if (slot.slotX != 2 && slot.slotX != 4 && slot.slotX != 6 && slot.slotY != 3) return; + + Vector normal = backdrop_wall_normal(slot.slotX, slot.flip); + Vector center = wall_center(slot.quad); + Vector position = vector_make(normal.x * WALL_LIGHT_OUT + center.x, normal.y * WALL_LIGHT_OUT + center.y); + bool isB = backdrop.backdropId == BACKDROP_MAUSOLEUM3; + bool isOff = backdrop.rng.RandomInt(MAUSOLEUM_TORCH_ODDS) == 0; + std::string_view path = + isOff ? (isB ? "gfx/backdrop/05x_mausoleumB_torches_off.anm2" : "gfx/backdrop/05x_mausoleum_torches_off.anm2") + : (isB ? "gfx/backdrop/05x_mausoleumB_torches.anm2" : "gfx/backdrop/05x_mausoleum_torches.anm2"); + Entity* torch = slot_decoration_spawn(position, path, slot, slot_animation(slot)); + + torch->posOffset = vector_make(-normal.x * WALL_LIGHT_OUT, -normal.y * WALL_LIGHT_OUT); + torch->flags |= FLAG_BACKDROP_DETAIL; +} + +// Gehenna: wall details on half the first row's second variant cells, and chains (each link one in three) beside two +// of three top wall doors. +static void gehenna_details_spawn(Backdrop& backdrop, const WallSlot& slot) +{ + bool isDetailSlot = (slot.slotX > 1 && slot.slotX < 7) || (slot.slotY > 1 && slot.slotY < 5); + if (slot.wallRow == 0 && slot.variant == 1 && isDetailSlot && backdrop.rng.RandomInt(2) == 0) + { + Entity* details = slot_decoration_spawn(wall_center(slot.quad), "gfx/backdrop/06x_gehenna_wall_details.anm2", + slot, slot_animation(slot)); + details->sortingLayer = SORTING_DOOR; + } + if (slot.slotX != DOOR_SIDE_SLOT || (slot.flip & FLIP_Y)) return; + if (backdrop.rng.RandomInt(GEHENNA_CHAIN_ODDS) == 0) return; + + Entity* chains = hanging_decoration_spawn(slot, hanging_position(slot), "gfx/backdrop/06x_gehenna_chains.anm2"); + chains->sprite.SetFrame(chains->sprite.GetDefaultAnimationName(), (int)backdrop.rng.RandomInt(2)); + for (LayerState& layer : chains->sprite.layerStates) + layer.isVisible = backdrop.rng.RandomInt(GEHENNA_CHAIN_ODDS) == 0; +} + +// 0093b760 The effects a backdrop adds on a cell of wall as it is drawn: the Burning Basement's and Ashpit's embers, +// the Cathedral's window light, the Dank Depths' tar and details, the Dross's lights and pipes, the Mines' details and +// lanterns, Mausoleum's torches and Gehenna's details and chains. +void Backdrop::spawn_wall_details(const WallSlot& slot) +{ + bool isDark = g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK; + + switch (backdropId) + { + case BACKDROP_BURNING_BASEMENT: + if (slot.variant == 1) ember_spawn(*this, slot, BURNING_EMBER_DRAW_BACK, false); + break; + case BACKDROP_CATHEDRAL: cathedral_light_spawn(slot); break; + case BACKDROP_DANK_DEPTHS: dank_details_spawn(*this, slot); break; + case BACKDROP_DROSS: dross_details_spawn(*this, slot, isDark); break; + case BACKDROP_MINES_SHAFT: mines_details_spawn(*this, slot, true); break; + case BACKDROP_MINES: mines_details_spawn(*this, slot, isDark); break; + case BACKDROP_ASHPIT: + case BACKDROP_ASHPIT_SHAFT: + if (slot.wallRow <= 1 && (slot.slotX >= 2 || slot.slotY >= 2) && slot.variant == 1) + ember_spawn(*this, slot, ASHPIT_EMBER_DRAW_BACK, true); + break; + case BACKDROP_MAUSOLEUM: + case BACKDROP_MAUSOLEUM3: mausoleum_torch_spawn(*this, slot); break; + case BACKDROP_GEHENNA: gehenna_details_spawn(*this, slot); break; + } +} + +// The frames of the track a layer of an animation has, 0 for a layer the animation does not key. +static uint32_t layer_frame_count(const AnimationData* data, int layerId) +{ + // The original reads the track before the first for an unkeyed layer. + if (!data || layerId >= ANM2_LAYER_LIMIT || data->layerMap[layerId] < 0) return 0; + return (uint32_t)data->animLayers[data->layerMap[layerId]].frames.size(); +} + +// 0093d510 Draws the wall detail sprite at a corner of the walls: each of its layers on the walls it is for (named h... +// or v...) shows at the chance, on a random frame (Mausoleum's chains always on the top corners, never the bottom). +// Then, unless the room is dark or a shaft, a light spawns on each null named "*" and a shown layer's id, from the +// null's frame at the layer's keyframe. +void Backdrop::render_wall_detail(const WallDetail& detail) +{ + ANM2& sprite = wallDetailSprite; + const AnimationData* data = sprite.animState.animData; + float chance = backdropId == BACKDROP_MAUSOLEUM4 ? (detail.flip & FLIP_Y ? 0.0f : 1.0f) : detail.chance; + + for (int layerId = 0; layerId < (int)sprite.layerStates.size(); layerId++) + { + LayerState& layer = *sprite.GetLayer(layerId); + char kind = layer.layerData && !layer.layerData->name.empty() ? layer.layerData->name[0] : '\0'; + bool isOnWall = (kind == 'h' && (detail.sides & WALL_SIDES_HORIZONTAL)) || + (kind == 'v' && (detail.sides & WALL_SIDES_VERTICAL)); + layer.isVisible = isOnWall && rng.RandomFloat() < chance; + if (layer.isVisible) sprite.SetLayerFrame(layerId, (int)rng.RandomInt(layer_frame_count(data, layerId))); + } + sprite.isFlipX = detail.flip & FLIP_X; + sprite.isFlipY = detail.flip & FLIP_Y; + sprite.Render({.position = detail.position}); + + bool isDark = backdropId == BACKDROP_MINES_SHAFT || backdropId == BACKDROP_ASHPIT_SHAFT || + (g_game->room->descriptor->flags & ROOM_DESCRIPTOR_FLAG_PITCH_BLACK); + int nullCount = sprite.file ? (int)sprite.file->nullLayerNames.size() : 0; + if (isDark || !data) return; + + for (int nullId = 0; nullId < nullCount; nullId++) + { + const std::string& name = sprite.GetNullLayerName(nullId); + if (name.empty() || name[0] != '*') continue; + + int layerId = std::atoi(name.c_str() + 1); + if (!sprite.GetLayer(layerId)->isVisible) continue; + + int frameIndex = sprite.animState.GetLayerFrameIdx(layerId); + auto track = + std::find_if(data->nullLayers.begin(), data->nullLayers.end(), [&](const AnimationNullLayer& null) { + return null.nullLayerId == nullId && frameIndex >= 0 && frameIndex < (int)null.frames.size(); + }); + if (track == data->nullLayers.end() || !track->frames[frameIndex].isVisible) continue; + + const NullFrame& frame = track->frames[frameIndex]; + null_light_spawn(null_world_pos(frame, backdrop_detail_to_world_pos(detail.position), detail.flip), frame); + } +} + +// 0093ea00 Draws the floor: the Error room's sprite repeated over the floor, Mega Satan's sprite (or its surface while +// the closed floor shows), the Planetarium's sprite, or the floor surface in the room's floor color. Ultra Greed's shop +// blends its floor, the others draw it opaque. +void Backdrop::RenderFloor(Vector renderOffset, ColorMod color) +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + KAGE::Graphics::BlendMode savedBlend = graphics.blendMode; + graphics.blend_set(backdropId == BACKDROP_GREED_SHOP ? KAGE::Graphics::BLEND_NORMAL : KAGE::Graphics::BLEND_OPAQUE); + + if (backdropId == BACKDROP_ERROR_ROOM) + { + screen_shake_set(false); + for (float y = roomTopLeft.y, x = roomTopLeft.x; y < roomBottomRight.y - EDGE_EPSILON;) + { + SpriteDraw draw{.position = vector_make(x + renderOffset.x, y + renderOffset.y)}; + draw.bottomRightClamp = vector_make(std::max(x - roomBottomRight.x + ERROR_TILE, 0.0f), + std::max(y - roomBottomRight.y + ERROR_TILE, 0.0f)); + floorSprite.Render(draw); + x += ERROR_TILE; + if (roomBottomRight.x - EDGE_EPSILON < x) + { + x = roomTopLeft.x; + y += ERROR_TILE; + } + } + screen_shake_set(true); + } + else if (backdropId == BACKDROP_MEGA_SATAN) + { + screen_shake_set(false); + if (floorSprite.animState.is_finished(MEGA_SATAN_CLOSED_ANIMATION)) + { + color_offset_shader_select(); + Vector size = vector_make(MEGA_SATAN_BORDER + MEGA_SATAN_BORDER + (roomBottomRight.x - roomTopLeft.x), + (roomBottomRight.y - roomTopLeft.y) + MEGA_SATAN_BORDER + MEGA_SATAN_BORDER); + Vector source = vector_make((WALL_SIZE - MEGA_SATAN_BORDER) + MEGA_SATAN_FLOOR_X, + (WALL_SIZE - MEGA_SATAN_BORDER) + MEGA_SATAN_FLOOR_Y); + Vector position = vector_make(((renderOffset.x + WALL_SIZE) - MEGA_SATAN_BORDER) + MEGA_SATAN_FLOOR_X, + ((renderOffset.y + WALL_SIZE) - MEGA_SATAN_BORDER) + MEGA_SATAN_FLOOR_Y); + apply_sprite_shader_params(COLOR_DEFAULT, SPRITE_SHADER_COLOR_APPLY, *floorBuffer); + floorBuffer->Render(KAGE::Graphics::source_quad_rect(source, size), + KAGE::Graphics::color_quad_rect(position, size, WHITE), WHITE); + } + else + floorSprite.Render({.position = vector_make(renderOffset.x + roomTopLeft.x + MEGA_SATAN_FLOOR_X, + renderOffset.y + roomTopLeft.y + MEGA_SATAN_FLOOR_Y)}); + screen_shake_set(true); + } + else if (backdropId == BACKDROP_PLANETARIUM) + { + screen_shake_set(false); + floorSprite.Render({.position = renderOffset}); + screen_shake_set(true); + } + else + { + color_offset_shader_select(); + Vector size = + vector_make((roomBottomRight.x - roomTopLeft.x) + 0, (roomBottomRight.y - roomTopLeft.y) + GRID_SIZE); + Vector position = vector_make(renderOffset.x + WALL_SIZE, renderOffset.y + WALL_SIZE); + apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *floorBuffer); + floorBuffer->Render(KAGE::Graphics::source_quad_rect(vector_make(WALL_SIZE, WALL_SIZE), size), + KAGE::Graphics::color_quad_rect(position, size, WHITE), WHITE); + } + + graphics.blendMode = savedBlend; + graphics.shader_default_set(); +} + +// 0093f000 Draws the second floor surface over the floor, blended, in the room's floor color. +void Backdrop::render_floor_surface(Vector renderOffset, ColorMod color) +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + KAGE::Graphics::BlendMode savedBlend = graphics.blendMode; + + graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); + color_offset_shader_select(); + Vector size = vector_make((roomBottomRight.x - roomTopLeft.x) + 0, (roomBottomRight.y - roomTopLeft.y) + GRID_SIZE); + SourceQuad source = source_edges(WALL_SIZE, WALL_SIZE, size.x + WALL_SIZE, size.y + WALL_SIZE, FLIP_NONE); + Vector position = vector_make(renderOffset.x + WALL_SIZE, renderOffset.y + WALL_SIZE); + apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *floorSurface2); + floorSurface2->Render(source, KAGE::Graphics::color_quad_rect(position, size, WHITE), WHITE); + + graphics.blendMode = savedBlend; + graphics.shader_default_set(); +} + +// A rectangle of the wall surface, each side in halves of the floor's size plus pixels. +struct SurfaceRect +{ + float xHalves; + float x; + float yHalves; + float y; + float widthHalves; + float width; + float heightHalves; + float height; +}; + +// The wall surface a room shows: the left and right walls (with their corners) and the top and bottom walls between. +constexpr SurfaceRect WALL_LEFT = {0, 0, 0, 0, 0, WALL_SIZE, 2, 2 * WALL_SIZE}; +constexpr SurfaceRect WALL_RIGHT = {2, WALL_SIZE, 0, 0, 0, WALL_SIZE, 2, 2 * WALL_SIZE}; +constexpr SurfaceRect WALL_TOP = {0, WALL_SIZE, 0, 0, 2, 0, 0, WALL_SIZE}; +constexpr SurfaceRect WALL_BOTTOM = {0, WALL_SIZE, 2, WALL_SIZE, 2, 0, 0, WALL_SIZE}; +constexpr SurfaceRect ROOM_WALLS[4] = {WALL_LEFT, WALL_RIGHT, WALL_TOP, WALL_BOTTOM}; + +// An L room's walls, by its missing quarter: the two outer walls it keeps whole, the outer walls cut short, and the +// two inner walls. +constexpr SurfaceRect L_ROOM_WALLS[4][6] = {{WALL_RIGHT, + WALL_BOTTOM, + {0, 0, 1, 0, 0, WALL_SIZE, 1, 2 * WALL_SIZE}, + {1, 0, 0, 0, 0, WALL_SIZE, 1, 2 * WALL_SIZE}, + {0, WALL_SIZE, 1, 0, 1, 0, 0, WALL_SIZE}, + {1, WALL_SIZE, 0, 0, 1, 0, 0, WALL_SIZE}}, + {WALL_LEFT, + WALL_BOTTOM, + {2, WALL_SIZE, 1, 0, 0, WALL_SIZE, 1, 2 * WALL_SIZE}, + {1, WALL_SIZE, 0, 0, 0, WALL_SIZE, 1, 2 * WALL_SIZE}, + {1, WALL_SIZE, 1, 0, 1, 0, 0, WALL_SIZE}, + {0, WALL_SIZE, 0, 0, 1, 0, 0, WALL_SIZE}}, + {WALL_RIGHT, + WALL_TOP, + {1, 0, 1, 0, 0, WALL_SIZE, 1, 2 * WALL_SIZE}, + {0, 0, 0, 0, 0, WALL_SIZE, 1, 2 * WALL_SIZE}, + {0, WALL_SIZE, 1, WALL_SIZE, 1, 0, 0, WALL_SIZE}, + {1, WALL_SIZE, 2, WALL_SIZE, 1, 0, 0, WALL_SIZE}}, + {WALL_LEFT, + WALL_TOP, + {1, WALL_SIZE, 1, 0, 0, WALL_SIZE, 1, 2 * WALL_SIZE}, + {2, WALL_SIZE, 0, 0, 0, WALL_SIZE, 1, 2 * WALL_SIZE}, + {0, WALL_SIZE, 2, WALL_SIZE, 1, 0, 0, WALL_SIZE}, + {1, WALL_SIZE, 1, WALL_SIZE, 1, 0, 0, WALL_SIZE}}}; + +// Copies a rectangle of the wall surface (moved in by an inset) to the same place on screen. +static void wall_surface_blit(KAGE::Graphics::ImageBase& surface, const SurfaceRect& rect, Vector half, Vector inset, + Vector offset) +{ + Vector position = vector_make(rect.xHalves * half.x + rect.x + inset.x, rect.yHalves * half.y + rect.y + inset.y); + Vector size = vector_make(rect.widthHalves * half.x + rect.width, rect.heightHalves * half.y + rect.height); + SourceQuad source = source_edges(position.x, position.y, position.x + size.x, position.y + size.y, FLIP_NONE); + + image_draw(surface, source, + KAGE::Graphics::color_quad_rect(vector_make(position.x + offset.x, position.y + offset.y), size, WHITE)); +} + +// 0093f1d0 Draws the walls: the water first, Mega Satan's borders, the Planetarium's sprite, the closets' and Dogma's +// sprite past its floor layer (and nothing more), then for backdrops with walls the black borders around the room and +// the wall surface's walls in the room's wall color, piece by piece around the floor. +void Backdrop::RenderWalls(Vector renderOffset, ColorMod color) +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + + if (waterGfx) RenderWater(renderOffset); + if (backdropId == BACKDROP_MEGA_SATAN) + { + Vector size = vector_make(MEGA_SATAN_BORDER + MEGA_SATAN_BORDER + (roomBottomRight.x - roomTopLeft.x), + (roomBottomRight.y - roomTopLeft.y) + MEGA_SATAN_BORDER + MEGA_SATAN_BORDER); + render_wall_borders(vector_make(((renderOffset.x + WALL_SIZE) - MEGA_SATAN_BORDER) + MEGA_SATAN_FLOOR_X, + ((renderOffset.y + WALL_SIZE) - MEGA_SATAN_BORDER) + MEGA_SATAN_FLOOR_Y), + size); + } + if (backdropId == BACKDROP_PLANETARIUM) + { + screen_shake_set(false); + floorSprite.Render({.position = renderOffset}); + screen_shake_set(true); + } + if (backdropId == BACKDROP_CLOSET || backdropId == BACKDROP_CLOSET_B || backdropId == BACKDROP_DOGMA) + { + screen_shake_set(false); + for (int layer = 1; layer < (int)floorSprite.layerStates.size(); layer++) + floorSprite.RenderLayer(layer, {.position = renderOffset}); + screen_shake_set(true); + return; + } + if (configs[backdropId].walls == 0) return; + + KAGE::Graphics::BlendMode savedBlend = graphics.blendMode; + graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); + Vector floorSize = vector_make(roomBottomRight.x - roomTopLeft.x, roomBottomRight.y - roomTopLeft.y); + int shape = g_game->room->GetRoomShape(); + render_wall_borders(renderOffset, + vector_make(WALL_SIZE + WALL_SIZE + floorSize.x, WALL_SIZE + WALL_SIZE + floorSize.y)); + color_offset_shader_select(); + apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *wallsBuffer); + + Vector inset{}; + if (is_horizontal_narrow(shape)) + { + inset.y = WALL_SIZE; + floorSize.y -= 2 * WALL_SIZE; + } + else if (is_vertical_narrow(shape)) + { + inset.x = 2 * WALL_SIZE; + floorSize.x -= 4 * WALL_SIZE; + } + Vector half = vector_make(floorSize.x * 0.5f, floorSize.y * 0.5f); + if (is_l_shape(shape)) + for (const SurfaceRect& rect : L_ROOM_WALLS[shape - ROOMSHAPE_LTL]) + wall_surface_blit(*wallsBuffer, rect, half, inset, renderOffset); + else + for (const SurfaceRect& rect : ROOM_WALLS) wall_surface_blit(*wallsBuffer, rect, half, inset, renderOffset); + + graphics.blendMode = savedBlend; + graphics.shader_default_set(); +} + +// 0093e770 Blacks out the screen around the room (the walls' outer edge moved in for narrow rooms), and the corner an +// L room lacks. +void Backdrop::render_wall_borders(Vector roomTopLeftPos, Vector roomSize) +{ + float left = roomTopLeftPos.x; + float top = roomTopLeftPos.y; + float right = roomTopLeftPos.x + roomSize.x; + float bottom = roomTopLeftPos.y + roomSize.y; + std::array borders = {quad_edges(0, 0, left, g_screenHeight), quad_edges(left, 0, right, top), + quad_edges(right, 0, g_screenWidth, g_screenHeight), + quad_edges(left, bottom, right, g_screenHeight)}; + int shape = g_game->room->GetRoomShape(); + + if (is_horizontal_narrow(shape)) + { + borders[1]._bottomLeft.y += NARROW_BORDER_Y; + borders[1]._bottomRight.y += NARROW_BORDER_Y; + borders[3]._topLeft.y -= NARROW_BORDER_Y; + borders[3]._topRight.y -= NARROW_BORDER_Y; + } + else if (is_vertical_narrow(shape)) + { + borders[0]._topRight.x += NARROW_BORDER_X; + borders[0]._bottomRight.x += NARROW_BORDER_X; + borders[2]._topLeft.x -= NARROW_BORDER_X; + borders[2]._bottomLeft.x -= NARROW_BORDER_X; + } + for (const DestinationQuad& border : borders) + render_color_shader_pass(KAGE::Graphics::ColorQuad(border, BORDER_COLOR)); + if (!is_l_shape(shape)) return; + + int missing = shape - ROOMSHAPE_LTL; + Vector corner = roomTopLeftPos; + if (missing & FLIP_X) corner.x = roomSize.x * 0.5f + roomTopLeftPos.x + GRID_SIZE; + if (missing & FLIP_Y) corner.y = roomSize.y * 0.5f + roomTopLeftPos.y + GRID_SIZE; + render_color_shader_pass( + KAGE::Graphics::color_quad_rect(corner, vector_make(L_BORDER_WIDTH, L_BORDER_HEIGHT), BORDER_COLOR)); +} + +// A length along the room for the water under the walls: pixels plus a number of room widths and heights (in cells of +// 26 pixels). +struct WaterLength +{ + float pixels; + int widths; + int heights; +}; + +// How a strip of water maps the water sheet: running down a side wall (mirrored on the right), or along the top or +// bottom wall (the sheet turned, mirrored along the bottom). +enum WaterMapping +{ + WATER_DOWN, + WATER_DOWN_MIRRORED, + WATER_ALONG, + WATER_ALONG_MIRRORED +}; + +// A strip of water: its mapping with the two ends of the sheet it shows, and its edges on the wall surface. +struct WaterStrip +{ + WaterMapping mapping; + WaterLength start; + WaterLength end; + WaterLength left; + WaterLength top; + WaterLength right; + WaterLength bottom; +}; + +constexpr WaterLength px(float pixels) +{ + return {pixels, 0, 0}; +} + +constexpr WaterLength wide(float pixels, int widths = 1) +{ + return {pixels, widths, 0}; +} + +constexpr WaterLength tall(float pixels) +{ + return {pixels, 0, 1}; +} + +// The strips under each shape's walls: down the side walls, then along the top and bottom walls, an L room's inner +// walls with the outer walls they meet. +constexpr WaterStrip WATER_ROOM[] = {{WATER_DOWN, px(0), tall(-52), px(0), px(52), px(52), tall(0)}, + {WATER_DOWN_MIRRORED, px(0), tall(-52), wide(0), px(52), wide(52), tall(0)}, + {WATER_ALONG, px(0), wide(52, -1), px(52), px(0), wide(0), px(52)}, + {WATER_ALONG_MIRRORED, px(0), wide(52, -1), px(52), tall(0), wide(0), tall(52)}}; +constexpr WaterStrip WATER_LTL[] = {{WATER_DOWN, px(0), px(182), px(338), px(52), px(390), px(182)}, + {WATER_DOWN, px(182), tall(-52), px(0), px(182), px(52), tall(0)}, + {WATER_DOWN_MIRRORED, px(0), tall(-52), wide(0), px(52), wide(52), tall(0)}, + {WATER_ALONG, px(0), px(-338), px(52), px(182), px(338), px(234)}, + {WATER_ALONG, px(-338), wide(52, -1), px(338), px(0), wide(0), px(52)}, + {WATER_ALONG_MIRRORED, px(0), wide(52, -1), px(52), tall(0), wide(0), tall(52)}}; +constexpr WaterStrip WATER_LTR[] = {{WATER_DOWN, px(0), tall(-52), px(0), px(52), px(52), tall(0)}, + {WATER_DOWN_MIRRORED, px(0), px(182), wide(-338), px(52), wide(-286), px(182)}, + {WATER_DOWN_MIRRORED, px(182), tall(-52), wide(0), px(182), wide(52), tall(0)}, + {WATER_ALONG, px(0), px(-390), px(52), px(0), px(390), px(52)}, + {WATER_ALONG, px(15), wide(52, -1), px(390), px(182), wide(0), px(234)}, + {WATER_ALONG_MIRRORED, px(0), wide(52, -1), px(52), tall(0), wide(0), tall(52)}}; +constexpr WaterStrip WATER_LBL[] = {{WATER_DOWN, px(0), px(234), px(0), px(52), px(52), px(234)}, + {WATER_DOWN, px(234), tall(-52), px(338), px(234), px(390), tall(0)}, + {WATER_DOWN_MIRRORED, px(0), tall(-52), wide(0), px(52), wide(52), tall(0)}, + {WATER_ALONG, px(0), wide(52, -1), px(52), px(0), wide(0), px(52)}, + {WATER_ALONG_MIRRORED, px(0), px(-338), px(52), tall(-182), px(338), tall(-130)}, + {WATER_ALONG_MIRRORED, px(13), wide(52, -1), px(338), tall(0), wide(0), tall(52)}}; +constexpr WaterStrip WATER_LBR[] = { + {WATER_DOWN, px(0), tall(-52), px(0), px(52), px(52), tall(0)}, + {WATER_DOWN_MIRRORED, px(0), px(234), wide(0), px(52), wide(52), px(234)}, + {WATER_DOWN_MIRRORED, px(234), tall(-52), wide(-338), px(234), wide(-286), tall(0)}, + {WATER_ALONG, px(0), wide(52, -1), px(52), px(0), wide(0), px(52)}, + {WATER_ALONG_MIRRORED, px(0), px(-390), px(52), tall(0), px(390), tall(52)}, + {WATER_ALONG_MIRRORED, px(15), wide(52, -1), px(390), tall(-182), wide(0), tall(-130)}}; +constexpr WaterStrip WATER_IH[] = {{WATER_DOWN, px(0), px(78), px(0), px(104), px(52), px(182)}, + {WATER_DOWN_MIRRORED, px(0), px(78), wide(0), px(104), wide(52), px(182)}, + {WATER_ALONG, px(0), wide(52, -1), px(52), px(52), wide(0), px(104)}, + {WATER_ALONG_MIRRORED, px(0), wide(52, -1), px(52), tall(-52), wide(0), tall(0)}}; +constexpr WaterStrip WATER_IV[] = {{WATER_DOWN, px(0), tall(-52), px(104), px(52), px(156), tall(0)}, + {WATER_DOWN_MIRRORED, px(0), tall(-52), wide(-104), px(52), wide(-52), tall(0)}, + {WATER_ALONG, px(0), px(-130), px(156), px(0), wide(-104), px(52)}, + {WATER_ALONG_MIRRORED, px(0), px(-130), px(156), tall(0), wide(-104), tall(52)}}; + +// The water scrolls half a pixel a frame and draws behind the walls' depth. +constexpr float WATER_SCROLL = 0.5f; +constexpr float WATER_DEPTH_STEP = 0.04f; +constexpr int WATER_DEPTH_STEPS = 4; + +// The strips of water under a shape's walls. +static std::span water_strips_get(int shape) +{ + switch (shape) + { + case ROOMSHAPE_LTL: return WATER_LTL; + case ROOMSHAPE_LTR: return WATER_LTR; + case ROOMSHAPE_LBL: return WATER_LBL; + case ROOMSHAPE_LBR: return WATER_LBR; + case ROOMSHAPE_IH: + case ROOMSHAPE_IIH: return WATER_IH; + case ROOMSHAPE_IV: + case ROOMSHAPE_IIV: return WATER_IV; + default: return WATER_ROOM; + } +} + +// 00940d30 (009426b0) Draws the water under the walls, opaque: strips of the water sheet down the side walls and along +// the top and bottom walls, scrolling with the frames (backward for a reversed sheet), each pushed behind the walls. +void Backdrop::RenderWater(Vector renderOffset) +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + KAGE::Graphics::BlendMode savedBlend = graphics.blendMode; + Room& room = *g_game->room; + float scroll = (float)g_game->frameCount * WATER_SCROLL; + if (configs[backdropId].isReverseWaterGfx) scroll *= -1; + + float left = -scroll; + float right = WALL_SIZE - scroll; + auto length = [&](const WaterLength& value) { + return value.pixels + (float)(value.widths * room.gridWidth) * GRID_SIZE + + (float)(value.heights * room.gridHeight) * GRID_SIZE; + }; + + graphics.blend_set(KAGE::Graphics::BLEND_OPAQUE); + for (const WaterStrip& strip : water_strips_get(room.GetRoomShape())) + { + float start = length(strip.start); + float end = length(strip.end); + bool isMirrored = strip.mapping == WATER_DOWN_MIRRORED || strip.mapping == WATER_ALONG_MIRRORED; + float near = isMirrored ? right : left; + float far = isMirrored ? left : right; + SourceQuad source; + if (strip.mapping == WATER_DOWN || strip.mapping == WATER_DOWN_MIRRORED) + static_cast(source) = quad_edges(near, start, far, end); + else + { + source._topLeft = vector_make(near, start); + source._topRight = vector_make(near, end); + source._bottomLeft = vector_make(far, start); + source._bottomRight = vector_make(far, end); + } + source._coordinateSpace = KAGE::Graphics::COORDINATES_PIXEL; + + float* vertices = + image_draw(*waterGfx, source, + quad_edges(renderOffset.x + length(strip.left), renderOffset.y + length(strip.top), + renderOffset.x + length(strip.right), renderOffset.y + length(strip.bottom))); + if (!vertices) continue; + + size_t stride = graphics.currentShader->vertex_size_get() / sizeof(float); + for (int corner = 0; corner < KAGE::Graphics::QUAD_CORNERS; corner++) + for (int step = 0; step < WATER_DEPTH_STEPS; step++) vertices[corner * stride + 2] += WATER_DEPTH_STEP; + } + graphics.blendMode = savedBlend; } -void Backdrop::RenderWalls(Vector, ColorMod) { reconstruction_missing("Backdrop::RenderWalls 0093f1d0"); } -void Backdrop::RenderWater(Vector) { reconstruction_missing("Backdrop::RenderWater 00940d30"); } diff --git a/src/backdrop.h b/src/backdrop.h index cbe1710..0ebdfac 100644 --- a/src/backdrop.h +++ b/src/backdrop.h @@ -6,10 +6,30 @@ #include #include #include +#include // backdrops.xml fills ids 1 to 62. Id 0 is the default the others start from. constexpr int BACKDROP_COUNT = 63; +// How a piece of a backdrop sheet is mirrored as it is drawn, by bit. +enum Flip +{ + FLIP_NONE, + FLIP_X, + FLIP_Y, + FLIP_XY +}; + +// Which walls a wall detail sprite shows its layers on, by bit: the layers named h... on the top and bottom walls, the +// layers named v... on the side walls. +enum WallSides +{ + WALL_SIDES_NONE, + WALL_SIDES_HORIZONTAL, + WALL_SIDES_VERTICAL, + WALL_SIDES_ALL +}; + // Construction, copies, assignment and destruction (00931de0, 00934600, 00934430, 009324f0) are the defaults. // A room background of backdrops.xml: its wall and floor sheet and how many walls and floors it cuts into, the floor // overlays, the water, and the grid graphics (rocks, pits, doors ...) rooms of it use. Paths are under resources/. @@ -37,6 +57,38 @@ struct BackdropConfig bool isReverseWaterGfx = false; }; +// A cell of wall drawn into the wall surface, for the effects its backdrop adds there: where it was drawn, its place on +// the sheet's block (slotX along the top wall, slotY down the side wall), the sheet's wall row and its variant. +struct WallSlot +{ + DestinationQuad quad{}; + int slotX = 0; + int slotY = 0; + int variant = 0; + int wallRow = 0; + Flip flip = FLIP_NONE; +}; + +// A corner of the room's walls a wall detail sprite is drawn at, and how likely each of its layers shows. +struct WallDetail +{ + Vector position{}; + float chance = 0; + Flip flip = FLIP_NONE; + WallSides sides = WALL_SIDES_NONE; +}; + +// One row of the start room's control icons, laid out from the left: each icon's button frame and position, the +// cursor the icons are drawn from, and the controller whose bindings they show. +struct ControlRow +{ + std::vector frames; + std::vector positions; + float cursorX = 0; + float x = 0; + int controllerIndex = 0; +}; + // Destruction (00932570) is the default. // A room's background (Room's backdrop): the configs of backdrops.xml, and the walls, floor and water of the // room's backdrop, drawn once into surfaces the room renders from. @@ -65,20 +117,25 @@ struct Backdrop bool LoadConfig(std::string_view path); void Init(uint32_t id, bool isLoadGraphics); uint32_t get_random_floor_variant(); - KAGE::Graphics::ColorQuad render_grid_rect(int x, int y, int width, int height); + DestinationQuad render_grid_rect(int x, int y, int width, int height); void load_details(); - void pre_render_walls(); - void PreRenderControls(); - void render_control_icon(); void render_ashpit_ash(); - void render_floor_to_target(); - void spawn_detail_effects(Vector offset, bool isFlipX, bool isFlipY); - void spawn_wall_details(); - void render_wall_detail(); - void render_wall_borders(Vector roomTopLeftPos, Vector roomSize); + void render_floor_to_target(uint32_t variant, const KAGE::Graphics::ImagePtr& sheet, + const KAGE::Graphics::ImagePtr& alternate); + void PreRenderControls(); + void render_control_icon(ControlRow& row, int action); + void pre_render_walls(); + void spawn_wall_details(const WallSlot& slot); + void render_wall_detail(const WallDetail& detail); + void RenderFloor(Vector renderOffset, ColorMod color); void render_floor_surface(Vector renderOffset, ColorMod color); void RenderWalls(Vector renderOffset, ColorMod color); + void render_wall_borders(Vector roomTopLeftPos, Vector roomSize); void RenderWater(Vector renderOffset); }; + +int controller_button_to_glyph_frame(int button); +Vector backdrop_detail_to_world_pos(Vector position); +Vector backdrop_wall_normal(int slotX, Flip flip); diff --git a/src/entity.cpp b/src/entity.cpp index fe88e95..d9ac440 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -1284,18 +1284,6 @@ void Entity::convert_shot_for_enemy_owner(Entity*) reconstruction_missing("Entity::convert_shot_for_enemy_owner 0064bb70"); } -// 006a9c90 -void Entity::CollideWithGrid(GridCollisionMode) -{ - reconstruction_missing("Entity::CollideWithGrid 006a9c90"); -} - -// 006ab240 -bool Entity::is_grid_collision_at(const Vector&) -{ - reconstruction_missing("Entity::is_grid_collision_at 006ab240"); -} - // 006ace60 bool Entity::TakeDamage(float, uint64_t, const EntityRef&, int) { @@ -1368,36 +1356,6 @@ void Entity::RemoveStatusEffects() reconstruction_missing("Entity::RemoveStatusEffects 006ae630"); } -// 006b2210 -float Entity::collision_mass_get(Entity*) -{ - reconstruction_missing("Entity::collision_mass_get 006b2210"); -} - -// 006b25b0 -void Entity::push_apart_capsule(Entity*) -{ - reconstruction_missing("Entity::push_apart_capsule 006b25b0"); -} - -// 006b2940 -bool Entity::push_apart_circle(Entity*) -{ - reconstruction_missing("Entity::push_apart_circle 006b2940"); -} - -// 006b2ee0 -void Entity::collide_with_entity(Entity*) -{ - reconstruction_missing("Entity::collide_with_entity 006b2ee0"); -} - -// 006b2f50 -bool Entity::ForceCollide(Entity*, Entity*, bool) -{ - reconstruction_missing("Entity::ForceCollide 006b2f50"); -} - // 006b45c0 void Entity::BloodExplode() { diff --git a/src/entity.h b/src/entity.h index 9ceb872..1d1c06e 100644 --- a/src/entity.h +++ b/src/entity.h @@ -58,7 +58,7 @@ enum EntityType : int // The types an enemy can have, both ends included. constexpr int ENTITY_FIRST_ENEMY = 10; -constexpr int ENTITY_LAST_ENEMY = 997; +constexpr int ENTITY_LAST_ENEMY = 999; // Lua's EntityFlag: the state and status effects an entity carries. enum EntityFlag : uint64_t diff --git a/src/entity_collision.cpp b/src/entity_collision.cpp index 68f7805..271bcec 100644 --- a/src/entity_collision.cpp +++ b/src/entity_collision.cpp @@ -1,8 +1,13 @@ +#include "entity_collision.h" #include "entity_player.h" +#include "entity_projectile.h" #include "game.h" #include "grid_entity_door.h" #include "log.h" +#include "manager.h" #include "room.h" +#include +#include #include // What crushes rocks on contact: The Nail, Leo (worn or rolled by Zodiac), Thunder Thighs, Stompy and Mega Mush. @@ -10,6 +15,8 @@ constexpr int COLLECTIBLE_THE_NAIL = 83; constexpr int COLLECTIBLE_LEO = 302; constexpr int COLLECTIBLE_THUNDER_THIGHS = 314; constexpr int PLAYERFORM_STOMPY = 13; +// A transformation counts once the player holds this many of its items. +constexpr int PLAYER_FORM_ITEMS = 3; // A poop's reach for a player's collision: a giga poop's quarter from its shared center, any other from its cell's. constexpr int POOP_GIGA_FIRST = 7; @@ -22,37 +29,163 @@ constexpr std::array POOP_GIGA_CENTER_X = {POOP_GIGA_QUARTER, -POOP_GI constexpr std::array POOP_GIGA_CENTER_Y = {POOP_GIGA_QUARTER, POOP_GIGA_QUARTER, -POOP_GIGA_QUARTER, -POOP_GIGA_QUARTER}; -// The grid collision a player passes, through the Lost's mirror door or past a wall it is pushed out of. -constexpr uint32_t GRID_COLLISION_WALL_EXCEPT_PLAYER = 5; +// The Lost passes the mirror door in the mirror world. constexpr int MIRROR_DIMENSION = 1; // The Beast's dungeon keeps players this far above its floor's center line. constexpr float BEAST_DUNGEON_OFFSET_Y = 20; -// A wall hit keeps this much of the speed into it, and pushes back this much more. +// A player's wall hit keeps this much of the speed into it, any other entity's turns it back this much, and both +// push back a little more. Entities then lose up to half their speed against the wall. constexpr float WALL_BOUNCE = 0.9f; +constexpr float WALL_REBOUND = 1.8f; constexpr float WALL_PUSH = 0.1f; +constexpr float WALL_FRICTION = 0.5f; constexpr float NORMAL_EPSILON = 0.001f; constexpr float PUSH_OUT_MIN_SPEED = 2; constexpr int PUSH_OUT_STEPS_GROUND = 12; constexpr int PUSH_OUT_STEPS = 6; +constexpr float HALF_CELL = GRID_CELL_SIZE / 2; + +// The enemies that bounce harder off walls, with the sounds some make. +constexpr int ENTITY_GURDY_JR = 99; +constexpr int ENTITY_DIP = 217; +constexpr int ENTITY_SQUIRT = 220; +constexpr int ENTITY_BALL_AND_CHAIN = 893; +constexpr int ENTITY_SINGE = 915; +constexpr int SINGE_BALL = 1; +constexpr float REBOUND_GURDY_JR = 1.4f; +constexpr float REBOUND_BOUNCER = 1.2f; +constexpr int SOUND_DEATH_BURST_LARGE = 28; +constexpr int SOUND_STONE_IMPACT = 487; +constexpr int SOUND_BALL_AND_CHAIN_HIT = 581; +constexpr float BOUNCE_VOLUME_SCALE = 0.05f; +constexpr float BOUNCE_VOLUME_BASE = 0.2f; +constexpr float BOUNCE_VOLUME_MAX = 1.2f; +constexpr float BOUNCE_PITCH_BASE = 0.9f; +constexpr float BOUNCE_PITCH_SPREAD = 0.2f; +constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; + +// Samson's Chains' ball breaks rocks it hits faster than this. +constexpr int FAMILIAR_SAMSONS_CHAINS = 75; +constexpr float CHAINS_CRUSH_SPEED_SQUARED = 25; + +// Mega Satan's room lets shots leave through its walls. +constexpr int BOSS_MEGA_SATAN = 55; // The room types whose doors Notched Axe hacks open. constexpr int ROOM_TYPE_SECRET = 7; constexpr int ROOM_TYPE_SUPERSECRET = 8; -// A world position's cell index in the room, or -1 off its grid. -static int grid_index_at(Room& room, Vector position) +// What weighs an entity down as it collides: a magnet against enemies, Mega Mush and the Cube Baby for a player, +// enemies that shots barely move, and what makes a player shrug off projectiles. +constexpr float MASS_HEAVY = 10; +constexpr float MASS_ANCHORED = 100; +constexpr float MASS_PROJECTILE_PROOF = 20; +constexpr int FAMILIAR_CUBE_BABY = 239; +constexpr int COLLECTIBLE_ISAACS_HEART = 276; +constexpr int NULL_TOOTH_AND_NAIL = 59; +// Charger, Boom Fly, Knight, Leech, Pin, Swarmer, Floating Knight, Bone Knight, Poop and Movable TNT. +constexpr std::array SHOT_ANCHORED_TYPES = {23, 25, 41, 55, 62, 91, 254, 283, 245, 292}; + +// Two entities closer than this are not pushed apart. A player or the Punching Bag is not pushed into a wall. +constexpr float PUSH_MIN_DISTANCE = 0.0001f; +constexpr int FAMILIAR_PUNCHING_BAG = 67; +constexpr float PLAYER_PUSH_SHARE = 0.5f; +constexpr float BEAST_PUSH_DAMPING = 0.25f; + +// One side of a push apart: the direction it moves along, the impulse its velocity takes, the overlap and its share. +struct EntityPush { - int column = (int)((position.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); - int row = (int)((position.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); - if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return -1; - return room.gridWidth * row + column; + Vector direction{}; + Vector impulse{}; + float overlap = 0; + float share = 0; +}; + +static float vector_length(Vector v) +{ + return std::sqrt(v.x * v.x + v.y * v.y); } -// The grid entity on a cell, or none past the grid. -static GridEntity* grid_entity_at(Room& room, int gridIndex) +// A vector scaled to length one, or as it is with no length (Vector::Normalized). +static Vector vector_normalized(Vector v) { - return gridIndex >= 0 && gridIndex < ROOM_GRID_CELLS ? room.gridEntities[gridIndex] : nullptr; + float length = vector_length(v); + if (length > 0) return vector_make(v.x * (1 / length), v.y * (1 / length)); + return v; +} + +static bool is_unit_size(const Entity& entity) +{ + return entity.sizeMulti.x == 1 && entity.sizeMulti.y == 1; +} + +static bool is_wall(uint32_t collision) +{ + return collision == COLLISION_WALL || collision == COLLISION_WALL_EXCEPT_PLAYER; +} + +static bool is_singe_ball(const Entity& entity) +{ + return entity.type == ENTITY_SINGE && entity.variant == SINGE_BALL; +} + +// Plays a sound through the fart seeds. +static void sound_play(int sound, float volume, float pitch) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = volume, .pitch = pitch}); +} + +// The knock of a heavy ball, louder the faster it goes, at a slightly random pitch. +static void bounce_sound_play(int sound, float speed) +{ + float pitch = (float)Random() * RANDOM_UNIT_SCALE * BOUNCE_PITCH_SPREAD + BOUNCE_PITCH_BASE; + sound_play(sound, std::min(speed * BOUNCE_VOLUME_SCALE + BOUNCE_VOLUME_BASE, BOUNCE_VOLUME_MAX), pitch); +} + +// Moves an entity back along a wall's normal out of what blocks it, bisecting for steps tries between its depth into +// the wall and that depth less its speed (at least two). +template +static void grid_push_out(Entity& entity, Vector normal, int steps, IsFreeAt isFreeAt) +{ + float depth = std::sqrt(normal.y * entity.sizeMulti.y * (normal.y * entity.sizeMulti.y) + + normal.x * entity.sizeMulti.x * (normal.x * entity.sizeMulti.x)) * + entity.size; + float freeDepth = depth - std::max(vector_length(entity.velocity), PUSH_OUT_MIN_SPEED); + float blockedDepth = depth; + for (int step = 0; step < steps; step++) + { + float middle = (blockedDepth - freeDepth) * 0.5f + freeDepth; + Vector at = vector_make(normal.x * middle + entity.pos.x, normal.y * middle + entity.pos.y); + (isFreeAt(at) ? freeDepth : blockedDepth) = middle; + } + entity.pos.x += normal.x * (freeDepth - depth); + entity.pos.y += normal.y * (freeDepth - depth); +} + +// A crushed rock bridges the pit beyond it, on the axis its crusher came along. +static void crush_bridge(Room& room, Entity& crusher, GridEntity& rock) +{ + Vector center = room.GetGridPosition(rock.gridIndex); + float dx = center.x - crusher.pos.x; + float dy = center.y - crusher.pos.y; + float directionX = 0; + float directionY = 0; + if (std::abs(dx) > std::abs(dy)) directionX = dx < 0 ? -1 : 1; + else directionY = dy < 0 ? -1 : 1; + + int beyond = room.GetGridIndex( + vector_make(center.x + directionX * GRID_CELL_SIZE, center.y + directionY * GRID_CELL_SIZE)); + GridEntity* pit = room.GetGridEntity(beyond); + if (pit && pit->type == GRID_PIT) reconstruction_missing("Room::TryMakeBridge 0081e6e0"); +} + +// 007aa7c0 Whether the player has a transformation: three items of its set, out of the cursed mist and alive. +bool Entity_Player::HasPlayerForm(int playerForm) +{ + if (hasCurseMistEffect || isCoopGhost || playerForm < 0 || playerForm >= PLAYER_FORM_SLOTS) return false; + return playerForms[playerForm] >= PLAYER_FORM_ITEMS; } // 006b5fd0 The grid collision a player meets at a position: a poop only within its reach, the Lost's way through a @@ -60,9 +193,9 @@ static GridEntity* grid_entity_at(Room& room, int gridIndex) uint32_t Entity_Player::get_grid_collision_at(Vector position) { Room& room = *g_game->room; - int gridIndex = grid_index_at(room, position); + int gridIndex = room.GetGridIndex(position); uint32_t collision = room.GetGridCollision(gridIndex); - GridEntity* grid = grid_entity_at(room, gridIndex); + GridEntity* grid = room.GetGridEntity(gridIndex); if (collision == COLLISION_SOLID && grid && grid->type == GRID_POOP) { bool isGiga = grid->variant >= POOP_GIGA_FIRST && grid->variant <= POOP_GIGA_LAST; @@ -85,9 +218,9 @@ uint32_t Entity_Player::get_grid_collision_at(Vector position) if (!(door.doorFlags & DOOR_FLAG_MIRROR) || door.state == DOOR_STATE_OPEN) return COLLISION_WALL; bool isSpirit = GetHealthType() == HEALTH_NO_HEALTH || HasInstantDeathCurse(); if (!isSpirit && g_game->currentDimensionIdx != MIRROR_DIMENSION) return COLLISION_WALL; - collision = GRID_COLLISION_WALL_EXCEPT_PLAYER; + collision = COLLISION_WALL_EXCEPT_PLAYER; } - else if (collision != GRID_COLLISION_WALL_EXCEPT_PLAYER) return collision; + else if (collision != COLLISION_WALL_EXCEPT_PLAYER) return collision; // The original reads a non-player's fields here. A non-player meets the wall. if (type != ENTITY_PLAYER || variant != 0 || isCoopGhost || parent || IsHologram()) return COLLISION_WALL; @@ -127,24 +260,6 @@ static void mega_mush_crush(Room& room, Entity& player, GridEntity& grid, int gr if (room.gridEntities[gridIndex]) room.gridEntities[gridIndex]->Destroy(false, EntityRef(&player)); } -// A crushed rock bridges the pit beyond it, on the axis the player came along. -static void crush_bridge(Room& room, Entity& player, GridEntity& rock) -{ - Vector center = room.GetGridPosition(rock.gridIndex); - float dx = center.x - player.pos.x; - float dy = center.y - player.pos.y; - float directionX = 0; - float directionY = 0; - if (std::abs(dx) > std::abs(dy)) directionX = dx < 0 ? -1 : 1; - else directionY = dy < 0 ? -1 : 1; - - int beyond = grid_index_at( - room, vector_make(center.x + directionX * GRID_CELL_SIZE, center.y + directionY * GRID_CELL_SIZE)); - if (beyond < 0) return; - GridEntity* pit = grid_entity_at(room, beyond); - if (pit && pit->type == GRID_PIT) reconstruction_missing("Room::TryMakeBridge 0081e6e0"); -} - // What a player does to the grid entity at one of its collision points: Mega Mush stomps blocks and kicks doors and // webs, rock crushers break what they touch, Notched Axe opens secret doors. Returns whether the point is spent on it. static bool player_grid_act(Room& room, Entity_Player& player, GridEntity* grid, int gridIndex, uint32_t collision) @@ -182,7 +297,7 @@ static bool player_grid_act(Room& room, Entity_Player& player, GridEntity* grid, bool isSecret = door.currentRoomType == ROOM_TYPE_SECRET || door.targetRoomType == ROOM_TYPE_SECRET || door.currentRoomType == ROOM_TYPE_SUPERSECRET || door.targetRoomType == ROOM_TYPE_SUPERSECRET; if (!isSecret) return false; - if (GridEntity* target = grid_entity_at(room, gridIndex)) target->Destroy(false, EntityRef(&player)); + if (GridEntity* target = room.GetGridEntity(gridIndex)) target->Destroy(false, EntityRef(&player)); return true; } @@ -232,14 +347,14 @@ void Entity::PlayerCollideWithGrid(GridCollisionMode mode) for (const Vector& point : collisionPoints) { Vector position = vector_make(pos.x + point.x, pos.y + point.y); - int gridIndex = grid_index_at(room, position); + int gridIndex = room.GetGridIndex(position); if (gridIndex < 0) continue; - GridEntity* grid = grid_entity_at(room, gridIndex); + GridEntity* grid = room.GetGridEntity(gridIndex); uint32_t collision = player->get_grid_collision_at(position); if (!isSimulated && player_grid_act(room, *player, grid, gridIndex, collision)) continue; bool isWall = collision == COLLISION_WALL || (collision == COLLISION_SOLID && grid && grid->type == GRID_DOOR); - bool isBlocked = collision != COLLISION_NONE && collision != GRID_COLLISION_WALL_EXCEPT_PLAYER; + bool isBlocked = collision != COLLISION_NONE && collision != COLLISION_WALL_EXCEPT_PLAYER; if ((entityGridCollisionClass == GRIDCOLL_WALLS && isWall) || (entityGridCollisionClass == GRIDCOLL_GROUND && isBlocked)) { @@ -248,18 +363,12 @@ void Entity::PlayerCollideWithGrid(GridCollisionMode mode) } } - float lengthSquared = normal.x * normal.x + normal.y * normal.y; - if (lengthSquared < NORMAL_EPSILON) + if (normal.x * normal.x + normal.y * normal.y < NORMAL_EPSILON) { if (!isSimulated) gridCollisionNormal = {}; return; } - float length = std::sqrt(lengthSquared); - if (length > 0) - { - normal.x *= 1 / length; - normal.y *= 1 / length; - } + normal = vector_normalized(normal); if (!isSimulated) gridCollisionNormal = normal; float approach = -normal.x * velocity.x - normal.y * velocity.y; @@ -272,22 +381,429 @@ void Entity::PlayerCollideWithGrid(GridCollisionMode mode) velocity.y += push * gridCollisionNormal.y; } - float depth = std::sqrt(normal.y * sizeMulti.y * (normal.y * sizeMulti.y) + - normal.x * sizeMulti.x * (normal.x * sizeMulti.x)) * - size; - float speed = std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y); - float freeDepth = depth - std::max(speed, PUSH_OUT_MIN_SPEED); - float blockedDepth = depth; bool isGround = entityGridCollisionClass == GRIDCOLL_GROUND; - for (int step = 0; step < (isGround ? PUSH_OUT_STEPS_GROUND : PUSH_OUT_STEPS); step++) - { - float middle = (blockedDepth - freeDepth) * 0.5f + freeDepth; - uint32_t collision = - player->get_grid_collision_at(vector_make(normal.x * middle + pos.x, normal.y * middle + pos.y)); - bool isFree = isGround ? collision == COLLISION_NONE || collision == GRID_COLLISION_WALL_EXCEPT_PLAYER - : collision != COLLISION_WALL; - (isFree ? freeDepth : blockedDepth) = middle; - } - pos.x += normal.x * (freeDepth - depth); - pos.y += normal.y * (freeDepth - depth); + grid_push_out(*this, normal, isGround ? PUSH_OUT_STEPS_GROUND : PUSH_OUT_STEPS, + [player, isGround](Vector at) + { + uint32_t collision = player->get_grid_collision_at(at); + return isGround ? collision == COLLISION_NONE || collision == COLLISION_WALL_EXCEPT_PLAYER + : collision != COLLISION_WALL; + }); +} + +// Clamps a wall-bound entity into the room along its one axis, noting the hit with a normal back into the room. +static void axis_clamp(Entity& entity, Vector clamped, bool isAxisX, bool isSimulated) +{ + float& coordinate = isAxisX ? entity.pos.x : entity.pos.y; + float target = isAxisX ? clamped.x : clamped.y; + if (!isSimulated && coordinate != target) + { + entity.isCollidesWithGrid = true; + entity.gridCollisionVelocity = entity.velocity; + float direction = coordinate <= target ? 1.0f : -1.0f; + entity.gridCollisionNormal = isAxisX ? vector_make(direction, 0) : vector_make(0, direction); + } + coordinate = target; +} + +// Clamps an entity into the room. Applied, the hit is noted, and the returned normal points out of the room along +// each axis it was clamped on. +static Vector room_clamp(Entity& entity, Vector clamped, bool isSimulated) +{ + Vector normal{}; + if (!isSimulated && (entity.pos.x != clamped.x || entity.pos.y != clamped.y)) + { + entity.isCollidesWithGrid = true; + entity.gridCollisionVelocity = entity.velocity; + if (entity.pos.x != clamped.x) normal.x = entity.pos.x <= clamped.x ? -1 : 1; + if (entity.pos.y != clamped.y) normal.y = entity.pos.y <= clamped.y ? -1 : 1; + } + entity.pos = clamped; + return normal; +} + +// A shot only notes where it stands in what stops it: a wall it does not fly back from (Mega Satan's room and rooms +// without walls let it leave), a rock or other solid, and for a tear an object too. Pits stop nothing. +static void shot_grid_collide(Entity& shot, Room& room) +{ + bool isOpen = room.bossId == BOSS_MEGA_SATAN || + (room.descriptor && (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_NO_WALLS)); + int gridIndex = room.GetGridIndex(shot.pos); + uint32_t collision = room.GetGridCollision(gridIndex); + if (is_wall(collision)) + { + Vector clamped = room.GetClampedPositionImpl(shot.pos, 0, 0, 0, 0); + bool isOutside = clamped.x != shot.pos.x || clamped.y != shot.pos.y; + float inward = (clamped.y - shot.pos.y) * shot.velocity.y + (clamped.x - shot.pos.x) * shot.velocity.x; + if (isOutside && (isOpen || inward >= 0)) return; + } + else if (collision != COLLISION_SOLID && (shot.type != ENTITY_TEAR || collision != COLLISION_OBJECT)) return; + + GridEntity* grid = room.GetGridEntity(gridIndex); + if (!grid || grid->type == GRID_PIT) return; + shot.isCollidesWithGrid = true; + shot.gridCollisionVelocity = shot.velocity; +} + +// Whether a cell blocks an entity of a grid collision class: anything for ground, all but pits for pits only, what +// stands for no pits, and walls outside crawlspaces for walls. +static bool is_cell_blocked(int gridClass, uint32_t collision, GridEntity* grid) +{ + switch (gridClass) + { + case GRIDCOLL_GROUND: return collision != COLLISION_NONE; + case GRIDCOLL_PITSONLY: return collision != COLLISION_PIT; + case GRIDCOLL_NOPITS: + return collision != COLLISION_NONE && collision != COLLISION_PIT && (!grid || grid->type != GRID_PIT); + default: return is_wall(collision) && g_game->room->roomType != ROOM_DUNGEON; + } +} + +// Whether the push out of a wall stops at a cell for a grid collision class. +static bool is_cell_free(int gridClass, uint32_t collision) +{ + switch (gridClass) + { + case GRIDCOLL_GROUND: return collision == COLLISION_NONE; + case GRIDCOLL_PITSONLY: return collision == COLLISION_PIT; + case GRIDCOLL_NOPITS: return collision == COLLISION_NONE || collision == COLLISION_PIT; + default: return !is_wall(collision); + } +} + +// Samson's Chains' ball breaks a rock it hits fast enough, bridging the pit beyond. Whether it broke one. +static bool chains_crush(Entity& ball, Room& room, GridEntity& grid) +{ + float speedSquared = ball.velocity.x * ball.velocity.x + ball.velocity.y * ball.velocity.y; + if (speedSquared <= CHAINS_CRUSH_SPEED_SQUARED || grid.collisionClass != COLLISION_SOLID) return false; + if (!grid.Destroy(false, EntityRef(&ball))) return false; + + crush_bridge(room, ball, grid); + return true; +} + +// The sum of the collision points in cells that block the entity. Samson's Chains' ball that meets a rock without +// breaking it starts the sum over. +static Vector blocked_points_sum(Entity& entity, Room& room, int gridClass, bool isSimulated) +{ + bool isChains = !isSimulated && entity.type == ENTITY_FAMILIAR && entity.variant == FAMILIAR_SAMSONS_CHAINS && + gridClass == GRIDCOLL_NOPITS; + Vector sum{}; + for (const Vector& point : entity.collisionPoints) + { + int gridIndex = room.GetGridIndex(vector_make(entity.pos.x + point.x, entity.pos.y + point.y)); + uint32_t collision = room.GetGridCollision(gridIndex); + GridEntity* grid = room.GetGridEntity(gridIndex); + if (is_cell_blocked(gridClass, collision, grid)) + { + sum.x += point.x; + sum.y += point.y; + } + + bool isHit = collision == COLLISION_SOLID || collision == COLLISION_OBJECT; + if (isChains && isHit && grid && !chains_crush(entity, room, *grid)) sum = {}; + } + return sum; +} + +// A tear whose collision points cancel out takes its normal from where it sits in its cell: back along the axis it is +// nearer the cell's edge on, when it reaches past one. +static Vector tear_cell_normal(Entity& tear, Room& room, Vector normal) +{ + Vector center = room.GetGridPosition(room.GetGridIndex(tear.pos)); + float halfWidth = tear.size * tear.sizeMulti.x; + float offsetX = tear.pos.x - center.x; + float offsetY = tear.pos.y - center.y; + if (std::abs(offsetX) + halfWidth >= HALF_CELL && std::abs(offsetY) + tear.size * tear.sizeMulti.y >= HALF_CELL) + return normal; + + if (std::abs(tear.sizeMulti.x * offsetX) > std::abs(tear.sizeMulti.y * offsetY)) + return vector_make(offsetX > 0 ? -halfWidth : halfWidth, 0); + float halfHeight = tear.sizeMulti.y * tear.size; + return vector_make(0, offsetY > 0 ? -halfHeight : halfHeight); +} + +// Turns an entity back from a wall it runs into, harder for Gurdy Jr., Dips, Squirts and the heavy balls, which +// knock. +static void wall_bounce(Entity& entity, float approach) +{ + entity.gridCollisionVelocity = entity.velocity; + entity.isCollidesWithGrid = true; + float push = approach * WALL_REBOUND - WALL_PUSH; + if (entity.type == ENTITY_GURDY_JR) + { + sound_play(SOUND_DEATH_BURST_LARGE, std::min(-approach * BOUNCE_VOLUME_SCALE, BOUNCE_VOLUME_MAX), 1); + push *= REBOUND_GURDY_JR; + } + else if (entity.type == ENTITY_DIP || entity.type == ENTITY_SQUIRT) push *= REBOUND_BOUNCER; + else if (is_singe_ball(entity) || entity.type == ENTITY_BALL_AND_CHAIN) + { + bool isChain = entity.type == ENTITY_BALL_AND_CHAIN; + bounce_sound_play(isChain ? SOUND_BALL_AND_CHAIN_HIT : SOUND_STONE_IMPACT, vector_length(entity.velocity)); + push *= REBOUND_BOUNCER; + } + entity.velocity.x += push * entity.gridCollisionNormal.x; + entity.velocity.y += push * entity.gridCollisionNormal.y; +} + +// 006a9c90 An entity's collision with the room's grid by its grid collision class: clamped into the room along one +// axis or both, a shot only noting what stops it, the rest pushed out along the normal of the cells their collision +// points are blocked in, bouncing off and slowed. Simulating (Interpolate's prediction) only moves the position. +// A projectile in a crawlspace flies over pits rather than stopping at walls only. +void Entity::CollideWithGrid(GridCollisionMode mode) +{ + bool isSimulated = mode == GRID_COLLISION_SIMULATE; + if (!isSimulated) isCollidesWithGrid = false; + if (minecart || entityGridCollisionClass == GRIDCOLL_NONE) return; + + Room& room = *g_game->room; + int gridClass = entityGridCollisionClass; + if (type == ENTITY_PROJECTILE && gridClass == GRIDCOLL_BULLET && room.roomType == ROOM_DUNGEON) + gridClass = GRIDCOLL_NOPITS; + + Vector clamped = room.GetClampedPositionImpl(pos, 0, 0, 0, 0); + if (gridClass == GRIDCOLL_WALLS_X || gridClass == GRIDCOLL_WALLS_Y) + return axis_clamp(*this, clamped, gridClass == GRIDCOLL_WALLS_X, isSimulated); + if (gridClass == GRIDCOLL_BULLET) + { + if (!isSimulated) shot_grid_collide(*this, room); + return; + } + + Vector clampNormal = room_clamp(*this, clamped, isSimulated); + if (collisionPoints.empty()) return; + Vector normal = blocked_points_sum(*this, room, gridClass, isSimulated); + if (normal.x == 0 && normal.y == 0) + { + if (!isSimulated) gridCollisionNormal = clampNormal; + return; + } + + bool isCancelled = normal.y * normal.y + normal.x * normal.x < NORMAL_EPSILON; + if (type == ENTITY_TEAR && isCancelled) normal = tear_cell_normal(*this, room, normal); + else if (IsEnemy() && gridClass == GRIDCOLL_GROUND && isCancelled) + reconstruction_missing("Room::FindFreeTilePosition 0081e520"); + normal = vector_normalized(normal); + if (!isSimulated) gridCollisionNormal = normal; + + float approach = -normal.x * velocity.x - velocity.y * normal.y; + if (approach >= 0) return; + if (!isSimulated) wall_bounce(*this, approach); + + float speed = vector_length(velocity); + int steps = gridClass == GRIDCOLL_GROUND ? PUSH_OUT_STEPS_GROUND : PUSH_OUT_STEPS; + auto isFreeAt = [&room, gridClass](Vector at) + { return is_cell_free(gridClass, room.GetGridCollision(room.GetGridIndex(at))); }; + if (speed > 0) grid_push_out(*this, normal, steps, isFreeAt); + if (isSimulated) return; + + float slowdown = 1 - (-approach / speed) * WALL_FRICTION; + velocity.y *= slowdown; + velocity.x *= slowdown; +} + +// 006ab240 Whether the entity's collision points, moved by an offset, meet walls (or a solid door) for a walls class, +// or anything but a players' wall for a ground class. +bool Entity::is_grid_collision_at(const Vector& offset) +{ + if (entityGridCollisionClass == GRIDCOLL_NONE) return false; + + Room& room = *g_game->room; + Vector sum{}; + for (const Vector& point : collisionPoints) + { + int gridIndex = room.GetGridIndex(vector_make(point.x + offset.x + pos.x, point.y + pos.y + offset.y)); + if (gridIndex < 0) continue; + + uint32_t collision = room.GetGridCollision(gridIndex); + GridEntity* grid = room.GetGridEntity(gridIndex); + bool isWall = collision == COLLISION_WALL || (collision == COLLISION_SOLID && grid && grid->type == GRID_DOOR); + bool isBlocked = collision != COLLISION_NONE && collision != COLLISION_WALL_EXCEPT_PLAYER; + if ((entityGridCollisionClass == GRIDCOLL_WALLS && isWall) || + (entityGridCollisionClass == GRIDCOLL_GROUND && isBlocked)) + { + sum.x += point.x; + sum.y += point.y; + } + } + return sum.x != 0 || sum.y != 0; +} + +// 006b2210 How much the entity weighs against another as they push apart: heavier when magnetized against enemies, +// as a player against the Cube Baby or under Mega Mush, as an enemy shots barely move, and as a player whom +// projectiles do not move (Isaac's Heart, Tooth and Nail, the Forgotten's soul). +float Entity::collision_mass_get(Entity* other) +{ + float weight = mass; + if (HasEntityFlags(FLAG_MAGNETIZED) && is_enemy_type(other->type)) weight *= MASS_HEAVY; + if (type == ENTITY_PLAYER) + { + if (other->type == ENTITY_FAMILIAR && other->variant == FAMILIAR_CUBE_BABY) weight *= MASS_HEAVY; + if (static_cast(this)->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH)) + weight *= MASS_HEAVY; + } + + bool isShot = other->type == ENTITY_TEAR || other->type == ENTITY_LASER; + bool isAnchored = std::ranges::find(SHOT_ANCHORED_TYPES, type) != SHOT_ANCHORED_TYPES.end(); + if (is_enemy_type(type) && isShot && isAnchored) weight *= MASS_ANCHORED; + if (type != ENTITY_PLAYER || other->type != ENTITY_PROJECTILE) return weight; + + Entity_Player& player = static_cast(*this); + bool isProof = player.HasCollectible(COLLECTIBLE_ISAACS_HEART) || + player.temporaryEffects.HasNullEffect(NULL_TOOTH_AND_NAIL) || + player.playerType == PLAYER_THEFORGOTTEN_B; + return isProof ? weight * MASS_PROJECTILE_PROOF : weight; +} + +// Moves an entity by its share of a push and changes its velocity by its share of the impulse. In the Beast's dungeon +// a player only slows, a quarter as much. An entity without physics knockback stays. +static void push_apply(Entity& entity, const EntityPush& push) +{ + if (entity.HasEntityFlags(FLAG_NO_PHYSICS_KNOCKBACK)) return; + + Vector impulse = push.impulse; + if (g_game->room->IsBeastDungeon() && entity.type == ENTITY_PLAYER) + impulse = vector_make(impulse.x * BEAST_PUSH_DAMPING, impulse.y * BEAST_PUSH_DAMPING); + else + { + entity.pos.x += push.direction.x * push.share * push.overlap; + entity.pos.y += push.direction.y * push.share * push.overlap; + } + entity.velocity.x += impulse.x * push.share; + entity.velocity.y += impulse.y * push.share; +} + +// 006b2940 Pushes the entity and another apart as circles when they overlap and may meet, the lower type first. +// Each moves by the other's share of their weights (a player half as far, and not into a wall) and their velocities +// trade along the line between them. Whether they met. +bool Entity::push_apart_circle(Entity* other) +{ + bool isVersusTearHit = g_game->deathmatchManager.is_active() && type == ENTITY_TEAR && other->type == ENTITY_PLAYER; + bool isSwapped = !isVersusTearHit && other->type < type; + Entity& first = isSwapped ? *other : *this; + Entity& second = isSwapped ? *this : *other; + + Vector delta = vector_make(second.pos.x - first.pos.x, second.pos.y - first.pos.y); + float reach = first.size + second.size; + float distanceSquared = delta.y * delta.y + delta.x * delta.x; + if (!(distanceSquared < reach * reach) || is_collision_ignored(first, second)) return false; + + first.isCollidesWithEntity = second.type != ENTITY_TEAR; + second.isCollidesWithEntity = first.type != ENTITY_TEAR; + float distance = std::sqrt(distanceSquared); + if (distance < PUSH_MIN_DISTANCE) return true; + + Vector relative = vector_make(first.velocity.x - second.velocity.x, first.velocity.y - second.velocity.y); + if (reach * 0.5f < vector_length(relative) && delta.y * relative.y + delta.x * relative.x < 0) + { + Vector relativeDirection = vector_normalized(relative); + Vector deltaDirection = vector_normalized(delta); + float dot = relativeDirection.y * deltaDirection.y + relativeDirection.x * deltaDirection.x; + delta.y = dot * delta.y + dot * delta.y + delta.y; + delta.x = delta.x + dot * delta.x + dot * delta.x; + distance = std::sqrt(delta.y * delta.y + delta.x * delta.x); + } + + float firstWeight = first.collision_mass_get(&second); + float secondShare = firstWeight / (second.collision_mass_get(&first) + firstWeight); + float firstShare = 1 - secondShare; + float overlap = (reach - distance) / distance; + bool isWallBound = first.type == ENTITY_PLAYER || + (first.type == ENTITY_FAMILIAR && first.variant == FAMILIAR_PUNCHING_BAG); + if (isWallBound && + first.is_grid_collision_at(vector_make(-delta.x * firstShare * overlap, -delta.y * firstShare * overlap))) + { + secondShare = 1; + firstShare = 0; + } + if (first.type == ENTITY_PLAYER) firstShare *= PLAYER_PUSH_SHARE; + + float relativeSpeed = vector_length( + vector_make(second.velocity.x - first.velocity.x, second.velocity.y - first.velocity.y)); + Vector impulse = vector_make(delta.x / distance * relativeSpeed, delta.y / distance * relativeSpeed); + if (is_singe_ball(first) && is_singe_ball(second)) bounce_sound_play(SOUND_STONE_IMPACT, relativeSpeed); + + push_apply(first, {vector_make(-delta.x, -delta.y), vector_make(-impulse.x, -impulse.y), overlap, firstShare}); + push_apply(second, {delta, impulse, overlap, secondShare}); + return true; +} + +// 006b25b0 Pushes a stretched entity and another apart along where their capsules overlap. Capsule is not written yet. +void Entity::push_apart_capsule(Entity*) +{ + reconstruction_missing("Entity::push_apart_capsule 006b25b0 (Capsule::Collide 00945470)"); +} + +// 006b2ee0 Pushes the entity and another apart: as circles when neither is stretched, as capsules otherwise. +void Entity::collide_with_entity(Entity* other) +{ + if (is_unit_size(*this) && is_unit_size(*other)) push_apart_circle(other); + else push_apart_capsule(other); +} + +// 006b2f50 Makes two entities meet wherever they are: through their collision classes, or when low straight through +// both HandleCollision calls. Whether the collision is ignored. +bool Entity::ForceCollide(Entity* first, Entity* second, bool isLow) +{ + g_forceCollideDepth++; + bool isIgnored = false; + if (!isLow) isIgnored = is_collision_ignored(*first, *second); + else + { + bool isFirstIgnoring = first->HandleCollision(second, true); + bool isSecondIgnoring = second->HandleCollision(first, false); + isIgnored = isFirstIgnoring || isSecondIgnoring; + } + g_forceCollideDepth--; + return isIgnored; +} + +// 006b2390 Whether an entity is on the players' side, as ENTCOLL_PLAYEROBJECTS meets it: a player, tear, familiar, +// knife or bomb, a charmed or friendly enemy, the Blood Puppy, Dark Esau and poop, or a projectile that hits enemies. +bool is_player_object(Entity& entity) +{ + switch (entity.type) + { + case ENTITY_PLAYER: + case ENTITY_TEAR: + case ENTITY_FAMILIAR: + case ENTITY_BOMB: + case ENTITY_KNIFE: return true; + default: break; + } + + bool isAlly = entity.HasEntityFlags(FLAG_CHARM | FLAG_FRIENDLY) || entity.type == ENTITY_BLOOD_PUPPY || + entity.type == ENTITY_DARK_ESAU || entity.type == ENTITY_POOP; + if (entity.IsEnemy() && isAlly) return true; + return entity.type == ENTITY_PROJECTILE && + (static_cast(entity).projectileFlags & PROJECTILE_HIT_ENEMIES); +} + +// An entity's collision class, a charmed or friendly enemy's player-side class meeting all. +static int collision_class_get(Entity& entity) +{ + int collisionClass = entity.entityCollisionClass; + bool isPlayerSide = collisionClass == ENTCOLL_PLAYERONLY || collisionClass == ENTCOLL_PLAYEROBJECTS; + bool isAlly = Entity::is_enemy_type(entity.type) && entity.HasEntityFlags(FLAG_CHARM | FLAG_FRIENDLY); + return isPlayerSide && isAlly ? ENTCOLL_ALL : collisionClass; +} + +// 006b2410 Whether two entities pass through each other: by their collision classes (the first's player-only class +// meets nothing), either being dead, or else either's HandleCollision ignoring the other. +bool is_collision_ignored(Entity& first, Entity& second) +{ + int firstClass = collision_class_get(first); + int secondClass = collision_class_get(second); + bool isNone = firstClass == ENTCOLL_NONE || secondClass == ENTCOLL_NONE; + bool isNotPlayerObject = (firstClass == ENTCOLL_PLAYEROBJECTS && !is_player_object(second)) || + (secondClass == ENTCOLL_PLAYEROBJECTS && !is_player_object(first)); + bool isNotPlayer = firstClass == ENTCOLL_PLAYERONLY || + (secondClass == ENTCOLL_PLAYERONLY && first.type != ENTITY_PLAYER); + bool isNotEnemy = (firstClass == ENTCOLL_ENEMIES && !Entity::is_enemy_type(second.type)) || + (secondClass == ENTCOLL_ENEMIES && !Entity::is_enemy_type(first.type)); + if (first.isDead || second.isDead || isNone || isNotPlayerObject || isNotPlayer || isNotEnemy) return true; + + bool isFirstIgnoring = first.HandleCollision(&second, true); + bool isSecondIgnoring = second.HandleCollision(&first, false); + return isFirstIgnoring || isSecondIgnoring; } diff --git a/src/entity_collision.h b/src/entity_collision.h new file mode 100644 index 0000000..4c0fe83 --- /dev/null +++ b/src/entity_collision.h @@ -0,0 +1,6 @@ +#pragma once + +#include "entity.h" + +bool is_player_object(Entity& entity); +bool is_collision_ignored(Entity& first, Entity& second); diff --git a/src/entity_effect.cpp b/src/entity_effect.cpp index a6a86a0..9f25f74 100644 --- a/src/entity_effect.cpp +++ b/src/entity_effect.cpp @@ -1,10 +1,13 @@ #include "entity_effect.h" +#include "entity_list.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 "room_config.h" #include "sfx_manager.h" #include #include @@ -28,11 +31,56 @@ constexpr int EFFECT_TIMER = 119; constexpr int EFFECT_ENEMY_SOUL = 179; constexpr int EFFECT_ANIMA_CHAIN = 193; constexpr int EFFECT_REDEMPTION = 185; +constexpr int EFFECT_BLOOD_EXPLOSION = 2; +constexpr int EFFECT_POOF01 = 15; +constexpr int EFFECT_POOF02 = 16; +constexpr int EFFECT_TINY_FLY = 33; -// The variants whose Init, Update and Render are reconstructed: the tear poofs and the blood stains. -constexpr std::array EFFECT_RECONSTRUCTED_VARIANTS = { +// The variants whose Init, Update and Render are reconstructed: the tear poofs, the blood stains, the poofs and the +// ambient tiny fly. +constexpr std::array EFFECT_RECONSTRUCTED_VARIANTS = { EFFECT_BLOOD_SPLAT, EFFECT_BULLET_POOF, EFFECT_TEAR_POOF_A, EFFECT_TEAR_POOF_B, - EFFECT_RIPPLE_POOF, EFFECT_TEAR_POOF_SMALL, EFFECT_TEAR_POOF_VERYSMALL, EFFECT_IMPACT}; + EFFECT_RIPPLE_POOF, EFFECT_TEAR_POOF_SMALL, EFFECT_TEAR_POOF_VERYSMALL, EFFECT_IMPACT, + EFFECT_POOF01, EFFECT_POOF02, EFFECT_TINY_FLY}; + +// The animations a poof plays by its subtype: POOF01 from 1 to 3, POOF02's lava splash at random. +constexpr std::array POOF01_ANIMATIONS = {"Poof2", "Poof_Small", "Poof", "Poof_Large"}; +constexpr std::array LAVA_SPLASH_ANIMATIONS = {"Poof0", "Poof1", "Poof2"}; +constexpr int POOF01_SUBTYPE_LAST = 3; +constexpr int POOF02_LAVA_SPLASH = 66; +constexpr int POOF02_LAVA_SPLASH_LARGE = 67; +constexpr int POOF_RENDER_Z = 8000; +constexpr uint32_t LAVA_SPLASH_SHIFT = 4; + +// The tiny fly: white in the Cathedral, its own color in Dross, how it wanders, flees the nearest player within +// range, dies to tears, knives and fires, and drops down in circles when dead. +constexpr int STAGE_ID_CATHEDRAL = 15; +constexpr int BACKDROP_DROSS = 45; +constexpr int ENTITY_KNIFE_TYPE = 8; +constexpr int FLY_WANDER_ODDS = 5; +constexpr int FLY_JITTER_FRAMES = 5; +constexpr float FLY_MASS = 1; +constexpr float FLY_FRICTION = 0.98f; +constexpr float FLY_DEAD_FRICTION = 0.8f; +constexpr float FLY_PULL = 0.5f; +constexpr float FLY_JITTER = 0.9f; +constexpr float FLY_FLEE_RANGE = 60; +constexpr float FLY_FLEE_PUSH = -0.2f; +constexpr float FLY_HIT_RADIUS = 0.5f; +constexpr float FLY_KNIFE_REACH = 1.5f; +constexpr float FLY_FIRE_REACH = 2; +constexpr float FLY_FALL_STEP = 0.25f; +constexpr float FLY_FALL_HEIGHT = 16; +constexpr float FLY_CIRCLE_SPEED = 15; +constexpr float FLY_CIRCLE_RADIUS = 3; +constexpr float FLY_CLAMP_MARGIN = 2; +constexpr float FLY_SPLAT_SCALE = 0.1f; +constexpr float FLY_BURST_SCALE = 0.3f; +constexpr float FLY_BURST_RISE = -16; +constexpr float MIN_DISTANCE = 0.01f; +constexpr float RANDOM_UNIT = 2.3283064e-10f; +constexpr float RANDOM_HALF_TURN = 3.14f; +constexpr float DEGREES_TO_RADIANS = 0.017453292f; // The poofs that turn with their rotation. constexpr std::array EFFECT_TURNED_POOFS = {EFFECT_TEAR_POOF_A, EFFECT_TEAR_POOF_B, EFFECT_TEAR_POOF_SMALL, EFFECT_TEAR_POOF_VERYSMALL, EFFECT_IMPACT}; @@ -60,12 +108,6 @@ constexpr int LUA_CALLBACK_POST_EFFECT_INIT = 54; constexpr int LUA_CALLBACK_POST_EFFECT_UPDATE = 55; constexpr int LUA_CALLBACK_POST_EFFECT_RENDER = 56; -// Stops where a mod has a function for one of the effect's Lua callbacks, which LuaEngine does not run yet. -static void lua_callback_check(int callback, const char* name) -{ - if (static_cast(g_luaEngine)->enabledCallbacks[callback]) reconstruction_missing(name); -} - template static bool is_listed(const std::array& list, int value) { @@ -158,6 +200,8 @@ void Entity_Effect::Init(int entityType, int entityVariant, int entitySubType, u isUnknown176 = true; } if (variant == EFFECT_IMPACT) sprite.isFlipX = !(Random() & 1); + if (variant == EFFECT_POOF01 || variant == EFFECT_POOF02) poof_init(); + if (variant == EFFECT_TINY_FLY) tiny_fly_init(); sprite.LoadGraphics(); if (g_game->deathmatchManager.is_active()) @@ -199,12 +243,194 @@ void Entity_Effect::Update() } if (variant == EFFECT_BLOOD_SPLAT) stain_update(); + else if (variant == EFFECT_TINY_FLY) tiny_fly_update(); else poof_update(); if (timeout > 0 && --timeout < 1) isDead = true; pausePosition = pos; lua_callback_check(LUA_CALLBACK_POST_EFFECT_UPDATE, "LuaEngine::PostEffectUpdate 00861410"); } +// A poof's animation by its subtype. POOF01 and POOF02's large kinds draw over everything, POOF02's small kinds lie +// on the floor outside the crawl space, and its lava splashes face a seeded side. +void Entity_Effect::poof_init() +{ + if (variant == EFFECT_POOF01) + { + if (subtype >= 1 && subtype <= POOF01_SUBTYPE_LAST) sprite.Play(POOF01_ANIMATIONS[subtype]); + renderZOffset = POOF_RENDER_Z; + return; + } + + if (subtype == 1 || subtype == 3) + { + if (g_game->room->roomType != ROOM_DUNGEON) sortingLayer = SORTING_BACKGROUND; + sprite.Play("Poof"); + } + else if (subtype == 2 || subtype == 4 || subtype == 5) + { + renderZOffset = POOF_RENDER_Z; + sprite.Play("Poof"); + } + else if (subtype == POOF02_LAVA_SPLASH || subtype == POOF02_LAVA_SPLASH_LARGE) + { + RNG rng = rng_make(initSeed, LAVA_SPLASH_SHIFT); + uint32_t roll = subtype == POOF02_LAVA_SPLASH ? rng.Next() % LAVA_SPLASH_ANIMATIONS.size() : 0; + sprite.Play(subtype == POOF02_LAVA_SPLASH ? LAVA_SPLASH_ANIMATIONS[roll] : "PoofLarge"); + sprite.isFlipX = !(initSeed & 1); + } +} + +// A tiny fly: white in the Cathedral, uncolored in Dross, light and colliding with everything. +void Entity_Effect::tiny_fly_init() +{ + if (RoomConfig::GetStageID((int)g_game->stage, (int)g_game->stageType, (RoomMode)-1) == STAGE_ID_CATHEDRAL) + sprite.Play("White"); + mass = FLY_MASS; + entityCollisionClass = ENTCOLL_ALL; + isUnknown176 = true; + if (g_game->room->backdropType == BACKDROP_DROSS) sprite.color = COLOR_DEFAULT; +} + +// The player nearest a position, the first one on a tie (Game::GetNearestPlayer 00703950, which Game does not +// declare yet). +static Entity_Player* nearest_player_get(const Vector& position) +{ + Entity_Player* nearest = nullptr; + float nearestDistance = 0; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + float dx = position.x - player->pos.x; + float dy = position.y - player->pos.y; + float distance = dy * dy + dx * dx; + if (nearest && distance >= nearestDistance) continue; + nearest = player; + nearestDistance = distance; + } + return nearest; +} + +static float random_unit() +{ + return (float)Random() * RANDOM_UNIT; +} + +static Vector vector_scaled(Vector v, float scale) +{ + return vector_make(v.x * scale, v.y * scale); +} + +static float vector_length(Vector v) +{ + return std::sqrt(v.x * v.x + v.y * v.y); +} + +// Whether an entity of the list stands within reach of a position, reach scaled from its size. +static bool is_within_reach(Entity& entity, const Vector& position, float reach) +{ + float dx = entity.pos.x - position.x; + float dy = entity.pos.y - position.y; + return dx * dx + dy * dy < reach * reach; +} + +// Bursts the fly into a small splash of its blood color. +void Entity_Effect::tiny_fly_burst() +{ + isDead = true; + Entity* burst = g_game->Spawn({vector_make(pos.x, pos.y + FLY_BURST_RISE), {}, nullptr, 0, ENTITY_EFFECT, + EFFECT_BLOOD_EXPLOSION, Random()}); + burst->SetColor(splatColor, -1, 255, false, true); + burst->sprite.scale = vector_make(FLY_BURST_SCALE, FLY_BURST_SCALE); + burst->Update(); + sprite.Stop(); +} + +// A tiny fly's frame: alive it drifts at random, now and then toward its parent or the nearest player, and away +// from a player close by, and bursts on a tear, knife or fire. Dead, it spirals down and splats. It faces its motion +// and stays in the room. +void Entity_Effect::tiny_fly_update() +{ + Entity_Player* player = nearest_player_get(pos); + Vector toPlayer = vector_make(player->pos.x - pos.x, player->pos.y - pos.y); + float distance = vector_length(toPlayer); + Vector direction = vector_scaled(toPlayer, 1 / (distance == 0 ? MIN_DISTANCE : distance)); + EntityList& entities = g_game->room->entityList; + + friction *= FLY_FRICTION; + if (isDead) + { + LayerState& layer = *sprite.GetLayer(0); + if (layer.pos.y <= FLY_FALL_HEIGHT) + { + layer.pos.y += FLY_FALL_STEP; + float side = (float)(index % 2) * 2 - 1; + float angle = (float)g_game->frameCount * FLY_CIRCLE_SPEED * side * DEGREES_TO_RADIANS; + Vector circle = vector_make(std::cos(angle), std::sin(angle)); + circle = vector_scaled(vector_scaled(circle, std::abs(layer.pos.y) / FLY_FALL_HEIGHT), FLY_CIRCLE_RADIUS); + pos = vector_make(pos.x + circle.x, pos.y + circle.y); + friction *= FLY_DEAD_FRICTION; + } + else + { + Entity* splat = g_game->Spawn({pos, {}, nullptr, 0, ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, Random()}); + splat->SetColor(splatColor, -1, 255, false, true); + splat->sprite.scale = vector_make(FLY_SPLAT_SCALE, FLY_SPLAT_SCALE); + splat->Update(); + Remove(); + } + } + + if (!isDead) + { + if (Random() % FLY_WANDER_ODDS == 0) + { + Vector pull = direction; + if (parent) + { + Vector toParent = vector_make(parent->pos.x - pos.x, parent->pos.y - pos.y); + float length = vector_length(toParent); + if (length > 0) toParent = vector_scaled(toParent, (length - parent->size) / length); + float resized = vector_length(toParent); + pull = resized > 0 ? vector_scaled(toParent, 1 / resized) : toParent; + } + AddVelocity_divided(vector_scaled(pull, random_unit() * FLY_PULL), false); + } + if (IsFrame(FLY_JITTER_FRAMES, (int)index)) + { + float angle = random_unit() * RANDOM_HALF_TURN * 2; + Vector jitter = vector_make(std::cos(angle), std::sin(angle)); + AddVelocity_divided(vector_scaled(jitter, random_unit() * FLY_JITTER), false); + } + if (distance < FLY_FLEE_RANGE) + { + float push = (1 - distance * distance / (FLY_FLEE_RANGE * FLY_FLEE_RANGE)) * FLY_FLEE_PUSH; + AddVelocity_divided(vector_scaled(direction, push), false); + } + + EntityList_EL shots; + entities.partitions[PARTITION_SHOTS].query_box(shots, pos, vector_make(FLY_HIT_RADIUS, FLY_HIT_RADIUS)); + bool isShot = std::any_of(shots.begin(), shots.end(), [this](Entity* shot) { + return !shot->HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && shot->type == ENTITY_TEAR && + is_within_reach(*shot, pos, FLY_HIT_RADIUS + shot->size); + }); + if (isShot) tiny_fly_burst(); + + std::vector hazards(entities.updateEL); + for (Entity* hazard : hazards) + { + bool isKnife = + hazard->type == ENTITY_KNIFE_TYPE && is_within_reach(*hazard, pos, hazard->size * FLY_KNIFE_REACH); + bool isFire = + hazard->type == ENTITY_FIREPLACE && is_within_reach(*hazard, pos, hazard->size + FLY_FIRE_REACH); + if (isKnife || isFire) tiny_fly_burst(); + } + } + + sprite.isFlipX = pos.x - targetPosition.x < 0; + pos = g_game->room->GetClampedPosition(pos, FLY_CLAMP_MARGIN); + targetPosition = pos; +} + // Turns a poof by its rotation, mirrored unless flipped, and removes it once its animation ends. A ripple first // draws its small sizes larger with their own animations. void Entity_Effect::poof_update() diff --git a/src/entity_effect.h b/src/entity_effect.h index 6f091c2..533b197 100644 --- a/src/entity_effect.h +++ b/src/entity_effect.h @@ -12,7 +12,8 @@ constexpr int EFFECT_SPAWN_PENTAGRAM = 203; // Field accessors (00435e60, 00435eb0, 004d7770, 005784c0, 0060ce20) are the public fields. // An effect (Lua's EntityEffect): a visual or a hazard such as creep, a poof or a light beam, with its timeout, its // fall, the per-variant data it keeps and the extra data some variants share. -// Only the tear poofs and the blood stains are reconstructed yet: Init stops at any other variant. +// Only the tear poofs, the blood stains, the poofs and the tiny fly are reconstructed yet: Init stops at any other +// variant. struct Entity_Effect : Entity { // The base of the extra data some variants keep (MrMeData, PickupGhostData, SpriteTrailData). @@ -66,6 +67,10 @@ struct Entity_Effect : Entity void setup_loot_preview(void* lootQueue); private: + void poof_init(); + void tiny_fly_init(); void poof_update(); void stain_update(); + void tiny_fly_update(); + void tiny_fly_burst(); }; diff --git a/src/entity_familiar.h b/src/entity_familiar.h index 35e710e..9ab1e85 100644 --- a/src/entity_familiar.h +++ b/src/entity_familiar.h @@ -2,12 +2,12 @@ #include "entity.h" #include "anm2.h" +#include "path_finder.h" #include "weapon.h" #include #include -// Construction and destruction (0060d3d0, 0060d200) are the defaults, but for the pathfinder's owner the constructor -// sets. PathFinder::Init's reset waits for PathFinder's takeover. +// Construction and destruction (0060d3d0, 0060d200) are the defaults, with the familiar owning its pathfinder. // Field accessors (004361f0, 00505cf0, 0060d0e0, 0060d100) are the public fields. // A familiar (Lua's EntityFamiliar): its player, its place in the following line or an orbit, the consumables it // collects, its weapon, and the extra data some variants keep. @@ -20,7 +20,7 @@ struct Entity_Familiar : Entity }; ANM2 chargeBarSprite; - NPCAI_Pathfinder pathfinder{}; + PathFinder pathfinder{this}; std::unique_ptr extraData; std::vector hitList; ColorMod dirtColor = COLOR_DEFAULT; @@ -61,8 +61,6 @@ struct Entity_Familiar : Entity bool isNotCountedAsFollower = false; bool isSubtype55555 = false; - Entity_Familiar() { pathfinder._entity = this; } - void Init(int type, int variant, int subType, uint32_t initSeed) override; void Update() override; void Interpolate() override; diff --git a/src/entity_list.cpp b/src/entity_list.cpp index 046a61d..d5f0a74 100644 --- a/src/entity_list.cpp +++ b/src/entity_list.cpp @@ -30,6 +30,21 @@ constexpr uint32_t RENDER_Z_NORMAL_START = 10000; constexpr int RENDER_LIST_CAPACITY = 0x4000; constexpr int RENDER_SORT_SWAP_BUDGET = (RENDER_LIST_CAPACITY >> 4) + 1; +// The room's render surface, its size and margin, centered on the screen. +constexpr float ROOM_SURFACE_WIDTH = 338; +constexpr float ROOM_SURFACE_HEIGHT = 182; +constexpr float ROOM_SURFACE_MARGIN = 52; + +// A surface surfaces_bake draws into: the flag of the entities drawn there, the flags that keep them, and whether any +// is to be drawn. +struct SurfacePass +{ + KAGE::Graphics::ImageBase* surface = nullptr; + uint64_t flag = 0; + uint64_t keptFlags = 0; + bool isUsed = false; +}; + // 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, ...) { @@ -47,13 +62,6 @@ static bool is_unit_size(const Entity& entity) return entity.sizeMulti.x == 1 && entity.sizeMulti.y == 1; } -// Pushes one entity off another: as circles when neither is stretched, as capsules otherwise. -static void entity_push_apart(Entity& pusher, Entity& other) -{ - if (is_unit_size(pusher) && is_unit_size(other)) pusher.push_apart_circle(&other); - else pusher.push_apart_capsule(&other); -} - // 00417670 Drops every occurrence of the entity. void EntityList_EL::remove(Entity* entity) { @@ -150,7 +158,7 @@ void CellSpace::collide_entity(Entity& entity) { Entity& other = *cell->entities[i]; if (&other == &entity || !owner->is_pair_new(other, entity)) continue; - entity_push_apart(other, entity); + other.collide_with_entity(&entity); } } } @@ -170,7 +178,7 @@ void CellSpace::collide(CellSpace& other) { Entity& first = *cells[c].entities[i]; Entity& second = *other.cells[c].entities[j]; - if (&first != &second && owner->is_pair_new(first, second)) entity_push_apart(first, second); + if (&first != &second && owner->is_pair_new(first, second)) first.collide_with_entity(&second); } } } @@ -187,7 +195,7 @@ void CellSpace::collide_self() { Entity& first = *cell.entities[i]; Entity& second = *cell.entities[j]; - if (&first != &second && owner->is_pair_new(first, second)) entity_push_apart(first, second); + if (&first != &second && owner->is_pair_new(first, second)) first.collide_with_entity(&second); } } } @@ -320,6 +328,53 @@ void EntityList::AddPersistentEntity(Entity* entity) if (!isListed) persistentEL.push_back(entity); } +// Draws the entities flagged to render into the floor or the walls into the backdrop's surfaces, at the room +// surface's corner on screen snapped to the display's pixels, and removes them. One drawn into both stays for the +// walls, and one with FLAG_NO_REMOVE_ON_TEX_RENDER stays. Whether any was removed. +static bool surfaces_bake(EntityList_EL& renderEL) +{ + Backdrop& backdrop = g_game->room->backdrop; + std::array passes = {{ + {backdrop.floorBuffer.get(), FLAG_RENDER_FLOOR, FLAG_RENDER_WALL | FLAG_NO_REMOVE_ON_TEX_RENDER}, + {backdrop.wallsBuffer.get(), FLAG_RENDER_WALL, FLAG_NO_REMOVE_ON_TEX_RENDER}, + }}; + auto isDrawn = [](Entity* entity, uint64_t flag) { return entity->isExists && entity->HasEntityFlags(flag); }; + for (SurfacePass& pass : passes) + pass.isUsed = std::any_of(renderEL.begin(), renderEL.end(), + [&pass, &isDrawn](Entity* entity) { return isDrawn(entity, pass.flag); }); + if (!passes[0].isUsed && !passes[1].isUsed) return false; + + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + float pixelScale = g_displayPixelRatio * g_screenPointScale; + auto corner = [pixelScale](float screen, float surface) + { return -(std::floor(pixelScale * ((screen - surface) * 0.5f - ROOM_SURFACE_MARGIN) + 0.5f) / pixelScale); }; + Vector offset = vector_make(corner(g_screenWidth, ROOM_SURFACE_WIDTH), corner(g_screenHeight, ROOM_SURFACE_HEIGHT)); + auto size = graphics.isScreenTarget ? KAGE::Graphics::TARGET_SCREEN_SIZE : KAGE::Graphics::TARGET_OWN_SIZE; + graphics.render_target_push(graphics.renderTarget, size, KAGE::Graphics::PRESENT_FLUSH); + graphics.isCullOffscreen = false; + graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); + + bool isRemoved = false; + for (SurfacePass& pass : passes) + { + if (!pass.isUsed) continue; + graphics.SetRenderTarget(pass.surface, KAGE::Graphics::TARGET_OWN_SIZE); + for (size_t i = 0; i < renderEL.size(); i++) + { + Entity* entity = renderEL[i]; + if (!isDrawn(entity, pass.flag)) continue; + entity->Render(offset); + if (entity->HasEntityFlags(pass.keptFlags)) continue; + entity->Remove(); + isRemoved = true; + } + graphics.Present(KAGE::Graphics::PRESENT_FINISH); + } + graphics.isCullOffscreen = true; + graphics.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); + return isRemoved; +} + // 004186c0 One frame of the room's entities: pre-updates and updates (only those that update in transitions during // one), the players' in-between updates without interpolation, the enemy and boss counts and the boss bar, the // removal of the entities that stopped existing, then the collisions and the draw order. @@ -341,13 +396,8 @@ void EntityList::Update(UpdateMode mode) isAnyBaited = tally.isAnyBaited; boss_bar_update(tally); enemyDamageInflicted = tally.damageInflicted; - for (Entity* entity : renderEL) - { - if (entity->isExists && entity->HasEntityFlags(FLAG_RENDER_FLOOR | FLAG_RENDER_WALL)) - reconstruction_missing("EntityList::Update 004186c0: drawing entities into the floor and wall surfaces"); - } - - if (tally.isAnyRemoved) removed_drop(); + bool isBakedAway = surfaces_bake(renderEL); + if (tally.isAnyRemoved || isBakedAway) removed_drop(); if (mode == UPDATE_NORMAL) rebuild_sublists(); sort_by_render_z(); } @@ -614,8 +664,10 @@ void EntityList::twins_push_apart() if (twin->playerIndex != -1 && player->playerIndex > twin->playerIndex && twin != player) continue; bool isEvenFrame = (g_game->frameCount & 1) == 0; - entity_push_apart(isEvenFrame ? *player : *twin, isEvenFrame ? *twin : *player); - entity_push_apart(isEvenFrame ? *twin : *player, isEvenFrame ? *player : *twin); + Entity_Player* first = isEvenFrame ? player : twin; + Entity_Player* second = isEvenFrame ? twin : player; + first->collide_with_entity(second); + second->collide_with_entity(first); } } diff --git a/src/entity_npc.cpp b/src/entity_npc.cpp index d57cb0d..490285a 100644 --- a/src/entity_npc.cpp +++ b/src/entity_npc.cpp @@ -1,9 +1,1032 @@ #include "entity_npc.h" +#include "entity_config.h" +#include "entity_effect.h" +#include "entity_player.h" +#include "entity_projectile.h" +#include "data.h" #include "game.h" -#include "room.h" +#include "grid_entity.h" #include "log.h" +#include "manager.h" +#include "npc_ai.h" +#include "persistent_game_data.h" +#include "platform.h" +#include "room.h" +#include "room_config.h" +#include "room_descriptor.h" +#include "sfx_manager.h" +#include +#include +#include +constexpr int ENTITY_FLY = 13; +constexpr int ENTITY_POOTER = 14; +constexpr int ENTITY_ATTACKFLY = 18; +constexpr int ENTITY_MULLIGAN = 16; +constexpr int ENTITY_HIVE = 22; +constexpr int ENTITY_SPIDER = 85; +constexpr int ENTITY_ETERNAL_FLY = 96; +constexpr int ENTITY_FEAR_IMMUNE = 205; +constexpr int ENTITY_DEATHS_HEAD = 212; +constexpr int ENTITY_NO_DECOY_TYPE = 213; +constexpr int ENTITY_COLLISION_SPAWNER_SPECIAL = 873; +constexpr int ENTITY_BIG_HORN = 411; +constexpr int ENTITY_MOMS_HEART_PLAYER_PICK = 53; +constexpr int ENTITY_DEATH_REWARD_EXEMPT = 885; +constexpr int ENTITY_ROTGUT = 911; +constexpr int ENTITY_UNREACHABLE_EXEMPT = 886; +constexpr int ENTITY_FLICKER_TYPE = 252; +constexpr int ENTITY_DEATH_SPARK_TYPE = 882; +constexpr int ENTITY_SHADOW_OVERLAY_TYPE = 886; +constexpr int ENTITY_DAMAGE_NUMBERS_TYPE = 964; +constexpr int ENTITY_ERASE_EXEMPT = 950; +constexpr int APPEAR_OVERLAY_KEPT_TYPE = 266; +constexpr int APPEAR_SOUND_TYPE_A = 401; +constexpr int APPEAR_SOUND_TYPE_B = 403; +constexpr std::array APPEAR_EVENT_TYPES = {404, 912, 913, 917}; +constexpr std::array DEATH_EVENT_TYPES = {102, 900, 907, 908, 912, 913, 915, 921}; +constexpr std::array FLUSH_TYPES = {217, 220, 223, 261, 402, 870, 871, 872, 914}; +constexpr int FLUSH_PROP_TYPE = 237; +constexpr int FLUSH_PROP_VARIANT = 2; +constexpr int FLUSH_RENDER_Z = 5000; +constexpr int ENTITY_FORWARD_NONE = 45; +constexpr int ENTITY_FORWARD_DOWN_A = 262; +constexpr int ENTITY_FORWARD_DOWN_B = 263; +constexpr int DEATH_HEAD_LAYER_TYPE = 405; +constexpr int DEATH_NO_BURST_FIRST = 74; +constexpr int DEATH_NO_BURST_LAST = 76; +constexpr int MULLIGAN_VARIANT_FLEEING = 2; +constexpr int FAMILIAR_BLUE_FLY = 43; +constexpr int CHALLENGE_KILL_CHARGE = 33; +constexpr int COLLECTIBLE_SKATOLE_ID = 9; +constexpr int COLLECTIBLE_BURSTING_SACK_ID = 377; +constexpr int COLLECTIBLE_E_COLI_ID = 236; +constexpr int COLLECTIBLE_LIL_PORTAL_ID = 661; +constexpr std::string_view BIG_HORN_SPIT_EVENT = "Item"; +constexpr std::string_view DIRT_LAYER = "dirt"; +constexpr std::string_view HOLE_LAYER = "Hole"; +constexpr std::string_view HOLE2_LAYER = "Hole2"; +constexpr std::string_view GFUEL_ISAAC_ANM2 = "gfx/promo/gfuel/102.001_g baby (true final boss).anm2"; +constexpr int DIRT_SAMPLE_FRAMES = 15; +constexpr float DIRT_GREEN = 0.9f; +constexpr float DIRT_LERP = 0.1f; +constexpr int MORPH_COLOR_PRIORITY = -1000; +constexpr int COLOR_PRIORITY_DEFAULT = 255; +constexpr ColorMod COLOR_INVISIBLE = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0}}; +constexpr int UNREACHABLE_CHECK_FRAMES = 60; +constexpr int UNREACHABLE_GRACE_FRAMES = 900; +constexpr int SHRINK_PULSE_FRAMES = 60; +constexpr float MIDAS_COIN_SPEED = 3; +constexpr float TOXIC_CREEP_SCALE = 0.05f; +constexpr int TOXIC_SHOCK_POISON = -40; +constexpr int MODEM_FRAMES = 50; +constexpr int PUPPY_HIT_FRAMES = 3; +constexpr int FORCED_TARGET_BOSS_COOLDOWN = 150; +constexpr int CONFUSION_RETARGET_FRAMES = 15; +constexpr float CONFUSION_WANDER = 240; +constexpr float FEAR_WANDER = 100; +constexpr int FEAR_RETARGET_RANGE = 15; +constexpr int FEAR_RETARGET_MIN = 5; +constexpr float MOVEMENT_DEADZONE = 0.1f; +constexpr float ATTACK_PREDICT_FRAMES = 5; +constexpr int LINE_CHECK_PROJECTILE = 3; +constexpr int LINE_MODE_GROUND = 0; +constexpr int LINE_MODE_PROJECTILE = 3; +constexpr float LINE_STEP = 10; +constexpr int LINE_BLOCKED_MAX = 8; +// The corners of the band a line check samples around each step. +struct LineCorner +{ + float x; + float y; +}; +constexpr std::array LINE_CORNERS = {{{-5, -5}, {-5, 5}, {5, 5}, {5, -5}}}; +constexpr int GRID_PATH_PIT = 3000; +constexpr uint32_t GRID_PATH_BAND = 1000; +constexpr int STAGE_BEAST_DUNGEON = 35; +constexpr int LINE_CHECK_THRESHOLD = 999; +constexpr float KNOCKBACK_IMPACT_SPEED = 6; +constexpr float SHIELD_SECOND = 30; +constexpr float SHIELD_BASE = 0.09f; +constexpr float SHIELD_FALLOFF = 0.18f; +constexpr uint32_t BLACK_HEART_CHANCE = 5; +constexpr float EXORCIST_ROOM_MARGIN = -10; +constexpr int SOUND_POOP_DEATH = 237; +constexpr float POOP_DEATH_VOLUME = 0.9f; +constexpr uint32_t DEBUG_HEALTH_VALUES = 1 << 6; +constexpr uint64_t FLAG_FRIENDLY_BALL_DYING = 1ull << 60; +constexpr uint64_t PROJECTILE_ANY_HEIGHT_ENTITY_HIT = 1ull << 17; + +// The burst effects a dead NPC leaves besides blood (Lua's EffectVariant). +enum DeathBurst : int +{ + EFFECT_SPIDER_EXPLOSION = 38, + EFFECT_POOP_EXPLOSION = 43, + EFFECT_BURST_810 = 130, + EFFECT_BURST_853 = 131, + EFFECT_BURST_818 = 145 +}; + +// Lua's DamageFlag bits the NPC code reads beyond entity.h's. +enum NpcDamageFlag : uint64_t +{ + DAMAGE_ACID = 1ull << 4, + DAMAGE_INVINCIBLE = 1ull << 13, + DAMAGE_SPAWN_FLY = 1ull << 14, + DAMAGE_SPAWN_BLACK_HEART = 1ull << 23, + DAMAGE_SPAWN_RED_HEART = 1ull << 26, + DAMAGE_SPAWN_COIN = 1ull << 27, + DAMAGE_IGNORE_ARMOR = 1ull << 30, + DAMAGE_SPAWN_CARD = 1ull << 31, + DAMAGE_SPAWN_RUNE = 1ull << 32 +}; +constexpr int ENTITY_SUCKER = 61; +constexpr int ENTITY_SIREN_HELPER = 966; +constexpr int ENTITY_BABY_PLUM = 908; constexpr int ENTITY_EXORCIST = 832; +constexpr int ENTITY_ISAAC_BOSS = 102; +constexpr int ENTITY_HORNFEL = 906; +constexpr int ENTITY_GIDEON = 907; +constexpr int ENTITY_SHADOW_CHARGER = 23; +constexpr int ENTITY_ULTRA_GREED_DOOR = 889; +constexpr int ENTITY_MONSTRO = 45; +constexpr int ENTITY_GURDY_JR = 78; +constexpr int SUCKER_VARIANT_BULB = 5; +constexpr int FAMILIAR_PUNCHING_BAG = 67; +constexpr int SHADOW_CHARGER_SUBTYPE = 1; +constexpr int TYPE_NO_TICK_A = 274; +constexpr int TYPE_NO_TICK_B = 275; + +// The effects the NPC code spawns (Lua's EffectVariant). +enum NpcEffect : int +{ + EFFECT_BLOOD_EXPLOSION = 2, + EFFECT_FLY_EXPLOSION = 3, + EFFECT_BLOOD_SPLAT = 7, + EFFECT_POOF01 = 15, + EFFECT_POOF02 = 16, + EFFECT_TARGET = 19, + EFFECT_HEART = 49, + EFFECT_PLAYER_CREEP_GREEN = 53, + EFFECT_WATER_RIPPLE = 99 +}; + +constexpr int ENTITY_KEY_TEAR_A = 43; +constexpr int ENTITY_KEY_TEAR_B = 44; +constexpr int PICKUP_COIN = 20; +constexpr int COIN_PENNY = 1; + +// The items and seeds whose effects the NPC update reads, by Lua id. +constexpr int COLLECTIBLE_HOURGLASS_ID = 66; +constexpr int COLLECTIBLE_GAMEKID_ID = 93; +constexpr int COLLECTIBLE_CHAMPION_BELT_ID = 208; +constexpr int COLLECTIBLE_GIMPY_ID = 225; +constexpr int COLLECTIBLE_STOP_WATCH_ID = 232; +constexpr int COLLECTIBLE_INFESTATION_2_ID = 234; +constexpr int COLLECTIBLE_SOUL_ID = 335; +constexpr int COLLECTIBLE_TOXIC_SHOCK_ID = 350; +constexpr int COLLECTIBLE_BETRAYAL_ID = 391; +constexpr int COLLECTIBLE_SPIDER_MOD_ID = 403; +constexpr int COLLECTIBLE_MAW_OF_THE_VOID_ID = 408; +constexpr int COLLECTIBLE_JAR_OF_FLIES_ID = 434; +constexpr int COLLECTIBLE_CONTAGION_ID = 466; +constexpr int COLLECTIBLE_BROKEN_MODEM_ID = 514; +constexpr int COLLECTIBLE_SANGUINE_BOND_ID = 640; +constexpr int COLLECTIBLE_VASCULITIS_ID = 657; +constexpr int COLLECTIBLE_BONE_SPURS_ID = 683; +constexpr int COLLECTIBLE_LIL_ABADDON_ID = 684; +constexpr int COLLECTIBLE_SALVATION_ID = 696; +constexpr int COLLECTIBLE_VANISHING_TWIN_ID = 697; +constexpr int TRINKET_PURPLE_HEART_ID = 5; +constexpr int TRINKET_TICK_ID = 53; +constexpr int TRINKET_SUPER_MAGNET_ID = 68; +constexpr int TRINKET_LIGHTER_ID = 135; +constexpr int TRINKET_ICE_CUBE_ID = 188; +constexpr int TRINKET_DEVILS_CROWN_ID = 185; +constexpr int NULLITEM_DAMOCLES_WEAKNESS = 64; + +constexpr int STAGE_VOID = 12; +constexpr int CHALLENGE_ULTRA_HARD = 34; +constexpr int CHALLENGE_BEANS = 30; +constexpr int CHALLENGE_SLOW = 22; +constexpr int ACHIEVEMENT_BOSS_COLORS = 3; +constexpr int ACHIEVEMENT_MORE_BOSS_COLORS = 33; +constexpr int ACHIEVEMENT_REDIRECTS = 348; +constexpr uint32_t ROOM_CONFIG_FLAG_NO_CHAMPIONS = 1 << 2; +constexpr int GRID_CELL = 40; +constexpr float GRID_TOP = 120; +constexpr float HALF = 0.5f; +constexpr int SHIELD_FRAMES_DEFAULT = 120; +constexpr uint32_t DEBUG_QUICK_KILL = 1 << 9; +constexpr int BOSS_ID_NONE_EXCLUDED_FIRST = 46; +constexpr int BOSS_ID_NONE_EXCLUDED_LAST = 52; +constexpr int BOSS_ID_EXCLUDED = 38; +constexpr int BOSS_ID_EXCLUDED_PAIR = 260; +constexpr int BOSS_ID_EXCLUDED_PAIR_VARIANT = 10; + +// The champion chances: any enemy, with Champion Belt, on the Void, and a boss's color. +constexpr float CHAMPION_CHANCE = 0.05f; +constexpr float CHAMPION_CHANCE_BELT = 0.2f; +constexpr float CHAMPION_CHANCE_VOID = 0.75f; +constexpr float CHAMPION_CHANCE_LATE_SPAWN = 0.2f; +constexpr float CHAMPION_CHANCE_VICTORY_LAP = 0.25f; +constexpr float CHAMPION_CHANCE_PURPLE_HEART = 3; + +// What a layer's bitflags say about it: drawn in the floor's dirt color, and wearing its champion sheet. +constexpr unsigned int LAYER_DIRT_COLORED = 1 << 0; +constexpr unsigned int LAYER_CHAMPION_SHEET = 1 << 4; +constexpr unsigned int SPRITE_UNKNOWN_FLAG_20 = 1 << 5; +constexpr unsigned int STATUS_SHARED = 1u << 31; +constexpr int TYPE_SPRITE_FLAG_A = 950; +constexpr int TYPE_SPRITE_FLAG_B = 960; +constexpr int VARIANT_SPRITE_FLAG_B = 4; +constexpr std::string_view CHAMPION_SUFFIX = "_champion"; +constexpr std::string_view STATUS_EFFECTS_ANM2 = "gfx/StatusEffects.anm2"; +constexpr size_t SHEET_EXTENSION_SIZE = 4; + +// The target search: how far enemies look for players, and what pushes a player back or pulls a twin forward. +constexpr float TARGET_RANGE = 5000; +constexpr float TARGET_INVINCIBLE_PENALTY = 400; +constexpr float TARGET_UNCONTROLLED_PENALTY = 800; +constexpr float TWIN_NEAR_SQUARED = 10000; +constexpr float BULB_CHARGE_BASE = 10000; +constexpr float BULB_CHARGE_STEP = 2000; +constexpr float BULB_DISTANCE_SCALE = 0.001f; +constexpr int TARGET_REFRESH_FRAMES = 15; +constexpr int DECOY_TIMER_MAX = 180; + +// The appear poof and the sizes of poofs and blood bursts by the NPC's size. +constexpr int APPEAR_POOF_FRAME = 1; +constexpr int APPEAR_SHOW_FRAME = 4; +constexpr int APPEAR_MIN_FRAMES = 20; +constexpr float APPEAR_FRICTION = 0.01f; +constexpr float TICK_HEALTH_MIN = 60; +constexpr float TICK_HEALTH_SCALE = 0.85f; +constexpr float POOF_SMALL_SIZE = 13; +constexpr float POOF_LARGE_SIZE = 18; +constexpr float POOF_LARGE_SHADOW = 30; +constexpr float POOF_HUGE_SIZE = 40; +constexpr float POOF_HUGE_SHADOW = 50; +constexpr float BLOOD_DEPTH_OFFSET = 10; +constexpr float PAUSE_SLOWDOWN = 0.6f; +constexpr float RIPPLE_SCALE = 0.05f; +constexpr float RIPPLE_DEPTH = -10; +constexpr float RIPPLE_SPEED = 0.5f; +constexpr int RIPPLE_FRAMES = 7; +constexpr float SLOW_FRICTION = 0.92f; +constexpr int WEAKNESS_FRAMES = 2; +constexpr int STATUS_REFRESH = -2; +constexpr int SLOW_TIMESCALE_EFFECT_FRAMES = 30; + +// The speed an NPC moves at: slowed by the stopwatch, the hourglass, its own slowing and Betrayal's charm. +constexpr float SPEED_HALF = 0.5f; +constexpr float SPEED_WEAKENED = 0.65f; +constexpr float SPEED_VANISHING_TWIN = 0.75f; + +// The champion color looks, sprite color, HP multiplier and scale, that the exe keeps at 00c354c0. +const ColorMod* champion_color_get(int championColor); + +// 0043ef30 Shoots one plain shot at a random circle angle. +ProjectileParams::ProjectileParams() : circleAngle(random_unit() * PI_F) {} + +// Plays a sound through the fart seeds. +void npc_sound_play(int sound, float volume, int frameDelay, float pitch) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = volume, .frameDelay = frameDelay, .pitch = pitch}); +} + +// The size class of the poofs and blood bursts an NPC leaves: 1 small to 4 huge, the last only when isHugeAllowed. +static int poof_size_get(Entity& entity, bool isHugeAllowed) +{ + int poof = entity.size < POOF_SMALL_SIZE ? 1 : 2; + if (entity.size >= POOF_LARGE_SIZE || entity.shadowSize > POOF_LARGE_SHADOW) poof = 3; + if (isHugeAllowed && (entity.size >= POOF_HUGE_SIZE || entity.shadowSize > POOF_HUGE_SHADOW)) poof = 4; + return poof; +} + +// Spawns an entity where an NPC stands. +static Entity* spawn_at(int type, int variant, int subType, const Vector& position, Entity* spawner) +{ + return g_game->Spawn({.position = position, + .spawner = spawner, + .subType = subType, + .type = type, + .variant = variant, + .seed = Random()}); +} + +// 00703950 The player nearest a position, the first on ties. +Entity_Player* game_nearest_player(const Vector& position) +{ + std::vector& players = g_game->playerManager.playerList; + Entity_Player* nearest = g_game->GetPlayer(0); + float best = vector_length_squared(vector_sub(position, nearest->pos)); + + for (size_t i = 1; i < players.size(); i++) + { + float distance = vector_length_squared(vector_sub(position, players[i]->pos)); + if (distance >= best) continue; + best = distance; + nearest = players[i]; + } + return nearest; +} + +// The charge Bulb drains a player for: one per full active, else its charges. +static int active_charges_get(Entity_Player& player) +{ + int charges = 0; + for (int slot = 0; slot < ACTIVE_SLOT_COUNT; slot++) + { + if (!g_manager->itemConfig.GetCollectible(player.activeItems[slot].item)) continue; + int maxCharge = player.GetActiveMaxCharge(slot); + if (maxCharge > 0) charges += maxCharge == 1 ? 1 : player.activeItems[slot].charge; + } + return charges; +} + +// What a target counts as from a position: its squared distance, pushed back while its player is invincible or (for +// Baby Plum) without control, pulled to a twin walking into the other, and for Bulb led by the active charge it holds. +static float target_score_get(const Vector& position, Entity* source, Entity& target, Entity_Player* player, + bool isBulb) +{ + float distance = vector_length_squared(vector_sub(target.pos, position)); + if (!player) return distance; + + Entity_Player* twin = player->twin_get(); + if (player->HasInvincibility(0, EntityRef())) distance += TARGET_INVINCIBLE_PENALTY; + else if ((!player->isControlsEnabled || player->controlsCooldown > 0) && source && source->type == ENTITY_BABY_PLUM) + distance += TARGET_UNCONTROLLED_PENALTY; + else if (twin) + { + Vector between = vector_sub(twin->pos, player->pos); + bool isMeeting = vector_dot(vector_add(player->velocity, twin->velocity), between) < 0 && + vector_length_squared(between) < TWIN_NEAR_SQUARED; + if (isMeeting) distance = vector_length_squared(vector_sub(twin->pos, position)) + 1; + } + if (!isBulb) return distance; + + float priority = std::max(BULB_CHARGE_BASE - (float)active_charges_get(*player) * BULB_CHARGE_STEP, 0.0f); + return distance * BULB_DISTANCE_SCALE + priority; +} + +// 007069a0 What an enemy at a position goes after: the nearest visible player within reach (Dark Esau only Jacob), +// else a Punching Bag or a baited enemy. An enemy forced onto a target keeps it. +// The stand-in targets players keep (Entity_Player 0x144c and 0x1450) wait for Entity_Player to name them. +Entity* game_nearest_target_player(const Vector& position, Entity* source, bool isPlayersOnly, bool isTargetDecoys, + float maxDistance) +{ + if (!isPlayersOnly && isTargetDecoys && source && source->IsEnemy()) + { + Entity* forced = static_cast(source)->forcedTarget; + if (forced) return forced; + } + + bool isBulb = source && source->type == ENTITY_SUCKER && source->variant == SUCKER_VARIANT_BULB; + isPlayersOnly = isPlayersOnly || isBulb; + isTargetDecoys = isTargetDecoys && !isBulb; + Entity* nearest = nullptr; + float best = maxDistance * maxDistance; + + for (Entity_Player* candidate : g_game->playerManager.playerList) + { + Entity_Player* twin = candidate->twin_get(); + bool isTwinLed = (candidate->playerType == PLAYER_LAZARUS_B || candidate->playerType == PLAYER_LAZARUS2_B) && + twin && twin->playerIndex != -1 && twin->playerIndex < candidate->playerIndex; + if (candidate->isCoopGhost || (candidate->isExists && isTwinLed && twin != candidate)) continue; + if (source && source->IsFriendly() && source->IsDamageSourceFriendly(EntityRef(candidate))) continue; + + Entity* target = candidate; + if (!isPlayersOnly && candidate->darkArtsLastSnare) target = candidate->darkArtsLastSnare->GetLastParent(); + Entity_Player* player = target && target->type == ENTITY_PLAYER ? static_cast(target) : nullptr; + if (!target) continue; + + bool isJacob = candidate->playerType == PLAYER_JACOB || candidate->playerType == PLAYER_JACOB_B || + candidate->playerType == PLAYER_JACOB2_B; + if (source && source->type == ENTITY_DARK_ESAU && !isJacob) continue; + if (target->type == ENTITY_FAMILIAR) + reconstruction_missing("Game::GetNearestTargetPlayer 007069a0: a familiar standing in for its player"); + if (player && player->IsInvisible()) continue; + + float score = target_score_get(position, source, *target, player, isBulb); + if (score >= best) continue; + best = score; + nearest = target; + } + if (isPlayersOnly) return nearest; + + if (isTargetDecoys) + { + for (Entity* decoy : g_game->room->entityList.mainEL) + { + if (decoy->type != ENTITY_FAMILIAR || decoy->variant != FAMILIAR_PUNCHING_BAG) continue; + float distance = vector_length_squared(vector_sub(decoy->pos, position)); + if (distance >= best) continue; + best = distance; + nearest = decoy; + } + } + if (g_game->room->entityList.isAnyBaited) + reconstruction_missing("Game::GetNearestTargetPlayer 007069a0: the baited enemies that draw attacks"); + if (source && source->type == ENTITY_BLOOD_PUPPY) + reconstruction_missing("Game::GetNearestTargetPlayer 007069a0: the Blood Puppy's prey"); + return nearest; +} + +// 00703670 Shakes the screen for a time. The controllers' rumble is not wired here. +void game_shake_screen(int timeout) +{ + g_game->screenShakeTimer = timeout; +} + +// 006d8240 Whether the run is on Hard or Greedier. +bool game_is_hard_mode() +{ + return g_game->difficulty == DIFFICULTY_HARD || g_game->difficulty == DIFFICULTY_GREEDIER; +} + +// 00703470 Remembers a boss as met this run, but for the ones the boss list leaves out. +static void game_encountered_boss_add(int bossType, int bossVariant) +{ + std::vector& bosses = g_game->encounteredBosses; + auto isSame = [&](const BossId& boss) { + return boss.type == bossType && boss.variant == bossVariant; + }; + if (std::ranges::any_of(bosses, isSame)) return; + + bool isListed = (bossType < BOSS_ID_NONE_EXCLUDED_FIRST || bossType > BOSS_ID_NONE_EXCLUDED_LAST) && + bossType != BOSS_ID_EXCLUDED && + (bossType != BOSS_ID_EXCLUDED_PAIR || bossVariant != BOSS_ID_EXCLUDED_PAIR_VARIANT); + if (isListed) bosses.push_back({bossType, bossVariant}); +} + +// 007f0780 The grid collision of the cell under a position, or of no cell outside the grid. +uint32_t room_grid_collision_at(const Vector& position) +{ + Room& room = *g_game->room; + int column = (int)((position.x - GRID_CELL) / GRID_CELL + HALF); + int row = (int)((position.y - GRID_TOP) / GRID_CELL + HALF); + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + return room.GetGridCollision(isInside ? room.gridWidth * row + column : -1); +} + +// What a line check meets in a cell: an outside cell is a wall, an empty one by its grid path (3000 to 3999 a pit, +// 1000 up blocked), else its grid entity's collision. The Beast's crawlspace blocks nothing. +static int line_cell_collision(Room& room, int column, int row) +{ + RoomConfig_Room* config = room.descriptor ? room.descriptor->data : nullptr; + if (config && config->type == ROOM_DUNGEON && config->stageId == STAGE_BEAST_DUNGEON) return COLLISION_NONE; + if (column < 0 || column >= room.gridWidth || row < 0 || row >= room.gridHeight) return COLLISION_WALL; + + int gridIndex = row * room.gridWidth + column; + if (GridEntity* grid = room.GetGridEntity(gridIndex)) return grid->collisionClass; + int path = room.GetGridPath(gridIndex); + if ((uint32_t)(path - GRID_PATH_PIT) < GRID_PATH_BAND) return COLLISION_PIT; + return path >= GRID_PATH_SOLID ? COLLISION_SOLID : COLLISION_NONE; +} + +// 007f0df0 Whether a line from start to end is clear, walked in steps of 10: mode 0 checks a 10 wide band for grid +// collision and for more than 8 cells walked past their grid path threshold, mode 3 the same band for shots (which +// fly over pits). The other modes, crushable rocks and the stop position are left to come. +bool room_check_line(const Vector& start, const Vector& end, int mode, int gridPathThreshold) +{ + if (mode != LINE_MODE_GROUND && mode != LINE_MODE_PROJECTILE) + reconstruction_missing("Room::CheckLine 007f0df0: the single cell modes"); + + Room& room = *g_game->room; + Vector step = vector_sub(start, end); + float length = vector_length(step); + if (length <= 0) return true; + + step = vector_scale(step, LINE_STEP / length); + auto cellOf = [](float value, float origin) { + return (int)((value - origin) / GRID_CELL + HALF); + }; + int startColumn = cellOf(start.x, GRID_CELL); + int startRow = cellOf(start.y, GRID_TOP); + bool isStartInside = + startColumn >= 0 && startColumn < room.gridWidth && startRow >= 0 && startRow < room.gridHeight; + int startIndex = isStartInside ? room.gridWidth * startRow + startColumn : -1; + + int blocked = 0; + Vector at = start; + for (float walked = 0; walked < length; walked += LINE_STEP) + { + at = vector_sub(at, step); + for (const LineCorner& corner : LINE_CORNERS) + { + int column = cellOf(at.x + corner.x, GRID_CELL); + int row = cellOf(at.y + corner.y, GRID_TOP); + int collision = line_cell_collision(room, column, row); + if (mode == LINE_MODE_PROJECTILE && collision == COLLISION_PIT) continue; + if (collision != COLLISION_NONE) return false; + + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int cornerIndex = isInside ? row * room.gridWidth + column : -1; + if (cornerIndex == startIndex) continue; + int path = cornerIndex >= 0 ? room.GetGridPath(cornerIndex) : 0; + if (mode == LINE_MODE_GROUND && path > gridPathThreshold) blocked++; + } + } + return blocked <= LINE_BLOCKED_MAX; +} + +// The suppression the console sets so its next spawned NPC is not rolled a champion (the original's 00c71670). +bool g_isChampionRollSkipped = false; + +// 006b8b20 Starts it appearing: every counter and link back to its defaults, its config loaded (Entity::Init), and +// a boss counted by the room. +void Entity_NPC::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) +{ + isChampion = false; + championColorIdx = CHAMPION_NONE; + flickerTimer = 0; + flickerState = 0; + flickerAlpha = 1; + championSpeed = 1; + bosscoloridx = -1; + isUnreachableOnce = false; + scale = 1; + shieldStrength = 0; + shieldFrames = SHIELD_FRAMES_DEFAULT; + deliriumBossType = 0; + deliriumBossVariant = 0; + deliriumTransformationTimer = 0; + deliriumRemainingAttacks = 0; + deliriumState = 0; + deliriumEntity = nullptr; + isBestiaryEncountered = false; + isDeathSoundAlt = false; + aiCallFlags = 0; + controllerID = -1; + unknownF2c = 0; + controllerMovement = {}; + aimTargetEffect = nullptr; + forwardVector = {}; + forcedTarget = nullptr; + forcedTargetTimer = 0; + sirenPlayerEntity = nullptr; + hitPointsMulti = 1; + scaleMulti = 1; + lastGridIndex = -1; + if (pickupGhostsEntity) pickupGhostsEntity->Remove(); + pickupGhostsEntity = nullptr; + if (salvationTarget) salvationTarget->Remove(); + salvationTarget = nullptr; + unknownF54 = nullptr; + killDamageEvents.clear(); + killDamage = 0; + killDamageFlags = 0; + + Entity::Init(entityType, entityVariant, entitySubType, seed); + AddEntityFlags(FLAG_APPEAR); + state = NPC_STATE_APPEAR; + savedState = NPC_STATE_INIT; + aiCallPhase = AI_PHASE_UPDATE; + stateFrame = 0; + aiCounter = 0; + appearFrames = 0; + decoyTargetTimer = 0; + groupIdx = -1; + targetPosition = {}; + confusionTargetPos = {}; + aiFloat = 1; + v1 = {}; + v2 = {}; + championRegenTimer = 0; + championRegenCount = 0; + holdCountdown = 0; + i1 = 0; + i2 = 0; + entityRef = nullptr; + projectileCooldown = 0; + projectileDelay = -1; + championTimer = 0; + holdPosition = {}; + isUnknownC61 = false; + isUnknownC62 = false; + floorColor = {}; + hitList.clear(); + secondaryHitList.clear(); + pathfinder.Reset(); + if (isBoss) reconstruction_missing("Entity_NPC::Init 006b8b20: the room's boss count (Room+0x7224)"); + totalDamageTaken = 0; + lua_callback_check(CALLBACK_POST_NPC_INIT, "Entity_NPC::Init 006b8b20: MC_POST_NPC_INIT"); +} + +// The odds a boss spawns in one of its alternate colors. +static float boss_color_chance_get() +{ + Game& game = *g_game; + float chance = g_manager->persistentGameData.Unlocked(ACHIEVEMENT_MORE_BOSS_COLORS) ? 0.3f : 0.1f; + if (game.difficulty == DIFFICULTY_GREEDIER) chance = 0.6f; + if (game.playerManager.AnyoneHasTrinket(TRINKET_PURPLE_HEART_ID)) + chance *= (float)game.playerManager.GetTrinketMultiplier(TRINKET_PURPLE_HEART_ID) * 2; + if (game.challenge == CHALLENGE_ULTRA_HARD || game.victoryLap > 0) chance = 1; + return chance; +} + +// Part of 006bb790: a boss rolls one of its alternate colors from the room's spawn seed (its subtype, 1 up), the +// Repentance stages fix Monstro's and Gurdy Jr's, and a color that loads swaps in its sheet, scale and health. +void Entity_NPC::boss_color_roll() +{ + Game& game = *g_game; + int colors = (int)config->bossColors.size(); + if (spawnerEntity && spawnerEntity->type == ENTITY_BIG_HORN) colors = 0; + + if (g_isChampionRollSkipped) + { + colors = 0; + g_isChampionRollSkipped = false; + } + else if (colors > 0 && subtype == 0 && g_manager->persistentGameData.Unlocked(ACHIEVEMENT_BOSS_COLORS)) + { + RoomDescriptor* descriptor = game.room->descriptor; + RNG rng = {descriptor ? descriptor->spawnSeed : 0, 1, 11, 16}; + if (rng.RandomFloat() < boss_color_chance_get()) subtype = (int)rng.RandomInt(colors) + 1; + if (config->id == ENTITY_MONSTRO && subtype == 2 && game.challenge == CHALLENGE_BEANS) subtype = 0; + } + if (game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B) + { + if (config->id == ENTITY_MONSTRO) subtype = 3; + else if (config->id == ENTITY_GURDY_JR) subtype = 1; + } + if (subtype == 0 || subtype > colors) return; + + EntityConfig_BossColor color = config->bossColors[subtype - 1]; + bosscoloridx = subtype - 1; + sprite.scale = vector_scale(sprite.scale, color.scale); + scale = color.scale; + maxHitPoints *= color.hpMultiplier; + ResetColor(); + load_graphics(true); + sprite.SetFrame(sprite.GetDefaultAnimationName(), 0); +} + +// 006bb790 Loads its config and sprite, then rolls whether it spawns a champion, or a boss's alternate color. +void Entity_NPC::LoadEntityConfig() +{ + RNG rng = {initSeed, 1, 5, 16}; + isBoss = false; + Entity::LoadEntityConfig(); + if (!config) + { + log_printf(LOG_INFO, "[warn] No entity config for NPC %d.%d\n", type, variant); + return; + } + + load_graphics(true); + sprite.scale = vector_make(1, 1); + if (sprite.SetAnimation(sprite.GetDefaultAnimationName(), SWITCH_KEEP_FRAME) && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(0); + sprite.animState.isPlaying = false; + } + isCanShutDoors = config->isShutDoors; + isBoss = config->isBoss; + shieldStrength = config->shieldStrength; + shieldFrames = config->shieldFrames; + + Game& game = *g_game; + Room& room = *game.room; + float chance = game.playerManager.FirstCollectibleOwner(COLLECTIBLE_CHAMPION_BELT_ID, LAZARUS_SHARE_CHECK) + ? CHAMPION_CHANCE_BELT + : CHAMPION_CHANCE; + if (game.stage == STAGE_VOID) chance = CHAMPION_CHANCE_VOID; + if (game.playerManager.AnyoneHasTrinket(TRINKET_PURPLE_HEART_ID)) + chance *= + (float)game.playerManager.GetTrinketMultiplier(TRINKET_PURPLE_HEART_ID) * CHAMPION_CHANCE_PURPLE_HEART; + if (room.isInitialized) chance *= CHAMPION_CHANCE_LATE_SPAWN; + if (game.seedEffects.HasSeedEffect(SEED_ALL_CHAMPIONS)) chance = 1; + + if (isBoss) boss_color_roll(); + else + { + bool isAllowed = config->isCanBeChampion && !isChampion && !room.isInitialized && + !room.has_room_config_flag(ROOM_CONFIG_FLAG_NO_CHAMPIONS) && + (room.roomType != ROOM_BOSS || type != ENTITY_ULTRA_GREED_DOOR); + if (isAllowed && (rng.RandomFloat() < chance || game.challenge == CHALLENGE_ULTRA_HARD || + (game.victoryLap > 0 && rng.RandomFloat() < CHAMPION_CHANCE_VICTORY_LAP))) + isChampion = true; + } + + if (g_isChampionRollSkipped) + { + isChampion = false; + g_isChampionRollSkipped = false; + } + else if (isChampion) MakeChampion(rng.Next(), championColorIdx, true); +} + +// 006b9c10 A layer's sheet with the champion suffix and the stage's floor suffix put before its extension, the first +// of (both, champion only, floor only) a mod or the resources hold, else the sheet itself. isChampionSheet says +// whether the one found has the champion suffix. +static std::string sheet_path_resolve(const std::string& path, std::string_view floorSuffix, + std::string_view championSuffix, bool& isChampionSheet) +{ + isChampionSheet = false; + if (path.size() < SHEET_EXTENSION_SIZE || (floorSuffix.empty() && championSuffix.empty())) return path; + + std::string stem = path.substr(0, path.size() - SHEET_EXTENSION_SIZE); + std::string extension = path.substr(path.size() - SHEET_EXTENSION_SIZE); + auto isFound = [&](const std::string& candidate) { + return std::filesystem::exists(resource_path(g_manager->modManager.TryRedirectPath(candidate))); + }; + + std::string both = stem + std::string(championSuffix) + std::string(floorSuffix) + extension; + if (!championSuffix.empty() && !floorSuffix.empty() && isFound(both)) + { + isChampionSheet = true; + return both; + } + std::string champion = stem + std::string(championSuffix) + extension; + if (!championSuffix.empty() && isFound(champion)) + { + isChampionSheet = true; + return champion; + } + std::string floor = stem + std::string(floorSuffix) + extension; + return !floorSuffix.empty() && isFound(floor) ? floor : path; +} + +// 006baf40 Reloads its sprite (with isReloadAnm2, from the config or its boss color's .anm2) and swaps each layer's +// sheet for its champion and floor versions, marking the layers drawn in the floor's dirt color. +void Entity_NPC::load_graphics(bool isReloadAnm2) +{ + bool isBossColor = bosscoloridx >= 0 && bosscoloridx < (int)config->bossColors.size(); + if (isReloadAnm2) + { + bool isColorAnm2 = isBossColor && !config->bossColors[bosscoloridx].anm2Path.empty(); + sprite.Load(isColorAnm2 ? config->bossColors[bosscoloridx].anm2Path : config->anm2Path, GRAPHICS_DEFER); + if (g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && type == ENTITY_ISAAC_BOSS && variant == 1) + sprite.Load(GFUEL_ISAAC_ANM2, GRAPHICS_LOAD); + } + + std::string floorSuffix; + if (isBossColor) floorSuffix = config->bossColors[bosscoloridx].suffix; + else if (config->isHasFloorAlts) floorSuffix = g_game->roomConfig.stages[Level::GetStageID()].suffix; + const ColorMod* championLook = isChampion ? champion_color_get(championColorIdx) : nullptr; + std::string_view championSuffix = championLook ? CHAMPION_SUFFIX : ""; + bool isChampionSheetUsed = false; + bool isDirtUsed = false; + + for (int i = 0; i < (int)sprite.layerStates.size(); i++) + { + LayerState& layer = sprite.layerStates[i]; + std::string name = layer.layerData ? layer.layerData->name : ""; + if (name == DIRT_LAYER || name == HOLE_LAYER) + { + layer.bitflags |= LAYER_DIRT_COLORED; + isDirtUsed = true; + } + if (name == HOLE2_LAYER) layer.bitflags |= LAYER_DIRT_COLORED; + + bool isChampionSheet = false; + std::string sheet = layer.layerData ? layer.layerData->spriteSheetPath : ""; + sprite.ReplaceSpritesheet(i, sheet_path_resolve(sheet, floorSuffix, championSuffix, isChampionSheet)); + LayerState& replaced = sprite.layerStates[i]; + replaced.bitflags = + isChampionSheet ? replaced.bitflags | LAYER_CHAMPION_SHEET : replaced.bitflags & ~LAYER_CHAMPION_SHEET; + isChampionSheetUsed = isChampionSheetUsed || isChampionSheet; + } + sprite.championColor = isChampionSheetUsed && championLook ? *championLook : ColorMod{}; + + bool isFlagged = type == TYPE_SPRITE_FLAG_A || (type == TYPE_SPRITE_FLAG_B && variant == VARIANT_SPRITE_FLAG_B); + sprite.bitflags = isFlagged ? sprite.bitflags | SPRITE_UNKNOWN_FLAG_20 : sprite.bitflags & ~SPRITE_UNKNOWN_FLAG_20; + sprite.LoadGraphics(); + if (isDirtUsed) UpdateDirtColor(true); +} + +// 006c04b0 Lerps its dirt layers toward the floor color under it (Room::GetFloorColorAt doubled), sampled every 15 +// frames unless isImmediate. A green champion's dirt is green. +void Entity_NPC::UpdateDirtColor(bool isImmediate) +{ + if (isImmediate || IsFrame(DIRT_SAMPLE_FRAMES, (int)index)) + { + if (!isChampion || championColorIdx != CHAMPION_GREEN) + reconstruction_missing("Entity_NPC::UpdateDirtColor 006c04b0: Room::GetFloorColorAt"); + dirtColor._tint[0] = 0; + dirtColor._tint[1] = DIRT_GREEN; + dirtColor._tint[2] = 0; + dirtColor._tint[3] = 1; + } + + for (int i = 0; i < (int)sprite.layerStates.size(); i++) + { + LayerState& layer = sprite.layerStates[i]; + std::string name = layer.layerData ? layer.layerData->name : ""; + if (name == DIRT_LAYER || name == HOLE_LAYER) + layer.color = color_lerp(layer.color, dirtColor, isImmediate ? 1 : DIRT_LERP); + } +} + +// 006d0300 Switches to another of its boss colors, reloading its sprite on its default animation's first frame. +void Entity_NPC::SetBossColorIdx(int bossColorIdx, int) +{ + if (bosscoloridx != bossColorIdx) + { + bosscoloridx = bossColorIdx; + load_graphics(true); + if (sprite.SetAnimation(sprite.GetDefaultAnimationName(), SWITCH_KEEP_FRAME) && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(0); + sprite.animState.isPlaying = false; + } + } + ResetColor(); +} + +// 006d03e0 +void Entity_NPC::MakeChampion(uint32_t, int, bool) +{ + reconstruction_missing("Entity_NPC::MakeChampion 006d03e0"); +} + +// 00c354c0 (data) The table of champion looks. +const ColorMod* champion_color_get(int championColor) +{ + if (championColor < 0 || championColor >= CHAMPION_COUNT) return nullptr; + reconstruction_missing("Entity_NPC champion colors: the table at 00c354c0"); +} + +// The enemy a "random enemy" spawn (type 306) turns into on each stage, on Normal and on Hard. +struct StageEnemy +{ + int normalType; + int normalVariant; + int hardType; + int hardVariant; +}; + +constexpr int REDIRECT_RANDOM_ENEMY = 306; +constexpr std::array STAGE_RANDOM_ENEMIES = {{ + {85, 0, 94, 0}, + {10, 0, 284, 0}, + {85, 0, 94, 0}, + {10, 0, 284, 0}, + {21, 0, 23, 0}, + {26, 0, 26, 1}, + {23, 0, 23, 1}, + {209, 0, 227, 0}, + {227, 0, 24, 1}, + {24, 0, 277, 0}, + {15, 0, 58, 0}, + {58, 0, 39, 0}, + {39, 0, 39, 1}, + {297, 0, 297, 0}, + {87, 0, 252, 0}, + {26, 2, 55, 2}, + {48, 1, 50, 1}, + {267, 0, 410, 0}, +}}; +constexpr std::array GREED_RANDOM_ENEMIES = {{ + {10, 0, 284, 0}, + {21, 0, 23, 0}, + {209, 0, 227, 0}, + {15, 0, 58, 0}, + {87, 0, 252, 0}, + {50, 0, 50, 1}, +}}; +constexpr int GREED_RANDOM_ENEMY_DEFAULT = 299; +constexpr int STAGE_RANDOM_ENEMY_BLUE_WOMB = 26; +constexpr StageEnemy BLUE_WOMB_RANDOM_ENEMY = {412, 0, 412, 0}; + +// Normal or Greed (the easy ones) against Hard or Greedier. +static bool is_easy_difficulty() +{ + return g_game->difficulty == DIFFICULTY_NORMAL || g_game->difficulty == DIFFICULTY_GREED; +} + +// 006c07e0 Swaps an enemy about to spawn for what it stands for: Bulbs (61.5) for flies until they are unlocked, the +// placeholder types (299 to 306) for their difficulty's or stage's enemy until the redirects are unlocked, and with +// G-Fuel a few enemies for their variants. True when it picked a placeholder's enemy. +bool Entity_NPC::Redirect(int* entityType, int* entityVariant) +{ + PersistentGameData& data = g_manager->persistentGameData; + if (!data.Unlocked(ACHIEVEMENT_MORE_BOSS_COLORS) && *entityType == ENTITY_SUCKER && + *entityVariant == SUCKER_VARIANT_BULB) + { + *entityType = ENTITY_FLY; + *entityVariant = 0; + } + + bool isEasy = is_easy_difficulty(); + auto redirect = [&](int newType, int newVariant) { + *entityType = newType; + *entityVariant = newVariant; + return true; + }; + auto byDifficulty = [&](const StageEnemy& enemy) { + return isEasy ? redirect(enemy.normalType, enemy.normalVariant) : redirect(enemy.hardType, enemy.hardVariant); + }; + + if (!data.Unlocked(ACHIEVEMENT_REDIRECTS)) + { + switch (*entityType) + { + case 303: + return isEasy ? redirect(29, 1) : redirect(250, 0); + case 300: + return redirect(27, 0); + case 305: + return redirect(29, 0); + case 231: + *entityVariant = 0; + return true; + case 301: + return redirect(32, 0); + case 302: + return redirect(isEasy ? 208 : 257, 0); + case 304: + return redirect(isEasy ? 240 : 242, 0); + case REDIRECT_RANDOM_ENEMY: + if (g_game->IsGreedMode()) + { + int stage = (int)g_game->stage; + bool isListed = stage >= 1 && stage <= (int)GREED_RANDOM_ENEMIES.size(); + return isListed ? byDifficulty(GREED_RANDOM_ENEMIES[stage - 1]) + : redirect(GREED_RANDOM_ENEMY_DEFAULT, 0); + } + { + int stage = g_game->room->GetRoomConfigStage(); + if (stage == STAGE_RANDOM_ENEMY_BLUE_WOMB) return byDifficulty(BLUE_WOMB_RANDOM_ENEMY); + if (stage >= 0 && stage < (int)STAGE_RANDOM_ENEMIES.size()) + return byDifficulty(STAGE_RANDOM_ENEMIES[stage]); + } + break; + } + } + + if (!g_game->seedEffects.HasSeedEffect(SEED_G_FUEL)) return false; + switch (*entityType) + { + case 27: + *entityVariant = 1; + break; + case 204: + *entityType = 247; + break; + case 859: + *entityType = 25; + *entityVariant = 1; + break; + case 221: + *entityType = 58; + break; + } + return false; +} + +// 006c0f30 Turns it into another entity in place: its config and color reloaded, its health refilled, its champion +// kept only where the new one can be one. An enemy the run erased leaves in a poof. +void Entity_NPC::Morph(int entityType, int entityVariant, int entitySubType, int championId) +{ + bool isSame = entityType == type && entityVariant == variant && entitySubType == subtype && + (championId < 0 || championId == championColorIdx); + if (isSame) return; + + type = entityType; + variant = entityVariant; + subtype = entitySubType; + if (championId >= 0) + { + championColorIdx = championId; + isChampion = true; + } + EntityConfig_Entity* found = g_manager->entityConfig.GetEntity(entityType, entityVariant, entitySubType); + if (found && !found->isCanBeChampion) + { + championColorIdx = CHAMPION_NONE; + isChampion = false; + } + + flickerTimer = 0; + championRegenTimer = 0; + flickerState = 0; + flickerAlpha = 1; + championSpeed = 1; + championTimer = 0; + ResetColor(); + scale = 1; + sprite.scale = vector_make(shrinkStatus1, shrinkStatus1); + LoadEntityConfig(); + totalDamageTaken = 0; + health = hitPointsMulti * maxHitPoints; + if (!colorParams.empty()) SetColor(COLOR_DEFAULT, 1, MORPH_COLOR_PRIORITY, false, true); + pathfinder.Reset(); + g_manager->persistentGameData.TryAddBestiaryEncounter(type, variant); + isBestiaryEncountered = true; + if (game_is_enemy_erased(*this)) Entity::RemoveWithPoof(this); +} + +// 007078f0 Whether the run erased this kind of enemy (Eraser). A friendly enemy is never erased. +bool game_is_enemy_erased(Entity& entity) +{ + if (entity.type == ENTITY_ERASE_EXEMPT || (Entity::is_enemy_type(entity.type) && entity.IsFriendly())) return false; + if (g_game->erasedEntities.empty()) return false; + reconstruction_missing("Game::ShouldEraseEnemy 007078f0: FixErasedEnemyID"); +} // 006c4ac0 Remembers where it was, and keeps the Exorcist's room in its state while it lives. void Entity_NPC::PreUpdate() @@ -35,110 +1058,1501 @@ bool Entity_NPC::IsBoss() // 006a8240 Forgets where its pathfinder was taking it. void Entity_NPC::ResetPathFinderTarget() { - pathfinder._movementTarget = {}; - pathfinder._moveDirection = {}; + pathfinder.movementTarget = {}; + pathfinder.moveDirection = {}; } // 006d6610 Scales it, shrinking included. void Entity_NPC::SetScale(float newScale) { scale = newScale; - float spriteScale = newScale * shrinkStatus1; - sprite.scale = vector_make(spriteScale, spriteScale); + sprite.scale = vector_make(newScale * shrinkStatus1, newScale * shrinkStatus1); +} + +// 006b9910 Sends it after a target for a time, unless forced targets are on cooldown or the one it has is nearer. +bool Entity_NPC::TryForceTarget(Entity* newTarget, int duration) +{ + if (forcedTargetTimer < 0) return false; + + Entity* current = forcedTarget; + bool isKept = current == newTarget; + if (!isKept && current) + { + float currentDistance = vector_length_squared(vector_sub(pos, current->pos)); + if (currentDistance <= vector_length_squared(vector_sub(pos, newTarget->pos))) return false; + } + if (!isKept) forcedTarget = newTarget; + forcedTargetTimer = duration; + return true; +} + +// 006d6ba0 Plays a sound, higher for a tiny champion and lower for a giant one. +void Entity_NPC::PlaySound(int id, float volume, int frameDelay, bool isLoop, float pitch) +{ + if (championColorIdx == CHAMPION_TINY) pitch += 0.5f; + else if (championColorIdx == CHAMPION_GIANT) pitch *= 0.5f; + seed_fart_sound_override(&id); + g_manager->sfxManager.Play( + id, {.volume = volume, .frameDelay = frameDelay, .loop = isLoop ? SOUND_LOOP : SOUND_ONCE, .pitch = pitch}); +} + +// 006b64d0 Leaves a blood splat of a size where it stands. +Entity_Effect* Entity_NPC::MakeSplat(float size) +{ + Entity* splat = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_SPLAT, 0, pos, this); + splat->sprite.scale = vector_make(size, size); + splat->Update(); + return static_cast(splat); +} + +// 006d6c20 The enemies its side still faces: the room's living enemies, or for a friendly one the friendly enemies. +int Entity_NPC::GetAliveEnemyCount() +{ + if (!IsFriendly()) return g_game->room->GetAliveEnemiesCount(); + + int count = 0; + for (Entity* entity : g_game->room->entityList.mainEL) + if (Entity::is_enemy_type(entity->type) && !entity->isDead && entity->IsFriendly()) count++; + return count; +} + +// 006d48a0 The way it faces: the forward vector an AI set, else down for a few, else along its motion. +Vector Entity_NPC::GetForwardVector() +{ + if (!vector_is_zero(forwardVector)) return forwardVector; + if (type == ENTITY_FORWARD_NONE) return {}; + if (type == ENTITY_FORWARD_DOWN_A || type == ENTITY_FORWARD_DOWN_B) return vector_make(0, 1); + return Entity::GetForwardVector(); +} + +// Part of 006c4b30: shows the status effect it suffers on its OverlayEffect null, most important first. The +// shadow champion charger is never charmed, and Crown and Skull mark the king and death champions. +void Entity_NPC::status_overlay_update() +{ + bool isShadowCharger = type == ENTITY_SHADOW_CHARGER && variant == 0 && subtype == SHADOW_CHARGER_SUBTYPE; + TemporaryEffects& roomEffects = g_game->room->temporaryEffects; + bool isTimeSlowed = roomEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) || + roomEffects.HasCollectibleEffect(COLLECTIBLE_HOURGLASS_ID) || + (g_game->challenge != CHALLENGE_SLOW && g_game->room->brokenWatchState == BROKEN_WATCH_SLOW); + bool isTimeImmune = (flags & (FLAG_FRIENDLY | FLAG_NO_STATUS_EFFECTS)) && type != ENTITY_DEATHS_HEAD; + + std::string_view animation; + bool isShared = false; + if (championColorIdx == CHAMPION_KING) animation = "Crown"; + else if (championColorIdx == CHAMPION_DEATH) animation = "Skull"; + isShared = !animation.empty(); + + if (HasEntityFlags(FLAG_CHARM) && !isShadowCharger) animation = "Charm", isShared = true; + else if (HasEntityFlags(FLAG_BRIMSTONE_MARKED)) animation = "BrimstoneCurse", isShared = true; + else if (HasEntityFlags(FLAG_MAGNETIZED)) animation = "Magnetize", isShared = true; + else if (HasEntityFlags(FLAG_BAITED)) animation = "Bait", isShared = false; + else if (HasEntityFlags(FLAG_CONFUSION)) animation = "Confuse", isShared = true; + else if (HasEntityFlags(FLAG_BURN)) animation = "Burning", isShared = false; + else if (HasEntityFlags(FLAG_POISON)) animation = "Poison", isShared = true; + else if (HasEntityFlags(FLAG_FEAR)) animation = "Fear", isShared = true; + else if (HasEntityFlags(FLAG_BLEED_OUT)) animation = "BleedingOut", isShared = true; + else if (HasEntityFlags(FLAG_SLOW) || (isTimeSlowed && !isTimeImmune)) animation = "Slow", isShared = true; + else if (HasEntityFlags(FLAG_WEAKNESS)) animation = "Weakness", isShared = true; + else if (type == ENTITY_SIREN_HELPER) animation = "EnemyCharm", isShared = true; + else if (animation.empty()) + { + if (statusEffectSprite.animState.animData) statusEffectSprite.animState.isPlaying = false; + return; + } + + if (!statusEffectSprite.isLoaded) statusEffectSprite.Load(STATUS_EFFECTS_ANM2, GRAPHICS_LOAD); + if (statusEffectSprite.IsPlaying() && statusEffectSprite.isLoaded) + { + statusEffectSprite.animState.Update(statusEffectSprite.playbackSpeed); + statusEffectSprite.overlayAnimState.Update(statusEffectSprite.playbackSpeed); + } + statusEffectSprite.Play(animation); + statusEffectSprite.bitflags = isShared ? STATUS_SHARED : 0; +} + +// Part of 006c4b30: stopped by a pause or held (Lil Abaddon, a hook), it stays put and slows, its AI's pre-update +// call and the base update still run (without its sprite), and it goes on with the update only if that killed it. +// False when the update stops here. +bool Entity_NPC::paused_update() +{ + if (vector_is_zero(pausePosition)) pausePosition = pos; + if (pauseTimer > 0 && --pauseTimer > 0) pos = pausePosition; + velocity = vector_scale(velocity, PAUSE_SLOWDOWN); + + bool wasDead = isDead; + spawn_damage_numbers(); + update_damage_history(); + if (aiCallFlags & AI_CALL_PRE_UPDATE) ai_call(AI_PHASE_PRE_UPDATE); + + float healthBefore = health; + bool isSpriteFrozen = HasEntityFlags(FLAG_NO_SPRITE_UPDATE); + AddEntityFlags(FLAG_NO_SPRITE_UPDATE); + Entity::Update(); + if (!isSpriteFrozen) ClearEntityFlags(FLAG_NO_SPRITE_UPDATE); + totalDamageTaken += std::max(healthBefore - health, 0.0f); + return wasDead != isDead; +} + +// Runs the AI in a phase other than the update's own. +void Entity_NPC::ai_call(AiPhase phase) +{ + aiCallPhase = phase; + npc_ai_update(*this); + aiCallPhase = AI_PHASE_UPDATE; +} + +// Part of 006c4b30: the first appear frame runs the AI's init (a champion's or Tick's changes with it), the second +// poofs it in, the fourth shows it playing Appear, and once that ends (20 frames at least) its AI takes over. +void Entity_NPC::appear_update() +{ + if (appearFrames == 0) appear_init(); + else if (appearFrames == APPEAR_POOF_FRAME) + { + Entity* poof = spawn_at(ENTITY_EFFECT, EFFECT_POOF01, poof_size_get(*this, false), pos, this); + poof->posOffset = posOffset; + poof->renderDepthOffset = posOffset.y + 1; + if (isChampion && championColorIdx < CHAMPION_COUNT) + reconstruction_missing("Entity_NPC::Update 006c4b30: a champion's appear poof color (GetColorWithFlash)"); + + int sound = isDeathSoundAlt ? SOUND_SUMMON_POOF : SOUND_SUMMONSOUND; + g_manager->sfxManager.Stop(sound); + PlaySound(sound, 1, 2, false, 1); + if (type == APPEAR_SOUND_TYPE_A || type == APPEAR_SOUND_TYPE_B || (type == ENTITY_BIG_HORN && variant == 0)) + reconstruction_missing("Entity_NPC::Update 006c4b30: a Repentance boss's appear sounds"); + } + else if (appearFrames == APPEAR_SHOW_FRAME) + { + if (type != ENTITY_PIN) isVisible = true; + if (sprite.GetAnimationData("Appear")) + { + if (type != APPEAR_OVERLAY_KEPT_TYPE) sprite.RemoveOverlay(); + sprite.Play("Appear", PLAY_FORCED); + } + } + else + { + bool isAppearing = + sprite.GetAnimationData("Appear") && !sprite.IsFinished("Appear") && sprite.GetAnimation() == "Appear"; + if (appearFrames >= APPEAR_MIN_FRAMES && !isAppearing) + { + state = savedState; + friction = baseFriction; + } + } + + if (std::ranges::find(APPEAR_EVENT_TYPES, type) != APPEAR_EVENT_TYPES.end()) + reconstruction_missing("Entity_NPC::Update 006c4b30: a Repentance boss's appear events"); + if (state == NPC_STATE_APPEAR) friction *= APPEAR_FRICTION; + appearFrames++; +} + +// Part of 006c4b30: the AI's init call on the first appear frame, with what spawning does to it. +void Entity_NPC::appear_init() +{ + state = NPC_STATE_INIT; + if (championColorIdx == CHAMPION_WHITE) + { + isInvincible = true; + AddEntityFlags(FLAG_NO_STATUS_EFFECTS); + } + npc_ai_update(*this); + if (championColorIdx == CHAMPION_FLY_PROTECTED || championColorIdx == CHAMPION_RAINBOW) + spawn_at(ENTITY_ETERNAL_FLY, 0, 0, pos, this)->parent = this; + if (HasEntityFlags(FLAG_APPEAR)) + { + isVisible = false; + savedState = state; + state = NPC_STATE_APPEAR; + } + + PlayerManager& players = g_game->playerManager; + if (players.AnyoneHasTrinket(TRINKET_TICK_ID) && type != TYPE_NO_TICK_A && type != TYPE_NO_TICK_B && + health > TICK_HEALTH_MIN) + for (int i = 0; i < players.GetTrinketMultiplier(TRINKET_TICK_ID); i++) health *= TICK_HEALTH_SCALE; + + auto isDirt = [](const LayerState& layer) { + return layer.layerData && (layer.layerData->name == DIRT_LAYER || layer.layerData->name == HOLE_LAYER); + }; + if (std::ranges::any_of(sprite.layerStates, isDirt)) UpdateDirtColor(true); + if (IsBoss() && !parent) game_encountered_boss_add(type, variant); +} + +// Part of 006c4b30: a boss or Chub dying through its death animations, which ends it (trigger_kill_item_effects). +void Entity_NPC::death_animation_update() +{ + if (state != NPC_STATE_DEATH && state != NPC_STATE_UNIQUE_DEATH) return; + + friction *= APPEAR_FRICTION; + if (stateFrame == 0) death_animation_start(); + stateFrame++; + if (std::ranges::find(DEATH_EVENT_TYPES, type) != DEATH_EVENT_TYPES.end()) + reconstruction_missing("Entity_NPC::Update 006c4b30: a boss's death animation events"); + + if (sprite.GetNullFrame("BloodGuide")) + reconstruction_missing("Entity_NPC::Update 006c4b30: the blood guided gibs of a death animation"); + if (type == ENTITY_HUSH && sprite.IsEventTriggered("ash")) + reconstruction_missing("Entity_NPC::Update 006c4b30: the ash a boss leaves"); + if (sprite.IsFinished() && isExists) trigger_kill_item_effects(); +} + +// Part of 006c4b30: the first frame of the death states: a flushed boss plays Flush, the rest Death, or bursts +// where it has none. +void Entity_NPC::death_animation_start() +{ + bool isFlushable = std::ranges::find(FLUSH_TYPES, type) != FLUSH_TYPES.end() || + (type == FLUSH_PROP_TYPE && variant == FLUSH_PROP_VARIANT); + if (state == NPC_STATE_UNIQUE_DEATH) + { + if (!isFlushable) return; + if (sprite.GetAnimationData("Flush")) + { + sprite.Play("Flush"); + renderZOffset = FLUSH_RENDER_Z; + return; + } + state = NPC_STATE_DEATH; + } + + if (sprite.GetAnimationData("Death")) + { + if (type == ENTITY_BIG_HORN || type == DEATH_HEAD_LAYER_TYPE) + reconstruction_missing("Entity_NPC::Update 006c4b30: Big Horn's and its kin's death animations"); + sprite.Play("Death"); + return; + } + if (type == ENTITY_CHUB || type == ENTITY_LARRYJR || type == ENTITY_PIN || type == ENTITY_TURDLET) + reconstruction_missing("Entity_NPC::Update 006c4b30: a segmented boss's death animations"); + if (type >= DEATH_NO_BURST_FIRST && type <= DEATH_NO_BURST_LAST) return; + BloodExplode(); + trigger_kill_item_effects(); +} + +// Part of 006c4b30: a charmed enemy's attention drifts to a Punching Bag it targets for up to 180 frames, then away +// for as long, before the bag can draw it again. +void Entity_NPC::decoy_update() +{ + if (decoyTargetTimer > DECOY_TIMER_MAX) decoyTargetTimer = -1; + else if (decoyTargetTimer < -DECOY_TIMER_MAX) decoyTargetTimer = 0; + + Entity* playerTarget = GetPlayerTarget(); + if (playerTarget->type == ENTITY_FAMILIAR && playerTarget->variant == FAMILIAR_PUNCHING_BAG) decoyTargetTimer++; + else if (decoyTargetTimer != 0) decoyTargetTimer--; +} + +// Part of 006c4b30: what a champion's color does each frame (the fly-spawning, flickering, regenerating, pulsing, +// creep and shot champions), and Wrath's twin flicker. +void Entity_NPC::champion_update() +{ + if (isChampion || type == ENTITY_FLICKER_TYPE) + reconstruction_missing("Entity_NPC::Update 006c4b30: the champion colors' effects"); + if (HasEntityFlags(FLAG_SHRINK) && shrinkCountdown >= 1 && shrinkCountdown < SHRINK_PULSE_FRAMES) + reconstruction_missing("Entity_NPC::Update 006c4b30: the shrinking pulse"); +} + +// Part of 006c4b30: in a room that checks it, an enemy no grounded player has a path to stops holding the doors +// after its second miss, checked every 60 frames once 900 frames passed. +void Entity_NPC::unreachable_update() +{ + Room& room = *g_game->room; + if (!room.isUnknown11f5) return; + + bool isGrounded = !isDead && !isBoss && !IsFlying() && entityGridCollisionClass != GRIDCOLL_NOPITS && + type != ENTITY_UNREACHABLE_EXEMPT; + int frames = room.GetFrameCount(); + if ((uint32_t)(frames + (int)index) % UNREACHABLE_CHECK_FRAMES != 0 || frames <= UNREACHABLE_GRACE_FRAMES || + !isGrounded) + return; + if (room.roomType != ROOM_DEFAULT || room.IsClear() || any_player_flying()) return; + + for (Entity_Player* player : g_game->playerManager.playerList) + if (!player->IsFlying() && pathfinder.HasPathToPos(player->pos, true)) return; + if (!isUnreachableOnce) isUnreachableOnce = true; + else isCanShutDoors = false; +} + +// 009be9c0 Whether a living player moves over pits (its grid collision ignores them). +bool any_player_flying() +{ + for (Entity_Player* player : g_game->playerManager.playerList) + if (!player->isCoopGhost && player->entityGridCollisionClass <= GRIDCOLL_WALLS) return true; + return false; +} + +// Part of 006c4b30: the frame it dies: its burst, Midas' coins, its death triggers (rewards and the players' on-kill +// items), Toxic Shock's creep, then its removal, or a boss's death animation. In a crawlspace it drops off a ladder. +void Entity_NPC::dead_update() +{ + PlayDeathEffects(); + if (HasEntityFlags(FLAG_MIDAS_FREEZE) && !HasEntityFlags(FLAG_NO_REWARD)) midas_coins_spawn(); + if (!HasEntityFlags(FLAG_NO_DEATH_TRIGGER)) + { + trigger_death_rewards(); + for (Entity_Player* player : g_game->playerManager.playerList) player->trigger_npc_death(this); + } + toxic_shock_creep_spawn(); + if (!isBoss && type != ENTITY_CHUB) trigger_kill_item_effects(); + else + { + state = NPC_STATE_DEATH; + stateFrame = 0; + } + if (g_game->room->roomType == ROOM_DUNGEON && !IsFlying()) + reconstruction_missing("Entity_NPC::Update 006c4b30: a crawlspace enemy dropping off its ladder"); +} + +// Part of 006c4b30: a gold enemy's coins, one to three (none to two for a coin hearted player). +void Entity_NPC::midas_coins_spawn() +{ + Entity_Player* player = game_nearest_player(pos); + int coins = player && player->GetHealthType() == HEALTH_COIN ? random_below(3) : random_below(3) + 1; + for (int i = 0; i < coins; i++) + { + uint32_t seed = Random(); + Vector speed = vector_scale(random_direction(), random_unit() * MIDAS_COIN_SPEED); + g_game->Spawn({.position = pos, + .velocity = speed, + .subType = COIN_PENNY, + .type = ENTITY_PICKUP, + .variant = PICKUP_COIN, + .seed = seed}); + } +} + +// 006d5350 Toxic Shock leaves its green creep where the enemy died, sized to it. +void Entity_NPC::toxic_shock_creep_spawn() +{ + Entity_Player* owner = g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_CHECK); + if (!owner) return; + + Entity* creep = spawn_at(ENTITY_EFFECT, EFFECT_PLAYER_CREEP_GREEN, 0, pos, owner); + float creepScale = size * TOXIC_CREEP_SCALE; + creep->sprite.scale = vector_make(creepScale, creepScale); + creep->Update(); +} + +// Part of 006c4b30: the items whose aura works on enemies near a player (The Soul, Super Magnet, Salvation). +void Entity_NPC::player_aura_update() +{ + if (state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH || IsFriendly() || !IsVulnerableEnemy(nullptr)) + return; + for (Entity_Player* player : g_game->playerManager.playerList) + { + bool isAura = player->HasCollectible(COLLECTIBLE_SOUL_ID) || player->HasTrinket(TRINKET_SUPER_MAGNET_ID) || + player->HasCollectible(COLLECTIBLE_SALVATION_ID); + if (isAura) + reconstruction_missing("Entity_NPC::Update 006c4b30: The Soul's, Super Magnet's and Salvation's pull"); + } +} + +// Part of 006c4b30: what the players' items do to enemies each frame: Toxic Shock's poison, Lighter's burn and Ice +// Cube's freeze on the room's first frame, confusion while its target is invisible, Broken Modem's stalls, Game +// Kid's fear and the time stopping items' tint. +void Entity_NPC::item_effects_update() +{ + PlayerManager& players = g_game->playerManager; + if (g_game->room->GetFrameCount() == 0 && IsVulnerableEnemy(nullptr)) + { + if (Entity_Player* owner = players.FirstCollectibleOwner(COLLECTIBLE_TOXIC_SHOCK_ID, LAZARUS_SHARE_IGNORE)) + AddPoison(EntityRef(owner), TOXIC_SHOCK_POISON, 0, false); + if (players.FirstTrinketOwner(TRINKET_LIGHTER_ID) || players.FirstTrinketOwner(TRINKET_ICE_CUBE_ID)) + reconstruction_missing("Entity_NPC::Update 006c4b30: Lighter's burn and Ice Cube's freeze"); + } + + Entity_Player* targetPlayer = GetPlayerTarget()->ToPlayer(); + if (targetPlayer && targetPlayer->IsInvisible()) AddConfusion(EntityRef(this), STATUS_REFRESH, false); + if (players.FirstCollectibleOwner(COLLECTIBLE_BROKEN_MODEM_ID, LAZARUS_SHARE_IGNORE)) + reconstruction_missing("Entity_NPC::Update 006c4b30: Broken Modem's stalls"); + if (IsActiveEnemy(DEAD_EXCLUDED) && HasEntityFlags(FLAG_FREEZE) && freezeCountdown < 1 && IsFrame(MODEM_FRAMES, 0)) + reconstruction_missing("Entity_NPC::Update 006c4b30: Broken Modem's release"); + + if (!HasEntityFlags(FLAG_NO_TARGET)) + for (Entity_Player* player : players.playerList) + if (player->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_GAMEKID_ID)) + reconstruction_missing("Entity_NPC::Update 006c4b30: Game Kid's fear"); + + TemporaryEffects& roomEffects = g_game->room->temporaryEffects; + bool isTimeSlowed = roomEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) || + roomEffects.HasCollectibleEffect(COLLECTIBLE_HOURGLASS_ID) || + g_game->room->GetBrokenWatchState() == BROKEN_WATCH_SLOW; + bool isTimeImmune = (flags & (FLAG_FRIENDLY | FLAG_NO_STATUS_EFFECTS)) && type != ENTITY_DEATHS_HEAD; + if (isTimeSlowed && !isTimeImmune) reconstruction_missing("Entity_NPC::Update 006c4b30: the slowed time tint"); +} + +// How much of a per-tick factor is left over a step of timeScale ticks (Math::timescale_factor). +static float timescale_factor(float factor, float timeScale) +{ + return timeScale == 1 ? factor : factor / ((factor + timeScale) - factor * timeScale); +} + +// Part of 006c4b30: a poof02 event puffs smoke from the null of that name. +void Entity_NPC::poof02_spawn() +{ + reconstruction_missing("Entity_NPC::Update 006c4b30: the poof02 event's smoke"); +} + +// Part of 006c4b30: a grounded enemy walking through water leaves a ripple every 7 frames. +void Entity_NPC::ripple_spawn() +{ + if (IsFlying() || !isVisible || !IsActiveEnemy(DEAD_EXCLUDED) || vector_length_squared(velocity) <= 1) return; + if (!g_game->room->HasWater() || !IsFrame(RIPPLE_FRAMES, (int)index) || entityCollisionClass == ENTCOLL_NONE) + return; + + Entity* ripple = spawn_at(ENTITY_EFFECT, EFFECT_WATER_RIPPLE, 0, vector_add(pos, velocity), this); + float rippleScale = size * RIPPLE_SCALE * scale; + ripple->sprite.scale = vector_make(rippleScale, rippleScale); + ripple->renderDepthOffset = RIPPLE_DEPTH; + ripple->velocity = vector_scale(velocity, RIPPLE_SPEED); + ripple->Update(); +} + +// 006c4b30 One frame of an enemy: its speed, status overlay and pause, appearing, its AI, champion and item +// effects, dying, the base update (movement), then the seeds and debug modes that change it, and its forced target. +void Entity_NPC::Update() +{ + if (!isExists) return; + + speedMultiplier = compute_speed_multiplier(); + UpdateChildEffectPosition(false); + if (controllerID == -1) + { + controllerMovement = {}; + if (aimTargetEffect) aimTargetEffect->Remove(); + aimTargetEffect = nullptr; + } + if (HasEntityFlags(FLAG_ICE_FROZEN)) return update_frozen(); + + bool isWeakened = g_game->room->temporaryEffects.HasNullEffect(NULLITEM_DAMOCLES_WEAKNESS); + if (IsFrame(WEAKNESS_FRAMES, 0) && !IsFriendly() && IsActiveEnemy(DEAD_EXCLUDED) && isWeakened) + AddWeakness(EntityRef(nullptr), -3); + if (salvationTarget && salvationTarget->target.get() == this) + { + salvationTarget->pos = pos; + salvationTarget->velocity = velocity; + } + status_overlay_update(); + + bool isDeadBefore = isDead; + if ((pauseTimer != 0 || HasEntityFlags(FLAG_HELD))) + { + if (!paused_update()) return; + isDeadBefore = isDead; + } + + bool isAppearing = HasEntityFlags(FLAG_APPEAR); + if (!isAppearing && state == NPC_STATE_APPEAR) state = savedState; + else if (isAppearing && state == NPC_STATE_APPEAR) appear_update(); + else death_animation_update(); + + bool isHeld = HasEntityFlags(FLAG_FREEZE) || HasEntityFlags(FLAG_HELD) || holdCountdown > 0; + bool isDying = state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH; + if (isDying || ((isHeld || state == NPC_STATE_APPEAR) && !isDead)) + { + if (HasEntityFlags(FLAG_FREEZE) || holdCountdown > 0) + { + friction *= APPEAR_FRICTION; + if (holdCountdown > 0 && !vector_is_zero(holdPosition)) pos = holdPosition; + } + if (!isDead) player_aura_update(); + } + else + { + if (!HasEntityFlags(FLAG_CHARM)) decoy_update(); + if (isDead && state == NPC_STATE_APPEAR) + { + friction = baseFriction; + state = savedState; + isVisible = true; + } + if (championRegenTimer == 0) npc_ai_update(*this); + + champion_update(); + unreachable_update(); + if (isDead && isExists) dead_update(); + if (!isDead) player_aura_update(); + } + item_effects_update(); + if (HasEntityFlags(FLAG_BAITED)) friction *= timescale_factor(SLOW_FRICTION, speedMultiplier); + if (isChampion) + velocity = vector_scale(velocity, timescale_factor(1 - (1 - championSpeed) * (1 - friction), speedMultiplier)); + if (sprite.IsEventTriggered("poof02")) poof02_spawn(); + spawn_damage_numbers(); + update_damage_history(); + if (aiCallFlags & AI_CALL_PRE_UPDATE) ai_call(AI_PHASE_PRE_UPDATE); + if (HasEntityFlags(FLAG_PERSISTENT | FLAG_FRIENDLY_BALL_DYING)) + reconstruction_missing("Entity_NPC::Update 006c4b30: a captured enemy wasting away"); + + float healthBefore = health; + if (type == ENTITY_MINECART) update_physics(); + else Entity::Update(); + totalDamageTaken += std::max(healthBefore - health, 0.0f); + if (aiCallFlags & AI_CALL_POST_UPDATE) ai_call(AI_PHASE_POST_UPDATE); + + seed_effects_update(); + sprite.scale = vector_make(scale * shrinkStatus1, scale * shrinkStatus1); + ripple_spawn(); + pausePosition = pos; + if (!isBestiaryEncountered) + { + g_manager->persistentGameData.TryAddBestiaryEncounter(type, variant); + isBestiaryEncountered = true; + } + if (IsFrame(config->collisionInterval * 2, (int)index)) hitList.clear(); + else if (type == ENTITY_BLOOD_PUPPY && state == NPC_STATE_ATTACK && sprite.animState.IsLoopingAnimation() && + IsFrame(PUPPY_HIT_FRAMES, (int)index)) + hitList.clear(); + type_update(); + + if (isDead && !isDeadBefore && !IsBoss() && !config->isBoss && HasEntityFlags(FLAG_ICE)) + reconstruction_missing("Entity_NPC::Update 006c4b30: an iced enemy turning into a statue"); + if (!isDead && state != NPC_STATE_DEATH) + { + ClearEntityFlags(FLAG_EXTRA_GORE); + ClearEntityFlags(FLAG_SPAWN_STICKY_SPIDERS); + } + forced_target_update(); +} + +// Part of 006c4b30: the seeds and the debug mode that change every enemy: invisible enemies, camouflage, and the +// pacifist seed and quick kill that make them waste away. +void Entity_NPC::seed_effects_update() +{ + Seeds& seeds = g_game->seedEffects; + if (seeds.HasSeedEffect(SEED_INVISIBLE_ENEMIES)) + { + SetColor(COLOR_INVISIBLE, -1, COLOR_PRIORITY_DEFAULT, false, true); + sprite.color = COLOR_INVISIBLE; + shadowSize = 0; + } + if (seeds.HasSeedEffect(SEED_CAMO_ENEMIES) || seeds.HasSeedEffect(SEED_CAMO_EVERYTHING)) + reconstruction_missing("Entity_NPC::Update 006c4b30: the camouflage seeds"); + bool isQuickKill = seeds.HasSeedEffect(SEED_PACIFIST) || (g_game->debugFlags & DEBUG_QUICK_KILL); + if (isQuickKill && IsActiveEnemy(DEAD_EXCLUDED)) + reconstruction_missing("Entity_NPC::Update 006c4b30: the pacifist seed and quick kill debug mode"); +} + +// Part of 006c4b30: the few enemies with their own per-frame step: Hornfel, Gideon's camera, the Heart's partner and +// Big Horn's spit. +void Entity_NPC::type_update() +{ + if (type == ENTITY_HORNFEL) Hornfel_UpdateFrame(); + if (type == ENTITY_GIDEON && state == NPC_STATE_APPEAR) + reconstruction_missing("Entity_NPC::Update 006c4b30: Gideon's camera"); + if (type == ENTITY_HEART) + { + targetPosition = {}; + if (variant == 1 && entityRef && entityRef->IsEnemy()) + { + Entity* partner = entityRef; + targetPosition = vector_sub(partner->pos, pos); + partner->targetPosition = vector_scale(targetPosition, -1); + } + } + if (type == ENTITY_BIG_HORN && sprite.IsEventTriggered(BIG_HORN_SPIT_EVENT)) + reconstruction_missing("Entity_NPC::Update 006c4b30: Big Horn's spit"); +} + +// Part of 006c4b30: a forced target runs out, and a boss then waits 150 frames before taking another. +void Entity_NPC::forced_target_update() +{ + if (forcedTargetTimer < 0) + { + forcedTargetTimer++; + return; + } + if (forcedTargetTimer == 0 || --forcedTargetTimer != 0) return; + if (IsBoss()) forcedTargetTimer = -FORCED_TARGET_BOSS_COOLDOWN; + forcedTarget = nullptr; +} + +// 006b99e0 Its speed this frame: the room's time scale for it, halved under a stopwatch or the hourglass (or, for a +// friendly enemy, the room's slowdown), slowed and weakened enemies slower, and Vanishing Twin's boss slower still. +float Entity_NPC::compute_speed_multiplier() +{ + Room& room = *g_game->room; + float speed = room.GetTimeScale(this); + if (!IsFriendly()) + { + if (room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_STOP_WATCH_ID) || + (g_game->challenge != CHALLENGE_SLOW && room.brokenWatchState == BROKEN_WATCH_SLOW)) + speed *= SPEED_HALF; + else if (TemporaryEffect* hourglass = room.temporaryEffects.GetCollectibleEffect(COLLECTIBLE_HOURGLASS_ID)) + speed *= 1 - std::clamp((float)hourglass->cooldown / SLOW_TIMESCALE_EFFECT_FRAMES, 0.0f, 1.0f) * SPEED_HALF; + } + else if (room.slowdownDuration > 0) speed *= SPEED_HALF; + + if (HasEntityFlags(FLAG_SLOW) && state != NPC_STATE_DEATH) speed *= SPEED_HALF; + if (HasEntityFlags(FLAG_WEAKNESS)) speed *= SPEED_WEAKENED; + if (IsBoss() && !IsFriendly() && room.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_VANISHING_TWIN_ID)) + speed *= SPEED_VANISHING_TWIN; + return speed; +} + +// The NPC types whose collisions the generic rules below do not cover: bosses, segmented and special enemies. +constexpr std::array COLLISION_SPECIAL_TYPES = { + 17, 19, 21, 23, 25, 28, 29, 30, 31, 32, 33, 35, 36, 39, 40, 41, 44, 55, 61, 62, 63, + 66, 89, 99, 206, 207, 212, 213, 216, 218, 222, 237, 239, 243, 245, 251, 256, 260, 261, 265, 274, 281, + 289, 291, 292, 293, 295, 296, 308, 401, 402, 404, 406, 407, 410, 412, 802, 808, 810, 815, 818, 819, 822, + 853, 866, 868, 873, 877, 878, 881, 889, 893, 903, 909, 910, 912, 915, 918, 919, 951, 964, 965}; +constexpr std::array COLLISION_SPECIAL_COLLIDERS = {21, 23, 28, 31, 35, 40, 55, 62, 89, + 212, 218, 239, 243, 260, 274, 281, 293, 918}; +constexpr int ENTITY_COLLISION_IGNORED = 291; +constexpr float SPAWN_GRACE_FRAMES = 10; + +// 006cd410 What it does on touching another entity, and whether that contact is ignored: it hurts a player it +// touches (but for Skatole's flies and Bursting Sack's spiders), a shrunk enemy is squished, its friends and +// shots pass, and enemies just spawned in a challenge or ambush do not touch yet. +bool Entity_NPC::HandleCollision(Entity* collider, bool isLow) +{ + LuaResult lua = static_cast(g_luaEngine)->PreNPCCollision(this, collider, isLow); + if (lua == LUA_RESULT_TRUE) return true; + if (lua == LUA_RESULT_FALSE) return false; + + bool isSpecial = + std::ranges::find(COLLISION_SPECIAL_TYPES, type) != COLLISION_SPECIAL_TYPES.end() || + std::ranges::find(COLLISION_SPECIAL_COLLIDERS, collider->type) != COLLISION_SPECIAL_COLLIDERS.end() || + minecart || spawnerType == ENTITY_COLLISION_SPAWNER_SPECIAL; + if (isSpecial) reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a special enemy's contact"); + + bool isIgnored = true; + bool isMagnetized = HasEntityFlags(FLAG_MAGNETIZED) || collider->HasEntityFlags(FLAG_MAGNETIZED); + if (Entity::is_enemy_type(collider->type) && isMagnetized && + collider->GetStatusEffectTarget() != GetStatusEffectTarget()) + isIgnored = false; + + if (aiCallFlags & AI_CALL_COLLISION) + { + collisionEntity = collider; + isCollisionIsLow = isLow; + collisionResult = -1; + ai_call(AI_PHASE_COLLISION); + if (collisionResult > 0) return false; + if (collisionResult == 0) return isIgnored; + } + + if (HasEntityFlags(FLAG_SHRINK) && collider->type == ENTITY_PLAYER && !IsBoss()) + { + Kill(EntityRef()); + return isIgnored; + } + if (IsFriendly() && IsDamageSourceFriendly(EntityRef(collider))) + { + if (collider->type == ENTITY_PLAYER || collider->type == ENTITY_FAMILIAR) return isIgnored; + if (collider->IsEnemy() && collider->IsFriendly()) return isIgnored; + } + if (!isLow && collider->type == ENTITY_PROJECTILE) return isIgnored; + + Room& room = *g_game->room; + bool isGraceRoom = room.roomType == ROOM_CHALLENGE || room.roomType == ROOM_BOSSRUSH || + (g_game->IsGreedMode() && room.roomType == ROOM_DEFAULT) || HasEntityFlags(FLAG_AMBUSH); + if (isGraceRoom && (state == NPC_STATE_APPEAR || g_game->frameCount - spawnFrame < SPAWN_GRACE_FRAMES)) + return isIgnored; + if (collider->type == ENTITY_COLLISION_IGNORED) return isIgnored; + + if (!isLow) + { + if (collider->type == ENTITY_PLAYER) player_contact(*static_cast(collider)); + else if (collider->type == ENTITY_FAMILIAR) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: an enemy hurting a familiar"); + } + enemy_contact(*collider); + if (HasEntityFlags(FLAG_KNOCKED_BACK) && vector_length(knockbackDirection) > KNOCKBACK_IMPACT_SPEED) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a knocked back enemy's impact"); + return false; +} + +// Part of 006cd410: touching a player hurts it by the collision damage, unless Skatole spares flies or Bursting +// Sack spiders. E. Coli turns the enemy to poop and a kill-on-touch enemy dies. +void Entity_NPC::player_contact(Entity_Player& player) +{ + PlayerManager& players = g_game->playerManager; + bool isSpared = ((config->tags & ENTITY_TAG_FLY) && players.AnyoneHasCollectible(COLLECTIBLE_SKATOLE_ID)) || + ((config->tags & ENTITY_TAG_SPIDER) && players.AnyoneHasCollectible(COLLECTIBLE_BURSTING_SACK_ID)); + if (!isSpared && collisionDamage > 0) + { + bool isHurt = player.TakeDamage(collisionDamage, 0, EntityRef(this), 0); + if (isHurt && isChampion && championColorIdx == CHAMPION_ORANGE && player.numCoins > 0) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: the orange champion's stolen coins"); + } + if (player.HasCollectible(COLLECTIBLE_E_COLI_ID)) + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: E. Coli's poop"); + if (isKillOnTouch) Kill(EntityRef()); +} + +// Part of 006cd410: an active enemy meets another: a charmed one (or one targeting it) bumps it for damage once per +// hit list. +void Entity_NPC::enemy_contact(Entity& other) +{ + if (!other.IsEnemy() || !IsActiveEnemy(DEAD_EXCLUDED) || !other.IsActiveEnemy(DEAD_EXCLUDED)) return; + + bool isSameSide = HasEntityFlags(FLAG_CHARM) == other.HasEntityFlags(FLAG_CHARM); + bool isTargeted = target.get() == &other || forcedTarget.get() == &other; + if ((isSameSide && !isTargeted) || collisionDamage <= 0 || EntityList::HitListContains(hitList, other)) return; + reconstruction_missing("Entity_NPC::HandleCollision 006cd410: a charmed enemy hurting another"); +} + +// 006d60a0 Takes a hit as any entity (Entity::TakeDamage) and lets the items that react to it act: a player's hit +// ends Pacifist, Betrayal turns it on its attacker, the pulsing champion spawns its flies, and a hit taken spawns +// a blue fly for a hit that spawns one, marks a player's kill for Jar of Flies, and triggers the attacker's +// on-hit procedural items. +bool Entity_NPC::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown) +{ + bool isHurt = Entity::TakeDamage(damage, damageFlags, source, damageCountdown); + bool isPlayerSource = source.type == ENTITY_PLAYER || source.type == ENTITY_FAMILIAR || + source.spawnerType == ENTITY_PLAYER || source.spawnerType == ENTITY_FAMILIAR; + if (!IsFriendly() && isPlayerSource) g_game->room->isPacifist = false; + + PlayerManager& players = g_game->playerManager; + if (source.entity && players.FirstCollectibleOwner(COLLECTIBLE_BETRAYAL_ID, LAZARUS_SHARE_CHECK)) + reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: Betrayal"); + if (players.FirstCollectibleOwner(COLLECTIBLE_JAR_OF_FLIES_ID, LAZARUS_SHARE_CHECK)) + { + bool isBlueFly = source.type == ENTITY_FAMILIAR && source.variant == FAMILIAR_BLUE_FLY; + bool isPlayerKill = source.type == ENTITY_PLAYER || (source.spawnerType == ENTITY_PLAYER && !isBlueFly) || + (damageFlags & ((uint64_t)DAMAGE_ACID | DAMAGE_POISON_BURN)) || + source.type == ENTITY_EFFECT; + if (isPlayerKill) AddEntityFlags(FLAG_ADD_JAR_FLY); + else ClearEntityFlags(FLAG_ADD_JAR_FLY); + } + if (championColorIdx == CHAMPION_SIZE_PULSE && !isDead && pendingDamage < health) + reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: the size pulsing champion's flies"); + if (!isHurt || HasEntityFlags(FLAG_NO_STATUS_EFFECTS)) return isHurt; + + Entity* attacker = source.entity; + if (attacker && attacker->type != ENTITY_PLAYER) attacker = attacker->spawnerEntity; + Entity_Player* player = + attacker && attacker->type == ENTITY_PLAYER ? static_cast(attacker) : game_nearest_player(pos); + if (damageFlags & DAMAGE_SPAWN_FLY) reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: the hit's blue fly"); + if (!player->proceduralItems.empty()) + reconstruction_missing("Entity_NPC::TakeDamage 006d60a0: the attacker's on-hit procedural items"); + return isHurt; +} + +// 006be6f0 Keeps what killed it (the damage and its events) for the death triggers, then dies as any entity. +void Entity_NPC::Kill(const EntityRef& source) +{ + killDamage = pendingDamage; + killDamageFlags = pendingDamageFlags; + killDamageEvents = damageEvents; + Entity::Kill(source); +} + +// 006b8f30 Lets go of everything it points at, Gideon's chain and Mother's sounds included. +void Entity_NPC::ClearReferences() +{ + if (type == ENTITY_SIREN_HELPER || type == ENTITY_GIDEON || + (type == ENTITY_MOTHER && (variant == 0 || variant == 10))) + reconstruction_missing("Entity_NPC::ClearReferences 006b8f30: Siren's helper, Gideon's and Mother's links"); + pickupGhostsEntity = nullptr; + unknownF54 = nullptr; + salvationTarget = nullptr; + entityRef = nullptr; + if (aimTargetEffect) aimTargetEffect->Remove(); + aimTargetEffect = nullptr; + ClearDequeRefs(); + forcedTarget = nullptr; + Entity::ClearReferences(); + entityDeque.clear(); + vectorDeque1.clear(); + vectorDeque2.clear(); + statusEffectSprite.Reset(); + chargeBarSprite.Reset(); + hitList.clear(); + hitList.shrink_to_fit(); + secondaryHitList.clear(); + secondaryHitList.shrink_to_fit(); +} + +// 006d81c0 Lets go of the entities its deque holds, and the deque. +void Entity_NPC::ClearDequeRefs() +{ + entityDeque.clear(); +} + +// 006c1100 Shows its own color again: a boss's alternate color, or for a champion its champion color. +void Entity_NPC::ResetColor() +{ + if (isChampion) reconstruction_missing("Entity_NPC::ResetColor 006c1100: a champion's color"); + if (bosscoloridx < 0) sprite.color = color; + else if (bosscoloridx < (int)config->bossColors.size()) sprite.color = config->bossColors[bosscoloridx].color; +} + +// 006d4e00 Bursts it: a blood explosion its size (or a fly's, a spider's, a poop's), in its splat color, from its +// sprite's middle. +void Entity_NPC::PlayDeathEffects() +{ + if (g_game->playerManager.GetGFuelCount() > 0) + reconstruction_missing("Entity_NPC::PlayDeathEffects 006d4e00: G-Fuel's explosion"); + + Vector offset{}; + const AnimationFrame* frame = sprite.animState.animData && (type != ENTITY_SCOURGE || variant != 10) + ? sprite.animState.GetLayerFrame(0) + : nullptr; + if (frame) + offset = vector_make(frame->width * HALF - frame->pivot.x + frame->pos.x, + frame->height * HALF - frame->pivot.y + frame->pos.y); + if (HasEntityFlags(FLAG_NO_BLOOD_SPLASH)) return; + + int burst = death_burst_get(); + if (burst == EFFECT_BLOOD_EXPLOSION) + { + Entity* blood = spawn_at(ENTITY_EFFECT, EFFECT_BLOOD_EXPLOSION, poof_size_get(*this, true), pos, nullptr); + blood->sprite.offset = offset; + blood->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + blood->renderDepthOffset = BLOOD_DEPTH_OFFSET; + } + else + { + if (config->gibFlags & GIB_FLAG_POOP) npc_sound_play(SOUND_POOP_DEATH, POOP_DEATH_VOLUME, 2, 1); + Entity* burstEffect = spawn_at(ENTITY_EFFECT, burst, 0, vector_add(pos, offset), nullptr); + burstEffect->SetColor(splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + if (type == ENTITY_DEATH_SPARK_TYPE) + reconstruction_missing("Entity_NPC::PlayDeathEffects 006d4e00: the electric enemy's sparks"); +} + +// Part of 006d4e00: the burst effect a dead NPC leaves: a poop's, a fly's, a spider's, a few special ones, else +// blood. +int Entity_NPC::death_burst_get() +{ + if (config->gibFlags & GIB_FLAG_POOP) return EFFECT_POOP_EXPLOSION; + switch (type) + { + case ENTITY_FLY: + case ENTITY_POOTER: + case ENTITY_ATTACKFLY: + case 214: + case 222: + case 249: + case 256: + case 281: + case 296: + case 808: + case 838: + case 868: + return EFFECT_FLY_EXPLOSION; + case ENTITY_SPIDER: + case 94: + case 215: + case 250: + case 869: + case 884: + return EFFECT_SPIDER_EXPLOSION; + case 810: + return EFFECT_BURST_810; + case 818: + return EFFECT_BURST_818; + case 853: + return EFFECT_BURST_853; + default: + return EFFECT_BLOOD_EXPLOSION; + } +} + +// 006be840 What it goes after: a charmed enemy picks the nearest enemy, Mom's Heart's (type 53) its own player, +// the rest the nearest target player (Game::GetNearestTargetPlayer), else the first player. +Entity* Entity_NPC::GetPlayerTarget() +{ + if (type == ENTITY_MOMS_HEART_PLAYER_PICK) + reconstruction_missing("Entity_NPC::GetPlayerTarget 006be840: the shared player choice of its kind"); + + bool isRetargeting = IsFrame(TARGET_REFRESH_FRAMES, (int)index) || !target; + if (HasEntityFlags(FLAG_CHARM) && !g_game->room->isPacifist && isRetargeting) + reconstruction_missing("Entity_NPC::GetPlayerTarget 006be840: a charmed enemy's prey (Game::GetNearestEnemy)"); + if (target) return target; + + bool isTargetDecoys = type != ENTITY_NO_DECOY_TYPE && decoyTargetTimer >= 0; + Entity* found = game_nearest_target_player(pos, this, IsFriendly(), isTargetDecoys, TARGET_RANGE); + if (!found) return g_game->GetPlayer(0); + if (found->IsEnemy() && found->HasEntityFlags(FLAG_BAITED)) target = found; + return found; +} + +// 006bec40 Where it heads for its target: a confused enemy wanders to a random spot (a new one every 15 frames), +// a feared or shrunk one runs from its target (a rare few stay put), the rest go straight for it. +Vector Entity_NPC::CalcTargetPosition(float distanceLimit) +{ + Room& room = *g_game->room; + if (HasEntityFlags(FLAG_CONFUSION)) + { + bool isKept = + !vector_is_zero(confusionTargetPos) && (HasEntityFlags(FLAG_INTERPOLATION_UPDATE) || g_game->IsPaused() || + g_game->frameCount % CONFUSION_RETARGET_FRAMES != 0); + if (!isKept) + { + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + float scaleFirst = random_unit(); + float distance = random_unit() * scaleFirst * CONFUSION_WANDER; + Vector spot = vector_make(std::cos(angle) * distance + pos.x, std::sin(angle) * distance + pos.y); + confusionTargetPos = room.GetClampedPositionImpl(spot, size, size, size, size); + } + return confusionTargetPos; + } + + bool isFleeingKind = type == ENTITY_MULLIGAN ? variant == MULLIGAN_VARIANT_FLEEING + : type != ENTITY_HIVE && type != ENTITY_FEAR_IMMUNE; + bool isFleeing = HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && isFleeingKind; + if (!isFleeing) return GetPlayerTarget()->pos; + + Vector away = vector_sub(GetPlayerTarget()->pos, pos); + if (distanceLimit != 0 && vector_length_squared(away) != 0) away = vector_resized(away, distanceLimit); + Vector flee = vector_sub(pos, away); + Vector clamped = room.GetClampedPositionImpl(flee, size, size, size, size); + if (clamped.x == flee.x && clamped.y == flee.y) + { + confusionTargetPos = {}; + return clamped; + } + if (!vector_is_zero(confusionTargetPos) && !IsFrame((int)(Random() % FEAR_RETARGET_RANGE) + FEAR_RETARGET_MIN, 0)) + return confusionTargetPos; + + Vector direction = random_direction(); + float distance = random_unit() * FEAR_WANDER; + Vector spot = vector_sub(pos, vector_scale(direction, distance)); + confusionTargetPos = room.GetClampedPositionImpl(spot, size, size, size, size); + return confusionTargetPos; +} + +// 006cae60 Whether its target is in range to attack (predicting its motion, checked every frameInterval frames) +// in a clear line, or the controlling player steers it. Confused, feared and shrunk enemies never attack. +bool Entity_NPC::IsTargetInAttackRange(float range, int frameInterval, bool isPredictVelocity) +{ + if (HasEntityFlags(FLAG_CONFUSION | FLAG_FEAR | FLAG_SHRINK)) return false; + if (controllerID != -1) return !vector_is_zero(GetControllerMovementInput(MOVEMENT_DEADZONE)); + + Entity* other = GetPlayerTarget(); + if (!IsHostileTo(other)) return false; + Vector aim = + isPredictVelocity ? vector_add(other->pos, vector_scale(other->velocity, ATTACK_PREDICT_FRAMES)) : other->pos; + if (frameInterval != 0 && !IsFrame(frameInterval, (int)index)) return false; + if (vector_length_squared(vector_sub(aim, pos)) >= range * range) return false; + return room_check_line(pos, other->pos, LINE_CHECK_PROJECTILE, LINE_CHECK_THRESHOLD) || + championColorIdx == CHAMPION_TRANSPARENT; +} + +// 006c1330 Walks its main animation: the vertical one stopped while slower than the threshold (half for a slow +// champion), else the one of the axis it moves most along, flipped to face left, and faces that way. +void Entity_NPC::AnimWalkFrame(std::string_view horizontalAnim, std::string_view verticalAnim, float speedThreshold) +{ + if (isChampion && championSpeed < 1) speedThreshold *= HALF; + if (vector_length_squared(velocity) < speedThreshold * speedThreshold) + { + if (sprite.SetAnimation(verticalAnim, SWITCH_KEEP_FRAME) && sprite.animState.animData) + { + sprite.animState.SetFrameFloat(0); + sprite.animState.isPlaying = false; + } + forwardVector = vector_make(0, 1); + return; + } + + bool isHorizontal = std::abs(velocity.x) > std::abs(velocity.y); + std::string_view walk = isHorizontal ? horizontalAnim : verticalAnim; + const AnimationData* current = sprite.animState.animData; + bool isWalking = current && current->name == walk && (!current->isLooping || sprite.animState.isPlaying); + if (!isWalking && sprite.SetAnimation(walk, SWITCH_KEEP_FRAME)) + { + sprite.animState.Rewind(); + sprite.animState.isPlaying = true; + } + if (isHorizontal) sprite.isFlipX = velocity.x < 0; + + if (isHorizontal) forwardVector = vector_make(velocity.x >= 0 ? 1.0f : -1.0f, 0); + else forwardVector = vector_make(0, velocity.y >= 0 ? 1.0f : -1.0f); +} + +// The rotation of each fan FireProjectiles shoots, as the cosine and sine the exe keeps and a speed scale. +struct ShotTurn +{ + float cosine; + float sine; + float speed; +}; + +constexpr ShotTurn SHOT_8 = {0.99f, 0.139f, 1}; +constexpr ShotTurn SHOT_12 = {0.978f, 0.208f, 1}; +constexpr ShotTurn SHOT_16 = {0.961f, 0.276f, 1}; +constexpr ShotTurn SHOT_16_SLOW = {0.961f, 0.276f, 0.9f}; +constexpr ShotTurn SHOT_24 = {0.914f, 0.407f, 1}; +constexpr ShotTurn SHOT_24_SLOW = {0.914f, 0.407f, 0.9f}; +constexpr float DIAGONAL = 0.70710677f; +constexpr float PROJECTILE_DEFAULT_FALL_SPEED = -3; +constexpr float PROJECTILE_DEFAULT_FALL_ACCEL = 0.1f; +constexpr float PROJECTILE_HEIGHT_LOW = -50; +constexpr float PROJECTILE_DAMAGE_LARGE_SCALE = 1.15f; +constexpr float SHOOTER_VELOCITY_SHARE = 0.4f; +constexpr float SHOT_VELOCITY_BOOST = 1.2f; + +// The shots of a fan: each turn spreads to both sides (a straight one once). +static void fan_velocities_add(std::vector& shots, Vector velocity, float spread, const ShotTurn& turn) +{ + float cosine = turn.cosine * turn.speed; + float sine = turn.sine * turn.speed * spread; + if (turn.sine == 0) + { + shots.push_back(velocity); + return; + } + shots.push_back(vector_make(velocity.x * cosine - velocity.y * sine, velocity.x * sine + velocity.y * cosine)); + shots.push_back(vector_make(velocity.y * sine + velocity.x * cosine, velocity.y * cosine - velocity.x * sine)); +} + +// 006cb2e0 Shoots projectiles of params' variant from a position in a mode's spread, then applies params to each: +// the fans also fall at once and take on part of its motion unless params keeps their fall. +void Entity_NPC::FireProjectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode, + const ProjectileParams& params) +{ + std::vector shots; + float speed = velocity.x; + switch (mode) + { + case PROJECTILES_SINGLE: + shots.push_back(velocity); + break; + case PROJECTILES_TWO: + fan_velocities_add(shots, velocity, params.spread, SHOT_16); + break; + case PROJECTILES_THREE: + shots.push_back(velocity); + fan_velocities_add(shots, velocity, params.spread, SHOT_16_SLOW); + break; + case PROJECTILES_THREE_WIDE: + shots.push_back(velocity); + fan_velocities_add(shots, velocity, params.spread, SHOT_24); + break; + case PROJECTILES_FOUR: + fan_velocities_add(shots, velocity, params.spread, SHOT_8); + fan_velocities_add(shots, velocity, params.spread, SHOT_24_SLOW); + break; + case PROJECTILES_FIVE: + shots.push_back(velocity); + fan_velocities_add(shots, velocity, params.spread, SHOT_12); + fan_velocities_add(shots, velocity, params.spread, SHOT_24); + break; + case PROJECTILES_PLUS: + shots.insert(shots.end(), {vector_make(speed, 0), vector_make(-speed, 0), vector_make(0, speed), + vector_make(0, -speed)}); + break; + case PROJECTILES_CROSS: + case PROJECTILES_EIGHT: + { + float diagonal = speed * DIAGONAL; + if (mode == PROJECTILES_EIGHT) + shots.insert(shots.end(), {vector_make(speed, 0), vector_make(-speed, 0), vector_make(0, speed), + vector_make(0, -speed)}); + shots.insert(shots.end(), {vector_make(diagonal, diagonal), vector_make(-diagonal, diagonal), + vector_make(diagonal, -diagonal), vector_make(-diagonal, -diagonal)}); + break; + } + case PROJECTILES_RING: + { + float angle = params.circleAngle; + int count = (int)(velocity.y + HALF); + float step = 2 * PI_F / (float)count; + for (int i = 0; i < count; i++) + { + angle += step; + Vector shot = vector_make(std::cos(angle) * speed, std::sin(angle) * speed); + bool isLimited = !vector_is_zero(params.fireDirectionLimit); + if (!isLimited || + vector_dot(vector_normalized(shot), params.fireDirectionLimit) > params.dotProductLimit) + shots.push_back(shot); + } + break; + } + } + + std::vector projectiles; + Vector origin = vector_add(position, params.positionOffset); + for (const Vector& shot : shots) + { + Entity* spawned = g_game->Spawn({.position = origin, + .velocity = shot, + .spawner = this, + .type = ENTITY_PROJECTILE, + .variant = params.variant, + .seed = Random()}); + if (!spawned) log_printf(LOG_ASSERT, "Failed to spawn Projectile"); + projectiles.push_back(static_cast(spawned)); + } + + bool isFan = mode < PROJECTILES_PLUS; + for (Entity_Projectile* projectile : projectiles) + { + if (!isFan || params.isFallingKept) break; + projectile->fallingSpeed = PROJECTILE_DEFAULT_FALL_SPEED; + projectile->fallingAccel = PROJECTILE_DEFAULT_FALL_ACCEL; + if (mode != PROJECTILES_THREE && mode != PROJECTILES_FOUR && mode != PROJECTILES_FIVE) continue; + projectile->fallingSpeed -= 1; + projectile->velocity = vector_add(vector_scale(this->velocity, SHOOTER_VELOCITY_SHARE), + vector_scale(projectile->velocity, SHOT_VELOCITY_BOOST)); + } + for (Entity_Projectile* projectile : projectiles) projectile_params_apply(*projectile, params); + for (Entity_Projectile* projectile : projectiles) fire_projectile_from_params(projectile); +} + +// Part of 006cb2e0: what params set on a shot fired. +void Entity_NPC::projectile_params_apply(Entity_Projectile& projectile, const ProjectileParams& params) +{ + projectile.height += params.heightModifier; + projectile.fallingSpeed += params.fallingSpeedModifier; + projectile.fallingAccel += params.fallingAccelModifier; + projectile.scale = params.scale; + float damage = params.damage >= 0 ? params.damage : params.scale > PROJECTILE_DAMAGE_LARGE_SCALE ? 2.0f : 1.0f; + projectile.SetCollisionDamage(damage); + projectile.velocity = vector_scale(projectile.velocity, params.velocityMulti); + projectile.projectileFlags |= params.bulletFlags; + projectile.SetColor(params.color, -1, COLOR_PRIORITY_DEFAULT, false, true); + projectile.targetPosition = params.targetPosition; + projectile.homingStrength = params.homingStrength; + projectile.curvingStrength = params.curvingStrength; + projectile.acceleration = params.acceleration; + projectile.wiggleFrameOffset = params.wiggleFrameOffset; + projectile.changeFlags |= params.changeFlags; + projectile.changeVelocity = params.changeVelocity; + projectile.changeTimeout = params.changeTimeout; + projectile.isRenderedAtGround = params.isRenderedAtGround; + projectile.renderDepthOffset = params.depthOffset - params.positionOffset.y; + if (projectile.height < PROJECTILE_HEIGHT_LOW && !(projectile.projectileFlags & PROJECTILE_ANY_HEIGHT_ENTITY_HIT)) + projectile.entityCollisionClass = ENTCOLL_NONE; + if (params.unknownA0 != 0) + reconstruction_missing("Entity_NPC::FireProjectiles 006cb2e0: the projectile field at 0x470"); +} + +// 006cb2a0 Hands a fired shot its shooter's champion color, scale and flags (Entity_Projectile::apply_spawn_flags). +void Entity_NPC::fire_projectile_from_params(Entity_Projectile*) +{ + reconstruction_missing( + "Entity_NPC::fire_projectile_from_params 006cb2a0: Entity_Projectile::apply_spawn_flags 006cb010"); +} + +// The NPC types with their own interpolation or drawing, which the generic steps below do not cover. +constexpr std::array INTERPOLATE_SPECIAL_TYPES = {62, 815, 830, 831, 881, 915}; +constexpr std::array RENDER_SPECIAL_TYPES = {273, 411, 807, 810, 815, 816, 835, 865, 881, 886, 893, + 906, 909, 910, 912, 920, 921, 950, 951, 964, 965}; + +// 006d2b50 Moves it the interpolation's half step (Entity::Interpolate), runs its AI's interpolation call, and moves +// the effect it aims with. +void Entity_NPC::Interpolate() +{ + if (pauseTimer != 0) return; + if (type == ENTITY_MINECART) reconstruction_missing("Entity_NPC::Interpolate 006d2b50: a minecart's half step"); + + Entity::Interpolate(); + if (aiCallFlags & AI_CALL_INTERPOLATE) ai_call(AI_PHASE_INTERPOLATE); + UpdateChildEffectPosition(true); + + bool isHeld = HasEntityFlags(FLAG_FREEZE | FLAG_HELD) || holdCountdown > 0; + bool isStill = isHeld || state == NPC_STATE_APPEAR || state == NPC_STATE_DEATH || state == NPC_STATE_UNIQUE_DEATH; + if (!isStill && std::ranges::find(INTERPOLATE_SPECIAL_TYPES, type) != INTERPOLATE_SPECIAL_TYPES.end()) + reconstruction_missing("Entity_NPC::Interpolate 006d2b50: a jumping enemy's height"); + if (type == ENTITY_HEART && variant == 1 && entityRef && entityRef->IsEnemy()) + { + Entity* partner = entityRef; + targetPosition = vector_sub(partner->pos, pos); + partner->targetPosition = vector_scale(targetPosition, -1); + } +} + +// 006d2e50 Draws it (Entity::Render) and, in the normal and above water passes, the status effect it suffers on its +// OverlayEffect null. +void Entity_NPC::Render(const Vector& offset) +{ + if (type == ENTITY_MINECART && variant == 0 && child) return; + bool isLinked = (type == ENTITY_LARRYJR && variant == 3 && child) || (type == ENTITY_POOP && entityRef); + if (minecart || isLinked || std::ranges::find(RENDER_SPECIAL_TYPES, type) != RENDER_SPECIAL_TYPES.end()) + reconstruction_missing("Entity_NPC::Render 006d2e50: a special enemy's drawing"); + if (spawnerEntity && spawnerEntity->type == ENTITY_PLAYER && g_manager->netplayManager.is_online()) + reconstruction_missing("Entity_NPC::Render 006d2e50: a remote player's faded enemy"); + if (championColorIdx == CHAMPION_SIZE_PULSE) + reconstruction_missing("Entity_NPC::Render 006d2e50: the size pulsing champion"); + + Entity::Render(offset); + if (!isVisible) + renderPosition = vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset); + lua_callback_check(CALLBACK_POST_NPC_RENDER, "Entity_NPC::Render 006d2e50: MC_POST_NPC_RENDER"); + + RenderMode renderMode = g_game->room->entityList.renderMode; + if (renderMode != RENDER_NORMAL && renderMode != RENDER_WATER_ABOVE) return; + status_overlay_render(offset); + if (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SPIDER_MOD_ID, LAZARUS_SHARE_CHECK) && isVisible && + IsActiveEnemy(DEAD_EXCLUDED)) + reconstruction_missing("Entity_NPC::Render 006d2e50: Spider Mod's health bar"); + if (HasEntityFlags(FLAG_PERSISTENT | FLAG_FRIENDLY_BALL_DYING) && (g_game->debugFlags & DEBUG_HEALTH_VALUES)) + reconstruction_missing("Entity_NPC::Render 006d2e50: the debug health text"); +} + +// Part of 006d2e50: the status effect sprite drawn on the OverlayEffect null, once on a shared body. +void Entity_NPC::status_overlay_render(const Vector& offset) +{ + bool isShown = + statusEffectSprite.isLoaded && statusEffectSprite.animState.animData && statusEffectSprite.animState.isPlaying; + if (!isShown) return; + + int nullIndex = sprite.null_index_get("OverlayEffect"); + if (nullIndex < 0) + { + if (!config) log_printf(LOG_INFO, "[warn] No OverlayEffect Null found for Entity (%d)\n", type); + else + log_printf(LOG_INFO, "[warn] No OverlayEffect Null found for Entity %s with sprite %s\n", + config->GetName(NAME_LANGUAGE_CURRENT).c_str(), sprite.filename.c_str()); + return; + } + const NullFrame* frame = sprite.GetNullFrameById(nullIndex); + bool isShared = statusEffectSprite.bitflags & STATUS_SHARED; + if (!frame || !frame->isVisible || (isShared && parent && is_same_segmented_body(nullptr))) return; + + statusEffectSprite.scale = frame->scale; + Vector at = + vector_add(vector_add(render_position_get(vector_add(pos, posOffset), RENDER_SNAPPED), offset), frame->pos); + statusEffectSprite.Render(SpriteDraw{at, {}, {}}); +} + +// 006d4840 Draws its shadow layer (Entity::RenderShadowLayer), a few with their links' shadows first. +bool Entity_NPC::RenderShadowLayer(const Vector& offset) +{ + if (type == ENTITY_SHADOW_OVERLAY_TYPE || (type == ENTITY_LARRYJR && variant == 3)) + reconstruction_missing("Entity_NPC::RenderShadowLayer 006d4840: a linked enemy's shadow"); + return Entity::RenderShadowLayer(offset); +} + +// 006d90e0 Moves the effect a controlled enemy aims with along the controller's input and keeps it in reach. +void Entity_NPC::UpdateChildEffectPosition(bool) +{ + if (controllerID == -1 || !aimTargetEffect) return; + reconstruction_missing("Entity_NPC::UpdateChildEffectPosition 006d90e0"); +} + +// 006d7010 With Spider Mod, shows the damage each hit of this frame dealt it as a rising number. +void Entity_NPC::spawn_damage_numbers() +{ + bool isShown = type == ENTITY_DAMAGE_NUMBERS_TYPE || + (g_game->playerManager.FirstCollectibleOwner(COLLECTIBLE_SPIDER_MOD_ID, LAZARUS_SHARE_CHECK) && + IsActiveEnemy(DEAD_EXCLUDED)); + if (!isShown || !isVisible || sprite.color._tint[3] <= 0 || health <= 0) return; + if (GetStatusEffectTarget() != this || isInvincible) return; + + auto isDealt = [](const DamageEvent& event) { + return event.damage > 0; + }; + if (std::ranges::any_of(damageEvents, isDealt)) + reconstruction_missing("Entity_NPC::spawn_damage_numbers 006d7010: the damage text"); +} + +// 006d7230 A shielded boss's shield: the damage of its last frames (shieldFrames) averaged per second, and past +// maxHitPoints / shieldStrength of it this frame's hits shrink. +void Entity_NPC::update_damage_history() +{ + Entity* root = this; + if (DoesEntityShareStatus()) + while (root->parent) root = root->parent; + if (!Entity::is_enemy_type(root->type)) root = this; + Entity_NPC& owner = static_cast(*root); + if (owner.shieldStrength <= 0) return; + + float frameDamage = 0; + for (const DamageEvent& event : damageEvents) + if (!(event.damageFlags & DAMAGE_INVINCIBLE)) frameDamage += event.damage; + if ((int)owner.damageHistory.size() >= owner.shieldFrames) owner.damageHistory.pop_front(); + owner.damageHistory.push_back(frameDamage); + + float total = 0; + for (float damage : owner.damageHistory) total += damage; + float perSecond = total / (float)owner.damageHistory.size() * SHIELD_SECOND; + float threshold = maxHitPoints / owner.shieldStrength; + float multiplier = 1; + if (threshold < perSecond) + { + float share = threshold / perSecond; + multiplier = std::max(SHIELD_BASE - share * SHIELD_FALLOFF, 0.0f) + share; + } + + pendingDamage = 0; + for (DamageEvent& event : damageEvents) + { + if (!(event.damageFlags & (DAMAGE_INVINCIBLE | DAMAGE_IGNORE_ARMOR))) event.damage *= multiplier; + pendingDamage += event.damage; + } +} + +// 006d5400 What happens as it leaves for good: a champion's drop or a boss's death, the dead enemy's flags' +// rewards (sticky spiders, black hearts), Jar of Flies' count, its removal, the on-kill items and its record. +void Entity_NPC::trigger_kill_item_effects() +{ + if (isBoss) reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: Room::TriggerBossDeath"); + if (isChampion) reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: NpcHelper::ChampionDrop"); + if (type == ENTITY_ROTGUT && variant == 1) + reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: Rotgut's death"); + if (HasEntityFlags(FLAG_SPAWN_STICKY_SPIDERS)) + reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: the sticky spiders"); + + if (!HasEntityFlags(FLAG_NO_REWARD)) + { + if (HasEntityFlags(FLAG_SPAWN_BLACK_HP) && dropRNG.Next() % BLACK_HEART_CHANCE == 0) + reconstruction_missing( + "Entity_NPC::trigger_kill_item_effects 006d5400: the black heart (Room::FindFreeTilePosition)"); + Entity_Player* jarOwner = + g_game->playerManager.RandomCollectibleOwner(COLLECTIBLE_JAR_OF_FLIES_ID, dropRNG.Next(), nullptr); + if (jarOwner && (HasEntityFlags(FLAG_ADD_JAR_FLY | FLAG_FREEZE) || HasEntityFlags(FLAG_ICE_FROZEN))) + reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: Jar of Flies' count"); + } + + if (type == ENTITY_HUSH) AddEntityFlags(FLAG_RENDER_FLOOR); + else Remove(); + + PlayerManager& players = g_game->playerManager; + bool isKillItem = players.FirstCollectibleOwner(COLLECTIBLE_CONTAGION_ID, LAZARUS_SHARE_IGNORE) || + players.FirstCollectibleOwner(COLLECTIBLE_MAW_OF_THE_VOID_ID, LAZARUS_SHARE_IGNORE) || + (IsFriendly() && g_game->challenge == CHALLENGE_KILL_CHARGE) || + HasEntityFlags(FLAG_FRIENDLY_BALL); + if (isKillItem) + reconstruction_missing( + "Entity_NPC::trigger_kill_item_effects 006d5400: Contagion, Maw of the Void and Lemegeton"); + + g_game->room->isFirstEnemyDead = true; + // Room::record_killed_npc 00820d30 waits for Room to hold the list of killed enemies, which nothing reads yet. + entityRef = nullptr; + aimTargetEffect = nullptr; + if (HasEntityFlags(FLAG_BRIMSTONE_MARKED) && HasEntityFlags(FLAG_EXTRA_GORE)) + reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400: the marked enemy's spreading status"); + lua_callback_check(CALLBACK_POST_NPC_DEATH, "Entity_NPC::trigger_kill_item_effects 006d5400: MC_POST_NPC_DEATH"); +} + +// 006bbdc0 The rewards a dead enemy gives its killers: the damage flags' and Gimpy's drops, the familiars' and +// items' on-kill effects, Keeper's and the bosses' coins, the soul hearts of Sanguine Bond and the like. None of them +// happens without its item or flag, which is all this covers yet. +void Entity_NPC::trigger_death_rewards() +{ + bool isRewarded = Entity::is_enemy_type(type) && type != ENTITY_FIREPLACE && type != ENTITY_SHOPKEEPER && + type != ENTITY_MOVABLE_TNT && !(type == ENTITY_DEATH_REWARD_EXEMPT && variant == 10) && + type != ENTITY_FROZEN_ENEMY && type != ENTITY_MINECART && type != ENTITY_POOP; + if (!isRewarded) return; + if (DoesEntityShareStatus() && parent && type != ENTITY_LARRYJR && type != ENTITY_BUTTLICKER) return; + + PlayerManager& players = g_game->playerManager; + auto isFamiliarKill = [](const DamageEvent& event) { + return event.source.type == ENTITY_FAMILIAR || event.source.type == ENTITY_BLOOD_PUPPY || + (event.source.type == ENTITY_TEAR && + (event.source.variant == ENTITY_KEY_TEAR_A || event.source.variant == ENTITY_KEY_TEAR_B)); + }; + bool isRewardItem = players.FirstCollectibleOwner(COLLECTIBLE_GIMPY_ID, LAZARUS_SHARE_CHECK) || + (killDamageFlags & ((uint64_t)DAMAGE_SPAWN_RED_HEART | DAMAGE_SPAWN_COIN | + DAMAGE_SPAWN_BLACK_HEART | DAMAGE_SPAWN_CARD | DAMAGE_SPAWN_RUNE)) || + std::ranges::any_of(killDamageEvents, isFamiliarKill) || + players.RandomCollectibleOwner(COLLECTIBLE_INFESTATION_2_ID, initSeed, nullptr) || + players.RandomCollectibleOwner(COLLECTIBLE_BONE_SPURS_ID, initSeed, nullptr) || + players.RandomCollectibleOwner(COLLECTIBLE_LIL_ABADDON_ID, initSeed, nullptr) || + players.RandomTrinketOwner(TRINKET_DEVILS_CROWN_ID, initSeed, nullptr) || + players.FirstCollectibleOwner(COLLECTIBLE_VASCULITIS_ID, LAZARUS_SHARE_CHECK); + if (!HasEntityFlags(FLAG_NO_REWARD) && isRewardItem) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: the kill's item and flag rewards"); + if (!CanShutDoors()) return; + + if (g_game->room->isExorcistActive && g_game->room->IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: the Exorcist's souls"); + if (g_game->room->IsPositionInRoom(pos, EXORCIST_ROOM_MARGIN)) + for (Entity_Player* player : players.playerList) + if (player->variant == 0 && player->HasCollectible(COLLECTIBLE_LIL_PORTAL_ID)) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Lil Portal's growth"); + for (Entity_Player* player : players.playerList) + { + bool isLiving = player->variant == 0 && !player->isCoopGhost; + if (isLiving && player->playerType == PLAYER_MAGDALENE_B) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: Tainted Magdalene's hearts"); + if (player->variant == 0 && player->HasCollectible(COLLECTIBLE_SANGUINE_BOND_ID)) + reconstruction_missing("Entity_NPC::trigger_death_rewards 006bbdc0: the soul drops"); + } +} + +// 00447770 Its parent, which only NPCs are. +Entity_NPC* Entity_NPC::ParentNPC() +{ + if (parent && !dynamic_cast(parent.get())) log_printf(LOG_ASSERT, "m_Parent invalid downcast\n"); + return static_cast(parent.get()); +} + +// 004567e0 Its child, which only NPCs are. +Entity_NPC* Entity_NPC::ChildNPC() +{ + if (child && !dynamic_cast(child.get())) log_printf(LOG_ASSERT, "m_Child invalid downcast\n"); + return static_cast(child.get()); +} + +// 006d8cf0 Removes the effect a controlled enemy aims with. +void Entity_NPC::ClearChild() +{ + if (!aimTargetEffect) return; + aimTargetEffect->Remove(); + aimTargetEffect = nullptr; +} + +// 006d0c20 +void Entity_NPC::SetRef_bec(Entity* entity) +{ + entityRef = entity; +} + +// 0060d140 +void Entity_NPC::set_entity_ptr_f54(Entity* entity) +{ + unknownF54 = entity; +} + +// 006b5e20 Holds it at a position for the longer of the countdowns. +void Entity_NPC::hold_set(int countdown, const Vector& position) +{ + holdCountdown = std::max(countdown, holdCountdown); + holdPosition = position; +} + +// 006d8260 Whether the controlling player holds an action, never without one. +bool Entity_NPC::IsControllerActionPressed(int) +{ + if (controllerID == -1) return false; + reconstruction_missing("Entity_NPC::IsControllerActionPressed 006d8260"); +} + +// 006d8290 Whether the controlling player pressed an action this frame, never without one. +bool Entity_NPC::IsControllerActionTriggered(int buttonAction) +{ + if (controllerID == -1) return false; + (void)buttonAction; + reconstruction_missing("Entity_NPC::IsControllerActionTriggered 006d8290"); +} + +// 006d82d0 The controlling player's shooting input, none without one. +Vector Entity_NPC::GetControllerInput(float) +{ + if (controllerID == -1) return {}; + reconstruction_missing("Entity_NPC::GetControllerInput 006d82d0"); +} + +// 006d85a0 The controlling player's movement input, none without one. +Vector Entity_NPC::GetControllerMovementInput(float) +{ + if (controllerID == -1) return {}; + reconstruction_missing("Entity_NPC::GetControllerMovementInput 006d85a0"); +} + +// 006d9050 Keeps the controlling player's last movement, or none without one. +void Entity_NPC::UpdateControllerMovement(bool) +{ + if (controllerID == -1) + { + controllerMovement = {}; + return; + } + reconstruction_missing("Entity_NPC::UpdateControllerMovement 006d9050"); } // The rest of Entity_NPC is not reconstructed yet. -// 006b8b20 -void Entity_NPC::Init(int, int, int, uint32_t) -{ - reconstruction_missing("Entity_NPC::Init 006b8b20"); -} - -// 006c4b30 -void Entity_NPC::Update() -{ - reconstruction_missing("Entity_NPC::Update 006c4b30"); -} - -// 006d2b50 -void Entity_NPC::Interpolate() -{ - reconstruction_missing("Entity_NPC::Interpolate 006d2b50"); -} - -// 006d2e50 -void Entity_NPC::Render(const Vector&) -{ - reconstruction_missing("Entity_NPC::Render 006d2e50"); -} - -// 006d4840 -bool Entity_NPC::RenderShadowLayer(const Vector&) -{ - reconstruction_missing("Entity_NPC::RenderShadowLayer 006d4840"); -} - -// 006d60a0 -bool Entity_NPC::TakeDamage(float, uint64_t, const EntityRef&, int) -{ - reconstruction_missing("Entity_NPC::TakeDamage 006d60a0"); -} - -// 006be6f0 -void Entity_NPC::Kill(const EntityRef&) -{ - reconstruction_missing("Entity_NPC::Kill 006be6f0"); -} - -// 006b8f30 -void Entity_NPC::ClearReferences() -{ - reconstruction_missing("Entity_NPC::ClearReferences 006b8f30"); -} - // 006d9440 bool Entity_NPC::TryThrow(const EntityRef&, const Vector&, float) { reconstruction_missing("Entity_NPC::TryThrow 006d9440"); } -// 006d48a0 -Vector Entity_NPC::GetForwardVector() -{ - reconstruction_missing("Entity_NPC::GetForwardVector 006d48a0"); -} - -// 006cd410 -bool Entity_NPC::HandleCollision(Entity*, bool) -{ - reconstruction_missing("Entity_NPC::HandleCollision 006cd410"); -} - -// 006c1100 -void Entity_NPC::ResetColor() -{ - reconstruction_missing("Entity_NPC::ResetColor 006c1100"); -} - -// 006bb790 -void Entity_NPC::LoadEntityConfig() -{ - reconstruction_missing("Entity_NPC::LoadEntityConfig 006bb790"); -} - -// 00447770 -Entity_NPC* Entity_NPC::ParentNPC() -{ - reconstruction_missing("Entity_NPC::ParentNPC 00447770"); -} - -// 004567e0 -Entity_NPC* Entity_NPC::ChildNPC() -{ - reconstruction_missing("Entity_NPC::ChildNPC 004567e0"); -} - // 004b92e0 void Entity_NPC::Hornfel_UpdateAI() { @@ -229,84 +2643,18 @@ void Entity_NPC::CreateGoldParticles(uint32_t) reconstruction_missing("Entity_NPC::CreateGoldParticles 0059e4c0"); } -// 0060d140 -void Entity_NPC::set_entity_ptr_f54(Entity*) -{ - reconstruction_missing("Entity_NPC::set_entity_ptr_f54 0060d140"); -} - -// 006b5e20 -void Entity_NPC::hold_set(int, const Vector&) -{ - reconstruction_missing("Entity_NPC::hold_set 006b5e20"); -} - -// 006b64d0 -Entity_Effect* Entity_NPC::MakeSplat(float) -{ - reconstruction_missing("Entity_NPC::MakeSplat 006b64d0"); -} - // 006b6830 Entity_Effect* Entity_NPC::MakeBloodCloud(const Vector&, const ColorMod&) { reconstruction_missing("Entity_NPC::MakeBloodCloud 006b6830"); } -// 006b9910 -bool Entity_NPC::TryForceTarget(Entity*, int) -{ - reconstruction_missing("Entity_NPC::TryForceTarget 006b9910"); -} - -// 006b99e0 -float Entity_NPC::compute_speed_multiplier() -{ - reconstruction_missing("Entity_NPC::compute_speed_multiplier 006b99e0"); -} - -// 006baf40 -void Entity_NPC::load_graphics(uint8_t) -{ - reconstruction_missing("Entity_NPC::load_graphics 006baf40"); -} - // 006be760 void Entity_NPC::KillUnique() { reconstruction_missing("Entity_NPC::KillUnique 006be760"); } -// 006be840 -Entity* Entity_NPC::GetPlayerTarget() -{ - reconstruction_missing("Entity_NPC::GetPlayerTarget 006be840"); -} - -// 006bec40 -Vector Entity_NPC::CalcTargetPosition(float) -{ - reconstruction_missing("Entity_NPC::CalcTargetPosition 006bec40"); -} - -// 006c04b0 -void Entity_NPC::UpdateDirtColor(uint8_t) -{ - reconstruction_missing("Entity_NPC::UpdateDirtColor 006c04b0"); -} - -// 006c07e0 -uint8_t Entity_NPC::Redirect(int*, int*) -{ - reconstruction_missing("Entity_NPC::Redirect 006c07e0"); -} - -// 006c0f30 -void Entity_NPC::Morph(int, int, int, int) -{ - reconstruction_missing("Entity_NPC::Morph 006c0f30"); -} - // 006c1ac0 void* Entity_NPC::shopkeeper_get_loot(void*, bool) { @@ -325,28 +2673,10 @@ void Entity_NPC::update_frozen() reconstruction_missing("Entity_NPC::update_frozen 006ca930"); } -// 006cb2a0 -void Entity_NPC::fire_projectile_from_params(Entity_Projectile*) +// 006ccdd0 +void Entity_NPC::FireBossProjectiles(int, const Vector&, float, const ProjectileParams&) { - reconstruction_missing("Entity_NPC::fire_projectile_from_params 006cb2a0"); -} - -// 006d0300 -void Entity_NPC::SetBossColorIdx(int, int) -{ - reconstruction_missing("Entity_NPC::SetBossColorIdx 006d0300"); -} - -// 006d03e0 -void Entity_NPC::MakeChampion(uint32_t, int, bool) -{ - reconstruction_missing("Entity_NPC::MakeChampion 006d03e0"); -} - -// 006d0c20 -void Entity_NPC::SetRef_bec(Entity*) -{ - reconstruction_missing("Entity_NPC::SetRef_bec 006d0c20"); + reconstruction_missing("Entity_NPC::FireBossProjectiles 006ccdd0"); } // 006d0c60 @@ -379,30 +2709,6 @@ bool Entity_NPC::CanReroll() reconstruction_missing("Entity_NPC::CanReroll 006d4db0"); } -// 006d4e00 -void Entity_NPC::PlayDeathEffects() -{ - reconstruction_missing("Entity_NPC::PlayDeathEffects 006d4e00"); -} - -// 006d5400 -void Entity_NPC::trigger_kill_item_effects() -{ - reconstruction_missing("Entity_NPC::trigger_kill_item_effects 006d5400"); -} - -// 006d6ba0 -void Entity_NPC::PlaySound(int, float, int, uint8_t, float) -{ - reconstruction_missing("Entity_NPC::PlaySound 006d6ba0"); -} - -// 006d6c20 -int Entity_NPC::GetAliveEnemyCount() -{ - reconstruction_missing("Entity_NPC::GetAliveEnemyCount 006d6c20"); -} - // 006d6d20 uint32_t Entity_NPC::on_player_damaged() { @@ -415,54 +2721,12 @@ void Entity_NPC::room_enter() reconstruction_missing("Entity_NPC::room_enter 006d6d80"); } -// 006d7010 -void Entity_NPC::spawn_damage_numbers() -{ - reconstruction_missing("Entity_NPC::spawn_damage_numbers 006d7010"); -} - -// 006d7230 -void Entity_NPC::update_damage_history() -{ - reconstruction_missing("Entity_NPC::update_damage_history 006d7230"); -} - // 006d7520 void Entity_NPC::update_blood_guide_gibs(float*) { reconstruction_missing("Entity_NPC::update_blood_guide_gibs 006d7520"); } -// 006d81c0 -void Entity_NPC::ClearDequeRefs() -{ - reconstruction_missing("Entity_NPC::ClearDequeRefs 006d81c0"); -} - -// 006d8260 -bool Entity_NPC::IsControllerActionPressed(int) -{ - reconstruction_missing("Entity_NPC::IsControllerActionPressed 006d8260"); -} - -// 006d8290 -bool Entity_NPC::IsControllerActionTriggered(int) -{ - reconstruction_missing("Entity_NPC::IsControllerActionTriggered 006d8290"); -} - -// 006d82d0 -Vector Entity_NPC::GetControllerInput(float) -{ - reconstruction_missing("Entity_NPC::GetControllerInput 006d82d0"); -} - -// 006d85a0 -Vector Entity_NPC::GetControllerMovementInput(float) -{ - reconstruction_missing("Entity_NPC::GetControllerMovementInput 006d85a0"); -} - // 006d88b0 void Entity_NPC::TransferControl(Entity_NPC*) { @@ -475,12 +2739,6 @@ void Entity_NPC::SpawnControlTarget(int, float) reconstruction_missing("Entity_NPC::SpawnControlTarget 006d8b20"); } -// 006d8cf0 -void Entity_NPC::ClearChild() -{ - reconstruction_missing("Entity_NPC::ClearChild 006d8cf0"); -} - // 006d8d30 Vector Entity_NPC::GetAimTargetPosition() { @@ -499,18 +2757,6 @@ void Entity_NPC::UpdateChargeBar(float, float, float, bool) reconstruction_missing("Entity_NPC::UpdateChargeBar 006d8e40"); } -// 006d9050 -void Entity_NPC::UpdateControllerMovement(bool) -{ - reconstruction_missing("Entity_NPC::UpdateControllerMovement 006d9050"); -} - -// 006d90e0 -void Entity_NPC::UpdateChildEffectPosition(bool) -{ - reconstruction_missing("Entity_NPC::UpdateChildEffectPosition 006d90e0"); -} - // 006d97e0 uint8_t Entity_NPC::split(float, const EntityRef&, bool) { diff --git a/src/entity_npc.h b/src/entity_npc.h index 13ca14f..c1b4171 100644 --- a/src/entity_npc.h +++ b/src/entity_npc.h @@ -2,71 +2,202 @@ #include "entity.h" #include "anm2.h" +#include "path_finder.h" #include #include -// Construction and destruction (006b88e0, 006b8590) are the defaults, but for the pathfinder's owner the constructor -// sets. PathFinder::Init's reset waits for PathFinder's takeover. -// Field accessors (004567a0, 006a8230, 006b8480, 007e92b0) are the public fields. +// Lua's NpcState: where an NPC's AI is in its routine. State 1 holds the AI while the NPC appears. +enum NpcState : int +{ + NPC_STATE_INIT = 0, + NPC_STATE_APPEAR = 1, + NPC_STATE_APPEAR_CUSTOM = 2, + NPC_STATE_IDLE = 3, + NPC_STATE_MOVE = 4, + NPC_STATE_SUICIDE = 5, + NPC_STATE_JUMP = 6, + NPC_STATE_STOMP = 7, + NPC_STATE_ATTACK = 8, + NPC_STATE_ATTACK2 = 9, + NPC_STATE_ATTACK3 = 10, + NPC_STATE_ATTACK4 = 11, + NPC_STATE_ATTACK5 = 12, + NPC_STATE_SUMMON = 13, + NPC_STATE_SUMMON2 = 14, + NPC_STATE_SUMMON3 = 15, + NPC_STATE_SPECIAL = 16, + NPC_STATE_UNIQUE_DEATH = 17, + NPC_STATE_DEATH = 18 +}; + +// Which extra AI calls an NPC asks for (_aiCallFlags), and the phase (_aiCallPhase) the AI sees in each. +enum AiCall : uint32_t +{ + AI_CALL_PRE_UPDATE = 1 << 0, + AI_CALL_INTERPOLATE = 1 << 1, + AI_CALL_COLLISION = 1 << 2, + AI_CALL_POST_UPDATE = 1 << 3 +}; + +enum AiPhase : int +{ + AI_PHASE_UPDATE = 0, + AI_PHASE_PRE_UPDATE = 1, + AI_PHASE_INTERPOLATE = 2, + AI_PHASE_COLLISION = 3, + AI_PHASE_POST_UPDATE = 4 +}; + +// The spreads FireProjectiles shoots (Lua's ProjectilesMode): fans of one to five shots along the velocity, plus and +// cross shapes and their union at the velocity's x, and a ring of round(velocity.y) shots at the velocity's x. +enum ProjectilesMode : int +{ + PROJECTILES_SINGLE, + PROJECTILES_TWO, + PROJECTILES_THREE, + PROJECTILES_THREE_WIDE, + PROJECTILES_FOUR, + PROJECTILES_FIVE, + PROJECTILES_PLUS, + PROJECTILES_CROSS, + PROJECTILES_EIGHT, + PROJECTILES_RING +}; + +// Lua's ChampionColor values the NPC code tests. +enum ChampionColor : int +{ + CHAMPION_NONE = -1, + CHAMPION_RED = 0, + CHAMPION_YELLOW = 1, + CHAMPION_GREEN = 2, + CHAMPION_ORANGE = 3, + CHAMPION_DARK_BLUE = 4, + CHAMPION_DARK_GREEN = 5, + CHAMPION_WHITE = 6, + CHAMPION_GREY = 7, + CHAMPION_TRANSPARENT = 8, + CHAMPION_FLICKER = 9, + CHAMPION_PINK = 10, + CHAMPION_PURPLE = 11, + CHAMPION_DARK_RED = 12, + CHAMPION_LIGHT_BLUE = 13, + CHAMPION_CAMO = 14, + CHAMPION_PULSE_GREEN = 15, + CHAMPION_PULSE_GREY = 16, + CHAMPION_FLY_PROTECTED = 17, + CHAMPION_TINY = 18, + CHAMPION_GIANT = 19, + CHAMPION_PULSE_RED = 20, + CHAMPION_SIZE_PULSE = 21, + CHAMPION_KING = 22, + CHAMPION_DEATH = 23, + CHAMPION_BROWN = 24, + CHAMPION_RAINBOW = 25, + CHAMPION_COUNT = 26 +}; + +// Construction (0043ef30) is the default, but for the circle angle it draws at random. +// How FireProjectiles shoots (Lua's ProjectileParams): the shots' variant, look, fall, homing and change, and the +// spread they leave in. +struct ProjectileParams +{ + ColorMod color = COLOR_DEFAULT; + Vector fireDirectionLimit{}; + Vector positionOffset{}; + Vector targetPosition{}; + uint64_t bulletFlags = 0; + uint64_t changeFlags = 0; + float acceleration = 1.01f; + float changeVelocity = 0; + float circleAngle; + float curvingStrength = 0.005f; + float damage = -1; + float depthOffset = 0; + float dotProductLimit = -1000; + float fallingAccelModifier = 0; + float fallingSpeedModifier = 0; + float heightModifier = 0; + float homingStrength = 1; + float scale = 1; + float spread = 1; + float unknownA0 = 0; + float velocityMulti = 1; + int changeTimeout = 30; + int variant = 0; + int wiggleFrameOffset = 0; + bool isGridCollision = true; + bool isFallingKept = false; + bool isRenderedAtGround = false; + + ProjectileParams(); +}; + +// Construction and destruction (006b88e0, 006b8590, 006b8910) are the defaults. +// Field accessors (004567a0, 006a8230, 006b8480, 007e92b0, 004e4850) are the public fields. // An enemy or other non-player character (Lua's EntityNPC): its AI state and counters, pathfinder, champion and boss // colors, shields, Delirium's forms, and the player controlling it with Siren or a friendly ball. struct Entity_NPC : Entity { ANM2 chargeBarSprite; ANM2 statusEffectSprite; - NPCAI_Pathfinder pathfinder{}; + PathFinder pathfinder{this}; std::deque entityDeque; std::deque vectorDeque1; std::deque vectorDeque2; + std::deque damageHistory; std::vector killDamageEvents; std::vector hitList; std::vector secondaryHitList; ColorMod dirtColor = COLOR_DEFAULT; ColorMod floorColor = COLOR_DEFAULT; + EntityPtr aimTargetEffect; EntityPtr entityRef; EntityPtr forcedTarget; + EntityPtr pickupGhostsEntity; + EntityPtr salvationTarget; + EntityPtr unknownF54; Entity* collisionEntity = nullptr; Entity* deliriumEntity = nullptr; - Entity_Effect* pickupGhostsEntity = nullptr; Entity_Player* sirenPlayerEntity = nullptr; - void* aimTargetEffect = nullptr; uint64_t killDamageFlags = 0; Vector confusionTargetPos{}; Vector controllerMovement{}; Vector forwardVector{}; Vector v1{}; Vector v2{}; - float aiFloat = 0; - float championSpeed = 0; - float flickerAlpha = 0; - float hitPointsMulti = 0; + float aiFloat = 1; + float championSpeed = 1; + float flickerAlpha = 1; + float hitPointsMulti = 1; float killDamage = 0; - float scale = 0; - float scaleMulti = 0; + float scale = 1; + float scaleMulti = 1; float shieldStrength = 0; float totalDamageTaken = 0; - int aiCallPhase = 0; + int aiCallPhase = AI_PHASE_UPDATE; int aiCounter = 0; int appearFrames = 0; - int bosscoloridx = 0; - int championColorIdx = 0; + int bosscoloridx = -1; + int championColorIdx = CHAMPION_NONE; int championTimer = 0; int collisionResult = 0; - int controllerID = 0; + int controllerID = -1; int decoyTargetTimer = 0; int flickerState = 0; int flickerTimer = 0; int forcedTargetTimer = 0; - int groupIdx = 0; + int groupIdx = -1; int i1 = 0; int i2 = 0; - int lastGridIndex = 0; + int lastGridIndex = -1; int projectileCooldown = 0; - int projectileDelay = 0; + int projectileDelay = -1; int savedState = 0; int shieldFrames = 0; - int state = 0; + int state = NPC_STATE_INIT; int stateFrame = 0; + int unknownF2c = 0; uint32_t aiCallFlags = 0; uint32_t deliriumAttackID = 0; uint32_t deliriumBossType = 0; @@ -84,10 +215,11 @@ struct Entity_NPC : Entity bool isCanShutDoors = false; bool isChampion = false; bool isCollisionIsLow = false; + bool isDeathSoundAlt = false; + bool isUnknownC61 = false; + bool isUnknownC62 = false; bool isUnreachableOnce = false; - Entity_NPC() { pathfinder._entity = this; } - void Init(int type, int variant, int subType, uint32_t initSeed) override; void PreUpdate() override; void Update() override; @@ -106,75 +238,127 @@ struct Entity_NPC : Entity void ResetColor() override; void LoadEntityConfig() override; - Entity_NPC* ParentNPC(); - Entity_NPC* ChildNPC(); - void Hornfel_UpdateAI(); - void Hornfel_UpdateFrame(); - void update_physics(); - void apply_velocity(char); - void update_move_direction_anim(); - void SetMinecartPosVel(const Vector& pos, const Vector& vel); - void MinecartUpdateChild(Entity* child); - void UpdateCordChain(bool isHalfScale); - void render_overlay(const Vector& offset, bool isShadow); - static int FindTargetPit(const Vector& pos1, const Vector& pos2, uint32_t pitIndex); - static Entity_NPC* ThrowStrider(const Vector& pos, Entity* spawner, const Vector& targetPos); - void render_v1_layer_frames(); - void RenderSegmentLink(const Vector& offset, bool isShadow); - void CreateBling(); - void CreateGoldParticles(uint32_t count); - void set_entity_ptr_f54(Entity* entity); - void ResetPathFinderTarget(); - void hold_set(int countdown, const Vector& position); - Entity_Effect* MakeSplat(float size); - Entity_Effect* MakeBloodCloud(const Vector& pos, const ColorMod& color); - bool TryForceTarget(Entity* target, int duration); - float compute_speed_multiplier(); - void load_graphics(uint8_t); - void KillUnique(); - Entity* GetPlayerTarget(); - Vector CalcTargetPosition(float distanceLimit); - void UpdateDirtColor(uint8_t immediate); - static uint8_t Redirect(int* entityType, int* variant); - void Morph(int entityType, int variant, int subType, int championid); - void* shopkeeper_get_loot(void* outLoot, bool isShouldAdvance); - static Entity_NPC* ThrowSpider(const Vector& position, Entity* spawner, Vector targetPos, bool isBig, - float yOffset); - void update_frozen(); - void fire_projectile_from_params(Entity_Projectile* projectile); - void SetBossColorIdx(int bossColorIdx, int unused); + void load_graphics(bool isReloadAnm2); + void boss_color_roll(); + static bool Redirect(int* entityType, int* variant); + void Morph(int entityType, int variant, int subType, int championId); void MakeChampion(uint32_t seed, int championColor, bool isInit); - void SetRef_bec(Entity* entity); - static void* QueryNPCsType(void* outList, int type, int variant); - static EntityList* QueryNPCsGroup(EntityList* outList, int groupIdx); - void* fireplace_get_loot(void* outLoot, bool isShouldAdvance); - bool CanBeDamagedFromVelocity(Vector velocity); - bool CanReroll(); - void PlayDeathEffects(); - void trigger_kill_item_effects(); + void SetBossColorIdx(int bossColorIdx, int unused); void SetScale(float newScale); - void PlaySound(int id, float volume, int framedelay, uint8_t loop, float pitch); - int GetAliveEnemyCount(); - uint32_t on_player_damaged(); + void UpdateDirtColor(bool isImmediate); void room_enter(); + + float compute_speed_multiplier(); + void ai_call(AiPhase phase); + void status_overlay_update(); + bool paused_update(); + void appear_update(); + void appear_init(); + void death_animation_update(); + void death_animation_start(); + void decoy_update(); + void champion_update(); + void unreachable_update(); + void dead_update(); + void midas_coins_spawn(); + void toxic_shock_creep_spawn(); + void player_aura_update(); + void item_effects_update(); + void poof02_spawn(); + void ripple_spawn(); + void seed_effects_update(); + void type_update(); + void forced_target_update(); + void update_frozen(); + void update_physics(); + void apply_velocity(char isInterpolated); + void update_move_direction_anim(); + void update_blood_guide_gibs(float* nullFrame); void spawn_damage_numbers(); void update_damage_history(); - void update_blood_guide_gibs(float* nullFrame); + void status_overlay_render(const Vector& offset); + void Hornfel_UpdateAI(); + void Hornfel_UpdateFrame(); + + Entity* GetPlayerTarget(); + Vector CalcTargetPosition(float distanceLimit); + bool TryForceTarget(Entity* target, int duration); + void ResetPathFinderTarget(); + bool IsTargetInAttackRange(float range, int frameInterval, bool isPredictVelocity); + int GetAliveEnemyCount(); + void AnimWalkFrame(std::string_view horizontalAnim, std::string_view verticalAnim, float speedThreshold); + void PlaySound(int id, float volume, int frameDelay, bool isLoop, float pitch); + void FireProjectiles(const Vector& position, const Vector& velocity, ProjectilesMode mode, + const ProjectileParams& params); + void FireBossProjectiles(int count, const Vector& targetPos, float trajectoryModifier, + const ProjectileParams& params); + void projectile_params_apply(Entity_Projectile& projectile, const ProjectileParams& params); + void fire_projectile_from_params(Entity_Projectile* projectile); + Entity_Effect* MakeSplat(float size); + Entity_Effect* MakeBloodCloud(const Vector& pos, const ColorMod& color); + static Entity_NPC* ThrowSpider(const Vector& position, Entity* spawner, Vector targetPos, bool isBig, + float yOffset); + + void player_contact(Entity_Player& player); + void enemy_contact(Entity& other); + void PlayDeathEffects(); + int death_burst_get(); + void trigger_kill_item_effects(); + void trigger_death_rewards(); + void KillUnique(); + bool CanBeDamagedFromVelocity(Vector velocity); + bool CanReroll(); + uint8_t split(float damage, const EntityRef& source, bool isPlaySound); + + Entity_NPC* ParentNPC(); + Entity_NPC* ChildNPC(); + void ClearChild(); void ClearDequeRefs(); + void set_entity_ptr_f54(Entity* entity); + void SetRef_bec(Entity* entity); + void hold_set(int countdown, const Vector& position); + bool IsControllerActionPressed(int action); bool IsControllerActionTriggered(int buttonAction); Vector GetControllerInput(float deadzone); Vector GetControllerMovementInput(float deadzone); - void TransferControl(Entity_NPC* target); - void SpawnControlTarget(int inputMode, float rotation); - void ClearChild(); - Vector GetAimTargetPosition(); bool is_controller_input_idle(); - void UpdateChargeBar(float start, float end, float value, bool isHideWhenFull); void UpdateControllerMovement(bool isForceUpdate); void UpdateChildEffectPosition(bool isPredictMovement); - uint8_t split(float damage, const EntityRef& source, bool isPlaySound); - void UpdatePickupGhosts(); + void TransferControl(Entity_NPC* target); + void SpawnControlTarget(int inputMode, float rotation); + Vector GetAimTargetPosition(); void SetAimAngle(float angle); - static void render_debug(float*, int); + void UpdateChargeBar(float start, float end, float value, bool isHideWhenFull); + void UpdatePickupGhosts(); + + void SetMinecartPosVel(const Vector& pos, const Vector& vel); + void MinecartUpdateChild(Entity* child); + void UpdateCordChain(bool isHalfScale); + void render_overlay(const Vector& offset, bool isShadow); + void render_v1_layer_frames(); + void RenderSegmentLink(const Vector& offset, bool isShadow); + void CreateBling(); + void CreateGoldParticles(uint32_t count); + void* shopkeeper_get_loot(void* outLoot, bool isShouldAdvance); + void* fireplace_get_loot(void* outLoot, bool isShouldAdvance); + uint32_t on_player_damaged(); + static int FindTargetPit(const Vector& pos1, const Vector& pos2, uint32_t pitIndex); + static Entity_NPC* ThrowStrider(const Vector& pos, Entity* spawner, const Vector& targetPos); + static void* QueryNPCsType(void* outList, int type, int variant); + static EntityList* QueryNPCsGroup(EntityList* outList, int groupIdx); + static void render_debug(float* position, int unused); }; + +extern bool g_isChampionRollSkipped; + +// Game's, Room's and PlayerManager's queries the enemies need, until those classes carry them. +Entity_Player* game_nearest_player(const Vector& position); +bool game_is_enemy_erased(Entity& entity); +bool any_player_flying(); +Entity* game_nearest_target_player(const Vector& position, Entity* source, bool isPlayersOnly, bool isTargetDecoys, + float maxDistance); +void game_shake_screen(int timeout); +bool game_is_hard_mode(); +uint32_t room_grid_collision_at(const Vector& position); +bool room_check_line(const Vector& start, const Vector& end, int mode, int gridPathThreshold); diff --git a/src/entity_pickup.cpp b/src/entity_pickup.cpp index f6b248b..8f75bf1 100644 --- a/src/entity_pickup.cpp +++ b/src/entity_pickup.cpp @@ -1,11 +1,1812 @@ #include "entity_pickup.h" +#include "entity_config.h" #include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity.h" #include "log.h" +#include "lua_engine.h" +#include "manager.h" +#include "platform.h" +#include "room.h" #include #include +#include +#include + +// Lua's PickupVariant: the kinds of pickup. +enum PickupVariant : int +{ + PICKUP_NULL = 0, + PICKUP_HEART = 10, + PICKUP_COIN = 20, + PICKUP_KEY = 30, + PICKUP_BOMB = 40, + PICKUP_THROWABLEBOMB = 41, + PICKUP_POOP = 42, + PICKUP_CHEST = 50, + PICKUP_BOMBCHEST = 51, + PICKUP_SPIKEDCHEST = 52, + PICKUP_ETERNALCHEST = 53, + PICKUP_MIMICCHEST = 54, + PICKUP_OLDCHEST = 55, + PICKUP_WOODENCHEST = 56, + PICKUP_MEGACHEST = 57, + PICKUP_HAUNTEDCHEST = 58, + PICKUP_LOCKEDCHEST = 60, + PICKUP_GRAB_BAG = 69, + PICKUP_PILL = 70, + PICKUP_LIL_BATTERY = 90, + PICKUP_COLLECTIBLE = 100, + PICKUP_BROKEN_SHOVEL = 110, + PICKUP_SHOPITEM = 150, + PICKUP_TAROTCARD = 300, + PICKUP_BIGCHEST = 340, + PICKUP_TRINKET = 350, + PICKUP_REDCHEST = 360, + PICKUP_TROPHY = 370, + PICKUP_BED = 380, + PICKUP_MOMSCHEST = 390 +}; // The chest variants (chest, locked, red, bomb, eternal, spiked, mimic, mom's, old, wooden, mega, haunted). -constexpr std::array CHESTS = {50, 60, 360, 51, 53, 52, 54, 390, 55, 56, 57, 58}; +constexpr std::array CHESTS = {PICKUP_CHEST, PICKUP_LOCKEDCHEST, PICKUP_REDCHEST, PICKUP_BOMBCHEST, + PICKUP_ETERNALCHEST, PICKUP_SPIKEDCHEST, PICKUP_MIMICCHEST, PICKUP_MOMSCHEST, + PICKUP_OLDCHEST, PICKUP_WOODENCHEST, PICKUP_MEGACHEST, + PICKUP_HAUNTEDCHEST}; + +// The coins a coin subtype is worth (penny, nickel, dime, double, lucky, sticky, golden), from subtype 1. +constexpr std::array COIN_VALUES = {1, 1, 5, 10, 2, 1, 5, 1}; + +// The pickup subtypes the code tells apart, as Lua's HeartSubType, CoinSubType, KeySubType and BombSubType name them. +// HeartKind (entity_player.h) holds the soul, black, golden, bone and rotten hearts. +enum HeartSubType : int +{ + HEART_FULL = 1, + HEART_HALF = 2, + HEART_ETERNAL = 4, + HEART_DOUBLEPACK = 5, + HEART_HALF_SOUL = 8, + HEART_SCARED = 9, + HEART_BLENDED = 10 +}; +enum CoinSubType : int +{ + COIN_PENNY = 1, + COIN_NICKEL, + COIN_DIME, + COIN_DOUBLEPACK, + COIN_LUCKYPENNY, + COIN_STICKYNICKEL, + COIN_GOLDEN +}; +enum KeySubType : int +{ + KEY_NORMAL = 1, + KEY_GOLDEN, + KEY_DOUBLEPACK, + KEY_CHARGED +}; +enum BombSubType : int +{ + BOMB_NORMAL = 1, + BOMB_DOUBLEPACK, + BOMB_TROLL, + BOMB_GOLDEN, + BOMB_SUPERTROLL, + BOMB_GOLDENTROLL, + BOMB_GIGA +}; + +// The items, trinkets, characters, challenges, seeds and unlocks the pickups ask about. +constexpr int COLLECTIBLE_MAGNETO = 53; +constexpr int COLLECTIBLE_HUMBLEING_BUNDLE = 203; +constexpr int COLLECTIBLE_BOGO_BOMBS = 250; +constexpr int COLLECTIBLE_STARTER_DECK = 251; +constexpr int COLLECTIBLE_LITTLE_BAGGY = 252; +constexpr int COLLECTIBLE_THE_JAR = 290; +constexpr int COLLECTIBLE_MAGGYS_BOW = 312; +constexpr int COLLECTIBLE_PAY_TO_PLAY = 380; +constexpr int COLLECTIBLE_SACK_HEAD = 424; +constexpr int COLLECTIBLE_GUPPYS_EYE = 665; +constexpr int COLLECTIBLE_BROKEN_SHOVEL_1 = 550; +constexpr int COLLECTIBLE_KNIFE_PIECE_1 = 626; +constexpr int COLLECTIBLE_KNIFE_PIECE_2 = 627; +constexpr int COLLECTIBLE_MOMS_SHOVEL = 668; +constexpr int COLLECTIBLE_THE_POLAROID = 327; +constexpr int COLLECTIBLE_THE_NEGATIVE = 328; +constexpr int STAGE_VOID = 12; +constexpr float OPTIONS_POOF_DROP = 10; +constexpr int OPTIONS_ITEM_TIMEOUT = 4; +constexpr int TRINKET_BROKEN_MAGNET = 6; +constexpr int TRINKET_BLACK_LIPSTICK = 17; +constexpr int TRINKET_BIBLE_TRACT = 18; +constexpr int TRINKET_DAEMONS_TAIL = 22; +constexpr int TRINKET_MOMS_PEARL = 38; +constexpr int TRINKET_BLOODY_PENNY = 49; +constexpr int TRINKET_BURNT_PENNY = 50; +constexpr int TRINKET_FLAT_PENNY = 51; +constexpr int TRINKET_COUNTERFEIT_PENNY = 52; +constexpr int TRINKET_LEFT_HAND = 61; +constexpr int TRINKET_SUPER_MAGNET = 68; +constexpr int TRINKET_WATCH_BATTERY = 72; +constexpr int TRINKET_RIB_OF_GREED = 84; +constexpr int TRINKET_MOMS_LOCKET = 87; +constexpr int TRINKET_ROTTEN_PENNY = 126; +constexpr int TRINKET_BLESSED_PENNY = 131; +constexpr int TRINKET_APPLE_OF_SODOM = 140; +constexpr int TRINKET_CHARGED_PENNY = 147; +constexpr int TRINKET_FLAT_FILE = 151; +constexpr int TRINKET_GILDED_KEY = 159; +constexpr int TRINKET_NUH_UH = 165; +constexpr int TRINKET_CURSED_PENNY = 172; +constexpr int COLLECTIBLE_MITRE = 173; +// The trinkets that turn a collected coin into something more, which are not reconstructed yet. +constexpr std::array PENNY_TRINKETS = {TRINKET_BLOODY_PENNY, TRINKET_BURNT_PENNY, TRINKET_FLAT_PENNY, + TRINKET_COUNTERFEIT_PENNY, TRINKET_BLESSED_PENNY, TRINKET_CHARGED_PENNY, + TRINKET_CURSED_PENNY, (int)TRINKET_BUTT_PENNY, TRINKET_ROTTEN_PENNY}; +constexpr int CHALLENGE_APRILS_FOOL = 32; +constexpr int CHALLENGE_ULTRA_HARD = 34; +constexpr int SPECIAL_DAILY_NICKELS = 7; +// Achievement 33 unlocks both the half soul heart and the micro battery. +constexpr int ACHIEVEMENT_HALF_SOUL_HEART = 33; +constexpr int ACHIEVEMENT_GOLDEN_HEART = 224; +constexpr int ACHIEVEMENT_GOLDEN_BOMB = 226; +constexpr int ACHIEVEMENT_STICKY_NICKEL = 240; +constexpr int ACHIEVEMENT_LUCKY_PENNY = 242; +constexpr int ACHIEVEMENT_SCARED_HEART = 328; +constexpr int ACHIEVEMENT_CHARGED_KEY = 333; +constexpr int ACHIEVEMENT_BONE_HEART = 391; +constexpr int ACHIEVEMENT_ROTTEN_HEART = 411; +constexpr int ACHIEVEMENT_MEGA_CHEST = 601; +constexpr int ACHIEVEMENT_BLACK_SACK = 604; +constexpr int ACHIEVEMENT_WOODEN_CHEST = 609; +constexpr int ACHIEVEMENT_HAUNTED_CHEST = 611; +constexpr int ACHIEVEMENT_GOLDEN_PENNY = 613; +constexpr int ACHIEVEMENT_GOLDEN_BATTERY = 615; +constexpr int STAGE_HOME = 35; +constexpr int GAME_STATE_HEART_BOMB_COIN_PICKED = 41; + +// The other entities and effects pickups spawn, meet and are saved with. +constexpr int ENTITY_PITFALL = 291; +constexpr int ENTITY_ULTRA_GREED = 406; +constexpr int ENTITY_POLTY = 816; +constexpr int ENTITY_GIDEON = 907; +constexpr int ENTITY_BUMBINO = 916; +constexpr int FAMILIAR_BUM_FRIEND = 24; +constexpr int FAMILIAR_DARK_BUM = 64; +constexpr int FAMILIAR_BUMBO = 88; +constexpr int FAMILIAR_KEY_BUM = 90; +constexpr int FAMILIAR_SUPER_BUM = 102; +constexpr int FAMILIAR_ABYSS_LOCUST = 231; +constexpr int FAMILIAR_LIL_PORTAL = 232; +constexpr int FIREPLACE_VARIANT_COUNT = 10; +constexpr int MINECART_UNSAVED_VARIANT = 10; +constexpr int BOMB_THROWABLE = 13; +constexpr int BOMB_ROCKET = 19; +constexpr int BOMB_ROCKET_GIGA = 20; +constexpr int EFFECT_SMOKE_CLOUD = 141; +constexpr int EFFECT_PORTAL_TELEPORT = 161; +constexpr int EFFECT_TALL_LADDER = 156; +constexpr uint32_t PORTAL_SAVED_SUBTYPE_MIN = 899; +// The effects a room keeps when it or no spawner placed them (tiny bugs and flies, wall bugs, worms, wisps, beetles, +// butterflies, tadpoles, lil ghosts), and the ones it always keeps (carpet, dice floor, heaven light, dirt patch, +// spawner, fissure spawner). +constexpr std::initializer_list SAVED_AMBIENT_EFFECTS = {21, 33, 68, 63, 65, 64, 69, 158, 159}; +constexpr std::initializer_list SAVED_EFFECTS = {74, 76, 39, 116, 120, 192}; +constexpr int ENTITY_FLY = 13; +constexpr int BOMB_VARIANT_TROLL = 3; +constexpr int BOMB_VARIANT_SUPERTROLL = 4; +constexpr int BOMB_VARIANT_GOLDENTROLL = 18; +constexpr int EFFECT_POOF01 = 15; +constexpr int EFFECT_POOF02 = 16; +constexpr int POOF02_LAVA_SPLASH = 66; +constexpr int FAMILIAR_WISP = 206; +constexpr int WISP_HEALED_BY_HEARTS = 296; + +// The sounds pickups play. +constexpr int SOUND_CHEST_DROP = 21; +constexpr int SOUND_FETUS_JUMP = 38; +constexpr int SOUND_FETUS_LAND = 40; +constexpr int SOUND_HOLY = 54; +constexpr int SOUND_KEYPICKUP_GAUNTLET = 58; +constexpr int SOUND_KEY_DROP0 = 59; +constexpr int SOUND_MEAT_FEET_SLOW0 = 68; +constexpr int SOUND_BOOK_PAGE_TURN_12 = 8; +constexpr int SOUND_BOSS2_BUBBLES = 185; +constexpr int SOUND_DIMEDROP = 198; +constexpr int SOUND_DIMEPICKUP = 199; +constexpr int SOUND_LUCKYPICKUP = 200; +constexpr int SOUND_FETUS_FEET = 201; +constexpr int SOUND_GOLDENKEY = 204; +constexpr int SOUND_NICKELDROP = 231; +constexpr int SOUND_NICKELPICKUP = 232; +constexpr int SOUND_PENNYDROP = 233; +constexpr int SOUND_PENNYPICKUP = 234; +constexpr int SOUND_SCAMPER = 249; +constexpr int SOUND_SHELLGAME = 252; +constexpr int SOUND_SPLATTER = 258; +constexpr int SOUND_SUPERHOLY = 266; +constexpr int SOUND_PING_PONG = 458; +constexpr int SOUND_BONE_HEART = 461; +constexpr int SOUND_SHOVEL_DROP = 463; +constexpr int SOUND_GOLD_HEART = 465; +constexpr int SOUND_GOLD_HEART_DROP = 466; +constexpr int SOUND_BONE_DROP = 467; +constexpr int SOUND_UNHOLY = 468; +constexpr int SOUND_GOLDENBOMB = 470; +constexpr int SOUND_ROTTEN_HEART = 497; +constexpr int SOUND_BUTTER_LAND = 902; +constexpr float KEY_PICKUP_VOLUME = 0.85f; +constexpr float STICKY_NICKEL_VOLUME = 0.5f; +constexpr float POOP_PITCH_MIN = 0.9f; +constexpr float POOP_PITCH_RANGE = 0.3f; +constexpr int PILL_GOLD = 14; +constexpr int PILL_COLOR_MASK = 0x7ff; +constexpr int CARD_PLAYING_FLAG = 0x8000; +constexpr float RANDOM_UNIT = 2.3283064e-10f; +// The card pickup subtypes that sound like objects, not paper, when collected. +constexpr std::initializer_list CARD_OBJECT_SUBTYPES = {3, 4, 6, 7, 13, 15}; +constexpr uint32_t GOLDEN_TRINKET_SPRITE_FLAG = 0x80; + +// The weights of a random pickup (5.0.N): coins, hearts, keys, bombs, chests, pills, cards, batteries, trinkets, items. +constexpr int WEIGHT_COIN = 20; +constexpr int WEIGHT_COMMON = 15; +constexpr int WEIGHT_CHEST = 5; +constexpr int WEIGHT_POCKET = 4; +constexpr int WEIGHT_BATTERY = 2; +constexpr int WEIGHT_RARE = 1; +constexpr int KEY_WEIGHT_NORMAL = 49; +constexpr int RANDOM_NO_COINS = 3; +constexpr int RANDOM_NO_CHESTS_A = 1; +constexpr int RANDOM_NO_CHESTS_B = 4; +constexpr float RIB_OF_GREED_ROLL = 0.1f; +constexpr float WATCH_BATTERY_ROLL = 0.2f; +constexpr int DAEMONS_TAIL_KEEP_ODDS = 5; +constexpr uint32_t PICKUP_RNG_SHIFT = 35; +constexpr uint32_t ROLL_SHIFT = 7; +constexpr uint32_t DAEMONS_TAIL_SHIFT = 47; +constexpr uint32_t KEEPER_FLIES_SHIFT = 19; + +// The chance denominators of the pickup subtypes, as "one in N". +constexpr int ODDS_HALF_HEART = 2; +constexpr int ODDS_DOUBLE_HEART = 20; +constexpr int ODDS_DOUBLE_HEART_HARD = 50; +constexpr int ODDS_ROTTEN_HEART = 50; +constexpr int ODDS_SCARED_HEART = 100; +constexpr int ODDS_BLENDED_HEART = 100; +constexpr int ODDS_ETERNAL_HEART = 50; +constexpr int ODDS_BIBLE_TRACT = 30; +constexpr int ODDS_KEY_PIECE = 40; +constexpr int ODDS_SOUL_HEART = 10; +constexpr int ODDS_MITRE = 3; +constexpr int ODDS_MOMS_PEARL = 10; +constexpr int ODDS_EVE_SOUL = 16; +constexpr int ODDS_HALF_SOUL = 4; +constexpr int ODDS_BONE_HEART = 20; +constexpr int ODDS_BLACK_HEART = 20; +constexpr int ODDS_BLACK_LIPSTICK = 10; +constexpr int ODDS_FORGOTTEN_BONE = 5; +constexpr int ODDS_GOLDEN_HEART = 160; +constexpr int ODDS_NICKEL = 20; +constexpr int ODDS_STICKY_NICKEL = 100; +constexpr int ODDS_DIME = 100; +constexpr int ODDS_LUCKY_PENNY = 100; +constexpr int ODDS_GOLDEN_PENNY = 200; +constexpr int ODDS_DOUBLE_BOMB = 7; +constexpr int ODDS_GOLDEN_BOMB = 100; +constexpr int ODDS_SUPERTROLL = 50; +constexpr int ODDS_TROLL = 10; +constexpr int ODDS_MIMIC = 40; +constexpr int ODDS_RED_CHEST = 20; +constexpr int ODDS_BOMB_CHEST = 50; +constexpr int ODDS_SPIKED_CHEST = 80; +constexpr int ODDS_GRAB_BAG = 100; +constexpr int ODDS_WOODEN_CHEST = 80; +constexpr int ODDS_HAUNTED_CHEST = 40; +constexpr int ODDS_ETERNAL_CHEST = 1600; +constexpr int ODDS_MEGA_CHEST = 120; +constexpr int ODDS_BLACK_SACK = 100; +constexpr int ODDS_MICRO_BATTERY = 3; +constexpr int ODDS_MEGA_BATTERY = 100; +constexpr int ODDS_GOLDEN_BATTERY = 120; +constexpr int MEGA_CHEST_ROLL = 4; +constexpr int CARD_SPECIAL_CHANCE = 25; +constexpr int CARD_RUNE_CHANCE = 10; +constexpr int CARD_SUIT_CHANCE = 10; + +// Pickup motion and timing. +constexpr int COLLISION_COOLDOWN = 10; +constexpr int SETTLE_FRAMES = 6; +constexpr int APPEAR_KICK = 15; +constexpr int TIMEOUT_BLINK = 30; +constexpr int SEED_TIMEOUT_BLINK = 150; +constexpr int SEED_TIMEOUT_REMOVE = 210; +constexpr int BLINK_PRIORITY = 255; +constexpr int BED_RENDER_Z = -3000; +constexpr int SACK_HEAD_ODDS = 5; +constexpr int SACK_HEAD_COIN_ODDS = 10; +constexpr int JAR_HEARTS_MAX = 8; +constexpr int ROOM_DUNGEON_BEAST_STAGE = STAGE_HOME; +constexpr int ETERNAL_CHEST_CLOSE_WAIT = 30; +constexpr float HAUNTED_CHEST_RANGE = 100; +constexpr float MIMIC_CHEST_RANGE = 50; +constexpr float THROW_GRAVITY = 1.2f; +constexpr float THROW_LOW = -50; +constexpr float CHEST_DRAG = 0.8f; +constexpr float PICKUP_FRICTION = 0.965f; +constexpr float BUMP_SLIDE = 0.1f; +constexpr float DUNGEON_GRAVITY = 0.9f; +constexpr float BEAST_DUNGEON_GRAVITY = 0.4f; +constexpr float BEAST_DUNGEON_FRICTION = 0.95f; +constexpr float DUNGEON_FLOOR_PROBE = 0.5f; +constexpr float DUNGEON_LAVA_MARGIN = 30; +constexpr uint32_t DUNGEON_PIT_COLLISION = 4; +constexpr int DUNGEON_SETTLE_FRAMES = 2; +constexpr float HALF = 0.5f; + +constexpr int LUA_CALLBACK_POST_PICKUP_INIT = 34; +constexpr int LUA_CALLBACK_POST_PICKUP_UPDATE = 35; +constexpr int LUA_CALLBACK_POST_PICKUP_RENDER = 36; +constexpr int LUA_CALLBACK_POST_PICKUP_SELECTION = 37; +constexpr int LUA_CALLBACK_GET_CARD = 20; + +// How deep pickup_variant_pick is in itself, which Nuh Uh! only rerolls at the top of. +static int pickDepth = 0; + +static bool is_listed(std::initializer_list list, int value) +{ + return std::find(list.begin(), list.end(), value) != list.end(); +} + +// A card from the pools as MC_GET_CARD leaves it (lua_callback_run_get_card 00865340), which no mod changes yet. +static int card_draw(RNG& rng) +{ + int card = ItemPool::GetCardEx((int)rng.Next(), CARD_SPECIAL_CHANCE, CARD_RUNE_CHANCE, CARD_SUIT_CHANCE, true); + lua_callback_check(LUA_CALLBACK_GET_CARD, "lua_callback_run_get_card 00865340"); + return card; +} + +static bool is_unlocked(int achievement) +{ + return g_manager->persistentGameData.Unlocked(achievement); +} + +static bool anyone_has_trinket(int trinket) +{ + return g_game->playerManager.AnyoneHasTrinket(trinket); +} + +static bool anyone_has_collectible(int collectible) +{ + return g_game->playerManager.FirstCollectibleOwner(collectible, LAZARUS_SHARE_CHECK) != nullptr; +} + +// One in odds from the generator, whose draw it always takes. +static bool rng_chance(RNG& rng, int odds) +{ + return rng.RandomInt((uint32_t)odds) == 0; +} + +// The outcome a roll lands on among weighted ones (WeightedOutcomePicker::PickOutcome 0049cbf0): the generator +// steps once on a copy, and the first outcome whose running weight passes the roll wins. +static int weighted_pick(std::initializer_list> outcomes, RNG rng) +{ + uint32_t total = 0; + int sum = 0; + + for (auto [id, weight] : outcomes) total += weight; + uint32_t roll = rng.Next(); + roll = total ? roll % total : 0; + + for (auto [id, weight] : outcomes) + if ((int)roll < (sum += weight)) return id; + return 0; +} + +// Whether a player stands within range of a position. +static bool is_player_near(const Vector& position, float range) +{ + for (Entity_Player* player : g_game->playerManager.playerList) + { + float dx = player->pos.x - position.x; + float dy = player->pos.y - position.y; + if (dx * dx + dy * dy < range * range) return true; + } + return false; +} + +static Vector vector_sub(Vector a, Vector b) +{ + return vector_make(a.x - b.x, a.y - b.y); +} + +static void pickup_sound_play(int sound, SoundPlay play = {}) +{ + grid_sound_play(sound, play); +} + +static Entity* entity_spawn(const EntitySpawn& spawn) +{ + return g_game->Spawn(spawn); +} + +// The random pickup a 5.0.N draws, N leaving out coins (3), chests (1, 3, 4), trinkets (4) and items (all but 0). +// Daemon's Tail redraws four in five hearts, Rib of Greed and Watch Battery claim the low rolls. +static void random_variant_pick(PickupChoice& choice, uint32_t firstSeed) +{ + int filter = choice.subType; + float roll = rng_make(firstSeed, ROLL_SHIFT).RandomFloat(); + bool isChests = filter != RANDOM_NO_CHESTS_A && filter != RANDOM_NO_COINS && filter != RANDOM_NO_CHESTS_B; + RNG pickRng = rng_make(firstSeed, PICKUP_RNG_SHIFT); + + choice.variant = weighted_pick({{PICKUP_COIN, filter != RANDOM_NO_COINS ? WEIGHT_COIN : 0}, + {PICKUP_HEART, WEIGHT_COMMON}, + {PICKUP_KEY, WEIGHT_COMMON}, + {PICKUP_BOMB, WEIGHT_COMMON}, + {PICKUP_CHEST, isChests ? WEIGHT_CHEST : 0}, + {PICKUP_LOCKEDCHEST, isChests ? WEIGHT_CHEST : 0}, + {PICKUP_PILL, WEIGHT_POCKET}, + {PICKUP_TAROTCARD, WEIGHT_POCKET}, + {PICKUP_LIL_BATTERY, WEIGHT_BATTERY}, + {PICKUP_TRINKET, filter != RANDOM_NO_CHESTS_B ? WEIGHT_RARE : 0}, + {PICKUP_COLLECTIBLE, filter == 0 ? WEIGHT_RARE : 0}}, + pickRng); + choice.subType = 0; + + if (choice.variant == PICKUP_HEART && anyone_has_trinket(TRINKET_DAEMONS_TAIL)) + { + RNG tailRng = rng_make(firstSeed, DAEMONS_TAIL_SHIFT); + uint32_t tailSeed = tailRng.Next(); + if (tailSeed % DAEMONS_TAIL_KEEP_ODDS != 0) + choice.variant = weighted_pick({{PICKUP_COIN, WEIGHT_COIN}, + {PICKUP_KEY, WEIGHT_COMMON}, + {PICKUP_BOMB, WEIGHT_COMMON}, + {PICKUP_HEART, WEIGHT_COMMON}}, + tailRng); + } + + bool isRibOfGreed = filter != RANDOM_NO_COINS && choice.variant != PICKUP_COIN && + anyone_has_trinket(TRINKET_RIB_OF_GREED) && roll < RIB_OF_GREED_ROLL; + if (isRibOfGreed) choice.variant = PICKUP_COIN; + else if (choice.variant != PICKUP_LIL_BATTERY && anyone_has_trinket(TRINKET_WATCH_BATTERY) && + roll >= RIB_OF_GREED_ROLL && roll < WATCH_BATTERY_ROLL) + choice.variant = PICKUP_LIL_BATTERY; +} + +// A heart's kind, each later chance overriding the earlier ones, and the one a super secret room layout holds. +static void heart_subtype_pick(PickupChoice& choice, RNG& rng) +{ + PlayerManager& players = g_game->playerManager; + + if (choice.subType == 0) + { + int& kind = choice.subType; + kind = HEART_FULL; + if (rng_chance(rng, ODDS_HALF_HEART)) kind = HEART_HALF; + if (rng_chance(rng, g_game->difficulty == DIFFICULTY_HARD || g_game->difficulty == DIFFICULTY_GREEDIER + ? ODDS_DOUBLE_HEART_HARD + : ODDS_DOUBLE_HEART)) + kind = HEART_DOUBLEPACK; + if (rng_chance(rng, ODDS_ROTTEN_HEART) && is_unlocked(ACHIEVEMENT_ROTTEN_HEART)) kind = HEART_ROTTEN; + if (rng_chance(rng, ODDS_SCARED_HEART) && is_unlocked(ACHIEVEMENT_SCARED_HEART)) kind = HEART_SCARED; + if (rng_chance(rng, ODDS_BLENDED_HEART)) kind = HEART_BLENDED; + + bool isEternal = rng_chance(rng, ODDS_ETERNAL_HEART); + if (!isEternal && players.AnyoneHasTrinket(TRINKET_BIBLE_TRACT)) + isEternal = rng_chance(rng, ODDS_BIBLE_TRACT / players.GetTrinketMultiplier(TRINKET_BIBLE_TRACT)); + if (!isEternal && anyone_has_collectible(COLLECTIBLE_KEY_PIECE_1)) isEternal = rng_chance(rng, ODDS_KEY_PIECE); + if (!isEternal && anyone_has_collectible(COLLECTIBLE_KEY_PIECE_2)) isEternal = rng_chance(rng, ODDS_KEY_PIECE); + if (isEternal) kind = HEART_ETERNAL; + + bool isSoul = rng_chance(rng, ODDS_SOUL_HEART); + if (!isSoul && anyone_has_collectible(COLLECTIBLE_MITRE)) isSoul = rng_chance(rng, ODDS_MITRE); + if (!isSoul && players.AnyoneHasTrinket(TRINKET_MOMS_PEARL)) + isSoul = rng_chance(rng, ODDS_MOMS_PEARL / players.GetTrinketMultiplier(TRINKET_MOMS_PEARL)); + if (!isSoul && players.FirstPlayerByType(PLAYER_EVE)) isSoul = rng_chance(rng, ODDS_EVE_SOUL); + if (isSoul) + { + kind = HEART_SOUL; + if (rng_chance(rng, ODDS_HALF_SOUL) && is_unlocked(ACHIEVEMENT_HALF_SOUL_HEART)) kind = HEART_HALF_SOUL; + if (rng_chance(rng, ODDS_BONE_HEART) && is_unlocked(ACHIEVEMENT_BONE_HEART)) kind = HEART_BONE; + + bool isBlack = rng_chance(rng, ODDS_BLACK_HEART); + if (!isBlack && players.AnyoneHasTrinket(TRINKET_BLACK_LIPSTICK)) + isBlack = rng_chance(rng, ODDS_BLACK_LIPSTICK / players.GetTrinketMultiplier(TRINKET_BLACK_LIPSTICK)); + if (isBlack) kind = HEART_BLACK; + + bool isForgotten = players.FirstPlayerByType(PLAYER_THEFORGOTTEN) || + players.FirstPlayerByType(PLAYER_THESOUL); + if (rng_chance(rng, ODDS_FORGOTTEN_BONE) && isForgotten) kind = HEART_BONE; + } + if (rng_chance(rng, ODDS_GOLDEN_HEART) && is_unlocked(ACHIEVEMENT_GOLDEN_HEART)) kind = HEART_GOLDEN; + if (players.AnyoneHasTrinket(TRINKET_DAEMONS_TAIL) && g_game->room->roomType != ROOM_SUPERSECRET) + kind = HEART_BLACK; + } + + if (g_game->room->roomType == ROOM_SUPERSECRET) + reconstruction_missing("Pickup_PickVariant 006ddcd0: a super secret room's heart"); + if (choice.subType == HEART_HALF && players.AnyoneHasTrinket(TRINKET_MOMS_LOCKET)) choice.subType = HEART_FULL; +} + +// A coin's kind: penny, then nickel or a rare sticky nickel, dime or a rare lucky penny, and a rarer golden penny. +static void coin_subtype_pick(PickupChoice& choice, RNG& rng) +{ + int& kind = choice.subType; + + if (kind == 0) + { + kind = COIN_PENNY; + if (rng_chance(rng, ODDS_NICKEL)) kind = COIN_NICKEL; + else if (rng_chance(rng, ODDS_STICKY_NICKEL) && is_unlocked(ACHIEVEMENT_STICKY_NICKEL)) + kind = COIN_STICKYNICKEL; + if (rng_chance(rng, ODDS_DIME)) kind = COIN_DIME; + else if (kind == COIN_PENNY && rng_chance(rng, ODDS_LUCKY_PENNY) && is_unlocked(ACHIEVEMENT_LUCKY_PENNY)) + kind = COIN_LUCKYPENNY; + if (rng_chance(rng, ODDS_GOLDEN_PENNY) && is_unlocked(ACHIEVEMENT_GOLDEN_PENNY)) + { + kind = COIN_GOLDEN; + return; + } + } + bool isNickelDaily = g_game->dailyChallenge._specialDailyId == SPECIAL_DAILY_NICKELS; + if (kind == COIN_NICKEL && isNickelDaily) kind = COIN_STICKYNICKEL; +} + +// A bomb's kind: single, then double, golden, a super troll (golden troll from a golden) and a troll. +static void bomb_subtype_pick(PickupChoice& choice, RNG& rng) +{ + int& kind = choice.subType; + + if (kind != 0) return; + kind = BOMB_NORMAL; + if (rng_chance(rng, ODDS_DOUBLE_BOMB)) kind = BOMB_DOUBLEPACK; + if (rng_chance(rng, ODDS_GOLDEN_BOMB) && is_unlocked(ACHIEVEMENT_GOLDEN_BOMB)) kind = BOMB_GOLDEN; + if (rng_chance(rng, ODDS_SUPERTROLL)) kind = kind == BOMB_GOLDEN ? BOMB_GOLDENTROLL : BOMB_SUPERTROLL; + if (rng_chance(rng, ODDS_TROLL)) kind = kind == BOMB_GOLDEN ? BOMB_GOLDENTROLL : BOMB_TROLL; +} + +// A chest's kind and its contents: a plain chest may turn mimic, red, bomb, spiked, a grab bag, wooden or haunted, any +// chest or locked chest rolls eternal, Left Hand turns the locked kinds red, Flat File spiked ones mimic, Gilded Key +// locks them, and a locked chest may turn mega. A closed chest's subtype is 1 (2 for an eternal chest), a mega +// chest's the number of opening rounds. +static void chest_variant_pick(PickupChoice& choice, RNG& rng) +{ + int& variant = choice.variant; + bool isUnset = choice.subType == 0; + bool isRolled = variant == PICKUP_CHEST || variant == PICKUP_LOCKEDCHEST; + bool isLockedKind = isRolled || is_listed({PICKUP_BOMBCHEST, PICKUP_SPIKEDCHEST, PICKUP_ETERNALCHEST, + PICKUP_MIMICCHEST, PICKUP_WOODENCHEST, PICKUP_HAUNTEDCHEST}, + variant); + + if (variant == PICKUP_CHEST && isUnset) + { + if (rng_chance(rng, ODDS_MIMIC)) variant = PICKUP_MIMICCHEST; + else if (rng_chance(rng, ODDS_RED_CHEST)) variant = PICKUP_REDCHEST; + else if (rng_chance(rng, ODDS_BOMB_CHEST)) variant = PICKUP_BOMBCHEST; + else if (rng_chance(rng, ODDS_SPIKED_CHEST)) variant = PICKUP_SPIKEDCHEST; + else if (rng_chance(rng, ODDS_GRAB_BAG)) + { + variant = PICKUP_GRAB_BAG; + choice.subType = rng_chance(rng, ODDS_BLACK_SACK) && is_unlocked(ACHIEVEMENT_BLACK_SACK) ? 2 : 1; + return; + } + else if (rng_chance(rng, ODDS_WOODEN_CHEST) && is_unlocked(ACHIEVEMENT_WOODEN_CHEST)) + variant = PICKUP_WOODENCHEST; + else if (rng_chance(rng, ODDS_HAUNTED_CHEST)) + { + int shape = g_game->room->GetRoomShape(); + bool isNarrow = is_listed({ROOMSHAPE_IH, ROOMSHAPE_IV, ROOMSHAPE_IIH, ROOMSHAPE_IIV}, shape); + if (!isNarrow && is_unlocked(ACHIEVEMENT_HAUNTED_CHEST)) variant = PICKUP_HAUNTEDCHEST; + } + } + + if (isRolled && isUnset && rng_chance(rng, ODDS_ETERNAL_CHEST)) variant = PICKUP_ETERNALCHEST; + if (isLockedKind && isUnset && anyone_has_trinket(TRINKET_LEFT_HAND)) variant = PICKUP_REDCHEST; + else if (isLockedKind && variant == PICKUP_SPIKEDCHEST && anyone_has_trinket(TRINKET_FLAT_FILE)) + variant = PICKUP_MIMICCHEST; + if (!isUnset) return; + + bool isGilded = anyone_has_trinket(TRINKET_GILDED_KEY) && !anyone_has_trinket(TRINKET_LEFT_HAND) && + variant != PICKUP_MEGACHEST; + if (isGilded) variant = PICKUP_LOCKEDCHEST; + if (variant == PICKUP_LOCKEDCHEST && rng_chance(rng, ODDS_MEGA_CHEST) && is_unlocked(ACHIEVEMENT_MEGA_CHEST)) + variant = PICKUP_MEGACHEST; + if (variant == PICKUP_MEGACHEST) + { + uint32_t first = rng.RandomInt(MEGA_CHEST_ROLL); + choice.subType = (int)(rng.RandomInt(MEGA_CHEST_ROLL) + 1 + first); + } + else choice.subType = variant == PICKUP_ETERNALCHEST ? 2 : 1; +} + +// A key's kind by weight: normal, golden, and charged once unlocked (a second normal before). +static void key_subtype_pick(PickupChoice& choice, RNG& rng) +{ + if (choice.subType != 0) return; + int extraKey = is_unlocked(ACHIEVEMENT_CHARGED_KEY) ? KEY_CHARGED : KEY_NORMAL; + RNG pickRng = rng_make(rng.Next(), PICKUP_RNG_SHIFT); + + choice.subType = + weighted_pick({{KEY_NORMAL, KEY_WEIGHT_NORMAL}, {KEY_GOLDEN, WEIGHT_RARE}, {extraKey, WEIGHT_RARE}}, pickRng); +} + +// A battery's kind: lil, micro once unlocked two times in three (or on hard mode an odd draw), then mega or golden. +static void battery_subtype_pick(PickupChoice& choice, RNG& rng) +{ + if (choice.subType != 0) return; + choice.subType = 1; + uint32_t first = rng.Next(); + uint32_t second = rng.Next(); + + bool isHard = g_game->difficulty == DIFFICULTY_HARD || g_game->difficulty == DIFFICULTY_GREEDIER; + if ((is_unlocked(ACHIEVEMENT_HALF_SOUL_HEART) && first % ODDS_MICRO_BATTERY != 0) || (isHard && (second & 1))) + choice.subType = 2; + if (rng_chance(rng, ODDS_MEGA_BATTERY)) choice.subType = 3; + else if (rng_chance(rng, ODDS_GOLDEN_BATTERY) && is_unlocked(ACHIEVEMENT_GOLDEN_BATTERY)) choice.subType = 4; +} + +// What the run's items and challenges change in the kind: Humbleing Bundle and BOGO Bombs double, Scat Man turns +// hearts into coins, Cantripped and DELETE THIS turn pocket items and items into cards and trinkets, and Tainted +// ???'s bombs are poops. +static void choice_modifiers_apply(PickupChoice& choice) +{ + int& variant = choice.variant; + int& kind = choice.subType; + bool isBundle = anyone_has_collectible(COLLECTIBLE_HUMBLEING_BUNDLE) && !(choice.seed & CARD_PLAYING_FLAG); + + if (!isBundle && variant == PICKUP_BOMB) isBundle = anyone_has_collectible(COLLECTIBLE_BOGO_BOMBS); + if (isBundle && !g_pickupIgnoreModifiers) + { + if (variant == PICKUP_HEART && (kind == HEART_FULL || kind == HEART_SCARED)) kind = HEART_DOUBLEPACK; + if (variant == PICKUP_COIN && kind == COIN_PENNY) kind = COIN_DOUBLEPACK; + if (variant == PICKUP_KEY && kind == KEY_NORMAL) kind = KEY_DOUBLEPACK; + else if (variant == PICKUP_BOMB && kind == BOMB_NORMAL) kind = BOMB_DOUBLEPACK; + } + + bool isScatHeart = is_listed({HEART_FULL, HEART_HALF, HEART_DOUBLEPACK, HEART_BLENDED, HEART_SCARED, HEART_ROTTEN}, + kind); + if (g_game->challenge == CHALLENGE_HAVE_A_HEART && variant == PICKUP_HEART && isScatHeart) + { + variant = PICKUP_COIN; + kind = kind == HEART_FULL ? COIN_DOUBLEPACK : kind == HEART_DOUBLEPACK ? COIN_NICKEL : COIN_PENNY; + } + if (g_game->challenge == CHALLENGE_PICA_RUN || g_game->challenge == CHALLENGE_CANTRIPPED) + reconstruction_missing("Pickup_PickVariant 006ddcd0: DELETE THIS and Cantripped's pickups"); + + bool isPoopBomb = variant == PICKUP_BOMB && g_game->playerManager.are_all_players_tainted_blue_baby() && + !is_listed({BOMB_TROLL, BOMB_SUPERTROLL, BOMB_GOLDENTROLL}, kind); + if (isPoopBomb) + { + variant = PICKUP_POOP; + kind = 1; + } +} + +// 006ddcd0 Chooses a pickup's variant and subtype where they are 0: a random variant by weight, then a subtype per +// variant, then the run's modifiers. A sale for a party of Keepers swaps hearts for keys or bombs. +bool pickup_variant_pick(PickupChoice& choice) +{ + RNG rng = rng_make(choice.seed, PICKUP_RNG_SHIFT); + + pickDepth++; + if (choice.variant == PICKUP_NULL) random_variant_pick(choice, rng.Next()); + + bool isStarterDeck = anyone_has_collectible(COLLECTIBLE_STARTER_DECK); + bool isLittleBaggy = anyone_has_collectible(COLLECTIBLE_LITTLE_BAGGY); + if (isStarterDeck && isLittleBaggy) isStarterDeck = isLittleBaggy = false; + + ItemConfig_Card* card = g_manager->itemConfig.GetCard(choice.subType); + bool isBaggyCard = !card || is_listed({CARD_TAROT, CARD_SUIT, CARD_SPECIAL, CARD_TAROT_REVERSE}, card->cardType); + if (choice.variant == PICKUP_PILL && isStarterDeck) + { + choice.variant = PICKUP_TAROTCARD; + choice.subType = 0; + } + else if (choice.variant == PICKUP_TAROTCARD && isLittleBaggy && isBaggyCard) + { + choice.variant = PICKUP_PILL; + choice.subType = 0; + } + + TrinketDraw trinketDraw = choice.draw == POOL_DRAW_TAKE ? TRINKET_DRAW_TAKE : TRINKET_DRAW_PEEK; + switch (choice.variant) + { + case PICKUP_HEART: + heart_subtype_pick(choice, rng); + break; + case PICKUP_COIN: + coin_subtype_pick(choice, rng); + break; + case PICKUP_KEY: + key_subtype_pick(choice, rng); + break; + case PICKUP_BOMB: + bomb_subtype_pick(choice, rng); + break; + case PICKUP_THROWABLEBOMB: + case PICKUP_POOP: + case PICKUP_SHOPITEM: + case PICKUP_BIGCHEST: + case PICKUP_TROPHY: + case PICKUP_BED: + break; + case PICKUP_CHEST: + case PICKUP_BOMBCHEST: + case PICKUP_SPIKEDCHEST: + case PICKUP_ETERNALCHEST: + case PICKUP_MIMICCHEST: + case PICKUP_WOODENCHEST: + case PICKUP_MEGACHEST: + case PICKUP_HAUNTEDCHEST: + case PICKUP_LOCKEDCHEST: + case PICKUP_REDCHEST: + chest_variant_pick(choice, rng); + break; + case PICKUP_OLDCHEST: + case PICKUP_MOMSCHEST: + if (choice.subType == 0) choice.subType = 1; + break; + case PICKUP_GRAB_BAG: + if (choice.subType == 0) + choice.subType = rng_chance(rng, ODDS_BLACK_SACK) && is_unlocked(ACHIEVEMENT_BLACK_SACK) ? 2 : 1; + break; + case PICKUP_PILL: + if (choice.subType == 0) choice.subType = ItemPool::GetPill(rng.Next()); + break; + case PICKUP_LIL_BATTERY: + battery_subtype_pick(choice, rng); + break; + case PICKUP_COLLECTIBLE: + reconstruction_missing("Pickup_PickVariant 006ddcd0: an item"); + case PICKUP_BROKEN_SHOVEL: + choice.subType = COLLECTIBLE_BROKEN_SHOVEL_1; + break; + case PICKUP_TAROTCARD: + if (choice.subType == 0) choice.subType = card_draw(rng); + break; + case PICKUP_TRINKET: + if (choice.subType != 0) break; + choice.subType = (int)g_game->itemPool.GetTrinket(trinketDraw); + if (choice.subType != 0) break; + choice.variant = PICKUP_TAROTCARD; + choice.subType = card_draw(rng); + if (!isLittleBaggy) break; + choice.variant = PICKUP_PILL; + choice.subType = ItemPool::GetPill(rng.Next()); + break; + default: + log_printf(LOG_INFO, "[warn] Pickup variant %d not implemented yet!\n", choice.variant); + break; + } + choice_modifiers_apply(choice); + + bool isNuhUhVariant = choice.variant == PICKUP_COIN || choice.variant == PICKUP_KEY; + bool isGreed = g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER; + if (isNuhUhVariant && !isGreed && g_game->stage >= 7 && !g_pickupIgnoreModifiers && pickDepth <= 1 && + anyone_has_trinket(TRINKET_NUH_UH)) + reconstruction_missing("Pickup_PickVariant 006ddcd0: Nuh Uh!'s reroll"); + + if (choice.sale == PICKUP_FOR_SALE) + { + PlayerManager& players = g_game->playerManager; + bool isKeeperParty = true; + for (Entity_Player* player : players.playerList) + if (player->variant == 0 && player->playerType != PLAYER_KEEPER && player->playerType != PLAYER_KEEPER_B) + isKeeperParty = false; + if (isKeeperParty && choice.variant == PICKUP_HEART) + { + choice.variant = (rng.Next() & 1) ? PICKUP_BOMB : PICKUP_KEY; + choice.subType = 1; + } + } + pickDepth--; + return true; +} + +// 007eed10 Whether an entity of the kind is kept in its room's saved state: pickups but a throwable bomb, bombs but +// the rockets and giga bomb kinds, slots, shopkeepers, fireplaces and a few props, and the effects the room or no +// spawner placed. A few more are saved only while the game state or Glowing Hourglass is being stored. +bool entity_type_is_saved(int type, int variant, uint32_t subType, int spawnerType, bool isRoomEntry) +{ + bool isStoring = g_manager->isSavingGameState || g_game->isStoringGlowingHourglassState; + bool isUnspawned = isRoomEntry || spawnerType == 0; + + switch (type) + { + case ENTITY_PICKUP: + return variant != PICKUP_THROWABLEBOMB; + case ENTITY_BOMB: + return !is_listed({BOMB_THROWABLE, BOMB_ROCKET, BOMB_ROCKET_GIGA}, variant); + case ENTITY_SLOT: + case ENTITY_SHOPKEEPER: + case ENTITY_MOVABLE_TNT: + case ENTITY_GENERIC_PROP: + return true; + case ENTITY_FIREPLACE: + return (uint32_t)variant < FIREPLACE_VARIANT_COUNT; + case ENTITY_PITFALL: + return spawnerType == 0; + case ENTITY_MINECART: + return variant != MINECART_UNSAVED_VARIANT; + case ENTITY_GIDEON: + return subType == 1 && isRoomEntry; + case ENTITY_EFFECT: + break; + default: + return false; + } + + if (is_listed(SAVED_AMBIENT_EFFECTS, variant) && isUnspawned) return true; + if (is_listed(SAVED_EFFECTS, variant)) return true; + if (variant == EFFECT_SMOKE_CLOUD) return spawnerType == 0; + if (variant == EFFECT_PORTAL_TELEPORT) return subType > PORTAL_SAVED_SUBTYPE_MIN || isStoring; + if (variant == EFFECT_TALL_LADDER) return subType == 1 && isStoring; + return false; +} + +// 006e02f0 Starts a pickup: clears what a previous life left, chooses its kind (the pick seeded from its seed), loads +// its sprite, makes it appear, and gives Pay To Play's chests a coin slot. +// Items, shop wares, the big chest, trophy and bed are not reconstructed yet. +void Entity_Pickup::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) +{ + isUnknown176 = true; + coopDuplicateIndex = -1; + price = 0; + shopItemId = 0; + timeout = -1; + wait = 0; + chestReCloseTimer = 0; + isTouched = false; + isUnknown52d = false; + isForceBlind = false; + isPayToPlay = false; + collisionCooldown = 0; + gridRepositionState = 0; + colorMod = {}; + state = 0; + isAutoUpdatePrice = true; + unkEntityRef = nullptr; + if (pickupGhost) pickupGhost->Remove(); + pickupGhost = nullptr; + megaChestCollectible = {}; + height = 0; + heightVelocity = 0; + flipSaveState.reset(); + dropDelay = 0; + cycleCollectibleCount = 0; + invisibleFrames = 0; + charge = 0; + varData = 0; + + PickupChoice choice = {entitySubType, entityVariant, seed}; + if (!pickup_variant_pick(choice)) + { + if (choice.variant != -1) return; + entity_spawn({pos, {}, nullptr, 0, ENTITY_FLY, 0, dropRNG.Next()})->scoreMultiplier = 0; + return; + } + if (is_listed({PICKUP_SHOPITEM, PICKUP_COLLECTIBLE, PICKUP_BROKEN_SHOVEL, PICKUP_BIGCHEST, PICKUP_TROPHY, + PICKUP_BED, PICKUP_MOMSCHEST}, + choice.variant)) + reconstruction_missing("Entity_Pickup::Init 006e02f0: items, shop wares and the big pickups"); + lua_callback_check(LUA_CALLBACK_POST_PICKUP_SELECTION, "lua_callback_run_post_pickup_selection 00863340"); + + bool isPoopBomb = choice.variant == PICKUP_BOMB && g_game->playerManager.are_all_players_tainted_blue_baby() && + !is_listed({BOMB_TROLL, BOMB_SUPERTROLL, BOMB_GOLDENTROLL}, choice.subType); + if (isPoopBomb) choice = {1, PICKUP_POOP, seed}; + if (g_game->challenge == CHALLENGE_CANTRIPPED) reconstruction_missing("Entity_Pickup::Init 006e02f0: Cantripped"); + + if (choice.variant == PICKUP_TAROTCARD) + { + ItemConfig_Card* card = g_manager->itemConfig.GetCard(choice.subType); + Entity::Init(entityType, PICKUP_TAROTCARD, card ? card->pickupSubtype : 2, seed); + subtype = choice.subType; + } + else Entity::Init(entityType, choice.variant, choice.subType, seed); + + bool isPayChest = is_listed({PICKUP_ETERNALCHEST, PICKUP_OLDCHEST, PICKUP_MEGACHEST, PICKUP_LOCKEDCHEST}, variant); + if (anyone_has_collectible(COLLECTIBLE_PAY_TO_PLAY) && isPayChest) isPayToPlay = true; + if (config) + { + sprite.Load(config->anm2Path, GRAPHICS_DEFER); + UpdateSprite(false); + } + appear_start(); + + optionsPickupIndex = 0; + bool isSaleSeed = g_game->seedEffects.HasSeedEffect(SEED_ITEMS_COST_MONEY) && variant != PICKUP_COIN && + CanReroll() && !IsChest(variant); + if (isSaleSeed) reconstruction_missing("Entity_Pickup::Init 006e02f0: the seed that sells every pickup"); + update_price_sprite(price); + + if (variant == PICKUP_HEART && g_game->challenge == CHALLENGE_ULTRA_HARD) Remove(); + if (variant == PICKUP_THROWABLEBOMB) entityGridCollisionClass = GRIDCOLL_GROUND; + else if (variant == PICKUP_POOP) sprite.isFlipX = initSeed & 1; + + UpdateLootPreview(); + log_printf(LOG_INFO, "Entity Pickup Initialized as: %d.%d.%d Seed: %08x \n", type, variant, subtype, initSeed); + itemPoolType = g_game->itemPool.lastPool; + lua_callback_check(LUA_CALLBACK_POST_PICKUP_INIT, "LuaEngine::PostPickupInit 00862f00"); +} + +// Plays the pickup's appear animation, uncollectable until it lands, or shows it idle in a room the players are +// entering. An appearing pickup in the Beast's dungeon starts landed and falls in from above. +void Entity_Pickup::appear_start() +{ + Room& room = *g_game->room; + + if (!sprite.isLoaded) return log_printf(LOG_INFO, "[warn] No sprite for Pickup variant %d\n", variant); + + bool isEntering = room.isFirstVisit ? !room.isInitialized && g_game->GetStageID() == STAGE_HOME + : room.GetFrameCount() < 1; + if (isEntering) + { + sprite.Play("Idle"); + entityCollisionClass = ENTCOLL_ALL; + return; + } + + sprite.Play("Appear"); + entityCollisionClass = ENTCOLL_NONE; + if (room.IsBeastDungeon()) + { + sprite.SetLastFrame(); + velocity.y -= APPEAR_KICK; + return; + } + if (g_game->playerManager.GetGFuelCount() > 1) reconstruction_missing("Entity_Pickup::Init 006e02f0: the G FUEL!"); +} + +// 006e21f0 Swaps in the spritesheets a variant shows: a trinket's own and its golden flag, a collectible's image, and +// Pay To Play's coin slot chests, then loads them. +void Entity_Pickup::UpdateSprite(bool) +{ + if (variant == PICKUP_TRINKET) + { + // The original reads an unknown trinket's null config. Its sheet is left unchanged here. + ItemConfig_Item* trinket = g_manager->itemConfig.GetTrinket(subtype & TRINKET_ID_MASK); + if (trinket) sprite.ReplaceSpritesheet(0, trinket->gfxFilename); + sprite.bitflags = ((uint32_t)subtype >> 8) & GOLDEN_TRINKET_SPRITE_FLAG; + } + else if (variant == PICKUP_COLLECTIBLE || variant == PICKUP_BED || isPayToPlay) + reconstruction_missing("Entity_Pickup::UpdateSprite 006e21f0: items, the bed and the coin slot chests"); + sprite.LoadGraphics(); +} + +// 006e2570 Sets the price and its sprite. A free pickup drops the price sprite. +// Prices, which shops set, are not reconstructed yet. +void Entity_Pickup::update_price_sprite(int newPrice) +{ + if (newPrice != 0 || price != 0) reconstruction_missing("Entity_Pickup::update_price_sprite 006e2570: a price"); + + if (variant == PICKUP_COLLECTIBLE) + reconstruction_missing("Entity_Pickup::update_price_sprite 006e2570: an item's pedestal"); + priceANM2.Reset(); + if (child) child->Remove(); +} + +// 006e17c0 Shows a chest's or sack's contents to a holder of Guppy's Eye, and otherwise removes the preview. +void Entity_Pickup::UpdateLootPreview() +{ + if (anyone_has_collectible(COLLECTIBLE_GUPPYS_EYE)) + reconstruction_missing("Entity_Pickup::UpdateLootPreview 006e17c0: Guppy's Eye"); + if (pickupGhost) pickupGhost->Remove(); +} + +// 006e38d0 Moves the pickup half a step, a chest flying in the air from its height. +void Entity_Pickup::Interpolate() +{ + if (IsChest(variant)) posOffset.y = std::min(heightVelocity * speedMultiplier * HALF + height, 0.0f); + Entity::Interpolate(); +} + +// 006e69b0 Draws the pickup and its price, unless it is waiting to drop. +// An item's pedestal is not reconstructed yet. +void Entity_Pickup::Render(const Vector& offset) +{ + if (!isExists || !isVisible || dropDelay >= 1) return; + + if (variant == PICKUP_COLLECTIBLE) reconstruction_missing("Entity_Pickup::Render 006e69b0: an item's pedestal"); + Entity::Render(offset); + if (priceANM2.isLoaded) priceANM2.Render(SpriteDraw{renderPosition, {}, {}}); + lua_callback_check(LUA_CALLBACK_POST_PICKUP_RENDER, "LuaEngine::PostPickupRender 008630c0"); +} + +// 006e3940 Runs the pickup for a frame: a thrown chest's flight, Keeper's hearts turning into flies, Sack Head's +// sacks, troll bombs going off, holding its place where it must, its motion and friction, its appear animation and +// drop sound, its timeouts and the crawl space's gravity. +// Items, the glitched pickups and the rarer kinds' behaviours are not reconstructed yet. +void Entity_Pickup::Update() +{ + if (dropDelay > 0) + { + if (entityCollisionClass == ENTCOLL_NONE) + { + dropDelay--; + return; + } + dropDelay = 0; + } + + if (height < 0 || heightVelocity < 0) + { + float fallSpeed = heightVelocity; + entityCollisionClass = height < THROW_LOW ? ENTCOLL_NONE : ENTCOLL_ALL; + entityGridCollisionClass = height < THROW_LOW ? GRIDCOLL_WALLS : GRIDCOLL_NOPITS; + heightVelocity = speedMultiplier * THROW_GRAVITY + fallSpeed; + height = speedMultiplier * fallSpeed + height; + if (isCollidesWithGrid && IsChest(variant) && subtype != 0) TryOpenChest(nullptr); + if (height >= 0) + { + ClearEntityFlags(FLAG_THROWN); + height = 0; + heightVelocity = 0; + entityCollisionClass = ENTCOLL_ALL; + entityGridCollisionClass = GRIDCOLL_GROUND; + if (IsChest(variant) && subtype != 0) TryOpenChest(nullptr); + } + } + if (IsChest(variant)) + { + posOffset.y = height; + if (parent && HasEntityFlags(FLAG_HELD)) velocity = vector_sub(parent->pos, pos); + } + if (variant == PICKUP_COLLECTIBLE) reconstruction_missing("Entity_Pickup::Update 006e3940: an item"); + if (price == 0 && variant == PICKUP_HEART && keeper_flies_update()) return; + + if (anyone_has_collectible(COLLECTIBLE_SACK_HEAD) && price == 0 && spawnerType != ENTITY_PLAYER) + { + bool isSackSpawned = + spawnerType == ENTITY_PICKUP ? spawnerVariant == PICKUP_GRAB_BAG : spawnerType == ENTITY_FAMILIAR; + bool isSackable = + is_listed({PICKUP_KEY, PICKUP_BOMB, PICKUP_COIN, PICKUP_LIL_BATTERY, PICKUP_TAROTCARD}, variant); + if (!isSackSpawned && isSackable) + { + if (rng_chance(dropRNG, variant == PICKUP_COIN ? SACK_HEAD_COIN_ODDS : SACK_HEAD_ODDS)) + { + Remove(); + EntitySpawn spawn = {pos, velocity, nullptr, 0, ENTITY_PICKUP, PICKUP_GRAB_BAG, dropRNG.Next()}; + Entity* sack = entity_spawn(spawn); + static_cast(sack)->optionsPickupIndex = optionsPickupIndex; + return; + } + spawnerType = ENTITY_PICKUP; + spawnerVariant = PICKUP_GRAB_BAG; + } + } + + if (variant == PICKUP_BOMB) + { + int bomb = subtype == BOMB_TROLL ? BOMB_VARIANT_TROLL : subtype == BOMB_SUPERTROLL ? BOMB_VARIANT_SUPERTROLL + : subtype == BOMB_GOLDENTROLL ? BOMB_VARIANT_GOLDENTROLL : 0; + if (bomb) + { + entity_spawn({pos, {}, nullptr, 0, ENTITY_BOMB, bomb, Random()}); + return Remove(); + } + bool isTrollDrop = spawnerType == ENTITY_BOMB && is_listed({BOMB_VARIANT_TROLL, BOMB_VARIANT_SUPERTROLL, + BOMB_VARIANT_GOLDENTROLL}, + (int)spawnerVariant); + if (isTrollDrop && sprite.IsPlaying("Appear")) + { + sprite.Play("Idle"); + entityCollisionClass = ENTCOLL_ALL; + } + } + + target_position_update(); + if (variant == PICKUP_BED) renderZOffset = BED_RENDER_Z; + else if (variant == PICKUP_HEART && subtype == HEART_SCARED && price == 0 && !isDead) + reconstruction_missing("Entity_Pickup::Update 006e3940: a scared heart running away"); + + Entity::Update(); + if (IsChest(variant) && !HasEntityFlags(FLAG_THROWN)) + velocity = vector_make(velocity.x * CHEST_DRAG, velocity.y * CHEST_DRAG); + if (!HasEntityFlags(FLAG_THROWN)) friction *= PICKUP_FRICTION; + update_magnet_attraction(); + if (isAutoUpdatePrice && price != 0) reconstruction_missing("Entity_Pickup::Update 006e3940: a price"); + appear_update(); + + bool isClosedChest = IsChest(variant) && subtype != 0; + bool isAwake = collisionCooldown < 1 && entityCollisionClass != ENTCOLL_NONE; + bool isHaunting = variant == PICKUP_HAUNTEDCHEST && isClosedChest && + (HasEntityFlags(FLAG_HELD) || (isAwake && is_player_near(pos, HAUNTED_CHEST_RANGE))); + bool isMimicking = variant == PICKUP_MIMICCHEST && isClosedChest && isAwake && + !anyone_has_trinket(TRINKET_FLAT_FILE) && is_player_near(pos, MIMIC_CHEST_RANGE); + bool isMegaOpening = variant == PICKUP_MEGACHEST && isClosedChest && sprite.IsEventTriggered("Open"); + if (isHaunting || isMimicking || isMegaOpening || (variant == PICKUP_HEART && subtype == HEART_ROTTEN)) + reconstruction_missing("Entity_Pickup::Update 006e3940: haunted, mega and mimic chests and rotten hearts"); + if (timeout > 0 && --timeout == 0) Remove(); + if (wait > 0) wait--; + if (chestReCloseTimer > 0 && --chestReCloseTimer == 0 && variant == PICKUP_ETERNALCHEST) + { + subtype = 1; + sprite.Play("Close"); + pickup_sound_play(SOUND_CHEST_DROP); + wait = ETERNAL_CHEST_CLOSE_WAIT; + UpdateLootPreview(); + } + + Room& room = *g_game->room; + if (room.roomType == ROOM_DUNGEON) + { + RoomConfig_Room* data = room.descriptor->data; + bool isBeastDungeon = data && data->type == ROOM_DUNGEON && data->stageId == ROOM_DUNGEON_BEAST_STAGE; + Vector below = vector_make(pos.x, sizeMulti.y * size + DUNGEON_FLOOR_PROBE + pos.y); + if (room.GetGridCollision(room.GetGridIndex(below)) != DUNGEON_PIT_COLLISION) + { + velocity.y += isBeastDungeon ? BEAST_DUNGEON_GRAVITY : DUNGEON_GRAVITY; + if (isBeastDungeon) friction *= BEAST_DUNGEON_FRICTION; + } + bool isInLava = g_game->frameCount - spawnFrame > DUNGEON_SETTLE_FRAMES && velocity.y > 0 && + room.bottomRightPos.y - DUNGEON_LAVA_MARGIN < pos.y; + if (isBeastDungeon && isInLava) + { + Remove(); + entity_spawn({pos, {}, nullptr, POOF02_LAVA_SPLASH, ENTITY_EFFECT, EFFECT_POOF02, Random()})->Update(); + } + } + + bool isSlider = is_listed({PICKUP_HEART, PICKUP_KEY, PICKUP_BOMB, PICKUP_COIN, PICKUP_PILL, PICKUP_LIL_BATTERY, + PICKUP_TAROTCARD, PICKUP_TRINKET}, + variant) || + IsChest(variant); + if (g_game->seedEffects.HasSeedEffect(SEED_PICKUPS_SLIDE) && isSlider) + reconstruction_missing("Entity_Pickup::Update 006e3940: the seed that slides pickups"); + if (g_game->seedEffects.HasSeedEffect(SEED_CAMO_PICKUPS) || g_game->seedEffects.HasSeedEffect(SEED_CAMO_EVERYTHING)) + reconstruction_missing("Entity_Pickup::Update 006e3940: the seeds that recolor pickups"); + + if (timeout > 0 && variant != PICKUP_COLLECTIBLE) + { + if (timeout < TIMEOUT_BLINK && timeout % 2 == 1) SetColor({}, 1, BLINK_PRIORITY, false, true); + } + else if (g_game->seedEffects.HasSeedEffect(SEED_PICKUPS_TIMEOUT)) + { + int age = g_game->frameCount - spawnFrame; + if (age > SEED_TIMEOUT_BLINK && age % 2 == 1) SetColor({}, 1, BLINK_PRIORITY, false, true); + if (age > SEED_TIMEOUT_REMOVE) return Remove(); + } + + if (variant == PICKUP_COIN && subtype == COIN_STICKYNICKEL && sprite.GetAnimation() == "Touched") + { + if (sprite.IsEventTriggered("DropSound")) pickup_sound_play(SOUND_NICKELDROP, {STICKY_NICKEL_VOLUME}); + if (!sprite.IsPlaying()) sprite.Play("Idle"); + } + bool isAppearing = sprite.IsPlaying("Appear") || sprite.IsPlaying("AppearFast"); + if (collisionCooldown > 0 && !isAppearing) collisionCooldown--; + lua_callback_check(LUA_CALLBACK_POST_PICKUP_UPDATE, "LuaEngine::PostPickupUpdate 00862fe0"); +} + +// A heart's swap for blue flies when every main player is a Keeper: the flies go to one of them at random, more for +// the heartier kinds. A golden heart stays. Whether the heart went. +bool Entity_Pickup::keeper_flies_update() +{ + std::vector keepers; + size_t mainPlayers = 0; + + for (Entity_Player* player : g_game->playerManager.playerList) + { + if (player->variant != 0) continue; + mainPlayers++; + if (player->playerType == PLAYER_KEEPER || player->playerType == PLAYER_KEEPER_B) keepers.push_back(player); + } + if (keepers.size() != mainPlayers || subtype == HEART_GOLDEN || keepers.empty()) return false; + + RNG rng = rng_make(initSeed, KEEPER_FLIES_SHIFT); + Entity_Player* keeper = keepers[rng.RandomInt((uint32_t)keepers.size())]; + int flies = 1; + Remove(); + if (is_listed({HEART_FULL, HEART_HALF_SOUL, HEART_SCARED, HEART_BLENDED, HEART_ROTTEN}, subtype)) flies = 2; + else if (subtype == HEART_SOUL) flies = 3; + else if (subtype == HEART_ETERNAL) flies = 5; + else if (is_listed({HEART_DOUBLEPACK, HEART_BLACK, HEART_BONE}, subtype)) flies = 4; + keeper->AddBlueFlies(flies, pos, nullptr); + return true; +} + +// Holds a pickup that must stay put (priced, a sticky nickel, the bed, mom's and mega chests) on its first position, +// moved off a blocked cell when it was just spawned. +void Entity_Pickup::target_position_update() +{ + if (targetPosition.x == 0 && targetPosition.y == 0) targetPosition = pos; + if (gridRepositionState == 2) + { + targetPosition = pos; + gridRepositionState = 0; + } + + bool isHeld = price != 0 || variant == PICKUP_BED || (variant == PICKUP_COIN && subtype == COIN_STICKYNICKEL) || + variant == PICKUP_MOMSCHEST || variant == PICKUP_MEGACHEST; + if (isHeld) + { + Room& room = *g_game->room; + bool isFresh = room.roomType != ROOM_DUNGEON && g_game->frameCount - spawnFrame < SETTLE_FRAMES; + if (isFresh && room.GetGridCollision(room.GetGridIndex(targetPosition)) != 0) + reconstruction_missing("Room::FindFreePickupSpawnPosition 00813520"); + velocity = vector_sub(targetPosition, pos); + } + if (gridRepositionState == 1) + reconstruction_missing("Entity_Pickup::Update 006e3940: a pickup pushed away from a door"); +} + +// Settles the appear animation: once it ends the pickup idles (a chest without contents shows open) and can be +// collected. Its drop sound plays on its event, which also lets it be collected while it still appears. +void Entity_Pickup::appear_update() +{ + if (HasEntityFlags(FLAG_GLITCH)) reconstruction_missing("Entity_Pickup::Update 006e3940: a glitched pickup"); + if (isDead && !sprite.IsPlaying()) return Remove(); + if (!sprite.animState.animData) return; + + bool isChest = IsChest(variant); + const std::string& animation = sprite.GetAnimation(); + bool isAppearAnimation = animation == "Appear" || animation == "AppearFast" || animation == "Reappear"; + if (!sprite.IsPlaying() && isAppearAnimation) + { + if (isChest && subtype == 0) return sprite.Play("Opened"); + sprite.Play("Idle"); + } + else + { + if (!sprite.IsEventTriggered("DropSound")) return; + PlayDropSound(); + bool isAppearing = sprite.IsPlaying("Appear") || sprite.IsPlaying("AppearFast") || sprite.IsPlaying("Reappear"); + if (isChest || !isAppearing) return; + } + entityCollisionClass = ENTCOLL_ALL; + if (variant == PICKUP_THROWABLEBOMB) entityGridCollisionClass = GRIDCOLL_GROUND; +} + +// 006ed690 Magneto, Super Magnet and Broken Magnet pull pickups to the players. Without them a pickup flying over the +// pits lands again. +void Entity_Pickup::update_magnet_attraction() +{ + PlayerManager& players = g_game->playerManager; + bool isMagnet = anyone_has_collectible(COLLECTIBLE_MAGNETO) || players.AnyoneHasTrinket(TRINKET_SUPER_MAGNET) || + players.AnyoneHasTrinket(TRINKET_BROKEN_MAGNET); + + if (isMagnet) reconstruction_missing("Entity_Pickup::update_magnet_attraction 006ed690: the magnets"); + if (entityGridCollisionClass == GRIDCOLL_WALLS) entityGridCollisionClass = GRIDCOLL_GROUND; +} + +// 006e8ae0 A player touching the pickup collects it (hearts, coins, keys and bombs into their counters), plays its +// pickup sound and animation and marks it dead. Coop ghosts, babies and players who cannot pick up take only a few +// kinds. Whether the collision is solid: a priced or collected pickup and players' bombs pass through. +// Items, chests, sacks, cards, pills, trinkets, shops, familiars that collect and the rarer items and trinkets that +// change what a pickup gives are not reconstructed yet. +bool Entity_Pickup::HandleCollision(Entity* collider, bool isLow) +{ + if (variant == PICKUP_COLLECTIBLE) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: an item"); + LuaResult result = static_cast(g_luaEngine)->PrePickupCollision(this, collider, isLow); + if (result == LUA_RESULT_TRUE) return true; + if (result == LUA_RESULT_FALSE) return false; + + if (collider->type == ENTITY_PLAYER) + { + if (collisionCooldown > 0) + { + collisionCooldown = COLLISION_COOLDOWN; + return true; + } + if (g_game->seedEffects.HasSeedEffect(SEED_PICKUPS_TIMEOUT)) ResetColor(); + if (HasEntityFlags(FLAG_THROWN) && spawnerType == ENTITY_POLTY) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a thrown pickup's hit"); + } + if (variant == PICKUP_COIN && subtype == COIN_STICKYNICKEL) + { + if (collider->type != ENTITY_PLAYER) return true; + sprite.Play("Touched"); + collisionCooldown = COLLISION_COOLDOWN; + if (static_cast(collider)->HasTrinket(TRINKET_CURSED_PENNY)) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Cursed Penny"); + return true; + } + if (isLow || collider->type != ENTITY_PLAYER) + { + int familiar = collider->type == ENTITY_FAMILIAR ? collider->variant : -1; + bool isCoinBum = is_listed({FAMILIAR_BUM_FRIEND, FAMILIAR_BUMBO, FAMILIAR_SUPER_BUM}, familiar); + bool isHeartBum = familiar == FAMILIAR_DARK_BUM || familiar == FAMILIAR_SUPER_BUM; + bool isKeyBum = familiar == FAMILIAR_KEY_BUM || familiar == FAMILIAR_SUPER_BUM; + bool isBum = !isLow && ((isCoinBum && variant == PICKUP_COIN) || (isHeartBum && variant == PICKUP_HEART) || + (isKeyBum && variant == PICKUP_KEY && subtype != KEY_GOLDEN)); + bool isEater = !isLow && (familiar == FAMILIAR_ABYSS_LOCUST || familiar == FAMILIAR_LIL_PORTAL) && + is_listed({PICKUP_HEART, PICKUP_COIN, PICKUP_KEY, PICKUP_BOMB, PICKUP_PILL, PICKUP_LIL_BATTERY, + PICKUP_TAROTCARD, PICKUP_TRINKET}, + variant); + bool isGreed = + (collider->type == ENTITY_ULTRA_GREED || collider->type == ENTITY_BUMBINO) && variant == PICKUP_COIN; + if (isBum || isEater || isGreed) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a familiar or enemy collecting it"); + return g_game->room->roomType == ROOM_DUNGEON || collider->type == ENTITY_BOMB || price != 0; + } + + Entity_Player* player = static_cast(collider); + if (player->playerType == PLAYER_JACOB2_B && player->twin_get() && variant != PICKUP_THROWABLEBOMB) + player = player->twin_get(); + + bool isRestricted = (variant == PICKUP_HEART && subtype == HEART_ETERNAL) || + (variant == PICKUP_BOMB && (subtype == BOMB_SUPERTROLL || subtype == BOMB_TROLL)) || + !is_listed({PICKUP_HEART, PICKUP_COIN, PICKUP_BOMB, PICKUP_GRAB_BAG, PICKUP_KEY}, variant); + if (!player->CanPickupItem() && isRestricted && !player->isDead) return price != 0; + + bool isRefused = wait > 0; + bool isGhostPickup = is_listed({PICKUP_COIN, PICKUP_KEY, PICKUP_BOMB, PICKUP_LOCKEDCHEST, PICKUP_GRAB_BAG, + PICKUP_BIGCHEST, PICKUP_REDCHEST}, + variant) || + (variant >= PICKUP_CHEST && variant <= PICKUP_HAUNTEDCHEST) || + (variant == PICKUP_HEART && subtype == HEART_ETERNAL); + bool isHelperRefused = is_listed({PICKUP_TAROTCARD, PICKUP_PILL, PICKUP_TRINKET, PICKUP_BED, PICKUP_BIGCHEST, + PICKUP_TROPHY}, + variant); + if (player->variant == 1 && player->babySkin == BABY_MAGNET && CanReroll()) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a co-op baby rerolling it"); + if (player->variant != 0) isRefused = true; + else if (player->isCoopGhost) isRefused |= !isGhostPickup; + else if (player->parent) isRefused |= isHelperRefused; + if (isRefused) return g_game->room->roomType == ROOM_DUNGEON || price != 0 || player->variant == 1; + if (price != 0) reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: buying"); + + bool isPickedUp = false; + int collectedSubtype = subtype; + switch (variant) + { + case PICKUP_HEART: + isPickedUp = heart_collect(*player); + break; + case PICKUP_COIN: + coin_collect(*player); + isPickedUp = true; + break; + case PICKUP_KEY: + isPickedUp = key_collect(*player); + break; + case PICKUP_BOMB: + isPickedUp = bomb_collect(*player); + break; + default: + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: chests, sacks, pocket items and trinkets"); + } + + if (!isPickedUp) + { + if (CanReroll() && isCollidesWithGrid) + velocity = vector_make(gridCollisionNormal.y * BUMP_SLIDE + velocity.x, + -gridCollisionNormal.x * BUMP_SLIDE + velocity.y); + return g_game->room->roomType == ROOM_DUNGEON || price != 0; + } + + RemoveOtherOptions(); + Room& room = *g_game->room; + bool isDevilDeal = room.roomType == ROOM_DEVIL || + (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_DEVIL_TREASURE) || + (room.roomType == ROOM_BOSS && (g_game->levelStateFlags & 0x20000)); + if (isDevilDeal && (state == 1 || spawnGridIndex >= 0)) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a devil deal"); + g_game->scoreSheet.add_pickup_points(variant, collectedSubtype, pos); + PlayPickupSound(); + collect_finish(player); + + if (g_game->playerManager.IsCoopPlay() && coopDuplicateIndex != -1) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a co-op item copy"); + return true; +} + +// The end of a collection: the procedural items' triggers, the pickup flying into its "Collect" animation and dying, +// and the run's note that a heart, bomb or coin was picked up. +void Entity_Pickup::collect_finish(Entity_Player* player) +{ + if (!player->proceduralItems.empty()) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: the procedural items' pickup trigger"); + + velocity = {}; + entityCollisionClass = ENTCOLL_NONE; + entityGridCollisionClass = GRIDCOLL_WALLS; + sprite.Play("Collect"); + isDead = true; + UpdateLootPreview(); + if (variant == PICKUP_COIN && subtype == COIN_GOLDEN) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a golden penny's return"); + if (variant == PICKUP_HEART || variant == PICKUP_BOMB || variant == PICKUP_COIN) + g_game->gameStateFlags |= 1ull << GAME_STATE_HEART_BOMB_COIN_PICKED; +} + +// The hearts a red heart of each kind holds, in halves. +static int red_heart_amount(int heartKind) +{ + return heartKind == HEART_HALF ? 1 : heartKind == HEART_DOUBLEPACK ? 4 : 2; +} + +// The red hearts a player can still take, counting bone hearts as containers unless they only hold soul hearts. +static int red_heart_room(Entity_Player& player) +{ + HealthType health = player.GetHealthType(); + int containers = health == HEALTH_SOUL || health == HEALTH_NO_HEALTH ? player.maxHearts + : player.maxHearts + player.boneHearts * 2; + return containers - player.redHearts; +} + +// A heart into the player's health: red hearts fill every player who can take them, the picker first, then the +// wisps they heal and The Jar. Soul, black, eternal, golden, bone and rotten hearts go to the picker, a blended heart +// fills red first and soul after. Whether anything was taken. +bool Entity_Pickup::heart_collect(Entity_Player& player) +{ + if (player.HasTrinket(TRINKET_APPLE_OF_SODOM)) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Apple of Sodom"); + if (g_game->challenge == CHALLENGE_APRILS_FOOL) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Bloody Mary's hearts"); + + switch (subtype) + { + case HEART_FULL: + case HEART_HALF: + case HEART_DOUBLEPACK: + case HEART_SCARED: + break; + case HEART_SOUL: + case HEART_HALF_SOUL: + { + if (!player.CanPickSoulHearts()) return false; + int amount = subtype == HEART_SOUL ? 2 : 1; + player.AddSoulHearts(amount, false); + player.AddImmaculateConceptionCounter(amount); + return true; + } + case HEART_ETERNAL: + { + bool isRoom = player.maxHearts < player.GetHeartLimit(false) || player.eternalHearts == 0; + if (!isRoom || player.GetHealthType() == HEALTH_COIN) return false; + player.AddEternalHearts(1); + player.AddImmaculateConceptionCounter(1); + return true; + } + case HEART_BLACK: + if (!player.CanPickBlackHearts()) return false; + player.AddBlackHearts(2); + player.AddImmaculateConceptionCounter(2); + return true; + case HEART_GOLDEN: + if (!player.CanPickGoldenHearts()) return false; + player.AddGoldenHearts(1, false); + return true; + case HEART_BLENDED: + { + bool isMaggysBow = player.HasCollectible(COLLECTIBLE_MAGGYS_BOW); + bool isRed = false; + bool isSoul = false; + for (int left = 2; left > 0; left--) + { + if (player.CanPickRedHearts()) + { + player.AddHearts(isMaggysBow + 1, true, false); + isRed = true; + continue; + } + if (player.CanPickSoulHearts()) + { + player.AddSoulHearts(left, false); + isSoul = true; + } + else if (left > 1) return false; + break; + } + if (isRed) + { + pickup_sound_play(SOUND_BOSS2_BUBBLES); + player.AddImmaculateConceptionCounter(2); + } + if (isSoul) pickup_sound_play(SOUND_HOLY); + return true; + } + case HEART_BONE: + if (!player.CanPickBoneHearts()) return false; + player.AddBoneHearts(1); + player.AddImmaculateConceptionCounter(2); + return true; + case HEART_ROTTEN: + if (player.playerType == PLAYER_BETHANY_B) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Tainted Bethany's blood"); + if (!player.CanPickRottenHearts()) return false; + player.AddRottenHearts(2, false); + player.AddImmaculateConceptionCounter(2); + return true; + default: + return false; + } + + int amount = red_heart_amount(subtype); + bool isMaggysBow = player.HasCollectible(COLLECTIBLE_MAGGYS_BOW); + bool isPickedUp = false; + if (isMaggysBow) amount *= 2; + if (player.playerType == PLAYER_BETHANY_B && player.CanPickRedHearts()) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Tainted Bethany's blood"); + + for (Entity_Player* other : g_game->playerManager.playerList) + { + if (amount <= 0) break; + if (other->isDead || !other->CanPickRedHearts()) continue; + if (other != &player && other->variant != 1) continue; + + bool isSoulOwner = + other == &player && other->variant == 0 && other->playerType == PLAYER_THESOUL && other->subPlayer; + int taken = std::min(amount, red_heart_room(isSoulOwner ? *other->subPlayer : *other)); + other->AddHearts(taken, true, false); + other->AddImmaculateConceptionCounter(taken); + amount -= taken; + isPickedUp = true; + } + for (Entity* entity : g_game->room->entityList.updateEL) + if (entity->IsType(ENTITY_FAMILIAR, FAMILIAR_WISP, WISP_HEALED_BY_HEARTS) && entity->isExists && + static_cast(entity)->player == &player) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a wisp healed by hearts"); + + int jarAmount = isMaggysBow ? amount / 2 : amount; + if (jarAmount > 0 && player.activeItems[0].item == COLLECTIBLE_THE_JAR && player.jarHearts < JAR_HEARTS_MAX) + { + player.AddJarHearts(jarAmount); + isPickedUp = true; + } + return isPickedUp; +} + +// A coin into the player's coins, and a lucky penny's luck with its name shown. +// The pennies trinkets turn into other pickups are not reconstructed yet. +void Entity_Pickup::coin_collect(Entity_Player& player) +{ + if (g_game->challenge == CHALLENGE_APRILS_FOOL) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Bloody Mary's coins"); + player.AddCoins(GetCoinValue()); + + for (int trinket : PENNY_TRINKETS) + if (player.HasTrinket(trinket)) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a penny trinket"); + + if (subtype != COIN_LUCKYPENNY) return; + StringTable& strings = g_manager->stringTable; + std::string description(strings.translate("#LUCKY_PENNY_DESCRIPTION")); + std::string name(strings.translate("#LUCKY_PENNY_NAME")); + player.DonateLuck(1); + g_game->hud.show_pill_name(&player, name.c_str(), description.c_str()); + player.AnimateHappy(); +} + +// A key into the player's keys: one, two from a key ring, or a golden key. Whether it was taken. +// A charged key's charge is not reconstructed yet. +bool Entity_Pickup::key_collect(Entity_Player& player) +{ + if (g_game->challenge == CHALLENGE_APRILS_FOOL) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Bloody Mary's keys"); + + switch (subtype) + { + case KEY_NORMAL: + player.AddKeys(1); + return true; + case KEY_DOUBLEPACK: + player.AddKeys(2); + return true; + case KEY_GOLDEN: + player.AddGoldenKey(); + return true; + case KEY_CHARGED: + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: a charged key"); + default: + return false; + } +} + +// A bomb into the player's bombs: one, two, a golden bomb or a giga bomb with its bomb. Whether it was taken. +bool Entity_Pickup::bomb_collect(Entity_Player& player) +{ + if (g_game->challenge == CHALLENGE_APRILS_FOOL) + reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0: Bloody Mary's bombs"); + + switch (subtype) + { + case BOMB_NORMAL: + player.AddBombs(1); + return true; + case BOMB_DOUBLEPACK: + player.AddBombs(2); + return true; + case BOMB_GOLDEN: + player.AddGoldenBomb(); + return true; + case BOMB_GIGA: + player.AddBombs(1); + player.AddGigaBombs(1); + return true; + default: + return false; + } +} + +// 006e7be0 Plays the sound of the pickup landing, by its kind. +void Entity_Pickup::PlayDropSound() +{ + int sound = 0; + + switch (variant) + { + case PICKUP_HEART: + sound = subtype == HEART_GOLDEN ? SOUND_GOLD_HEART_DROP : subtype == HEART_BONE ? SOUND_BONE_DROP + : SOUND_MEAT_FEET_SLOW0; + break; + case PICKUP_COIN: + if (is_listed({COIN_PENNY, COIN_LUCKYPENNY, COIN_DOUBLEPACK}, subtype)) sound = SOUND_PENNYDROP; + else if (subtype == COIN_NICKEL || subtype == COIN_STICKYNICKEL) sound = SOUND_NICKELDROP; + else if (subtype == COIN_DIME || subtype == COIN_GOLDEN) sound = SOUND_DIMEDROP; + break; + case PICKUP_KEY: + sound = SOUND_KEY_DROP0; + break; + case PICKUP_BOMB: + sound = subtype == BOMB_GOLDEN ? SOUND_GOLD_HEART_DROP : SOUND_FETUS_LAND; + break; + case PICKUP_PILL: + sound = (subtype & PILL_COLOR_MASK) == PILL_GOLD ? SOUND_GOLD_HEART_DROP : SOUND_FETUS_JUMP; + break; + case PICKUP_GRAB_BAG: + sound = SOUND_FETUS_JUMP; + break; + case PICKUP_TAROTCARD: + sound = SOUND_SCAMPER; + break; + case PICKUP_TRINKET: + sound = subtype == TRINKET_BUTTER ? SOUND_BUTTER_LAND : SOUND_SCAMPER; + break; + case PICKUP_BROKEN_SHOVEL: + sound = SOUND_SHOVEL_DROP; + break; + case PICKUP_THROWABLEBOMB: + sound = SOUND_FETUS_LAND; + break; + case PICKUP_POOP: + sound = SOUND_SPLATTER; + break; + } + if (IsChest(variant)) sound = SOUND_CHEST_DROP; + if (sound) pickup_sound_play(sound); +} + +// 006e7dc0 Plays the sound of the pickup being collected, by its kind. +// An item's fanfare is not reconstructed yet. +void Entity_Pickup::PlayPickupSound() +{ + int sound = 0; + + switch (variant) + { + case PICKUP_HEART: + if (subtype == HEART_ETERNAL) sound = SOUND_SUPERHOLY; + else if (subtype == HEART_SOUL || subtype == HEART_HALF_SOUL) sound = SOUND_HOLY; + else if (subtype == HEART_BLACK) sound = SOUND_UNHOLY; + else if (subtype == HEART_GOLDEN) sound = SOUND_GOLD_HEART; + else if (subtype == HEART_BONE) sound = SOUND_BONE_HEART; + else if (subtype == HEART_ROTTEN) sound = SOUND_ROTTEN_HEART; + else if (subtype != HEART_BLENDED) sound = SOUND_BOSS2_BUBBLES; + break; + case PICKUP_COIN: + if (is_listed({COIN_PENNY, COIN_DOUBLEPACK, COIN_GOLDEN}, subtype)) sound = SOUND_PENNYPICKUP; + else if (subtype == COIN_NICKEL || subtype == COIN_STICKYNICKEL) sound = SOUND_NICKELPICKUP; + else if (subtype == COIN_DIME) sound = SOUND_DIMEPICKUP; + else if (subtype == COIN_LUCKYPENNY) sound = SOUND_LUCKYPICKUP; + break; + case PICKUP_KEY: + if (subtype == KEY_GOLDEN) sound = SOUND_GOLDENKEY; + else if (is_listed({KEY_NORMAL, KEY_DOUBLEPACK, KEY_CHARGED}, subtype)) + return pickup_sound_play(SOUND_KEYPICKUP_GAUNTLET, {KEY_PICKUP_VOLUME}); + break; + case PICKUP_BOMB: + sound = subtype == BOMB_GOLDEN ? SOUND_GOLDENBOMB : SOUND_FETUS_FEET; + break; + case PICKUP_PILL: + case PICKUP_TRINKET: + case PICKUP_GRAB_BAG: + sound = SOUND_SHELLGAME; + break; + case PICKUP_TAROTCARD: + { + ItemConfig_Card* card = g_manager->itemConfig.GetCard(subtype); + bool isObject = + card && (is_listed(CARD_OBJECT_SUBTYPES, card->pickupSubtype) || card->cardType == CARD_RUNE); + sound = isObject ? SOUND_SHELLGAME : SOUND_BOOK_PAGE_TURN_12; + break; + } + case PICKUP_COLLECTIBLE: + reconstruction_missing("Entity_Pickup::PlayPickupSound 006e7dc0: an item"); + case PICKUP_THROWABLEBOMB: + sound = SOUND_FETUS_FEET; + break; + case PICKUP_POOP: + { + float pitch = (float)Random() * RANDOM_UNIT * POOP_PITCH_RANGE + POOP_PITCH_MIN; + return pickup_sound_play(SOUND_PING_PONG, {1, 2, SOUND_ONCE, pitch}); + } + } + if (sound) pickup_sound_play(sound); +} + +// 006e8380 How many coins a coin is worth, 0 for anything else. +int Entity_Pickup::GetCoinValue() +{ + return variant == PICKUP_COIN && subtype >= COIN_PENNY && subtype <= COIN_GOLDEN ? COIN_VALUES[subtype] : 0; +} + +// 006ee390 Whether a player can collect the kind straight into their counters or pockets, if it is free or the price +// is ignored. +bool Entity_Pickup::CanBePickedUp(bool isIgnorePrice) +{ + bool isCollectable = is_listed({PICKUP_HEART, PICKUP_COIN, PICKUP_LIL_BATTERY, PICKUP_BOMB, PICKUP_KEY, + PICKUP_PILL, PICKUP_TAROTCARD, PICKUP_TRINKET, PICKUP_GRAB_BAG, + PICKUP_THROWABLEBOMB, PICKUP_POOP}, + variant); + return isCollectable && (isIgnorePrice || price == 0); +} + +// 006ee200 Whether rerolls may change it: alive, of a rerollable kind, and not an opened chest. +bool Entity_Pickup::CanReroll() +{ + return !isDead && CanRerollVariant(variant, subtype) && (!IsChest(variant) || subtype != 0); +} + +// 006ee240 Whether rerolls may change a kind: not the big chest, trophy, bed, mom's chest or a throwable bomb, and not +// the items a run needs (the Broken Shovel, the knife pieces, the Polaroid and the Negative where a challenge's path +// needs them, the glitched item a seed hides). +bool Entity_Pickup::CanRerollVariant(int pickupVariant, int pickupSubType) +{ + if (is_listed({PICKUP_BED, PICKUP_TROPHY, PICKUP_BIGCHEST, PICKUP_THROWABLEBOMB, PICKUP_MOMSCHEST}, pickupVariant)) + return false; + if (pickupVariant != PICKUP_COLLECTIBLE) return true; + if (pickupSubType == COLLECTIBLE_MOMS_SHOVEL) return false; + if (g_game->seedEffects.HasSeedEffect(SEED_G_FUEL) && pickupSubType == -1) return false; + + bool isChallenge = g_game->challenge != 0 || g_game->dailyChallenge._id != 0; + PathType path = isChallenge ? g_game->GetChallengeParams().pathType : PATH_TYPE_SHEOL; + bool isKnifePiece = pickupSubType == COLLECTIBLE_KNIFE_PIECE_1 || pickupSubType == COLLECTIBLE_KNIFE_PIECE_2; + bool isPhoto = pickupSubType == COLLECTIBLE_THE_POLAROID || pickupSubType == COLLECTIBLE_THE_NEGATIVE; + if (isChallenge && isKnifePiece && path == PATH_TYPE_REPENTANCE) return false; + return !(isChallenge && isPhoto && (path == PATH_TYPE_HOME || g_game->GetChallengeParams().endStage == STAGE_VOID)); +} + +// 006ee750 Taking one of a set of options removes the others in a poof, items after a short timeout. +// The Death Certificate floor's items are not reconstructed yet. +void Entity_Pickup::RemoveOtherOptions() +{ + if (variant == PICKUP_COLLECTIBLE) reconstruction_missing("Entity_Pickup::RemoveOtherOptions 006ee750: an item"); + if (optionsPickupIndex == 0) return; + + std::vector pickups(g_game->room->entityList.updateEL); + for (Entity* entity : pickups) + { + if (!entity || entity->type != ENTITY_PICKUP || entity == this) continue; + Entity_Pickup* other = static_cast(entity); + bool isEmptyPedestal = other->variant == PICKUP_COLLECTIBLE && other->subtype == 0; + if (other->optionsPickupIndex != optionsPickupIndex || isEmptyPedestal) continue; + entity_spawn({vector_make(other->pos.x, other->pos.y + OPTIONS_POOF_DROP), {}, nullptr, 0, ENTITY_EFFECT, + EFFECT_POOF01, Random()}); + if (other->variant == PICKUP_COLLECTIBLE) other->timeout = OPTIONS_ITEM_TIMEOUT; + else other->Remove(); + } + optionsPickupIndex = 0; +} + +// 006e3800 A held chest thrown by a source: it flies from the ground up at the force, pushed along the direction. +// Nothing else is thrown. +bool Entity_Pickup::TryThrow(const EntityRef& source, const Vector& direction, float force) +{ + if (!IsChest(variant) || HasEntityFlags(FLAG_THROWN)) return false; + + spawnerType = source.type; + spawnerVariant = (uint32_t)source.variant; + height = 0; + posOffset.y = 0; + velocity = vector_make(velocity.x + direction.x, velocity.y + direction.y); + flags = (flags & ~FLAG_HELD) | FLAG_THROWN; + isVisible = true; + heightVelocity = -force; + return false; +} // 006ee110 Removes it with the ghost that shows its contents. void Entity_Pickup::Remove() @@ -14,6 +1815,16 @@ void Entity_Pickup::Remove() Entity::Remove(); } +// 006ee130 Removes the contents preview and lets go of its links. +void Entity_Pickup::ClearReferences() +{ + if (pickupGhost) pickupGhost->Remove(); + unkEntityRef = nullptr; + pickupGhost = nullptr; + megaChestCollectible = {}; + Entity::ClearReferences(); +} + // 005b1930 Whether a shop sells it. bool Entity_Pickup::IsShopItem() { @@ -28,54 +1839,12 @@ bool Entity_Pickup::IsChest(int pickupVariant) // The rest of Entity_Pickup is not reconstructed yet. -// 006e02f0 -void Entity_Pickup::Init(int, int, int, uint32_t) -{ - reconstruction_missing("Entity_Pickup::Init 006e02f0"); -} - -// 006e3940 -void Entity_Pickup::Update() -{ - reconstruction_missing("Entity_Pickup::Update 006e3940"); -} - -// 006e38d0 -void Entity_Pickup::Interpolate() -{ - reconstruction_missing("Entity_Pickup::Interpolate 006e38d0"); -} - -// 006e69b0 -void Entity_Pickup::Render(const Vector&) -{ - reconstruction_missing("Entity_Pickup::Render 006e69b0"); -} - // 006edda0 bool Entity_Pickup::TakeDamage(float, uint64_t, const EntityRef&, int) { reconstruction_missing("Entity_Pickup::TakeDamage 006edda0"); } -// 006ee130 -void Entity_Pickup::ClearReferences() -{ - reconstruction_missing("Entity_Pickup::ClearReferences 006ee130"); -} - -// 006e3800 -bool Entity_Pickup::TryThrow(const EntityRef&, const Vector&, float) -{ - reconstruction_missing("Entity_Pickup::TryThrow 006e3800"); -} - -// 006e8ae0 -bool Entity_Pickup::HandleCollision(Entity*, bool) -{ - reconstruction_missing("Entity_Pickup::HandleCollision 006e8ae0"); -} - // 005832c0 void Entity_Pickup::GetLootList(const Vector&) { @@ -94,12 +1863,6 @@ bool Entity_Pickup::TryFlip(Entity_Player*, uint32_t) reconstruction_missing("Entity_Pickup::TryFlip 006e1640"); } -// 006e17c0 -void Entity_Pickup::UpdateLootPreview() -{ - reconstruction_missing("Entity_Pickup::UpdateLootPreview 006e17c0"); -} - // 006e1a80 void Entity_Pickup::SetAlternatePedestal(int) { @@ -118,18 +1881,6 @@ void Entity_Pickup::SetForceBlind(uint8_t) reconstruction_missing("Entity_Pickup::SetForceBlind 006e1e60"); } -// 006e21f0 -void Entity_Pickup::UpdateSprite(bool) -{ - reconstruction_missing("Entity_Pickup::UpdateSprite 006e21f0"); -} - -// 006e2570 -void Entity_Pickup::update_price_sprite(int) -{ - reconstruction_missing("Entity_Pickup::update_price_sprite 006e2570"); -} - // 006e3020 void Entity_Pickup::AppearFast() { @@ -142,24 +1893,6 @@ bool Entity_Pickup::TryOpenChest(Entity_Player*) reconstruction_missing("Entity_Pickup::TryOpenChest 006e6e40"); } -// 006e7be0 -void Entity_Pickup::PlayDropSound() -{ - reconstruction_missing("Entity_Pickup::PlayDropSound 006e7be0"); -} - -// 006e7dc0 -void Entity_Pickup::PlayPickupSound() -{ - reconstruction_missing("Entity_Pickup::PlayPickupSound 006e7dc0"); -} - -// 006e8380 -int Entity_Pickup::GetCoinValue() -{ - reconstruction_missing("Entity_Pickup::GetCoinValue 006e8380"); -} - // 006e83a0 uint32_t Entity_Pickup::can_player_buy(Entity_Player*) { @@ -178,48 +1911,18 @@ uint8_t Entity_Pickup::empty_pedestal() reconstruction_missing("Entity_Pickup::empty_pedestal 006ed580"); } -// 006ed690 -void Entity_Pickup::update_magnet_attraction() -{ - reconstruction_missing("Entity_Pickup::update_magnet_attraction 006ed690"); -} - // 006edfa0 void Entity_Pickup::update_cycle_collectible(bool) { reconstruction_missing("Entity_Pickup::update_cycle_collectible 006edfa0"); } -// 006ee200 -bool Entity_Pickup::CanReroll() -{ - reconstruction_missing("Entity_Pickup::CanReroll 006ee200"); -} - -// 006ee240 -bool Entity_Pickup::CanRerollVariant(int, int) -{ - reconstruction_missing("Entity_Pickup::CanRerollVariant 006ee240"); -} - -// 006ee390 -bool Entity_Pickup::CanBePickedUp(bool) -{ - reconstruction_missing("Entity_Pickup::CanBePickedUp 006ee390"); -} - // 006ee3f0 bool Entity_Pickup::CanJeraDuplicate() { reconstruction_missing("Entity_Pickup::CanJeraDuplicate 006ee3f0"); } -// 006ee750 -void Entity_Pickup::RemoveOtherOptions() -{ - reconstruction_missing("Entity_Pickup::RemoveOtherOptions 006ee750"); -} - // 006eea30 void Entity_Pickup::MakeShopItem(int) { diff --git a/src/entity_pickup.h b/src/entity_pickup.h index 03a085e..185b7a8 100644 --- a/src/entity_pickup.h +++ b/src/entity_pickup.h @@ -8,21 +8,48 @@ // The most items a glitched pedestal cycles through. constexpr int CYCLE_COLLECTIBLE_LIMIT = 8; -// Construction and destruction (006e0130, 006e0010) are the defaults. +// Whether pickup_variant_pick draws its trinkets and items for good, or only looks at what a draw would give. +enum PoolDraw +{ + POOL_DRAW_PEEK, + POOL_DRAW_TAKE +}; + +// Whether pickup_variant_pick chooses for a shop's wares, which Keeper-only parties never buy hearts for. +enum PickupSale +{ + PICKUP_FREE, + PICKUP_FOR_SALE +}; + +// A pickup kind to choose (Pickup_PickVariant): a variant and subtype where 0 asks for a random one, the seed the +// choice comes from, and how it draws from the pools. +struct PickupChoice +{ + int subType = 0; + int variant = 0; + uint32_t seed = 0; + PoolDraw draw = POOL_DRAW_TAKE; + PickupSale sale = PICKUP_FREE; +}; + +// Construction and destruction (006e0130, 006e0010, 006e0160) are the defaults. // Field accessors (00431740, 005b1940, 005b1980, 007e9390, 007e93a0, 007e93b0, 007e93c0, 0085e440) are the public // fields. // A pickup (Lua's EntityPickup): coins, hearts, keys, chests, cards, items on pedestals and the like, with the price -// a shop sets, its timeout, and the items a glitched pedestal cycles through. +// a shop sets, its timeout, the height a thrown chest flies at, and the items a glitched pedestal cycles through. struct Entity_Pickup : Entity { ANM2 altPedestalANM2; ANM2 priceANM2; - std::array megaChestCollectible{}; + std::array megaChestCollectible; std::array cycleCollectibleList{}; std::shared_ptr flipSaveState; ColorMod colorMod = COLOR_DEFAULT; + EntityPtr pickupGhost; EntityPtr unkEntityRef; - Entity_Effect* pickupGhost = nullptr; + float height = 0; + float heightVelocity = 0; int charge = 0; int chestReCloseTimer = 0; int collisionCooldown = 0; @@ -43,6 +70,7 @@ struct Entity_Pickup : Entity bool isForceBlind = false; bool isPayToPlay = false; bool isTouched = false; + bool isUnknown52d = false; void Init(int type, int variant, int subType, uint32_t initSeed) override; void Update() override; @@ -63,7 +91,7 @@ struct Entity_Pickup : Entity int GetAlternatePedestal(); void SetForceBlind(uint8_t setBlind); void UpdateSprite(bool isIgnoreBlind); - void update_price_sprite(int price); + void update_price_sprite(int newPrice); void AppearFast(); bool TryOpenChest(Entity_Player* player); void PlayDropSound(); @@ -77,10 +105,24 @@ struct Entity_Pickup : Entity bool CanReroll(); static bool CanRerollVariant(int variant, int subType); static bool IsChest(int pickupVariant); - bool CanBePickedUp(bool ignorePrice); + bool CanBePickedUp(bool isIgnorePrice); bool CanJeraDuplicate(); - static void RemoveOtherOptions(); + void RemoveOtherOptions(); void MakeShopItem(int shopId); int AssignOptionsIndex(); static void RestoreState(Room* room, Entity_Pickup* entity, void* saveState); + +private: + void appear_start(); + bool keeper_flies_update(); + void target_position_update(); + void appear_update(); + bool heart_collect(Entity_Player& player); + void coin_collect(Entity_Player& player); + bool key_collect(Entity_Player& player); + bool bomb_collect(Entity_Player& player); + void collect_finish(Entity_Player* player); }; + +bool pickup_variant_pick(PickupChoice& choice); +bool entity_type_is_saved(int type, int variant, uint32_t subType, int spawnerType, bool isRoomEntry); diff --git a/src/entity_player.h b/src/entity_player.h index b78c652..7adfd6e 100644 --- a/src/entity_player.h +++ b/src/entity_player.h @@ -691,6 +691,7 @@ public: uint8_t holyMantleStacks = 0; uint8_t holyMantleState = 0; bool isHurtPending = false; + bool isHurtThisRoom = false; std::shared_ptr playerHUD; std::vector contactHitList; @@ -762,6 +763,7 @@ public: int eveSumptoriumCharge = 0; int forgottenSwapFormCooldown = 0; int gnawedLeafTimer = 0; + int evilCharmHazardFrames = 0; int hallowedGroundCountdown = 0; int immaculateConceptionState = 0; int keepersSackBonus = 0; @@ -801,6 +803,7 @@ public: short tonsilCounter = 0; bool isBrokenRemotePending = false; bool isDarkArtsBlastPending = false; + bool isInEvilCharmHazard = false; bool isLevelStartPending = false; bool isMarsDashReady = true; bool isPostLevelInitFinished = false; @@ -1010,6 +1013,7 @@ public: bool TryUseKey(); void AddCostume(ItemConfig_Item* item, bool isItemStateOnly); void AddNullCostume(int costumeid); + bool IsItemCostumeVisible(ItemConfig_Item* item, int playerSpriteLayerID); bool IsNullItemCostumeVisible(int nullItemID, int playerSpriteLayerID); void ClearQueueItem(); bool FlushQueueItem(); @@ -1038,6 +1042,8 @@ public: void update_bomb_input(); void trigger_fire_item_effects(Vector direction, bool isShotFired); const char* GetDeathAnimName(); + void death_count(const EntityRef& source, uint64_t damageFlags); + void death_update(); Entity* GetActiveWeaponEntity(); uint32_t CanTurnHead(); float FireDelay(); @@ -1182,6 +1188,7 @@ public: void ChangePlayerType(int playerType, bool isUnknown); void player_type_change_prepare(int newPlayerType); bool IsLocalPlayer(); + float local_volume_get(); void GetGlyphOfBalanceDrop(int* variant, int* subtype); Vector GetEnterPosition(); Entity_Familiar* AddMinisaac(Vector position, bool isPlayAnim); diff --git a/src/entity_player_damage.cpp b/src/entity_player_damage.cpp new file mode 100644 index 0000000..7a1dc33 --- /dev/null +++ b/src/entity_player_damage.cpp @@ -0,0 +1,861 @@ +#include "entity_familiar.h" +#include "entity_npc.h" +#include "entity_player.h" +#include "game.h" +#include "level.h" +#include "log.h" +#include "lua_engine.h" +#include "manager.h" +#include "room.h" +#include +#include + +constexpr int COLLECTIBLE_BINKY = 438; +constexpr int COLLECTIBLE_BOBS_CURSE = 140; +constexpr int COLLECTIBLE_BOOMERANG = 338; +constexpr int COLLECTIBLE_CONE_HEAD = 457; +constexpr int COLLECTIBLE_DOGMA = 633; +constexpr int COLLECTIBLE_DULL_RAZOR = 486; +constexpr int COLLECTIBLE_EVIL_CHARM = 632; +constexpr int COLLECTIBLE_GLASS_CANNON = 352; +constexpr int COLLECTIBLE_HOST_HAT = 375; +constexpr int COLLECTIBLE_HOT_BOMBS = 256; +constexpr int COLLECTIBLE_HYPERCOAGULATION = 724; +constexpr int COLLECTIBLE_INNER_CHILD = 688; +constexpr int COLLECTIBLE_IPECAC = 149; +constexpr int COLLECTIBLE_ISAACS_HEART = 276; +constexpr int COLLECTIBLE_JELLY_BELLY = 690; +constexpr int COLLECTIBLE_LARYNX = 611; +constexpr int COLLECTIBLE_MARBLES = 538; +constexpr int COLLECTIBLE_METAL_PLATE = 449; +constexpr int COLLECTIBLE_MOMS_BRACELET = 604; +constexpr int COLLECTIBLE_PLUTO = 598; +constexpr int COLLECTIBLE_PYROMANIAC = 223; +constexpr int COLLECTIBLE_SCAPULAR = 142; +constexpr int COLLECTIBLE_SHOOP_DA_WHOOP = 49; +constexpr int COLLECTIBLE_SPIRIT_SHACKLES = 674; +constexpr int COLLECTIBLE_ASTRAL_PROJECTION = 677; +constexpr int COLLECTIBLE_BERSERK = 704; +constexpr int COLLECTIBLE_BLACK_CANDLE = 260; +constexpr int COLLECTIBLE_THE_NAIL = 83; +constexpr int TRINKET_BLIND_RAGE = 81; +constexpr int TRINKET_CALLUS = 14; +constexpr int TRINKET_CROW_HEART = 107; +constexpr int TRINKET_FINGER_BONE = 128; +constexpr int TRINKET_MONKEY_PAW = 20; +constexpr int TRINKET_PERFECTION = 145; +constexpr int TRINKET_SWALLOWED_M80 = 178; +constexpr int TRINKET_WALNUT = 108; +constexpr int NULLITEM_BOOMERANG = 30; +constexpr int NULLITEM_DOUBLE_DAMAGE = 29; +constexpr int NULLITEM_SHACKLES_GHOST = 101; +constexpr int PLAYER_FORM_ADULT = 11; +constexpr int PLAYER_FORM_BEELZEBUB = 13; +constexpr int PLAYER_FORM_BOB = 4; +constexpr int SAMSON_B_HIT_CHARGE = 10000; +constexpr int BLEED_OUT_HEALTH = 600; + +// The items and trinkets a landed hit sets off, by id, from Infestation's flies to Tonsil and Pinking Shears. +constexpr int HIT_COLLECTIBLES[] = {148, 525, 658, 696, 162, 117, 610, 274, 156, 180, 214, 204, 219, 225, 227, 211, 262, + 301, 303, 392, 157, 695, 186, 371, 407, 412, 448, 452, 560, 675, 702, 502, 513}; +constexpr int HIT_TRINKETS[] = {40, 48, 29, 1, 8, 67, 158, 97, 105, 33, 104, 122}; +constexpr int CROWN_OF_LIGHT = 415; +constexpr int HYPERCOAGULATION_IGNORED = 0x10040000; + +constexpr int ENTITY_MOM = 45; +constexpr int ENTITY_MOMS_HEART = 78; +constexpr int ENTITY_BISHOP = 805; +constexpr int ENTITY_SEGMENTED_WORM = 903; +constexpr int ENTITY_DAMAGE_RELAY = 966; +constexpr int SEGMENTED_WORM_VARIANT = 10; +constexpr int WHITE_FIRE_VARIANT = 4; +constexpr int EFFECT_SELF_DAMAGE = 19; +constexpr int EFFECT_POISON_CLOUD = 123; +constexpr int FAMILIAR_WISP = 206; +constexpr int ITEM_STATE_HOLD_STILL = 47; +constexpr int ENEMY_TYPE_FIRST = 10; +constexpr int ENEMY_TYPE_LAST = 999; +constexpr int BABY_GHOST = 59; +constexpr int BABY_HALO = 24; +constexpr int BABY_SHIELD = 11; +constexpr int BABY_BOMB = 20; +constexpr int BABY_FART = 17; +constexpr int BABY_BOOK = 44; + +// The thieves that knock a coin loose: Greed and its likes by their hits or shots, the Ultra Greeds also by what they +// spawn. +constexpr int COIN_THIEF_TYPES[] = {50, 86, 90, 294, 299, 406}; +constexpr int COIN_SHOOTER_TYPES[] = {50, 86, 90}; +constexpr int ULTRA_GREED = 406; +constexpr int ULTRA_GREED_DOOR = 294; +constexpr uint32_t CHALLENGE_PAY_TO_PLAY = 24; + +constexpr int SOUND_FIREDEATH_HISS = 43; +constexpr int SOUND_ISAAC_HURT_GRUNT = 55; +constexpr int SOUND_NAIL_HURT_1 = 104; +constexpr int SOUND_NAIL_HURT_2 = 106; +constexpr int SOUND_MOM_VOX = 84; +constexpr int SOUND_HEARTBEAT = 86; +constexpr int SOUND_BOSS_DELAY_RANDOM = 130; +constexpr int SOUND_BOSS_DELAY_MIN = 50; +constexpr int SOUND_FRAME_DELAY = 2; + +constexpr uint64_t DAMAGE_RED_HEARTS = 1ull << 5; +constexpr uint64_t DAMAGE_INVINCIBLE_IGNORED = 1ull << 13; +constexpr uint64_t DAMAGE_SPAWN_FLY = 1ull << 14; +constexpr uint64_t DAMAGE_FAKE = 1ull << 21; +constexpr uint64_t DAMAGE_NO_MODIFIERS = 1ull << 25; +constexpr uint64_t DAMAGE_NO_PENALTIES = 1ull << 28; +constexpr uint64_t DAMAGE_IGNORED = 1ull << 34; +constexpr uint64_t DAMAGE_THROUGH_COOLDOWN = 1ull << 35; +constexpr uint64_t DAMAGE_NO_HURT_EFFECTS = 0x100d0400; +constexpr uint64_t DAMAGE_ISAACS_HEART_PIERCE = 0x2820; +constexpr uint64_t DAMAGE_UNPENALIZED = DAMAGE_NO_PENALTIES | DAMAGE_RED_HEARTS; + +constexpr int LEVEL_STATE_DAMAGED = 5; +constexpr int LAST_DAMAGE_STAGE_MAX = 13; +constexpr int HURT_FRAMES_PER_HEART = 60; +constexpr int HURT_HEARTS_MAX = 2; +constexpr int HIT_COOLDOWN = 4; +constexpr int MC_ENTITY_TAKE_DMG = 11; +constexpr uint32_t DEBUG_INFINITE_HP = 1 << 2; +constexpr uint32_t DEBUG_DAMAGE_VALUES = 1 << 6; +constexpr uint32_t STAGE_FULL_HEART_DAMAGE = 7; +constexpr int MASSIVE_DAMAGE = 24; +constexpr int EVIL_CHARM_GRACE_FRAMES = 30; +constexpr int COOLDOWN_SCALE_MIN = 16; +constexpr int COOLDOWN_SCALE_SHIFT = 3; +constexpr int CROW_HEART_KEEP_2 = 25; +constexpr int CROW_HEART_KEEP_3 = 50; +constexpr float DAMAGE_ROUNDING = 0.5f; +constexpr float HALVED_DAMAGE = 0.5f; +constexpr float HALVED_DAMAGE_DEATHMATCH = 0.75f; +constexpr float DOUBLED_DAMAGE_DEATHMATCH = 1.25f; +constexpr float VOICE_PITCH_PLAYER = 1; +constexpr float VOICE_PITCH_BABY = 1.5f; +constexpr float VOICE_PITCH_PER_PILL = 0.1f; +constexpr float VOICE_PITCH_PLUTO = 0.5f; +constexpr float VOICE_PITCH_STEP = 0.2f; +constexpr float VOICE_PITCH_MIN = 0.5f; +constexpr float VOICE_PITCH_MAX = 2; +constexpr float REMOTE_VOLUME_SCALE = 0.1f; +constexpr int PILL_EFFECT_PUBERTY = 33; +constexpr int PILL_EFFECT_HELIUM = 32; + +// The extra lives the HUD counts: 1up!, Ankh, Guppy's Collar, Judas' Shadow, Lazarus' Rags and Inner Child. +constexpr int EXTRA_LIFE_ITEMS[] = {11, 161, 212, 311, 332, 688}; +constexpr int TAINTED_LOST_BIRTHRIGHT = 619; + +// The hazards Evil Charm protects from: fires, creep, and the effects that hurt on contact. +constexpr int EVIL_CHARM_EFFECTS[] = {22, 23, 24, 25, 26, 32, 37, 44, 45, 46, 53, 54, 56, 78, 90, 94, 141, 147, 155, 169, 204}; +constexpr int EVIL_CHARM_GRID_VARIANT = 10000; + +// The temporary effects that make the player invincible to any hit: Gamekid, My Little Unicorn, Unicorn Stump and +// Teleport. +constexpr int INVINCIBLE_EFFECTS[] = {93, 77, 298, 44}; +constexpr int COLLECTIBLE_BREATH_OF_LIFE = 326; +constexpr int COLLECTIBLE_DARK_ARTS = 705; +constexpr int COLLECTIBLE_GNAWED_LEAF = 210; +constexpr int NULLITEM_INVINCIBLE_SHIELD = 59; +constexpr int BLOOD_DONATION_VARIANT = 2; +constexpr int BLOOD_BANK_VARIANT = 5; +constexpr float GNAWED_LEAF_MASS = 1000; +constexpr int BREATH_OF_LIFE_WINDOW = 5; + +// Whether a hit passes the player by: its own self damage, friendly sources, another's Dark Esau, a dead player, +// Isaac's Heart, Evil Charm's hazards, and a co-op baby still appearing. +static bool is_damage_ignored(Entity_Player& player, const EntityRef& source, uint64_t damageFlags) +{ + Game& game = *g_game; + Entity* entity = source.entity; + + if (source.type == ENTITY_EFFECT && source.variant == EFFECT_SELF_DAMAGE && source.spawnerType == ENTITY_PLAYER) + return true; + if (source.IsFriendly() && !game.deathmatchManager.is_active()) return true; + if (source.IsFriendly()) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (friendly fire in versus)"); + if (damageFlags & DAMAGE_IGNORED) return true; + + Entity* darkEsau = player.darkEsau.get(); + bool isOtherEsau = entity && entity->type == ENTITY_DARK_ESAU && entity != darkEsau && + (entity->parent.get() != darkEsau || !darkEsau) && (entity->child.get() != darkEsau || !darkEsau) && + entity->spawnerEntity.get() != &player && entity->spawnerEntity.get() != darkEsau; + if (isOtherEsau || player.isDead) return true; + + Entity_Player* heartOwner = player.playerType == PLAYER_THESOUL_B && player.twin_get() ? player.twin_get() : &player; + bool isHeartProtected = heartOwner->HasCollectible(COLLECTIBLE_ISAACS_HEART) || player.playerType == PLAYER_THEFORGOTTEN_B; + if (isHeartProtected && !(damageFlags & DAMAGE_ISAACS_HEART_PIERCE)) return true; + if (player.is_evil_charm_immune(source)) return true; + + bool isAppearing = player.sprite.IsPlaying("Appear") || player.sprite.IsPlaying("Glitch"); + if ((player.variant == PLAYER_VARIANT_COOP_BABY || player.isCoopGhost) && isAppearing) return true; + if (source.type == ENTITY_SEGMENTED_WORM && source.variant == SEGMENTED_WORM_VARIANT && entity) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a worm segment of the player's own)"); + return false; +} + +// Whether a Bishop the player charmed stands in the room to take the hit (find_nearest_enemy 004e7d10). +static bool is_bishop_present() +{ + return std::ranges::any_of(g_game->room->entityList.updateEL, [](Entity* entity) + { return entity->type == ENTITY_BISHOP && entity->HasEntityFlags(FLAG_CHARM); }); +} + +// Whether a wisp of the player's could take the hit (FUN_007c7b10). +static bool is_wisp_shield_present(Entity_Player& player) +{ + return std::ranges::any_of(g_game->room->entityList.updateEL, [&](Entity* entity) + { + return !entity->isDead && entity->IsFamiliar() && entity->variant == FAMILIAR_WISP && + entity->subtype == COLLECTIBLE_DULL_RAZOR && + static_cast(entity)->player == &player; + }); +} + +// The items that answer a hit before it lands, each stopping or turning it, none written yet. +static void damage_reactions_check(Entity_Player& player, uint64_t damageFlags) +{ + bool isExplosion = damageFlags & DAMAGE_EXPLOSION; + bool isFire = damageFlags & DAMAGE_FIRE; + + if (is_bishop_present()) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a charmed Bishop's shield)"); + if (player.HasTrinket(TRINKET_WALNUT) && isExplosion) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Walnut)"); + if (player.HasCollectible(COLLECTIBLE_PYROMANIAC) && (isFire || isExplosion)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Pyromaniac)"); + if (player.HasCollectible(COLLECTIBLE_HOST_HAT)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Host Hat)"); + bool isFetus = player.HasWeaponType(WEAPON_BOMBS) || player.HasWeaponType(WEAPON_BONE); + if (isFetus && player.HasCollectible(COLLECTIBLE_IPECAC) && isExplosion) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Ipecac with Dr. Fetus)"); + if (player.HasCollectible(COLLECTIBLE_HOT_BOMBS) && isFire) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Hot Bombs)"); + if (player.variant == PLAYER_VARIANT_COOP_BABY && player.babySkin == BABY_BOMB && isExplosion) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the bomb baby)"); + if (player.HasCollectible(COLLECTIBLE_JELLY_BELLY) && !(damageFlags & (DAMAGE_NO_MODIFIERS | DAMAGE_FAKE))) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Jelly Belly)"); + if (player.HasCollectible(COLLECTIBLE_METAL_PLATE) || player.HasCollectible(COLLECTIBLE_CONE_HEAD)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Metal Plate and Cone Head)"); +} + +// Whether a list of ids has one. +template static bool is_listed(const int (&ids)[N], int id) +{ + return std::ranges::find(ids, id) != std::end(ids); +} + +// A random number below max, or 0 for none (Isaac::Random 0067f010). +static int random_below(int max) +{ + return max == 0 ? 0 : (int)(Random() % (uint32_t)max); +} + +// 007db330 A damage cooldown in frames, scaled down in versus. +static int damage_cooldown_scale(int frames) +{ + if (!g_game->deathmatchManager.is_active()) return frames; + return frames > COOLDOWN_SCALE_MIN - 1 ? frames >> COOLDOWN_SCALE_SHIFT : 1; +} + +// The bestiary count an enemy adds to, unless the save is frozen or the enemy has no page. +static void bestiary_count_add(std::map& counts, int type, int variant) +{ + PersistentGameData& data = g_manager->persistentGameData; + EntityConfig_Entity* entity = data.isReadOnly ? nullptr : g_manager->entityConfig.GetBestiaryConfig(type, variant); + if (entity && entity->isBestiary) counts[entity->id << 20 | entity->variant << 8]++; +} + +// Plays one of the player's sounds at a volume and pitch, unless the seeds swap it for a fart. +static void voice_play(int sound, float volume, int frameDelay, float pitch) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = volume, .frameDelay = frameDelay, .pitch = pitch}); +} + +// The damage a hit deals in half hearts: rounded, two from the Womb on or on a victory lap, halved by the Wafer and +// its likes, doubled by the double damage effect, and set by the seeds that hurt more. +static int damage_amount_get(Entity_Player& player, float damage, uint64_t damageFlags, const EntityRef& source) +{ + Game& game = *g_game; + bool isDeathmatch = game.deathmatchManager.is_active(); + int amount = (int)(damage + DAMAGE_ROUNDING); + + if (isDeathmatch && amount == 0 && damage > 0) amount = 1; + if (damageFlags & DAMAGE_NO_MODIFIERS) return amount; + + if (!game.IsGreedMode() && (game.stage >= STAGE_FULL_HEART_DAMAGE || game.victoryLap >= 1 || game.IsAscent())) + amount = std::max(amount, 2); + + bool isHardMode = game.difficulty == DIFFICULTY_HARD || game.difficulty == DIFFICULTY_GREEDIER; + bool isHalved = player.HasCollectible(COLLECTIBLE_WAFER) || + player.temporaryEffects.HasCollectibleEffect(COLLECTIBLE_WAFER) || + player.GetTrinketMultiplier(TRINKET_CALLUS) > 2 || (source.flags & ENTITY_REF_WEAKNESS) || + (player.HasCollectible(COLLECTIBLE_DOGMA) && !isHardMode); + if (isHalved && amount > 1) + amount = std::max((int)((float)amount * (isDeathmatch ? HALVED_DAMAGE_DEATHMATCH : HALVED_DAMAGE) + DAMAGE_ROUNDING), 1); + if (player.temporaryEffects.HasNullEffect(NULLITEM_DOUBLE_DAMAGE)) + amount = (int)((float)std::max(amount, 2) * (isDeathmatch ? DOUBLED_DAMAGE_DEATHMATCH : 1)); + if (player.GetHealthType() == HEALTH_COIN) amount = 2; + if (game.seedEffects.HasSeedEffect(SEED_ISAAC_TAKES_HIGH_DAMAGE)) amount = std::max(amount, 2); + if (game.seedEffects.HasSeedEffect(SEED_ISAAC_TAKES_MASSIVE_DAMAGE)) amount = std::max(amount, MASSIVE_DAMAGE); + return amount; +} + +// Takes a hit's half hearts from soul hearts first, then red ones, marking the floor as hurt for the red heart deals. +// Bone hearts, Crow Heart and red heart hits are not written yet. +static void hearts_remove(Entity_Player& player, int amount, uint64_t damageFlags, bool isPenalized) +{ + if (player.boneHearts > 0) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (bone hearts)"); + if ((damageFlags & DAMAGE_RED_HEARTS) || player.HasTrinket(TRINKET_CROW_HEART)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (hits that take red hearts first)"); + + int soulBoneCount = (player.soulHearts + 1) / 2 + player.boneHearts; + int filledCount = (std::min(player.redHearts, player.maxHearts) + 1) / 2; + + if (player.soulHearts > 0) + { + amount = std::min(amount, player.soulHearts); + for (int heart = player.soulHearts; heart > player.soulHearts - amount; heart--) + if (player.IsBlackHeart(heart)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (black hearts)"); + if (player.eternalHearts > 0 && player.redHearts < 1 && player.boneHearts < 1 && player.soulHearts - amount < 1) + { + amount = std::max(amount - player.eternalHearts, 0); + player.eternalHearts = 0; + } + if (amount > 0) player.soulHearts -= std::min(player.soulHearts, amount); + } + else + { + if (player.rottenHearts > 0 && player.eternalHearts < 1) amount += std::min(player.rottenHearts, amount); + if (player.eternalHearts > 0) + { + amount = std::max(amount - player.eternalHearts, 0); + player.eternalHearts = 0; + } + + bool isRedLost = amount > player.rottenHearts * 2; + player.rottenHearts = std::max(player.rottenHearts - (amount + 1) / 2, 0); + player.AddHearts(-amount, false, false); + + bool isKeeper = player.playerType == PLAYER_KEEPER || player.playerType == PLAYER_KEEPER_B; + if (player.playerType == PLAYER_MAGDALENE_B) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Tainted Magdalene's red heart damage)"); + if (isRedLost && !isKeeper && !player.parent && isPenalized && amount > 0 && player.redHearts < player.maxHearts) + { + int multiplier = player.GetTrinketMultiplier(TRINKET_CROW_HEART); + uint32_t keptChance = multiplier == 2 ? CROW_HEART_KEEP_2 : multiplier >= 3 ? CROW_HEART_KEEP_3 : 0; + if (player.GetTrinketRNG(TRINKET_CROW_HEART).RandomInt(100) >= keptChance) + { + g_game->SetRedHeartDamage(); + g_game->room->isRedHeartDamaged = true; + } + } + } + + player.update_greeds_gullet(); + int golden = player.goldenHearts; + int newSoulBoneCount = (player.soulHearts + 1) / 2 + player.boneHearts; + int newFilledCount = (std::min(player.redHearts, player.maxHearts) + 1) / 2; + for (; soulBoneCount > newSoulBoneCount && player.goldenHearts > 0; soulBoneCount--) player.goldenHearts--; + for (; filledCount > newFilledCount && player.goldenHearts > 0; filledCount--) player.goldenHearts--; + if (player.goldenHearts < golden) player.BreakGoldenHearts(golden - player.goldenHearts); +} + +// The items a landed hit sets off, none written yet, then Tainted Samson's rage. Bleeding out restarts its timer. +static void hit_items_check(Entity_Player& player, uint64_t damageFlags, bool isPenalized) +{ + bool isItemHit = std::ranges::any_of(HIT_COLLECTIBLES, [&](int item) { return player.HasCollectible(item); }) || + std::ranges::any_of(HIT_TRINKETS, [&](int trinket) { return player.HasTrinket(trinket); }) || + (isPenalized && player.HasTrinket(TRINKET_PERFECTION)) || player.HasPlayerForm(PLAYER_FORM_BEELZEBUB) || + (player.HasCollectible(CROWN_OF_LIGHT) && !g_game->deathmatchManager.is_active()) || + (player.HasCollectible(COLLECTIBLE_HYPERCOAGULATION) && !(damageFlags & HYPERCOAGULATION_IGNORED)) || + std::ranges::any_of(player.activeItems, [](const ActiveItemDesc& active) { return active.item == COLLECTIBLE_LARYNX; }); + if (isItemHit) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the items and trinkets a hit sets off)"); + if (player.playerType == PLAYER_SAMSON_B && (player.redHearts > 0 || player.soulHearts > 0 || player.boneHearts > 0)) + player.add_samson_berserk_charge(SAMSON_B_HIT_CHARGE); + + if (player.HasEntityFlags(FLAG_BLEED_OUT) && player.bleedSource.entity == &player && player.bleedOutHealth > 0) + player.bleedOutHealth = BLEED_OUT_HEALTH; + if (!player.proceduralItems.empty()) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (glitched items, trigger_set_dispatch)"); +} + +// 007729d0 The player takes a hit: the hit is ignored or turned by many items, then costs its hearts, plays the hurt +// grunt and the Hit animation, starts the invincibility frames, and kills the player out of hearts. True when it hurt. +bool Entity_Player::TakeDamage(float damage, uint64_t damageFlags, const EntityRef& source, int damageCountdown) +{ + Game& game = *g_game; + Entity_Player* twin = twin_get(); + + if (playerType == PLAYER_THESOUL_B && twin && !twin->HasCollectible(COLLECTIBLE_ISAACS_HEART)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the Forgotten's soul passing the hit on)"); + if (source.entity && (source.type == ENTITY_DAMAGE_RELAY || source.type == ENTITY_FAMILIAR)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a familiar or relay source)"); + if (is_wisp_shield_present(*this)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (wisp shields)"); + if (source.type == ENTITY_FIREPLACE && source.variant == WHITE_FIRE_VARIANT) + { + bool isGhost = playerType == PLAYER_THELOST || playerType == PLAYER_THELOST_B || playerType == PLAYER_THESOUL_B; + if (isGhost || HasInstantDeathCurse() || isDead) return false; + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (white fire's lost curse)"); + } + if (IsHologram() || is_damage_ignored(*this, source, damageFlags)) return false; + damage_reactions_check(*this, damageFlags); + + if (!(damageFlags & DAMAGE_NO_HURT_EFFECTS)) play_hurt_effects(); + bool isSeedProtected = game.seedEffects.HasSeedEffect(SEED_INVINCIBLE) || + (variant == PLAYER_VARIANT_COOP_BABY && game.seedEffects.HasSeedEffect(SEED_KIDS_MODE)) || + (game.deathmatchManager.is_active() && isInvincible); + if (isSeedProtected) + { + damageCooldown = std::min((int)(damage + DAMAGE_ROUNDING), HURT_HEARTS_MAX) * HURT_FRAMES_PER_HEART; + return false; + } + bool isPoisonImmune = HasPoisonImmunity() && !(source.type == ENTITY_EFFECT && source.variant == EFFECT_POISON_CLOUD); + if (damage <= 0 && (damageFlags & DAMAGE_POISON_BURN) && !isPoisonImmune) + { + damageEvents.push_back({.source = source, .damage = damage, .damageFlags = damageFlags}); + pendingDamageFlags |= damageFlags; + pendingDamage += damage; + } + + int hurtFrames = (int)(damage + DAMAGE_ROUNDING); + int amount = damage_amount_get(*this, damage, damageFlags, source); + bool isFake = damageFlags & DAMAGE_FAKE; + if (isFake) amount = 0; + if (damageFlags & DAMAGE_SPAWN_FLY) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a fly for the hit)"); + + bool isInvincibleNow = HasInvincibility(damageFlags, source); + bool isPenalized = !(damageFlags & DAMAGE_UNPENALIZED); + if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_SHIELD && hasBabyRoomShield) + { + isInvincibleNow = true; + hasBabyRoomShield = false; + } + bool isBlocked = (damageCooldown > 0 && !(damageFlags & DAMAGE_THROUGH_COOLDOWN)) || damage <= 0 || isInvincibleNow; + if (isBlocked && !isFake) return false; + + if (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_HOLY_MANTLE) && !(damageFlags & DAMAGE_RED_HEARTS)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Holy Mantle's shield)"); + if (hallowedGroundCountdown > 0 && !(damageFlags & DAMAGE_NO_MODIFIERS)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Hallowed Ground)"); + if (static_cast(g_luaEngine)->enabledCallbacks.test(MC_ENTITY_TAKE_DMG)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (LuaEngine::EntityTakeDamage 00864560)"); + (void)damageCountdown; + if (try_end_astral_projection()) return false; + if (playerType == PLAYER_JACOB_B && source.type == ENTITY_DARK_ESAU) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Tainted Jacob's ghost form)"); + + // The online stats tally (Player_stats_add 00425ac0) is not written yet: only the online stats screen shows it. + lastDamageSource = source; + lastDamageFlags = damageFlags; + isHurtThisRoom = true; + maggyHealthDrainCooldown = 0; + damageCooldown = HIT_COOLDOWN; + float volume = local_volume_get(); + if (isPenalized) + { + roomDamageTaken += amount; + if (playerType == PLAYER_MAGDALENE_B) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Tainted Magdalene's damage taken)"); + totalDamageTaken += amount; + } + if (source.type >= ENEMY_TYPE_FIRST && source.type <= ENEMY_TYPE_LAST) + bestiary_count_add(g_manager->persistentGameData.bestiary.hits, source.type, source.variant); + if (game.debugFlags & DEBUG_DAMAGE_VALUES) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (spawn_debug_damage_text)"); + if ((damageFlags & (DAMAGE_FIRE | DAMAGE_POOP)) && !(damageFlags & DAMAGE_EXPLOSION)) + voice_play(SOUND_FIREDEATH_HISS, 1, SOUND_FRAME_DELAY, 1); + + bool isThief = is_listed(COIN_THIEF_TYPES, source.type) || source.spawnerType == ULTRA_GREED || + source.spawnerType == ULTRA_GREED_DOOR || + (source.type == ENTITY_PROJECTILE && is_listed(COIN_SHOOTER_TYPES, source.spawnerType)); + if ((isThief || game.challenge == CHALLENGE_PAY_TO_PLAY) && numCoins > 0) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (dropping coins to Greed)"); + if (variant == PLAYER_VARIANT_COOP_BABY && (babySkin == BABY_FART || babySkin == BABY_BOMB || babySkin == BABY_BOOK)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the co-op babies that answer hits)"); + if (HasCollectible(COLLECTIBLE_MARBLES) && (trinkets[0] != 0 || queuedItem.item)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Marbles)"); + + float pitch = get_voice_pitch(); + int grunt = SOUND_ISAAC_HURT_GRUNT; + if (temporaryEffects.HasCollectibleEffect(COLLECTIBLE_THE_NAIL)) grunt = random_below(2) ? SOUND_NAIL_HURT_1 : SOUND_NAIL_HURT_2; + voice_play(grunt, volume, SOUND_FRAME_DELAY, pitch); + if (source.type == ENTITY_MOM || source.type == ENTITY_MOMS_HEART) + voice_play(source.type == ENTITY_MOM ? SOUND_MOM_VOX : SOUND_HEARTBEAT, 1, + random_below(SOUND_BOSS_DELAY_RANDOM) + SOUND_BOSS_DELAY_MIN, 1); + + hit_items_check(*this, damageFlags, isPenalized); + for (size_t i = 0; i < game.room->entityList.updateEL.size(); i++) + { + Entity* entity = game.room->entityList.updateEL[i]; + if (entity->IsFamiliar() && static_cast(entity)->player == this) + reconstruction_missing("Entity_Familiar::trigger_player_damage 0062b750"); + else if (!entity->IsFamiliar() && entity->IsEnemy()) + static_cast(entity)->on_player_damaged(); + } + if (isPenalized && !parent) + { + game.SetStateFlag(LEVEL_STATE_DAMAGED, true); + game.lastLevelWithDamage = std::clamp((int)game.stage, 0, LAST_DAMAGE_STAGE_MAX); + } + + if (game.debugFlags & DEBUG_INFINITE_HP) amount = 0; + else if (amount > 0 && game.deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (versus hearts)"); + else if (amount > 0) hearts_remove(*this, amount, damageFlags, isPenalized); + + bool isAstral = HasCollectible(COLLECTIBLE_ASTRAL_PROJECTION) && !game.room->IsClear() && + !temporaryEffects.HasCollectibleEffect(COLLECTIBLE_ASTRAL_PROJECTION) && !astralProjectionBody; + bool isInstantDeath = HasInstantDeathCurse() && amount > 0; + bool isDeathSkipped = isAstral || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BERSERK); + bool isHurt = true; + + if ((redHearts < 1 && soulHearts < 1 && boneHearts < 1) || isInstantDeath) + { + if (HasCollectible(COLLECTIBLE_HEARTBREAK)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Heartbreak)"); + if (damageFlags & DAMAGE_NOKILL) TryPreventDeath(); + else + { + if (isInstantDeath) + { + redHearts = 0; + soulHearts = 0; + blackHearts = 0; + boneHearts = 0; + eternalHearts = 0; + rottenHearts = 0; + } + if (!isDeathSkipped) + { + if (isInstantDeath) Kill(EntityRef()); + bool isKilled = try_trigger_astral_projection(); + lastDamageSource = source; + if (isKilled && game.deathmatchManager.is_active()) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (a versus kill, trigger_npc_death)"); + if (isDead) death_count(source, damageFlags); + } + } + } + if (!isDead && HasCollectible(COLLECTIBLE_CURSED_EYE) && !HasCollectible(COLLECTIBLE_BLACK_CANDLE) && weapons[1]) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Cursed Eye's teleport)"); + + bool isHitAnimated = pitfallState == 0 && isHurt; + if (HasTrinket(TRINKET_CURSED_SKULL) && !isDead) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Cursed Skull)"); + if (redHearts <= scale_for_hard_difficulty(1)) + { + if (HasCollectible(COLLECTIBLE_POLAROID) || HasCollectible(COLLECTIBLE_NEGATIVE)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the Polaroid and the Negative)"); + bool isLastHeart = soulHearts < 1 || (redHearts < 1 && soulHearts == scale_for_hard_difficulty(1)); + if (isLastHeart && (HasCollectible(COLLECTIBLE_SCAPULAR) || (HasTrinket(TRINKET_MONKEY_PAW) && variant == PLAYER_VARIANT_PLAYER))) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Scapular and Monkey Paw)"); + } + + damageCooldown = damage_cooldown_scale(std::min(hurtFrames, HURT_HEARTS_MAX) * HURT_FRAMES_PER_HEART); + flags &= ~FLAG_NO_DAMAGE_BLINK; + if (isAstral) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Astral Projection)"); + if (HasTrinket(TRINKET_BLIND_RAGE) || HasTrinket(TRINKET_FINGER_BONE)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Blind Rage and Finger Bone)"); + if (isPenalized && HasCollectible(COLLECTIBLE_GLASS_CANNON)) reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Glass Cannon)"); + + if (isHitAnimated) + { + if (twin && twin->playerType == PLAYER_THESOUL_B) twin->PlayExtraAnimation("Hit"); + else if (game.challenge != CHALLENGE_GUARDIAN) PlayExtraAnimation("Hit"); + if (itemState != ITEM_STATE_HOLD_STILL) ResetItemState(); + } + isHurtPending = true; + // Rumble is not wired to the controllers here. + + ClampGoldenHearts(false); + update_bone_hearts(); + if (damageCooldown > 0 && !isDead && twin && twin->damageCooldown < damageCooldown && !twin->isDead) + twin->damageCooldown = damageCooldown; + if (HasTrinket(TRINKET_SWALLOWED_M80) && !(damageFlags & DAMAGE_NO_PENALTIES)) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Swallowed M80)"); + bool isGlitching = isPlayingExtraAnimation && sprite.IsPlaying("Glitch"); + if (!isDead && playerType == PLAYER_EDEN_B && isPenalized && !isGlitching) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (Tainted Eden's reroll)"); + return true; +} + +// Counts the player's death in the bestiary of the enemy behind the hit. Dying to one's own Ipecac unlocks an +// achievement that is not written yet. +void Entity_Player::death_count(const EntityRef& source, uint64_t damageFlags) +{ + PersistentGameData_Bestiary& bestiary = g_manager->persistentGameData.bestiary; + + if (source.type >= ENEMY_TYPE_FIRST && source.type <= ENEMY_TYPE_LAST) + bestiary_count_add(bestiary.deaths, source.type, source.variant); + else if (source.spawnerType >= ENEMY_TYPE_FIRST && source.spawnerType <= ENEMY_TYPE_LAST) + bestiary_count_add(bestiary.deaths, source.spawnerType, (int)source.spawnerVariant); + if ((damageFlags & DAMAGE_EXPLOSION) && source.type == ENTITY_TEAR && source.entity) + reconstruction_missing("Entity_Player::TakeDamage 007729d0 (the achievement for dying to Ipecac)"); +} + +// 007db6b0 Whether a hit kills at once: the Lost's curse, or Tainted Jacob's ghost. +bool Entity_Player::HasInstantDeathCurse() +{ + return (!temporaryEffects.isDisabled && + std::ranges::any_of(temporaryEffects.effects, [](const TemporaryEffect& effect) + { return effect.item->type == ITEM_NULL && effect.item->id == NULLITEM_LOST_CURSE; })) || + playerType == PLAYER_JACOB2_B; +} + +// 007bf670 The lives the HUD counts: Dead Cat's and the items that revive, Lazarus's own and Tainted Lost's Birthright. +int Entity_Player::GetExtraLives() +{ + int lives = deadCatLives; + + for (int item : EXTRA_LIFE_ITEMS) lives += collectibleCounts[item]; + if (playerType == PLAYER_THELOST_B) lives += collectibleCounts[TAINTED_LOST_BIRTHRIGHT]; + return lives + (playerType == PLAYER_LAZARUS); +} + +// 0075d900 Whether an item's costume shows on a layer of the player's sprite, or on any layer for a negative one. +bool Entity_Player::IsItemCostumeVisible(ItemConfig_Item* item, int playerSpriteLayerID) +{ + int first = std::max(playerSpriteLayerID, 0); + int end = playerSpriteLayerID < 0 ? COSTUME_LAYER_COUNT : playerSpriteLayerID + 1; + + for (int layer = first; layer < end; layer++) + if (playerCostumeMap[layer].index >= 0 && costumeSpriteDescs[playerCostumeMap[layer].index].item == item) + return true; + return false; +} + +// 0075d980 Whether a null item's costume shows on a layer, as IsItemCostumeVisible for an id out of range asks of none. +bool Entity_Player::IsNullItemCostumeVisible(int nullItemID, int playerSpriteLayerID) +{ + std::vector>& nullItems = g_manager->itemConfig.nullItems; + bool isKnown = nullItemID >= 0 && nullItemID < (int)nullItems.size(); + return IsItemCostumeVisible(isKnown ? nullItems[nullItemID].get() : nullptr, playerSpriteLayerID); +} + +// 007c3100 Whether a hit passes the player by: the invincibility items' effects, Gnawed Leaf's statue, Breath of Life, +// Taurus's charge, the shields red heart hits still pass, the halo baby and a co-op ghost. Book of Shadows lets a blood +// donation hurt. +bool Entity_Player::HasInvincibility(uint64_t damageFlags, const EntityRef& source) +{ + if (damageFlags & DAMAGE_INVINCIBLE_IGNORED) return false; + + TemporaryEffects& effects = temporaryEffects; + bool isRedHit = damageFlags & DAMAGE_RED_HEARTS; + bool isInvincible = effects.HasCollectibleEffect(COLLECTIBLE_BOOK_OF_SHADOWS); + if (isInvincible) + { + bool isBloodSlot = source.type == ENTITY_SLOT && (source.variant == BLOOD_DONATION_VARIANT || source.variant == BLOOD_BANK_VARIANT); + if (isBloodSlot && effects.GetCollectibleEffect(COLLECTIBLE_BOOK_OF_SHADOWS)->unknown != 0) isInvincible = false; + } + if (!isInvincible) + { + TemporaryEffect* taurus = effects.HasCollectibleEffect(COLLECTIBLE_TAURUS) ? effects.GetCollectibleEffect(COLLECTIBLE_TAURUS) : nullptr; + isInvincible = std::ranges::any_of(INVINCIBLE_EFFECTS, [&](int item) { return effects.HasCollectibleEffect(item); }) || + (HasCollectible(COLLECTIBLE_GNAWED_LEAF) && mass == GNAWED_LEAF_MASS && !isRedHit) || + effects.HasCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE) || (taurus && taurus->cooldown != 0) || + (effects.HasNullEffect(NULLITEM_INVINCIBLE_SHIELD) && !isRedHit) || + (effects.HasNullEffect(NULLITEM_REVERSE_CHARIOT) && !isRedHit) || + ((effects.HasCollectibleEffect(COLLECTIBLE_DARK_ARTS) || isDarkArtsBlastPending) && !isRedHit) || + (suplexState != 0 && !isRedHit) || effects.HasCollectibleEffect(COLLECTIBLE_MEGA_MUSH); + } + return isInvincible || (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_HALO) || isCoopGhost; +} + +// 007c3320 Whether poison passes the player by: Jupiter, Bob's Curse and the Bob transformation. +bool Entity_Player::HasPoisonImmunity() +{ + return HasCollectible(COLLECTIBLE_JUPITER) || HasCollectible(COLLECTIBLE_BOBS_CURSE) || HasPlayerForm(PLAYER_FORM_BOB); +} + +// 007dba30 Whether Evil Charm keeps a hazard off the player: fireplaces always, creep and the like only for their +// first frames on it. +bool Entity_Player::is_evil_charm_immune(EntityRef source) +{ + if (!HasCollectible(COLLECTIBLE_EVIL_CHARM) && !temporaryEffects.HasCollectibleEffect(COLLECTIBLE_EVIL_CHARM)) return false; + if (source.type == ENTITY_FIREPLACE) return true; + + bool isHazard = (source.type == 0 && source.variant == EVIL_CHARM_GRID_VARIANT) || + (source.type == ENTITY_PROJECTILE && source.variant == 2) || + (source.type == ENTITY_EFFECT && is_listed(EVIL_CHARM_EFFECTS, source.variant)); + if (!isInEvilCharmHazard && !isHazard) + { + isInEvilCharmHazard = false; + return false; + } + isInEvilCharmHazard = true; + return isHazard && evilCharmHazardFrames < EVIL_CHARM_GRACE_FRAMES; +} + +// 007c9ad0 The pitch of the player's voice: higher for babies, Pluto, Inner Child, Binky and Helium pills, lower +// for Puberty pills and the Adult transformation. +float Entity_Player::get_voice_pitch() +{ + float pitch = variant == PLAYER_VARIANT_PLAYER ? VOICE_PITCH_PLAYER : VOICE_PITCH_BABY; + + pitch += (float)(pillEffectUses[PILL_EFFECT_PUBERTY] - pillEffectUses[PILL_EFFECT_HELIUM]) * VOICE_PITCH_PER_PILL; + if (HasCollectible(COLLECTIBLE_PLUTO) || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_INNER_CHILD)) + pitch += VOICE_PITCH_PLUTO; + if (HasCollectible(COLLECTIBLE_BINKY)) pitch += VOICE_PITCH_STEP; + if (HasPlayerForm(PLAYER_FORM_ADULT)) pitch -= VOICE_PITCH_STEP; + return std::clamp(pitch, VOICE_PITCH_MIN, VOICE_PITCH_MAX); +} + +// 007cf8c0 Whether the player plays on this machine: every one does offline. +bool Entity_Player::IsLocalPlayer() +{ + return !g_manager->netplayManager.is_online() || g_manager->netplayManager.IsIdxLocalPlayer(controllerIndex); +} + +// 007cf8f0 The volume of the player's sounds: full for a local player, the remote players' option for others. +float Entity_Player::local_volume_get() +{ + if (IsLocalPlayer()) return 1; + return (float)g_manager->optionsConfig.onlinePlayerVolume * REMOTE_VOLUME_SCALE; +} + +// 007d1c10 Breath of Life's holy light when the player is hit as it runs out, not written yet. True when it shines. +uint32_t Entity_Player::play_hurt_effects() +{ + TemporaryEffect* effect = temporaryEffects.GetCollectibleEffect(COLLECTIBLE_BREATH_OF_LIFE); + bool isBlocked = damageCooldown > 0 && !HasEntityFlags(FLAG_NO_DAMAGE_BLINK); + if (isBlocked || !effect || effect->count != 2) return 0; + if (effect->cooldown < g_manager->itemConfig.GetCollectible(COLLECTIBLE_BREATH_OF_LIFE)->maxCooldown - BREATH_OF_LIFE_WINDOW) + return 0; + reconstruction_missing("Entity_Player::play_hurt_effects 007d1c10 (Breath of Life)"); +} + +// 007caaa0 Whether a heart container is a bone heart. +bool Entity_Player::IsBoneHeart(int heart) +{ + return boneHearts > 0 && (boneHeartsMask & 1 << heart); +} + +// 00759220 Whether a soul heart, counted in halves from 1, is the first half of a black heart. +bool Entity_Player::IsBlackHeart(int heart) +{ + return heart <= soulHearts && heart >= 1 && (heart & 1) && (blackHearts & 1 << ((heart - 1) / 2)); +} + +// 007caad0 Leaves a player a last half heart of its kind when a hit was not to kill. True when it did. +bool Entity_Player::TryPreventDeath() +{ + if (boneHearts + redHearts + soulHearts != 0) return false; + + switch (GetHealthType()) + { + case HEALTH_DEFAULT: + if (playerType == PLAYER_BETHANY) + { + if (maxHearts < 2) AddMaxHearts(2, false); + AddHearts(1, true, false); + return true; + } + if (maxHearts <= 0) break; + AddHearts(scale_for_hard_difficulty(1), true, false); + return true; + case HEALTH_COIN: + if (maxHearts < 2) AddMaxHearts(2, false); + AddHearts(2, true, false); + return true; + case HEALTH_BONE: + AddBoneHearts(1); + return true; + default: + break; + } + soulHearts = 1; + return true; +} + +// 007afc20 Kills the player out of hearts and starts the death sequence, unless it is dead, a ghost, berserk or +// projected. Spirit Shackles' second chance is not written yet. True when it killed. +bool Entity_Player::try_trigger_astral_projection() +{ + bool isOutOfHearts = redHearts < 1 && soulHearts < 1 && boneHearts < 1; + if (g_game->deathmatchManager.is_active() && isOutOfHearts && blackHearts > 0) isOutOfHearts = false; + if (isDead || !isOutOfHearts || isCoopGhost) return false; + + TemporaryEffect* astral = temporaryEffects.isDisabled ? nullptr : temporaryEffects.GetCollectibleEffect(COLLECTIBLE_ASTRAL_PROJECTION); + int astralState = astral ? astral->count : 0; + if (astralState == 1 || temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BERSERK)) return false; + if (astralState != 2) + { + bool isShackled = HasCollectible(COLLECTIBLE_SPIRIT_SHACKLES) && + temporaryEffects.GetNullEffectNum(NULLITEM_SPIRIT_SHACKLES_DISABLED) == 0 && + temporaryEffects.GetNullEffectNum(NULLITEM_SHACKLES_GHOST) == 0; + if (isShackled) reconstruction_missing("Entity_Player::try_trigger_astral_projection 007afc20 (Spirit Shackles)"); + // The online stats tally of deaths to spikes (Player_stats_add 00425ac0) is not written yet. + lastDamageSource = EntityRef(); + } + Kill(EntityRef()); + return true; +} + +// 007d35b0 Ends Astral Projection's spirit form when the spirit is hit, not written yet. True when it ended. +bool Entity_Player::try_end_astral_projection() +{ + TemporaryEffect* astral = temporaryEffects.isDisabled ? nullptr : temporaryEffects.GetCollectibleEffect(COLLECTIBLE_ASTRAL_PROJECTION); + if (!astral || astral->count != 1) return false; + reconstruction_missing("Entity_Player::try_end_astral_projection 007d35b0"); +} + +// 007828f0 The animation the player dies with: the Lost's for ghosts and the cursed, Forgotten's, or falling in a hole. +const char* Entity_Player::GetDeathAnimName() +{ + bool isGhost = playerType == PLAYER_THELOST || playerType == PLAYER_THELOST_B || playerType == PLAYER_JACOB2_B || + playerType == PLAYER_THESOUL_B || playerType == PLAYER_THESOUL || + temporaryEffects.GetCollectibleEffectNum(COLLECTIBLE_ASTRAL_PROJECTION) == 1 || + temporaryEffects.GetNullEffectNum(NULLITEM_SHACKLES_GHOST) == 1 || + temporaryEffects.HasNullEffect(NULLITEM_LOST_CURSE) || + (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_GHOST) || isCoopGhost; + if (isGhost) return "LostDeath"; + if (playerType == PLAYER_THEFORGOTTEN_B) return "ForgottenDeath"; + return pitfallState == 0 ? "Death" : "HoleDeath"; +} + +// 007abe20 Plays an animation on the whole sprite, over the body and head, until it ends. +void Entity_Player::PlayExtraAnimation(std::string_view animName) +{ + isPlayingItemAnimation = false; + bodySprite.Reset(); + sprite.playbackSpeed = 1; + sprite.overlayAnimState.SetAnimationData(nullptr); + if (sprite.SetAnimation(animName)) + { + sprite.animState.Rewind(); + sprite.animState.isPlaying = true; + } + isPlayingItemAnimation = false; + isPlayingExtraAnimation = true; +} + +// 007abe90 Plays an animation of the player's sprite on its body sprite, as picking items up does. +void Entity_Player::PlayExtraAnimation(std::string_view animation, bool) +{ + bodySprite = sprite; + bodySprite.playbackSpeed = 1; + if (bodySprite.SetAnimation(animation)) + { + bodySprite.animState.Rewind(); + bodySprite.animState.isPlaying = true; + } + isPlayingExtraAnimation = false; + isPlayingItemAnimation = true; +} + +// 007c36b0 Puts away what the player holds up for an item: its costumes for the hold, and the item over its head. +void Entity_Player::ResetItemState() +{ + if (itemState == COLLECTIBLE_SHOOP_DA_WHOOP) + reconstruction_missing("Entity_Player::ResetItemState 007c36b0 (TryRemoveCollectibleCostume)"); + else if (itemState == COLLECTIBLE_BOOMERANG) + RemoveCostume(g_manager->itemConfig.GetNullItem(NULLITEM_BOOMERANG)); + if (variant == PLAYER_VARIANT_PLAYER && !isCoopGhost) + { + std::erase_if(costumeSpriteDescs, [](const CostumeSpriteDesc& desc) { return desc.isItemStateOnly; }); + UpdateCostumes(); + } + bool isHiding = bodySprite.animState.animData && bodySprite.animState.isPlaying && bodySprite.GetAnimation() == "HideItem"; + if ((isPlayingExtraAnimation || isPlayingItemAnimation) && !isHiding && itemState == COLLECTIBLE_MOMS_BRACELET) + PlayExtraAnimation("HideItem"); + itemState = 0; +} diff --git a/src/entity_player_frame.cpp b/src/entity_player_frame.cpp index 461423b..6ee23bb 100644 --- a/src/entity_player_frame.cpp +++ b/src/entity_player_frame.cpp @@ -22,6 +22,9 @@ constexpr float WALK_FASTEST_SPEED = 10; constexpr float WALK_SLOW_SPEED = 2.3f; constexpr int DAMAGE_BLINK_PERIOD = 6; constexpr int DAMAGE_BLINK_HIDDEN = 3; +constexpr int COLLECTIBLE_INTRUDER = 575; +constexpr int BABY_FOUND_SOUL = 59; +constexpr float DEATH_FRICTION = 0.6f; constexpr float EMOTE_HEIGHT = 52; constexpr float EMOTE_MOVING_SPEED = 0.1f; constexpr float GRAVITY_PULL = 0.225f; @@ -618,8 +621,16 @@ void Entity_Player::update_shooting() // item, pocket and drop actions stop the game until reached. void Entity_Player::Update() { - if (!is_evaluation_plain() || isPlayingExtraAnimation || isPlayingItemAnimation || heldEntity || queuedItem.item) - reconstruction_missing("Entity_Player::Update 00782af0 (items, effects and extra animations)"); + if (isPlayingExtraAnimation && sprite.IsFinished()) isPlayingExtraAnimation = false; + if (isHurtPending && !isPlayingExtraAnimation) + { + isHurtPending = false; + if (HasCollectible(COLLECTIBLE_INTRUDER) && !temporaryEffects.HasNullEffect(NULLITEM_INTRUDER)) + reconstruction_missing("Entity_Player::Update 00782af0 (the spiders a hurt sets loose)"); + } + if (isDead) return death_update(); + if (!is_evaluation_plain() || isPlayingItemAnimation || heldEntity || queuedItem.item) + reconstruction_missing("Entity_Player::Update 00782af0 (items, effects and item animations)"); for (ButtonAction action : {ACTION_BOMB, ACTION_ITEM, ACTION_PILL_CARD, ACTION_DROP}) if (isControlsEnabled && action_value(action, controllerIndex) > 0) reconstruction_missing("Entity_Player::Update 00782af0 (bombs, items, pockets and drop)"); @@ -628,6 +639,30 @@ void Entity_Player::Update() update_body_animations(); update_shooting(); walk_animation_update(); + if (damageCooldown > 0) damageCooldown--; +} + +// The death sequence part of 00782af0: the player plays its death animation once, stops, and slows to a halt. Whether +// it revives, and the save deletion of a run lost, are WillPlayerRevive's (not written yet). +void Entity_Player::death_update() +{ + std::string_view animation = GetDeathAnimName(); + + if (g_game->roomTransition.mode == TRANSITION_NONE && sprite.GetAnimation() != animation) + { + isVisible = true; + PlayExtraAnimation(animation); + if (GetTrinketMultiplier(TRINKET_MYSTERIOUS_PAPER) > 0) + reconstruction_missing("Entity_Player::Update 00782af0 (Mysterious Paper's revival chance)"); + if (heldEntity) ThrowHeldEntity(Vector{}); + if (LayerState* ghost = sprite.GetLayer("ghost")) ghost->isVisible = true; + if (!parent && variant == PLAYER_VARIANT_PLAYER && !isCoopGhost && !WillPlayerRevive()) + reconstruction_missing("Entity_Player::Update 00782af0 (the save deletion of a lost run)"); + if (variant == PLAYER_VARIANT_COOP_BABY && babySkin == BABY_FOUND_SOUL && parent && parent->is_player()) + parent->ToPlayer()->temporaryEffects.AddTrinketEffect(TRINKET_FOUND_SOUL, true, 1); + velocity = Vector{}; + } + friction *= DEATH_FRICTION; } // 0078ca00 Draws the player at its place, lifted by its flight and its offset: blinking while hurt, the held entity @@ -694,7 +729,17 @@ void Entity_Player::render_pass(const Vector& offset, RenderPass pass) if (const NullFrame* held = bodySprite.animState.GetNullFrameById(0); held && held->isVisible && playerType == PLAYER_LILITH_B) reconstruction_missing("Entity_Player::render_pass 0078b640 (Tainted Lilith's held item)"); - if (IsFullSpriteRendering()) reconstruction_missing("Entity_Player::render_pass 0078b640 (the whole sprite)"); + if (IsFullSpriteRendering()) + { + Vector heldOffset = posOffset; + posOffset = {}; + sprite.overlayAnimState.SetAnimationData(nullptr); + Entity::Render(offset); + if (pass == RENDER_PASS_MAIN && IsHoldingItem()) + reconstruction_missing("Entity_Player::render_pass 0078b640 (the held item over the whole sprite)"); + posOffset = heldOffset; + return; + } renderPosition = vector_add(render_position_get(pos, RENDER_SNAPPED), offset); bool isHeaded = !IsHeadless(); diff --git a/src/entity_player_missing.cpp b/src/entity_player_missing.cpp index 170fe09..54ba130 100644 --- a/src/entity_player_missing.cpp +++ b/src/entity_player_missing.cpp @@ -1,10 +1,6 @@ #include "entity_player.h" #include "log.h" -bool Entity_Player::TakeDamage(float, uint64_t, const EntityRef&, int) -{ - reconstruction_missing("Entity_Player::TakeDamage 007729d0"); -} bool Entity_Player::TryThrow(const EntityRef&, const Vector&, float) { reconstruction_missing("Entity_Player::TryThrow 007d2930"); @@ -107,7 +103,6 @@ void Entity_Player::trigger_max_hearts_removed(int) } void Entity_Player::AddEternalHearts(int) { reconstruction_missing("Entity_Player::AddEternalHearts 00758c20"); } void Entity_Player::RemoveBlackHeart(int) { reconstruction_missing("Entity_Player::RemoveBlackHeart 007591e0"); } -bool Entity_Player::IsBlackHeart(int) { reconstruction_missing("Entity_Player::IsBlackHeart 00759220"); } void Entity_Player::AddJarHearts(int) { reconstruction_missing("Entity_Player::AddJarHearts 00759390"); } void Entity_Player::AddGoldenKey() { reconstruction_missing("Entity_Player::AddGoldenKey 00759620"); } void Entity_Player::RemoveGoldenKey() { reconstruction_missing("Entity_Player::RemoveGoldenKey 00759660"); } @@ -129,10 +124,6 @@ Entity* Entity_Player::AddSwarmFlyOrbital(Vector) bool Entity_Player::TryUseKey() { reconstruction_missing("Entity_Player::TryUseKey 00759e20"); } void Entity_Player::AddCostume(ItemConfig_Item*, bool) { reconstruction_missing("Entity_Player::AddCostume 0075d1d0"); } void Entity_Player::AddNullCostume(int) { reconstruction_missing("Entity_Player::AddNullCostume 0075d800"); } -bool Entity_Player::IsNullItemCostumeVisible(int, int) -{ - reconstruction_missing("Entity_Player::IsNullItemCostumeVisible 0075d980"); -} void Entity_Player::ClearQueueItem() { reconstruction_missing("Entity_Player::ClearQueueItem 0075e190"); } bool Entity_Player::FlushQueueItem() { reconstruction_missing("Entity_Player::FlushQueueItem 0075e1d0"); } void Entity_Player::IncrementPlayerFormCounter(int, int) @@ -169,7 +160,6 @@ TearFlags Entity_Player::check_bomb_tearflags(const TearFlags&) reconstruction_missing("Entity_Player::check_bomb_tearflags 00780ec0"); } void Entity_Player::update_bomb_input() { reconstruction_missing("Entity_Player::update_bomb_input 00780f40"); } -const char* Entity_Player::GetDeathAnimName() { reconstruction_missing("Entity_Player::GetDeathAnimName 007828f0"); } uint32_t Entity_Player::CanTurnHead() { reconstruction_missing("Entity_Player::CanTurnHead 00782a60"); } void Entity_Player::RemoveCollectibleByHistoryIndex(int, bool) { @@ -216,9 +206,7 @@ void Entity_Player::DropPocketItem(int, Vector) { reconstruction_missing("Entity void Entity_Player::ShootCandle(Vector) { reconstruction_missing("Entity_Player::ShootCandle 007a6300"); } int Entity_Player::GetTrinket(uint32_t) { reconstruction_missing("Entity_Player::GetTrinket 007a6430"); } void Entity_Player::room_exit(bool) { reconstruction_missing("Entity_Player::room_exit 007a6680"); } -void Entity_Player::room_enter() { reconstruction_missing("Entity_Player::room_enter 007a6c50"); } void Entity_Player::TriggerRoomClear() { reconstruction_missing("Entity_Player::TriggerRoomClear 007a8fd0"); } -bool Entity_Player::HasPlayerForm(int) { reconstruction_missing("Entity_Player::HasPlayerForm 007aa7c0"); } bool Entity_Player::CanAddCollectible(int) { reconstruction_missing("Entity_Player::CanAddCollectible 007aa800"); } void Entity_Player::AnimatePickup(ANM2*, bool, std::string_view) { @@ -249,10 +237,6 @@ void Entity_Player::AnimateTeleport(bool) { reconstruction_missing("Entity_Playe void Entity_Player::AnimateHappy() { reconstruction_missing("Entity_Player::AnimateHappy 007abd30"); } void Entity_Player::AnimateSad() { reconstruction_missing("Entity_Player::AnimateSad 007abd90"); } void Entity_Player::AddPrettyFly() { reconstruction_missing("Entity_Player::AddPrettyFly 007abdf0"); } -void Entity_Player::PlayExtraAnimation(std::string_view) -{ - reconstruction_missing("Entity_Player::PlayExtraAnimation 007abe20"); -} void Entity_Player::active_used_post(int, bool, int) { reconstruction_missing("Entity_Player::active_used_post 007abf80"); @@ -290,10 +274,6 @@ void Entity_Player::RestoreGameState(GameStatePlayer*) { reconstruction_missing("Entity_Player::RestoreGameState 007ae4b0"); } -bool Entity_Player::try_trigger_astral_projection() -{ - reconstruction_missing("Entity_Player::try_trigger_astral_projection 007afc20"); -} void Entity_Player::spawn_dark_esau(void*) { reconstruction_missing("Entity_Player::spawn_dark_esau 007b0070"); } void Entity_Player::DonateLuck(int) { reconstruction_missing("Entity_Player::DonateLuck 007b2200"); } void Entity_Player::UseCard(int, uint32_t) { reconstruction_missing("Entity_Player::UseCard 007b2230"); } @@ -332,21 +312,14 @@ Entity_Familiar* Entity_Player::ThrowBlueSpider(Vector, Vector) reconstruction_missing("Entity_Player::ThrowBlueSpider 007bf640"); } void Entity_Player::RemoveBlueSpider() { reconstruction_missing("Entity_Player::RemoveBlueSpider 007bf660"); } -int Entity_Player::GetExtraLives() { reconstruction_missing("Entity_Player::GetExtraLives 007bf670"); } uint32_t Entity_Player::GetGlitchBabySubType() { reconstruction_missing("Entity_Player::GetGlitchBabySubType 007c2e90"); } -bool Entity_Player::HasInvincibility(uint64_t, const EntityRef&) -{ - reconstruction_missing("Entity_Player::HasInvincibility 007c3100"); -} -bool Entity_Player::HasPoisonImmunity() { reconstruction_missing("Entity_Player::HasPoisonImmunity 007c3320"); } bool Entity_Player::CanPickRedHearts() { reconstruction_missing("Entity_Player::CanPickRedHearts 007c3410"); } bool Entity_Player::CanPickSoulHearts() { reconstruction_missing("Entity_Player::CanPickSoulHearts 007c3460"); } bool Entity_Player::CanPickBlackHearts() { reconstruction_missing("Entity_Player::CanPickBlackHearts 007c3550"); } void Entity_Player::RemoveSkinCostume() { reconstruction_missing("Entity_Player::RemoveSkinCostume 007c3620"); } -void Entity_Player::ResetItemState() { reconstruction_missing("Entity_Player::ResetItemState 007c36b0"); } void Entity_Player::SetShootingCooldown(int) { reconstruction_missing("Entity_Player::SetShootingCooldown 007c37f0"); } bool Entity_Player::NeedsCharge(int) { reconstruction_missing("Entity_Player::NeedsCharge 007c3810"); } bool Entity_Player::FullCharge(int, bool, bool) { reconstruction_missing("Entity_Player::FullCharge 007c38c0"); } @@ -382,7 +355,6 @@ void Entity_Player::apply_victory_lap_penalty(uint32_t) { reconstruction_missing("Entity_Player::apply_victory_lap_penalty 007c97f0"); } -float Entity_Player::get_voice_pitch() { reconstruction_missing("Entity_Player::get_voice_pitch 007c9ad0"); } void Entity_Player::AddJarFlies(int) { reconstruction_missing("Entity_Player::AddJarFlies 007c9bb0"); } bool Entity_Player::IsPosInSpotLight(Vector) { reconstruction_missing("Entity_Player::IsPosInSpotLight 007c9c00"); } void Entity_Player::AddGoldenHearts(int, bool) { reconstruction_missing("Entity_Player::AddGoldenHearts 007c9d10"); } @@ -390,8 +362,6 @@ bool Entity_Player::CanPickGoldenHearts() { reconstruction_missing("Entity_Playe void Entity_Player::BreakGoldenHearts(int) { reconstruction_missing("Entity_Player::BreakGoldenHearts 007ca2d0"); } void Entity_Player::AddBoneHearts(int) { reconstruction_missing("Entity_Player::AddBoneHearts 007ca840"); } bool Entity_Player::CanPickBoneHearts() { reconstruction_missing("Entity_Player::CanPickBoneHearts 007caa00"); } -bool Entity_Player::IsBoneHeart(int) { reconstruction_missing("Entity_Player::IsBoneHeart 007caaa0"); } -bool Entity_Player::TryPreventDeath() { reconstruction_missing("Entity_Player::TryPreventDeath 007caad0"); } void Entity_Player::apply_coop_baby_spawn_bonus() { reconstruction_missing("Entity_Player::apply_coop_baby_spawn_bonus 007cb090"); @@ -425,17 +395,14 @@ void Entity_Player::player_type_change_prepare(int) { reconstruction_missing("Entity_Player::player_type_change_prepare 007cf610"); } -bool Entity_Player::IsLocalPlayer() { reconstruction_missing("Entity_Player::IsLocalPlayer 007cf8c0"); } void Entity_Player::GetGlyphOfBalanceDrop(int*, int*) { reconstruction_missing("Entity_Player::GetGlyphOfBalanceDrop 007d12c0"); } -Vector Entity_Player::GetEnterPosition() { reconstruction_missing("Entity_Player::GetEnterPosition 007d1620"); } Entity_Familiar* Entity_Player::AddMinisaac(Vector, bool) { reconstruction_missing("Entity_Player::AddMinisaac 007d1860"); } -uint32_t Entity_Player::play_hurt_effects() { reconstruction_missing("Entity_Player::play_hurt_effects 007d1c10"); } Entity_Player* Entity_Player::InitTwin(int) { reconstruction_missing("Entity_Player::InitTwin 007d2000"); } bool Entity_Player::TryHoldEntity(Entity*) { reconstruction_missing("Entity_Player::TryHoldEntity 007d2170"); } Entity* Entity_Player::ThrowHeldEntity(Vector) { reconstruction_missing("Entity_Player::ThrowHeldEntity 007d2470"); } @@ -463,10 +430,6 @@ void Entity_Player::trigger_vampire_charm_kill() } void Entity_Player::AddUrnSouls(uint32_t) { reconstruction_missing("Entity_Player::AddUrnSouls 007d3480"); } void Entity_Player::AddGigaBombs(int) { reconstruction_missing("Entity_Player::AddGigaBombs 007d34f0"); } -bool Entity_Player::try_end_astral_projection() -{ - reconstruction_missing("Entity_Player::try_end_astral_projection 007d35b0"); -} void Entity_Player::fire_saturnus_tears() { reconstruction_missing("Entity_Player::fire_saturnus_tears 007d3e40"); } int Entity_Player::GetMaxInventorySize() { reconstruction_missing("Entity_Player::GetMaxInventorySize 007d4150"); } bool Entity_Player::CanAddCollectibleToInventory(int) @@ -523,15 +486,10 @@ void Entity_Player::remove_wooden_cross_mantles() { reconstruction_missing("Entity_Player::remove_wooden_cross_mantles 007db160"); } -bool Entity_Player::HasInstantDeathCurse() { reconstruction_missing("Entity_Player::HasInstantDeathCurse 007db6b0"); } void Entity_Player::TriggerEchoChamber(uint32_t, int) { reconstruction_missing("Entity_Player::TriggerEchoChamber 007db740"); } -bool Entity_Player::is_evil_charm_immune(EntityRef) -{ - reconstruction_missing("Entity_Player::is_evil_charm_immune 007dba30"); -} void Entity_Player::add_random_drug_item_effect() { reconstruction_missing("Entity_Player::add_random_drug_item_effect 007dbba0"); @@ -559,18 +517,10 @@ void Entity_Player::CheckPoopSpellQueue(Vector) { reconstruction_missing("Entity_Player::CheckPoopSpellQueue 0095ffb0"); } -void Entity_Player::StoreGameState(GameStatePlayer*, bool) -{ - reconstruction_missing("Entity_Player::StoreGameState 007b0be0"); -} void Entity_Player::PlayCollectibleAnim(int, bool, std::string_view, int) { reconstruction_missing("Entity_Player::PlayCollectibleAnim 00759f50"); } -void Entity_Player::PlayExtraAnimation(std::string_view, bool) -{ - reconstruction_missing("Entity_Player::PlayExtraAnimation 007abe90"); -} void History::AddHistoryItem(const HistoryItem&) { reconstruction_missing("History::AddHistoryItem 00721a70"); } bool History::RemoveHistoryItemByIndex(int) { reconstruction_missing("History::RemoveHistoryItemByIndex 00721c00"); } void History::merge(History&) { reconstruction_missing("History::merge 00721c80"); } diff --git a/src/entity_player_room.cpp b/src/entity_player_room.cpp new file mode 100644 index 0000000..63ec66e --- /dev/null +++ b/src/entity_player_room.cpp @@ -0,0 +1,340 @@ +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "log.h" +#include "manager.h" +#include "room.h" +#include + +constexpr int TRINKET_TICK = 53; +constexpr int TRINKET_DOOR_STOP = 124; +constexpr int TRINKET_MODELING_CLAY = 166; +constexpr int TRINKET_LIL_CLOT = 176; +constexpr int TRINKET_BETHS_ESSENCE = 182; +constexpr int TRINKET_THE_TWINS = 183; +constexpr int COLLECTIBLE_BROKEN_WATCH = 337; +constexpr int COLLECTIBLE_TOXIC_SHOCK = 350; +constexpr int COLLECTIBLE_DOG_TOOTH = 445; +constexpr int COLLECTIBLE_BELIAL_PARTNER = 474; +constexpr int COLLECTIBLE_BELIAL_EFFECT = 214; +constexpr int COLLECTIBLE_POKE_GO = 505; +constexpr int COLLECTIBLE_MERCURIUS = 590; +constexpr int COLLECTIBLE_SATURNUS = 595; +constexpr int COLLECTIBLE_DOGMA = 633; +constexpr int NULL_ITEM_BELIAL = 123; +constexpr int NULL_ITEM_FORGOTTEN_CHALLENGE = 106; +constexpr int BELIAL_NULL_COUNT = 4; +constexpr int VERSUS_EFFECT_COOLDOWN = 300; +constexpr int PLAYER_THE_FORGOTTEN = 16; +constexpr int PLAYER_THE_FORGOTTEN_B = 35; +constexpr int PLAYER_NO_DOGMA = 40; +constexpr int CHALLENGE_FORGOTTEN_COSTUME = 42; +constexpr int BABY_SKIN_WITH_FOLLOWER = 58; +constexpr int STAGE_ID_HOME = 35; +constexpr int STAGE_MOMS_FLOOR = 6; +constexpr int ENTITY_ROTGUT = 911; +constexpr int BETHS_ESSENCE_WISPS = 5; +constexpr int BETHS_ESSENCE_CHANCE_DOUBLE = 50; +constexpr int BETHS_ESSENCE_CHANCE_TRIPLE = 100; +constexpr int PERCENT = 100; +constexpr int SOUND_BETHS_ESSENCE = 471; +constexpr int SOUND_DOG_TOOTH_SECRET = 442; +constexpr int SOUND_DOG_TOOTH_ROCK = 441; +constexpr int DOG_TOOTH_SECRET_DELAY = 30; +constexpr int DOG_TOOTH_ROCK_DELAY = 60; +constexpr int DELAYED_SOUND_FRAMES = 2; +constexpr int POKE_GO_CHANCE = 5; +constexpr int GREED_WAVE_MAX = 12; +constexpr int DOOR_STOP_UNLOCK_COPIES = 3; +constexpr int DOOR_STOP_BOSS_RUSH_COPIES = 2; +constexpr float DOOR_STOP_REACH_SQUARED = 10000; +constexpr uint32_t LEVEL_STATE_DUNGEON_ROCK_BROKEN = 1u << 13; +constexpr float DOOR_ENTER_OFFSET = 40; +constexpr uint32_t DOOR_SIDES = 4; +constexpr int ROCK_STATE_BROKEN = 2; +constexpr ColorMod TOXIC_SHOCK_COLOR = {{1, 1, 1, 1}, {0, 1, 0, 1}, {0, 0, 0}}; + +// The grid entities Dog Tooth howls at when the floor's crawlspace rock hides there. +constexpr GridEntityType DOG_TOOTH_ROCKS[] = {GRID_ROCK, GRID_ROCKT, GRID_ROCK_BOMB, + GRID_ROCK_ALT, GRID_ROCK_SS, GRID_ROCK_SPIKED, + GRID_ROCK_ALT2, GRID_ROCK_GOLD}; + +// 007d1620 Where the player comes into the room: Level's spot for rooms entered without a door, else a cell inside the +// door the players come in by (one of the layout's doors from a random slot when none is set). +Vector Entity_Player::GetEnterPosition() +{ + Game& game = *g_game; + Room& room = *game.room; + uint32_t enterDoor = (uint32_t)game.enterDoor; + + if (game.enterDoor == DOOR_NONE) + { + enterDoor = Random() & (DOOR_SLOT_COUNT - 1); + for (int i = 0; i < DOOR_SLOT_COUNT && !(enterDoor < DOOR_SLOT_COUNT && room.descriptor->data->doors >> enterDoor & 1); i++) + enterDoor = (enterDoor + 1) % DOOR_SLOT_COUNT; + } + + Vector enter = game.GetEnterPosition(); + if (enter.x != 0 || enter.y != 0) return enter; + + Vector door = enterDoor < DOOR_SLOT_COUNT ? room.GetGridPosition(room.doorGridPositions[enterDoor]) : Vector{}; + switch (enterDoor % DOOR_SIDES) + { + case DIRECTION_LEFT: + return vector_make(door.x + DOOR_ENTER_OFFSET, door.y); + case DIRECTION_UP: + return vector_make(door.x, door.y + DOOR_ENTER_OFFSET); + case DIRECTION_RIGHT: + return vector_make(door.x - DOOR_ENTER_OFFSET, door.y); + default: + return vector_make(door.x, door.y - DOOR_ENTER_OFFSET); + } +} + +// Plays the player's pending delayed sound at once and queues another, as Entity_Player::PlayDelayedSFX (007cb5d0). +static void delayed_sound_queue(Entity_Player& player, int sound, int delay) +{ + if (player.delayedSfxId != 0 && player.delayedSfxDelay > 0) + { + int pending = player.delayedSfxId; + seed_fart_sound_override(&pending); + g_manager->sfxManager.Play(pending, {.volume = player.delayedSfxVolume, .frameDelay = player.delayedSfxFrameDelay}); + } + player.delayedSfxId = sound; + player.delayedSfxVolume = 1; + player.delayedSfxDelay = delay; + player.delayedSfxFrameDelay = DELAYED_SOUND_FRAMES; +} + +// Beth's Essence in an angel room's first visit: five wisps, of the Book of Virtues or (half the time with two copies, +// always with three) a random active item. +static void beths_essence_wisps_add(Entity_Player& player) +{ + int multiplier = player.GetTrinketMultiplier(TRINKET_BETHS_ESSENCE); + int chance = multiplier == 2 ? BETHS_ESSENCE_CHANCE_DOUBLE : multiplier == 3 ? BETHS_ESSENCE_CHANCE_TRIPLE : 0; + + for (int i = 0; i < BETHS_ESSENCE_WISPS; i++) + { + if (chance == 0 || (int)player.trinketRNGs[TRINKET_BETHS_ESSENCE].RandomInt(PERCENT) >= chance) + player.AddWisp(COLLECTIBLE_BOOK_OF_VIRTUES, player.pos, true, false); + else + reconstruction_missing("Entity_Player::room_enter 007a6c50: Beth's Essence's random active item wisps " + "(the actives with a wisp, ItemConfig_Item +0x190)"); + } + sound_play(SOUND_BETHS_ESSENCE); +} + +// Door Stop: the door the player came in by (or, entering without one, the first within reach, if any) opens, and with +// three copies its ambush lock opens too. With two or more copies, coming back from the boss rush keeps its door. +static void door_stop_apply(Entity_Player& player) +{ + Game& game = *g_game; + Room& room = *game.room; + int slot = game.enterDoor; + + if (slot == DOOR_NONE) + for (slot = 0; slot < DOOR_SLOT_COUNT; slot++) + { + GridEntity_Door* door = room.doors[slot]; + if (!door) continue; + + Vector position = room.GetGridPosition(door->gridIndex); + float dx = player.pos.x - position.x; + float dy = player.pos.y - position.y; + if (dy * dy + dx * dx < DOOR_STOP_REACH_SQUARED) break; + } + if (slot < 0 || (game.enterDoor == DOOR_NONE && slot == DOOR_SLOT_COUNT)) return; + + int multiplier = player.GetTrinketMultiplier(TRINKET_DOOR_STOP); + GridEntity_Door* door = slot < DOOR_SLOT_COUNT ? room.doors[slot] : nullptr; + if (door) door->Open(); + if (door && multiplier >= DOOR_STOP_UNLOCK_COPIES) + { + if (door->doorFlags & DOOR_FLAG_AMBUSH) door->TryUnlock(player, true); + } + else if (multiplier < DOOR_STOP_BOSS_RUSH_COPIES) return; + if (game.lastRoomIdx == ROOM_BOSSRUSH_IDX) room.TrySpawnBossRushDoor(true, true); +} + +// Dog Tooth howls once at an unvisited secret room behind a closed door, and growls at the floor's crawlspace rock. +static void dog_tooth_apply(Entity_Player& player) +{ + Game& game = *g_game; + Room& room = *game.room; + + for (GridEntity_Door* door : room.doors) + { + bool isSecret = door && (door->targetRoomType == ROOM_SECRET || door->targetRoomType == ROOM_SUPERSECRET); + if (!isSecret || door->state == DOOR_STATE_OPEN || game.GetRoomByIdx(door->targetRoomIdx)->visitedCount != 0) + continue; + delayed_sound_queue(player, SOUND_DOG_TOOTH_SECRET, DOG_TOOTH_SECRET_DELAY); + break; + } + + int rockIdx = room.dungeonRockIdx; + GridEntity* rock = rockIdx >= 0 && rockIdx < ROOM_GRID_CELLS ? room.gridEntities[rockIdx] : nullptr; + bool isRock = rock && std::ranges::find(DOG_TOOTH_ROCKS, rock->type) != std::end(DOG_TOOTH_ROCKS); + if (!(game.levelStateFlags & LEVEL_STATE_DUNGEON_ROCK_BROKEN) && isRock && rock->state != ROCK_STATE_BROKEN) + delayed_sound_queue(player, SOUND_DOG_TOOTH_ROCK, DOG_TOOTH_ROCK_DELAY); +} + +// What the player's items do on entering a room after it is placed: Toxic Shock's clouds, Poke Go's charmed enemy, +// Dog Tooth's sounds, the locusts, a co-op baby's shield, the Broken Watch, the weapons' new room reset and the +// poop under the player. +static void room_items_apply(Entity_Player& player) +{ + Game& game = *g_game; + Room& room = *game.room; + bool isFresh = room.isFirstVisit && !room.IsClear(); + + if (!game.isLevelGenerating) player.spawn_low_health_blood_splat(); + if (player.HasCollectible(COLLECTIBLE_TOXIC_SHOCK) && !room.IsClear()) room.fxLayers.AddPoopFx(TOXIC_SHOCK_COLOR); + if (player.HasCollectible(COLLECTIBLE_POKE_GO) && isFresh && + player.collectibleRNGs[COLLECTIBLE_POKE_GO].RandomInt(POKE_GO_CHANCE) == 0) + reconstruction_missing("Entity_Player::room_enter 007a6c50: Poke Go's charmed enemy (Entity::SetVisibleFlag, " + "HUD::show_fortune_line with #POKE_GO_APPEAR_NOTIFY)"); + if (player.HasCollectible(COLLECTIBLE_DOG_TOOTH)) dog_tooth_apply(player); + if (isFresh) player.spawn_locusts(); + + if (player.variant == PLAYER_VARIANT_COOP_BABY) + { + player.hasBabyRoomShield = true; + if (player.babySkin == BABY_SKIN_WITH_FOLLOWER) + reconstruction_missing("Entity_Player::room_enter 007a6c50: the co-op baby's follower effect 1000.114"); + } + else if (player.variant == PLAYER_VARIANT_PLAYER && room.isFirstVisit && player.HasCollectible(COLLECTIBLE_BROKEN_WATCH)) + reconstruction_missing("Entity_Player::room_enter 007a6c50: the Broken Watch's rooms counter (Entity_Player +0x1820)"); + + Entity* parent = player.parent.get(); + if (player.variant == PLAYER_VARIANT_COOP_BABY && parent && + game.GetRoomByIdx(game.currentRoomIdx)->listIndex == game.lastBossRoomListIdx && game.stage == STAGE_MOMS_FLOOR) + player.pos = parent->pos; + for (int slot = 1; slot < WEAPON_SLOT_COUNT; slot++) + if (player.weapons[slot]) player.weapons[slot]->TriggerNewRoom(); + if (player.weapons[0]) player.weapons[0]->TriggerNewRoom(); + + int column = (int)((player.pos.x - GRID_ORIGIN_X) / GRID_CELL_SIZE + 0.5f); + int row = (int)((player.pos.y - GRID_ORIGIN_Y) / GRID_CELL_SIZE + 0.5f); + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + int cell = room.gridWidth * row + column; + GridEntity* poop = isInside && cell < ROOM_GRID_CELLS ? room.gridEntities[cell] : nullptr; + if (poop && poop->type == GRID_POOP && !player.canFly) + reconstruction_missing("Entity_Player::room_enter 007a6c50: Room::RemoveGridEntity 0081e930 on the poop entered on"); + else if (poop && poop->type == GRID_POOP && poop->variant == 1) + reconstruction_missing("Entity_Player::room_enter 007a6c50: the red poop flown over drops to its last state"); +} + +// 007a6c50 Sets the player up in the room just entered (after the floor's start): the cursed mist, Beth's Essence, +// Dogma in the living room, the Twins and Judas's Belial, then the player stands at its entry with its motion, held +// throw and pit fall reset, and its items react to the room. Friendly enemies follow it in, and Used Diaper, Lil Clot, +// the Forgotten's body and the item sounds come last. +// The original also clears the list at +0x1b34 and the words at +0x1c54..+0x1c60, which this player does not have. +void Entity_Player::room_enter() +{ + Game& game = *g_game; + Room& room = *game.room; + RoomConfig_Room* data = room.descriptor->data; + if (!isPostLevelInitFinished) return; + + if (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_CURSED_MIST) AddCurseMistEffect(); + if (room.roomType == ROOM_ANGEL && room.descriptor->visitedCount == 1 && HasTrinket(TRINKET_BETHS_ESSENCE)) + beths_essence_wisps_add(*this); + bool isDogmaRoom = data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME; + if (isDogmaRoom && collectibleCounts[COLLECTIBLE_DOGMA] < 1 && playerType != PLAYER_NO_DOGMA) + AddCollectible(COLLECTIBLE_DOGMA, 0, true, 0, 0); + if (playerType == PLAYER_THE_FORGOTTEN_B && game.challenge == CHALLENGE_FORGOTTEN_COSTUME) + { + ItemConfig_Item* costume = g_manager->itemConfig.GetNullItem(NULL_ITEM_FORGOTTEN_CHALLENGE); + for (PlayerCostumeMap& layer : playerCostumeMap) + { + if (layer.index < 0 || layer.isBodyLayer || costumeSpriteDescs[layer.index].item != costume) continue; + AnimationState& state = costumeSpriteDescs[layer.index].sprite.animState; + if (state.animData) state.SetFrameFloat(0); + break; + } + } + if (HasTrinket(TRINKET_THE_TWINS)) + twins_duplicate_familiars( + (int)trinketRNGs[TRINKET_THE_TWINS].RandomInt(GetTrinketMultiplier(TRINKET_THE_TWINS) + 1)); + if (HasCollectible(COLLECTIBLE_BOOK_OF_BELIAL_PASSIVE) && HasCollectible(COLLECTIBLE_BELIAL_PARTNER)) + { + if (!temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BELIAL_EFFECT)) + if (ItemConfig_Item* item = g_manager->itemConfig.GetCollectible(COLLECTIBLE_BELIAL_EFFECT)) + { + TemporaryEffect effect(item); + if (game.deathmatchManager.state >= DEATHMATCH_INTRO) effect.cooldown = VERSUS_EFFECT_COOLDOWN; + temporaryEffects.AddEffect(effect, true, 1); + } + temporaryEffects.AddNullEffect(NULL_ITEM_BELIAL, true, BELIAL_NULL_COUNT); + } + + moveToTarget = vector_make(0, 0); + Vector enter = GetEnterPosition(); + if (game.IsGreedMode() && (uint32_t)game.greedLastBeatenWave < (uint32_t)game.greedModeWave) + game.greedModeWave = std::min(game.greedLastBeatenWave, GREED_WAVE_MAX); + pos = enter; + velocity = vector_make(0, 0); + strengthMaxHearts = 0; + heightVelocity = 0; + posOffset.y = 0; + if (flags & FLAG_THROWN) + { + flags &= ~FLAG_THROWN; + isControlsEnabled = true; + } + + RoomConfig_Room* lastData = game.GetRoomByIdx(game.lastRoomIdx, game.lastRoomDimensionIdx)->data; + bool isOutOfRotgut = lastData && lastData->type == ROOM_DUNGEON && + (room.descriptor->flags & ROOM_DESCRIPTOR_FLAG_ROTGUT_CLEARED); + if (isOutOfRotgut) + for (Entity* entity : room.entityList.updateEL) + if (entity->type == ENTITY_ROTGUT && entity->variant == 0) + { + reconstruction_missing("Entity_Player::room_enter 007a6c50: thrown out of Rotgut (Entity_Player::TryThrow)"); + break; + } + if (HasCollectible(COLLECTIBLE_SATURNUS)) fire_saturnus_tears(); + if (pitfallState != 0 && !isDead) + { + pitfallTimer = 0; + pitfallState = 0; + isPlayingExtraAnimation = false; + isPlayingItemAnimation = false; + isControlsEnabled = true; + entityCollisionClass = ENTCOLL_ALL; + } + if (!(flags & FLAG_HELD)) entityCollisionClass = ENTCOLL_ALL; + if (HasTrinket(TRINKET_ERROR) || HasTrinket(TRINKET_MODELING_CLAY)) + { + cacheFlags |= CACHE_ALL; + EvaluateItems(); + game.hud.mark_all_slots_dirty(HISTORY_KEEP_ICONS, HISTORY_KEEP_ITEMS); + } + if (HasTrinket(TRINKET_TICK) && room.roomType == ROOM_BOSS && room.isFirstVisit) + AddHearts(GetTrinketMultiplier(TRINKET_TICK) * 2, false, false); + if (HasCollectible(COLLECTIBLE_MERCURIUS) && room.roomType == ROOM_DEFAULT) + for (GridEntity_Door* door : room.doors) + if (door && door->targetRoomType == ROOM_DEFAULT) door->Open(); + if (HasTrinket(TRINKET_DOOR_STOP)) door_stop_apply(*this); + room_items_apply(*this); + + for (Entity* entity : room.entityList.updateEL) + { + if (game.isRestoringGlowingHourglassState && entity->type == ENTITY_BLOOD_PUPPY) + { + entity->Remove(); + continue; + } + bool isFollower = (game.deathmatchManager.state >= DEATHMATCH_INTRO && entity->type == ENTITY_PLAYER) || + (entity->type >= ENTITY_FIRST_ENEMY && entity->type < ENTITY_EFFECT); + if ((entity->flags & FLAG_FRIENDLY) && isFollower) + reconstruction_missing("Entity_Player::room_enter 007a6c50: a friendly enemy following the player in " + "(Entity_NPC +0x418, +0x420)"); + } + if (HasTrinket(TRINKET_USED_DIAPER) && room.isFirstVisit && !room.IsClear() && room.GetAliveEnemiesCount() > 0 && + !game.isRestoringGlowingHourglassState) + for (int i = GetTrinketMultiplier(TRINKET_USED_DIAPER); i > 0; i--) AddBlueFlies(1, pos, nullptr); + if (HasTrinket(TRINKET_LIL_CLOT)) spawn_lil_clot_familiars(); + if (playerType == PLAYER_THE_FORGOTTEN) spawn_forgotten_body(); + preload_item_sounds(); +} diff --git a/src/entity_save_state.h b/src/entity_save_state.h new file mode 100644 index 0000000..9fec175 --- /dev/null +++ b/src/entity_save_state.h @@ -0,0 +1,45 @@ +#pragma once + +#include "classes.h" +#include +#include +#include +#include + +constexpr int ENTITY_SAVE_EXTRA_SIZE = 32; + +// The bytes a saved entity may carry for a mod. +using EntitySaveExtraData = std::array; + +// An entity kept while nobody is in its room (a room's saved entities and effects, a Moving Box, Flip's other item): +// its kind and seeds, the storage fields its class saves into, a mod's extra bytes, and a second saved entity it carries. +// Construction (004d3080) and copies (004d3130) are the defaults. +struct EntitySaveState +{ + std::optional extraData; + std::shared_ptr child; + Vector targetPosition{}; + float floatStorage1 = 60; + float floatStorage2 = 1; + float floatStorage3 = 1; + int64_t int64Storage = -1; + int intStorage4 = -1; + int intStorage5 = -1; + int spawnerType = 0; + int spawnerVariant = 0; + int subtype = 0; + int type = 0; + int variant = 0; + uint32_t dropSeed = 0; + uint32_t initSeed = 0; + uint32_t intStorage1 = 0; + uint32_t intStorage2 = 0; + uint32_t intStorage3 = 0; + uint32_t intStorage6 = 0; + uint32_t intStorage7 = 0; + uint32_t intStorage8 = 0; + int16_t gridSpawnIdx = 0; + uint8_t byteStorage = 1; + bool boolStorage1 = false; + bool boolStorage2 = false; +}; diff --git a/src/entity_slot.cpp b/src/entity_slot.cpp index 0ae7ee5..d5d2d4e 100644 --- a/src/entity_slot.cpp +++ b/src/entity_slot.cpp @@ -1,26 +1,203 @@ #include "entity_slot.h" +#include "entity_config.h" +#include "game.h" #include "log.h" +#include "manager.h" +#include "room.h" +#include + +// Lua's SlotVariant: the machines and beggars. +enum SlotVariant : int +{ + SLOT_MACHINE = 1, + SLOT_BLOOD_DONATION_MACHINE, + SLOT_FORTUNE_TELLING_MACHINE, + SLOT_BEGGAR, + SLOT_DEVIL_BEGGAR, + SLOT_SHELL_GAME, + SLOT_KEY_MASTER, + SLOT_DONATION_MACHINE, + SLOT_BOMB_BUM, + SLOT_SHOP_RESTOCK_MACHINE, + SLOT_GREED_DONATION_MACHINE, + SLOT_MOMS_DRESSER, + SLOT_BATTERY_BUM, + SLOT_ISAAC_SECRET, + SLOT_HELL_GAME, + SLOT_CRANE_GAME, + SLOT_CONFESSIONAL, + SLOT_ROTTEN_BEGGAR, + SLOT_REVIVE_MACHINE +}; + +// The event counters the donation machines show (DONATION_MACHINE_COUNTER, GREED_DONATION_MACHINE_COUNTER). +constexpr int EVENT_DONATION_MACHINE = 20; +constexpr int EVENT_GREED_DONATION_MACHINE = 115; + +// The run's state flags of a broken or jammed donation machine. +constexpr int GAME_STATE_DONATION_SLOT_BROKEN = 17; +constexpr int GAME_STATE_DONATION_SLOT_JAMMED = 18; +constexpr int GAME_STATE_GREED_SLOT_JAMMED = 34; + +// The animations a jammed donation machine plays, one at random. +constexpr std::array COIN_JAM_ANIMATIONS = {"CoinJam", "CoinJam2", "CoinJam3", "CoinJam4"}; + +constexpr int SLOT_STATE_IDLE = 1; +constexpr int SLOT_STATE_JAMMED = 3; +constexpr int REVIVE_MACHINE_EXCLUDED_ROOM = -20; +constexpr int DIGIT_BASE = 10; +constexpr int HUNDREDS = 100; +constexpr float MACHINE_OFFSET_Y = -8; +constexpr float BEGGAR_OFFSET_Y = 8; +constexpr float BLOOD_MACHINE_OFFSET_X = -5; +constexpr float MACHINE_WIDTH = 1.5f; +constexpr float SHELL_GAME_WIDTH = 3; +constexpr float MACHINE_DEPTH = 0.75f; + +// Whether the run counts toward achievements (Game::AchievementUnlocksDisallowed 00705080, which Game does not declare +// yet): not on a custom seed, a seed or mod that blocks them, or a rerun. +static bool achievements_disallowed() +{ + Game& game = *g_game; + return game.seedEffects.isCustomRun || game.seedEffects.AchievementUnlocksDisallowed() || + Manager::AchievementUnlocksDisallowed() || game.isRerun; +} + +// 0065d200 Starts a slot from its config's sprite, sized and offset for its kind. The donation machines show their +// save's count and break or jam as the run left them, the dresser appears on a first visit, and the Revive Machine +// only stays in co-op. In Greed mode the blood donation machine is a devil beggar. +// Isaac's secret closet and the Revive Machine's setup are not reconstructed yet. +void Entity_Slot::Init(int entityType, int entityVariant, int entitySubType, uint32_t seed) +{ + bool isGreed = g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER; + int kind = isGreed && entityVariant == SLOT_BLOOD_DONATION_MACHINE ? SLOT_DEVIL_BEGGAR : entityVariant; + + persistentData = &g_manager->persistentGameData; + Entity::Init(entityType, kind, entitySubType, seed); + if (config) + { + sprite.Load(config->anm2Path, GRAPHICS_LOAD); + sprite.Play(sprite.GetDefaultAnimationName()); + } + + targetPosition = {}; + posOffset = {}; + sizeMulti = vector_make(1, 1); + donationValue = 0; + triggerTimer = 0; + unkShort1 = 0; + touch = 0; + isUnknown544 = false; + isUnknown418 = false; + state = SLOT_STATE_IDLE; + prizeAnm2.Reset(); + prizeCollectible = 0; + + switch (kind) + { + case SLOT_MACHINE: + case SLOT_BLOOD_DONATION_MACHINE: + case SLOT_FORTUNE_TELLING_MACHINE: + case SLOT_CRANE_GAME: + case SLOT_CONFESSIONAL: + posOffset.y = MACHINE_OFFSET_Y; + sizeMulti = vector_make(MACHINE_WIDTH, MACHINE_DEPTH); + if (kind == SLOT_BLOOD_DONATION_MACHINE) posOffset.x = BLOOD_MACHINE_OFFSET_X; + break; + case SLOT_SHELL_GAME: + case SLOT_HELL_GAME: + posOffset.y = MACHINE_OFFSET_Y; + sizeMulti = vector_make(SHELL_GAME_WIDTH, MACHINE_DEPTH); + prizeAnm2 = sprite; + break; + case SLOT_BEGGAR: + case SLOT_DEVIL_BEGGAR: + case SLOT_KEY_MASTER: + case SLOT_BOMB_BUM: + case SLOT_BATTERY_BUM: + case SLOT_ROTTEN_BEGGAR: + posOffset.y = BEGGAR_OFFSET_Y; + break; + case SLOT_DONATION_MACHINE: + { + posOffset.y = MACHINE_OFFSET_Y; + sizeMulti = vector_make(MACHINE_WIDTH, MACHINE_DEPTH); + counter_show(persistentData->eventCounters[EVENT_DONATION_MACHINE]); + bool isOnline = g_manager->netplayManager.is_online(); + bool isBroken = g_game->GetStateFlag((GameStateFlag)GAME_STATE_DONATION_SLOT_BROKEN) || + (isOnline ? g_game->challenge != 0 || g_game->dailyChallenge._id != 0 + : achievements_disallowed()); + if (isBroken) Remove(); + if (g_game->GetStateFlag((GameStateFlag)GAME_STATE_DONATION_SLOT_JAMMED)) + { + sprite.Play(COIN_JAM_ANIMATIONS[Random() & 3]); + state = SLOT_STATE_JAMMED; + } + AddEntityFlags(FLAG_NO_KNOCKBACK); + break; + } + case SLOT_GREED_DONATION_MACHINE: + posOffset.y = MACHINE_OFFSET_Y; + sizeMulti = vector_make(MACHINE_WIDTH, MACHINE_DEPTH); + counter_show(persistentData->eventCounters[EVENT_GREED_DONATION_MACHINE]); + if (achievements_disallowed() && !g_manager->netplayManager.is_online()) Remove(); + if (g_game->GetStateFlag((GameStateFlag)GAME_STATE_GREED_SLOT_JAMMED)) + { + sprite.Play(COIN_JAM_ANIMATIONS[Random() & 3]); + state = SLOT_STATE_JAMMED; + } + break; + case SLOT_SHOP_RESTOCK_MACHINE: + posOffset.y = MACHINE_OFFSET_Y; + sizeMulti = vector_make(MACHINE_WIDTH, MACHINE_DEPTH); + AddEntityFlags(FLAG_NO_KNOCKBACK); + break; + case SLOT_MOMS_DRESSER: + sizeMulti = vector_make(MACHINE_WIDTH, MACHINE_DEPTH); + if (!g_game->room->isFirstVisit) sprite.Play("Idle"); + else + { + sprite.Play("Appear"); + isVisible = false; + } + break; + case SLOT_ISAAC_SECRET: + reconstruction_missing("Entity_Slot::Init 0065d200: Isaac's secret closet"); + case SLOT_REVIVE_MACHINE: + if (!g_game->playerManager.IsCoopPlay() || g_game->currentRoomIdx == REVIVE_MACHINE_EXCLUDED_ROOM) Remove(); + else reconstruction_missing("Entity_Slot::Init 0065d200: the Revive Machine in co-op (FUN_006655e0)"); + break; + } + entityGridCollisionClass = GRIDCOLL_NONE; + timeout = 0; +} + +// Shows a donation count on the machine's three digit layers. +void Entity_Slot::counter_show(int count) +{ + sprite.SetFrame("Prize", 0); + sprite.SetLayerFrame(1, count / HUNDREDS % DIGIT_BASE); + sprite.SetLayerFrame(2, count / DIGIT_BASE % DIGIT_BASE); + sprite.SetLayerFrame(3, count % DIGIT_BASE); +} + +// 00665370 Draws the slot, and a shell game's prize while it plays. +void Entity_Slot::Render(const Vector& offset) +{ + Entity::Render(offset); + bool isShellGame = variant == SLOT_SHELL_GAME || variant == SLOT_HELL_GAME; + if (isShellGame && prizeAnm2.animState.animData && prizeAnm2.animState.isPlaying) + prizeAnm2.Render(SpriteDraw{renderPosition, {}, {}}); +} // The rest of Entity_Slot is not reconstructed yet. -// 0065d200 -void Entity_Slot::Init(int, int, int, uint32_t) -{ - reconstruction_missing("Entity_Slot::Init 0065d200"); -} - // 0065d950 void Entity_Slot::Update() { reconstruction_missing("Entity_Slot::Update 0065d950"); } -// 00665370 -void Entity_Slot::Render(const Vector&) -{ - reconstruction_missing("Entity_Slot::Render 00665370"); -} - // 00664560 bool Entity_Slot::TakeDamage(float, uint64_t, const EntityRef&, int) { diff --git a/src/entity_slot.h b/src/entity_slot.h index 35103ec..b4690cf 100644 --- a/src/entity_slot.h +++ b/src/entity_slot.h @@ -3,9 +3,24 @@ #include "entity.h" // Construction and destruction (0065d130) are the defaults. -// A slot machine, beggar or other paying machine (Lua's EntitySlot), which pays out a prize. +// A slot machine, beggar or other paying machine (Lua's EntitySlot), which pays out a prize: its state, the prize it +// shows and the save data its donations count into. struct Entity_Slot : Entity { + ANM2 prizeAnm2; + PersistentGameData* persistentData = nullptr; + int donationValue = 0; + int prizeCollectible = 0; + int prizeType = 0; + int state = 0; + uint32_t triggerTimer = 0; + int16_t shellGameAnimationIndex = 0; + int16_t timeout = 0; + int16_t unkShort1 = 0; + uint16_t touch = 0; + bool isUnknown418 = false; + bool isUnknown544 = false; + void Init(int type, int variant, int subType, uint32_t initSeed) override; void Update() override; void Render(const Vector& offset) override; @@ -14,4 +29,7 @@ struct Entity_Slot : Entity void spawn_break_drops(); void SetPrizeType(int prizeType); + +private: + void counter_show(int count); }; diff --git a/src/entity_tear.cpp b/src/entity_tear.cpp index efb1b95..4124142 100644 --- a/src/entity_tear.cpp +++ b/src/entity_tear.cpp @@ -146,6 +146,30 @@ constexpr std::array BLOOD_ANIMATION_VARIANTS = {TEAR_BLOOD, TE constexpr std::array STONE_ANIMATION_VARIANTS = {TEAR_STONE, TEAR_BOOGER, TEAR_EGG, TEAR_RAZOR, TEAR_BONE, TEAR_SPORE}; +// The halo of a glowing tear, and the tear effects in the order SetTearFlags picks them: the flag that shows each and +// its sprite. Rift's tears show Little Horn's effect tinted. +constexpr const char* TEAR_HALO_ANM2 = "gfx/TearHalo.anm2"; +constexpr ColorMod RIFT_EFFECT_COLOR = {{1, 0.7f, 0.7f, 1}, {0, 0, 0, 0}, {0, 0, 0}}; +// A render flag the creep, fire and dark matter effects and their first layer carry, read by nothing written yet. +constexpr unsigned int TEAR_EFFECT_LAYERED = 1 << 12; + +// A tear effect: the flag that shows it and its sprite. +struct TearEffect +{ + int flag = 0; + const char* anm2 = nullptr; +}; + +constexpr std::array TEAR_EFFECTS = {{ + {TEAR_HORN, "gfx/LittleHornTearEffect.anm2"}, + {TEAR_RIFT, "gfx/LittleHornTearEffect.anm2"}, + {TEAR_LIGHT_FROM_HEAVEN, "gfx/HolyLightTearEffect.anm2"}, + {TEAR_JACOBS, "gfx/JacobsLadderTearEffect.anm2"}, + {TEAR_MYSTERIOUS_LIQUID_CREEP, "gfx/MysteriousTearEffect.anm2"}, + {TEAR_BURN, "gfx/FireMindTearEffect.anm2"}, + {TEAR_DARK_MATTER_FLAG, "gfx/DarkMatterTearEffect.anm2"}, +}}; + // The splash a dying tear leaves: its poof and its sound. struct TearSplash { @@ -209,12 +233,6 @@ static bool is_crawlspace() return g_game->room->roomType == ROOM_DUNGEON; } -// Stops where a mod has a function for one of the tear's Lua callbacks, which LuaEngine does not run yet. -static void lua_callback_check(int callback, const char* name) -{ - if (static_cast(g_luaEngine)->enabledCallbacks[callback]) reconstruction_missing(name); -} - // Whether the player is another machine's in an online game, whose shots the game fades. static bool is_remote_player(Entity_Player* player) { @@ -726,6 +744,47 @@ void Entity_Tear::SetScale(float scale) ResetSpriteScale(); } +// Loads the tear effect the first of its flags calls for and plays it: Little Horn's additive (tinted for Rift's +// tears), Holy Light's and Jacob's Ladder's first layer additive, and the creep, fire and dark matter drawn behind. +static void tear_effect_load(ANM2& effect, const TearFlags& flags) +{ + auto shown = std::find_if(TEAR_EFFECTS.begin(), TEAR_EFFECTS.end(), + [&flags](const TearEffect& candidate) { return flags[candidate.flag]; }); + if (shown == TEAR_EFFECTS.end()) return; + + effect.Load(shown->anm2, GRAPHICS_LOAD); + switch (shown->flag) + { + case TEAR_HORN: + case TEAR_RIFT: + for (int i = 0; i < (int)effect.layerStates.size(); i++) + { + layer_additive_set(effect, i); + if (shown->flag == TEAR_RIFT) effect.GetLayer(i)->color = RIFT_EFFECT_COLOR; + } + break; + case TEAR_LIGHT_FROM_HEAVEN: + case TEAR_JACOBS: layer_additive_set(effect, 0); break; + default: + effect.bitflags |= TEAR_EFFECT_LAYERED | TEAR_EFFECT_BEHIND; + effect.GetLayer(0)->bitflags = TEAR_EFFECT_LAYERED; + if (shown->flag == TEAR_MYSTERIOUS_LIQUID_CREEP) layer_additive_set(effect, 1); + } + effect.Play("Idle"); +} + +// 00676150 Sets the tear flags, loading what they show the first time: a glowing tear's halo, and its one effect. +void Entity_Tear::SetTearFlags(TearFlags flags) +{ + if (flags[TEAR_GLOW] && !tearHaloANM2.isLoaded) + { + tearHaloANM2.Load(TEAR_HALO_ANM2, GRAPHICS_LOAD); + tearHaloANM2.Play("Idle"); + } + if (!tearEffectANM2.isLoaded) tear_effect_load(tearEffectANM2, flags); + tearFlags = flags; +} + // 00676be0 Applies what its flags do when it dies, splitting it or chaining lightning. A tear without flags does // nothing. void Entity_Tear::apply_death_flag_effects(Entity*) @@ -902,12 +961,6 @@ void Entity_Tear::update_wiggle() reconstruction_missing("Entity_Tear::update_wiggle 00666ba0"); } -// 00676150 -void Entity_Tear::SetTearFlags(TearFlags) -{ - reconstruction_missing("Entity_Tear::SetTearFlags 00676150"); -} - // 00678080 void Entity_Tear::fire_split_projectiles(bool) { diff --git a/src/entity_tear.h b/src/entity_tear.h index 3ace806..6cd3b58 100644 --- a/src/entity_tear.h +++ b/src/entity_tear.h @@ -11,10 +11,17 @@ enum TearFlagBit : int TEAR_EXPLOSIVE = 12, TEAR_WAIT = 17, TEAR_QUADSPLIT = 18, + TEAR_BURN = 22, TEAR_GLOW = 31, + TEAR_MYSTERIOUS_LIQUID_CREEP = 33, TEAR_SHIELDED = 34, + TEAR_LIGHT_FROM_HEAVEN = 39, TEAR_TRACTOR_BEAM = 42, + TEAR_JACOBS = 55, + TEAR_HORN = 56, TEAR_POP = 58, + TEAR_RIFT = 76, + TEAR_DARK_MATTER_FLAG = 124, TEAR_LUDOVICO = 127 }; diff --git a/src/game.cpp b/src/game.cpp index 4738aad..eab006f 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -407,9 +407,9 @@ void Game::ResetState() for (BackwardsStageDesc& backwards : backwardsStages) { - backwards._isXL = false; - backwards._bossRoomsCount = 0; - backwards._treasureRoomsCount = 0; + backwards.isXL = false; + backwards.bossRooms.clear(); + backwards.treasureRooms.clear(); } deathCertificateExitTimer = 0; @@ -425,7 +425,7 @@ void Game::ResetState() isRestoringGlowingHourglassState = false; currentGlowingHourglassSlot = -1; rewindsThisFloor = 0; - for (GlowingHourglassState& state : glowingHourglassStates) state._isUsable = false; + for (GlowingHourglassState& state : glowingHourglassStates) state.isUsable = false; isPocketItemRewindSaved = false; reviveMachineUses = 0; reviveMachineCoinsLeft = REVIVE_MACHINE_COINS; @@ -537,66 +537,6 @@ void Game::Fadein(float speed, FadeIcon icon, KColor color) for (Entity_Player* player : playerManager.playerList) player->isControlsEnabled = false; } -// 006f9000 Copies the run into a game state to save: its rules and seeds, the counters and histories of the run, the -// item and boss pools, the TMTRAINER seeds, the floor (after leaving the room), the players, the Ascent's saved -// stages, the nightmare stage bar, the ambush wave, the score and the versus rules. -// The saved flags are the first 53 of the run's state flags. -void Game::store_game_state(GameState& state) -{ - state.Clear(); - state.seeds = seedEffects; - state.playerManagerSeed = playerManager.rng._seed; - state.fortuneSeed = fortuneRNG._seed; - state.challenge = (int)challenge; - state.isRerun = isRerun; - state.isConsoleUsedThisRun = isConsoleUsedThisRun; - state.difficulty = difficulty; - state.gameStateFlags = std::bitset(gameStateFlags); - - state.lastDevilRoomStage = lastDevilRoomStage; - state.treasureRoomsVisited = treasureRoomsVisited; - state.planetariumsVisited = planetariumsVisited; - state.stagesWithoutHeartsPicked = stagesWithoutHeartsPicked; - state.stagesWithoutDamage = stagesWithoutDamage; - state.devilRoomDeals = devilRoomDeals; - state.shopVisits = shopVisits; - state.donationModGreed = donationModGreed; - state.donationModAngel = donationModAngel; - state.reviveMachineCoinsLeft = reviveMachineCoinsLeft; - state.reviveMachineUses = reviveMachineUses; - state.bossRushParTime = bossRushParTime; - state.blueWombParTime = blueWombParTime; - state.frameCount = frameCount; - state.timeCounter = timeCounter; - state.stageNameNumeral = stageNameNumeral; - state.victoryLap = victoryLap; - state.lastLevelWithoutHalfHp = lastLevelWithoutHalfHp; - state.lastLevelWithDamage = lastLevelWithDamage; - state.encounteredBosses = encounteredBosses; - state.pixelationTimer = pixelationTimer; - state.pixelationDuration = pixelationDuration; - state.magicSkinUses = magicSkinUses; - state.erasedEntities = erasedEntities; - itemPool.StoreGameState(state.itemPool); - bossPool.store_game_state(state.bossPool); - if (!proceduralItemManager.proceduralItems.empty()) - reconstruction_missing("Game::store_game_state 006f9000: the TMTRAINER items' seeds (ProceduralItem +0x8)"); - - reconstruction_missing("Game::store_game_state 006f9000: Room::on_leave 007efa50"); - Level::store_game_state(state); - playerManager.store_game_state(&state); - - state.isAscent = ascentTimer > 0; - state.backwardsStages = backwardsStages; - state.deathCertificateExitTimer = deathCertificateExitTimer; - state.nightmareStageIcons = g_manager->nightmareScene.stageIcons; - state.isAmbushActive = ambush._isActive; - state.ambushWave = ambush._currentWave > 0 ? ambush._currentWave - 1 : ambush._currentWave; - scoreSheet.store_state(state.scoreSheet); - reconstruction_missing("Game::store_game_state 006f9000: the versus rules (DeathmatchTypeBase slot 1 and its " - "StoreGameState)"); -} - // 009b5cb0 Closes the pause screen for a new run on Resume, with its paper's animation stopped, the options listed // again, My Stuff closed and the quit prompt reset. // The original also stops the full-size paper and resets fields of it, which pause_screen.h leaves out. @@ -615,11 +555,6 @@ void Game::Exit(bool) reconstruction_missing("Game::Exit 006fa0c0"); } -void Game::save_rewind_state(int) -{ - reconstruction_missing("Game::save_rewind_state 00705ee0"); -} - constexpr const char* BLOOM_SHADER = "Bloom"; constexpr const char* COLOR_MOD_SHADER = "ColorMod"; constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; diff --git a/src/game.h b/src/game.h index d762575..369b6bb 100644 --- a/src/game.h +++ b/src/game.h @@ -301,6 +301,7 @@ public: void Fadein(float speed, FadeIcon icon, KColor color); void SetColorModifier(const ColorModState& color, bool isLerp, float rate); void save_rewind_state(int leaveDoor); + void StartRoomTransition(RoomTransitionRequest request); void Fadeout(float speed, FadeOutTarget target, KColor color = kcolor_rgba(0, 0, 0, 1)); void store_game_state(GameState& state); static void Exit(bool isSaving); diff --git a/src/game_save.cpp b/src/game_save.cpp new file mode 100644 index 0000000..f2b2870 --- /dev/null +++ b/src/game_save.cpp @@ -0,0 +1,528 @@ +#include "game.h" +#include "game_state_player.h" +#include "entity_familiar.h" +#include "entity_npc.h" +#include "log.h" +#include "manager.h" +#include "platform.h" +#include "room.h" +#include + +constexpr int CHALLENGE_SPEED = 22; +constexpr int ENTITY_CHARGER = 23; +constexpr int CHARGER_MY_SHADOW = 1; +constexpr int FAMILIAR_WISP = 206; +constexpr int FAMILIAR_UMBILICAL_BABY = 240; +constexpr int FAMILIAR_FORGOTTEN_BODY = 900; +constexpr int COLLECTIBLE_VENTRICLE_RAZOR = 396; +constexpr int REWIND_DOOR_FRAMES = 15; +constexpr int ROOM_REF_MODE_SHIFT = 16; +constexpr int ROOM_REF_HALF_SHIFT = 16; +constexpr uint32_t ROOM_FLAG_SAVED = 0x40; +constexpr uint32_t ROOM_REF_FLAGGED = 0x20000000; +constexpr uint32_t ROOM_REF_MIRRORED = 0x40000000; +constexpr uint32_t ROOM_REF_MERGED = 0x80000000; + +// The versus rules each kind of match plays, as its slot 1 answers. +static const std::array, DEATHMATCH_VENOM> DEATHMATCH_TYPE_RULES = {{ + {&typeid(DeathmatchTypeNormal), DEATHMATCH_NORMAL}, + {&typeid(DeathmatchTypeIpecac), DEATHMATCH_IPECAC}, + {&typeid(DeathmatchTypeBomberman), DEATHMATCH_BOMBERMAN}, + {&typeid(DeathmatchTypeLudovico), DEATHMATCH_LUDOVICO}, + {&typeid(DeathmatchTypeSumo), DEATHMATCH_SUMO}, + {&typeid(DeathmatchTypeKnockout), DEATHMATCH_KNOCKOUT}, + {&typeid(DeathmatchTypeSwordFight), DEATHMATCH_SWORD_FIGHT}, + {&typeid(DeathmatchTypeMachineGun), DEATHMATCH_MACHINE_GUN}, + {&typeid(DeathmatchTypeIndigestion), DEATHMATCH_INDIGESTION}, + {&typeid(DeathmatchTypeKnifeFight), DEATHMATCH_KNIFE_FIGHT}, + {&typeid(DeathmatchTypeVenom), DEATHMATCH_VENOM}, +}}; + +// Saves the versus rules as DeathmatchTypeBase::StoreGameState does: which kind of match the run drew (each type's +// slot 1) and its players. +// Offline no player ever joins a match, so its player set stays empty. A run without rules saves none. +static void versus_store(DeathmatchManager& manager, GameState& state) +{ + state.versusPlayers.clear(); + if (!manager.type) return; + + DeathmatchTypeBase* type = manager.type.get(); + const std::type_info& drawn = typeid(*type); + for (auto [info, rules] : DEATHMATCH_TYPE_RULES) + if (*info == drawn) state.versusRules = (uint8_t)rules; +} + +// 006f9000 Copies the run into a game state to save: its rules and seeds, the counters and histories of the run, the +// item and boss pools, the TMTRAINER seeds, the floor (after leaving the room), the players, the Ascent's saved +// stages, the nightmare stage bar, the ambush wave, the score and the versus rules. +// The saved flags are the first 53 of the run's state flags. +void Game::store_game_state(GameState& state) +{ + state.Clear(); + state.seeds = seedEffects; + state.playerManagerSeed = playerManager.rng._seed; + state.fortuneSeed = fortuneRNG._seed; + state.challenge = (int)challenge; + state.isRerun = isRerun; + state.isConsoleUsedThisRun = isConsoleUsedThisRun; + state.difficulty = difficulty; + state.gameStateFlags = std::bitset(gameStateFlags); + + state.lastDevilRoomStage = lastDevilRoomStage; + state.treasureRoomsVisited = treasureRoomsVisited; + state.planetariumsVisited = planetariumsVisited; + state.stagesWithoutHeartsPicked = stagesWithoutHeartsPicked; + state.stagesWithoutDamage = stagesWithoutDamage; + state.devilRoomDeals = devilRoomDeals; + state.shopVisits = shopVisits; + state.donationModGreed = donationModGreed; + state.donationModAngel = donationModAngel; + state.reviveMachineCoinsLeft = reviveMachineCoinsLeft; + state.reviveMachineUses = reviveMachineUses; + state.bossRushParTime = bossRushParTime; + state.blueWombParTime = blueWombParTime; + state.frameCount = frameCount; + state.timeCounter = timeCounter; + state.stageNameNumeral = stageNameNumeral; + state.victoryLap = victoryLap; + state.lastLevelWithoutHalfHp = lastLevelWithoutHalfHp; + state.lastLevelWithDamage = lastLevelWithDamage; + state.encounteredBosses = encounteredBosses; + state.pixelationTimer = pixelationTimer; + state.pixelationDuration = pixelationDuration; + state.magicSkinUses = magicSkinUses; + state.erasedEntities = erasedEntities; + itemPool.StoreGameState(state.itemPool); + bossPool.store_game_state(state.bossPool); + if (!proceduralItemManager.proceduralItems.empty()) + reconstruction_missing("Game::store_game_state 006f9000: the TMTRAINER items' seeds (ProceduralItem +0x8)"); + + room->on_leave(); + Level::store_game_state(state); + playerManager.store_game_state(&state); + + state.isAscent = ascentTimer > 0; + state.backwardsStages = backwardsStages; + state.deathCertificateExitTimer = deathCertificateExitTimer; + state.nightmareStageIcons = g_manager->nightmareScene.stageIcons; + state.isAmbushActive = ambush._isActive; + state.ambushWave = ambush._currentWave > 0 ? ambush._currentWave - 1 : ambush._currentWave; + scoreSheet.store_state(state.scoreSheet); + versus_store(deathmatchManager, state); +} + +// 00705ee0 Saves the run for the Glowing Hourglass as the players enter a room, by the door they leave it through. +// A door left again within 15 frames of entering (or the same door) keeps the saved state. Saving the room again keeps +// its devil deal stage, and a new room flips to the other slot, the old one remembering the door it was left by. +void Game::save_rewind_state(int leaveDoorSlot) +{ + if (isStoringGlowingHourglassState || isRestoringGlowingHourglassState || isPocketItemRewindSaved) return; + + int slot = 0; + bool isSameRoom = false; + if (currentGlowingHourglassSlot >= 0 && glowingHourglassStates[currentGlowingHourglassSlot].isUsable) + { + GlowingHourglassState& current = glowingHourglassStates[currentGlowingHourglassSlot]; + isSameRoom = current.gameState.currentRoomIdx == currentRoomIdx && current.gameState.stage == stage; + slot = isSameRoom ? currentGlowingHourglassSlot : 1 - currentGlowingHourglassSlot; + if (!isSameRoom) current.gameState.enterDoor = leaveDoor; + if (isSameRoom && leaveDoorSlot >= 0) + { + bool isRecent = (uint32_t)(frameCount - current.timeCounter) < REWIND_DOOR_FRAMES; + if (leaveDoorSlot == current.leaveDoor || (current.leaveDoor >= 0 && isRecent)) return; + } + } + + currentGlowingHourglassSlot = slot; + isStoringGlowingHourglassState = true; + GlowingHourglassState& state = glowingHourglassStates[slot]; + int keptDevilRoomStage = state.gameState.lastDevilRoomStage; + store_game_state(state.gameState); + if (isSameRoom) state.gameState.lastDevilRoomStage = keptDevilRoomStage; + + state.isUsable = true; + state.leaveDoor = leaveDoorSlot; + state.timeCounter = frameCount; + state.eventCounters = g_manager->persistentGameData.eventCounters; + isStoringGlowingHourglassState = false; +} + +// 00747360 Names a room's config for a saved run: its stage, mode, mirroring and flag 0x40 packed with its type and +// variant, or for a merged room its shape, with its halves appended to the merged configs. Without that list a merged +// room is left as it was. +void room_config_ref_save(RoomConfig_Room& config, RoomConfigRef& ref, std::vector* mergedConfigs) +{ + if (!(config.flags & ROOM_FLAG_MERGED)) + { + ref.packed = (uint32_t)(uint8_t)config.mode << ROOM_REF_MODE_SHIFT | (uint32_t)config.stageId; + if (config.flags & ROOM_FLAG_MIRRORED) ref.packed |= ROOM_REF_MIRRORED; + if (config.flags & ROOM_FLAG_SAVED) ref.packed |= ROOM_REF_FLAGGED; + ref.type = config.type; + ref.variant = config.variant; + return; + } + if (!mergedConfigs) return; + + ref.packed = ROOM_REF_MERGED; + ref.type = config.shape; + ref.variant = 0; + for (size_t i = 0; i < config.mergedData.size(); i++) + { + size_t index = mergedConfigs->size(); + RoomConfigRef half; + + ref.variant |= (uint32_t)(uint16_t)index << (ROOM_REF_HALF_SHIFT * i); + mergedConfigs->push_back({}); + room_config_ref_save(*config.mergedData[i], half, mergedConfigs); + (*mergedConfigs)[index] = half; + } +} + +// 00747e10 Copies the floor into a game state: its stage, curses, flags and Greed waves, its seeds, the 13x13 maps, every +// room descriptor (006f8d60, a plain copy) with its config named apart (its config pointer cleared), the rooms the +// players are in and came from, the room's watch speed and slowdown, the Ventricle Razor portals and bombs spawned. +// The Speed! challenge saves the watch as fast. +void Level::store_game_state(GameState& state) +{ + state.stage = stage; + state.stageType = stageType; + state.startingRoomIdx = startingRoomIdx; + state.lastBossRoomListIdx = lastBossRoomListIdx; + state.curses = curses; + state.isBossChallenge = isBossChallenge; + state.levelStateFlags = std::bitset(levelStateFlags); + state.greedModeWave = greedModeWave; + state.greedWaveSeeds = greedWaveSeeds; + state.greedModeTreasureRoomIdx = greedModeTreasureRoomIdx; + state.greedLastBeatenWave = greedLastBeatenWave; + state.greedLastPaidWave = greedLastPaidWave; + state.isHeartPicked = isHeartPicked; + state.isDevilRoomDisabled = isDevilRoomDisabled; + state.isCanSeeEverything = isCanSeeEverything; + state.dungeonPlacementSeed = dungeonPlacementSeed; + state.devilAngelRoomSeed = devilAngelRoomRNG._seed; + state.angelRoomChance = angelRoomChance; + state.bombPickupsSpawned = bombPickupsSpawned; + state.roomMap = roomMap; + + state.mergedRoomConfigs.clear(); + state.roomCount = nbRooms; + state.rooms.resize(ROOM_DESCRIPTOR_COUNT); + for (int i = 0; i < ROOM_DESCRIPTOR_COUNT; i++) + { + SavedRoom& saved = state.rooms[i]; + if (roomList[i].data) room_config_ref_save(*roomList[i].data, saved.config, &state.mergedRoomConfigs); + saved.desc = roomList[i]; + saved.desc.data = nullptr; + } + + state.currentRoomIdx = currentRoomIdx; + state.lastRoomIdx = lastRoomIdx; + state.brokenWatchState = g_game->challenge == CHALLENGE_SPEED ? BROKEN_WATCH_FAST : room->brokenWatchState; + state.slowdownDuration = room->slowdownDuration; + state.currentDimensionIdx = (uint8_t)currentDimensionIdx; + state.lastRoomDimensionIdx = (uint8_t)lastRoomDimensionIdx; + state.dungeonReturnPosition = dungeonReturnPosition; + state.dungeonReturnRoomIndex = dungeonReturnRoomIndex; + state.enterDoor = enterDoor; + state.ventricleRazorPortals = ventricleRazorPortals; +} + +// 009bd150 Copies the players into a game state, each leaving the room first unless the Glowing Hourglass saves: +// every main player, then its backup player (marked as one), up to 8, then the Esau Jr. players. The first player +// also keeps the glitched baby seed and the random babies. Each player learns its place in the save. +// A player that leaving the room removed from the list is skipped. +void PlayerManager::store_game_state(GameState* state) +{ + bool isRewind = g_game->isStoringGlowingHourglassState; + std::vector& players = state->players; + + // Whether every place is taken, which the original logs. + auto is_full = [&]() + { + bool isFull = players.size() >= GAME_STATE_PLAYER_LIMIT; + if (isFull) log_printf(LOG_WARN, "Number of players exceeds supported player limit (%d)!\n", GAME_STATE_PLAYER_LIMIT); + return isFull; + }; + // Saves a player into the next place. + auto player_store = [&](Entity_Player& player) + { + player.glowingHourglassIndex = (int)players.size(); + player.StoreGameState(&players.emplace_back(), true); + }; + + players.clear(); + for (size_t i = 0; i < playerList.size(); i++) + { + Entity_Player* player = playerList[i]; + size_t count = playerList.size(); + if (player->variant != PLAYER_VARIANT_PLAYER) continue; + if (is_full()) break; + + if (!isRewind) player->room_exit(true); + if (playerList.size() < count) + { + i--; + continue; + } + player_store(*player); + + Entity_Player* backup = player->backupPlayer; + if (!backup) continue; + if (is_full()) break; + if (!isRewind) backup->room_exit(true); + player_store(*backup); + players.back().isBackupPlayer = true; + } + + for (size_t i = 0; i < esauJrState.size(); i++) + { + GameStatePlayer& slot = state->esauJrStates[i]; + if (esauJrState[i]) esauJrState[i]->StoreGameState(&slot, true); + else slot.playerType = -1; + } + + if (players.empty()) return; + GameStatePlayer& first = players.front(); + first.glitchBabySeed = (int)glitchBabyRng._seed; + first.randomBabies = randomBabies; + first.randomBabyCount = randomBabyCount; +} + +// 007b0b40 A co-op baby's or sub player's character (a baby's skin) and hearts, a baby without eternal hearts. +static CoPlayerState co_player_save(Entity_Player& player) +{ + bool isBaby = player.variant == PLAYER_VARIANT_COOP_BABY; + return {.blackHearts = player.blackHearts, + .boneHearts = player.boneHearts, + .boneHeartsMask = player.boneHeartsMask, + .brokenHearts = player.brokenHearts, + .eternalHearts = isBaby ? 0 : player.eternalHearts, + .goldenHearts = player.goldenHearts, + .maxHearts = player.maxHearts, + .playerType = isBaby ? player.babySkin : player.playerType, + .redHearts = player.redHearts, + .rottenHearts = player.rottenHearts, + .soulHearts = player.soulHearts}; +} + +// 006d0370 A charmed enemy as a player keeps it: its kind, champion and health, and whether a player controls it. +static EntityDesc charmed_enemy_save(Entity_NPC& npc) +{ + return {.health = npc.health, + .maxHealth = npc.maxHitPoints, + .subtype = (uint32_t)npc.subtype, + .type = (uint32_t)npc.type, + .variant = (uint32_t)npc.variant, + .championId = npc.championColorIdx, + .isPlayerControlled = npc.IsFriendly() && npc.controllerID != -1}; +} + +// The seeds of a player's item RNGs. +static void rng_seeds_save(std::vector& rngs, std::vector& seeds) +{ + seeds.clear(); + for (RNG& rng : rngs) seeds.push_back(rng._seed); +} + +// Whether a familiar follows its player into a saved run: not the Forgotten's body, Ventricle Razor's wisp or the +// Umbilical Baby, and a temporary one only when those are saved. +static bool is_familiar_saved(Entity_Familiar& familiar, bool isSaveTemporaryFamiliars) +{ + bool isRazorWisp = familiar.variant == FAMILIAR_WISP && familiar.subtype == COLLECTIBLE_VENTRICLE_RAZOR; + if (familiar.variant == FAMILIAR_FORGOTTEN_BODY || isRazorWisp || familiar.variant == FAMILIAR_UMBILICAL_BABY) + return false; + return isSaveTemporaryFamiliars || !familiar.isNotCountedAsFollower; +} + +// 007b0be0 Copies the player into a saved player: its character, health and consumables, its sub player and the co-op +// babies that belong to the first player, history, stats and counters, items, pockets and their RNGs, costumes, the +// Moving Box, the friendly enemies it charmed (up to 10, the first twin only), its familiars and persistent effects. +// The fields the curated player does not have yet keep their defaults: the candy heart and soul locket stat ups, the +// soul charge, the last pill color, the kill counter, the crafting pool, the later poop spells and their counters, +// the last collectible frame and the unknown fields. Its Echo Chamber items are saved without their kind, and its +// voided passives without their second word. The unlisted restore state is never set, so familiars come from the room. +void Entity_Player::StoreGameState(GameStatePlayer* saveState, bool isSaveTemporaryFamiliars) +{ + GameStatePlayer& state = *saveState; + Game& game = *g_game; + PlayerManager& players = game.playerManager; + + state.controllerIndex = controllerIndex; + state.isHolyMantle = holyMantleState != 0; + state.playerType = playerType; + state.redHearts = redHearts; + state.maxHearts = maxHearts; + state.soulHearts = soulHearts; + state.blackHearts = blackHearts; + state.boneHearts = boneHearts; + state.boneHeartsMask = boneHeartsMask; + state.eternalHearts = eternalHearts; + state.subPlayer.reset(); + if (subPlayer) state.subPlayer = co_player_save(*subPlayer); + + state.coopBabies.clear(); + for (Entity_Player* baby : players.playerList) + { + bool isOwnBaby = baby->variant == PLAYER_VARIANT_COOP_BABY && !baby->parent.get() && players.GetPlayer(0) == this; + if (isOwnBaby) state.coopBabies.push_back(co_player_save(*baby)); + } + state.history = history.historyItems; + state.inventory = inventory; + + state.jarHearts = jarHearts; + state.jarFlies = jarFlies; + state.numCoins = numCoins; + state.numKeys = numKeys; + state.numBombs = numBombs; + state.hasGoldenKey = hasGoldenKey; + state.hasGoldenBomb = hasGoldenBomb; + state.monkeyPawCounter = (int16_t)monkeyPawCounter; + state.totalDamageTaken = (int16_t)totalDamageTaken; + state.speedModifier = speedModifier; + state.fireDelayModifier = fireDelayModifier; + state.damageModifier = damageModifier; + state.tearRangeModifier = tearRangeModifier; + state.shotSpeedModifier = shotSpeedModifier; + state.luckModifier = luckModifier; + state.donateLuck = donateLuck; + state.potatoPeelerCounter = potatoPeelerCounter; + state.potatoPeelerBandageCounter = potatoPeelerBandageCounter; + state.brittleBonesUpgrades = brittleBonesUpgrades; + state.redStewBonusDuration = redStewBonusDuration; + state.brokenHearts = brokenHearts; + state.rottenHearts = rottenHearts; + state.effectiveSoulCharge = effectiveSoulCharge; + state.urnSouls = urnSouls; + state.numGigaBombs = numGigaBombs; + state.rockBottomDamage = rockBottomDamage; + state.rockBottomMaxFireDelay = rockBottomMaxFireDelay; + state.rockBottomLuck = rockBottomLuck; + state.rockBottomTearRange = rockBottomTearRange; + state.rockBottomMoveSpeed = rockBottomMoveSpeed; + state.rockBottomShotSpeed = rockBottomShotSpeed; + state.reverseEmpressMaxHearts = reverseEmpressMaxHearts; + state.reverseSunBoneHearts = reverseSunBoneHearts; + state.forgottenBodyRoomIdx = forgottenBodyRoomIdx; + state.forgottenBodyPos = forgottenBodyPos; + state.maggyHealthDrainCooldown = maggyHealthDrainCooldown; + state.echoChamberItems.clear(); + for (int item : echoChamberItems) state.echoChamberItems.push_back({.id = item}); + std::copy(bagOfCraftingContent.begin(), bagOfCraftingContent.end(), state.bagOfCraftingContent.begin()); + std::copy(poopSpellQueue.begin(), poopSpellQueue.end(), state.poopSpellQueue.begin()); + state.poopMana = poopMana; + state.effectiveBloodCharge = effectiveBloodCharge; + state.itemCards = itemCards; + state.modelingClayEffect = modelingClayEffect; + state.keepersSackBonus = keepersSackBonus; + state.isLevelStartPending = isLevelStartPending; + state.hasCurseMistEffect = hasCurseMistEffect; + state.consumablesBackup = consumablesBackup; + state.curseMistFamiliars.clear(); + for (Entity_Familiar* familiar : curseMistFamiliars) familiar->store_backup(&state.curseMistFamiliars.emplace_back()); + state.curseMistRedHearts = curseMistRedHearts; + state.curseMistPocketItems = curseMistPocketItems; + state.curseMistTrinkets = curseMistTrinkets; + state.isCoopGhost = isCoopGhost; + state.ghostPocketItems = ghostPocketItems; + state.ghostTrinkets = ghostTrinkets; + state.wildCardItemType = wildCardItemType; + state.wildCardItem = wildCardItem; + state.wildCardVarData = wildCardVarData; + state.samsonBerserkCharge = samsonBerserkCharge; + state.ibsCharge = ibsCharge; + + Entity* owner = parent.get(); + if (owner && owner->type == ENTITY_PLAYER) state.parentIndex = static_cast(owner)->glowingHourglassIndex; + Entity* esau = darkEsau.get(); + state.darkEsauHealth = !esau || esau->health <= 0 ? 0 : esau->health; + state.proceduralItems = proceduralItems; + + state.edenSpeed = edenSpeed; + state.edenFireDelay = edenFireDelay; + state.edenDamage = edenDamage; + state.edenTearRange = edenTearRange; + state.edenShotSpeed = edenShotSpeed; + state.edenLuck = edenLuck; + state.vampireCharmKills = vampireCharmKills; + state.activeItems = activeItems; + state.tonsilCounter = tonsilCounter; + state.tonsilCount = tonsilCount; + state.numLeprosy = numLeprosy; + state.playerSpriteScale = playerSpriteScale; + if (variant == PLAYER_VARIANT_PLAYER && !isCoopGhost) + { + state.headScale = headScale; + state.bodyScale = bodyScale; + } + state.pocketItems = pocketItems; + state.playerForms = playerForms; + state.playerFormsRewarded = playerFormsRewarded; + state.collectibleCounts = collectibleCounts; + state.voidedCollectibles = voidedCollectibles; + state.voidedPassives.clear(); + for (int passive : voidedPassives) state.voidedPassives.push_back({.id = passive}); + state.trinkets = trinkets; + state.costumes.clear(); + for (CostumeSpriteDesc& costume : costumeSpriteDescs) state.costumes.push_back({costume.item->id, costume.item->type}); + state.movingBoxContents = movingBoxContents; + rng_seeds_save(collectibleRNGs, state.collectibleRngSeeds); + rng_seeds_save(trinketRNGs, state.trinketRngSeeds); + rng_seeds_save(pillRNGs, state.pillRngSeeds); + rng_seeds_save(cardRNGs, state.cardRngSeeds); + state.pillEffectUses = pillEffectUses; + state.rUaWizardTimer = rUaWizardTimer; + state.bloodLustCounter = bloodLustCounter; + state.deadCatLives = deadCatLives; + state.friendBallEnemy = friendBallEnemy; + state.purityState = purityState; + state.immaculateConceptionState = immaculateConceptionState; + state.cambionConceptionState = cambionConceptionState; + state.conceptionFamiliarFlags = conceptionFamiliarFlags; + state.d8DamageModifier = d8DamageModifier; + state.d8SpeedModifier = d8SpeedModifier; + state.d8RangeModifier = d8RangeModifier; + state.d8FireDelayModifier = d8FireDelayModifier; + state.goldenHearts = goldenHearts; + state.planCKillCountdown = planCKillCountdown; + state.imExcitedSpeedupCountdown = imExcitedSpeedupCountdown; + + std::vector& entities = game.room->entityList.updateEL; + Entity_Player* twin = static_cast(twinPlayer.get()); + bool isFirstTwin = !twin || twin->playerIndex == -1 || playerIndex <= twin->playerIndex || twin == this; + state.charmedEnemies.clear(); + for (size_t i = 0; !replacedPlayer && isFirstTwin && i < entities.size(); i++) + { + if (state.charmedEnemies.size() >= SAVED_CHARMED_ENEMY_LIMIT) break; + Entity_NPC* npc = dynamic_cast(entities[i]); + if (!npc || !npc->IsFriendly() || npc->IsBoss()) continue; + if (npc->type == ENTITY_CHARGER && npc->variant == 0 && npc->subtype == CHARGER_MY_SHADOW) continue; + + bool isMine = npc->controllerID == -1 ? playerIndex == 0 : controllerIndex == npc->controllerID; + if (isMine) state.charmedEnemies.push_back(charmed_enemy_save(*npc)); + } + + state.familiars.clear(); + for (Entity* entity : entities) + { + if (entity->type != ENTITY_FAMILIAR) continue; + Entity_Familiar& familiar = *static_cast(entity); + if (familiar.player == this && is_familiar_saved(familiar, isSaveTemporaryFamiliars)) + familiar.store_backup(&state.familiars.emplace_back()); + } + state.levelEffectItems = levelEffectItems; + bool isBleedingOut = (flags & FLAG_BLEED_OUT) && bleedSource.entity == this; + state.bleedOutHealth = isBleedingOut ? bleedOutHealth : 0; + state.greedsGulletHearts = greedsGulletHearts; + state.greedsGulletOverflow = greedsGulletOverflow; + + state.persistentEffects.clear(); + for (TemporaryEffect& effect : temporaryEffects.effects) + if (effect.item && effect.item->isPersistentEffect) + state.persistentEffects.push_back({effect.cooldown, effect.count, effect.item->id, (int)effect.item->type}); + state.holyMantleStacks = holyMantleStacks; + state.ductTapeMode = (uint8_t)ductTapeMode; + state.queuedItem = queuedItem; + state.temporaryEffects = temporaryEffects.effects; + state.strengthMaxHearts = strengthMaxHearts; +} diff --git a/src/game_state.cpp b/src/game_state.cpp index 24bd4ea..33602eb 100644 --- a/src/game_state.cpp +++ b/src/game_state.cpp @@ -1,17 +1,53 @@ #include "game_state.h" +#include "game_state_player.h" #include "log.h" -#include "persistent_game_data.h" #include "platform.h" +#include +#include #include +#include // The header a saved run starts with (version 169, with its terminator), and the key its checksum is scrambled with. constexpr char SAVE_HEADER[] = "ISAACNG_GSR0169"; constexpr uint32_t CHECKSUM_KEY = 0x96696996; +constexpr int ERASED_ENEMY_LIMIT = 255; +constexpr int SAVED_COUNTER_MAX = 255; +constexpr int SEED_STRING_LENGTH = 9; +constexpr int SPECIAL_SEED_BYTES = SPECIAL_SEED_COUNT / 8; +constexpr uint16_t ROOM_MAP_EMPTY_RUN = 0x8000; +constexpr uint32_t HISTORY_TRINKET = 0x1000000; +constexpr uint32_t HISTORY_NEGATIVE = 0x2000000; +constexpr uint8_t WRITE_HAS_EXTRA_DATA = 1; +constexpr uint8_t WRITE_HAS_CHILD = 2; +constexpr uint8_t WRITE_GOLDEN_KEY = 1; +constexpr uint8_t WRITE_GOLDEN_BOMB = 2; +constexpr uint8_t WRITE_LEVEL_START_PENDING = 2; +constexpr uint8_t WRITE_CURSE_MIST = 4; +constexpr int ROOM_UNSET_WORDS = 8; + +// An Esau Jr. slot without a player. +static GameStatePlayer esau_jr_empty() +{ + GameStatePlayer player; + player.playerType = -1; + return player; +} + +GameState::GameState() : esauJrStates(ESAU_JR_STATE_COUNT, esau_jr_empty()) {} +GameState::GameState(const GameState& other) = default; +GameState::GameState(GameState&& other) noexcept = default; +GameState& GameState::operator=(const GameState& other) = default; +GameState& GameState::operator=(GameState&& other) noexcept = default; +GameState::~GameState() = default; + // 009c79a0 Empties the saved run and drops both availabilities, keeping the files it is saved to. void GameState::Clear() { - *this = {.rerunPath = std::move(rerunPath), .savePath = std::move(savePath)}; + GameState cleared; + cleared.rerunPath = std::move(rerunPath); + cleared.savePath = std::move(savePath); + *this = std::move(cleared); } // 009c8350 Removes the saved run's file, warning when there is none named, and empties the run. @@ -31,28 +67,479 @@ void GameState::DeleteRerun() } // A saved run as it is written: its bytes, and the checksum (CRC-32 from Checksum's seed) over all of them after the -// header. +// header. Each part of the run has its writer, in the original's order and widths. +// The checksum folds bytes one at a time, so a block written at once sums as its values written one by one. struct StateWriter { std::vector bytes; Checksum checksum; - void write_bytes(std::span data) + // Appends bytes and folds them into the checksum. + void bytes_write(std::span data) { bytes.insert(bytes.end(), data.begin(), data.end()); checksum.Update(data); } - template void write(Value value) { write_bytes({(const uint8_t*)&value, sizeof(Value)}); } + // Appends a value as its bytes. + template void write(Value value) { bytes_write({(const uint8_t*)&value, sizeof(Value)}); } + + // Appends each value of a list as a type of the original's width. + template void each_write(const List& values) + { + for (auto value : values) write((Width)value); + } + + // 009d84d0 Appends a list's length and its values as 32-bit words. + template void list_write(const List& values) + { + write((uint32_t)values.size()); + each_write(values); + } + + // 009c85d0 Appends a bit list's length (16 bits), then its bits eight to a byte from the lowest. + template void bits_write(const Bits& bits) + { + uint16_t count = (uint16_t)bits.size(); + uint8_t packed = 0; + + write(count); + for (int i = 0; i < count; i++) + { + if (bits[i]) packed |= 1 << (i % 8); + if (i % 8 < 7) continue; + write(packed); + packed = 0; + } + if (count % 8) write(packed); + } + + void entity_write(const EntitySaveState& entity); + void room_write(const SavedRoom& room); + void co_player_write(const CoPlayerState& player); + void consumables_write(const ConsumableData& data); + void familiars_write(const std::vector& familiars); + void pockets_write(const std::array& pockets); + void player_write(const GameStatePlayer& player); + void item_pool_write(const GameStateItemPool& pool); + void score_write(const ScoreRecord& score); }; +// 009c88e0 Writes a saved entity: its kind, storage fields and seeds, then which of the extra bytes and the carried +// entity follow, and those. +void StateWriter::entity_write(const EntitySaveState& entity) +{ + for (uint32_t value : {(uint32_t)entity.type, (uint32_t)entity.variant, (uint32_t)entity.subtype, + entity.intStorage1, entity.intStorage2, entity.intStorage3}) + write(value); + write(entity.byteStorage); + write(entity.intStorage4); + write(entity.intStorage5); + write((uint8_t)entity.boolStorage1); + for (uint32_t value : {entity.intStorage6, std::bit_cast(entity.targetPosition.x), + std::bit_cast(entity.targetPosition.y), entity.intStorage7, entity.initSeed, + entity.dropSeed, (uint32_t)entity.spawnerType, (uint32_t)entity.spawnerVariant}) + write(value); + write(entity.int64Storage); + write((uint8_t)entity.boolStorage2); + write(entity.floatStorage1); + write(entity.floatStorage2); + write(entity.gridSpawnIdx); + write(entity.floatStorage3); + write(entity.intStorage8); + + write((uint8_t)((entity.extraData ? WRITE_HAS_EXTRA_DATA : 0) | (entity.child ? WRITE_HAS_CHILD : 0))); + if (entity.extraData) bytes_write(*entity.extraData); + if (entity.child) entity_write(*entity.child); +} + +// 009c8d20 Writes a saved room: its config (009c87e0), its place on the map and doors, what happened in it, its seeds, +// its grid cells (with the details of the ones holding something), its saved entities, restricted cells and effects, +// its shop indices, group and Tainted Keeper's coin count. +// A merged config's two 16-bit indices are the bytes of its variant word, so every config is three words. +// The original's words at 0x94..0xab are never set, so they are written as zeros. +void StateWriter::room_write(const SavedRoom& room) +{ + const RoomDescriptor& desc = room.desc; + + for (uint32_t value : {room.config.packed, room.config.type, room.config.variant}) write(value); + for (int value : {desc.gridIndex, desc.safeGridIndex, desc.listIndex}) write((uint16_t)value); + write((uint8_t)desc.dimension); + write(desc.allowedDoors); + each_write(desc.doors); + for (uint32_t value : {desc.displayFlags, (uint32_t)desc.visitedCount, desc.flags}) write(value); + write(desc.clearCount); + write(desc.totalMoneySpent); + for (uint32_t value : {(uint32_t)desc.greedSubType, (uint32_t)desc.pitsCount, desc.decorationSeed, desc.spawnSeed, + desc.awardSeed, desc.bossDeathSeed}) + write(value); + + for (const GridEntityDesc& cell : desc.savedGridEntities) + { + write((uint16_t)cell._type); + if (!cell._type) continue; + write(cell._variant); + write(cell._state); + write((uint16_t)cell._spawnCount); + write(cell._spawnSeed); + write(cell._variableSeed); + write(cell._varData); + } + + write((uint32_t)desc.savedEntities.size()); + for (const EntitySaveState& entity : desc.savedEntities) entity_write(entity); + list_write(desc.restrictedGridIndexes); + write((uint32_t)desc.savedEffects.size()); + for (const EntitySaveState& entity : desc.savedEffects) entity_write(entity); + + write(desc.shopItemDiscountIdx); + write(desc.shopItemIdx); + each_write(std::array{}); + each_write(std::array{}); + write(desc.group); + write(desc.tKeeperCoinSpawns); +} + +// 009d0100 Writes a co-op baby or sub player: its character and hearts (16 bits each), then its black hearts and bone +// heart mask, then its broken and rotten hearts. +void StateWriter::co_player_write(const CoPlayerState& player) +{ + for (int value : {player.playerType, player.redHearts, player.maxHearts, player.soulHearts, player.eternalHearts, + player.goldenHearts, 0, player.boneHearts}) + write((uint16_t)value); + write(player.blackHearts); + write(player.boneHeartsMask); + write((uint16_t)player.brokenHearts); + write((uint16_t)player.rottenHearts); +} + +// 009d0440 Writes the consumables Curse of the Mist set aside (16 bits each) and the golden key and bomb. +// The original loses the golden key's bit when the golden bomb is set too, which this keeps. +void StateWriter::consumables_write(const ConsumableData& data) +{ + for (int value : {data.coins, data.keys, data.bombs}) write((uint16_t)value); + write((uint8_t)(data.isGoldenBomb ? WRITE_GOLDEN_BOMB : data.isGoldenKey ? WRITE_GOLDEN_KEY : 0)); + for (int value : {data.soulCharges, data.gigaBombs, data.poopMana, data.bloodCharges}) write((uint16_t)value); +} + +// Writes a list of familiars, each with its seeds, kind, counters, offset and health. +void StateWriter::familiars_write(const std::vector& familiars) +{ + write((uint32_t)familiars.size()); + for (const FamiliarData& familiar : familiars) + { + for (int value : {(int)familiar.initSeed, familiar.variant, familiar.subtype, familiar.coins, familiar.hearts, + familiar.keys, familiar.state, familiar.roomClearCount}) + write(value); + write(familiar.formationTargetOffset.x); + write(familiar.formationTargetOffset.y); + write(familiar.health); + write(familiar.dropSeed); + write((uint8_t)familiar.isNotCountedAsFollower); + write((uint8_t)familiar.isSubtype55555); + } +} + +// Writes pocket slots, each as its kind (a byte) and id. +void StateWriter::pockets_write(const std::array& pockets) +{ + for (const PocketItem& pocket : pockets) + { + write((uint8_t)pocket.type); + write(pocket.id); + } +} + +// The bits of a history entry: a trinket's flag and a negative id's, over the id's magnitude. +static uint32_t history_id_pack(const HistoryItem& item) +{ + uint32_t flags = (item.isTrinket ? HISTORY_TRINKET : 0) | (item.id < 0 ? HISTORY_NEGATIVE : 0); + return (uint32_t)std::abs(item.id) | flags; +} + +// A count the original saves as a byte, clamped to one. +static uint8_t counter_byte(int value) +{ + return (uint8_t)std::clamp(value, 0, SAVED_COUNTER_MAX); +} + +// 009d45c0 Writes a saved player in the original's order: health and consumables, stats, items and their charges, +// pockets, forms, item lists and RNGs, PlayerManager's babies, charmed enemies and boxed entities, familiars and co-op +// babies, counters, persistent effects, crafting and spells, Curse of the Mist and ghost backups, history, inventory and +// the Echo Chamber's items (twice, the second time as words). +// The Echo Chamber's type is written as a word whose padding the original leaves unset. It is zero here. +void StateWriter::player_write(const GameStatePlayer& player) +{ + for (int value : {player.playerType, player.redHearts, player.maxHearts, player.soulHearts, player.blackHearts, + player.eternalHearts, player.jarHearts, player.jarFlies, player.numCoins, player.numKeys, + player.numBombs}) + write(value); + write((uint8_t)player.hasGoldenKey); + write((uint8_t)player.hasGoldenBomb); + write(player.monkeyPawCounter); + write(player.totalDamageTaken); + write((uint8_t)(player.isHolyMantle | (player.isLevelStartPending ? WRITE_LEVEL_START_PENDING : 0) | + (player.hasCurseMistEffect ? WRITE_CURSE_MIST : 0))); + for (int16_t value : {player.tonsilCounter, player.tonsilCount, player.numLeprosy}) write(value); + for (int value : {player.planCKillCountdown, (int)player.imExcitedSpeedupCountdown, player.lastPillColor, + player.boneHearts, player.boneHeartsMask, player.speedModifier, player.fireDelayModifier, + player.damageModifier, player.tearRangeModifier, player.shotSpeedModifier, player.luckModifier, + player.donateLuck, player.potatoPeelerCounter, player.potatoPeelerBandageCounter}) + write(value); + for (float value : {player.edenSpeed, player.edenFireDelay, player.edenDamage, player.edenTearRange, + player.edenShotSpeed, player.edenLuck}) + write(value); + write(player.vampireCharmKills); + write(player.killCounter); + + for (const ActiveItemDesc& active : player.activeItems) + for (int value : {active.item, active.unknown, active.charge, active.batteryCharge, active.partialCharge, + active.varData}) + write(value); + for (float value : {player.playerSpriteScale.x, player.playerSpriteScale.y, player.headScale.x, + player.headScale.y, player.bodyScale.x, player.bodyScale.y}) + write(value); + pockets_write(player.pocketItems); + each_write(player.playerForms); + write(player.playerFormsRewarded); + list_write(player.collectibleCounts); + list_write(player.voidedCollectibles); + write((uint32_t)player.voidedPassives.size()); + for (const VoidedPassive& passive : player.voidedPassives) + { + write((uint16_t)passive.id); + write((uint16_t)passive.value); + } + each_write(player.trinkets); + write((uint32_t)player.costumes.size()); + for (const CostumeItem& costume : player.costumes) + { + write(costume.type); + write(costume.id); + } + for (auto* seeds : {&player.collectibleRngSeeds, &player.trinketRngSeeds, &player.pillRngSeeds, + &player.cardRngSeeds}) + list_write(*seeds); + list_write(player.pillEffectUses); + + write(player.glitchBabySeed); + write(player.randomBabyCount); + each_write(player.randomBabies); + write(player.rUaWizardTimer); + write(player.bloodLustCounter); + write(player.deadCatLives); + const EntityDesc& ball = player.friendBallEnemy; + for (uint32_t value : {ball.type, ball.variant, ball.subtype, (uint32_t)ball.championId}) write(value); + write(ball.health); + write(ball.maxHealth); + write((uint32_t)player.charmedEnemies.size()); + for (const EntityDesc& enemy : player.charmedEnemies) + { + for (uint32_t value : {enemy.type, enemy.variant, enemy.subtype, (uint32_t)enemy.championId}) write(value); + write(enemy.health); + write(enemy.maxHealth); + write((uint8_t)enemy.isPlayerControlled); + } + write((uint32_t)player.movingBoxContents.size()); + for (const EntitySaveState& entity : player.movingBoxContents) entity_write(entity); + + for (int value : {player.purityState, player.immaculateConceptionState, player.cambionConceptionState, + (int)player.conceptionFamiliarFlags}) + write(value); + for (float value : {player.d8DamageModifier, player.d8SpeedModifier, player.d8RangeModifier, + player.d8FireDelayModifier}) + write(value); + for (int value : {player.goldenHearts, 0, 0}) write(value); + familiars_write(player.familiars); + write((uint8_t)player.coopBabies.size()); + for (const CoPlayerState& baby : player.coopBabies) co_player_write(baby); + write((uint8_t)player.subPlayer.has_value()); + if (player.subPlayer) co_player_write(*player.subPlayer); + + write(player.brittleBonesUpgrades); + write(player.bleedOutHealth); + write((uint16_t)player.greedsGulletHearts); + write(player.greedsGulletOverflow); + for (int value : {player.redStewBonusDuration, player.brokenHearts, player.rottenHearts, + player.effectiveSoulCharge}) + write(value); + each_write(player.candyHeartStatUps); + each_write(player.soulLocketStatUps); + write(player.unknownCounter); + for (int value : {player.soulCharge, player.numGigaBombs, (int)player.urnSouls}) write(counter_byte(value)); + for (float value : {player.rockBottomMoveSpeed, player.rockBottomMaxFireDelay, player.rockBottomDamage, + player.rockBottomTearRange, player.rockBottomShotSpeed, player.rockBottomLuck}) + write(value); + write(player.reverseEmpressMaxHearts); + write((uint16_t)player.persistentEffects.size()); + for (const PersistentEffect& effect : player.persistentEffects) + for (int value : {effect.type, effect.id, effect.count, effect.cooldown}) write(value); + write(player.reverseSunBoneHearts); + write(player.unknownTimer); + write((uint16_t)player.unknownValue); + write(player.forgottenBodyRoomIdx); + write(player.forgottenBodyPos.x); + write(player.forgottenBodyPos.y); + write(player.lastCollectibleFrame); + write(player.maggyHealthDrainCooldown); + + uint8_t echoCount = (uint8_t)player.echoChamberItems.size(); + write(echoCount); + for (int i = 0; i < echoCount; i++) + { + write((uint8_t)player.echoChamberItems[i].type); + write(player.echoChamberItems[i].id); + } + each_write(player.bagOfCraftingContent); + write(player.bagOfCraftingOutput); + write(player.bagOfCraftingPool); + std::span spells = player.poopSpellQueue; + bytes_write(spells.first(POOP_SPELL_QUEUE_SIZE)); + write((uint8_t)(POOP_SPELL_SLOTS - POOP_SPELL_QUEUE_SIZE)); + bytes_write(spells.subspan(POOP_SPELL_QUEUE_SIZE)); + write(player.poopSpellCounter); + write(player.poopMana); + write(player.poopSpellFloat); + write(player.effectiveBloodCharge); + for (int value : {player.isBackupPlayer ? -1 : 0, player.parentIndex, 0}) write(value); + write(player.darkEsauHealth); + + consumables_write(player.consumablesBackup); + familiars_write(player.curseMistFamiliars); + write(player.curseMistRedHearts); + pockets_write(player.curseMistPocketItems); + each_write(player.curseMistTrinkets); + write((uint8_t)player.isCoopGhost); + pockets_write(player.ghostPocketItems); + each_write(player.ghostTrinkets); + write(player.samsonBerserkCharge); + write(player.ibsCharge); + write(player.holyMantleStacks); + write(player.ductTapeMode); + write(player.controllerIndex); + write((uint8_t)player.itemCards.size()); + each_write(std::span(player.itemCards).first((uint8_t)player.itemCards.size())); + write(player.modelingClayEffect); + write(player.keepersSackBonus); + write(player.wildCardItemType); + if (player.wildCardItemType != WILD_CARD_NONE) + { + write(player.wildCardItem); + write(player.wildCardVarData); + } + + write((uint32_t)player.history.size()); + for (const HistoryItem& item : player.history) + for (uint32_t value : {history_id_pack(item), (uint32_t)item.levelStage, (uint32_t)item.stageType, + (uint32_t)item.roomType, (uint32_t)item.itemPoolType, (uint32_t)item.time}) + write(value); + auto last = std::find_if(player.inventory.rbegin(), player.inventory.rend(), [](int id) { return id >= 0; }); + uint8_t inventoryCount = (uint8_t)(player.inventory.rend() - last); + write(inventoryCount); + each_write(std::span(player.inventory).first(inventoryCount)); + write((uint8_t)player.levelEffectItems.size()); + each_write(std::span(player.levelEffectItems).first((uint8_t)player.levelEffectItems.size())); + write((uint32_t)player.proceduralItems.size()); + for (auto [key, value] : player.proceduralItems) + { + write((uint16_t)key); + write((uint16_t)value); + } + write((uint32_t)player.echoChamberItems.size()); + for (const PocketItem& item : player.echoChamberItems) + { + write(item.id); + write((uint32_t)item.type); + } +} + +// 009cec80 Writes the item pools: each pool's weights, the Bible's chances, the seeds and the last pool, the removed +// collectibles and the trinkets still in the pool (a byte each), the pill colors and the Genesis counts. +void StateWriter::item_pool_write(const GameStateItemPool& pool) +{ + for (const std::vector& weights : pool.poolsItemWeights) + { + write((uint32_t)weights.size()); + each_write(weights); + } + each_write(pool.bibleUpgrades); + for (uint32_t value : {pool.seed, (uint32_t)pool.lastPool, pool.itemPoolRNGseed, pool.trinketPoolRNGseed}) + write(value); + write(pool.unkFloat674); + write(pool.unkFloat678); + for (const std::vector* bits : {&pool.removedCollectibles, &pool.trinketPoolItems}) + { + write((uint32_t)bits->size()); + each_write(*bits); + } + each_write(pool.pillEffects); + each_write(pool.identifiedPillEffects); + each_write(pool.remainingGenesisItems); +} + +// 009d77e0 Writes the score's record: the furthest floor and its time, the points, the ending, the rooms entered and +// cleared, the boss challenges and angels, and the floors finished and played again. +void StateWriter::score_write(const ScoreRecord& score) +{ + for (int value : {score.runTimeLevel, score.runTimeLevelType, score.runTime, score.pickupPoints, score.enemyPoints, + (int)score.runEnding}) + write(value); + for (const std::vector* rooms : {&score.visitedRooms, &score.clearedRooms}) + { + write((uint32_t)rooms->size()); + for (const RoomScore& room : *rooms) + { + write(room.type); + write((uint8_t)room.isRedRoom); + write(room.multiplier); + } + } + write(score.bossChallengesCleared); + write(score.angelsKilled); + for (const std::vector* stages : {&score.finishedStages, &score.replayedStages}) + { + write((uint32_t)stages->size()); + for (const StageVisit& visit : *stages) + { + write(visit.stage); + write(visit.stageType); + write((uint8_t)visit.isAscent); + } + } +} + +// The map's cells packed for saving: each room index, and each run of empty cells as its length minus one over +// ROOM_MAP_EMPTY_RUN. +static std::vector room_map_pack(const std::array& roomMap) +{ + std::vector packed; + uint16_t emptyRun = 0; + + for (int roomIdx : roomMap) + { + if (roomIdx < 0) + { + emptyRun++; + continue; + } + if (emptyRun) packed.push_back((emptyRun - 1) | ROOM_MAP_EMPTY_RUN); + emptyRun = 0; + packed.push_back((uint16_t)roomIdx); + } + if (emptyRun) packed.push_back((emptyRun - 1) | ROOM_MAP_EMPTY_RUN); + return packed; +} + // 009c9340 Writes the saved run in the original's format: the unchecked header, then the run's rules, flags and -// counters, the ambush and the score, the floor, the players, the pools, the seeds, the histories, the Ascent's stages -// and the versus rules, closed by the checksum of everything after the header, scrambled. -// The format is written up to the score sheet so far. The rest waits for the floor's and the players' states. +// counters, the ambush and the score, the floor and its rooms, the players and the Esau Jr. players, the pools, the seed +// and the special seeds, the histories, the Ascent's stages and the versus rules, closed by the checksum of everything +// after the header, scrambled. More than 255 erased enemies are cut to 255, as the original does. +// The Death Certificate floor's way back, which Game does not keep yet, is written as the original's defaults. +// The original's rooms are a fixed array, so a state Level never stored writes default rooms. std::vector GameState::write() { StateWriter writer; + rooms.resize(ROOM_DESCRIPTOR_COUNT); writer.bytes.assign(SAVE_HEADER, SAVE_HEADER + sizeof(SAVE_HEADER)); writer.write(challenge); @@ -62,7 +549,6 @@ std::vector GameState::write() writer.write(difficulty); writer.write((uint16_t)gameStateFlags.size()); for (size_t i = 0; i < gameStateFlags.size(); i++) writer.write((uint8_t)gameStateFlags[i]); - for (int counter : {lastDevilRoomStage, treasureRoomsVisited, planetariumsVisited, stagesWithoutHeartsPicked, stagesWithoutDamage, devilRoomDeals, shopVisits, donationModGreed, donationModAngel, reviveMachineCoinsLeft, reviveMachineUses, bossRushParTime, blueWombParTime, frameCount, @@ -70,7 +556,105 @@ std::vector GameState::write() writer.write(counter); writer.write((uint8_t)isAmbushActive); writer.write(ambushWave); - reconstruction_missing("GameState::write 009c9340: the score sheet (write_score_sheet 009d77e0) and on"); + writer.score_write(scoreSheet); + + for (uint32_t value : {stage, stageType, (uint32_t)startingRoomIdx, (uint32_t)lastBossRoomListIdx, curses, + dungeonPlacementSeed, devilAngelRoomSeed, std::bit_cast(angelRoomChance)}) + writer.write(value); + for (bool flag : {isHeartPicked, isDevilRoomDisabled, isCanSeeEverything, isBossChallenge}) + writer.write((uint8_t)flag); + writer.write((uint16_t)levelStateFlags.size()); + for (size_t i = 0; i < levelStateFlags.size(); i++) writer.write((uint8_t)levelStateFlags[i]); + writer.write(greedModeWave); + writer.each_write(greedWaveSeeds); + for (int value : {(int)greedModeTreasureRoomIdx, greedLastBeatenWave, greedLastPaidWave}) writer.write(value); + writer.each_write(nightmareStageIcons); + + writer.write((uint32_t)mergedRoomConfigs.size()); + for (const RoomConfigRef& config : mergedRoomConfigs) + for (uint32_t value : {config.packed, config.type, config.variant}) writer.write(value); + writer.write(roomCount); + for (int i = 0; i < roomCount; i++) writer.room_write(rooms[i]); + for (int i = ROOM_MAP_CELLS; i < ROOM_DESCRIPTOR_COUNT; i++) writer.room_write(rooms[i]); + std::vector packedMap = room_map_pack(roomMap); + writer.write((uint16_t)packedMap.size()); + writer.each_write(packedMap); + + writer.write(currentRoomIdx); + writer.write(currentDimensionIdx); + writer.write(lastRoomDimensionIdx); + writer.write(lastRoomIdx); + writer.write(brokenWatchState); + writer.write(slowdownDuration); + writer.write(dungeonReturnPosition.x); + writer.write(dungeonReturnPosition.y); + for (int value : {dungeonReturnRoomIndex, -1, 0, 0}) writer.write(value); + writer.write((uint8_t)0); + writer.write((uint8_t)0); + writer.write(enterDoor); + for (const VentricleRazorPortal& portal : ventricleRazorPortals) + { + writer.write(portal.roomIndex); + writer.write(portal.gridIndex); + writer.write((uint8_t)portal.isMarked); + } + writer.write(bombPickupsSpawned); + writer.write(0); + writer.write((uint8_t)0); + + writer.write((uint8_t)players.size()); + for (const GameStatePlayer& player : players) writer.player_write(player); + writer.write((uint8_t)esauJrStates.size()); + for (const GameStatePlayer& player : esauJrStates) + { + writer.write((uint8_t)(player.playerType != -1)); + if (player.playerType != -1) writer.player_write(player); + } + writer.item_pool_write(itemPool); + + if (!seeds.gameStartSeed) log_printf(LOG_ASSERT, "Error: Game Start Seed was not set.\n"); + std::string seedString = Seeds::Seed2String(seeds.gameStartSeed); + seedString.resize(SEED_STRING_LENGTH); + writer.bytes_write({(const uint8_t*)seedString.data(), seedString.size()}); + std::array specialSeeds{}; + for (int i = 0; i < SPECIAL_SEED_COUNT; i++) + if (seeds.HasSeedEffect(i)) specialSeeds[i / 8] |= 1 << (i % 8); + writer.write((uint8_t)specialSeeds.size()); + writer.bytes_write(specialSeeds); + for (uint32_t value : {playerManagerSeed, fortuneSeed, (uint32_t)lastLevelWithDamage}) writer.write(value); + + writer.write((uint32_t)encounteredBosses.size()); + for (const BossId& boss : encounteredBosses) + { + writer.write(boss.type); + writer.write(boss.variant); + } + writer.bits_write(bossPool.removedBosses); + writer.write((uint16_t)bossPool.rngSeeds.size()); + writer.each_write(bossPool.rngSeeds); + writer.write(magicSkinUses); + if (erasedEntities.size() > ERASED_ENEMY_LIMIT) erasedEntities.resize(ERASED_ENEMY_LIMIT); + writer.write((uint8_t)erasedEntities.size()); + for (const ErasedEnemy& enemy : erasedEntities) + for (int value : {enemy.type, enemy.variant, enemy.subtype}) writer.write(value); + writer.write((uint16_t)pixelationTimer); + writer.write((uint16_t)pixelationDuration); + writer.write((uint8_t)isAscent); + + for (const BackwardsStageDesc& backwards : backwardsStages) + { + writer.write((uint8_t)backwards.stageType); + for (const std::vector* stageRooms : {&backwards.bossRooms, &backwards.treasureRooms}) + { + writer.write((uint8_t)stageRooms->size()); + for (const SavedRoom& room : *stageRooms) writer.room_write(room); + } + writer.write((uint8_t)backwards.isXL); + } + writer.write((uint16_t)deathCertificateExitTimer); + writer.list_write(proceduralItemSeeds); + writer.write(versusRules); + writer.list_write(versusPlayers); checksum = writer.checksum.value_get(); uint32_t sealed = checksum ^ CHECKSUM_KEY; diff --git a/src/game_state.h b/src/game_state.h index 40d0fb4..fe20ee1 100644 --- a/src/game_state.h +++ b/src/game_state.h @@ -1,8 +1,11 @@ #pragma once #include "boss_pool.h" +#include "entity_save_state.h" #include "item_pool.h" +#include "level.h" #include "nightmare_scene.h" +#include "persistent_game_data.h" #include "score_sheet.h" #include "seeds.h" #include @@ -13,6 +16,8 @@ #include constexpr int BACKWARDS_STAGE_COUNT = 7; +constexpr int ESAU_JR_STATE_COUNT = 4; +constexpr int LEVEL_STATE_FLAG_COUNT = 26; // How many of the run's state flags a saved run keeps. constexpr int SAVED_GAME_STATE_FLAG_COUNT = 53; @@ -31,12 +36,41 @@ struct ErasedEnemy int variant = 0; }; +// A room config as a saved run names it (GameStateRoomConfig): its stage and mode packed with two of its flags, then +// its type and variant. A merged room is a flag with its shape, and its halves' indices among the merged configs packed +// in the last word. +struct RoomConfigRef +{ + uint32_t packed = 0; + uint32_t type = 0; + uint32_t variant = 0; +}; + +// A saved room: its descriptor and the config it was laid out from. +struct SavedRoom +{ + RoomDescriptor desc; + RoomConfigRef config; +}; + +// The rooms a Backwards Path stage keeps for the Ascent: its boss and treasure rooms with their configs, its stage type +// and whether it was XL. Copies (006f8a40) are the defaults. +struct BackwardsStageDesc +{ + std::vector bossRooms; + std::vector treasureRooms; + uint32_t stageType = 0; + bool isXL = false; +}; + // A save slot's saved run (gamestate.dat), to continue from the menus, and its rerun (rep+rerunstate.dat), // the last run's character and seed to play again. -// Modelled so far: what the menus read and what Game::store_game_state copies itself (the run's rules, seeds, -// counters and histories, the boss pools, the Ascent's saved stages). The floor's rooms and the players come with -// Level's and PlayerManager's stores, and the file format with read and write. -// Construction and destruction (009c73c0, 009c7800) are the defaults. +// It keeps the run's rules, seeds, counters and histories, the floor and its rooms, the players, the pools, the +// Ascent's saved stages and the versus rules, as Game::store_game_state copies them, and write saves them in the +// original's format. +// Its rooms are every room descriptor of the floor once Level stored them. The Esau Jr. players are always four, a +// player type of -1 for an empty one. +// Construction and destruction (009c73c0, 009c7800) are the defaults, defined where GameStatePlayer is complete. // Steam Cloud is offline, so the cloud file names are dropped. struct GameState { @@ -45,27 +79,47 @@ struct GameState GameStateItemPool itemPool{}; ScoreRecord scoreSheet{}; std::array backwardsStages{}; + std::array ventricleRazorPortals{}; + std::array roomMap{}; std::array nightmareStageIcons{}; + std::array greedWaveSeeds{}; std::bitset gameStateFlags{}; - std::vector encounteredBosses{}; - std::vector erasedEntities{}; - std::vector proceduralItemSeeds{}; + std::bitset levelStateFlags{}; + std::vector esauJrStates; + std::vector players; + std::vector rooms; + std::vector mergedRoomConfigs; + std::vector encounteredBosses; + std::vector erasedEntities; + std::vector proceduralItemSeeds; + std::vector versusPlayers; std::string rerunPath; std::string savePath; + Vector dungeonReturnPosition{}; + float angelRoomChance = 0; int ambushWave = 0; int blueWombParTime = 0; + int bombPickupsSpawned = 0; int bossRushParTime = 0; int challenge = 0; + int currentRoomIdx = 0; int deathCertificateExitTimer = 0; int devilRoomDeals = 0; int difficulty = 0; int donationModAngel = 0; int donationModGreed = 0; + int dungeonReturnRoomIndex = 0; + int enterDoor = 0; int frameCount = 0; + int greedLastBeatenWave = 0; + int greedLastPaidWave = 0; + int greedModeWave = 0; + int lastBossRoomListIdx = 0; int lastDevilRoomStage = 0; int lastLevelWithDamage = 0; int lastLevelWithoutHalfHp = 0; + int lastRoomIdx = 0; int magicSkinUses = 0; int pixelationDuration = 0; int pixelationTimer = 0; @@ -73,25 +127,49 @@ struct GameState int playerType = 0; int reviveMachineCoinsLeft = 0; int reviveMachineUses = 0; + int roomCount = 0; int shopVisits = 0; + int slowdownDuration = 0; int stageNameNumeral = 0; int stagesWithoutDamage = 0; int stagesWithoutHeartsPicked = 0; + int startingRoomIdx = 0; int timeCounter = 0; int treasureRoomsVisited = 0; int victoryLap = 0; uint32_t checksum = 0; + uint32_t curses = 0; + uint32_t devilAngelRoomSeed = 0; + uint32_t dungeonPlacementSeed = 0; uint32_t fortuneSeed = 0; + uint32_t greedModeTreasureRoomIdx = 0; uint32_t playerManagerSeed = 0; + uint32_t stage = 0; + uint32_t stageType = 0; + uint8_t brokenWatchState = 0; + uint8_t currentDimensionIdx = 0; + uint8_t lastRoomDimensionIdx = 0; + uint8_t versusRules = 0; bool isAmbushActive = false; bool isAscent = false; + bool isBossChallenge = false; + bool isCanSeeEverything = false; bool isConsoleUsedThisRun = false; + bool isDevilRoomDisabled = false; + bool isHeartPicked = false; bool isModded = false; bool isRerun = false; bool isRerunAvailable = false; bool isSaveAvailable = false; + GameState(); + GameState(const GameState& other); + GameState(GameState&& other) noexcept; + GameState& operator=(const GameState& other); + GameState& operator=(GameState&& other) noexcept; + ~GameState(); + void Clear(); void Delete(); void DeleteRerun(); @@ -99,3 +177,16 @@ struct GameState bool read_rerun(std::span file); std::vector write(); }; + +// The run as the Glowing Hourglass can rewind it: the game state as the players entered a room, the door they left +// the room before by, the frame it was saved on and the event counters then. +struct GlowingHourglassState +{ + GameState gameState; + std::array eventCounters{}; + int leaveDoor = 0; + int timeCounter = 0; + bool isUsable = false; +}; + +void room_config_ref_save(RoomConfig_Room& config, RoomConfigRef& ref, std::vector* mergedConfigs); diff --git a/src/game_state_player.h b/src/game_state_player.h new file mode 100644 index 0000000..61005cd --- /dev/null +++ b/src/game_state_player.h @@ -0,0 +1,236 @@ +#pragma once + +#include "anm2.h" +#include "entity_player.h" +#include "entity_save_state.h" +#include +#include +#include +#include +#include + +constexpr int CANDY_HEART_STATS = 6; +constexpr int GAME_STATE_PLAYER_LIMIT = 8; +constexpr int POOP_SPELL_SLOTS = 26; +constexpr int SAVED_CHARMED_ENEMY_LIMIT = 10; +constexpr int SAVED_RANDOM_BABIES = 5; +constexpr int SAVE_FORGOTTEN_BODY_ROOM_NONE = -100000; +constexpr int SAVE_MONKEY_PAW_CHARGES = 3; +constexpr float SAVE_ROCK_BOTTOM_LUCK_UNSET = -9999; + +// A familiar as it follows its player into a saved run or through Curse of the Mist (FamiliarData). +struct FamiliarData +{ + Vector formationTargetOffset{}; + float health = 0; + int coins = 0; + int hearts = 0; + int keys = 0; + int roomClearCount = 0; + int state = 0; + int subtype = 0; + int variant = 0; + uint32_t dropSeed = 0; + uint32_t initSeed = 0; + bool isNotCountedAsFollower = false; + bool isSubtype55555 = false; +}; + +// A co-op baby or a sub player, by its character and health. +struct CoPlayerState +{ + int blackHearts = 0; + int boneHearts = 0; + int boneHeartsMask = 0; + int brokenHearts = 0; + int eternalHearts = 0; + int goldenHearts = 0; + int maxHearts = 0; + int playerType = 0; + int redHearts = 0; + int rottenHearts = 0; + int soulHearts = 0; +}; + +// A temporary effect that lasts the run, by its item's type and id. +struct PersistentEffect +{ + int cooldown = 0; + int count = 0; + int id = 0; + int type = 0; +}; + +// An item a costume shows, by its type and id. +struct CostumeItem +{ + int id = 0; + int type = 0; +}; + +// A passive the Void absorbed. Its second word is only ever copied. +struct VoidedPassive +{ + int id = 0; + int value = 0; +}; + +// A player as a saved run keeps it (GameStatePlayer): its character, health and consumables, its items and their RNGs, +// stats and the counters items keep, the familiars and charmed enemies that follow it, and its co-op babies. +// The first player also keeps PlayerManager's glitched baby seed and random babies. +// Init (009cf050) is the defaults, as are copies and destruction (00754d90). +// The words at 0x36c, 0x370 and 0x514 of the original are saved but never set, so they are written as 0. +// The unknown fields are saved and restored, but what the original keeps in them is not known yet. +struct GameStatePlayer +{ + std::vector history; + std::vector coopBabies; + std::vector costumes; + std::vector charmedEnemies; + std::vector movingBoxContents; + std::vector curseMistFamiliars; + std::vector familiars; + std::vector persistentEffects; + std::vector echoChamberItems; + std::vector temporaryEffects; + std::vector voidedPassives; + std::vector collectibleCounts; + std::vector itemCards; + std::vector levelEffectItems; + std::vector pillEffectUses; + std::vector voidedCollectibles; + std::vector cardRngSeeds; + std::vector collectibleRngSeeds; + std::vector pillRngSeeds; + std::vector trinketRngSeeds; + std::map proceduralItems; + std::optional subPlayer; + + std::array activeItems{}; + std::array curseMistPocketItems{}; + std::array ghostPocketItems{}; + std::array pocketItems{}; + std::array inventory{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + std::array playerForms{}; + std::array randomBabies{}; + std::array curseMistTrinkets{}; + std::array ghostTrinkets{}; + std::array trinkets{}; + std::array candyHeartStatUps{}; + std::array soulLocketStatUps{}; + std::array bagOfCraftingContent{}; + std::array poopSpellQueue{}; + ConsumableData consumablesBackup; + EntityDesc friendBallEnemy; + QueueItemData queuedItem; + + Vector bodyScale = vector_make(1, 1); + Vector forgottenBodyPos{}; + Vector headScale = vector_make(1, 1); + Vector playerSpriteScale = vector_make(1, 1); + float d8DamageModifier = 1; + float d8FireDelayModifier = 1; + float d8RangeModifier = 1; + float d8SpeedModifier = 1; + float darkEsauHealth = 0; + float edenDamage = 0; + float edenFireDelay = 0; + float edenLuck = 0; + float edenShotSpeed = 0; + float edenSpeed = 0; + float edenTearRange = 0; + float ibsCharge = 0; + float poopSpellFloat = 0; + float rockBottomDamage = 0; + float rockBottomLuck = SAVE_ROCK_BOTTOM_LUCK_UNSET; + float rockBottomMaxFireDelay = 0; + float rockBottomMoveSpeed = 0; + float rockBottomShotSpeed = 0; + float rockBottomTearRange = 0; + int bagOfCraftingOutput = 0; + int bagOfCraftingPool = -1; + int blackHearts = 0; + int bleedOutHealth = 0; + int boneHearts = 0; + int boneHeartsMask = 0; + int brokenHearts = 0; + int cambionConceptionState = 0; + int controllerIndex = 0; + int curseMistRedHearts = 0; + int damageModifier = 0; + int donateLuck = 0; + int effectiveBloodCharge = 0; + int effectiveSoulCharge = 0; + int eternalHearts = 0; + int fireDelayModifier = 0; + int forgottenBodyRoomIdx = SAVE_FORGOTTEN_BODY_ROOM_NONE; + int glitchBabySeed = 0; + int goldenHearts = 0; + int greedsGulletHearts = 0; + int immaculateConceptionState = 0; + int jarFlies = 0; + int jarHearts = 0; + int keepersSackBonus = 0; + int killCounter = 0; + int lastCollectibleFrame = -1; + int lastPillColor = 0; + int luckModifier = 0; + int maxHearts = 0; + int modelingClayEffect = 0; + int numBombs = 0; + int numCoins = 0; + int numGigaBombs = 0; + int numKeys = 0; + int parentIndex = -1; + int planCKillCountdown = 0; + int playerType = 0; + int poopMana = 0; + int potatoPeelerBandageCounter = 0; + int potatoPeelerCounter = 0; + int purityState = 0; + int rUaWizardTimer = 0; + int randomBabyCount = 0; + int redHearts = 0; + int redStewBonusDuration = 0; + int reverseEmpressMaxHearts = 0; + int reverseSunBoneHearts = 0; + int rottenHearts = 0; + int samsonBerserkCharge = 0; + int shotSpeedModifier = 0; + int soulCharge = 0; + int soulHearts = 0; + int speedModifier = 0; + int strengthMaxHearts = 0; + int tearRangeModifier = 0; + int unknownCounter = 0; + int unknownTimer = -1; + int unknownValue = 0; + int wildCardItem = 0; + int wildCardVarData = 0; + uint32_t conceptionFamiliarFlags = 0; + uint32_t imExcitedSpeedupCountdown = 0; + uint32_t maggyHealthDrainCooldown = 0; + uint32_t playerFormsRewarded = 0; + uint32_t urnSouls = 0; + uint32_t vampireCharmKills = 0; + int16_t bloodLustCounter = 0; + int16_t brittleBonesUpgrades = 0; + int16_t deadCatLives = 0; + int16_t greedsGulletOverflow = 0; + int16_t monkeyPawCounter = SAVE_MONKEY_PAW_CHARGES; + int16_t numLeprosy = 0; + int16_t tonsilCount = 0; + int16_t tonsilCounter = 0; + int16_t totalDamageTaken = 0; + uint8_t ductTapeMode = 0; + uint8_t holyMantleStacks = 0; + uint8_t poopSpellCounter = 0; + uint8_t wildCardItemType = WILD_CARD_NONE; + bool hasCurseMistEffect = false; + bool hasGoldenBomb = false; + bool hasGoldenKey = false; + bool isBackupPlayer = false; + bool isCoopGhost = false; + bool isHolyMantle = false; + bool isLevelStartPending = false; +}; diff --git a/src/game_transition.cpp b/src/game_transition.cpp new file mode 100644 index 0000000..fb37629 --- /dev/null +++ b/src/game_transition.cpp @@ -0,0 +1,432 @@ +#include "entity_player.h" +#include "game.h" +#include "grid_entity_door.h" +#include "log.h" +#include "manager.h" +#include "platform.h" +#include "room.h" +#include "seeds.h" +#include +#include +#include + +constexpr int ROOM_INDEX_MIN = -20; +constexpr int ROOM_INDEX_MAX = LEVEL_GRID_CELLS - 1; +constexpr int DIMENSION_MAX = 2; +constexpr int DEATH_CERTIFICATE_DIMENSION = 2; +constexpr int MIRROR_DIMENSION = 1; +constexpr int DOOR_SIDES = 4; +constexpr int SIDE_ACROSS = 2; +constexpr int STAGE_ID_HOME = 35; +constexpr int STAGE_ID_SPECIAL_ROOMS = 0; +constexpr uint32_t STAGE_CAVES_I = 3; +constexpr uint32_t STAGE_CAVES_II = 4; +constexpr int MINESHAFT_ENTRANCE_SUBTYPE = 10; +constexpr int MAZE_MOVE_CHANCE = 10; +constexpr int MAZE_SWAP_CHANCE = 5; +constexpr int MAZE_SHAKE_FRAMES = 30; +constexpr int SOUND_MAZE = 22; +constexpr float SOUND_MAZE_VOLUME = 0.5f; +constexpr int SOUND_ERROR_BUZZ = 187; +constexpr int SOUND_TELEPORT_UP = 215; +constexpr int ONLINE_STAT_ESCAPES = 9; +constexpr const char* ANIMATION_TELEPORT_UP = "TeleportUp"; +constexpr const char* ANIMATION_OPEN = "Open"; +constexpr uint32_t ROOM_DESCRIPTOR_FLAG_BLUE_REDIRECT = 1u << 18; +constexpr uint64_t GAME_STATE_BOSSPOOL_SWITCHED = 1ull << 4; +constexpr uint64_t GAME_STATE_KEY_FAMILIAR_DOOR_PASSED = 1ull << 49; +constexpr int BACKWARDS_FIRST_STAGE = 1; +constexpr int BACKWARDS_LAST_STAGE = 6; +constexpr uint32_t BLUE_ROOM_DOORS_ACROSS = 1u << DIRECTION_LEFT | 1u << DIRECTION_RIGHT; +constexpr uint32_t BLUE_ROOM_DOORS_DOWN = 1u << DIRECTION_UP | 1u << DIRECTION_DOWN; +constexpr int BLUE_ROOM_LONG_CHANCE = 4; +constexpr int BLUE_ROOM_DIFFICULTY_MAX = 10; +constexpr RNG BLUE_ROOM_RNG = {0, 5, 27, 28}; + +// The room indices the players leave without becoming the room they came from: the ones off the map that only lead on. +constexpr int ROOM_PASSAGE_IDX = -14; +constexpr int ROOM_PASSAGE_EXIT_IDX = -15; + +// Whether a room type hides behind a secret door. +static bool is_secret_type(int type) +{ + return type == ROOM_SECRET || type == ROOM_SUPERSECRET; +} + +// Shuffles room indices, a random swap from the back as the original's own shuffle does. +static void room_indices_shuffle(std::vector& indices) +{ + for (int i = (int)indices.size() - 1; i > 0; i--) std::swap(indices[i], indices[Random() % (uint32_t)(i + 1)]); +} + +// 006fd7c0 Checks a room transition and starts it. A versus match's fight only buzzes. The Glowing Hourglass on the +// first floor's untouched start room goes back to the menu's stage transition (in Greed, teleports to the error room). +// A teleport in the Beast's dungeon only moves the player. Leaving saves the rewind state (a teleport out of an +// uncleared challenge, a curse or the error room counts as an escape), and a walk into a Blue Key door's room enters +// the blue room in between. +void Game::StartRoomTransition(RoomTransitionRequest request) +{ + Entity_Player* player = request.player; + RoomTransitionAnim& animation = request.animation; + bool isStartRoom = currentRoomIdx == startingRoomIdx && room->isFirstVisit; + bool isSaved = false; + + if (request.roomIndex < ROOM_INDEX_MIN || request.roomIndex > ROOM_INDEX_MAX) + return log_printf(LOG_ERROR, "Invalid room index passed to Game::StartRoomTransition()\n"); + if ((uint32_t)animation > TRANSITION_TRAPDOOR) + return log_printf(LOG_ERROR, "Invalid animation passed to Game::StartRoomTransition()\n"); + if (request.dimension > DIMENSION_MAX) + return log_printf(LOG_ERROR, "Invalid dimension passed to Game::StartRoomTransition()\n"); + if (deathmatchManager.state == DEATHMATCH_FIGHT) return sound_play(SOUND_ERROR_BUZZ); + + if (animation == TRANSITION_GLOWING_HOURGLASS && stage == 1 && !IsAltPath() && isStartRoom) + { + if (!IsGreedMode()) + { + reconstruction_missing("Game::StartStageTransition 006fdc10, the Glowing Hourglass back to the stage start"); + if (!player) return; + player->PlayExtraAnimation(ANIMATION_TELEPORT_UP); + return sound_play(SOUND_TELEPORT_UP); + } + request.roomIndex = ROOM_ERROR_IDX; + animation = TRANSITION_TELEPORT; + } + if (request.roomIndex == ROOM_ERROR_IDX) request.dimension = 0; + + if (player && (animation == TRANSITION_TELEPORT || animation == TRANSITION_GLOWING_HOURGLASS)) + { + if (room->IsBeastDungeon()) + reconstruction_missing("Game::StartRoomTransition 006fd7c0: a teleport in the Beast's dungeon " + "(Room::GetRandomPosition, Entity_Player::Teleport 007cd950)"); + if (animation == TRANSITION_TELEPORT) + { + int type = room->roomType; + bool isGuarded = type == ROOM_CHALLENGE || type == ROOM_BOSSRUSH; + bool isEscape = isGuarded ? !room->IsClear() : type == ROOM_CURSE || type == ROOM_ERROR; + + if (isEscape) Player_stats_add(&onlinePlayerStats, ONLINE_STAT_ESCAPES, player, 1); + isSaved = true; + } + } + else if (!player && animation == TRANSITION_TELEPORT) isSaved = true; + + bool isStarted = false; + if (!isSaved && animation == TRANSITION_PORTAL_TELEPORT) isSaved = true; + else if (!isSaved && isStartRoom) + { + isStarted = animation == TRANSITION_GLOWING_HOURGLASS; + isSaved = !isStarted; + } + if (isSaved) save_rewind_state(DOOR_NONE); + + bool isSameDimension = request.dimension < 0 || request.dimension == currentDimensionIdx; + if (!isStarted && animation == TRANSITION_WALK && isSameDimension && + prepare_blue_room(currentRoomIdx, request.roomIndex, request.direction)) + request.roomIndex = ROOM_BLUE_ROOM_IDX; + + roomTransition.start(request); + if (roomTransition.is_versus_screen()) framesSinceRoomTransition = 0; + isRoomRespawned = false; +} + +// 0073d9b0 The slot a door side takes in a room, by the cell of the room it is seen from: the second row's side doors +// and the second column's top and bottom ones are 4 further. Checked, -1 when the room's layout has no such door. +int Level::get_door_slot(int roomIdx, int doorSlot, bool isChecked, int dimension) +{ + RoomDescriptor& desc = *g_game->GetRoomByIdx(roomIdx, dimension); + int offset = roomIdx < 0 ? 0 : roomIdx - desc.gridIndex; + bool isVertical = doorSlot == DIRECTION_UP || doorSlot == DIRECTION_DOWN; + bool isSide = doorSlot == DIRECTION_LEFT || doorSlot == DIRECTION_RIGHT; + + if ((isVertical && offset % LEVEL_GRID_WIDTH > 0) || (isSide && offset / LEVEL_GRID_WIDTH > 0)) doorSlot += DOOR_SIDES; + if (isChecked && !((desc.data->doors | desc.data->questDoors) >> doorSlot & 1)) return DOOR_NONE; + return doorSlot; +} + +// 0073da40 The slot the players come in by on a door side of a room: that side's door for the cell, else the first +// slot from the side across (going round) that the layout has a door or a quest door at. +int Level::GetTargetSlot(int roomIdx, int doorSlot) +{ + int slot = get_door_slot(roomIdx, doorSlot, true, -1); + if (slot != DOOR_NONE) return slot; + + RoomConfig_Room& data = *GetRoomByIdx(roomIdx)->data; + slot = doorSlot + DOOR_SIDES; + for (int attempt = 0; attempt < DOOR_SLOT_COUNT && !((data.doors | data.questDoors) >> slot & 1); attempt++) + slot = (slot + 1) % DOOR_SLOT_COUNT; + if (roomIdx >= 0 && !(data.doors >> slot & 1)) + log_printf(LOG_ASSERT, "Level::get_target_slot: Could not find a valid door slot for room idx %d\n", roomIdx); + return slot; +} + +// 0074d4a0 Readies the blue room a walk from a room on the map through a door into a room a Blue Key opened leads to +// first: a fresh descriptor seeded from the target's decoration seed, a blue room layout of the door's axis (one in +// four the long one, else any shape), with doors back to the room left and on to the target. False when no layout fits. +bool Level::prepare_blue_room(int fromRoomIdx, int targetRoomIdx, int direction) +{ + if (direction == DIRECTION_NONE || fromRoomIdx < 0) return false; + + RoomDescriptor& target = *GetRoomByIdx(targetRoomIdx); + if (!(target.flags & ROOM_DESCRIPTOR_FLAG_BLUE_REDIRECT)) return false; + + RoomDescriptor& blue = *GetRoomByIdx(ROOM_BLUE_ROOM_IDX); + RNG rng = BLUE_ROOM_RNG; + int listIndex = blue.listIndex; + bool isAcross = direction == DIRECTION_LEFT || direction == DIRECTION_RIGHT; + + rng._seed = target.decorationSeed; + blue = RoomDescriptor{}; + blue.listIndex = listIndex; + blue.gridIndex = ROOM_BLUE_ROOM_IDX; + blue.InitSeeds(rng); + + bool isLong = rng.RandomInt(BLUE_ROOM_LONG_CHANCE) == 0; + RoomQuery query = {.requiredDoors = isAcross ? BLUE_ROOM_DOORS_ACROSS : BLUE_ROOM_DOORS_DOWN, + .shape = isAcross ? (isLong ? ROOMSHAPE_IIH : ROOMSHAPE_2x1) : (isLong ? ROOMSHAPE_IIV : ROOMSHAPE_1x2), + .maxDifficulty = BLUE_ROOM_DIFFICULTY_MAX, + .minDifficulty = 1, + .stageId = STAGE_ID_SPECIAL_ROOMS, + .type = ROOM_BLUE}; + + blue.data = g_game->roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + if (!blue.data) + { + query.shape = ROOMSHAPE_ANY; + blue.data = g_game->roomConfig.GetRandomRoom(rng.Next(), WEIGHT_KEEP, query); + if (!blue.data) return false; + } + blue.allowedDoors = query.requiredDoors; + blue.doors[direction] = targetRoomIdx; + blue.doors[(direction + SIDE_ACROSS) % DOOR_SIDES] = fromRoomIdx; + return true; +} + +// Under the Curse of the Maze, one leave in ten lands in a random room within two doors of the target (not a secret +// or curse room) that has a door back toward the side left through to a room that is not secret. Returns whether it +// did, and the side the players then come in from. One leave in five swaps a visited room with a matching one. +static bool maze_move(Level& level, int& newRoomIdx, int& enterSide) +{ + bool isMoved = false; + + if (Random() % MAZE_MOVE_CHANCE == 0) + { + std::set nearby = level.get_rooms_within_two_doors(newRoomIdx); + std::vector candidates(nearby.begin(), nearby.end()); + + room_indices_shuffle(candidates); + for (int candidate : candidates) + { + RoomDescriptor& desc = *level.GetRoomByIdx(candidate); + int type = desc.data->type; + if (is_secret_type(type) || type == ROOM_CURSE || desc.gridIndex < 0) continue; + if (level.leaveDoor < 0) + { + level.currentRoomIdx = newRoomIdx = candidate; + log_printf(LOG_INFO, "Found a candidate without leave door\n"); + isMoved = true; + break; + } + + enterSide = (level.leaveDoor + SIDE_ACROSS) % DOOR_SIDES; + int slot = level.GetTargetSlot(candidate, enterSide); + if (slot % DOOR_SIDES != enterSide || !(desc.allowedDoors >> slot & 1)) continue; + if (is_secret_type(level.GetRoomByIdx(desc.doors[slot])->data->type)) continue; + + level.currentRoomIdx = newRoomIdx = candidate; + level.lastRoomIdx = desc.doors[slot]; + log_printf(LOG_INFO, "Found a candidate\n"); + isMoved = true; + break; + } + if (isMoved && g_game->roomTransition.animation == TRANSITION_WALK) + { + g_game->roomTransition.animation = TRANSITION_MAZE; + g_game->minimap.shakeDuration = MAZE_SHAKE_FRAMES; + int sound = SOUND_MAZE; + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, {.volume = SOUND_MAZE_VOLUME}); + } + } + if (Random() % MAZE_SWAP_CHANCE == 0) + { + std::vector order; + for (int i = 0; i < level.nbRooms; i++) order.push_back(i); + room_indices_shuffle(order); + for (int i : order) + { + RoomDescriptor& desc = level.roomList[i]; + if (desc.visitedCount == 0) continue; + + int match = level.find_matching_room_idx(desc.safeGridIndex); + if (match == -1) continue; + level.maze_swap_rooms(desc.safeGridIndex, match); + break; + } + } + return isMoved; +} + +// The side the players come in from without a door to go by: random for a room off the map, else facing the way from +// the room left, across or down by the larger step between their cells. +static int enter_side_guess(Level& level, int newRoomIdx) +{ + if (newRoomIdx < 0) return (int)(Random() & (DOOR_SIDES - 1)); + + int columns = level.currentRoomIdx % LEVEL_GRID_WIDTH - level.lastRoomIdx % LEVEL_GRID_WIDTH; + int rows = level.currentRoomIdx / LEVEL_GRID_WIDTH - level.lastRoomIdx / LEVEL_GRID_WIDTH; + if (std::abs(rows) < std::abs(columns)) return columns > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + return rows < 1 ? DIRECTION_DOWN : DIRECTION_UP; +} + +// The door the players come in by in the room just loaded: the one they entered through, else (or when a secret room's +// leads to a red room) the first door of a normal room from a random slot, else the last door seen there. None found, +// none. A secret door blows open from either side and closes again in a room not cleared, and a door back the way +// they came opens for good unless barred. +static void enter_door_open(Level& level, int previousType) +{ + Room& room = *level.room; + bool isSecret = is_secret_type(room.roomType); + auto isLeadingToRed = [&](GridEntity_Door* door) + { + RoomDescriptor* target = level.GetRoomByIdx(door->targetRoomIdx); + return target && (target->flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM); + }; + // The original reads the cell before the doors (the room's last grid cell) for no entry door. Here there is none. + GridEntity_Door* door = level.enterDoor >= 0 && level.enterDoor < DOOR_SLOT_COUNT ? room.doors[level.enterDoor] : nullptr; + + if (!door || (isSecret && isLeadingToRed(door))) + { + GridEntity_Door* fallback = nullptr; + uint32_t start = Random() & (DOOR_SLOT_COUNT - 1); + + door = nullptr; + for (int i = 0; i < DOOR_SLOT_COUNT; i++) + { + level.enterDoor = (int)((start + i) % DOOR_SLOT_COUNT); + door = room.doors[level.enterDoor]; + if (door && isSecret && isLeadingToRed(door)) door = nullptr; + if (!door) continue; + if (door->targetRoomType == ROOM_DEFAULT) break; + fallback = door; + } + if (!door) door = fallback; + if (!door) return; + } + + RoomDescriptor& current = *level.GetRoomByIdx(level.currentRoomIdx); + bool isFromSecret = door->targetRoomIdx == level.lastRoomIdx && is_secret_type(previousType); + if (isSecret || isFromSecret) + { + door->TryBlowOpen(false, nullptr); + if (!(current.flags & ROOM_DESCRIPTOR_FLAG_CLEAR) && door->state != DOOR_STATE_CLOSED) + { + door->state = DOOR_STATE_CLOSED; + door->UpdateAnimation(); + bool isHidden = is_secret_type(door->currentRoomType) || is_secret_type(door->targetRoomType) || + door->currentRoomType == ROOM_ULTRASECRET || door->targetRoomType == ROOM_ULTRASECRET; + if (isHidden) door->openAnimation = ANIMATION_OPEN; + } + } + if (current.visitedCount == 0 || door->targetRoomIdx != level.lastRoomIdx || door->variant == DOOR_LOCKED_BARRED) return; + if (door->variant == DOOR_LOCKED_KEYFAMILIAR) g_game->gameStateFlags |= GAME_STATE_KEY_FAMILIAR_DOOR_PASSED; + door->variant = DOOR_UNLOCKED; + door->UpdateAnimation(); +} + +// 0073fc80 Leaves the room for another (clamped to the room indices and dimensions): the room left is stored, the save +// file written when it changed, and the room left recorded unless it only led on. The Curse of the Maze may move the +// players elsewhere. The door they come in by is the one across from the door left, else guessed from the rooms' +// cells, or the same door going between the mirror worlds. Blue Key redirects behind the old room's doors are +// dropped, a mineshaft entrance marks its descent, the new room loads and its entry door opens, then the map updates. +void Level::ChangeRoom(int targetRoomIdx, int dimension) +{ + Game& game = *g_game; + PersistentGameData& persistent = g_manager->persistentGameData; + int newRoomIdx = std::clamp(targetRoomIdx, ROOM_INDEX_MIN, ROOM_INDEX_MAX); + + dimension = dimension < 0 ? -1 : std::min(dimension, DIMENSION_MAX); + room->on_leave(); + game.gameStateFlags |= GAME_STATE_BOSSPOOL_SWITCHED; + if (persistent.isChangesMade && persistent.isFileLoaded) + { + persistent.isChangesMade = false; + persistent.BackupSaveFile(); + persistent.Save(); + } + if (dimension < 0) dimension = currentDimensionIdx; + if (currentDimensionIdx == DEATH_CERTIFICATE_DIMENSION && dimension != DEATH_CERTIFICATE_DIMENSION) + reconstruction_missing("Level::ChangeRoom 0073fc80: the way back from the Death Certificate floor (Game " + "+0x18900..+0x18914 hold the room, dimension and door left)"); + + RoomDescriptor& target = *GetRoomByIdx(newRoomIdx, dimension); + bool isHomeDungeon = target.data && target.data->type == ROOM_DUNGEON && target.data->stageId == STAGE_ID_HOME; + if (currentDimensionIdx != dimension || isHomeDungeon) + for (VentricleRazorPortal& portal : ventricleRazorPortals) portal.roomIndex = PORTAL_ROOM_NONE; + + int oldRoomIdx = currentRoomIdx; + lastRoomDimensionIdx = currentDimensionIdx; + if (newRoomIdx == oldRoomIdx && dimension == currentDimensionIdx) + log_printf(LOG_INFO, "[warn] ChangeRoom() called with current room index\n"); + else + { + int previousIdx = lastRoomIdx; + bool isOldKept = oldRoomIdx >= 0 || oldRoomIdx == ROOM_DUNGEON_IDX || oldRoomIdx == ROOM_DEBUG_IDX || + oldRoomIdx == ROOM_GIDEON_DUNGEON_IDX || oldRoomIdx == ROOM_SECRET_SHOP_IDX; + bool isOldPassage = oldRoomIdx == ROOM_PASSAGE_IDX || oldRoomIdx == ROOM_PASSAGE_EXIT_IDX; + + if (newRoomIdx >= 0 ? !isOldPassage : isOldKept) lastRoomIdx = oldRoomIdx; + if (newRoomIdx == ROOM_PASSAGE_IDX) lastRoomIdx = previousIdx; + currentDimensionIdx = dimension; + currentRoomIdx = newRoomIdx; + currentRoomMap = &roomMap[dimension * LEVEL_GRID_CELLS]; + } + + bool isMazeMoved = false; + int enterSide = DIRECTION_NONE; + bool isMazeFloor = currentDimensionIdx != MIRROR_DIMENSION || !HasAbandonedMineshaft(); + if ((GetCurses() & CURSE_OF_MAZE) && currentRoomIdx >= 0 && lastRoomIdx >= 0 && + currentDimensionIdx == lastRoomDimensionIdx && isMazeFloor) + isMazeMoved = maze_move(*this, newRoomIdx, enterSide); + + int slotRoomIdx = newRoomIdx; + if (leaveDoor < 0 || (currentRoomIdx == lastRoomIdx && currentDimensionIdx == lastRoomDimensionIdx)) + enterSide = enter_side_guess(*this, newRoomIdx); + else if (enterSide == DIRECTION_NONE) + { + enterSide = (leaveDoor % DOOR_SIDES + SIDE_ACROSS) % DOOR_SIDES; + RoomDescriptor* previous = lastRoomIdx >= 0 ? GetRoomByIdx(lastRoomIdx, lastRoomDimensionIdx) : nullptr; + int neighbor = previous && (previous->data->doors >> leaveDoor & 1) ? previous->doors[leaveDoor] : -1; + + if (neighbor >= 0 && currentDimensionIdx == lastRoomDimensionIdx) + { + constexpr int CELL_STEPS[DOOR_SIDES] = {-1, -LEVEL_GRID_WIDTH, 1, LEVEL_GRID_WIDTH}; + lastRoomIdx = neighbor + CELL_STEPS[enterSide]; + if (currentRoomIdx >= 0 && (previous->allowedDoors >> leaveDoor & 1)) slotRoomIdx = currentRoomIdx = neighbor; + } + } + enterDoor = GetTargetSlot(slotRoomIdx, enterSide); + if (currentRoomIdx == lastRoomIdx && currentDimensionIdx != lastRoomDimensionIdx && HasMirrorDimension()) + enterDoor = leaveDoor; + + // The original reads the room left's layout unchecked. A room without one counts as no type here. + RoomConfig_Room* previousData = GetRoomByIdx(lastRoomIdx, lastRoomDimensionIdx)->data; + int previousType = previousData ? previousData->type : ROOM_NULL; + for (GridEntity_Door* door : room->doors) + if (door) GetRoomByIdx(door->targetRoomIdx)->flags &= ~ROOM_DESCRIPTOR_FLAG_BLUE_REDIRECT; + + bool isBackwards = stage >= BACKWARDS_FIRST_STAGE && stage <= BACKWARDS_LAST_STAGE && + game.GetStateFlag(GAME_STATE_BACKWARDS_PATH); + bool isAltStage = stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B; + bool isMineshaftFloor = + stage == STAGE_CAVES_II || (stage == STAGE_CAVES_I && (GetCurses() & CURSE_OF_LABYRINTH)); + RoomConfig_Room* leftData = room->descriptor->data; + bool isEntrance = leftData && room->roomType == ROOM_DEFAULT && leftData->subtype == MINESHAFT_ENTRANCE_SUBTYPE; + if (!game.IsGreedMode() && !isBackwards && isAltStage && isMineshaftFloor && lastRoomDimensionIdx == 0 && + currentDimensionIdx == MIRROR_DIMENSION && isEntrance) + room->descriptor->flags |= ROOM_DESCRIPTOR_FLAG_SACRIFICE_DONE; + + load_room(); + game.playerManager.trigger_new_room_effects(); + if (currentRoomIdx >= 0 && !isMazeMoved) enter_door_open(*this, previousType); + UpdateVisibility(); +} diff --git a/src/level.cpp b/src/level.cpp index 11a1ef7..3b4464e 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -4,6 +4,9 @@ #include "game.h" #include "grid_entity_door.h" #include "hud.h" +#include "lua_engine.h" +#include "menu_special_seeds.h" +#include "music_manager.h" #include "manager.h" #include "platform.h" #include "room.h" @@ -62,6 +65,38 @@ constexpr int STAGE_ID_DROSS = 28; constexpr int STAGE_ID_VOID = 26; constexpr uint32_t CHALLENGE_XXXXXXXXL = 21; + +// The Ascent's music: the alternate path's stages take the layers past the chapters'. +constexpr int ALT_PATH_LAYER_FIRST = 3; +constexpr int STAGE_ID_HOME = 35; +constexpr int DIMENSION_MINESHAFT = 2; +constexpr int ENEMY_TYPE_FIRST = 10; +constexpr int ENEMY_TYPE_LAST = 999; +constexpr int COLLECTIBLE_BERSERK = 704; + +// The enemies' health that makes a room's music intense, growing with the floor (a Greed floor counting as two). +constexpr float INTENSE_HEALTH_BASE = 40; +constexpr float INTENSE_HEALTH_PER_STAGE = 14; +constexpr float INTENSE_HEALTH_ALWAYS = 10000; +constexpr float MINESHAFT_HEALTH_PER_PIT = 3; +constexpr int GREED_STAGE_LAST_PAIRED = 4; +constexpr int GREED_STAGE_SHOP = 5; +constexpr int GREED_DEPTH_SHOP = 10; + +// The endless basement's floor number as roman numerals, and the counts its jokes start at. +struct RomanNumeral +{ + int value; + const char* text; +}; +constexpr RomanNumeral ROMAN_NUMERALS[] = {{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, + {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, + {1, "I"}}; +constexpr uint32_t NUMERAL_QUESTION = 3; +constexpr uint32_t NUMERAL_EXCLAIM = 4; +constexpr uint32_t NUMERAL_ELLIPSIS = 5; +constexpr uint32_t NUMERAL_SPIKES = 1001; +constexpr std::string_view DEATHMATCH_NAME_KEY = "Online/DEATHMATCH_NAME"; constexpr uint32_t SPECIAL_DAILY_NO_CURSES = 18; constexpr uint32_t SPECIAL_DAILY_DEALS = 17; constexpr uint32_t SPECIAL_DAILY_CURSED = 37; @@ -532,7 +567,7 @@ void Level::Init(bool isResetLilPortalRoom) room->camera->position_center(); room->camera->DoUpdate(false); TextureCache::Purge(); - FUN_00865260(); + static_cast(g_luaEngine)->PostNewLevel(); isLevelGenerating = false; } @@ -2464,7 +2499,7 @@ void Level::load_room() if (isUpdated && game.frameCount == entity.spawnFrame) entity.Update(); } - FUN_00865180(); + static_cast(g_luaEngine)->PostNewRoom(); if (!game.deathmatchManager.is_active()) return; game.deathmatchManager.type->Init(); game.dizzyTargetIntensity = 0; @@ -2620,12 +2655,6 @@ bool Level::boss_count_adjust(int&, int&) reconstruction_missing("Level::boss_count_adjust 007523e0"); } -// 0073fc80 Moves to another room. -void Level::ChangeRoom(int, int) -{ - reconstruction_missing("Level::ChangeRoom 0073fc80"); -} - // 0073fa20 Enters a room config directly, for debugging. void Level::DEBUG_goto_room(RoomConfig_Room*) { @@ -2727,18 +2756,6 @@ Vector Level::GetEnterPosition() return g_vectorZero; } -// 0073d9b0 A door slot as another shape sees it. -int Level::get_door_slot(int, int, bool, int) -{ - reconstruction_missing("Level::get_door_slot 0073d9b0"); -} - -// 0073da40 The slot a door leads into. -int Level::GetTargetSlot(int, int) -{ - reconstruction_missing("Level::GetTargetSlot 0073da40"); -} - // 0074c160 The cell a door leads to. XY Level::get_door_neighbor_pos(XY, RoomShape, int) { @@ -2787,12 +2804,6 @@ void Level::UncoverHiddenDoor(int, int) reconstruction_missing("Level::UncoverHiddenDoor 0074a1b0"); } -// 0074d4a0 Prepares a Blue Key room. -bool Level::prepare_blue_room(int, int, int) -{ - reconstruction_missing("Level::prepare_blue_room 0074d4a0"); -} - // 0074d780 Adds a second boss room. bool Level::TryInitializeExtraBossRoom(uint32_t) { @@ -2884,10 +2895,80 @@ void Level::RemoveCurses(uint32_t) reconstruction_missing("Level::RemoveCurses 00748bc0"); } -// 007eb870 Updates the Ascent's stages. +// The music layer the Ascent turns on for a stage it climbs through: one per chapter, the alternate paths' past them. +static int backwards_layer_get(int ascentStage) +{ + uint32_t stageType = g_game->backwardsStages[ascentStage - 1].stageType; + bool isAltPath = stageType == STAGETYPE_REPENTANCE || stageType == STAGETYPE_REPENTANCE_B; + return isAltPath ? (ascentStage - 2) / 2 + ALT_PATH_LAYER_FIRST : (ascentStage - 1) / 2; +} + +// 007eb870 Sets the current track's layers for the room the players are in (the original's this is the room). On the +// Ascent each layer is a stage climbed through outside its boss room. Elsewhere the intense layer plays while the +// room's enemies have health enough for the floor (always from the Blue Womb on, and with Berserk), the Mines' chase +// counting its pits. Nothing changes in the Home's dungeon or in Home's alternate. True when a layer plays. bool Level::UpdateBackwardsPathStages() { - reconstruction_missing("Level::UpdateBackwardsPathStages 007eb870"); + Game& game = *g_game; + MusicManager& music = g_manager->musicManager; + RoomDescriptor* descriptor = room->descriptor; + RoomConfig_Room* data = descriptor->data; + + if (data && data->type == ROOM_DUNGEON && data->stageId == STAGE_ID_HOME) return false; + int floor = (int)game.stage; + bool isAscentFloor = floor >= (int)LEVEL_STAGE_BASEMENT_I && floor <= (int)ASCENT_LAST_STAGE; + if (isAscentFloor && (game.gameStateFlags >> LEVEL_GAME_STATE_BACKWARDS_PATH & 1)) + { + bool isAltPath = game.stageType == STAGETYPE_REPENTANCE || game.stageType == STAGETYPE_REPENTANCE_B; + int first = floor + (isAltPath ? 1 : 0); + uint32_t layers = 0; + for (int ascentStage = first; ascentStage <= BACKWARDS_STAGE_COUNT; ascentStage++) + if (ascentStage != first || game.room->descriptor->listIndex != game.lastBossRoomListIdx) + layers |= 1u << backwards_layer_get(ascentStage); + for (int layer = 0; layer < MUSIC_LAYER_COUNT; layer++) + layers >> layer & 1 ? music.EnableLayer(layer, LAYER_FADE) : music.DisableLayer(layer); + return layers != 0; + } + if (!isAscentFloor && floor == (int)LEVEL_STAGE_HOME && game.stageType == STAGETYPE_WOTL) return true; + + int depth = floor; + if (game.IsGreedMode()) depth = floor <= GREED_STAGE_LAST_PAIRED ? floor * 2 - 1 : floor == GREED_STAGE_SHOP ? GREED_DEPTH_SHOP : 0; + float threshold = (float)depth * INTENSE_HEALTH_PER_STAGE + INTENSE_HEALTH_BASE; + float health = 0; + for (size_t i = 0; i < game.playerManager.playerList.size(); i++) + if (game.GetPlayer((int)i)->temporaryEffects.HasCollectibleEffect(COLLECTIBLE_BERSERK)) + { + health = INTENSE_HEALTH_ALWAYS; + break; + } + + if (floor < (int)LEVEL_STAGE_BLUE_WOMB) + { + for (Entity* entity : room->entityList.updateEL) + { + bool isCounted = (game.deathmatchManager.is_active() && entity->type == ENTITY_PLAYER) || + (entity->type >= ENEMY_TYPE_FIRST && entity->type <= ENEMY_TYPE_LAST); + if (isCounted && entity->CanShutDoors() && !entity->isDead && !entity->HasEntityFlags(FLAG_NO_TARGET)) + health += entity->health; + } + if (health > 0) + { + bool isMineshaft = false; + if (game.challenge == CHALLENGE_RED_REDEMPTION) + isMineshaft = RoomConfig::GetStageID(floor, GetRoomStageType(currentRoomIdx), ROOM_MODE_CURRENT) == STAGE_ID_MINES; + else if (game.currentDimensionIdx != DIMENSION_MINESHAFT) + isMineshaft = RoomConfig::GetStageID(floor, (int)game.stageType, ROOM_MODE_CURRENT) == STAGE_ID_MINES; + uint32_t flags = descriptor->flags; + bool isChase = isMineshaft && !(flags & ROOM_DESCRIPTOR_FLAG_CLEAR) && (flags & ROOM_DESCRIPTOR_FLAG_HAS_WATER) && + !(flags & ROOM_DESCRIPTOR_FLAG_FLOODED); + if (isChase) health += (float)descriptor->pitsCount * MINESHAFT_HEALTH_PER_PIT; + } + } + else if (!(descriptor->flags & ROOM_DESCRIPTOR_FLAG_CLEAR)) health += INTENSE_HEALTH_ALWAYS; + + bool isIntense = health >= threshold; + isIntense ? music.EnableLayer(0, LAYER_FADE) : music.DisableLayer(0); + return isIntense; } // 0074b960 The stage counted as in normal runs. @@ -2926,22 +3007,86 @@ RoomDescriptor* Level::get_secret_exit_room(int) reconstruction_missing("Level::get_secret_exit_room 0074bba0"); } -// 007460b0 The floor's name. +// 00745ca0 A stage's display name in the current language: stages.xml's, then the endless basement's roman numeral and +// its jokes, then " I" or " II" for a chapter's floor or " XL" for a labyrinth, scrambled for dyslexia. Greed and Red +// Redemption add no floor number. Empty for no stage. +std::string Level::get_stage_display_name(const StageNameQuery& query) +{ + if (query.stage == 0) return ""; + + Game& game = *g_game; + RoomMode mode = query.mode; + if (mode == ROOM_MODE_CURRENT) mode = g_game && g_game->IsGreedMode() ? ROOM_MODE_GREED : ROOM_MODE_NORMAL; + int stageId = RoomConfig::GetStageID(query.stage, query.stageType, mode); + std::string name = game.roomConfig.stages[stageId].GetDisplayName(LANGUAGE_CURRENT); + + if (query.numeral > 0) + { + name += ' '; + int remaining = query.numeral; + for (const RomanNumeral& numeral : ROMAN_NUMERALS) + for (; remaining >= numeral.value; remaining -= numeral.value) name += numeral.text; + + uint32_t count = (uint32_t)game.stageNameNumeral; + if (count == NUMERAL_QUESTION) name += "?"; + if (count == NUMERAL_EXCLAIM) name += "?!"; + if (count == NUMERAL_ELLIPSIS) name += "..."; + if (count == NUMERAL_SPIKES) name += " Spikes"; + if (count % 1000 == 0) name += "... Please stop."; + else if (count % 500 == 0) name += "!V"; + else if (count % 100 == 0) name += "!!!"; + else if (count % 50 == 0) name += "!!"; + else if (count % 10 == 0) name += "!"; + } + + bool isNumbered = mode != ROOM_MODE_GREED && game.challenge != CHALLENGE_RED_REDEMPTION; + if (isNumbered && (query.curses & CURSE_OF_LABYRINTH)) name += " XL"; + else if (isNumbered && query.numeral == 0 && query.stage >= 1 && query.stage <= (int)LEVEL_STAGE_WOMB_II) + name += query.stage & 1 ? " I" : " II"; + return query.isScrambled ? string_scramble_seeded(name) : name; +} + +// 007460b0 The floor's name, with Red Redemption's room stage type, the endless basement's numeral and dyslexia. std::string Level::GetName() { - reconstruction_missing("Level::GetName 007460b0"); + Game& game = *g_game; + bool isRedRedemption = game.challenge == CHALLENGE_RED_REDEMPTION; + + return get_stage_display_name({.stage = (int)stage, + .stageType = isRedRedemption ? GetRoomStageType(currentRoomIdx) : (int)stageType, + .curses = GetCurses(), + .numeral = game.seedEffects.HasSeedEffect(SEED_INFINITE_BASEMENT) ? game.stageNameNumeral : 0, + .isScrambled = game.seedEffects.HasSeedEffect(SEED_DYSLEXIA), + .mode = ROOM_MODE_CURRENT}); } -// 00746260 The floor's curse's name. +// 00746260 The name of the floor's first curse, scrambled for dyslexia. Empty for none. std::string Level::GetCurseName() { - reconstruction_missing("Level::GetCurseName 00746260"); + Game& game = *g_game; + std::string name; + + for (uint32_t curse = 0; curse < game.roomConfig.curses.size(); curse++) + if (GetCurses() & 1u << curse) + { + name = game.roomConfig.GetCurseName(curse + 1); + break; + } + return game.seedEffects.HasSeedEffect(SEED_DYSLEXIA) ? string_scramble_seeded(name) : name; } -// 00746560 Shows the floor's name. -void Level::ShowName(bool) +// 00746560 Shows the floor's name and curse in the HUD's banner, hiding by itself unless sticky. Versus shows its own. +void Level::ShowName(bool isSticky) { - reconstruction_missing("Level::ShowName 00746560"); + std::string name = GetName(); + std::string curse = GetCurseName(); + + if (g_game->deathmatchManager.is_active()) + { + name = g_manager->stringTable.translate(DEATHMATCH_NAME_KEY); + curse.clear(); + } + g_game->hud.messageMain.Show(name.c_str(), curse.c_str(), !isSticky, !curse.empty()); } // 007475b0 Restores the floor from a save. @@ -2950,18 +3095,6 @@ void Level::RestoreGameState(GameState&) reconstruction_missing("Level::RestoreGameState 007475b0"); } -// 00747e10 Saves the floor. -void Level::store_game_state(GameState&) -{ - reconstruction_missing("Level::store_game_state 00747e10"); -} - -// 00747360 Saves a room config's id. -void Level::write_room_config(RoomConfig_Room*, void*, void*) -{ - reconstruction_missing("Level::write_room_config 00747360"); -} - // 007474a0 The room config a saved id names. RoomConfig_Room* Level::get_room_config_from_saved_id(uint32_t*, void*) { diff --git a/src/level.h b/src/level.h index 2a83996..74f22bd 100644 --- a/src/level.h +++ b/src/level.h @@ -1,6 +1,7 @@ #pragma once #include "classes.h" +#include "entity_save_state.h" #include "level_generator.h" #include "room_descriptor.h" #include "seeds.h" @@ -84,6 +85,18 @@ enum StageType : uint32_t STAGETYPE_REPENTANCE_B }; +// What get_stage_display_name names: a stage and its type, the curses (a labyrinth's XL), the endless basement's +// numeral, dyslexia's scrambling, and the mode to number it in (the game's by default). +struct StageNameQuery +{ + int stage = 0; + int stageType = 0; + uint32_t curses = 0; + int numeral = 0; + bool isScrambled = false; + RoomMode mode = ROOM_MODE_CURRENT; +}; + // A Ventricle Razor portal: the room and grid cell it stands on (no room by default), and a flag its user passes. struct VentricleRazorPortal { @@ -240,11 +253,11 @@ public: int get_secret_exit_kind(); RoomDescriptor* get_secret_exit_room(int kind); + static std::string get_stage_display_name(const StageNameQuery& query); std::string GetName(); std::string GetCurseName(); void ShowName(bool isSticky); void RestoreGameState(GameState& state); void store_game_state(GameState& state); - static void write_room_config(RoomConfig_Room* roomConfig, void* gameStateRoom, void* deque); static RoomConfig_Room* get_room_config_from_saved_id(uint32_t* savedId, void* mergeTable); }; diff --git a/src/level_stage.cpp b/src/level_stage.cpp index 9868092..471ce45 100644 --- a/src/level_stage.cpp +++ b/src/level_stage.cpp @@ -82,8 +82,8 @@ static void ascent_stage_set(Level& level) auto& stages = g_game->backwardsStages; int next = floor - 1; - if (next > 1 && stages[next - 2]._isXL) next--; - if (is_repentance_type(stages[next - 1]._stageType)) return level.SetStage(next - 1, STAGETYPE_REPENTANCE); + if (next > 1 && stages[next - 2].isXL) next--; + if (is_repentance_type(stages[next - 1].stageType)) return level.SetStage(next - 1, STAGETYPE_REPENTANCE); level.SetStage(next, STAGETYPE_ORIGINAL); } diff --git a/src/lua_engine.cpp b/src/lua_engine.cpp index ee0918d..39d4cd0 100644 --- a/src/lua_engine.cpp +++ b/src/lua_engine.cpp @@ -81,6 +81,12 @@ const void* lua_class_key(LuaClass luaClass) return &classKeys[luaClass]; } +// Stops where a mod has a function for a callback LuaEngine does not run yet. +void lua_callback_check(int callback, const char* name) +{ + if (static_cast(g_luaEngine)->enabledCallbacks[callback]) reconstruction_missing(name); +} + // Pushes a callback argument: integers and booleans as themselves. static void value_push(lua_State* state, int value) { @@ -507,6 +513,18 @@ void LuaEngine::PostKnifeInit(Entity_Knife* knife) LuaObject{knife, LUA_CLASS_KNIFE}); } +// 00865260 Runs MC_POST_NEW_LEVEL once a floor is generated and its first room entered. +void LuaEngine::PostNewLevel() +{ + callback_notify(*this, {"PostNewLevel", MC_POST_NEW_LEVEL}); +} + +// 00865180 Runs MC_POST_NEW_ROOM once a room is loaded. +void LuaEngine::PostNewRoom() +{ + callback_notify(*this, {"PostNewRoom", MC_POST_NEW_ROOM}); +} + // 00864050 Runs MC_POST_PLAYER_INIT, filtered by the player's variant. void LuaEngine::PostPlayerInit(Entity_Player* player) { diff --git a/src/lua_engine.h b/src/lua_engine.h index 9b686f0..3c9e52f 100644 --- a/src/lua_engine.h +++ b/src/lua_engine.h @@ -35,6 +35,8 @@ enum LuaCallback MC_POST_PLAYER_INIT = 9, MC_USE_PILL = 10, MC_POST_GAME_STARTED = 15, + MC_POST_NEW_LEVEL = 18, + MC_POST_NEW_ROOM = 19, MC_PRE_FAMILIAR_COLLISION = 26, MC_PRE_NPC_COLLISION = 30, MC_PRE_PLAYER_COLLISION = 33, @@ -149,6 +151,8 @@ struct LuaEngine void PostEntityKill(Entity* entity); void PostGameStart(bool isContinued); void PostKnifeInit(Entity_Knife* knife); + void PostNewLevel(); + void PostNewRoom(); void PostPlayerInit(Entity_Player* player); void PostRender(); bool UseItem(LuaItemUse& use); @@ -156,3 +160,4 @@ struct LuaEngine }; const void* lua_class_key(LuaClass luaClass); +void lua_callback_check(int callback, const char* name); diff --git a/src/npc_ai.cpp b/src/npc_ai.cpp new file mode 100644 index 0000000..7d9419f --- /dev/null +++ b/src/npc_ai.cpp @@ -0,0 +1,665 @@ +#include "npc_ai.h" +#include "game.h" +#include "manager.h" +#include "sfx_manager.h" + +// The Beast's forms, by variant: its stalactites, rocks and soul, the four ultra horsemen and their summons, and +// the background beasts. +static void beast_update(Entity_NPC& npc) +{ + switch (npc.variant) + { + case 1: + return NpcAI::ENTITY_BEAST_stalactite(&npc); + case 2: + return NpcAI::ENTITY_BEAST_rock_projectile(&npc); + case 3: + return NpcAI::ENTITY_BEAST_soul(&npc); + case 10: + return NpcAI::ENTITY_BEAST_ultra_famine(&npc); + case 11: + return NpcAI::ENTITY_BEAST_ultra_famine_fly(&npc); + case 20: + return NpcAI::ENTITY_BEAST_ultra_pestilence(&npc); + case 21: + return NpcAI::ENTITY_BEAST_pestilence_fly(&npc); + case 22: + return NpcAI::ENTITY_BEAST_ultra_pestilence_maggot(&npc); + case 23: + return NpcAI::ENTITY_BEAST_ultra_pestilence_fly_ball(&npc); + case 30: + return NpcAI::ENTITY_BEAST_ultra_war(&npc); + case 31: + return NpcAI::ENTITY_BEAST_ultra_war_bomb(&npc); + case 40: + return NpcAI::ENTITY_BEAST_ultra_death(&npc); + case 41: + return NpcAI::ENTITY_BEAST_ultra_death_scythe(&npc); + case 42: + return NpcAI::ENTITY_BEAST_ultra_death_head(&npc); + case 100: + case 101: + case 102: + case 103: + case 104: + return NpcAI::ENTITY_BEAST_background(&npc); + default: + return NpcAI::ENTITY_BEAST(&npc); + } +} + +// Mother's forms, by variant: her two phases, her rotten gapers, worms and balls. +static void mother_update(Entity_NPC& npc) +{ + switch (npc.variant) + { + case 0: + return NpcAI::ENTITY_MOTHER(&npc); + case 10: + return NpcAI::ENTITY_MOTHER_2(&npc); + case 20: + return NpcAI::ENTITY_ROTTEN_GAPER(&npc); + case 30: + return NpcAI::ENTITY_MOTHER_worm(&npc); + case 100: + return NpcAI::ENTITY_MOTHER_ball(&npc); + } +} + +// The AI routine of each NPC type. Types it does not list (the ones the game left without an AI) do nothing. +static void npc_ai_routine_run(Entity_NPC& npc) +{ + switch (npc.type) + { + case 10: + case 208: + case 252: + case 257: + case 284: + case 302: + case 807: + return npc_gaper_update(npc); + case 11: + case 210: + case 211: + case 238: + case 280: + return (void)NpcAI::ENTITY_GUSHER(&npc); + case 12: + case 248: + return npc_horf_update(npc); + case 13: + case 14: + case 18: + case 61: + case 80: + case 214: + case 249: + case 819: + return npc_fly_update(npc); + case 15: + case 282: + case 872: + return (void)NpcAI::ENTITY_CLOTTY(&npc); + case 16: + return (void)NpcAI::ENTITY_MULLIGAN(&npc); + case 17: + return (void)NpcAI::ENTITY_SHOPKEEPER(&npc); + case 19: + case 89: + case 239: + return (void)NpcAI::ENTITY_LARRYJR(&npc); + case 20: + case 43: + return (void)NpcAI::ENTITY_MONSTRO(&npc); + case 21: + case 23: + case 31: + case 55: + case 237: + case 243: + return (void)NpcAI::ENTITY_MAGGOT(&npc); + case 22: + case 205: + case 817: + return (void)NpcAI::ENTITY_HIVE(&npc); + case 24: + case 278: + return (void)NpcAI::ENTITY_GLOBIN(&npc); + case 25: + return (void)NpcAI::ENTITY_BOOMFLY(&npc); + case 26: + return (void)NpcAI::ENTITY_MAW(&npc); + case 27: + case 859: + return (void)NpcAI::ENTITY_HOST(&npc); + case 28: + return (void)NpcAI::ENTITY_CHUB(&npc); + case 29: + case 34: + case 54: + case 86: + case 246: + case 305: + case 840: + return (void)NpcAI::ENTITY_HOPPER(&npc); + case 30: + return (void)NpcAI::ENTITY_BOIL(&npc); + case 32: + case 279: + case 301: + return (void)NpcAI::ENTITY_BRAIN(&npc); + case 33: + return (void)NpcAI::ENTITY_FIREPLACE(&npc); + case 35: + return (void)NpcAI::ENTITY_MRMAW(&npc); + case 36: + return (void)NpcAI::ENTITY_GURDY(&npc); + case 38: + case 259: + return (void)NpcAI::ENTITY_BABY(&npc); + case 39: + case 49: + case 836: + return (void)NpcAI::ENTITY_VIS(&npc); + case 40: + case 218: + case 862: + return (void)NpcAI::ENTITY_GUTS(&npc); + case 41: + case 254: + case 283: + return (void)NpcAI::ENTITY_KNIGHT(&npc); + case 42: + case 203: + case 235: + case 236: + return (void)NpcAI::ENTITY_STONEHEAD(&npc); + case 44: + return (void)NpcAI::ENTITY_POKY(&npc); + case 45: + return (void)NpcAI::ENTITY_MOM(&npc); + case 46: + return (void)NpcAI::ENTITY_SLOTH(&npc); + case 47: + return (void)NpcAI::ENTITY_LUST(&npc); + case 48: + return (void)NpcAI::ENTITY_WRATH(&npc); + case 50: + return (void)NpcAI::ENTITY_GREED(&npc); + case 51: + return (void)NpcAI::ENTITY_ENVY(&npc); + case 52: + return (void)NpcAI::ENTITY_PRIDE(&npc); + case 53: + return (void)NpcAI::ENTITY_DOPLE(&npc); + case 56: + return (void)NpcAI::ENTITY_LUMP(&npc); + case 57: + case 223: + return (void)NpcAI::ENTITY_MEMBRAIN(&npc); + case 58: + return (void)NpcAI::ENTITY_PARA_BITE(&npc); + case 59: + return (void)NpcAI::ENTITY_FRED(&npc); + case 60: + return (void)NpcAI::ENTITY_EYE(&npc); + case 62: + return (void)NpcAI::ENTITY_PIN(&npc); + case 63: + return (void)NpcAI::ENTITY_FAMINE(&npc); + case 64: + return (void)NpcAI::ENTITY_PESTILENCE(&npc); + case 65: + return (void)NpcAI::ENTITY_WAR(&npc); + case 66: + return (void)NpcAI::ENTITY_DEATH(&npc); + case 67: + return (void)NpcAI::ENTITY_DUKE(&npc); + case 68: + return (void)NpcAI::ENTITY_PEEP(&npc); + case 69: + return (void)NpcAI::ENTITY_LOKI(&npc); + case 71: + case 72: + case 73: + return (void)NpcAI::ENTITY_FISTULA_BIG(&npc); + case 74: + case 75: + case 76: + return (void)NpcAI::ENTITY_BLASTOCYST_BIG(&npc); + case 77: + return (void)NpcAI::ENTITY_EMBRYO(&npc); + case 78: + return (void)NpcAI::ENTITY_MOMS_HEART(&npc); + case 79: + reconstruction_missing("npc_ai_update 006c2990: Gemini's parts and death shots"); + case 81: + return (void)NpcAI::ENTITY_FALLEN(&npc); + case 82: + case 83: + return (void)NpcAI::ENTITY_HEADLESS_HORSEMAN(&npc); + case 84: + return (void)NpcAI::ENTITY_SATAN(&npc); + case 85: + case 94: + case 215: + case 250: + case 869: + return (void)NpcAI::ENTITY_SPIDER(&npc); + case 87: + return (void)NpcAI::ENTITY_GURGLE(&npc); + case 88: + return (void)NpcAI::ENTITY_WALKINGBOIL(&npc); + case 90: + return (void)NpcAI::ENTITY_HANGER(&npc); + case 91: + case 229: + case 230: + case 253: + return (void)NpcAI::ENTITY_SWARMER(&npc); + case 92: + return (void)NpcAI::ENTITY_HEART(&npc); + case 93: + reconstruction_missing("npc_ai_update 006c2990: Mask pairing with its Heart"); + case 96: + return (void)NpcAI::ENTITY_ETERNALFLY(&npc); + case 97: + return (void)NpcAI::ENTITY_MASK_OF_INFAMY(&npc); + case 98: + if (npc.state == NPC_STATE_INIT) npc.state = NPC_STATE_MOVE; + return; + case 99: + return (void)NpcAI::ENTITY_GURDY_JR(&npc); + case 100: + return (void)NpcAI::ENTITY_WIDOW(&npc); + case 101: + return (void)NpcAI::ENTITY_DADDYLONGLEGS(&npc); + case 102: + return (void)NpcAI::ENTITY_ISAAC(&npc); + case 201: + return (void)NpcAI::ENTITY_STONE_EYE(&npc); + case 202: + return (void)NpcAI::ENTITY_CONSTANT_STONE_SHOOTER(&npc); + case 204: + case 247: + return (void)NpcAI::ENTITY_MOBILE_HOST(&npc); + case 206: + case 207: + return (void)NpcAI::ENTITY_BABY_LONG_LEGS(&npc); + case 209: + return (void)NpcAI::ENTITY_FAT_SACK(&npc); + case 212: + case 286: + return (void)NpcAI::ENTITY_DEATHS_HEAD(&npc); + case 213: + case 287: + return (void)NpcAI::ENTITY_MOMS_HAND(&npc); + case 216: + return (void)NpcAI::ENTITY_SWINGER(&npc); + case 217: + case 870: + return npc_dip_update(npc); + case 219: + case 285: + return (void)NpcAI::ENTITY_WIZOOB(&npc); + case 220: + case 871: + return (void)NpcAI::ENTITY_SQUIRT(&npc); + case 221: + return (void)NpcAI::ENTITY_COD_WORM(&npc); + case 222: + return (void)NpcAI::ENTITY_RING_OF_FLIES(&npc); + case 224: + return (void)NpcAI::ENTITY_OOB(&npc); + case 225: + return (void)NpcAI::ENTITY_BLACK_MAW(&npc); + case 226: + case 227: + case 277: + return (void)NpcAI::ENTITY_SKINNY(&npc); + case 228: + case 251: + return (void)NpcAI::ENTITY_HOMUNCULUS(&npc); + case 231: + case 964: + return (void)NpcAI::ENTITY_NERVE_ENDING(&npc); + case 232: + case 234: + return (void)NpcAI::ENTITY_SKINBALL(&npc); + case 240: + case 241: + case 242: + case 304: + return (void)NpcAI::ENTITY_WALL_CREEP(&npc); + case 244: + case 255: + case 276: + case 289: + return (void)NpcAI::ENTITY_ROUND_WORM(&npc); + case 245: + return (void)NpcAI::ENTITY_POOP(&npc); + case 256: + return (void)NpcAI::ENTITY_DART_FLY(&npc); + case 258: + return (void)NpcAI::ENTITY_FAT_BAT(&npc); + case 260: + return (void)NpcAI::ENTITY_THE_HAUNT(&npc); + case 261: + return (void)NpcAI::ENTITY_DINGLE(&npc); + case 262: + return (void)NpcAI::ENTITY_MEGA_MAW(&npc); + case 263: + return (void)NpcAI::ENTITY_GATE(&npc); + case 264: + return (void)NpcAI::ENTITY_MEGA_FATTY(&npc); + case 265: + return (void)NpcAI::ENTITY_CAGE(&npc); + case 266: + return (void)NpcAI::ENTITY_MAMA_GURDY(&npc); + case 267: + return (void)NpcAI::ENTITY_DARK_ONE(&npc); + case 268: + return (void)NpcAI::ENTITY_ADVERSARY(&npc); + case 269: + case 401: + return (void)NpcAI::ENTITY_POLYCEPHALUS(&npc); + case 270: + return (void)NpcAI::ENTITY_MR_FRED(&npc); + case 271: + case 272: + return (void)NpcAI::ENTITY_URIEL(&npc); + case 273: + return (void)NpcAI::ENTITY_THE_LAMB(&npc); + case 274: + case 275: + if (npc.variant != 0) return NpcAI::ENTITY_MEGA_SATAN_hand(&npc); + NpcAI::ENTITY_MEGA_SATAN(&npc); + if (npc.isDead) npc.ClearEntityFlags(FLAG_NO_DEATH_TRIGGER); + return; + case 281: + return (void)NpcAI::ENTITY_SWARM(&npc); + case 288: + return (void)NpcAI::ENTITY_DUKIE(&npc); + case 290: + return (void)NpcAI::ENTITY_MEATBALL(&npc); + case 291: + return (void)NpcAI::ENTITY_PITFALL(&npc); + case 292: + return (void)NpcAI::ENTITY_MOVABLE_TNT(&npc); + case 293: + return (void)NpcAI::ENTITY_ULTRA_COIN(&npc); + case 294: + return (void)NpcAI::ENTITY_ULTRA_DOOR(&npc); + case 295: + return (void)NpcAI::ENTITY_CORN_MINE(&npc); + case 296: + return (void)NpcAI::ENTITY_HUSH_FLY(&npc); + case 297: + return (void)NpcAI::ENTITY_HUSH_GAPER(&npc); + case 298: + return (void)NpcAI::ENTITY_HUSH_BOIL(&npc); + case 299: + return (void)NpcAI::ENTITY_GREED_GAPER(&npc); + case 300: + return (void)NpcAI::ENTITY_MUSHROOM(&npc); + case 303: + return (void)NpcAI::ENTITY_BLISTER(&npc); + case 306: + return (void)NpcAI::ENTITY_PORTAL(&npc); + case 307: + return (void)NpcAI::ENTITY_TARBOY(&npc); + case 308: + return (void)NpcAI::ENTITY_FISTULOID(&npc); + case 309: + return (void)NpcAI::ENTITY_GUSH(&npc); + case 310: + return (void)NpcAI::ENTITY_LEPER(&npc); + case 311: + return (void)NpcAI::ENTITY_MR_MINE(&npc); + case 402: + return (void)NpcAI::ENTITY_BROWNIE(&npc); + case 403: + return (void)NpcAI::ENTITY_FORSAKEN(&npc); + case 404: + return (void)NpcAI::ENTITY_LITTLE_HORN(&npc); + case 405: + return (void)NpcAI::ENTITY_RAG_MAN(&npc); + case 406: + return (void)NpcAI::ENTITY_ULTRA_GREED(&npc); + case 407: + return (void)NpcAI::ENTITY_HUSH(&npc); + case 409: + return (void)NpcAI::ENTITY_RAG_MEGA(&npc); + case 410: + return (void)NpcAI::ENTITY_SISTERS_VIS(&npc); + case 411: + return (void)NpcAI::ENTITY_BIG_HORN(&npc); + case 412: + return (void)NpcAI::ENTITY_DELIRIUM(&npc); + case 413: + return (void)NpcAI::ENTITY_MATRIARCH(&npc); + case 802: + return (void)NpcAI::ENTITY_BLOOD_PUPPY(&npc); + case 804: + return (void)NpcAI::ENTITY_QUAKE_GRIMACE(&npc); + case 805: + return (void)NpcAI::ENTITY_BISHOP(&npc); + case 806: + return (void)NpcAI::ENTITY_BUBBLES(&npc); + case 808: + return (void)NpcAI::ENTITY_WILLO(&npc); + case 809: + return (void)NpcAI::ENTITY_BOMB_GRIMACE(&npc); + case 810: + return (void)NpcAI::ENTITY_SMALL_LEECH(&npc); + case 811: + return (void)NpcAI::ENTITY_DEEP_GAPER(&npc); + case 812: + return (void)NpcAI::ENTITY_SUB_HORF(&npc); + case 813: + return (void)NpcAI::ENTITY_BLURB(&npc); + case 814: + return (void)NpcAI::ENTITY_STRIDER(&npc); + case 815: + return (void)NpcAI::ENTITY_FISSURE(&npc); + case 816: + return (void)NpcAI::ENTITY_POLTY(&npc); + case 818: + return (void)NpcAI::ENTITY_ROCK_SPIDER(&npc); + case 820: + return (void)NpcAI::ENTITY_DANNY(&npc); + case 821: + return (void)NpcAI::ENTITY_BLASTER(&npc); + case 822: + return (void)NpcAI::ENTITY_BOUNCER(&npc); + case 823: + return (void)NpcAI::ENTITY_QUAKEY(&npc); + case 824: + return (void)NpcAI::ENTITY_GYRO(&npc); + case 825: + return (void)NpcAI::ENTITY_FIRE_WORM(&npc); + case 826: + return (void)NpcAI::ENTITY_HARDY(&npc); + case 827: + return (void)NpcAI::ENTITY_FACELESS(&npc); + case 828: + return (void)NpcAI::ENTITY_NECRO(&npc); + case 829: + return (void)NpcAI::ENTITY_MOLE(&npc); + case 830: + return (void)NpcAI::ENTITY_BIG_BONY(&npc); + case 831: + return (void)NpcAI::ENTITY_GUTTED_FATTY(&npc); + case 832: + return (void)NpcAI::ENTITY_EXORCIST(&npc); + case 833: + return (void)NpcAI::ENTITY_CANDLER(&npc); + case 834: + return (void)NpcAI::ENTITY_WHIPPER(&npc); + case 835: + return (void)NpcAI::ENTITY_PEEPER_FATTY(&npc); + case 837: + return (void)NpcAI::ENTITY_HENRY(&npc); + case 838: + return (void)NpcAI::ENTITY_WILLO_L2(&npc); + case 841: + return (void)NpcAI::ENTITY_REVENANT(&npc); + case 844: + return (void)NpcAI::ENTITY_BOMBGAGGER(&npc); + case 850: + return (void)NpcAI::ENTITY_GAPER_L2(&npc); + case 851: + return (void)NpcAI::ENTITY_TWITCHY(&npc); + case 852: + return (void)NpcAI::ENTITY_SPIKEBALL(&npc); + case 853: + return (void)NpcAI::ENTITY_SMALL_MAGGOT(&npc); + case 854: + return (void)NpcAI::ENTITY_ADULT_LEECH(&npc); + case 855: + return (void)NpcAI::ENTITY_CHARGER_L2(&npc); + case 856: + return (void)NpcAI::ENTITY_GASBAG(&npc); + case 857: + return (void)NpcAI::ENTITY_COHORT(&npc); + case 860: + return (void)NpcAI::ENTITY_UNBORN(&npc); + case 861: + return (void)NpcAI::ENTITY_PUSTULE(&npc); + case 863: + return (void)NpcAI::ENTITY_MORNINGSTAR(&npc); + case 864: + return (void)NpcAI::ENTITY_MOCKULUS(&npc); + case 865: + return (void)NpcAI::ENTITY_EVIS(&npc); + case 866: + return (void)NpcAI::ENTITY_DARK_ESAU(&npc); + case 867: + return (void)NpcAI::ENTITY_MOTHERS_SHADOW(&npc); + case 868: + return (void)NpcAI::ENTITY_ARMYFLY(&npc); + case 873: + return (void)NpcAI::ENTITY_FLY_TRAP(&npc); + case 874: + return (void)NpcAI::ENTITY_FARTIGAN(&npc); + case 875: + return (void)NpcAI::ENTITY_POOT_MINE(&npc); + case 876: + return (void)NpcAI::ENTITY_DUMP(&npc); + case 877: + return (void)NpcAI::ENTITY_GRUDGE(&npc); + case 878: + return (void)NpcAI::ENTITY_BUTT_SLICKER(&npc); + case 879: + return (void)NpcAI::ENTITY_BLOATY(&npc); + case 880: + return (void)NpcAI::ENTITY_FLESH_MAIDEN(&npc); + case 881: + return (void)NpcAI::ENTITY_NEEDLE(&npc); + case 882: + return (void)NpcAI::ENTITY_DUST(&npc); + case 883: + return (void)NpcAI::ENTITY_BABY_BEGOTTEN(&npc); + case 884: + return (void)NpcAI::ENTITY_SWARM_SPIDER(&npc); + case 885: + return (void)NpcAI::ENTITY_CULTIST(&npc); + case 886: + return (void)NpcAI::ENTITY_VIS_FATTY(&npc); + case 887: + return (void)NpcAI::ENTITY_DUSTY_DEATHS_HEAD(&npc); + case 888: + return (void)NpcAI::ENTITY_SHADY(&npc); + case 889: + return (void)NpcAI::ENTITY_CLICKETY_CLACK(&npc); + case 890: + return (void)NpcAI::ENTITY_MAZE_ROAMER(&npc); + case 891: + return (void)NpcAI::ENTITY_GOAT(&npc); + case 892: + return (void)NpcAI::ENTITY_POOFER(&npc); + case 893: + return (void)NpcAI::ENTITY_BALL_AND_CHAIN(&npc); + case 900: + return (void)NpcAI::ENTITY_REAP_CREEP(&npc); + case 901: + return (void)NpcAI::ENTITY_LIL_BLUB(&npc); + case 902: + return (void)NpcAI::ENTITY_RAINMAKER(&npc); + case 903: + if (npc.variant == 0) return NpcAI::ENTITY_VISAGE(&npc); + if (npc.variant == 1) return NpcAI::ENTITY_VISAGE_mask(&npc); + if (npc.variant == 10) return NpcAI::ENTITY_VISAGE_chain(&npc); + if (npc.variant == 20) return NpcAI::ENTITY_VISAGE_plasma(&npc); + return; + case 904: + return (void)NpcAI::ENTITY_SIREN(&npc); + case 905: + return (void)NpcAI::ENTITY_HERETIC(&npc); + case 906: + return npc.Hornfel_UpdateAI(); + case 907: + return (void)NpcAI::ENTITY_GIDEON(&npc); + case 908: + return (void)NpcAI::ENTITY_BABY_PLUM(&npc); + case 909: + return npc.variant == 10 ? NpcAI::ENTITY_SCOURGE_chain(&npc) : NpcAI::ENTITY_SCOURGE(&npc); + case 910: + return npc.variant == 2 ? (void)NpcAI::ENTITY_CHIMERA(&npc) : NpcAI::ENTITY_CHIMERA_body(&npc); + case 911: + if (npc.variant == 2) return NpcAI::ENTITY_ROTGUT(&npc); + return npc.variant == 1 ? NpcAI::ENTITY_ROTGUT_maggot(&npc) : NpcAI::ENTITY_ROTGUT_face(&npc); + case 912: + return mother_update(npc); + case 913: + return (void)NpcAI::ENTITY_MIN_MIN(&npc); + case 914: + return (void)NpcAI::ENTITY_CLOG(&npc); + case 915: + return npc.variant == 1 ? NpcAI::ENTITY_SINGE_ball(&npc) : NpcAI::ENTITY_SINGE_body(&npc); + case 916: + return (void)NpcAI::ENTITY_BUMBINO(&npc); + case 917: + return (void)NpcAI::ENTITY_COLOSTOMIA(&npc); + case 918: + return (void)NpcAI::ENTITY_TURDLET(&npc); + case 919: + return (void)NpcAI::ENTITY_RAGLICH(&npc); + case 920: + return (void)NpcAI::ENTITY_HORNY_BOYS(&npc); + case 921: + if (npc.variant == 0) return NpcAI::ENTITY_CLUTCH(&npc); + reconstruction_missing("npc_ai_update 006c2990: Clutch's orbitals"); + case 922: + reconstruction_missing("npc_ai_update 006c2990: Cadavra's green splat"); + case 950: + if (npc.variant == 1) return NpcAI::ENTITY_DOGMA_tv(&npc); + if (npc.variant == 2) return NpcAI::ENTITY_DOGMA_angel(&npc); + if (npc.variant == 10) return (void)NpcAI::ENTITY_DOGMA_angel_baby(&npc); + return NpcAI::ENTITY_DOGMA(&npc); + case 951: + return beast_update(npc); + case 960: + return (void)NpcAI::ENTITY_GENERIC_PROP(&npc); + case 965: + return (void)NpcAI::ENTITY_MINECART(&npc); + case 966: + return (void)NpcAI::ENTITY_SIREN_HELPER(&npc); + case 967: + return NpcAI::ENTITY_HORNFEL_DOOR(&npc); + default: + return; + } +} + +// 006c2990 Runs the NPC's AI for its type, in whatever phase (aiCallPhase) the caller set, with the mods' NPC +// update callbacks around the update phase. +void npc_ai_update(Entity_NPC& npc) +{ + if (npc.aiCallPhase == AI_PHASE_UPDATE) + lua_callback_check(CALLBACK_PRE_NPC_UPDATE, "npc_ai_update 006c2990: MC_PRE_NPC_UPDATE"); + npc_ai_routine_run(npc); + if (npc.aiCallPhase == AI_PHASE_UPDATE) + lua_callback_check(CALLBACK_NPC_UPDATE, "npc_ai_update 006c2990: MC_NPC_UPDATE"); +} diff --git a/src/npc_ai.h b/src/npc_ai.h new file mode 100644 index 0000000..2920606 --- /dev/null +++ b/src/npc_ai.h @@ -0,0 +1,116 @@ +#pragma once + +#include "entity_npc.h" +#include "log.h" +#include "lua_engine.h" +#include "seeds.h" +#include +#include + +constexpr float PI_F = 3.1415927f; +constexpr float RANDOM_UNIT_SCALE = 2.3283064e-10f; +constexpr float RANDOM_HALF_TURN = 3.14f; +constexpr float DEGREES_TO_RADIANS = 0.017453292f; + +// The mod callbacks the NPC code runs, by their ModCallbacks ids. +constexpr int CALLBACK_NPC_UPDATE = 0; +constexpr int CALLBACK_POST_NPC_INIT = 27; +constexpr int CALLBACK_POST_NPC_RENDER = 28; +constexpr int CALLBACK_POST_NPC_DEATH = 29; +constexpr int CALLBACK_PRE_NPC_UPDATE = 69; + +// The sound ids the common enemies play (Lua's SoundEffect). +enum NpcSound : int +{ + SOUND_BOSS1_EXPLOSIONS = 28, + SOUND_INSECT_SWARM_LOOP = 52, + SOUND_MEAT_IMPACTS = 77, + SOUND_ZOMBIE_WALKER_KID = 165, + SOUND_MONSTER_GRUNT_0 = 167, + SOUND_SUMMONSOUND = 286, + SOUND_SUMMON_POOF = 872 +}; + +inline Vector vector_add(Vector a, Vector b) +{ + return vector_make(a.x + b.x, a.y + b.y); +} + +inline Vector vector_sub(Vector a, Vector b) +{ + return vector_make(a.x - b.x, a.y - b.y); +} + +inline Vector vector_scale(Vector v, float scale) +{ + return vector_make(v.x * scale, v.y * scale); +} + +inline float vector_dot(Vector a, Vector b) +{ + return a.x * b.x + a.y * b.y; +} + +inline float vector_length_squared(Vector v) +{ + return v.x * v.x + v.y * v.y; +} + +inline float vector_length(Vector v) +{ + return std::sqrt(v.x * v.x + v.y * v.y); +} + +inline bool vector_is_zero(Vector v) +{ + return v.x == 0 && v.y == 0; +} + +// Vector::Normalized: a unit vector along v, or v when it has no length. +inline Vector vector_normalized(Vector v) +{ + float length = vector_length(v); + return length > 0 ? vector_scale(v, 1 / length) : v; +} + +// Vector::Resized: v at a length, or v when it has none. +inline Vector vector_resized(Vector v, float length) +{ + float current = vector_length(v); + return current > 0 ? vector_scale(v, length / current) : v; +} + +// random_float: a random fraction of one from the global generator. +inline float random_unit() +{ + return (float)Random() * RANDOM_UNIT_SCALE; +} + +// Isaac::Random: a random number below max, or 0 for none. +inline int random_below(int max) +{ + return max == 0 ? 0 : (int)(Random() % (uint32_t)max); +} + +// MusicManager::RandomVector: a random unit direction. +inline Vector random_direction() +{ + float angle = random_unit() * RANDOM_HALF_TURN; + angle += angle; + return vector_make(std::cos(angle), std::sin(angle)); +} + +// Plays a sound through the fart seeds, the way the AIs play the ones that are not the NPC's own. +void npc_sound_play(int sound, float volume, int frameDelay, float pitch); + +// The ticks the NPC moved on this update, which its timers count down by. +inline int npc_ticks_get(Entity_NPC& npc) +{ + return (int)npc.updateTime - (int)npc.prevUpdateTime; +} + +void npc_ai_update(Entity_NPC& npc); +void npc_fly_update(Entity_NPC& npc); +void npc_gaper_update(Entity_NPC& npc); +void npc_horf_update(Entity_NPC& npc); +void npc_dip_update(Entity_NPC& npc); diff --git a/src/npc_dip.cpp b/src/npc_dip.cpp new file mode 100644 index 0000000..fe6abea --- /dev/null +++ b/src/npc_dip.cpp @@ -0,0 +1,128 @@ +#include "npc_ai.h" +#include "entity_effect.h" +#include "entity_familiar.h" +#include "entity_player.h" +#include "game.h" +#include "room.h" + +constexpr int ENTITY_DIP = 217; +constexpr int DIP_CORN = 1; +constexpr int DIP_BROWNIE = 2; +constexpr int DIP_BIG_CORN = 3; +constexpr int FAMILIAR_DIP_CORN = 2; +constexpr int FAMILIAR_DIP_BROWNIE = 20; +constexpr int COLLECTIBLE_DIRTY_MIND_ID = 576; +constexpr int TRINKET_DIPPING_TRINKET_ID = 163; +constexpr int PROJECTILE_CORN = 5; +constexpr int SOUND_DIP_HURT = 60; +constexpr int COLOR_PRIORITY_DEFAULT = 255; + +// How a Dip hops: one chance in ten a frame from rest, at a random speed (doubled for the corn dip), and how it +// slows, splats and squeaks. +constexpr int HOP_ODDS = 10; +constexpr float HOP_SPEED_MIN = 5; +constexpr float HOP_SPEED_RANGE = 5; +constexpr float HOP_FRICTION = 0.8f; +constexpr float SLIDE_FRICTION = 0.95f; +constexpr float SPLAT_SIZE_MIN = 0.2f; +constexpr float SPLAT_SIZE_RANGE = 0.5f; +constexpr int SPLAT_ODDS = 10; +constexpr float HURT_VOLUME = 0.8f; +constexpr int HURT_SOUND_DELAY = 15; +constexpr float CORN_AIM_LEAD = 0.1f; +constexpr float CORN_SHOT_SPEED = 10; +constexpr float CONTROLLER_DEADZONE = 0.1f; +constexpr ColorMod DIP_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.25490198f, 0.16078432f, 0.13725491f}}; +constexpr ColorMod BROWNIE_SPLAT = {{0, 0, 0, 1}, {0, 0, 0, 0}, {0.6f, 0.4f, 0}}; + +// A hop: a random way (away from its target while it fears it), faster for the corn dips. +static void dip_hop(Entity_NPC& npc) +{ + npc.state = NPC_STATE_MOVE; + bool isFleeing = npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) && npc.controllerID == -1; + Vector direction; + if (isFleeing) direction = vector_normalized(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); + else + { + direction = random_direction(); + if (npc.controllerID != -1) direction = npc.GetControllerInput(0); + } + + float speed = random_unit() * HOP_SPEED_RANGE + HOP_SPEED_MIN; + bool isDoubled = npc.variant == DIP_CORN || (isFleeing && npc.variant == DIP_BROWNIE); + Vector hop = vector_scale(direction, isDoubled ? speed * 2 : speed); + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(hop, npc.speedMultiplier / npc.friction)); +} + +// The big corn dip's dying shot, aimed where its target is heading. +static void dip_corn_shoot(Entity_NPC& npc) +{ + Entity* target = npc.GetPlayerTarget(); + float distance = vector_length(vector_sub(npc.pos, target->pos)); + Vector lead = vector_add(target->pos, vector_scale(target->velocity, CORN_AIM_LEAD * distance)); + ProjectileParams params; + params.variant = PROJECTILE_CORN; + npc.FireProjectiles(npc.pos, vector_scale(vector_normalized(vector_sub(lead, npc.pos)), CORN_SHOT_SPEED), + PROJECTILES_SINGLE, params); +} + +// 00534860 The Dip's AI: it rests, hops about (fleeing what it fears), slides to a stop and leaves poop splats. Dirty +// Mind and the Dipping trinket turn it into the players' own dip. +void npc_dip_update(Entity_NPC& npc) +{ + if (npc.type != ENTITY_DIP) reconstruction_missing("npc_dip_update 00534860: the other dip kin"); + + PlayerManager& players = g_game->playerManager; + bool isTamed = players.FirstCollectibleOwner(COLLECTIBLE_DIRTY_MIND_ID, LAZARUS_SHARE_CHECK) || + players.AnyoneHasTrinket(TRINKET_DIPPING_TRINKET_ID); + if (!npc.isDead && isTamed) + { + Entity* owner = players.RandomCollectibleOwner(COLLECTIBLE_DIRTY_MIND_ID, npc.initSeed, nullptr); + if (!owner) owner = players.RandomTrinketOwner(TRINKET_DIPPING_TRINKET_ID, npc.initSeed, nullptr); + if (owner) + { + npc.entityCollisionClass = ENTCOLL_NONE; + npc.Remove(); + bool isCorn = npc.variant == DIP_CORN || npc.variant == DIP_BIG_CORN; + int dip = npc.variant == DIP_BROWNIE ? FAMILIAR_DIP_BROWNIE : isCorn ? FAMILIAR_DIP_CORN : 0; + Entity_Familiar::ThrowDip(dip, npc.pos, owner); + return; + } + } + + if (npc.state == NPC_STATE_INIT) + { + npc.state = NPC_STATE_IDLE; + npc.splatColor = npc.variant == DIP_BROWNIE ? BROWNIE_SPLAT : DIP_SPLAT; + return; + } + bool isFloating = npc.variant == DIP_BIG_CORN && g_game->room->waterAmount > 0; + npc.entityGridCollisionClass = isFloating ? GRIDCOLL_NOPITS : GRIDCOLL_GROUND; + + if (npc.state == NPC_STATE_IDLE || npc.state == NPC_STATE_SPECIAL) + { + npc.sprite.Play("Idle"); + bool isHopping = npc.state == NPC_STATE_SPECIAL || + (npc.controllerID == -1 ? Random() % HOP_ODDS == 0 + : !vector_is_zero(npc.GetControllerInput(CONTROLLER_DEADZONE))); + if (isHopping) dip_hop(npc); + npc.friction *= HOP_FRICTION; + } + else if (npc.state == NPC_STATE_MOVE) + { + npc.sprite.Play("Move"); + npc.friction *= SLIDE_FRICTION; + if (vector_length_squared(npc.velocity) < 1) npc.state = NPC_STATE_IDLE; + } + + npc.sprite.isFlipX = npc.velocity.x < 0; + if (Random() % SPLAT_ODDS == 0) + npc.MakeSplat(random_unit() * SPLAT_SIZE_RANGE + SPLAT_SIZE_MIN) + ->SetColor(npc.splatColor, -1, COLOR_PRIORITY_DEFAULT, false, true); + if (npc.pendingDamage > 0 && (Random() & 1) == 0) + npc.PlaySound(SOUND_DIP_HURT, HURT_VOLUME, HURT_SOUND_DELAY, false, 1); + if (npc.variant == DIP_BIG_CORN && npc.controllerID != -1) + reconstruction_missing("npc_dip_update 00534860: a controlled corn dip bursting"); + if (npc.isDead && npc.variant == DIP_BIG_CORN && !npc.HasEntityFlags(FLAG_SHRINK)) dip_corn_shoot(npc); +} diff --git a/src/npc_fly.cpp b/src/npc_fly.cpp new file mode 100644 index 0000000..f36cccb --- /dev/null +++ b/src/npc_fly.cpp @@ -0,0 +1,319 @@ +#include "npc_ai.h" +#include "entity_player.h" +#include "game.h" +#include "grid_entity.h" +#include "room.h" +#include "score_sheet.h" + +constexpr int ENTITY_ISAAC_BOSS = 102; +constexpr int ENTITY_ORBIT_SPAWNER = 873; +constexpr int SPAWNER_UNBOUNDED = 67; +constexpr int COLLECTIBLE_SKATOLE_ID = 9; +constexpr int POOTER_TRIPLE_VARIANT = 2; +constexpr int POOTER_TWO_SHOT_VARIANT = 1; + +// The fly types this file covers: the fly, the Pooter and the attack fly. +constexpr int ENTITY_FLY = 13; +constexpr int ENTITY_POOTER = 14; +constexpr int ENTITY_ATTACKFLY = 18; + +// How a Pooter shoots: when its target is in range (checked every 7 frames), its cooldowns, and its shot. +constexpr float POOTER_RANGE = 200; +constexpr int POOTER_RANGE_FRAMES = 7; +constexpr int POOTER_COOLDOWN = 35; +constexpr int POOTER_TRIPLE_COOLDOWN = 63; +constexpr float POOTER_SHOT_SPEED = 7; +constexpr float POOTER_HARD_SHOT_SPEED = 10; +constexpr float POOTER_FRICTION = 0.8f; +constexpr float POOTER_DRIFT_DECAY = 0.7f; +constexpr int SOUND_POOTER_SHOOT = 178; +constexpr uint64_t PROJECTILE_FLAG_54 = 1ull << 54; + +// The super Pooter's shot. +constexpr float SUPER_POOTER_SCALE = 1.4f; +constexpr float SUPER_POOTER_FALL_ACCEL = -0.15f; +constexpr float SUPER_POOTER_FALL_SPEED = 1; +constexpr float SUPER_POOTER_SPREAD = 1.2f; + +// How a fly wanders: the spot it eyes (and a poop or fireplace there), its drift and the bounds it stays within. +constexpr int FLY_RETARGET_FRAMES = 3; +constexpr float FLY_WANDER = 240; +constexpr int FLY_FIREPLACE_ODDS = 100; +constexpr int FLY_POOP_ODDS = 1000; +constexpr int FLY_CHASE_ODDS = 5; +constexpr float FLY_CHASE_SPEED = 0.7f; +constexpr float FLY_DRIFT_KEEP = 0.4f; +constexpr float FLY_DRIFT_NEW = 0.6f; +constexpr float FLY_DRIFT_STEP = 0.06f; +constexpr float FLY_TOP = 230; +constexpr float FLY_BOTTOM = 420; +constexpr float FLY_LEFT = 80; +constexpr float FLY_RIGHT = 540; +constexpr float FLY_FRICTION = 0.6f; +constexpr int FLY_DRIFT_PERIOD = 4; +constexpr int FLY_STEER_PERIOD = 3; + +// How a fly flees what it fears: within 400 (at full distance under 200), aimed in a random arc around away. +constexpr float FLEE_RANGE = 400; +constexpr float FLEE_NEAR = 200; +constexpr float FLEE_DISTANCE = 100; +constexpr float FLEE_ARC = 220; +constexpr float FLEE_ARC_BLOCKED = 360; +constexpr uint64_t FLEE_BLOCKERS = FLAG_FREEZE | FLAG_CHARM | FLAG_CONFUSION | FLAG_MIDAS_FREEZE; + +// How it flies to its target: how near it stops (an attack fly nearer), and how hard it pulls. +constexpr float TARGET_REACH = 30; +constexpr float TARGET_REACH_ATTACK = 25; +constexpr float TARGET_REACH_BIG = 15; +constexpr float TARGET_PULL = 0.08f; +constexpr float TARGET_PULL_MAX = 1.2f; +constexpr float TARGET_Y_SHARE = 0.5f; +constexpr float TARGET_PARENT_SHARE = 0.2f; +constexpr float BIG_FLY_SCALE = 1.1f; +constexpr float KILL_ON_TOUCH_FRICTION = 0.9f; +constexpr float CHARGE_INTERVAL = 2; +constexpr float REGENERATION_FRAMES = 60; +constexpr uint32_t GRID_COLLISION_WALL = 4; + +// The fly's sprite: Fly while it flies (restarted when it stopped), the Pooter's back to Fly after its attack. +static void fly_animation_update(Entity_NPC& npc) +{ + if (npc.type == ENTITY_POOTER) + { + bool isAttackDone = !npc.sprite.animState.animData || !npc.sprite.animState.isPlaying; + if (npc.state < NPC_STATE_SUICIDE) npc.sprite.Play("Fly"); + else if (npc.state == NPC_STATE_ATTACK && isAttackDone) npc.state = NPC_STATE_MOVE; + return; + } + + const AnimationData* current = npc.sprite.animState.animData; + bool isFlying = current && current->name == "Fly" && (!current->isLooping || npc.sprite.animState.isPlaying); + if (!isFlying && npc.sprite.SetAnimation("Fly", SWITCH_KEEP_FRAME)) + { + npc.sprite.animState.Rewind(); + npc.sprite.animState.isPlaying = true; + } +} + +// A fly that crosses a poop (one chance in a thousand a frame) eats it and becomes a Pooter. +static void fly_poop_eat(Entity_NPC& npc) +{ + if (npc.type != ENTITY_FLY || Random() % FLY_POOP_ODDS != 0) return; + + Room& room = *g_game->room; + int gridIndex = room.GetGridIndex(npc.pos); + GridEntity* grid = gridIndex >= 0 ? room.GetGridEntity(gridIndex) : nullptr; + if (grid && grid->type == GRID_POOP) reconstruction_missing("npc_fly_update 00506bd0: a fly eating poop"); +} + +// A Pooter in range of its target turns to it and shoots on its Shoot event: a single shot, two for the twin +// shooter, three heavy ones for the super Pooter. +static void pooter_attack_update(Entity_NPC& npc) +{ + if (npc.projectileCooldown < 1 && npc.IsTargetInAttackRange(POOTER_RANGE, POOTER_RANGE_FRAMES, false)) + { + npc.projectileCooldown = npc.variant == POOTER_TRIPLE_VARIANT ? POOTER_TRIPLE_COOLDOWN : POOTER_COOLDOWN; + npc.sprite.Play("Attack"); + npc.state = NPC_STATE_ATTACK; + npc.UpdateControllerMovement(true); + float facing = vector_is_zero(npc.controllerMovement) ? npc.GetPlayerTarget()->pos.x - npc.pos.x + : npc.controllerMovement.x; + npc.sprite.isFlipX = facing < 0; + } + + if (npc.state == NPC_STATE_ATTACK) + { + npc.UpdateControllerMovement(false); + if (npc.sprite.animState.animData && npc.sprite.animState.IsEventTriggered("Shoot")) + { + Vector aim = vector_is_zero(npc.controllerMovement) ? vector_sub(npc.GetPlayerTarget()->pos, npc.pos) + : npc.controllerMovement; + ProjectileParams params; + ProjectilesMode mode = npc.variant == POOTER_TWO_SHOT_VARIANT ? PROJECTILES_TWO : PROJECTILES_SINGLE; + float speed = game_is_hard_mode() ? POOTER_HARD_SHOT_SPEED : POOTER_SHOT_SPEED; + if (npc.variant == POOTER_TRIPLE_VARIANT) + { + params.scale = SUPER_POOTER_SCALE; + params.fallingAccelModifier = SUPER_POOTER_FALL_ACCEL; + params.fallingSpeedModifier = SUPER_POOTER_FALL_SPEED; + params.spread = SUPER_POOTER_SPREAD; + params.bulletFlags = PROJECTILE_FLAG_54; + params.isFallingKept = true; + mode = PROJECTILES_FOUR; + speed = POOTER_SHOT_SPEED; + } + npc.FireProjectiles(npc.pos, vector_resized(aim, speed), mode, params); + npc.PlaySound(SOUND_POOTER_SHOOT, 1, 2, false, 1); + } + } + + if (npc.projectileCooldown > 0) + { + npc.friction *= POOTER_FRICTION; + npc.projectileCooldown -= npc_ticks_get(npc); + npc.v1 = vector_scale(npc.v1, POOTER_DRIFT_DECAY); + } +} + +// Every third frame a fly picks where it heads: an attack fly (or any under Skatole) its target, a plain fly or +// Pooter eyes a random spot and its poop, or now and then a fireplace, though it heads nowhere in the end. +static void fly_target_pick(Entity_NPC& npc, bool isSkatoleActive) +{ + if (!npc.IsFrame(FLY_RETARGET_FRAMES, 0)) return; + if (npc.type == ENTITY_ATTACKFLY && npc.parent && npc.controllerID == -1) + reconstruction_missing("npc_fly_update 00506bd0: an attack fly circling its parent"); + + if (npc.type != ENTITY_ATTACKFLY && !isSkatoleActive) + { + Room& room = *g_game->room; + Vector direction = random_direction(); + float scaleFirst = random_unit(); + float distance = random_unit() * scaleFirst * FLY_WANDER; + int gridIndex = room.GetGridIndex(vector_add(npc.pos, vector_scale(direction, distance))); + GridEntity* grid = gridIndex >= 0 ? room.GetGridEntity(gridIndex) : nullptr; + if (grid && grid->type == GRID_POOP) npc.targetPosition = room.GetGridPosition(gridIndex); + if (Random() % FLY_FIREPLACE_ODDS == 0) + { + std::vector fireplaces; + for (Entity* entity : room.entityList.mainEL) + if (entity->type == ENTITY_FIREPLACE) fireplaces.push_back(entity); + if (!fireplaces.empty()) npc.targetPosition = fireplaces[random_below((int)fireplaces.size())]->pos; + } + return; + } + npc.targetPosition = npc.CalcTargetPosition(0); +} + +// A feared or shrunk fly within 400 of its target heads off to a random spot in an arc away from it, wider when it +// touches a wall. +static void fly_flee_update(Entity_NPC& npc) +{ + if (!npc.HasEntityFlags(FLAG_FEAR | FLAG_SHRINK) || npc.HasEntityFlags(FLEE_BLOCKERS) || npc.controllerID != -1) + return; + + float distance = vector_length(vector_sub(npc.pos, npc.GetPlayerTarget()->pos)); + if (distance >= FLEE_RANGE) return; + + float reach = + distance > FLEE_NEAR ? FLEE_DISTANCE - (distance - FLEE_NEAR) / FLEE_NEAR * FLEE_DISTANCE : FLEE_DISTANCE; + float arc = npc.isCollidesWithGrid ? FLEE_ARC_BLOCKED : FLEE_ARC; + Vector away = vector_sub(npc.pos, npc.GetPlayerTarget()->pos); + float angle = (random_unit() * arc - arc * 0.5f) * DEGREES_TO_RADIANS; + Vector turned = vector_make(std::cos(angle) * away.x - away.y * std::sin(angle), + away.y * std::cos(angle) + std::sin(angle) * away.x); + npc.targetPosition = vector_add(vector_resized(turned, reach), npc.pos); + npc.v1 = vector_scale(npc.v1, 0.5f); +} + +// Every other tick a fly with a target pulls toward it once farther than its reach, harder the farther. +static void fly_target_follow(Entity_NPC& npc) +{ + if (vector_is_zero(npc.targetPosition) || npc.GetIntervalTicks(CHARGE_INTERVAL, 0) == 0) return; + + float reach = npc.type == ENTITY_ATTACKFLY ? TARGET_REACH_ATTACK : TARGET_REACH; + if (npc.sprite.scale.x > BIG_FLY_SCALE) reach = TARGET_REACH_BIG; + + Vector toward = vector_sub(npc.targetPosition, npc.pos); + if (npc.controllerID == -1) + { + toward.y *= TARGET_Y_SHARE; + if (npc.parent) toward = vector_scale(toward, TARGET_PARENT_SHARE); + } + else toward = vector_scale(npc.GetControllerInput(0), FLEE_DISTANCE); + + float distance = vector_length(toward); + Vector direction = distance > 0 ? vector_scale(toward, 1 / distance) : toward; + if (npc.isKillOnTouch) npc.friction *= KILL_ON_TOUCH_FRICTION; + if (npc.type != ENTITY_ATTACKFLY) npc.v1 = vector_scale(npc.v1, POOTER_DRIFT_DECAY); + if (distance > reach) + npc.AddVelocity_divided(vector_scale(direction, std::min((distance - reach) * TARGET_PULL, TARGET_PULL_MAX)), + false); +} + +// A fly's buzzing: without a target it now and then darts toward its player, every fourth frame its drift turns, +// every third it drifts back inside the room's middle and its drift moves it. +static void fly_drift_update(Entity_NPC& npc) +{ + if (vector_is_zero(npc.targetPosition)) + { + if (npc.controllerID != -1) reconstruction_missing("npc_fly_update 00506bd0: a controlled fly's steering"); + if (Random() % FLY_CHASE_ODDS == 0) + { + Vector toward = vector_normalized(vector_sub(npc.GetPlayerTarget()->pos, npc.pos)); + npc.velocity = vector_add(npc.velocity, vector_scale(toward, FLY_CHASE_SPEED * npc.speedMultiplier)); + } + } + + if (g_game->frameCount % FLY_DRIFT_PERIOD == 1) + npc.v1 = vector_scale(vector_add(vector_scale(random_direction(), FLY_DRIFT_NEW), npc.v1), FLY_DRIFT_KEEP); + if (g_game->frameCount % FLY_STEER_PERIOD != 2) return; + + if (npc.spawnerType != SPAWNER_UNBOUNDED) + { + if (npc.pos.y < FLY_TOP) npc.v1.y += FLY_DRIFT_STEP; + else if (npc.pos.y > FLY_BOTTOM) npc.v1.y -= FLY_DRIFT_STEP; + if (npc.pos.x > FLY_RIGHT) npc.v1.x -= FLY_DRIFT_STEP; + else if (npc.pos.x < FLY_LEFT) npc.v1.x += FLY_DRIFT_STEP; + } + if (npc.friction != 0) + npc.velocity = vector_add(npc.velocity, vector_scale(npc.v1, 2 * npc.speedMultiplier / npc.friction)); + npc.friction *= FLY_FRICTION; +} + +// 00506bd0 The flies' AI (the fly, Pooter and attack fly, with Moter, Sucker and their kin left to come): Skatole +// befriends them, Lord of the Flies turns them blue, they buzz about drifting, the attack fly chases its target and +// the Pooter shoots at it. +void npc_fly_update(Entity_NPC& npc) +{ + bool isCovered = npc.type == ENTITY_FLY || npc.type == ENTITY_POOTER || npc.type == ENTITY_ATTACKFLY; + if (!isCovered) reconstruction_missing("npc_fly_update 00506bd0: the Sucker, Moter and the other fly kin"); + + if (npc.state == NPC_STATE_INIT) + { + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + npc.v2 = {}; + npc.state = NPC_STATE_IDLE; + npc.i1 = 0; + } + + PlayerManager& players = g_game->playerManager; + bool isSkatoleActive = + players.FirstCollectibleOwner(COLLECTIBLE_SKATOLE_ID, LAZARUS_SHARE_CHECK) && !npc.IsFriendly(); + if (isSkatoleActive && npc.type == ENTITY_ATTACKFLY) npc.Morph(ENTITY_FLY, 0, 0, -1); + + Entity_Player* beelzebub = players.GetRandomPlayer(npc.initSeed); + if (beelzebub && !npc.isDead) + { + if (npc.type == ENTITY_ATTACKFLY || npc.type == ENTITY_FLY) + { + g_game->scoreSheet.AddKilledEnemy(npc); + npc.Remove(); + beelzebub->AddBlueFlies(1, npc.pos, nullptr); + } + else if (!npc.IsBoss() && !npc.IsFriendly()) npc.AddCharmed(EntityRef(beelzebub), -1, true, false); + } + + if (npc.i1 > 0) + { + npc.health = std::min(npc.health + npc.maxHitPoints / REGENERATION_FRAMES, npc.maxHitPoints); + npc.i1--; + } + + fly_animation_update(npc); + fly_poop_eat(npc); + if (npc.type == ENTITY_POOTER && !isSkatoleActive) pooter_attack_update(npc); + + bool isIsaacsFly = npc.spawnerType == ENTITY_ISAAC_BOSS && npc.subtype != 0; + if (isIsaacsFly) NpcAI::ENTITY_FLY_isaac_spawned(&npc); + else if (npc.spawnerType == ENTITY_ORBIT_SPAWNER) return NpcAI::ENTITY_FLY_orbit_parent(&npc); + else fly_target_pick(npc, isSkatoleActive); + + if ((npc.type == ENTITY_FLY || npc.type == ENTITY_POOTER) && !isIsaacsFly) npc.targetPosition = {}; + fly_flee_update(npc); + if (!isIsaacsFly) fly_target_follow(npc); + + if (npc.entityGridCollisionClass == GRIDCOLL_NONE && g_game->room->IsPositionInRoom(npc.pos, npc.size) && + room_grid_collision_at(npc.pos) < GRID_COLLISION_WALL) + npc.entityGridCollisionClass = GRIDCOLL_WALLS; + fly_drift_update(npc); +} diff --git a/src/npc_gaper.cpp b/src/npc_gaper.cpp new file mode 100644 index 0000000..652f09f --- /dev/null +++ b/src/npc_gaper.cpp @@ -0,0 +1,97 @@ +#include "npc_ai.h" +#include "game.h" + +constexpr int ENTITY_GAPER = 10; +constexpr int ENTITY_GUSHER = 11; +constexpr int GAPER_FROWNING = 1; +constexpr int GAPER_FLAMING = 2; +constexpr int GAPER_ROTTEN = 3; +constexpr int GUSHER_PACER = 1; +constexpr int GAPER_SOUND_DELAY = 40; +constexpr int GAPER_SOUND_ODDS = 3; +constexpr int GUSHER_ODDS = 3; +constexpr int GUSHER_COOLDOWN_MIN = 20; +constexpr int GUSHER_COOLDOWN_RANGE = 20; +constexpr float GAPER_OVERKILL = -25; +constexpr int GAPER_PATH_MARKER = 900; +constexpr float WALK_THRESHOLD = 0.1f; +constexpr float FLEE_FRICTION = 0.8f; +constexpr int CONTROLLER_ACTION_GROAN = 10; + +// How fast each gaper walks: a plain one, faster once its head is up, the frowning and flaming ones. +constexpr float GAPER_SPEED = 0.6f; +constexpr float GAPER_SPEED_HEAD_UP = 0.72f; +constexpr float GAPER_SPEED_FROWNING = 0.498f; +constexpr float GAPER_SPEED_FLAMING = 0.5478f; + +// A gaper's first frame: walking, with its head on the first frame of its overlay (a flaming one's head plays). +static void gaper_init(Entity_NPC& npc) +{ + npc.state = NPC_STATE_MOVE; + npc.stateFrame = 0; + if (npc.variant == GAPER_FLAMING) npc.sprite.PlayOverlay("Head"); + else if (npc.sprite.SetOverlayAnimation("Head", SWITCH_KEEP_FRAME) && npc.sprite.overlayAnimState.animData) + npc.sprite.overlayAnimState.SetFrameFloat(0); + + if (npc.sprite.SetAnimation("WalkVert", SWITCH_KEEP_FRAME) && npc.sprite.animState.animData) + { + npc.sprite.animState.SetFrameFloat(0); + npc.sprite.animState.isPlaying = false; + } +} + +// A dying gaper that was not torn apart may get up as a Gusher (a pacer one time in three). +static void gaper_death_update(Entity_NPC& npc) +{ + if (npc.health <= GAPER_OVERKILL || (Random() & 1) != 0) return; + + bool isPacer = Random() % GUSHER_ODDS == 0 && npc.variant != GAPER_FLAMING; + npc.Morph(ENTITY_GUSHER, isPacer ? GUSHER_PACER : 0, 0, -1); + npc.isDead = false; + uint32_t cooldown = Random(); + npc.health = npc.maxHitPoints; + npc.projectileCooldown = (int)(cooldown % GUSHER_COOLDOWN_RANGE) + GUSHER_COOLDOWN_MIN; +} + +// The speed a gaper walks its path at. +static float gaper_speed_get(Entity_NPC& npc) +{ + if (npc.variant == GAPER_FROWNING) return GAPER_SPEED_FROWNING; + if (npc.variant == GAPER_FLAMING) + { + npc.sprite.PlayOverlay("Head"); + return GAPER_SPEED_FLAMING; + } + return npc.sprite.GetOverlayFrame() > 0 ? GAPER_SPEED_HEAD_UP : GAPER_SPEED; +} + +// 00508f40 The gaper's AI (with the rotten gaper's own, and Fatty and the rest of its kin left to come): it walks +// its path to its target, groans now and then when it sees it, lifts its head, and its kin do not hurt it. +void npc_gaper_update(Entity_NPC& npc) +{ + if (npc.type == ENTITY_GAPER && npc.variant == GAPER_ROTTEN) return NpcAI::ENTITY_ROTTEN_GAPER(&npc); + if (npc.type != ENTITY_GAPER) reconstruction_missing("npc_gaper_update 00508f40: Fatty and the gaper's kin"); + + if (npc.pendingDamage > 0) + for (DamageEvent& event : npc.damageEvents) + if (event.source.spawnerType == npc.type) event.damage = 0; + if (npc.state == NPC_STATE_INIT) gaper_init(npc); + if (npc.isDead) return gaper_death_update(npc); + + npc.AnimWalkFrame("WalkHori", "WalkVert", WALK_THRESHOLD); + npc.aiFloat = gaper_speed_get(npc); + if (!npc.HasEntityFlags(FLAG_SHRINK | FLAG_FEAR)) + npc.pathfinder.FindGridPath(npc.CalcTargetPosition(0), npc.aiFloat, GAPER_PATH_MARKER, true); + else + { + npc.pathfinder.EvadeTarget(npc.GetPlayerTarget()->pos, STATUS_OBEYED); + npc.friction *= FLEE_FRICTION; + } + + bool isGroaning = npc.controllerID == -1 ? npc.IsHostileTo(npc.GetPlayerTarget()) && npc.pathfinder.hasDirectPath && + Random() % GAPER_SOUND_ODDS == 0 + : npc.IsControllerActionTriggered(CONTROLLER_ACTION_GROAN); + if (isGroaning) npc.PlaySound(SOUND_ZOMBIE_WALKER_KID, 1, GAPER_SOUND_DELAY, false, 1); + if (npc.variant == 0 && npc.pathfinder.hasDirectPath && npc.sprite.GetOverlayFrame() < 1) + npc.sprite.PlayOverlay("Head", PLAY_FORCED); +} diff --git a/src/npc_horf.cpp b/src/npc_horf.cpp new file mode 100644 index 0000000..2bea9e3 --- /dev/null +++ b/src/npc_horf.cpp @@ -0,0 +1,103 @@ +#include "npc_ai.h" +#include "entity_effect.h" +#include "game.h" + +constexpr int ENTITY_PSY_HORF = 248; +constexpr int EFFECT_BLOOD_EXPLOSION = 2; +constexpr int BLOOD_EXPLOSION_SPIT = 5; +constexpr int SOUND_HORF_SHOOT = 146; +constexpr float HORF_FRICTION = 0.7f; +constexpr float HORF_RANGE = 200; +constexpr int HORF_RANGE_FRAMES = 7; +constexpr int HORF_COOLDOWN = 28; +constexpr int HORF_HARD_COOLDOWN = 14; +constexpr float HORF_SHOT_SPEED = 7; +constexpr float HORF_HARD_SHOT_SPEED = 10; +constexpr float MOVEMENT_DEADZONE = 0.1f; +constexpr float SPIT_OFFSET_Y = -10; +constexpr float SPIT_DEPTH = 1; +constexpr float PITCH_TINY = 1.5f; +constexpr float PITCH_GIANT = 0.5f; +constexpr int COLOR_PRIORITY_DEFAULT = 255; +constexpr ColorMod SPIT_COLOR = {{1, 1, 1, 0.4f}, {0, 0, 0, 0}, {0.6f, 0.1f, 0.1f}}; +constexpr ColorMod PSY_SPIT_COLOR = {{1, 1, 1, 0.6f}, {0.8f, 0.15f, 1, 1}, {0.26f, 0.05f, 0.4f}}; +constexpr uint64_t PROJECTILE_SMART = 1; + +// The movement its controlling player steers, none without one, kept while the stick rests. +static void horf_controller_update(Entity_NPC& npc, bool isKeptAtRest) +{ + if (npc.controllerID == -1) + { + npc.controllerMovement = {}; + return; + } + Vector input = npc.GetControllerMovementInput(MOVEMENT_DEADZONE); + if (!isKeptAtRest || !vector_is_zero(input)) npc.controllerMovement = input; +} + +// A Horf's spit: a blood burst in its mouth and a shot at its target (a homing one for the Psy Horf). +static void horf_shoot(Entity_NPC& npc) +{ + Vector aim = vector_sub(npc.GetPlayerTarget()->pos, npc.pos); + if (npc.controllerID != -1 && !vector_is_zero(npc.controllerMovement)) aim = npc.controllerMovement; + aim = vector_resized(aim, game_is_hard_mode() ? HORF_HARD_SHOT_SPEED : HORF_SHOT_SPEED); + + Entity_Effect* spit = static_cast(g_game->Spawn({.position = npc.pos, + .subType = BLOOD_EXPLOSION_SPIT, + .type = ENTITY_EFFECT, + .variant = EFFECT_BLOOD_EXPLOSION, + .seed = Random()})); + spit->SetColor(COLOR_DEFAULT, -1, COLOR_PRIORITY_DEFAULT, false, true); + spit->sprite.offset = vector_make(0, SPIT_OFFSET_Y); + spit->renderDepthOffset = SPIT_DEPTH; + spit->parent = &npc; + spit->parentOffset = vector_sub(spit->pos, npc.pos); + spit->sprite.isFlipX = true; + spit->isFollowing = true; + spit->SetColor(SPIT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + + ProjectileParams params; + if (npc.type == ENTITY_PSY_HORF) + { + params.bulletFlags |= PROJECTILE_SMART; + spit->SetColor(PSY_SPIT_COLOR, -1, COLOR_PRIORITY_DEFAULT, false, true); + } + npc.FireProjectiles(npc.pos, aim, PROJECTILES_SINGLE, params); + + float pitch = npc.championColorIdx == CHAMPION_TINY ? PITCH_TINY + : npc.championColorIdx == CHAMPION_GIANT ? PITCH_GIANT + : 1; + npc_sound_play(SOUND_HORF_SHOOT, 1, 2, pitch); +} + +// 00513080 The Horf's AI: it stays put shaking, and spits at its target in range (twice as often on Hard). +void npc_horf_update(Entity_NPC& npc) +{ + npc.friction *= HORF_FRICTION; + if (npc.projectileCooldown > 0) + { + npc.projectileCooldown -= npc_ticks_get(npc); + horf_controller_update(npc, true); + } + if (npc.projectileCooldown < 1 && npc.IsTargetInAttackRange(HORF_RANGE, HORF_RANGE_FRAMES, false)) + { + npc.projectileCooldown = game_is_hard_mode() ? HORF_HARD_COOLDOWN : HORF_COOLDOWN; + npc.sprite.Play("Attack"); + horf_controller_update(npc, false); + } + + AnimationState& animation = npc.sprite.animState; + if (animation.animData) + { + if (animation.IsEventTriggered("Shoot")) horf_shoot(npc); + if (animation.animData && animation.isPlaying) return; + } + + bool isShaking = animation.animData && animation.animData->name == "Shake" && + (!animation.animData->isLooping || animation.isPlaying); + if (!isShaking && npc.sprite.SetAnimation("Shake", SWITCH_KEEP_FRAME)) + { + animation.Rewind(); + animation.isPlaying = true; + } +} diff --git a/src/path_finder.cpp b/src/path_finder.cpp new file mode 100644 index 0000000..e2709e5 --- /dev/null +++ b/src/path_finder.cpp @@ -0,0 +1,109 @@ +#include "path_finder.h" +#include "entity_npc.h" +#include "game.h" +#include "log.h" +#include "room.h" + +constexpr float GRID_CELL = 40; +constexpr float GRID_TOP = 120; +constexpr float HALF = 0.5f; +constexpr int PATH_ENEMY_TYPE_LAST = 999; + +// 007e3260 Forgets every path, target and evasion, and its grid cell. +void PathFinder::Reset() +{ + gridIndex = -1; + pathStep = 0; + moveCountdown = 0; + hasDirectPath = false; + isPathFound = false; + gridPathTarget = {}; + evadeMovementCountdown = 0; + evadeDistance = 0; + stuckFrames = 0; + visitedGridIndices.clear(); + direction = PATH_DIRECTION_NONE; + directionTimer = 0; + targetGridIndex = -1; + canCrushRocks = false; + movementTarget = {}; + moveDirection = {}; +} + +// 007e6fa0 Forgets the spot it wanders to. +void PathFinder::ResetMovementTarget() +{ + movementTarget = {}; + moveDirection = {}; +} + +// 007e6ff0 Notes the grid cell its owner stands in, or -1 outside the grid. +void PathFinder::UpdateGridIndex() +{ + Room& room = *g_game->room; + int column = (int)((entity->pos.x - GRID_CELL) / GRID_CELL + HALF); + int row = (int)((entity->pos.y - GRID_TOP) / GRID_CELL + HALF); + bool isInside = column >= 0 && column < room.gridWidth && row >= 0 && row < room.gridHeight; + gridIndex = isInside ? room.gridWidth * row + column : -1; +} + +// 007e3340 Whether its owner paths as the players' side: charmed, the Blood Puppy, after a baited target, or an +// enemy under a player's control or forced onto a target. +bool PathFinder::is_entity_friendly() +{ + if (!entity) return false; + if (entity->HasEntityFlags(FLAG_CHARM) || entity->type == ENTITY_BLOOD_PUPPY) return true; + if (entity->target && entity->target->HasEntityFlags(FLAG_BAITED)) return true; + if (entity->type < ENTITY_FIRST_ENEMY || entity->type > PATH_ENEMY_TYPE_LAST) return false; + + Entity_NPC* npc = static_cast(entity); + return npc->controllerID != -1 || npc->forcedTarget; +} + +// 007e33c0 +void PathFinder::FindGridPath(const Vector&, float, int, bool) +{ + reconstruction_missing("PathFinder::FindGridPath 007e33c0"); +} + +// 007e4940 +void PathFinder::EvadeTarget(const Vector&, StatusMode) +{ + reconstruction_missing("PathFinder::EvadeTarget 007e4940"); +} + +// 007e6300 +bool PathFinder::MoveRandomly(StatusMode) +{ + reconstruction_missing("PathFinder::MoveRandomly 007e6300"); +} + +// 007e5340 +void PathFinder::MoveRandomlyAxisAligned(float, StatusMode) +{ + reconstruction_missing("PathFinder::MoveRandomlyAxisAligned 007e5340"); +} + +// 007e6650 +void PathFinder::MoveRandomlyBoss(StatusMode) +{ + reconstruction_missing("PathFinder::MoveRandomlyBoss 007e6650"); +} + +// 007e6b90 +void PathFinder::update_chase_movement() +{ + reconstruction_missing("PathFinder::update_chase_movement 007e6b90"); +} + +// 007e7070 +bool PathFinder::HasPathToPos(const Vector&, bool) +{ + reconstruction_missing("PathFinder::HasPathToPos 007e7070"); +} + +// 007e8010 +void PathFinder::SimulatePlayerMovement(float*) +{ + reconstruction_missing("PathFinder::SimulatePlayerMovement 007e8010"); +} diff --git a/src/path_finder.h b/src/path_finder.h new file mode 100644 index 0000000..be415d6 --- /dev/null +++ b/src/path_finder.h @@ -0,0 +1,64 @@ +#pragma once + +#include "classes.h" +#include + +struct Entity; + +// Lua's Direction, the way SimulatePlayerMovement reads a movement. +enum PathDirection : int +{ + PATH_DIRECTION_NONE = -1, + PATH_DIRECTION_LEFT, + PATH_DIRECTION_UP, + PATH_DIRECTION_RIGHT, + PATH_DIRECTION_DOWN +}; + +// Whether a movement call steers even while its owner is feared, confused or charmed. +enum StatusMode +{ + STATUS_OBEYED, + STATUS_IGNORED +}; + +// Construction (007e31a0) is the default, with the owner given by its holder. +// Field accessors (00456370, 00456740, 00499dc0, 004be6e0) are the public fields. +// How an NPC finds its way around the room (Lua's PathFinder, the original's NPCAI_Pathfinder): the grid path it +// follows to a target, the spot it wanders to, and the evasion it keeps up. +struct PathFinder +{ + std::set visitedGridIndices; + Entity* entity = nullptr; + Vector gridPathTarget{}; + Vector moveDirection{}; + Vector movementTarget{}; + float evadeDistance = 0; + int direction = PATH_DIRECTION_NONE; + int directionTimer = 0; + int evadeMovementCountdown = 0; + int gridIndex = -1; + int moveCountdown = 0; + int pathLength = 0; + int pathStep = 0; + int stuckFrames = 0; + int targetGridIndex = -1; + bool canCrushRocks = false; + bool hasDirectPath = false; + bool isPathFound = false; + + explicit PathFinder(Entity* owner) : entity(owner) {} + + void Reset(); + void ResetMovementTarget(); + void UpdateGridIndex(); + bool is_entity_friendly(); + void FindGridPath(const Vector& position, float speed, int pathMarker, bool isUseDirectPath); + void EvadeTarget(const Vector& targetPos, StatusMode mode); + bool MoveRandomly(StatusMode mode); + void MoveRandomlyAxisAligned(float speed, StatusMode mode); + void MoveRandomlyBoss(StatusMode mode); + void update_chase_movement(); + bool HasPathToPos(const Vector& position, bool isIgnorePoop); + void SimulatePlayerMovement(float* inputs); +}; diff --git a/src/player_manager.cpp b/src/player_manager.cpp index 5d482b6..f321945 100644 --- a/src/player_manager.cpp +++ b/src/player_manager.cpp @@ -4,8 +4,10 @@ #include "entity_player.h" #include "game.h" #include "item_config.h" +#include "kage_input.h" #include "log.h" #include "manager.h" +#include "menu_manager.h" #include "platform.h" #include "popups.h" #include "preload_manager.h" @@ -28,6 +30,25 @@ constexpr float PLAYER_START_X = 320; constexpr float PLAYER_START_Y = 400; constexpr int HOURGLASS_INDEX_LAST = 3; +// The join carousel: the frames a joined player cannot act, its minimum invincibility, how far from the first player it +// appears, and how far over a leaving baby's poof shows. +constexpr int JOIN_CONTROLS_COOLDOWN = 15; +constexpr int JOIN_DAMAGE_COOLDOWN = 45; +constexpr float JOIN_SPAWN_DISTANCE = 10; +constexpr float LEAVE_POOF_HEIGHT = 10; +constexpr float JOIN_MENU_POSITION = 1; +constexpr int COOP_BABY_MIN_HEARTS = 3; +constexpr int EFFECT_POOF01 = 15; +constexpr int SOUND_JOIN_REFUSED = 187; +constexpr int SOUND_CAROUSEL_LEFT = 194; +constexpr int SOUND_CAROUSEL_RIGHT = 195; +constexpr float JOIN_REFUSED_VOLUME = 0.5f; + +// The static buildup the poisoned players' rising damage plays, louder as it builds. +constexpr int SOUND_STATIC_BUILDUP = 508; +constexpr float STATIC_BUILDUP_FRAMES = 20; +constexpr float STATIC_BUILDUP_MIN_VOLUME = 0.01f; + // How far apart get_player_start_position spreads the players, and the rows past two players. constexpr float START_SPACING = 48; constexpr float START_ROW_OFFSET = 24; @@ -796,12 +817,205 @@ void PlayerManager::restore_controller_assignment() { reconstruction_missing("PlayerManager::restore_controller_assignment 009bf530"); } -void PlayerManager::handle_coop_join() { reconstruction_missing("PlayerManager::handle_coop_join 009bac40"); } void PlayerManager::spawn_coop_baby_for_join(int) { reconstruction_missing("PlayerManager::spawn_coop_baby_for_join 009bd3b0"); } -void PlayerManager::Update() { reconstruction_missing("PlayerManager::Update 009bb5d0"); } +// Plays a sound at a volume, unless the seeds swap it for a fart. +static void manager_sound_play(int sound, SoundPlay play = {}) +{ + seed_fart_sound_override(&sound); + g_manager->sfxManager.Play(sound, play); +} + +// Takes an action's buttons on a device as used this frame, so they do not trigger again until released. +static void device_action_consume(KAGE::Input::InputDevice& device, ButtonAction action) +{ + const InputBindings& bindings = platform.bindings; + const std::vector& table = + device.type == KAGE::Input::DEVICE_KEYBOARD ? bindings.keyboard : bindings.controller; + + if (action >= (int)table.size()) return; + for (int button : table[action]) + if (button != KAGE::Input::BUTTON_NONE) device.button_consume(button); +} + +// Whether a controller is a player's, a kept extra player's, or an open seat's. +static bool is_controller_joined(PlayerManager& players, int controller, Entity_Player** joined) +{ + bool isJoined = false; + + for (Entity_Player* player : players.playerList) + if (player->controllerIndex == controller) + { + isJoined = true; + *joined = player; + } + for (Entity_Player* extra : players.extraPlayers) isJoined = isJoined || extra->controllerIndex == controller; + for (CoopJoinSlot& seat : players.coopSlots) isJoined = isJoined || (seat.controllerIndex == controller && seat.state >= 0); + return isJoined; +} + +// A controller's join input: joining opens a seat on the carousel, or a co-op baby when only babies may join, refused +// in dailies. Pressing join again takes a co-op baby out. Joining with bomb and pill held spawns a possessor. +static void controller_join_update(PlayerManager& players, KAGE::Input::InputDevice& device) +{ + Game& game = *g_game; + int controller = device.id; + Entity_Player* joined = nullptr; + bool isJoined = is_controller_joined(players, controller, &joined); + + bool isPossessor = !isJoined && is_controller_action(controller, ACTION_JOIN_MULTIPLAYER, ACTION_TRIGGERED) && + is_controller_action(controller, ACTION_BOMB, ACTION_PRESSED) && + is_controller_action(controller, ACTION_PILL_CARD, ACTION_PRESSED); + if (isPossessor) + { + game.console.print_format(CONSOLE_WHITE, "Joining as possessor\n"); + players.SpawnCoPlayer2(-1)->SetControllerIndex(controller, true); + return; + } + + bool isJoinAllowed = !PlayerManager::CoopBabiesOnly() || + players.GetPlayer(0)->soulHearts + players.GetPlayer(0)->redHearts >= COOP_BABY_MIN_HEARTS; + if (game.dailyChallenge._id == 0 && isJoinAllowed && players.playerList.size() < MAX_PLAYERS && !isJoined) + { + int slot = is_controller_action(controller, ACTION_JOIN_MULTIPLAYER, ACTION_TRIGGERED) + ? players.GetPlayerSlotFromController(controller) : -1; + if (slot < 0) return; + if (PlayerManager::CoopBabiesOnly()) return players.spawn_coop_baby_for_join(controller); + + CoopJoinSlot& seat = players.coopSlots[slot]; + bool isForced = game.challenge != 0 || game.dailyChallenge._id != 0; + if (!isForced) device_action_consume(device, ACTION_JOIN_MULTIPLAYER); + seat.playerType = isForced ? game.GetChallengeParams().playerType : 0; + seat.state = 1; + seat.menuPosition = JOIN_MENU_POSITION; + seat.isPlayerTypeForced = isForced; + return; + } + if (game.dailyChallenge._id != 0 && !isJoined) + { + if (is_controller_action(controller, ACTION_JOIN_MULTIPLAYER, ACTION_TRIGGERED)) + manager_sound_play(SOUND_JOIN_REFUSED, {.volume = JOIN_REFUSED_VOLUME}); + return; + } + if (!isJoined || !joined || joined->parent) return; + if (!is_controller_action(controller, ACTION_JOIN_MULTIPLAYER, ACTION_TRIGGERED) || joined->variant == PLAYER_VARIANT_PLAYER) + return; + if (joined->sprite.animState.animData && joined->sprite.animState.isPlaying && joined->sprite.GetAnimation() == "Appear") + return; + + Entity_Player* first = players.GetPlayer(0); + if (first->isPlayingExtraAnimation || first->isPlayingItemAnimation) return; + uint32_t seed = Random(); + game.Spawn({.position = vector_make(joined->pos.x, joined->pos.y - LEAVE_POOF_HEIGHT), .type = ENTITY_EFFECT, + .variant = EFFECT_POOF01, .seed = seed}); + players.RemoveCoPlayer(joined); +} + +// A seat of the join carousel: left and right pick a character, confirming (or a forced character) spawns the player +// beside the first one, and backing out closes the seat. Only co-op babies may join closes it at once. +static void coop_seat_update(PlayerManager& players, CoopJoinSlot& seat) +{ + if (seat.controllerIndex < 0 || seat.state < 0) return; + if (PlayerManager::CoopBabiesOnly()) + { + seat.state = -1; + return; + } + + std::vector& types = players.coopPlayerTypes; + int carousel = (int)types.size(); + if (is_controller_action(seat.controllerIndex, ACTION_MENU_LEFT, ACTION_TRIGGERED)) + { + if (--seat.state < 0) seat.state = carousel - 1; + seat.playerType = types[seat.state]; + return manager_sound_play(SOUND_CAROUSEL_LEFT); + } + if (is_controller_action(seat.controllerIndex, ACTION_MENU_RIGHT, ACTION_TRIGGERED)) + { + if (++seat.state >= carousel) seat.state = 0; + seat.playerType = types[seat.state]; + return manager_sound_play(SOUND_CAROUSEL_RIGHT); + } + + bool isConfirmed = is_controller_action(seat.controllerIndex, ACTION_MENU_CONFIRM, ACTION_TRIGGERED) || seat.isPlayerTypeForced; + if (!isConfirmed) + { + if (is_controller_action(seat.controllerIndex, ACTION_MENU_BACK, ACTION_TRIGGERED)) seat.state = -1; + return; + } + + // A carousel of the random pick alone picks past its end in the original, so it picks the random pick here. + int playerType = seat.playerType; + seat.isPlayerTypeForced = false; + if (playerType == COOP_CHARACTER_RANDOM) + playerType = carousel > 1 ? types[1 + Random() % (uint32_t)(carousel - 1)] : types[0]; + + Game& game = *g_game; + Entity_Player* player = game.playerManager.SpawnCoPlayer2(playerType); + player->SetControllerIndex(seat.controllerIndex, true); + Vector first = game.playerManager.GetPlayer(0)->pos; + float angle = (float)Random() * RANDOM_SCALE * HALF_TURN; + angle += angle; + player->pos = vector_make(std::cos(angle) * JOIN_SPAWN_DISTANCE + first.x, std::sin(angle) * JOIN_SPAWN_DISTANCE + first.y); + game.hud.AssignPlayerHUDs(); + player->InitPostLevelInitStats(); + player->controlsCooldown = JOIN_CONTROLS_COOLDOWN; + game.Spawn({.position = player->pos, .type = ENTITY_EFFECT, .variant = EFFECT_POOF01, .seed = Random()}); + player->damageCooldown = std::max(player->damageCooldown, JOIN_DAMAGE_COOLDOWN); + seat.state = -1; +} + +// 009bac40 Co-op joining each frame, offline only: every controller's join input, then the join carousel's seats, then +// the extra players' spectated target. +void PlayerManager::handle_coop_join() +{ + if (!g_manager->netplayManager.is_online()) + { + for (int i = 0; i < KAGE::Input::manager.get_device_count(); i++) + if (std::shared_ptr device = KAGE::Input::manager.get_device(i)) + controller_join_update(*this, *device); + for (CoopJoinSlot& seat : coopSlots) coop_seat_update(*this, seat); + } + for (size_t i = 0; i < extraPlayers.size(); i++) extraPlayers[i]->cycle_spectate_target(); +} + +// 009bb5d0 The players each frame: those dead whose death animation (and their twin's) has ended trigger their death +// outside transitions, and the static buildup plays as loud as the most poisoned player's. +void PlayerManager::Update() +{ + Game& game = *g_game; + + if (game.roomTransition.mode == TRANSITION_NONE && game.stageTransition._state == 0) + for (size_t i = 0; i < game.playerManager.playerList.size(); i++) + { + Entity_Player* player = GetPlayer((int)i); + Entity_Player* twin = player->twin_get(); + bool isAnimating = player->sprite.animState.animData && player->sprite.animState.isPlaying; + bool isTwinAnimating = twin && twin->sprite.animState.animData && twin->sprite.animState.isPlaying; + if (player->isDead && !isAnimating && !isTwinAnimating) player->TriggerDeath(false); + } + + float volume = 0; + for (size_t i = 0; i < game.playerManager.playerList.size(); i++) + { + Entity_Player* player = GetPlayer((int)i); + if (player->poisonDamageFrames > 0 && !player->HasEntityFlags(FLAG_POISON) && !player->isDead) + volume = std::max(volume, std::clamp((float)player->poisonDamageFrames / STATIC_BUILDUP_FRAMES, 0.0f, 1.0f)); + } + + SFXManager& sfx = g_manager->sfxManager; + if (volume <= STATIC_BUILDUP_MIN_VOLUME) + { + if (sfx.IsPlaying(SOUND_STATIC_BUILDUP)) sfx.Stop(SOUND_STATIC_BUILDUP); + return; + } + if (!sfx.IsPlaying(SOUND_STATIC_BUILDUP)) return manager_sound_play(SOUND_STATIC_BUILDUP, {.volume = volume, .loop = SOUND_LOOP}); + sfx.AdjustVolume(SOUND_STATIC_BUILDUP, volume); + sfx.AdjustPitch(SOUND_STATIC_BUILDUP, 1); +} + void PlayerManager::trigger_room_clear() { reconstruction_missing("PlayerManager::trigger_room_clear 009bb840"); } void PlayerManager::trigger_coop_baby_death(Entity_Player*) { @@ -824,7 +1038,6 @@ void PlayerManager::RestoreGameState_PostLevelInit(GameState*) { reconstruction_missing("PlayerManager::RestoreGameState_PostLevelInit 009bd010"); } -void PlayerManager::store_game_state(GameState*) { reconstruction_missing("PlayerManager::store_game_state 009bd150"); } int* PlayerManager::match_saved_players(int*, int, bool) { reconstruction_missing("PlayerManager::match_saved_players 009bc790"); diff --git a/src/room.cpp b/src/room.cpp index 8b87ee8..b595af1 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -3374,3 +3374,54 @@ void Room::card_against_humanity_fill() { reconstruction_missing("Room::card_against_humanity_fill 007fe220"); } + +// The last frames of a clear's delay that leaving the room still counts the clear in. +constexpr int ROOM_CLEAR_DELAY_PENDING = 8; + +// Whether the room keeps an entity when the players leave, as Entity_Pickup::CanFlip (007eeeb0) checks before saving +// it: alive, not persistent, off any minecart (unless it rides the one saved with it), and of a kept type. +static bool is_entity_kept(Room& room, Entity& entity, bool isRiding) +{ + if (entity.isDead || (entity.flags & FLAG_PERSISTENT) || (entity.minecart && !isRiding)) return false; + return entity_type_is_saved(entity.type, entity.variant, (uint32_t)entity.subtype, entity.spawnerType, room.IsClear()); +} + +// 007efa50 Stores the room in its descriptor as the players leave: a partial shop restock comes due, and a clear still +// pending counts (the score, the players' room clear, the award and Greed's wave). Then, outside the debug room and +// once visited, its grid cells and the entities it keeps (a minecart only with its rider) are saved. +void Room::on_leave() +{ + Game& game = *g_game; + + if (shopRestockTimer > 0) + { + shopRestockTimer = -1; + reconstruction_missing("Room::ShopRestockPartial 008158a0"); + } + if (game.currentRoomIdx == ROOM_DEBUG_IDX || descriptor->visitedCount == 0) return; + if (roomClearDelay >= 1 && roomClearDelay <= ROOM_CLEAR_DELAY_PENDING && !IsClear()) + { + bool isGreedWave = game.IsGreedMode() && roomType == ROOM_DEFAULT; + + roomClearDelay = 0; + descriptor->flags |= ROOM_DESCRIPTOR_FLAG_CLEAR; + descriptor->clearCount++; + game.scoreSheet.add_cleared_room({descriptor->clearCount, descriptor->data->shape, roomType, + (descriptor->flags & ROOM_DESCRIPTOR_FLAG_RED_ROOM) != 0}); + if (!isGreedWave) game.playerManager.trigger_room_clear(); + reconstruction_missing("Room::SpawnClearAward 007fb250"); + if (isGreedWave) game.greedLastBeatenWave = game.greedModeWave; + } + + descriptor->savedEntities.clear(); + for (int i = 0; i < gridWidth * gridHeight; i++) + descriptor->savedGridEntities[i] = gridEntities[i] ? gridEntities[i]->desc_save() : GRID_SAVE_EMPTY; + for (Entity* entity : entityList.updateEL) + { + bool isCart = entity->type == ENTITY_MINECART && entity->variant == 0; + Entity* rider = entity->child.get(); + bool isKept = isCart ? rider && is_entity_kept(*this, *rider, true) && is_entity_kept(*this, *entity, false) + : is_entity_kept(*this, *entity, false); + if (isKept) reconstruction_missing("Room::on_leave 007efa50: saving an entity (EntitySaveState has no layout yet)"); + } +} diff --git a/src/room.h b/src/room.h index ea40d63..5904ea9 100644 --- a/src/room.h +++ b/src/room.h @@ -308,6 +308,7 @@ public: void PlayMusic(); void Update(); + void on_leave(); void update_ambient_sounds(); void first_frame_update(); void grid_paths_decay(); diff --git a/src/room_transition.cpp b/src/room_transition.cpp index 450b064..6a08242 100644 --- a/src/room_transition.cpp +++ b/src/room_transition.cpp @@ -4,6 +4,7 @@ #include "fx_layers.h" #include "game.h" #include "grid_entity_door.h" +#include "level.h" #include "log.h" #include "manager.h" #include "platform.h" @@ -46,6 +47,15 @@ constexpr int MINECART_RIDDEN = 10; constexpr int NPC_STATE_MINECART_MOVING = 4; constexpr int COLLECTIBLE_GLOWING_HOURGLASS = 422; constexpr int COLLECTIBLE_D7 = 437; +constexpr const char* ANIMATION_APPEAR = "Appear"; +constexpr float APPEAR_FRAME = 2; +constexpr float SCREEN_CELL_SIZE = 26; +constexpr int ROOM_CELLS_ACROSS = 13; +constexpr int ROOM_CELLS_DOWN = 7; +constexpr int DEATH_CERTIFICATE_DIMENSION = 2; +constexpr int STAGE_ID_HOME = 35; +constexpr int DOGMA_ROOM_VARIANT = 1000; +constexpr uint32_t BOSS_DOGMA = 99; // The items whose pickup animation an extra life plays once the player is back, from the Ankh to Lazarus' Rags: Ankh, // Dead Cat, 1up!, Guppy's Collar, Judas' Shadow and Lazarus' Rags. @@ -130,9 +140,137 @@ void RoomTransition::StartBossIntro(uint32_t, uint32_t) reconstruction_missing("RoomTransition::StartBossIntro 0082f1c0"); } +// The distance between two rooms in screen pixels, mirrored in the mirror world: from their map cells when both lie on +// the map of one dimension, else the size of the room on the side left through (the target's for left and up). +static Vector room_distance_get(RoomDescriptor& current, RoomDescriptor& target, bool isOnMap, Direction direction) +{ + Vector distance{}; + + if (isOnMap) + { + int columns = target.gridIndex % LEVEL_GRID_WIDTH - current.gridIndex % LEVEL_GRID_WIDTH; + int rows = target.gridIndex / LEVEL_GRID_WIDTH - current.gridIndex / LEVEL_GRID_WIDTH; + distance = vector_make((float)(columns * ROOM_CELLS_ACROSS) * SCREEN_CELL_SIZE, + (float)(rows * ROOM_CELLS_DOWN) * SCREEN_CELL_SIZE); + } + else switch (direction) + { + case DIRECTION_LEFT: + distance.x = -(float)target.data->width * SCREEN_CELL_SIZE; + break; + case DIRECTION_UP: + distance.y = -(float)target.data->height * SCREEN_CELL_SIZE; + break; + case DIRECTION_RIGHT: + distance.x = (float)current.data->width * SCREEN_CELL_SIZE; + break; + case DIRECTION_DOWN: + distance.y = (float)current.data->height * SCREEN_CELL_SIZE; + break; + default: + break; + } + if (Room::IsMirrorWorld()) distance.x = -distance.x; + return distance; +} + +// How far past a screen the rooms slide through a door: the rooms' distance less the camera's change between them, +// across mirrored in the mirror world. +void RoomTransition::slide_offset_set(Vector distance, Vector oldScroll) +{ + Vector newScroll = g_game->room->renderScrollOffset; + float across = Room::IsMirrorWorld() ? oldScroll.x - newScroll.x : newScroll.x - oldScroll.x; + + switch (direction) + { + case DIRECTION_LEFT: + slideOffset.x = across - g_screenWidth - distance.x; + break; + case DIRECTION_UP: + slideOffset.y = newScroll.y - oldScroll.y - g_screenHeight - distance.y; + break; + case DIRECTION_RIGHT: + slideOffset.x = -across - g_screenWidth + distance.x; + break; + case DIRECTION_DOWN: + slideOffset.y = oldScroll.y - newScroll.y - g_screenHeight + distance.y; + break; + default: + break; + } +} + +// Puts the players in the new room. A teleport keeps them hidden, else the main players not held show. The Forgotten's +// body, the Death Certificate's floor, a teleporter's pad and the Ventricle Razor's portals place them. +void RoomTransition::arrival_place() +{ + Game& game = *g_game; + Room& room = *game.room; + bool isTeleporterRoom = room.roomType == ROOM_TELEPORTER || room.roomType == ROOM_TELEPORTER_EXIT; + + if (animation == TRANSITION_WOMB_TELEPORT) + { + for (VentricleRazorPortal& portal : game.ventricleRazorPortals) + if (portal.roomIndex == game.currentRoomIdx) + reconstruction_missing("RoomTransition::ChangeRoom 00830950: the players jumping out of a Ventricle " + "Razor portal (Entity_Player +0x14c, +0x98)"); + return; + } + if (!is_teleport()) + for (Entity_Player* player : game.playerManager.playerList) + if (player->variant == PLAYER_VARIANT_PLAYER && !(player->flags & FLAG_HELD)) player->isVisible = true; + + if (animation == TRANSITION_FORGOTTEN_TELEPORT && game.playerManager.roomTransitionPlayer) + reconstruction_missing("RoomTransition::ChangeRoom 00830950: Entity_Player::Teleport 007cd950 to the body"); + else if (animation == TRANSITION_DEATH_CERTIFICATE && game.currentDimensionIdx == DEATH_CERTIFICATE_DIMENSION) + reconstruction_missing("RoomTransition::ChangeRoom 00830950: the players placed on the Death Certificate floor"); + else if (animation == TRANSITION_DEATH_CERTIFICATE) + for (Entity_Player* player : game.playerManager.playerList) + { + if (!player) continue; + player->PlayExtraAnimation(ANIMATION_APPEAR); + if (player->sprite.animState.animData) player->sprite.animState.SetFrameFloat(APPEAR_FRAME); + player->isControlsEnabled = false; + } + else if (animation == TRANSITION_TELEPORT && teleporterTarget > 0 && isTeleporterRoom) + reconstruction_missing("RoomTransition::ChangeRoom 00830950: Entity_Player::Teleport 007cd950 to a teleporter"); +} + +// 00830950 Takes the players into the target room (the Glowing Hourglass rewinds the room instead), their controls on +// while it loads, and works out how far a walk through a door slides. The new room's boss gets its versus screen +// (Dogma's living room too), else the room plays its music. The players are placed and the new room is captured. void RoomTransition::ChangeRoom() { - reconstruction_missing("RoomTransition::ChangeRoom 00830950"); + Game& game = *g_game; + std::vector& players = game.playerManager.playerList; + RoomDescriptor& current = *game.GetRoomByIdx(game.currentRoomIdx, game.currentDimensionIdx); + RoomDescriptor& target = *game.GetRoomByIdx(roomIndex, roomDimension); + bool isOnMap = roomIndex >= 0 && game.currentRoomIdx >= 0 && current.dimension == target.dimension; + Vector distance = room_distance_get(current, target, isOnMap, direction); + Vector oldScroll = game.room->renderScrollOffset; + + if (game.deathmatchManager.state < DEATHMATCH_INTRO) + for (Entity_Player* player : players) player->isControlsEnabled = true; + if (animation == TRANSITION_GLOWING_HOURGLASS) reconstruction_missing("Game::rewind 00706020"); + else + { + if (direction == DIRECTION_NONE) game.leaveDoor = DOOR_NONE; + game.ChangeRoom(roomIndex, roomDimension); + } + for (Entity_Player* player : players) player->isControlsEnabled = false; + if (animation == TRANSITION_WALK) slide_offset_set(distance, oldScroll); + + Room& room = *game.room; + RoomConfig_Room* data = room.descriptor->data; + bool isDogmaRoom = data && data->stageId == STAGE_ID_HOME && data->type == ROOM_DEFAULT && + data->variant == DOGMA_ROOM_VARIANT && !room.IsClear(); + + if (room.bossId != 0 && room.GetAliveBossesCount() >= 1) StartBossIntro(room.bossId, room.secondBossId); + else if (isDogmaRoom) StartBossIntro(BOSS_DOGMA, 0); + else if (game.deathmatchManager.state < DEATHMATCH_INTRO) room.PlayMusic(); + + arrival_place(); + room_capture(newRoomSurface); } // Whether a player plays an extra or item animation that holds the transition: one not looping. @@ -248,12 +386,25 @@ void RoomTransition::start_update(Entity_NPC* minecartNpc) old_room_capture(); } +// Renders the room as it stands, lit, into a surface. +void RoomTransition::room_capture(KAGE::Graphics::ImagePtr& surface) +{ + KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; + + g_game->room->render_lighting(); + graphics.render_target_push(surface.get(), KAGE::Graphics::TARGET_SCREEN_SIZE, KAGE::Graphics::PRESENT_FLUSH); + graphics.Clear(); + graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL); + g_game->room->Render(); + graphics.Present(KAGE::Graphics::PRESENT_FINISH); + graphics.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); +} + // Hides the players leaving (all of them, but only the one who walked out through a door or pixelated) and renders // the room into the old room surface. A fade shows it going out, a forced boss or arena transition changing room at // once, and anything else changes room and comes in. void RoomTransition::old_room_capture() { - KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; Game& game = *g_game; bool isWalking = animation == TRANSITION_WALK || animation == TRANSITION_PIXELATION; @@ -264,14 +415,7 @@ void RoomTransition::old_room_capture() (!isWalking || direction == DIRECTION_NONE || player == game.playerManager.roomTransitionPlayer)) player->isVisible = false; - game.room->render_lighting(); - graphics.render_target_push(oldRoomSurface.get(), KAGE::Graphics::TARGET_SCREEN_SIZE, - KAGE::Graphics::PRESENT_FLUSH); - graphics.Clear(); - graphics.blendMode.SetMode(KAGE::Graphics::BLEND_NORMAL); - game.room->Render(); - graphics.Present(KAGE::Graphics::PRESENT_FINISH); - graphics.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); + room_capture(oldRoomSurface); bool isChangedAtOnce = animation == TRANSITION_BOSS_FORCED || animation == TRANSITION_ARENA; if (is_fade() || isChangedAtOnce) @@ -547,6 +691,12 @@ bool RoomTransition::is_active() return mode != TRANSITION_NONE; } +// 006f0070 Whether a transition shows a boss's versus screen. +bool RoomTransition::is_versus_screen() +{ + return mode != TRANSITION_NONE && bossIntroBossId != 0; +} + // 0082eb90 Whether the players teleport out: a teleport, a womb teleport, the Glowing Hourglass or the D7. bool RoomTransition::is_teleport() { diff --git a/src/room_transition.h b/src/room_transition.h index 9f99aa6..9b9735e 100644 --- a/src/room_transition.h +++ b/src/room_transition.h @@ -20,7 +20,7 @@ enum RoomTransitionMode : int }; // How the players leave the room (Lua's RoomTransitionAnim). The extra lives play their item's pickup animation once -// in the new room, and ARENA enters the versus mode's arena. +// in the new room, ARENA enters the versus mode's arena and TRAPDOOR is a trap door's way into a secret exit. enum RoomTransitionAnim : int { TRANSITION_WALK, @@ -44,16 +44,17 @@ enum RoomTransitionAnim : int TRANSITION_FADE_MIRROR, TRANSITION_MINECART, TRANSITION_DEATH_CERTIFICATE, - TRANSITION_ARENA + TRANSITION_ARENA, + TRANSITION_TRAPDOOR }; // What Game::StartRoomTransition asks for: the room and dimension (negative for the current one), the door side left -// through (DIRECTION_NONE for none), the animation and the player who started it. +// through (none by default), the animation and the player who started it. struct RoomTransitionRequest { Entity_Player* player = nullptr; RoomTransitionAnim animation = TRANSITION_WALK; - Direction direction{}; + Direction direction = static_cast(-1); int dimension = -1; int roomIndex = 0; }; @@ -91,6 +92,7 @@ public: void Render(); bool is_active(); + bool is_versus_screen(); bool is_teleport(); bool is_fade(); float get_hud_alpha(); @@ -99,6 +101,9 @@ public: private: void start_update(Entity_NPC* minecartNpc); void old_room_capture(); + void room_capture(KAGE::Graphics::ImagePtr& surface); + void slide_offset_set(Vector distance, Vector oldScroll); + void arrival_place(); void versus_screen_update(); void arrival_update(); void landing_update(); diff --git a/src/room_update.cpp b/src/room_update.cpp index 3de2e69..cdfcc3b 100644 --- a/src/room_update.cpp +++ b/src/room_update.cpp @@ -36,6 +36,15 @@ constexpr float DOOR_PUSH_SPEED_SQUARED = 4; constexpr float DOOR_PUSH_FRAMES = 2; constexpr int DOOR_SLOT_SIDES = 4; constexpr float DUNGEON_EXIT_MARGIN = 20; +constexpr float DUNGEON_LADDER_Y = 110; +constexpr float DUNGEON_LADDER_LEFT = 100; +constexpr float DUNGEON_LADDER_RIGHT = 140; +constexpr uint32_t DUNGEON_BLACK_MARKET_DOOR = 1u << DIRECTION_RIGHT; +constexpr int ROOM_PASSAGE_IDX = -14; +constexpr int ROOM_PASSAGE_EXIT_IDX = -15; +constexpr int ROOM_INDEX_OTHER_DIMENSION = -100; +constexpr uint64_t GAME_STATE_ANGEL_ROOM_SPAWNED = 1ull << 0; +constexpr uint64_t GAME_STATE_DEVIL_ROOM_SPAWNED = 1ull << 5; // The weather a stage rains down: the drops' chances, and the Downpour's lightning flash and thunder. constexpr float WEATHER_DROP_Y = -10; @@ -365,7 +374,10 @@ static void clear_update(Room& room) } if (isDungeon && dungeonKind == DUNGEON_ROTGUT) return; if (isDungeon && dungeonKind == DUNGEON_ROTGUT_HEART) - reconstruction_missing("Room::Update 00802980: Game::StartRoomTransition 006fd7c0 out of Rotgut's heart"); + { + game.enterDoor = DOOR_NONE; + game.StartRoomTransition({.roomIndex = game.dungeonReturnRoomIndex}); + } bool isBackwards = game.stage >= 1 && game.stage <= 6 && game.GetStateFlag(GAME_STATE_BACKWARDS_PATH); if (game.stage != STAGE_HOME && !isBackwards) g_manager->musicManager.DisableLayer(0); @@ -407,10 +419,73 @@ static void pressure_plates_update(Room& room) reconstruction_missing("Room::update_pressure_plates 008024f0: the fireplaces' morph"); } +// Leaves through a door slot: the rewind state is saved and the door left recorded, a devil or angel room is made the +// first time its door is used, and a door to another dimension's room (below -99) goes there, by a mirror's fade for +// the other world's twin. +static void door_leave(Room& room, Entity_Player& player, int slot) +{ + Game& game = *g_game; + GridEntity_Door& door = *room.doors[slot]; + RoomTransitionRequest request = {.player = &player, .direction = (Direction)(slot % DOOR_SLOT_SIDES)}; + + game.save_rewind_state(slot); + game.leaveDoor = slot; + if (door.targetRoomIdx == ROOM_DEVIL_IDX && !game.GetRoomByIdx(ROOM_DEVIL_IDX)->data) + { + bool isAngel = door.targetRoomType == ROOM_ANGEL; + game.InitializeDevilAngelRoom(isAngel, !isAngel); + game.gameStateFlags |= isAngel ? GAME_STATE_ANGEL_ROOM_SPAWNED : GAME_STATE_DEVIL_ROOM_SPAWNED; + } + request.roomIndex = door.targetRoomIdx; + if (request.roomIndex <= ROOM_INDEX_OTHER_DIMENSION) + { + RoomDescriptor& target = *game.GetRoomByIdx(request.roomIndex); + if (door.targetRoomIdx == ROOM_INDEX_OTHER_DIMENSION) request.animation = TRANSITION_FADE_MIRROR; + request.dimension = target.dimension; + request.roomIndex = target.gridIndex; + } + game.StartRoomTransition(request); + game.isPocketItemRewindSaved = false; +} + +// A crawlspace's exits: up its ladder back to the room it was entered from by a pixelation, or walking out past its +// right edge (to the error room, the black market from a crawlspace with one, or on from the passage room), its left +// edge or its bottom (to the error room). Returns whether the player left. +static bool dungeon_exit(Room& room, Entity_Player& player) +{ + Game& game = *g_game; + Vector position = player.pos; + bool isUp = position.y < GRID_ORIGIN_Y || (position.y < DUNGEON_LADDER_Y && position.x > DUNGEON_LADDER_LEFT && + position.x < DUNGEON_LADDER_RIGHT); + RoomTransitionRequest request = {.player = &player, .roomIndex = ROOM_ERROR_IDX}; + + if (isUp) + { + request.animation = TRANSITION_PIXELATION; + request.direction = (Direction)game.enterDoor; + request.roomIndex = game.dungeonReturnRoomIndex; + game.StartRoomTransition(request); + return true; + } + if (room.bottomRightPos.x + DUNGEON_EXIT_MARGIN < position.x) + { + bool isBlackMarket = room.descriptor->data->doors & DUNGEON_BLACK_MARKET_DOOR; + request.direction = DIRECTION_RIGHT; + if (room.descriptor->gridIndex == ROOM_PASSAGE_IDX) request.roomIndex = ROOM_PASSAGE_EXIT_IDX; + else if (isBlackMarket) request.roomIndex = ROOM_BLACK_MARKET_IDX; + } + else if (position.x < 0) request.direction = DIRECTION_LEFT; + else if (room.bottomRightPos.y + DUNGEON_EXIT_MARGIN < position.y) request.direction = DIRECTION_DOWN; + else return false; + + game.leaveDoor = request.direction; + game.StartRoomTransition(request); + return true; +} + // 007f01c0 Takes the players through the doors: a player standing at an open door's edge (a mirror door's closed // edge) leaves through it, and one pushing into a locked door of a cleared room tries to unlock it. Tainted Forgotten // pushes by its speed. A crawlspace's exits lead back up or out to its neighbours. -// Leaving a room (Game::save_rewind_state, Game::StartRoomTransition) is not reconstructed yet. static void door_transitions_update(Room& room) { Game& game = *g_game; @@ -449,20 +524,11 @@ static void door_transitions_update(Room& room) bool isOpen = door->state == DOOR_STATE_OPEN; bool isPassable = door->doorFlags & DOOR_FLAG_MIRROR ? !isOpen : isOpen; - if (isPassable && distance < DOOR_ENTER_DISTANCE) - reconstruction_missing("Room::update_door_transitions 007f01c0: leaving through a door " - "(Game::StartRoomTransition 006fd7c0)"); + if (isPassable && distance < DOOR_ENTER_DISTANCE) return door_leave(room, player, slot); if (isLockedKind && room.IsClear() && distance < DOOR_UNLOCK_DISTANCE && direction == side) door->TryUnlock(player, false); } - if (room.roomType != ROOM_DUNGEON) continue; - - bool isUp = position.y < GRID_ORIGIN_Y; - bool isOut = room.bottomRightPos.x + DUNGEON_EXIT_MARGIN < position.x || position.x < 0 || - room.bottomRightPos.y + DUNGEON_EXIT_MARGIN < position.y; - if (isUp || isOut) - reconstruction_missing("Room::update_door_transitions 007f01c0: a crawlspace's exits " - "(Game::StartRoomTransition 006fd7c0)"); + if (room.roomType == ROOM_DUNGEON && dungeon_exit(room, player)) return; } }