Przeglądaj źródła

Split the entity manager into several files

- The manager is divided by subject: movement, triggers, player control and random encounters. The functions are unchanged.
Iñigo Valentin 1 dzień temu
rodzic
commit
80cec8447b

+ 4 - 0
src/engine/entity/CMakeLists.txt

@@ -4,6 +4,10 @@ vgears_sources(
     EntityCollision.cpp
     EntityDirection.cpp
     EntityManager.cpp
+    EntityManagerEncounters.cpp
+    EntityManagerMovement.cpp
+    EntityManagerPlayer.cpp
+    EntityManagerTriggers.cpp
     EntityModel.cpp
     EntityPoint.cpp
     EntityTrigger.cpp

+ 0 - 1361
src/engine/entity/EntityManager.cpp

@@ -14,10 +14,6 @@
  */
 
 #include <algorithm>
-#include <cstdlib>
-#include <iostream>
-#include <cmath>
-#include <limits>
 #include <OgreEntity.h>
 #include <OgreRoot.h>
 #include <OgreViewport.h>
@@ -26,7 +22,6 @@
 #include "engine/graphics/DebugDraw.h"
 #include "engine/entity/EntityManager.h"
 #include "engine/entity/EntityModel.h"
-#include "engine/input/InputManager.h"
 #include "common/Logger.h"
 #include "engine/script/ScriptManager.h"
 #include "engine/Timer.h"
@@ -35,39 +30,10 @@
 /**
  * Entity manager singleton.
  */
-/**
- * Priority of the script that runs when the player presses OK in front of an entity.
- *
- * It has to run before the scripts that fields leave running on an entity (the loops that play an
- * animation, requested with priority 5 or 6), or the entity could not be talked to. But it can't
- * be the highest: a script of the same entity that is requested with a higher priority (3 or
- * smaller) has to be able to run while the talk script waits for it, as in the scenes where a
- * talk script asks its own entity to do something and waits for it to start.
- */
-static const int INTERACT_SCRIPT_PRIORITY = 4;
-
 template<>EntityManager *Ogre::Singleton<EntityManager>::msSingleton = nullptr;
 
 ConfigVar cv_debug_grid("debug_grid", "Draw debug grid", "false");
 ConfigVar cv_debug_axis("debug_axis", "Draw debug axis", "false");
-ConfigVar cv_encounter_multiplier(
-  "encounter_multiplier", "Multiplier of the random encounter rate (0 disables them)", "1"
-);
-ConfigVar cv_debug_encounters("debug_encounters", "Log random encounter checks", "false");
-
-/**
- * Frames of walking (at 30 frames per second) between two encounter checks. The original game
- * checks every 8 frames.
- */
-static const float ENCOUNTER_CHECK_FRAMES = 8.0f;
-
-/**
- * Value added to the encounter accumulator in each check, before dividing it by the rate of the
- * table. The original game uses the speed of the player, which is not known here, so this is tuned
- * to a battle every 15-30 seconds of walking in most fields. The encounter_multiplier cvar scales
- * it.
- */
-static const float ENCOUNTER_STEP_VALUE = 5.0f;
 
 const float EntityManager::SCENE_SCALE = 1.0f / 255.0f;
 
@@ -75,73 +41,6 @@ const unsigned int EntityManager::BATTLE_BACKGROUND_ID = 1000;
 
 const unsigned int EntityManager::WORLD_MAP_BACKGROUND_ID = 1001;
 
-float EntityManager::GetTriangleHeight(int triangle, float x, float y, float fallback) const{
-    if (IsBattleModule() || triangle < 0 || triangle >= walkmesh_.GetNumberOfTriangles())
-        return fallback;
-    const float height = PointElevation(
-      Ogre::Vector2(x, y), walkmesh_.GetA(triangle), walkmesh_.GetB(triangle),
-      walkmesh_.GetC(triangle)
-    );
-    return std::isfinite(height) ? height : fallback;
-}
-
-float EntityManager::PointElevation(
-  const Ogre::Vector2& point, const Ogre::Vector3& a, const Ogre::Vector3& b, const Ogre::Vector3& c
-){
-    float _a = a.z * (b.y - c.y) + b.z * (c.y - a.y) + c.z * (a.y - b.y);
-    float _b = a.y * (b.x - c.x) + b.y * (c.x - a.x) + c.y * (a.x - b.x);
-    float _c = a.x * (b.z - c.z) + b.x * (c.z - a.z) + c.x * (a.z - b.z);
-    float _d
-      = a.x * (b.z * c.y - c.z * b.y) + b.x * (c.z * a.y - a.z * c.y)
-        + c.x * (a.z * b.y - b.z * a.y);
-    return (_d - _c * point.y - _a * point.x) / _b;
-}
-
-float EntityManager::SideOfVector(
-  const Ogre::Vector2& point, const Ogre::Vector2& p1, const Ogre::Vector2& p2
-){
-    Ogre::Vector2 AB = p2    - p1;
-    Ogre::Vector2 AP = point - p1;
-    return AB.x * AP.y - AB.y * AP.x;
-}
-
-float EntityManager::SquareDistanceToLine(
-  const Ogre::Vector3& point, const Ogre::Vector3& point_a, const Ogre::Vector3& point_b,
-  Ogre::Vector3& proj
-){
-    float temp =
-      -((point_a.x - point.x) * (point_b.x - point_a.x) + (point_a.y - point.y)
-      * (point_b.y - point_a.y) + (point_a.z - point.z) * (point_b.z - point_a.z))
-      / ((point_b.x - point_a.x) * (point_b.x - point_a.x) + (point_b.y - point_a.y)
-      * (point_b.y - point_a.y) + (point_b.z - point_a.z) * (point_b.z - point_a.z));
-
-    proj.x = temp * (point_b.x - point_a.x) + point_a.x;
-    proj.y = temp * (point_b.y - point_a.y) + point_a.y;
-    proj.z = temp * (point_b.z - point_a.z) + point_a.z;
-
-    if (
-      ((point_a.x >= proj.x && point_b.x <= proj.x) || (point_a.x < proj.x && point_b.x >= proj.x))
-      && (
-        (point_a.y >= proj.y && point_b.y <= proj.y) || (point_a.y < proj.y && point_b.y >= proj.y)
-      )
-    ){
-        return (proj.x - point.x) * (proj.x - point.x) + (proj.y - point.y)
-          * (proj.y - point.y) + (proj.z - point.z) * (proj.z - point.z);
-    }
-    return -1;
-}
-
-Ogre::Degree EntityManager::GetDirectionToPoint(
-  const Ogre::Vector3& current_point, const Ogre::Vector3& direction_point
-){
-    // TODO: Declare function in header file.
-    Ogre::Vector2 up(0.0f, -1.0f);
-    Ogre::Vector2 dir(direction_point.x - current_point.x, direction_point.y - current_point.y);
-    // Angle between vectors
-    Ogre::Degree angle(Ogre::Radian(SafeAcos(dir.dotProduct(up), dir.length() * up.length())));
-    return (dir.x < 0) ? Ogre::Degree(360) - angle : angle;
-}
-
 EntityManager::EntityManager():
     background_3d_(nullptr),
   player_entity_(nullptr),
@@ -181,56 +80,6 @@ EntityManager::~EntityManager(){
     LOG_TRIVIAL("EntityManager destroyed.");
 }
 
-void EntityManager::Input(const VGears::Event& event){
-    background_2d_.InputDebug(event);
-    if (paused_ == true) return;
-    if (ignore_held_walk_){
-        InputManager& input = InputManager::getSingleton();
-        if (
-          !input.IsGameEventPressed("walk_left") && !input.IsGameEventPressed("walk_right")
-          && !input.IsGameEventPressed("walk_up") && !input.IsGameEventPressed("walk_down")
-        ) ignore_held_walk_ = false;
-    }
-    if (player_entity_ != NULL && player_lock_ == false){
-        // Keys held since the world map are ignored until they are released.
-        const bool key_ignored = ignore_held_walk_ && (
-          event.event == "walk_left" || event.event == "walk_right" || event.event == "walk_up"
-          || event.event == "walk_down" || event.event == "run"
-        );
-        if (!key_ignored){
-            if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_left") player_move_.x = -1;
-            else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_right")
-                player_move_.x = 1;
-            if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_down") player_move_.y = -1;
-            else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_up")
-                player_move_.y = 1;
-            if (event.type == VGears::ET_KEY_REPEAT && event.event == "run") player_run_ = true;
-        }
-        if (event.type == VGears::ET_KEY_PRESS && event.event == "CONFIRM"){
-            CheckEntityInteract();
-            for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
-                if (
-                  entity_triggers_[i]->IsEnabled() == true
-                  && entity_triggers_[i]->CheckApproached() == true
-                ){
-                    ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
-                      ScriptManager::ENTITY, entity_triggers_[i]->GetName()
-                    );
-                    bool added = ScriptManager::getSingleton().ScriptRequest(
-                      scr_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
-                    );
-                    if (added == false){
-                        LOG_WARNING(
-                          "Script 'on_interact' for entity '" + entity_triggers_[i]->GetName()
-                          + "' doesn't exist."
-                        );
-                    }
-                }
-            }
-        }
-    }
-}
-
 void EntityManager::UpdateField(){
     // Update all entity scripts
     ScriptManager::getSingleton().Update(ScriptManager::ENTITY);
@@ -682,27 +531,6 @@ void EntityManager::ClearWorld(){
 
 Walkmesh* EntityManager::GetWalkmesh(){return &walkmesh_;}
 
-bool EntityManager::IsWorldPositionBlocked(
-    const Entity* moving_entity, const Ogre::Vector3& position
-) const{
-        if (!IsWorldModule() || moving_entity == nullptr) return false;
-
-        for (const Entity* other : entity_){
-                if (other == moving_entity || !other->IsSolid()) continue;
-
-                const Ogre::Vector3 other_position = other->GetPosition();
-                const Ogre::Real dx = position.x - other_position.x;
-                const Ogre::Real dz = position.z - other_position.z;
-                const Ogre::Real radius = moving_entity->GetSolidRadius() + other->GetSolidRadius();
-                if (dx * dx + dz * dz >= radius * radius) continue;
-
-                const Ogre::Real moving_top = position.y + moving_entity->GetHeight();
-                const Ogre::Real other_top = other_position.y + other->GetHeight();
-                if (position.y < other_top && other_position.y < moving_top) return true;
-        }
-        return false;
-}
-
 Background2D* EntityManager::GetBackground2D(){return &background_2d_;}
 
 ScreenFade* EntityManager::GetScreenFade(){return &screen_fade_;}
@@ -737,21 +565,6 @@ void EntityManager::ScriptAddEntity(
   const float x, const float y, const float z, const float rotation, int index
 ){AddEntity(name, file_name, Ogre::Vector3(x, y, z), Ogre::Degree(rotation), index);}
 
-void EntityManager::AddEntityTrigger(
-  const Ogre::String& name,
-  const Ogre::Vector3& point1, const Ogre::Vector3& point2, const bool enabled
-){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to add an entity trigger but the EntityManager is in battle mode.");
-        return;
-    }
-    EntityTrigger* trigger = new EntityTrigger(name);
-    trigger->SetPoints(point1, point2);
-    trigger->SetEnabled(enabled);
-    entity_triggers_.push_back(trigger);
-    ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, trigger->GetName(), nullptr);
-}
-
 void EntityManager::AddEntityPoint(
   const Ogre::String& name, const Ogre::Vector3& position, const float rotation
 ){
@@ -822,131 +635,6 @@ EntityPoint* EntityManager::ScriptGetEntityPoint(const char* name) const{
     return nullptr;
 }
 
-void EntityManager::ScriptSetPlayerEntity(const char* name){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set a player entity but the EntityManager is in battle mode.");
-        return;
-    }
-    for (unsigned int i = 0; i < entity_.size(); ++ i){
-        if (entity_[i]->GetName() == name){
-            // A script can read the walkmesh triangle of the player right after this, so if it was
-            // placed by position the triangle has to be known. Done before it's the player entity
-            // so that the entity not being on the walkmesh yet isn't logged as an error.
-            if (entity_[i]->GetMoveTriangleId() == -1 && entity_[i]->GetPosition().isZeroLength()){
-                // A model that has no position of its own (the fields put the dressed Cloud away
-                // until a script makes it the player) takes the place of the previous player,
-                // which is where the field entry put the party, as in the original game.
-                if (player_entity_ != nullptr && player_entity_ != entity_[i]){
-                    entity_[i]->SetPosition(player_entity_->GetPosition());
-                    entity_[i]->SetRotation(player_entity_->GetRotation());
-                }
-            }
-            if (entity_[i]->GetMoveTriangleId() == -1) SetEntityOnWalkmesh(entity_[i]);
-            LOG_TRIVIAL("Player entity set to '" + std::string(name) + "'.");
-            // The camera that follows the player keeps following it when another entity takes over
-            // (Cloud and the dressed Cloud, for example); a camera that follows some other entity
-            // is left as it is.
-            if (player_entity_ != nullptr && background_2d_.GetAutoScrollEntity() == player_entity_)
-                background_2d_.ScriptAutoScrollToEntity(entity_[i]);
-            // The camera follows the player when no script has said anything about it (the fields
-            // without a Director, such as ujunon1, have no opcode that starts it).
-            else if (!background_2d_.HasScrollControl())
-                background_2d_.ScriptAutoScrollToEntity(entity_[i]);
-            player_entity_ = entity_[i];
-            // Also, make it non-talkable. Visibility and solidity are left to the scripts, as in
-            // the original game: some fields use hidden helper entities (like the 'camera') as
-            // the player entity to scroll the screen, and they must stay invisible and
-            // non-solid. When the player moves manually, UpdateField makes it solid anyway.
-            entity_[i]->SetTalkable(false);
-        }
-    }
-}
-
-void EntityManager::ScriptPlacePlayerAtFieldEntry(
-    const float x, const float y, const int triangle_id, const float direction
-){
-        if (player_entity_ == nullptr || walkmesh_.GetNumberOfTriangles() <= 0) return;
-
-        int safe_triangle_id = triangle_id;
-        if (safe_triangle_id < 0 || safe_triangle_id >= walkmesh_.GetNumberOfTriangles()){
-                LOG_WARNING("World-map field entry has an invalid walkmesh triangle; using triangle 0.");
-                safe_triangle_id = 0;
-        }
-
-        player_entity_->SetPosition(Ogre::Vector3(
-            x, y, walkmesh_.GetA(static_cast<unsigned int>(safe_triangle_id)).z
-        ));
-        player_entity_->SetRotation(Ogre::Degree(direction));
-        player_entity_->SetMoveTriangleId(safe_triangle_id);
-        // In the WALKMESH state the entity walks to its move position: without this one it walks to
-        // whatever it had (the origin of the field), and the player enters the town walking.
-        player_entity_->SetMovePosition(player_entity_->GetPosition());
-        player_entity_->SetState(Entity::WALKMESH);
-        // The player starts standing still: no move or run from the world map, and the held keys
-        // don't count until they are released.
-        player_move_ = Ogre::Vector3::ZERO;
-        player_run_ = false;
-        ignore_held_walk_ = true;
-        player_entity_->PlayAnimationContinue(player_entity_->GetDefaultAnimationName());
-}
-
-Entity* EntityManager::ScriptGetPlayerEntity() const{
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set a player entity but the EntityManager is in battle mode.");
-        return nullptr;
-    }
-    return player_entity_;
-}
-
-void EntityManager::ScriptUnsetPlayerEntity(){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to unset a player entity but the EntityManager is in battle mode.");
-        return;
-    }
-    player_entity_ = nullptr;
-}
-
-void EntityManager::ScriptSetPlayerSlip(const bool slip){player_slip_ = slip;}
-
-void EntityManager::ScriptPlayerLock(const bool lock){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set player lock but the EntityManager is in battle mode.");
-        return;
-    }
-    player_lock_ = lock;
-    if (lock == true) player_move_ = Ogre::Vector3::ZERO;
-    // A field with no entity for the leader of the party (the parade of junonr4, where the player
-    // is a soldier that no PC opcode names) gives the control to the entity whose script lets go
-    // of it.
-    else if (player_entity_ == nullptr && IsFieldModule()){
-        const ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
-        Entity* entity = GetEntity(script.entity);
-        if (entity != nullptr && !entity->IsLine()){
-            LOG_TRIVIAL("The control goes to '" + script.entity + "', there is no player entity.");
-            ScriptSetPlayerEntity(script.entity.c_str());
-            if (!background_2d_.HasScrollControl()) background_2d_.ScriptAutoScrollToEntity(entity);
-        }
-    }
-}
-
-bool EntityManager::IsPlayerLocked() const{return player_lock_;}
-
-void EntityManager::SetPlayerDefaultRun(const bool run){player_default_run_ = run;}
-
-void EntityManager::SetPlayerMoveRotation(const Ogre::Radian rotation){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set player move rotation the EntityManager is in battle mode.");
-        return;
-    }
-    player_move_rotation_ = rotation;
-}
-
-float EntityManager::GetEncounterMultiplier() const{return cv_encounter_multiplier.GetF();}
-
-bool EntityManager::IsDebugEncounters() const{return cv_debug_encounters.GetB();}
-
-void EntityManager::SetRandomEncounters(bool active){random_encounters_ = active;}
-
 void EntityManager::HideFieldEntities(){
     entities_hidden_by_battle_.clear();
     for (Entity* entity : entity_){
@@ -965,136 +653,6 @@ void EntityManager::ShowFieldEntities(){
     entities_hidden_by_battle_.clear();
 }
 
-void EntityManager::ClearEncounterTables(){
-    encounter_tables_.clear();
-    encounter_table_ = 1;
-    encounter_distance_ = 0.0f;
-    encounter_last_position_valid_ = false;
-    encounter_accumulator_ = 0;
-    encounter_last_battle_ = -1;
-}
-
-void EntityManager::AddEncounterTable(
-  const int id, const int rate, const std::vector<std::pair<int, int>>& battles,
-  const std::vector<std::pair<int, int>>& specials
-){
-    EncounterTable table;
-    table.rate = rate;
-    table.battles = battles;
-    table.specials = specials;
-    encounter_tables_[id] = table;
-}
-
-void EntityManager::ScriptSetEncounterTable(const int id){encounter_table_ = id;}
-
-int EntityManager::ScriptRollEncounterBattle() const{
-    auto found = encounter_tables_.find(encounter_table_);
-    if (found == encounter_tables_.end()) return -1;
-    const EncounterTable& table = found->second;
-    // Like the original game: a roll out of 64 is checked against the special battles one after
-    // the other (each one adds its probability). If none is hit, a new roll chooses a standard
-    // battle, the last one being the default.
-    int roll = std::rand() % 64;
-    int sum = 0;
-    for (const auto& special : table.specials){
-        sum += special.second;
-        if (roll < sum) return special.first;
-    }
-    if (table.battles.empty()) return -1;
-    roll = std::rand() % 64;
-    sum = 0;
-    for (const auto& battle : table.battles){
-        sum += battle.second;
-        if (roll < sum) return battle.first;
-    }
-    return table.battles.back().first;
-}
-
-void EntityManager::UpdateEncounters(const bool walked){
-    if (player_entity_ == nullptr){
-        encounter_last_position_valid_ = false;
-        return;
-    }
-    const Ogre::Vector3 position = player_entity_->GetPosition();
-    const float distance
-      = encounter_last_position_valid_ ? (position - encounter_last_position_).length() : 0.0f;
-    encounter_last_position_ = position;
-    encounter_last_position_valid_ = true;
-    // Only walking counts: not scripted movements, and not jumps to another place.
-    if (!walked || player_lock_ || distance > 2.0f) return;
-    if (!random_encounters_ || encounter_tables_.empty()) return;
-    auto found = encounter_tables_.find(encounter_table_);
-    if (found == encounter_tables_.end()) return;
-    const float multiplier = cv_encounter_multiplier.GetF();
-    if (multiplier <= 0.0f) return;
-    // Same as the original game. Every few frames of walking the accumulator grows by a value
-    // divided by the rate (the lower the rate, the more often the encounters), and an encounter
-    // starts if a random number is lower than the accumulator.
-    const int rate = found->second.rate;
-    if (rate <= 0) return;
-    encounter_distance_ += Timer::getSingleton().GetGameTimeDelta() * 30.0f;
-    while (encounter_distance_ >= ENCOUNTER_CHECK_FRAMES){
-        encounter_distance_ -= ENCOUNTER_CHECK_FRAMES;
-        // Enemy Away and Enemy Lure materia change the rate of the party (see Party.get_encounter_modifier).
-        const float materia_multiplier
-          = ScriptManager::getSingleton().EvaluateNumber("Party.get_encounter_modifier()", 1.0f);
-        encounter_accumulator_ += static_cast<int>(ENCOUNTER_STEP_VALUE * multiplier * materia_multiplier * 256.0f) / rate;
-        const int roll = std::rand() % 256 * 256;
-        if (cv_debug_encounters.GetB()){
-            LOG_TRIVIAL(
-              "Encounter check: rate " + std::to_string(rate) + ", accumulator "
-              + std::to_string(encounter_accumulator_ / 256.0f) + "/256, roll "
-              + std::to_string(roll / 256)
-            );
-        }
-        if (roll >= encounter_accumulator_) continue;
-        int battle = ScriptRollEncounterBattle();
-        // The same battle is not repeated: it's rolled again once.
-        if (battle == encounter_last_battle_) battle = ScriptRollEncounterBattle();
-        if (battle < 0) return;
-        encounter_distance_ = 0.0f;
-        encounter_accumulator_ = 0;
-        encounter_last_battle_ = battle;
-        LOG_TRIVIAL("Random encounter: battle " + std::to_string(battle));
-        // The battle is started by a script, as it has to change the module of every manager.
-        ScriptManager::getSingleton().RunString("Encounter.start(" + std::to_string(battle) + ")");
-        return;
-    }
-}
-
-bool EntityManager::IsStartKeyRead() const{
-    return std::chrono::steady_clock::now() - start_key_read_time_ < std::chrono::milliseconds(300);
-}
-
-bool EntityManager::IsKeyOn(unsigned int key_code){
-    if (key_code & 2048) start_key_read_time_ = std::chrono::steady_clock::now();
-    // The keys are read even if the player is locked: scenes lock the player and still ask for a
-    // button, as the minigames that need to be pressed at the right time do. The scripts that
-    // must not read the keys at some point (while a message is open, for example) have their own
-    // flag for it. The triggers that check keys aren't run while the player is locked.
-    // The key code of the scripts is a mask of the pad buttons, and the check is true if any of
-    // them is pressed. Translate each to its game event (see bind_game_event in config.cfg), so
-    // the keys chosen in the controller settings are the ones that count. For example 32 is
-    // "Circle/Action", the OK button.
-    static const struct{unsigned int mask; const char* event;} BUTTONS[] = {
-      {1, "L2"}, {2, "R2"}, {4, "L1"}, {8, "R1"}, {16, "MENU"}, {32, "CONFIRM"}, {64, "CANCEL"},
-      {128, "EXTRA"}, {256, "SELECT"}, {2048, "START"},
-      {4096, "Up"}, {8192, "Right"}, {16384, "Down"}, {32768, "Left"}
-    };
-    for (const auto& entry : BUTTONS)
-        if ((key_code & entry.mask) && InputManager::getSingleton().IsGameEventPressed(entry.event))
-            return true;
-    // TODO: In the original game the button that makes the player run is the Cancel button (64),
-    // so scripts that check Cancel are checking if the player runs (the sneak out of ealin_2, for
-    // example). Here running has its own game event, "run", so it counts as Cancel too. Scripts
-    // that really want the Cancel button would see it pressed while running. Check which scripts
-    // need which, and maybe split them.
-    if ((key_code & 64) && InputManager::getSingleton().IsGameEventPressed("run")) return true;
-    return false;
-}
-
-bool EntityManager::IsKeyOff(unsigned int key_code){return !IsKeyOn(key_code);}
-
 void EntityManager::SetEntityToCharacter(const char* entity_name, unsigned int char_id){
     if (IsBattleModule()){
         for (unsigned int i = 0; i < battle_entity_.size(); ++ i){
@@ -1117,922 +675,3 @@ void EntityManager::SetEntityToCharacter(const char* entity_name, unsigned int c
       + "'. No entity by that name exists."
     );
 }
-
-bool EntityManager::SetEntityOnWalkmesh(Entity* entity){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set entity on the walkmesh, but the EntityManager is in battle mode");
-        return false;
-    }
-    Ogre::Vector3 position3 = entity->GetPosition();
-    Ogre::Vector2 position2;
-    position2.x = position3.x;
-    position2.y = position3.y;
-    std::vector<std::pair<int, float>> triangles;
-    // Search for possible triangles.
-    for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
-        Ogre::Vector3 A3 = walkmesh_.GetA(i);
-        Ogre::Vector3 B3 = walkmesh_.GetB(i);
-        Ogre::Vector3 C3 = walkmesh_.GetC(i);
-        Ogre::Vector2 A2(A3.x, A3.y);
-        Ogre::Vector2 B2(B3.x, B3.y);
-        Ogre::Vector2 C2(C3.x, C3.y);
-        if (Ogre::Math::pointInTri2D(position2, A2, B2, C2) == true){
-            triangles.push_back(std::make_pair(i, PointElevation(
-              position2, walkmesh_.GetA(i), walkmesh_.GetB(i), walkmesh_.GetC(i)
-            )));
-        }
-    }
-    // If the coordinates doesn't match any triangle, exit.
-    if (triangles.size() == 0 && entity == player_entity_){
-        LOG_ERROR(
-          "Can't find any triangle to place entity '" + entity->GetName() + "' on walkmesh."
-        );
-        return false;
-    }
-    // From the possible triangles, select the closest one (on the Z edge).
-    int closest_z_triangle = -1;
-    float closest_z_distance = 9999.0f;
-    float pos_z = position3.z;
-    for (size_t i = 0; i < triangles.size(); ++ i){
-        if (std::abs(pos_z - triangles[i].second) < closest_z_distance){
-            closest_z_triangle = triangles[i].first;
-            closest_z_distance = std::abs(pos_z - triangles[i].second);
-        }
-    }
-    if (closest_z_triangle == -1 && entity == player_entity_){
-        LOG_ERROR(
-          "Can't find nearby triangle to place entity '" + entity->GetName() + "' on walkmesh."
-        );
-        return false;
-    }
-    entity->SetPosition(Ogre::Vector3(position2.x, position2.y, pos_z));
-    entity->SetMoveTriangleId(closest_z_triangle);
-    return true;
-}
-
-float EntityManager::TriggerReach(float solid_radius){
-    // The radius an entity has when a script doesn't change it.
-    const float default_radius = 0.21f;
-    return solid_radius < 0.01f ? default_radius : solid_radius;
-}
-
-bool EntityManager::WalkmeshEdgeBlocks(bool is_player, bool scripted_move){
-    return is_player || !scripted_move;
-}
-
-bool EntityManager::IsBetterInteractionTarget(
-  float angle, float distance, float best_angle, float best_distance
-){
-    const float same_angle = 0.001f;
-    if (angle < best_angle - same_angle) return true;
-    return std::fabs(angle - best_angle) <= same_angle && distance < best_distance;
-}
-
-float EntityManager::ScriptedMoveStep(float distance, float stop_distance, float max_step){
-    return std::min(max_step, std::max(0.0f, distance - stop_distance));
-}
-
-bool EntityManager::PerformWalkmeshMove(Entity* entity, const float speed, const float delta_time){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to perform a walkmesh move, but the EntityManager is in battle mode");
-        return false;
-    }
-    Ogre::Vector3 start_point = entity->GetPosition();
-    Ogre::Vector3 move_vector = entity->GetMovePosition() - start_point;
-    Ogre::Vector2 direction(move_vector.x, move_vector.y);
-    const float distance_to_target = direction.length();
-    const bool scripted_move = entity->IsScriptedMove();
-    const float stop_distance = entity->GetMoveStopDistance();
-    if (scripted_move && distance_to_target <= stop_distance + 0.0001f){
-        entity->UnsetMove();
-        return false;
-    }
-    direction.normalise();
-    direction *= delta_time;
-    direction *= speed;
-    if (scripted_move && !direction.isZeroLength()){
-        direction.normalise();
-        direction *= ScriptedMoveStep(
-          distance_to_target, stop_distance, speed * delta_time
-        );
-    }
-    // If movement is still needed but speed or time don't allow it, just return for now.
-    if (direction.isZeroLength() == true){
-        if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
-        return false;
-    }
-    int current_triangle = entity->GetMoveTriangleId();
-    // A character that is not on the walkmesh (Jenova of shpin_3, that is placed outside it and
-    // moves with FMOVE) is walked in a straight line, or the scene that waits for it would never go
-    // on.
-    if (current_triangle == -1 && scripted_move && entity != player_entity_){
-        const float step = std::min(direction.length(), distance_to_target);
-        Ogre::Vector2 move = direction;
-        if (!move.isZeroLength()) move.normalise();
-        move *= step;
-        entity->SetPosition(Ogre::Vector3(start_point.x + move.x, start_point.y + move.y, start_point.z));
-        if (distance_to_target - step <= stop_distance + 0.0001f) entity->UnsetMove();
-        return step > 0.0f;
-    }
-    if (current_triangle == -1){
-        // The entities that a scene places later (the soldiers of the parade of junonr4) are asked
-        // to move before it, and wait. Only the player has to be on the walkmesh.
-        if (entity == player_entity_)
-            LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
-        return false;
-    }
-    Ogre::Vector3 rotation(0.0f, 0.0f, 0.0f);
-    Ogre::Quaternion q1(0.0f, 0.0f, 0.0f, 1.0f);
-    Ogre::Vector3 end_point(0.0f, 0.0f, 0.0f);
-    Ogre::Vector3 end_point2(0.0f, 0.0f, 0.0f);
-    bool first_triangle_check = false;
-    bool second_triangle_check = false;
-    bool third_triangle_check = false;
-    bool last_triangle_check = false;
-    bool first_entity_check = false;
-    bool second_entity_check = false;
-    bool third_entity_check = false;
-    // Shorten move vector by triangle angle
-    end_point.x = start_point.x + direction.x;
-    end_point.y = start_point.y + direction.y;
-    Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
-    Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
-    Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
-    end_point.z = PointElevation(Ogre::Vector2(end_point.x, end_point.y), A3, B3, C3);
-    Ogre::Vector3 temp = end_point - start_point;
-    temp.normalise();
-    temp = temp * direction.length();
-    direction.x = temp.x;
-    direction.y = temp.y;
-    // Set the direction for the entity if it has to move.
-    if (entity->GetMoveAutoRotation() == true){
-        Ogre::Vector2 up(0.0f, -1.0f);
-        // Angle between vectors
-        Ogre::Degree angle(Ogre::Radian(SafeAcos(
-          direction.dotProduct(up), direction.length() * up.length()
-        )));
-        angle = (direction.x < 0) ? Ogre::Degree(360) - angle : angle;
-        entity->SetRotation(Ogre::Degree(angle));
-    }
-    // A scripted walk (also of the player entity, while a scene has it locked) must end, or the
-    // scene waiting for it would never go on. Several scripts place solid entities next to where
-    // another one has to walk to, so they don't block it: only the walkmesh does. A manual move
-    // of the player is never scripted.
-    // The same goes for the points around the end of the step: they are there for the player and
-    // NPCs to slide along walls, and a destination next to an edge of the walkmesh would never be
-    // reached. The end point itself is still checked.
-    const bool check_probes = !scripted_move;
-    float solid = (entity->IsSolid() == true) ? entity->GetSolidRadius() : 0.01f;
-
-    // For not playable entities, be a bit more lenient with solid collisions.
-    // Don't use the solid radius.
-    if (entity != player_entity_) solid /= 10;
-
-    // Get ending point.
-    end_point.z = start_point.z;
-    for (
-      int i = 0;
-      (entity == player_entity_ && i < 16)
-        || (entity == player_entity_ &&  i < 3)
-        || (entity != player_entity_ && i <= 16);
-      ++ i
-    ){
-        end_point = Ogre::Vector3(
-          start_point.x + direction.x, start_point.y + direction.y, start_point.z
-        );
-        // 1st check.
-        // Rotate move_vector +45.
-        q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(45)), Ogre::Vector3::UNIT_Z);
-        rotation.x = direction.x;
-        rotation.y = direction.y;
-        rotation.z = 0;
-        rotation.normalise();
-        rotation = q1 * rotation;
-        // Multiply move_vector by solid range
-        rotation = rotation * solid;
-        end_point2.x = end_point.x + rotation.x;
-        end_point2.y = end_point.y + rotation.y;
-        // Check_triangle.
-        first_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
-        entity->SetMoveTriangleId(current_triangle);
-        // Model check.
-        first_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
-
-        // 2nd check.
-        // Rotate move_vector +45.
-        q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-45)), Ogre::Vector3::UNIT_Z);
-        rotation.x = direction.x;
-        rotation.y = direction.y;
-        rotation.z = 0;
-        rotation.normalise();
-        rotation = q1 * rotation;
-        // Multiply move_vector by solid range.
-        rotation = rotation * solid;
-        end_point2.x = end_point.x + rotation.x;
-        end_point2.y = end_point.y + rotation.y;
-        // Check triangle.
-        second_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
-        entity->SetMoveTriangleId(current_triangle);
-        // Model check.
-        second_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
-
-        // 3rd check.
-        rotation.x = direction.x;
-        rotation.y = direction.y;
-        rotation.z = 0;
-        rotation.normalise();
-        rotation = rotation * solid;
-        end_point2.x = end_point.x + rotation.x;
-        end_point2.y = end_point.y + rotation.y;
-        // Check triangle.
-        third_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
-        entity->SetMoveTriangleId(current_triangle);
-        // Model check.
-        third_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
-
-        // Check condition and modify move_vector.
-        if (
-          first_triangle_check != false || second_triangle_check != false
-          || third_triangle_check != false || first_entity_check != false
-          || second_entity_check != false || third_entity_check != false
-        ){
-            // Only for NPC.
-            if (entity != player_entity_){
-                // If the entity collides only directly into a triangle border.
-                if (
-                  first_triangle_check  == false
-                  && second_triangle_check == false
-                  && third_triangle_check != false
-                ){
-                    q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-7)), Ogre::Vector3::UNIT_Z);
-                    rotation.x = direction.x;
-                    rotation.y = direction.y;
-                    rotation = q1 * rotation;
-                    direction.x = rotation.x;
-                    direction.y = rotation.y;
-                }
-                // Or if the entity only collides into other entity directly.
-                else if (
-                  first_entity_check == false && second_entity_check == false
-                  && third_entity_check != false
-                ){
-                    q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z);
-                    rotation.x = direction.x;
-                    rotation.y = direction.y;
-                    rotation = q1 * rotation;
-                    direction.x = rotation.x;
-                    direction.y = rotation.y;
-                }
-
-                // If not both left and right check failed.
-                if (first_triangle_check == false || second_triangle_check == false){
-                    if (
-                      (first_triangle_check == false && first_entity_check != false)
-                      || (first_triangle_check != false && second_triangle_check == false)
-                    ){
-                        q1.FromAngleAxis(
-                          Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
-                        );
-                        rotation.x = direction.x;
-                        rotation.y = direction.y;
-                        rotation = q1 * rotation;
-                        direction.x = rotation.x;
-                        direction.y = rotation.y;
-                    }
-
-                    if (
-                      first_triangle_check == false
-                      && first_entity_check == false
-                      && (second_triangle_check != false || second_entity_check != false
-                      )
-                    ){
-                        q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z);
-                        rotation.x = direction.x;
-                        rotation.y = direction.y;
-                        rotation = q1 * rotation;
-                        direction.x = rotation.x;
-                        direction.y = rotation.y;
-                    }
-                    continue;
-                }
-                break;
-            }
-
-            // Only for playable character.
-            else{
-                if (
-                  first_entity_check  == false
-                  && second_entity_check == false
-                  && third_entity_check  == false
-                ){
-                    // If not both left and right check failed
-                    if (first_triangle_check == false || second_triangle_check == false){
-                        // With SLIP off the move is not turned along the wall: it stays blocked.
-                        if (!player_slip_) break;
-                        if (first_triangle_check != false && second_triangle_check == false){
-                            q1.FromAngleAxis(
-                              Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
-                            );
-                            rotation.x = direction.x;
-                            rotation.y = direction.y;
-                            rotation = q1 * rotation;
-                            direction.x = rotation.x;
-                            direction.y = rotation.y;
-                        }
-
-                        if (first_triangle_check == false && second_triangle_check != false){
-                            q1.FromAngleAxis(
-                              Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z
-                            );
-                            rotation.x = direction.x;
-                            rotation.y = direction.y;
-                            rotation = q1 * rotation;
-                            direction.x = rotation.x;
-                            direction.y = rotation.y;
-                        }
-                        continue;
-                    }
-                    break;
-                }
-            }
-        }
-    }
-
-    // Set new X, Y and Z
-    last_triangle_check = WalkmeshBorderCross(entity, end_point, direction);
-
-    if (
-      first_triangle_check != false || second_triangle_check != false
-      || third_triangle_check != false || last_triangle_check != false
-      || first_entity_check != false || second_entity_check != false
-      || third_entity_check != false
-    ){
-        // Event if the entity can't move, check for triggers, but use current position.
-        if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
-        return false;
-    }
-
-    // Check triggers before set entity position because move line is checked.
-    if (player_entity_ == entity) CheckTriggers(entity, end_point);
-    entity->SetPosition(end_point);
-
-    // If the entity has come to destination point, finish movement.
-    Ogre::Vector3 final = entity->GetMovePosition() - end_point;
-    const float tolerance = scripted_move ? 0.0001f : speed / 10;
-    if (Ogre::Vector2(final.x, final.y).length() <= stop_distance + tolerance)
-        entity->UnsetMove();
-
-    return true;
-}
-
-bool EntityManager::WalkmeshBorderCross(
-  Entity* entity, Ogre::Vector3& position, const Ogre::Vector2& move_vector
-){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to check for walkmesh cross, but the EntityManager is in battle mode");
-        return false;
-    }
-    int current_triangle = entity->GetMoveTriangleId();
-    if (current_triangle == -1) return true;
-    // While a scene has the player locked, the scene walks the player like any other character,
-    // and it can lead over the edge of the walkmesh.
-    const bool free_walk = !WalkmeshEdgeBlocks(
-      entity == player_entity_ && !player_lock_, entity->IsScriptedMove()
-    );
-    Ogre::Vector2 pos = Ogre::Vector2(position.x, position.y);
-    bool searched_other_triangle = false;
-    for (;;){
-        Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
-        Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
-        Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
-        Ogre::Vector2 A(A3.x, A3.y);
-        Ogre::Vector2 B(B3.x, B3.y);
-        Ogre::Vector2 C(C3.x, C3.y);
-        float sign1 = SideOfVector(pos, B, A);
-        float sign2 = SideOfVector(pos, C, B);
-        float sign3 = SideOfVector(pos, A, C);
-        int next_triangle = -1;
-        if (sign1 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 0);
-        else if (sign2 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 1);
-        else if (sign3 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 2);
-        else{
-            position.z = PointElevation(pos, A3, B3, C3);
-            entity->SetMoveTriangleId(current_triangle);
-            return false;
-        }
-        if (next_triangle >= 0){
-            bool lock = walkmesh_.IsLocked(next_triangle);
-            if (lock == false || free_walk){
-                current_triangle = next_triangle;
-                continue;
-            }
-        }
-        // A walk of a script goes on over the edge: it keeps the last triangle, unless the point is
-        // inside another one (the triangles apart from the rest, that scenes use to put a character
-        // higher than the floor, are not joined to it: the character would keep that height after
-        // leaving it).
-        if (free_walk && !searched_other_triangle){
-            searched_other_triangle = true;
-            int other_triangle = -1;
-            float other_distance = 9999.0f;
-            for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
-                if (i == current_triangle) continue;
-                const Ogre::Vector3 a = walkmesh_.GetA(i);
-                const Ogre::Vector3 b = walkmesh_.GetB(i);
-                const Ogre::Vector3 c = walkmesh_.GetC(i);
-                if (!Ogre::Math::pointInTri2D(
-                  pos, Ogre::Vector2(a.x, a.y), Ogre::Vector2(b.x, b.y), Ogre::Vector2(c.x, c.y)
-                )) continue;
-                const float distance = std::abs(position.z - PointElevation(pos, a, b, c));
-                if (distance < other_distance){
-                    other_distance = distance;
-                    other_triangle = i;
-                }
-            }
-            if (other_triangle >= 0){
-                current_triangle = other_triangle;
-                continue;
-            }
-        }
-        position.z = PointElevation(pos, A3, B3, C3);
-        entity->SetMoveTriangleId(current_triangle);
-        // A walk of a script goes on over the edge, keeping the last triangle.
-        return !free_walk;
-    }
-}
-
-bool EntityManager::CheckSolidCollisions(Entity* entity, Ogre::Vector3& position){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to check for solid collisions, but the EntityManager is in battle mode");
-        return false;
-    }
-    if (entity->IsSolid() == false) return false;
-    for (size_t i = 0; i < entity_.size(); ++ i){
-        if (entity_[i]->IsSolid() == false) continue;
-        if (entity_[i] == entity) continue;
-        Ogre::Vector3 pos1 = entity_[i]->GetPosition();
-        float solid_range = entity_[i]->GetSolidRadius();
-        solid_range *= solid_range;
-        float height = (pos1.z < position.z) ? entity_[i]->GetHeight() : entity->GetHeight();
-        if (
-          ((pos1.z - position.z + height) < (height * 2)) && ((pos1.z - position.z + height) >= 0)
-        ){
-            float distance
-              = (pos1.x - position.x) * (pos1.x - position.x)
-              + (pos1.y - position.y) * (pos1.y - position.y);
-            if (distance < solid_range) return true;
-        }
-    }
-    return false;
-}
-
-void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to check for triggers, but the EntityManager is in battle mode");
-        return;
-    }
-    if (entity->IsSolid() == false) return;
-    if (player_entity_ != entity) return;
-    if (player_entity_->IsSolid() == false) return;
-    if (player_lock_) return;
-    bool is_moving = true;
-    if (
-      std::fabs(entity->GetPosition().x - position.x) < 0.005f
-      && std::fabs(entity->GetPosition().y - position.y) < 0.005f
-      && std::fabs(entity->GetPosition().z - position.z) < 0.005f
-    ){
-        is_moving = false;
-    }
-
-    for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
-        ScriptEntity* trigger = ScriptManager::getSingleton().GetScriptEntityByName(
-          ScriptManager::ENTITY, entity_triggers_[i]->GetName()
-        );
-
-        if (trigger != nullptr && entity_triggers_[i]->IsEnabled() == true){
-            Ogre::Vector3 point_a = entity_triggers_[i]->GetPoint1();
-            Ogre::Vector3 point_b = entity_triggers_[i]->GetPoint2();
-            Ogre::Vector3 entity_position = entity->GetPosition();
-            Ogre::Vector3 proj;
-
-            // Calculate distance
-            float square_dist = SquareDistanceToLine(entity_position, point_a, point_b, proj);
-            float solid_radius = TriggerReach(entity->GetSolidRadius());
-
-            // Calculate direction.
-            const Ogre::Degree direction_to_line = GetDirectionToPoint(entity_position, proj);
-            const Ogre::Degree destination_direction_to_line = GetDirectionToPoint(position, proj);
-            const Ogre::Degree movement_direction = entity->GetRotation();
-            Ogre::Degree angle = direction_to_line - movement_direction + Ogre::Degree(90);
-            angle = (angle > Ogre::Degree(360)) ? angle - Ogre::Degree(360) : angle;
-
-
-            // Check on enter line.
-            // Must happen only once when the solid radius touches the line, while facing the line,
-            // while the entity is manually moving, and only if not already triggered.
-            if (
-              square_dist != -1 && square_dist <= solid_radius * solid_radius
-              && angle < Ogre::Degree(180) && angle > Ogre::Degree(0)
-              && entity_triggers_[i]->CheckApproached() == false
-              && is_moving
-            ){
-                entity_triggers_[i]->SetApproached(true);
-                //std::cout << "    [TRIGGER] " << entity->GetName() << " on_approach "
-                //  << entity_triggers_[i]->GetName() << std::endl;
-                ScriptManager::getSingleton().ScriptRequest(
-                  trigger, "on_approach", 1, entity->GetName(), "", false, false
-                );
-            }
-
-            // Check on move to line.
-            // Must happen only once when the entity center touches the line, if the entity has
-            // previously entered the line.
-            if (
-              square_dist != -1 && square_dist < 1
-              && entity_triggers_[i]->CheckCrossed() == false
-              && entity_triggers_[i]->CheckApproached() == true
-            ){
-                entity_triggers_[i]->SetCrossed(true);
-                //std::cout << "    [TRIGGER] " << entity->GetName() << " on_cross "
-                //  << entity_triggers_[i]->GetName() << std::endl;
-                ScriptManager::getSingleton().ScriptRequest(
-                  trigger, "on_cross", 1, entity->GetName(), "", false, false
-                );
-            }
-
-            // Check on cross line.
-            // Must happen on every frame while the entity solid radius collides with the line, if
-            // the entity has previously entered the line.
-            if (
-              square_dist != -1 && square_dist <= solid_radius * solid_radius
-              && entity_triggers_[i]->CheckApproached() == true
-            ){
-                // TODO: Fix this hack.
-                // After the on_near script is run, set a cooltime of 5 frames before running
-                // it again. This is because most of the time this trigger checks for a key, and
-                // if its pressed, is run multiple times.
-                if (entity_triggers_[i]->GetNearEventCooldown() == 0){
-                    //std::cout << "    [TRIGGER] " << entity->GetName()
-                    //  << " on_near " << entity_triggers_[i]->GetName() << std::endl;
-                    ScriptManager::getSingleton().ScriptRequest(
-                      trigger, "on_near", 1, entity->GetName(), "", true, true
-                    );
-                    entity_triggers_[i]->ResetNearEventCooldown();
-                }
-                else entity_triggers_[i]->DecreaseNearEventCooldown();
-            }
-
-            // Check on cross line once.
-            // The same as on cross line, but only once.
-            if (
-              square_dist != -1 && square_dist < solid_radius * solid_radius
-              && entity_triggers_[i]->CheckNearSingleEventTriggered() == false
-              && entity_triggers_[i]->CheckApproached() == true
-            ){
-                entity_triggers_[i]->SetNearSingleEventTriggered(true);
-                //std::cout << "    [TRIGGER] " << entity->GetName()
-                //  << " on_near_once " << entity_triggers_[i]->GetName() << std::endl;
-                ScriptManager::getSingleton().ScriptRequest(
-                  trigger, "on_near_once", 1, entity->GetName(), "", false, false
-                );
-
-            }
-
-            // Check on leave line.
-            // Must be triggered once when the line is not in the entity solid radius, but only if
-            // on enter script has been triggered previously.
-            if (
-              square_dist != -1 && square_dist > solid_radius * solid_radius
-              && entity_triggers_[i]->CheckApproached()
-            ){
-                //std::cout << "    [TRIGGER] " << entity->GetName() << " on_leave "
-                //  << entity_triggers_[i]->GetName() << std::endl;
-                ScriptManager::getSingleton().ScriptRequest(
-                  trigger, "on_leave", 1, entity->GetName(), "", false, false
-                );
-            }
-
-            // If the entity is far enough from the line, mark every trigger as inactive
-            if (square_dist == -1 || square_dist > solid_radius * solid_radius){
-                entity_triggers_[i]->Clear();
-                //std::cout << "    [TRIGGER] " << entity->GetName() << " clear of "
-                //  << entity_triggers_[i]->GetName() << std::endl;
-            }
-
-        }
-    }
-}
-
-void EntityManager::ScriptSetLine(
-  const char* name, const float x1, const float y1, const float z1, const float x2, const float y2,
-  const float z2
-){
-    for (EntityTrigger* trigger : entity_triggers_){
-        if (trigger->GetName() == name){
-            trigger->SetPoints(Ogre::Vector3(x1, y1, z1), Ogre::Vector3(x2, y2, z2));
-            return;
-        }
-    }
-}
-
-void EntityManager::CheckEntityContacts(){
-    if (IsBattleModule() || !IsFieldModule()) return;
-    if (player_entity_ == nullptr || player_lock_ || !player_entity_->IsSolid()){
-        entities_in_contact_.clear();
-        return;
-    }
-    const Ogre::Vector3 player_position = player_entity_->GetPosition();
-    for (Entity* entity : entity_){
-        if (entity == player_entity_ || entity->IsLine() || !entity->IsSolid()) continue;
-        const Ogre::Vector3 position = entity->GetPosition();
-        const float height = (position.z < player_position.z)
-          ? entity->GetHeight() : player_entity_->GetHeight();
-        const float distance_z = position.z - player_position.z + height;
-        bool touching = false;
-        if (distance_z < height * 2 && distance_z >= 0){
-            const float reach = player_entity_->GetSolidRadius() + entity->GetSolidRadius() + 0.05f;
-            const float dx = position.x - player_position.x;
-            const float dy = position.y - player_position.y;
-            touching = dx * dx + dy * dy < reach * reach;
-        }
-        if (!touching){
-            entities_in_contact_.erase(entity);
-            continue;
-        }
-        if (!entities_in_contact_.insert(entity).second) continue;
-        ScriptEntity* script_entity = ScriptManager::getSingleton().GetScriptEntityByName(
-          ScriptManager::ENTITY, entity->GetName()
-        );
-        // Most entities have no script for it: nothing to say then.
-        if (script_entity != nullptr){
-            ScriptManager::getSingleton().ScriptRequest(
-              script_entity, "script_2", INTERACT_SCRIPT_PRIORITY, "", "", false, false
-            );
-        }
-    }
-}
-
-void EntityManager::CheckEntityInteract(){
-    if (IsBattleModule()){
-        LOG_WARNING(
-          "Tried to check for entity interaction, but the EntityManager is in battle mode"
-        );
-        return;
-    }
-    if (player_entity_ == NULL || player_lock_ == true || player_entity_->IsSolid() == false)
-        return;
-    Ogre::Degree angle_pc = player_entity_->GetRotation();
-    Entity* entity_to_interact = NULL;
-    Ogre::Degree less_angle(90);
-    float best_distance = std::numeric_limits<float>::max();
-    Ogre::Real nearest_worldmap_distance = -1.0f;
-    for (unsigned int i = 0; i < entity_.size(); ++ i){
-        if (entity_[i]->IsTalkable() == false) continue;
-        if (entity_[i] == player_entity_) continue;
-        Ogre::Vector3 pos1 =  entity_[i]->GetPosition();
-        float interact_range =  entity_[i]->GetTalkRadius();
-        Ogre::Vector3 pos2 = player_entity_->GetPosition();
-        float solid_range = player_entity_->GetSolidRadius();
-                if (IsWorldModule()){
-                        const Ogre::Real target_bottom = pos1.y;
-                        const Ogre::Real player_bottom = pos2.y;
-                                                const Ogre::Real talk_range
-                                                    = interact_range + solid_range + 0.05f;
-                        const Ogre::Real distance
-                            = (pos1.x - pos2.x) * (pos1.x - pos2.x)
-                                + (pos1.z - pos2.z) * (pos1.z - pos2.z);
-                        const bool height_overlap
-                            = player_bottom <= target_bottom + entity_[i]->GetHeight()
-                                && player_bottom + player_entity_->GetHeight() >= target_bottom;
-                        if (
-                                height_overlap && distance <= talk_range * talk_range
-                                && (nearest_worldmap_distance < 0 || distance < nearest_worldmap_distance)
-                        ){
-                                entity_to_interact = entity_[i];
-                                nearest_worldmap_distance = distance;
-                        }
-                        continue;
-                }
-        int height = (pos1.z < pos2.z) ? entity_[i]->GetHeight() : player_entity_->GetHeight();
-        if (((pos1.z - pos2.z + height) < (height * 2)) && ((pos1.z - pos2.z + height) >= 0)){
-            interact_range = (interact_range + solid_range) * (interact_range + solid_range);
-            float distance
-              = (pos1.x - pos2.x) * (pos1.x - pos2.x) + (pos1.y - pos2.y) * (pos1.y - pos2.y);
-            if (distance < interact_range + solid_range){
-                Ogre::Degree angle_to_model = GetDirectionToPoint(pos2, pos1);
-                Ogre::Degree angle = angle_pc - angle_to_model;
-                angle = (angle < Ogre::Degree(0)) ? -angle : angle;
-                angle = (angle >= Ogre::Degree(180)) ? Ogre::Degree(360) - angle : angle;
-                // With several entities in range, interact with the one the player faces most.
-                // Nobody 90 degrees or more away from where the player faces is considered.
-                if (
-                  angle < Ogre::Degree(90) && IsBetterInteractionTarget(
-                    angle.valueDegrees(), distance, less_angle.valueDegrees(), best_distance
-                  )
-                ){
-                    less_angle = angle;
-                    best_distance = distance;
-                    entity_to_interact = entity_[i];
-                }
-            }
-        }
-    }
-    if (entity_to_interact != NULL && entity_to_interact->IsLine() == false){
-        Ogre::String name = entity_to_interact->GetName();
-        ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
-          ScriptManager::ENTITY, name
-        );
-        bool added = ScriptManager::getSingleton().ScriptRequest(
-          scr_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
-        );
-        if (added == false){
-            LOG_WARNING("Script 'on_interact' for entity '" +  name + "' doesn't exist.");
-        }
-    }
-}
-
-void EntityManager::SetNextOffsetStep(Entity* entity){
-    // TODO: Allow this while on battle mode?
-    ActionType type = entity->GetOffsetType();
-    float total = entity->GetOffsetSeconds();
-    float current = entity->GetOffsetCurrentSeconds();
-    current += Timer::getSingleton().GetGameTimeDelta();
-    current = (current > total) ? total : current;
-    Ogre::Vector3 start = entity->GetOffsetPositionStart();
-    Ogre::Vector3 end = entity->GetOffsetPositionEnd();
-    // An offset of zero seconds is done at once. Dividing would give NaN.
-    float x = (total > 0.0f) ? current / total : 1.0f;
-    if (std::isnan(x)) x = 0.0f;
-    float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
-    Ogre::Vector3 offset = start + (end - start) * smooth_modifier;
-    entity->SetOffset(offset);
-    if (current == total) entity->UnsetOffset();
-    else entity->SetOffsetCurrentSeconds(current);
-}
-
-void EntityManager::SetNextTurnStep(Entity* entity){
-    // TODO: Allow this while on battle mode?
-    ActionType type = entity->GetTurnType();
-    float total = entity->GetTurnSeconds();
-    float current = entity->GetTurnCurrentSeconds();
-    current += Timer::getSingleton().GetGameTimeDelta();
-    current = (current > total) ? total : current;
-    Ogre::Degree start = entity->GetTurnDirectionStart();
-    Ogre::Degree end = entity->GetTurnDirectionEnd();
-    // A turn of zero seconds is done at once. Dividing would give NaN, and a NaN rotation breaks
-    // the bounding box of the entity.
-    float x = (total > 0.0f) ? current / total : 1.0f;
-    float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
-    Ogre::Degree rotation = start + (end - start) * smooth_modifier;
-    entity->SetRotation(rotation);
-    if (current == total) entity->UnsetTurn();
-    else entity->SetTurnCurrentSeconds(current);
-}
-
-void EntityManager::SetNextLinearStep(Entity* entity){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set next linear step, but the EntityManager is in battle mode");
-        return;
-    }
-    bool to_end = true;
-    bool is_move = false;
-    Ogre::Vector3 start = entity->GetLinearStart();
-    Ogre::Vector3 end = entity->GetLinearEnd();
-    Ogre::Vector3 current = entity->GetPosition();
-    float delta = Timer::getSingleton().GetGameTimeDelta();
-    // The player climbs a ladder with the directional keys. While a scene has the player locked
-    // the keys have no effect, and the scene makes the player move on its own, as with any other
-    // entity.
-    if (entity == player_entity_ && !player_lock_){
-        LinearMovement move = entity->GetLinearMovement();
-        if (move == LM_DOWN_TO_UP || move == LM_UP_TO_DOWN){
-            if (player_move_.y > 0){ // move up
-                to_end = (move == LM_DOWN_TO_UP) ? true : false;
-                is_move = true;
-            }
-            else if (player_move_.y < 0){ // move down
-                to_end = (move == LM_DOWN_TO_UP) ? false : true;
-                is_move = true;
-            }
-        }
-        else if (move == LM_LEFT_TO_RIGHT || move == LM_RIGHT_TO_LEFT){
-            if (player_move_.x > 0){ // move right
-                to_end = (move == LM_LEFT_TO_RIGHT) ? true : false;
-                is_move = true;
-            }
-            else if (player_move_.x < 0){ // move left
-                to_end = (move == LM_LEFT_TO_RIGHT) ? false : true;
-                is_move = true;
-            }
-        }
-    }
-    else is_move = true;
-    if (is_move == true && (end - start).length() < 0.0001f){
-        // Start and end are the same place, so there is nothing to walk. Dividing by the time to
-        // cross the line (zero) would give a NaN position. Just finish the move.
-        entity->UnsetLinear();
-        if (to_end == true) entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
-        SetEntityOnWalkmesh(entity);
-        entity->SetPosition(to_end ? end : start);
-    }
-    else if (is_move == true){
-        Ogre::Vector3 position;
-        if (to_end == true){
-            Ogre::Vector3 end_start = end - start;
-            // Move across the whole line by this number of seconds.
-            float time = end_start.length() / 1.2f;
-            position.x = current.x + (end_start.x / time) * delta;
-            position.y = current.y + (end_start.y / time) * delta;
-            position.z = current.z + (end_start.z / time) * delta;
-            position.x = (end_start.x < 0)
-              ? std::max(position.x, end.x) : std::min(position.x, end.x);
-            position.y = (end_start.y < 0)
-              ? std::max(position.y, end.y) : std::min(position.y, end.y);
-            position.z = (end_start.z < 0)
-              ? std::max(position.z, end.z) : std::min(position.z, end.z);
-            // Compared with a tolerance: if the entity starts a bit off the end in one of the
-            // axes (the entry points are written with a few digits only), that axis could move
-            // less than the precision of a float per frame and never be exactly equal.
-            if ((position - end).length() < 0.0001f){
-                position = end;
-                entity->UnsetLinear();
-                entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
-                SetEntityOnWalkmesh(entity);
-            }
-        }
-        else{
-            Ogre::Vector3 end_start = start - end;
-            // Move across the whole line by this number of seconds.
-            float time = end_start.length() / 1.2f;
-            position.x = current.x + (end_start.x / time) * delta;
-            position.y = current.y + (end_start.y / time) * delta;
-            position.z = current.z + (end_start.z / time) * delta;
-            position.x = (end_start.x < 0)
-              ? std::max(position.x, start.x) : std::min(position.x, start.x);
-            position.y = (end_start.y < 0)
-              ? std::max(position.y, start.y) : std::min(position.y, start.y);
-            position.z = (end_start.z < 0)
-              ? std::max(position.z, start.z) : std::min(position.z, start.z);
-            if ((position - start).length() < 0.0001f){
-                position = start;
-                entity->UnsetLinear();
-                SetEntityOnWalkmesh(entity);
-            }
-        }
-        entity->SetPosition(position);
-        entity->UpdateAnimation((to_end == true) ? delta : -delta);
-    }
-}
-
-void EntityManager::SetNextJumpStep(Entity* entity){
-    if (IsBattleModule()){
-        LOG_WARNING("Tried to set next jump step, but the EntityManager is in battle mode");
-        return;
-    }
-    float total = entity->GetJumpSeconds();
-    float current = entity->GetJumpCurrentSeconds();
-    current += Timer::getSingleton().GetGameTimeDelta();
-    // A jump of zero seconds lands at once, without dividing by zero.
-    if (total <= 0.0f) total = 0.0001f;
-    current = (current > total) ? total : current;
-    Ogre::Vector3 start_position = entity->GetJumpStart();
-    Ogre::Vector3 end_position   = entity->GetJumpEnd();
-    Ogre::Vector3 position;
-    position.x = start_position.x + ((end_position.x - start_position.x) / total) * current;
-    position.y = start_position.y + ((end_position.y - start_position.y) / total) * current;
-    position.z = current * current * -1.0f + current
-      * ((end_position.z - start_position.z) / total + total * 1.0f) + start_position.z;
-    entity->SetPosition(position);
-    if (total == current){
-        entity->UnsetJump();
-        entity->SetMoveTriangleId(entity->GetJumpDestTriangle());
-        SetEntityOnWalkmesh(entity);
-        // The scripts set the animation of the jump as the default one (DFANM) and don't set it
-        // back, but the player stands normally after landing in the original game (the scene of
-        // mds6_2 where Cloud jumps down, for example). The scripts that do set it, do it after
-        // the jump, so they aren't affected.
-        if (entity == player_entity_){
-            entity->ScriptSetDefaultAnimation("Idle");
-            entity->PlayAnimationContinue("Idle");
-        }
-    }
-    else entity->SetJumpCurrentSeconds(current);
-}
-
-void EntityManager::SetNextScrollStep(){
-    // TODO: Allow this on battle mode?
-    background_2d_.UpdateScrollTarget();
-    Background2D::SCROLL_TYPE type = background_2d_.GetScrollType();
-    float total = background_2d_.GetScrollSeconds();
-    float current = background_2d_.GetScrollCurrentSeconds();
-    current += Timer::getSingleton().GetGameTimeDelta();
-    current = (current > total) ? total : current;
-    Ogre::Vector2 start = background_2d_.GetScrollPositionStart();
-    Ogre::Vector2 end = background_2d_.GetScrollPositionEnd();
-    float x = (total > 0.0f) ? current / total : 1.0f;
-    float smooth_modifier = (type == Background2D::SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
-    Ogre::Vector2 scroll = start + (end - start) * smooth_modifier;
-    background_2d_.SetScroll(scroll);
-    if (current == total) background_2d_.UnsetScroll();
-    else background_2d_.SetScrollCurrentSeconds(current);
-}

+ 12 - 0
src/engine/entity/EntityManager.h

@@ -650,6 +650,18 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         static const unsigned int  WORLD_MAP_BACKGROUND_ID;
 
+        /**
+         * Priority of the script that runs when the player presses OK in front of an entity.
+         *
+         * It has to run before the scripts that fields leave running on an entity (the loops that
+         * play an animation, requested with priority 5 or 6), or the entity could not be talked to.
+         * But it can't be the highest: a script of the same entity that is requested with a higher
+         * priority (3 or smaller) has to be able to run while the talk script waits for it, as in
+         * the scenes where a talk script asks its own entity to do something and waits for it to
+         * start.
+         */
+        static const int INTERACT_SCRIPT_PRIORITY;
+
         /**
          * Updates the field entities in the manager.
          */

+ 143 - 0
src/engine/entity/EntityManagerEncounters.cpp

@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <cstdlib>
+#include "engine/config/ConfigVar.h"
+#include "engine/entity/EntityManager.h"
+#include "common/Logger.h"
+#include "engine/script/ScriptManager.h"
+#include "engine/Timer.h"
+
+ConfigVar cv_encounter_multiplier(
+  "encounter_multiplier", "Multiplier of the random encounter rate (0 disables them)", "1"
+);
+ConfigVar cv_debug_encounters("debug_encounters", "Log random encounter checks", "false");
+
+/**
+ * Frames of walking (at 30 frames per second) between two encounter checks. The original game
+ * checks every 8 frames.
+ */
+static const float ENCOUNTER_CHECK_FRAMES = 8.0f;
+
+/**
+ * Value added to the encounter accumulator in each check, before dividing it by the rate of the
+ * table. The original game uses the speed of the player, which is not known here, so this is tuned
+ * to a battle every 15-30 seconds of walking in most fields. The encounter_multiplier cvar scales
+ * it.
+ */
+static const float ENCOUNTER_STEP_VALUE = 5.0f;
+
+float EntityManager::GetEncounterMultiplier() const{return cv_encounter_multiplier.GetF();}
+
+bool EntityManager::IsDebugEncounters() const{return cv_debug_encounters.GetB();}
+
+void EntityManager::SetRandomEncounters(bool active){random_encounters_ = active;}
+
+void EntityManager::ClearEncounterTables(){
+    encounter_tables_.clear();
+    encounter_table_ = 1;
+    encounter_distance_ = 0.0f;
+    encounter_last_position_valid_ = false;
+    encounter_accumulator_ = 0;
+    encounter_last_battle_ = -1;
+}
+
+void EntityManager::AddEncounterTable(
+  const int id, const int rate, const std::vector<std::pair<int, int>>& battles,
+  const std::vector<std::pair<int, int>>& specials
+){
+    EncounterTable table;
+    table.rate = rate;
+    table.battles = battles;
+    table.specials = specials;
+    encounter_tables_[id] = table;
+}
+
+void EntityManager::ScriptSetEncounterTable(const int id){encounter_table_ = id;}
+
+int EntityManager::ScriptRollEncounterBattle() const{
+    auto found = encounter_tables_.find(encounter_table_);
+    if (found == encounter_tables_.end()) return -1;
+    const EncounterTable& table = found->second;
+    // Like the original game: a roll out of 64 is checked against the special battles one after
+    // the other (each one adds its probability). If none is hit, a new roll chooses a standard
+    // battle, the last one being the default.
+    int roll = std::rand() % 64;
+    int sum = 0;
+    for (const auto& special : table.specials){
+        sum += special.second;
+        if (roll < sum) return special.first;
+    }
+    if (table.battles.empty()) return -1;
+    roll = std::rand() % 64;
+    sum = 0;
+    for (const auto& battle : table.battles){
+        sum += battle.second;
+        if (roll < sum) return battle.first;
+    }
+    return table.battles.back().first;
+}
+
+void EntityManager::UpdateEncounters(const bool walked){
+    if (player_entity_ == nullptr){
+        encounter_last_position_valid_ = false;
+        return;
+    }
+    const Ogre::Vector3 position = player_entity_->GetPosition();
+    const float distance
+      = encounter_last_position_valid_ ? (position - encounter_last_position_).length() : 0.0f;
+    encounter_last_position_ = position;
+    encounter_last_position_valid_ = true;
+    // Only walking counts: not scripted movements, and not jumps to another place.
+    if (!walked || player_lock_ || distance > 2.0f) return;
+    if (!random_encounters_ || encounter_tables_.empty()) return;
+    auto found = encounter_tables_.find(encounter_table_);
+    if (found == encounter_tables_.end()) return;
+    const float multiplier = cv_encounter_multiplier.GetF();
+    if (multiplier <= 0.0f) return;
+    // Same as the original game. Every few frames of walking the accumulator grows by a value
+    // divided by the rate (the lower the rate, the more often the encounters), and an encounter
+    // starts if a random number is lower than the accumulator.
+    const int rate = found->second.rate;
+    if (rate <= 0) return;
+    encounter_distance_ += Timer::getSingleton().GetGameTimeDelta() * 30.0f;
+    while (encounter_distance_ >= ENCOUNTER_CHECK_FRAMES){
+        encounter_distance_ -= ENCOUNTER_CHECK_FRAMES;
+        // Enemy Away and Enemy Lure materia change the rate of the party (see Party.get_encounter_modifier).
+        const float materia_multiplier
+          = ScriptManager::getSingleton().EvaluateNumber("Party.get_encounter_modifier()", 1.0f);
+        encounter_accumulator_ += static_cast<int>(ENCOUNTER_STEP_VALUE * multiplier * materia_multiplier * 256.0f) / rate;
+        const int roll = std::rand() % 256 * 256;
+        if (cv_debug_encounters.GetB()){
+            LOG_TRIVIAL(
+              "Encounter check: rate " + std::to_string(rate) + ", accumulator "
+              + std::to_string(encounter_accumulator_ / 256.0f) + "/256, roll "
+              + std::to_string(roll / 256)
+            );
+        }
+        if (roll >= encounter_accumulator_) continue;
+        int battle = ScriptRollEncounterBattle();
+        // The same battle is not repeated: it's rolled again once.
+        if (battle == encounter_last_battle_) battle = ScriptRollEncounterBattle();
+        if (battle < 0) return;
+        encounter_distance_ = 0.0f;
+        encounter_accumulator_ = 0;
+        encounter_last_battle_ = battle;
+        LOG_TRIVIAL("Random encounter: battle " + std::to_string(battle));
+        // The battle is started by a script, as it has to change the module of every manager.
+        ScriptManager::getSingleton().RunString("Encounter.start(" + std::to_string(battle) + ")");
+        return;
+    }
+}

+ 712 - 0
src/engine/entity/EntityManagerMovement.cpp

@@ -0,0 +1,712 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <cmath>
+#include <OgreMath.h>
+#include "engine/entity/EntityManager.h"
+#include "common/Logger.h"
+#include "engine/Timer.h"
+
+float EntityManager::GetTriangleHeight(int triangle, float x, float y, float fallback) const{
+    if (IsBattleModule() || triangle < 0 || triangle >= walkmesh_.GetNumberOfTriangles())
+        return fallback;
+    const float height = PointElevation(
+      Ogre::Vector2(x, y), walkmesh_.GetA(triangle), walkmesh_.GetB(triangle),
+      walkmesh_.GetC(triangle)
+    );
+    return std::isfinite(height) ? height : fallback;
+}
+
+float EntityManager::PointElevation(
+  const Ogre::Vector2& point, const Ogre::Vector3& a, const Ogre::Vector3& b, const Ogre::Vector3& c
+){
+    float _a = a.z * (b.y - c.y) + b.z * (c.y - a.y) + c.z * (a.y - b.y);
+    float _b = a.y * (b.x - c.x) + b.y * (c.x - a.x) + c.y * (a.x - b.x);
+    float _c = a.x * (b.z - c.z) + b.x * (c.z - a.z) + c.x * (a.z - b.z);
+    float _d
+      = a.x * (b.z * c.y - c.z * b.y) + b.x * (c.z * a.y - a.z * c.y)
+        + c.x * (a.z * b.y - b.z * a.y);
+    return (_d - _c * point.y - _a * point.x) / _b;
+}
+
+float EntityManager::SideOfVector(
+  const Ogre::Vector2& point, const Ogre::Vector2& p1, const Ogre::Vector2& p2
+){
+    Ogre::Vector2 AB = p2    - p1;
+    Ogre::Vector2 AP = point - p1;
+    return AB.x * AP.y - AB.y * AP.x;
+}
+
+bool EntityManager::IsWorldPositionBlocked(
+    const Entity* moving_entity, const Ogre::Vector3& position
+) const{
+        if (!IsWorldModule() || moving_entity == nullptr) return false;
+
+        for (const Entity* other : entity_){
+                if (other == moving_entity || !other->IsSolid()) continue;
+
+                const Ogre::Vector3 other_position = other->GetPosition();
+                const Ogre::Real dx = position.x - other_position.x;
+                const Ogre::Real dz = position.z - other_position.z;
+                const Ogre::Real radius = moving_entity->GetSolidRadius() + other->GetSolidRadius();
+                if (dx * dx + dz * dz >= radius * radius) continue;
+
+                const Ogre::Real moving_top = position.y + moving_entity->GetHeight();
+                const Ogre::Real other_top = other_position.y + other->GetHeight();
+                if (position.y < other_top && other_position.y < moving_top) return true;
+        }
+        return false;
+}
+
+bool EntityManager::SetEntityOnWalkmesh(Entity* entity){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to set entity on the walkmesh, but the EntityManager is in battle mode");
+        return false;
+    }
+    Ogre::Vector3 position3 = entity->GetPosition();
+    Ogre::Vector2 position2;
+    position2.x = position3.x;
+    position2.y = position3.y;
+    std::vector<std::pair<int, float>> triangles;
+    // Search for possible triangles.
+    for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
+        Ogre::Vector3 A3 = walkmesh_.GetA(i);
+        Ogre::Vector3 B3 = walkmesh_.GetB(i);
+        Ogre::Vector3 C3 = walkmesh_.GetC(i);
+        Ogre::Vector2 A2(A3.x, A3.y);
+        Ogre::Vector2 B2(B3.x, B3.y);
+        Ogre::Vector2 C2(C3.x, C3.y);
+        if (Ogre::Math::pointInTri2D(position2, A2, B2, C2) == true){
+            triangles.push_back(std::make_pair(i, PointElevation(
+              position2, walkmesh_.GetA(i), walkmesh_.GetB(i), walkmesh_.GetC(i)
+            )));
+        }
+    }
+    // If the coordinates doesn't match any triangle, exit.
+    if (triangles.size() == 0 && entity == player_entity_){
+        LOG_ERROR(
+          "Can't find any triangle to place entity '" + entity->GetName() + "' on walkmesh."
+        );
+        return false;
+    }
+    // From the possible triangles, select the closest one (on the Z edge).
+    int closest_z_triangle = -1;
+    float closest_z_distance = 9999.0f;
+    float pos_z = position3.z;
+    for (size_t i = 0; i < triangles.size(); ++ i){
+        if (std::abs(pos_z - triangles[i].second) < closest_z_distance){
+            closest_z_triangle = triangles[i].first;
+            closest_z_distance = std::abs(pos_z - triangles[i].second);
+        }
+    }
+    if (closest_z_triangle == -1 && entity == player_entity_){
+        LOG_ERROR(
+          "Can't find nearby triangle to place entity '" + entity->GetName() + "' on walkmesh."
+        );
+        return false;
+    }
+    entity->SetPosition(Ogre::Vector3(position2.x, position2.y, pos_z));
+    entity->SetMoveTriangleId(closest_z_triangle);
+    return true;
+}
+
+bool EntityManager::WalkmeshEdgeBlocks(bool is_player, bool scripted_move){
+    return is_player || !scripted_move;
+}
+
+float EntityManager::ScriptedMoveStep(float distance, float stop_distance, float max_step){
+    return std::min(max_step, std::max(0.0f, distance - stop_distance));
+}
+
+bool EntityManager::PerformWalkmeshMove(Entity* entity, const float speed, const float delta_time){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to perform a walkmesh move, but the EntityManager is in battle mode");
+        return false;
+    }
+    Ogre::Vector3 start_point = entity->GetPosition();
+    Ogre::Vector3 move_vector = entity->GetMovePosition() - start_point;
+    Ogre::Vector2 direction(move_vector.x, move_vector.y);
+    const float distance_to_target = direction.length();
+    const bool scripted_move = entity->IsScriptedMove();
+    const float stop_distance = entity->GetMoveStopDistance();
+    if (scripted_move && distance_to_target <= stop_distance + 0.0001f){
+        entity->UnsetMove();
+        return false;
+    }
+    direction.normalise();
+    direction *= delta_time;
+    direction *= speed;
+    if (scripted_move && !direction.isZeroLength()){
+        direction.normalise();
+        direction *= ScriptedMoveStep(
+          distance_to_target, stop_distance, speed * delta_time
+        );
+    }
+    // If movement is still needed but speed or time don't allow it, just return for now.
+    if (direction.isZeroLength() == true){
+        if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
+        return false;
+    }
+    int current_triangle = entity->GetMoveTriangleId();
+    // A character that is not on the walkmesh (Jenova of shpin_3, that is placed outside it and
+    // moves with FMOVE) is walked in a straight line, or the scene that waits for it would never go
+    // on.
+    if (current_triangle == -1 && scripted_move && entity != player_entity_){
+        const float step = std::min(direction.length(), distance_to_target);
+        Ogre::Vector2 move = direction;
+        if (!move.isZeroLength()) move.normalise();
+        move *= step;
+        entity->SetPosition(Ogre::Vector3(start_point.x + move.x, start_point.y + move.y, start_point.z));
+        if (distance_to_target - step <= stop_distance + 0.0001f) entity->UnsetMove();
+        return step > 0.0f;
+    }
+    if (current_triangle == -1){
+        // The entities that a scene places later (the soldiers of the parade of junonr4) are asked
+        // to move before it, and wait. Only the player has to be on the walkmesh.
+        if (entity == player_entity_)
+            LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
+        return false;
+    }
+    Ogre::Vector3 rotation(0.0f, 0.0f, 0.0f);
+    Ogre::Quaternion q1(0.0f, 0.0f, 0.0f, 1.0f);
+    Ogre::Vector3 end_point(0.0f, 0.0f, 0.0f);
+    Ogre::Vector3 end_point2(0.0f, 0.0f, 0.0f);
+    bool first_triangle_check = false;
+    bool second_triangle_check = false;
+    bool third_triangle_check = false;
+    bool last_triangle_check = false;
+    bool first_entity_check = false;
+    bool second_entity_check = false;
+    bool third_entity_check = false;
+    // Shorten move vector by triangle angle
+    end_point.x = start_point.x + direction.x;
+    end_point.y = start_point.y + direction.y;
+    Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
+    Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
+    Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
+    end_point.z = PointElevation(Ogre::Vector2(end_point.x, end_point.y), A3, B3, C3);
+    Ogre::Vector3 temp = end_point - start_point;
+    temp.normalise();
+    temp = temp * direction.length();
+    direction.x = temp.x;
+    direction.y = temp.y;
+    // Set the direction for the entity if it has to move.
+    if (entity->GetMoveAutoRotation() == true){
+        Ogre::Vector2 up(0.0f, -1.0f);
+        // Angle between vectors
+        Ogre::Degree angle(Ogre::Radian(SafeAcos(
+          direction.dotProduct(up), direction.length() * up.length()
+        )));
+        angle = (direction.x < 0) ? Ogre::Degree(360) - angle : angle;
+        entity->SetRotation(Ogre::Degree(angle));
+    }
+    // A scripted walk (also of the player entity, while a scene has it locked) must end, or the
+    // scene waiting for it would never go on. Several scripts place solid entities next to where
+    // another one has to walk to, so they don't block it: only the walkmesh does. A manual move
+    // of the player is never scripted.
+    // The same goes for the points around the end of the step: they are there for the player and
+    // NPCs to slide along walls, and a destination next to an edge of the walkmesh would never be
+    // reached. The end point itself is still checked.
+    const bool check_probes = !scripted_move;
+    float solid = (entity->IsSolid() == true) ? entity->GetSolidRadius() : 0.01f;
+
+    // For not playable entities, be a bit more lenient with solid collisions.
+    // Don't use the solid radius.
+    if (entity != player_entity_) solid /= 10;
+
+    // Get ending point.
+    end_point.z = start_point.z;
+    for (
+      int i = 0;
+      (entity == player_entity_ && i < 16)
+        || (entity == player_entity_ &&  i < 3)
+        || (entity != player_entity_ && i <= 16);
+      ++ i
+    ){
+        end_point = Ogre::Vector3(
+          start_point.x + direction.x, start_point.y + direction.y, start_point.z
+        );
+        // 1st check.
+        // Rotate move_vector +45.
+        q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(45)), Ogre::Vector3::UNIT_Z);
+        rotation.x = direction.x;
+        rotation.y = direction.y;
+        rotation.z = 0;
+        rotation.normalise();
+        rotation = q1 * rotation;
+        // Multiply move_vector by solid range
+        rotation = rotation * solid;
+        end_point2.x = end_point.x + rotation.x;
+        end_point2.y = end_point.y + rotation.y;
+        // Check_triangle.
+        first_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
+        entity->SetMoveTriangleId(current_triangle);
+        // Model check.
+        first_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
+
+        // 2nd check.
+        // Rotate move_vector +45.
+        q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-45)), Ogre::Vector3::UNIT_Z);
+        rotation.x = direction.x;
+        rotation.y = direction.y;
+        rotation.z = 0;
+        rotation.normalise();
+        rotation = q1 * rotation;
+        // Multiply move_vector by solid range.
+        rotation = rotation * solid;
+        end_point2.x = end_point.x + rotation.x;
+        end_point2.y = end_point.y + rotation.y;
+        // Check triangle.
+        second_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
+        entity->SetMoveTriangleId(current_triangle);
+        // Model check.
+        second_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
+
+        // 3rd check.
+        rotation.x = direction.x;
+        rotation.y = direction.y;
+        rotation.z = 0;
+        rotation.normalise();
+        rotation = rotation * solid;
+        end_point2.x = end_point.x + rotation.x;
+        end_point2.y = end_point.y + rotation.y;
+        // Check triangle.
+        third_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
+        entity->SetMoveTriangleId(current_triangle);
+        // Model check.
+        third_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
+
+        // Check condition and modify move_vector.
+        if (
+          first_triangle_check != false || second_triangle_check != false
+          || third_triangle_check != false || first_entity_check != false
+          || second_entity_check != false || third_entity_check != false
+        ){
+            // Only for NPC.
+            if (entity != player_entity_){
+                // If the entity collides only directly into a triangle border.
+                if (
+                  first_triangle_check  == false
+                  && second_triangle_check == false
+                  && third_triangle_check != false
+                ){
+                    q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-7)), Ogre::Vector3::UNIT_Z);
+                    rotation.x = direction.x;
+                    rotation.y = direction.y;
+                    rotation = q1 * rotation;
+                    direction.x = rotation.x;
+                    direction.y = rotation.y;
+                }
+                // Or if the entity only collides into other entity directly.
+                else if (
+                  first_entity_check == false && second_entity_check == false
+                  && third_entity_check != false
+                ){
+                    q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z);
+                    rotation.x = direction.x;
+                    rotation.y = direction.y;
+                    rotation = q1 * rotation;
+                    direction.x = rotation.x;
+                    direction.y = rotation.y;
+                }
+
+                // If not both left and right check failed.
+                if (first_triangle_check == false || second_triangle_check == false){
+                    if (
+                      (first_triangle_check == false && first_entity_check != false)
+                      || (first_triangle_check != false && second_triangle_check == false)
+                    ){
+                        q1.FromAngleAxis(
+                          Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
+                        );
+                        rotation.x = direction.x;
+                        rotation.y = direction.y;
+                        rotation = q1 * rotation;
+                        direction.x = rotation.x;
+                        direction.y = rotation.y;
+                    }
+
+                    if (
+                      first_triangle_check == false
+                      && first_entity_check == false
+                      && (second_triangle_check != false || second_entity_check != false
+                      )
+                    ){
+                        q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z);
+                        rotation.x = direction.x;
+                        rotation.y = direction.y;
+                        rotation = q1 * rotation;
+                        direction.x = rotation.x;
+                        direction.y = rotation.y;
+                    }
+                    continue;
+                }
+                break;
+            }
+
+            // Only for playable character.
+            else{
+                if (
+                  first_entity_check  == false
+                  && second_entity_check == false
+                  && third_entity_check  == false
+                ){
+                    // If not both left and right check failed
+                    if (first_triangle_check == false || second_triangle_check == false){
+                        // With SLIP off the move is not turned along the wall: it stays blocked.
+                        if (!player_slip_) break;
+                        if (first_triangle_check != false && second_triangle_check == false){
+                            q1.FromAngleAxis(
+                              Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
+                            );
+                            rotation.x = direction.x;
+                            rotation.y = direction.y;
+                            rotation = q1 * rotation;
+                            direction.x = rotation.x;
+                            direction.y = rotation.y;
+                        }
+
+                        if (first_triangle_check == false && second_triangle_check != false){
+                            q1.FromAngleAxis(
+                              Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z
+                            );
+                            rotation.x = direction.x;
+                            rotation.y = direction.y;
+                            rotation = q1 * rotation;
+                            direction.x = rotation.x;
+                            direction.y = rotation.y;
+                        }
+                        continue;
+                    }
+                    break;
+                }
+            }
+        }
+    }
+
+    // Set new X, Y and Z
+    last_triangle_check = WalkmeshBorderCross(entity, end_point, direction);
+
+    if (
+      first_triangle_check != false || second_triangle_check != false
+      || third_triangle_check != false || last_triangle_check != false
+      || first_entity_check != false || second_entity_check != false
+      || third_entity_check != false
+    ){
+        // Event if the entity can't move, check for triggers, but use current position.
+        if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
+        return false;
+    }
+
+    // Check triggers before set entity position because move line is checked.
+    if (player_entity_ == entity) CheckTriggers(entity, end_point);
+    entity->SetPosition(end_point);
+
+    // If the entity has come to destination point, finish movement.
+    Ogre::Vector3 final = entity->GetMovePosition() - end_point;
+    const float tolerance = scripted_move ? 0.0001f : speed / 10;
+    if (Ogre::Vector2(final.x, final.y).length() <= stop_distance + tolerance)
+        entity->UnsetMove();
+
+    return true;
+}
+
+bool EntityManager::WalkmeshBorderCross(
+  Entity* entity, Ogre::Vector3& position, const Ogre::Vector2& move_vector
+){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to check for walkmesh cross, but the EntityManager is in battle mode");
+        return false;
+    }
+    int current_triangle = entity->GetMoveTriangleId();
+    if (current_triangle == -1) return true;
+    // While a scene has the player locked, the scene walks the player like any other character,
+    // and it can lead over the edge of the walkmesh.
+    const bool free_walk = !WalkmeshEdgeBlocks(
+      entity == player_entity_ && !player_lock_, entity->IsScriptedMove()
+    );
+    Ogre::Vector2 pos = Ogre::Vector2(position.x, position.y);
+    bool searched_other_triangle = false;
+    for (;;){
+        Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
+        Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
+        Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
+        Ogre::Vector2 A(A3.x, A3.y);
+        Ogre::Vector2 B(B3.x, B3.y);
+        Ogre::Vector2 C(C3.x, C3.y);
+        float sign1 = SideOfVector(pos, B, A);
+        float sign2 = SideOfVector(pos, C, B);
+        float sign3 = SideOfVector(pos, A, C);
+        int next_triangle = -1;
+        if (sign1 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 0);
+        else if (sign2 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 1);
+        else if (sign3 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 2);
+        else{
+            position.z = PointElevation(pos, A3, B3, C3);
+            entity->SetMoveTriangleId(current_triangle);
+            return false;
+        }
+        if (next_triangle >= 0){
+            bool lock = walkmesh_.IsLocked(next_triangle);
+            if (lock == false || free_walk){
+                current_triangle = next_triangle;
+                continue;
+            }
+        }
+        // A walk of a script goes on over the edge: it keeps the last triangle, unless the point is
+        // inside another one (the triangles apart from the rest, that scenes use to put a character
+        // higher than the floor, are not joined to it: the character would keep that height after
+        // leaving it).
+        if (free_walk && !searched_other_triangle){
+            searched_other_triangle = true;
+            int other_triangle = -1;
+            float other_distance = 9999.0f;
+            for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
+                if (i == current_triangle) continue;
+                const Ogre::Vector3 a = walkmesh_.GetA(i);
+                const Ogre::Vector3 b = walkmesh_.GetB(i);
+                const Ogre::Vector3 c = walkmesh_.GetC(i);
+                if (!Ogre::Math::pointInTri2D(
+                  pos, Ogre::Vector2(a.x, a.y), Ogre::Vector2(b.x, b.y), Ogre::Vector2(c.x, c.y)
+                )) continue;
+                const float distance = std::abs(position.z - PointElevation(pos, a, b, c));
+                if (distance < other_distance){
+                    other_distance = distance;
+                    other_triangle = i;
+                }
+            }
+            if (other_triangle >= 0){
+                current_triangle = other_triangle;
+                continue;
+            }
+        }
+        position.z = PointElevation(pos, A3, B3, C3);
+        entity->SetMoveTriangleId(current_triangle);
+        // A walk of a script goes on over the edge, keeping the last triangle.
+        return !free_walk;
+    }
+}
+
+bool EntityManager::CheckSolidCollisions(Entity* entity, Ogre::Vector3& position){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to check for solid collisions, but the EntityManager is in battle mode");
+        return false;
+    }
+    if (entity->IsSolid() == false) return false;
+    for (size_t i = 0; i < entity_.size(); ++ i){
+        if (entity_[i]->IsSolid() == false) continue;
+        if (entity_[i] == entity) continue;
+        Ogre::Vector3 pos1 = entity_[i]->GetPosition();
+        float solid_range = entity_[i]->GetSolidRadius();
+        solid_range *= solid_range;
+        float height = (pos1.z < position.z) ? entity_[i]->GetHeight() : entity->GetHeight();
+        if (
+          ((pos1.z - position.z + height) < (height * 2)) && ((pos1.z - position.z + height) >= 0)
+        ){
+            float distance
+              = (pos1.x - position.x) * (pos1.x - position.x)
+              + (pos1.y - position.y) * (pos1.y - position.y);
+            if (distance < solid_range) return true;
+        }
+    }
+    return false;
+}
+
+void EntityManager::SetNextOffsetStep(Entity* entity){
+    // TODO: Allow this while on battle mode?
+    ActionType type = entity->GetOffsetType();
+    float total = entity->GetOffsetSeconds();
+    float current = entity->GetOffsetCurrentSeconds();
+    current += Timer::getSingleton().GetGameTimeDelta();
+    current = (current > total) ? total : current;
+    Ogre::Vector3 start = entity->GetOffsetPositionStart();
+    Ogre::Vector3 end = entity->GetOffsetPositionEnd();
+    // An offset of zero seconds is done at once. Dividing would give NaN.
+    float x = (total > 0.0f) ? current / total : 1.0f;
+    if (std::isnan(x)) x = 0.0f;
+    float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
+    Ogre::Vector3 offset = start + (end - start) * smooth_modifier;
+    entity->SetOffset(offset);
+    if (current == total) entity->UnsetOffset();
+    else entity->SetOffsetCurrentSeconds(current);
+}
+
+void EntityManager::SetNextTurnStep(Entity* entity){
+    // TODO: Allow this while on battle mode?
+    ActionType type = entity->GetTurnType();
+    float total = entity->GetTurnSeconds();
+    float current = entity->GetTurnCurrentSeconds();
+    current += Timer::getSingleton().GetGameTimeDelta();
+    current = (current > total) ? total : current;
+    Ogre::Degree start = entity->GetTurnDirectionStart();
+    Ogre::Degree end = entity->GetTurnDirectionEnd();
+    // A turn of zero seconds is done at once. Dividing would give NaN, and a NaN rotation breaks
+    // the bounding box of the entity.
+    float x = (total > 0.0f) ? current / total : 1.0f;
+    float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
+    Ogre::Degree rotation = start + (end - start) * smooth_modifier;
+    entity->SetRotation(rotation);
+    if (current == total) entity->UnsetTurn();
+    else entity->SetTurnCurrentSeconds(current);
+}
+
+void EntityManager::SetNextLinearStep(Entity* entity){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to set next linear step, but the EntityManager is in battle mode");
+        return;
+    }
+    bool to_end = true;
+    bool is_move = false;
+    Ogre::Vector3 start = entity->GetLinearStart();
+    Ogre::Vector3 end = entity->GetLinearEnd();
+    Ogre::Vector3 current = entity->GetPosition();
+    float delta = Timer::getSingleton().GetGameTimeDelta();
+    // The player climbs a ladder with the directional keys. While a scene has the player locked
+    // the keys have no effect, and the scene makes the player move on its own, as with any other
+    // entity.
+    if (entity == player_entity_ && !player_lock_){
+        LinearMovement move = entity->GetLinearMovement();
+        if (move == LM_DOWN_TO_UP || move == LM_UP_TO_DOWN){
+            if (player_move_.y > 0){ // move up
+                to_end = (move == LM_DOWN_TO_UP) ? true : false;
+                is_move = true;
+            }
+            else if (player_move_.y < 0){ // move down
+                to_end = (move == LM_DOWN_TO_UP) ? false : true;
+                is_move = true;
+            }
+        }
+        else if (move == LM_LEFT_TO_RIGHT || move == LM_RIGHT_TO_LEFT){
+            if (player_move_.x > 0){ // move right
+                to_end = (move == LM_LEFT_TO_RIGHT) ? true : false;
+                is_move = true;
+            }
+            else if (player_move_.x < 0){ // move left
+                to_end = (move == LM_LEFT_TO_RIGHT) ? false : true;
+                is_move = true;
+            }
+        }
+    }
+    else is_move = true;
+    if (is_move == true && (end - start).length() < 0.0001f){
+        // Start and end are the same place, so there is nothing to walk. Dividing by the time to
+        // cross the line (zero) would give a NaN position. Just finish the move.
+        entity->UnsetLinear();
+        if (to_end == true) entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
+        SetEntityOnWalkmesh(entity);
+        entity->SetPosition(to_end ? end : start);
+    }
+    else if (is_move == true){
+        Ogre::Vector3 position;
+        if (to_end == true){
+            Ogre::Vector3 end_start = end - start;
+            // Move across the whole line by this number of seconds.
+            float time = end_start.length() / 1.2f;
+            position.x = current.x + (end_start.x / time) * delta;
+            position.y = current.y + (end_start.y / time) * delta;
+            position.z = current.z + (end_start.z / time) * delta;
+            position.x = (end_start.x < 0)
+              ? std::max(position.x, end.x) : std::min(position.x, end.x);
+            position.y = (end_start.y < 0)
+              ? std::max(position.y, end.y) : std::min(position.y, end.y);
+            position.z = (end_start.z < 0)
+              ? std::max(position.z, end.z) : std::min(position.z, end.z);
+            // Compared with a tolerance: if the entity starts a bit off the end in one of the
+            // axes (the entry points are written with a few digits only), that axis could move
+            // less than the precision of a float per frame and never be exactly equal.
+            if ((position - end).length() < 0.0001f){
+                position = end;
+                entity->UnsetLinear();
+                entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
+                SetEntityOnWalkmesh(entity);
+            }
+        }
+        else{
+            Ogre::Vector3 end_start = start - end;
+            // Move across the whole line by this number of seconds.
+            float time = end_start.length() / 1.2f;
+            position.x = current.x + (end_start.x / time) * delta;
+            position.y = current.y + (end_start.y / time) * delta;
+            position.z = current.z + (end_start.z / time) * delta;
+            position.x = (end_start.x < 0)
+              ? std::max(position.x, start.x) : std::min(position.x, start.x);
+            position.y = (end_start.y < 0)
+              ? std::max(position.y, start.y) : std::min(position.y, start.y);
+            position.z = (end_start.z < 0)
+              ? std::max(position.z, start.z) : std::min(position.z, start.z);
+            if ((position - start).length() < 0.0001f){
+                position = start;
+                entity->UnsetLinear();
+                SetEntityOnWalkmesh(entity);
+            }
+        }
+        entity->SetPosition(position);
+        entity->UpdateAnimation((to_end == true) ? delta : -delta);
+    }
+}
+
+void EntityManager::SetNextJumpStep(Entity* entity){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to set next jump step, but the EntityManager is in battle mode");
+        return;
+    }
+    float total = entity->GetJumpSeconds();
+    float current = entity->GetJumpCurrentSeconds();
+    current += Timer::getSingleton().GetGameTimeDelta();
+    // A jump of zero seconds lands at once, without dividing by zero.
+    if (total <= 0.0f) total = 0.0001f;
+    current = (current > total) ? total : current;
+    Ogre::Vector3 start_position = entity->GetJumpStart();
+    Ogre::Vector3 end_position   = entity->GetJumpEnd();
+    Ogre::Vector3 position;
+    position.x = start_position.x + ((end_position.x - start_position.x) / total) * current;
+    position.y = start_position.y + ((end_position.y - start_position.y) / total) * current;
+    position.z = current * current * -1.0f + current
+      * ((end_position.z - start_position.z) / total + total * 1.0f) + start_position.z;
+    entity->SetPosition(position);
+    if (total == current){
+        entity->UnsetJump();
+        entity->SetMoveTriangleId(entity->GetJumpDestTriangle());
+        SetEntityOnWalkmesh(entity);
+        // The scripts set the animation of the jump as the default one (DFANM) and don't set it
+        // back, but the player stands normally after landing in the original game (the scene of
+        // mds6_2 where Cloud jumps down, for example). The scripts that do set it, do it after
+        // the jump, so they aren't affected.
+        if (entity == player_entity_){
+            entity->ScriptSetDefaultAnimation("Idle");
+            entity->PlayAnimationContinue("Idle");
+        }
+    }
+    else entity->SetJumpCurrentSeconds(current);
+}
+
+void EntityManager::SetNextScrollStep(){
+    // TODO: Allow this on battle mode?
+    background_2d_.UpdateScrollTarget();
+    Background2D::SCROLL_TYPE type = background_2d_.GetScrollType();
+    float total = background_2d_.GetScrollSeconds();
+    float current = background_2d_.GetScrollCurrentSeconds();
+    current += Timer::getSingleton().GetGameTimeDelta();
+    current = (current > total) ? total : current;
+    Ogre::Vector2 start = background_2d_.GetScrollPositionStart();
+    Ogre::Vector2 end = background_2d_.GetScrollPositionEnd();
+    float x = (total > 0.0f) ? current / total : 1.0f;
+    float smooth_modifier = (type == Background2D::SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
+    Ogre::Vector2 scroll = start + (end - start) * smooth_modifier;
+    background_2d_.SetScroll(scroll);
+    if (current == total) background_2d_.UnsetScroll();
+    else background_2d_.SetScrollCurrentSeconds(current);
+}

+ 221 - 0
src/engine/entity/EntityManagerPlayer.cpp

@@ -0,0 +1,221 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include "engine/entity/EntityManager.h"
+#include "common/Logger.h"
+#include "engine/input/InputManager.h"
+#include "engine/script/ScriptManager.h"
+
+void EntityManager::Input(const VGears::Event& event){
+    background_2d_.InputDebug(event);
+    if (paused_ == true) return;
+    if (ignore_held_walk_){
+        InputManager& input = InputManager::getSingleton();
+        if (
+          !input.IsGameEventPressed("walk_left") && !input.IsGameEventPressed("walk_right")
+          && !input.IsGameEventPressed("walk_up") && !input.IsGameEventPressed("walk_down")
+        ) ignore_held_walk_ = false;
+    }
+    if (player_entity_ != NULL && player_lock_ == false){
+        // Keys held since the world map are ignored until they are released.
+        const bool key_ignored = ignore_held_walk_ && (
+          event.event == "walk_left" || event.event == "walk_right" || event.event == "walk_up"
+          || event.event == "walk_down" || event.event == "run"
+        );
+        if (!key_ignored){
+            if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_left") player_move_.x = -1;
+            else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_right")
+                player_move_.x = 1;
+            if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_down") player_move_.y = -1;
+            else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_up")
+                player_move_.y = 1;
+            if (event.type == VGears::ET_KEY_REPEAT && event.event == "run") player_run_ = true;
+        }
+        if (event.type == VGears::ET_KEY_PRESS && event.event == "CONFIRM"){
+            CheckEntityInteract();
+            for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
+                if (
+                  entity_triggers_[i]->IsEnabled() == true
+                  && entity_triggers_[i]->CheckApproached() == true
+                ){
+                    ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
+                      ScriptManager::ENTITY, entity_triggers_[i]->GetName()
+                    );
+                    bool added = ScriptManager::getSingleton().ScriptRequest(
+                      scr_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
+                    );
+                    if (added == false){
+                        LOG_WARNING(
+                          "Script 'on_interact' for entity '" + entity_triggers_[i]->GetName()
+                          + "' doesn't exist."
+                        );
+                    }
+                }
+            }
+        }
+    }
+}
+
+void EntityManager::ScriptSetPlayerEntity(const char* name){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to set a player entity but the EntityManager is in battle mode.");
+        return;
+    }
+    for (unsigned int i = 0; i < entity_.size(); ++ i){
+        if (entity_[i]->GetName() == name){
+            // A script can read the walkmesh triangle of the player right after this, so if it was
+            // placed by position the triangle has to be known. Done before it's the player entity
+            // so that the entity not being on the walkmesh yet isn't logged as an error.
+            if (entity_[i]->GetMoveTriangleId() == -1 && entity_[i]->GetPosition().isZeroLength()){
+                // A model that has no position of its own (the fields put the dressed Cloud away
+                // until a script makes it the player) takes the place of the previous player,
+                // which is where the field entry put the party, as in the original game.
+                if (player_entity_ != nullptr && player_entity_ != entity_[i]){
+                    entity_[i]->SetPosition(player_entity_->GetPosition());
+                    entity_[i]->SetRotation(player_entity_->GetRotation());
+                }
+            }
+            if (entity_[i]->GetMoveTriangleId() == -1) SetEntityOnWalkmesh(entity_[i]);
+            LOG_TRIVIAL("Player entity set to '" + std::string(name) + "'.");
+            // The camera that follows the player keeps following it when another entity takes over
+            // (Cloud and the dressed Cloud, for example); a camera that follows some other entity
+            // is left as it is.
+            if (player_entity_ != nullptr && background_2d_.GetAutoScrollEntity() == player_entity_)
+                background_2d_.ScriptAutoScrollToEntity(entity_[i]);
+            // The camera follows the player when no script has said anything about it (the fields
+            // without a Director, such as ujunon1, have no opcode that starts it).
+            else if (!background_2d_.HasScrollControl())
+                background_2d_.ScriptAutoScrollToEntity(entity_[i]);
+            player_entity_ = entity_[i];
+            // Also, make it non-talkable. Visibility and solidity are left to the scripts, as in
+            // the original game: some fields use hidden helper entities (like the 'camera') as
+            // the player entity to scroll the screen, and they must stay invisible and
+            // non-solid. When the player moves manually, UpdateField makes it solid anyway.
+            entity_[i]->SetTalkable(false);
+        }
+    }
+}
+
+void EntityManager::ScriptPlacePlayerAtFieldEntry(
+    const float x, const float y, const int triangle_id, const float direction
+){
+        if (player_entity_ == nullptr || walkmesh_.GetNumberOfTriangles() <= 0) return;
+
+        int safe_triangle_id = triangle_id;
+        if (safe_triangle_id < 0 || safe_triangle_id >= walkmesh_.GetNumberOfTriangles()){
+                LOG_WARNING("World-map field entry has an invalid walkmesh triangle; using triangle 0.");
+                safe_triangle_id = 0;
+        }
+
+        player_entity_->SetPosition(Ogre::Vector3(
+            x, y, walkmesh_.GetA(static_cast<unsigned int>(safe_triangle_id)).z
+        ));
+        player_entity_->SetRotation(Ogre::Degree(direction));
+        player_entity_->SetMoveTriangleId(safe_triangle_id);
+        // In the WALKMESH state the entity walks to its move position: without this one it walks to
+        // whatever it had (the origin of the field), and the player enters the town walking.
+        player_entity_->SetMovePosition(player_entity_->GetPosition());
+        player_entity_->SetState(Entity::WALKMESH);
+        // The player starts standing still: no move or run from the world map, and the held keys
+        // don't count until they are released.
+        player_move_ = Ogre::Vector3::ZERO;
+        player_run_ = false;
+        ignore_held_walk_ = true;
+        player_entity_->PlayAnimationContinue(player_entity_->GetDefaultAnimationName());
+}
+
+Entity* EntityManager::ScriptGetPlayerEntity() const{
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to set a player entity but the EntityManager is in battle mode.");
+        return nullptr;
+    }
+    return player_entity_;
+}
+
+void EntityManager::ScriptUnsetPlayerEntity(){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to unset a player entity but the EntityManager is in battle mode.");
+        return;
+    }
+    player_entity_ = nullptr;
+}
+
+void EntityManager::ScriptSetPlayerSlip(const bool slip){player_slip_ = slip;}
+
+void EntityManager::ScriptPlayerLock(const bool lock){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to set player lock but the EntityManager is in battle mode.");
+        return;
+    }
+    player_lock_ = lock;
+    if (lock == true) player_move_ = Ogre::Vector3::ZERO;
+    // A field with no entity for the leader of the party (the parade of junonr4, where the player
+    // is a soldier that no PC opcode names) gives the control to the entity whose script lets go
+    // of it.
+    else if (player_entity_ == nullptr && IsFieldModule()){
+        const ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
+        Entity* entity = GetEntity(script.entity);
+        if (entity != nullptr && !entity->IsLine()){
+            LOG_TRIVIAL("The control goes to '" + script.entity + "', there is no player entity.");
+            ScriptSetPlayerEntity(script.entity.c_str());
+            if (!background_2d_.HasScrollControl()) background_2d_.ScriptAutoScrollToEntity(entity);
+        }
+    }
+}
+
+bool EntityManager::IsPlayerLocked() const{return player_lock_;}
+
+void EntityManager::SetPlayerDefaultRun(const bool run){player_default_run_ = run;}
+
+void EntityManager::SetPlayerMoveRotation(const Ogre::Radian rotation){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to set player move rotation the EntityManager is in battle mode.");
+        return;
+    }
+    player_move_rotation_ = rotation;
+}
+
+bool EntityManager::IsStartKeyRead() const{
+    return std::chrono::steady_clock::now() - start_key_read_time_ < std::chrono::milliseconds(300);
+}
+
+bool EntityManager::IsKeyOn(unsigned int key_code){
+    if (key_code & 2048) start_key_read_time_ = std::chrono::steady_clock::now();
+    // The keys are read even if the player is locked: scenes lock the player and still ask for a
+    // button, as the minigames that need to be pressed at the right time do. The scripts that
+    // must not read the keys at some point (while a message is open, for example) have their own
+    // flag for it. The triggers that check keys aren't run while the player is locked.
+    // The key code of the scripts is a mask of the pad buttons, and the check is true if any of
+    // them is pressed. Translate each to its game event (see bind_game_event in config.cfg), so
+    // the keys chosen in the controller settings are the ones that count. For example 32 is
+    // "Circle/Action", the OK button.
+    static const struct{unsigned int mask; const char* event;} BUTTONS[] = {
+      {1, "L2"}, {2, "R2"}, {4, "L1"}, {8, "R1"}, {16, "MENU"}, {32, "CONFIRM"}, {64, "CANCEL"},
+      {128, "EXTRA"}, {256, "SELECT"}, {2048, "START"},
+      {4096, "Up"}, {8192, "Right"}, {16384, "Down"}, {32768, "Left"}
+    };
+    for (const auto& entry : BUTTONS)
+        if ((key_code & entry.mask) && InputManager::getSingleton().IsGameEventPressed(entry.event))
+            return true;
+    // TODO: In the original game the button that makes the player run is the Cancel button (64),
+    // so scripts that check Cancel are checking if the player runs (the sneak out of ealin_2, for
+    // example). Here running has its own game event, "run", so it counts as Cancel too. Scripts
+    // that really want the Cancel button would see it pressed while running. Check which scripts
+    // need which, and maybe split them.
+    if ((key_code & 64) && InputManager::getSingleton().IsGameEventPressed("run")) return true;
+    return false;
+}
+
+bool EntityManager::IsKeyOff(unsigned int key_code){return !IsKeyOn(key_code);}

+ 353 - 0
src/engine/entity/EntityManagerTriggers.cpp

@@ -0,0 +1,353 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <cmath>
+#include <limits>
+#include "engine/entity/EntityManager.h"
+#include "common/Logger.h"
+#include "engine/script/ScriptManager.h"
+
+const int EntityManager::INTERACT_SCRIPT_PRIORITY = 4;
+
+float EntityManager::SquareDistanceToLine(
+  const Ogre::Vector3& point, const Ogre::Vector3& point_a, const Ogre::Vector3& point_b,
+  Ogre::Vector3& proj
+){
+    float temp =
+      -((point_a.x - point.x) * (point_b.x - point_a.x) + (point_a.y - point.y)
+      * (point_b.y - point_a.y) + (point_a.z - point.z) * (point_b.z - point_a.z))
+      / ((point_b.x - point_a.x) * (point_b.x - point_a.x) + (point_b.y - point_a.y)
+      * (point_b.y - point_a.y) + (point_b.z - point_a.z) * (point_b.z - point_a.z));
+
+    proj.x = temp * (point_b.x - point_a.x) + point_a.x;
+    proj.y = temp * (point_b.y - point_a.y) + point_a.y;
+    proj.z = temp * (point_b.z - point_a.z) + point_a.z;
+
+    if (
+      ((point_a.x >= proj.x && point_b.x <= proj.x) || (point_a.x < proj.x && point_b.x >= proj.x))
+      && (
+        (point_a.y >= proj.y && point_b.y <= proj.y) || (point_a.y < proj.y && point_b.y >= proj.y)
+      )
+    ){
+        return (proj.x - point.x) * (proj.x - point.x) + (proj.y - point.y)
+          * (proj.y - point.y) + (proj.z - point.z) * (proj.z - point.z);
+    }
+    return -1;
+}
+
+Ogre::Degree EntityManager::GetDirectionToPoint(
+  const Ogre::Vector3& current_point, const Ogre::Vector3& direction_point
+){
+    // TODO: Declare function in header file.
+    Ogre::Vector2 up(0.0f, -1.0f);
+    Ogre::Vector2 dir(direction_point.x - current_point.x, direction_point.y - current_point.y);
+    // Angle between vectors
+    Ogre::Degree angle(Ogre::Radian(SafeAcos(dir.dotProduct(up), dir.length() * up.length())));
+    return (dir.x < 0) ? Ogre::Degree(360) - angle : angle;
+}
+
+void EntityManager::AddEntityTrigger(
+  const Ogre::String& name,
+  const Ogre::Vector3& point1, const Ogre::Vector3& point2, const bool enabled
+){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to add an entity trigger but the EntityManager is in battle mode.");
+        return;
+    }
+    EntityTrigger* trigger = new EntityTrigger(name);
+    trigger->SetPoints(point1, point2);
+    trigger->SetEnabled(enabled);
+    entity_triggers_.push_back(trigger);
+    ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, trigger->GetName(), nullptr);
+}
+
+float EntityManager::TriggerReach(float solid_radius){
+    // The radius an entity has when a script doesn't change it.
+    const float default_radius = 0.21f;
+    return solid_radius < 0.01f ? default_radius : solid_radius;
+}
+
+bool EntityManager::IsBetterInteractionTarget(
+  float angle, float distance, float best_angle, float best_distance
+){
+    const float same_angle = 0.001f;
+    if (angle < best_angle - same_angle) return true;
+    return std::fabs(angle - best_angle) <= same_angle && distance < best_distance;
+}
+
+void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position){
+    if (IsBattleModule()){
+        LOG_WARNING("Tried to check for triggers, but the EntityManager is in battle mode");
+        return;
+    }
+    if (entity->IsSolid() == false) return;
+    if (player_entity_ != entity) return;
+    if (player_entity_->IsSolid() == false) return;
+    if (player_lock_) return;
+    bool is_moving = true;
+    if (
+      std::fabs(entity->GetPosition().x - position.x) < 0.005f
+      && std::fabs(entity->GetPosition().y - position.y) < 0.005f
+      && std::fabs(entity->GetPosition().z - position.z) < 0.005f
+    ){
+        is_moving = false;
+    }
+
+    for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
+        ScriptEntity* trigger = ScriptManager::getSingleton().GetScriptEntityByName(
+          ScriptManager::ENTITY, entity_triggers_[i]->GetName()
+        );
+
+        if (trigger != nullptr && entity_triggers_[i]->IsEnabled() == true){
+            Ogre::Vector3 point_a = entity_triggers_[i]->GetPoint1();
+            Ogre::Vector3 point_b = entity_triggers_[i]->GetPoint2();
+            Ogre::Vector3 entity_position = entity->GetPosition();
+            Ogre::Vector3 proj;
+
+            // Calculate distance
+            float square_dist = SquareDistanceToLine(entity_position, point_a, point_b, proj);
+            float solid_radius = TriggerReach(entity->GetSolidRadius());
+
+            // Calculate direction.
+            const Ogre::Degree direction_to_line = GetDirectionToPoint(entity_position, proj);
+            const Ogre::Degree destination_direction_to_line = GetDirectionToPoint(position, proj);
+            const Ogre::Degree movement_direction = entity->GetRotation();
+            Ogre::Degree angle = direction_to_line - movement_direction + Ogre::Degree(90);
+            angle = (angle > Ogre::Degree(360)) ? angle - Ogre::Degree(360) : angle;
+
+
+            // Check on enter line.
+            // Must happen only once when the solid radius touches the line, while facing the line,
+            // while the entity is manually moving, and only if not already triggered.
+            if (
+              square_dist != -1 && square_dist <= solid_radius * solid_radius
+              && angle < Ogre::Degree(180) && angle > Ogre::Degree(0)
+              && entity_triggers_[i]->CheckApproached() == false
+              && is_moving
+            ){
+                entity_triggers_[i]->SetApproached(true);
+                //std::cout << "    [TRIGGER] " << entity->GetName() << " on_approach "
+                //  << entity_triggers_[i]->GetName() << std::endl;
+                ScriptManager::getSingleton().ScriptRequest(
+                  trigger, "on_approach", 1, entity->GetName(), "", false, false
+                );
+            }
+
+            // Check on move to line.
+            // Must happen only once when the entity center touches the line, if the entity has
+            // previously entered the line.
+            if (
+              square_dist != -1 && square_dist < 1
+              && entity_triggers_[i]->CheckCrossed() == false
+              && entity_triggers_[i]->CheckApproached() == true
+            ){
+                entity_triggers_[i]->SetCrossed(true);
+                //std::cout << "    [TRIGGER] " << entity->GetName() << " on_cross "
+                //  << entity_triggers_[i]->GetName() << std::endl;
+                ScriptManager::getSingleton().ScriptRequest(
+                  trigger, "on_cross", 1, entity->GetName(), "", false, false
+                );
+            }
+
+            // Check on cross line.
+            // Must happen on every frame while the entity solid radius collides with the line, if
+            // the entity has previously entered the line.
+            if (
+              square_dist != -1 && square_dist <= solid_radius * solid_radius
+              && entity_triggers_[i]->CheckApproached() == true
+            ){
+                // TODO: Fix this hack.
+                // After the on_near script is run, set a cooltime of 5 frames before running
+                // it again. This is because most of the time this trigger checks for a key, and
+                // if its pressed, is run multiple times.
+                if (entity_triggers_[i]->GetNearEventCooldown() == 0){
+                    //std::cout << "    [TRIGGER] " << entity->GetName()
+                    //  << " on_near " << entity_triggers_[i]->GetName() << std::endl;
+                    ScriptManager::getSingleton().ScriptRequest(
+                      trigger, "on_near", 1, entity->GetName(), "", true, true
+                    );
+                    entity_triggers_[i]->ResetNearEventCooldown();
+                }
+                else entity_triggers_[i]->DecreaseNearEventCooldown();
+            }
+
+            // Check on cross line once.
+            // The same as on cross line, but only once.
+            if (
+              square_dist != -1 && square_dist < solid_radius * solid_radius
+              && entity_triggers_[i]->CheckNearSingleEventTriggered() == false
+              && entity_triggers_[i]->CheckApproached() == true
+            ){
+                entity_triggers_[i]->SetNearSingleEventTriggered(true);
+                //std::cout << "    [TRIGGER] " << entity->GetName()
+                //  << " on_near_once " << entity_triggers_[i]->GetName() << std::endl;
+                ScriptManager::getSingleton().ScriptRequest(
+                  trigger, "on_near_once", 1, entity->GetName(), "", false, false
+                );
+
+            }
+
+            // Check on leave line.
+            // Must be triggered once when the line is not in the entity solid radius, but only if
+            // on enter script has been triggered previously.
+            if (
+              square_dist != -1 && square_dist > solid_radius * solid_radius
+              && entity_triggers_[i]->CheckApproached()
+            ){
+                //std::cout << "    [TRIGGER] " << entity->GetName() << " on_leave "
+                //  << entity_triggers_[i]->GetName() << std::endl;
+                ScriptManager::getSingleton().ScriptRequest(
+                  trigger, "on_leave", 1, entity->GetName(), "", false, false
+                );
+            }
+
+            // If the entity is far enough from the line, mark every trigger as inactive
+            if (square_dist == -1 || square_dist > solid_radius * solid_radius){
+                entity_triggers_[i]->Clear();
+                //std::cout << "    [TRIGGER] " << entity->GetName() << " clear of "
+                //  << entity_triggers_[i]->GetName() << std::endl;
+            }
+
+        }
+    }
+}
+
+void EntityManager::ScriptSetLine(
+  const char* name, const float x1, const float y1, const float z1, const float x2, const float y2,
+  const float z2
+){
+    for (EntityTrigger* trigger : entity_triggers_){
+        if (trigger->GetName() == name){
+            trigger->SetPoints(Ogre::Vector3(x1, y1, z1), Ogre::Vector3(x2, y2, z2));
+            return;
+        }
+    }
+}
+
+void EntityManager::CheckEntityContacts(){
+    if (IsBattleModule() || !IsFieldModule()) return;
+    if (player_entity_ == nullptr || player_lock_ || !player_entity_->IsSolid()){
+        entities_in_contact_.clear();
+        return;
+    }
+    const Ogre::Vector3 player_position = player_entity_->GetPosition();
+    for (Entity* entity : entity_){
+        if (entity == player_entity_ || entity->IsLine() || !entity->IsSolid()) continue;
+        const Ogre::Vector3 position = entity->GetPosition();
+        const float height = (position.z < player_position.z)
+          ? entity->GetHeight() : player_entity_->GetHeight();
+        const float distance_z = position.z - player_position.z + height;
+        bool touching = false;
+        if (distance_z < height * 2 && distance_z >= 0){
+            const float reach = player_entity_->GetSolidRadius() + entity->GetSolidRadius() + 0.05f;
+            const float dx = position.x - player_position.x;
+            const float dy = position.y - player_position.y;
+            touching = dx * dx + dy * dy < reach * reach;
+        }
+        if (!touching){
+            entities_in_contact_.erase(entity);
+            continue;
+        }
+        if (!entities_in_contact_.insert(entity).second) continue;
+        ScriptEntity* script_entity = ScriptManager::getSingleton().GetScriptEntityByName(
+          ScriptManager::ENTITY, entity->GetName()
+        );
+        // Most entities have no script for it: nothing to say then.
+        if (script_entity != nullptr){
+            ScriptManager::getSingleton().ScriptRequest(
+              script_entity, "script_2", INTERACT_SCRIPT_PRIORITY, "", "", false, false
+            );
+        }
+    }
+}
+
+void EntityManager::CheckEntityInteract(){
+    if (IsBattleModule()){
+        LOG_WARNING(
+          "Tried to check for entity interaction, but the EntityManager is in battle mode"
+        );
+        return;
+    }
+    if (player_entity_ == NULL || player_lock_ == true || player_entity_->IsSolid() == false)
+        return;
+    Ogre::Degree angle_pc = player_entity_->GetRotation();
+    Entity* entity_to_interact = NULL;
+    Ogre::Degree less_angle(90);
+    float best_distance = std::numeric_limits<float>::max();
+    Ogre::Real nearest_worldmap_distance = -1.0f;
+    for (unsigned int i = 0; i < entity_.size(); ++ i){
+        if (entity_[i]->IsTalkable() == false) continue;
+        if (entity_[i] == player_entity_) continue;
+        Ogre::Vector3 pos1 =  entity_[i]->GetPosition();
+        float interact_range =  entity_[i]->GetTalkRadius();
+        Ogre::Vector3 pos2 = player_entity_->GetPosition();
+        float solid_range = player_entity_->GetSolidRadius();
+                if (IsWorldModule()){
+                        const Ogre::Real target_bottom = pos1.y;
+                        const Ogre::Real player_bottom = pos2.y;
+                                                const Ogre::Real talk_range
+                                                    = interact_range + solid_range + 0.05f;
+                        const Ogre::Real distance
+                            = (pos1.x - pos2.x) * (pos1.x - pos2.x)
+                                + (pos1.z - pos2.z) * (pos1.z - pos2.z);
+                        const bool height_overlap
+                            = player_bottom <= target_bottom + entity_[i]->GetHeight()
+                                && player_bottom + player_entity_->GetHeight() >= target_bottom;
+                        if (
+                                height_overlap && distance <= talk_range * talk_range
+                                && (nearest_worldmap_distance < 0 || distance < nearest_worldmap_distance)
+                        ){
+                                entity_to_interact = entity_[i];
+                                nearest_worldmap_distance = distance;
+                        }
+                        continue;
+                }
+        int height = (pos1.z < pos2.z) ? entity_[i]->GetHeight() : player_entity_->GetHeight();
+        if (((pos1.z - pos2.z + height) < (height * 2)) && ((pos1.z - pos2.z + height) >= 0)){
+            interact_range = (interact_range + solid_range) * (interact_range + solid_range);
+            float distance
+              = (pos1.x - pos2.x) * (pos1.x - pos2.x) + (pos1.y - pos2.y) * (pos1.y - pos2.y);
+            if (distance < interact_range + solid_range){
+                Ogre::Degree angle_to_model = GetDirectionToPoint(pos2, pos1);
+                Ogre::Degree angle = angle_pc - angle_to_model;
+                angle = (angle < Ogre::Degree(0)) ? -angle : angle;
+                angle = (angle >= Ogre::Degree(180)) ? Ogre::Degree(360) - angle : angle;
+                // With several entities in range, interact with the one the player faces most.
+                // Nobody 90 degrees or more away from where the player faces is considered.
+                if (
+                  angle < Ogre::Degree(90) && IsBetterInteractionTarget(
+                    angle.valueDegrees(), distance, less_angle.valueDegrees(), best_distance
+                  )
+                ){
+                    less_angle = angle;
+                    best_distance = distance;
+                    entity_to_interact = entity_[i];
+                }
+            }
+        }
+    }
+    if (entity_to_interact != NULL && entity_to_interact->IsLine() == false){
+        Ogre::String name = entity_to_interact->GetName();
+        ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
+          ScriptManager::ENTITY, name
+        );
+        bool added = ScriptManager::getSingleton().ScriptRequest(
+          scr_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
+        );
+        if (added == false){
+            LOG_WARNING("Script 'on_interact' for entity '" +  name + "' doesn't exist.");
+        }
+    }
+}