EntityManager.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #include <algorithm>
  16. #include <cstdlib>
  17. #include <iostream>
  18. #include <cmath>
  19. #include <limits>
  20. #include <OgreEntity.h>
  21. #include <OgreRoot.h>
  22. #include <OgreViewport.h>
  23. #include "core/CameraManager.h"
  24. #include "core/ConfigVar.h"
  25. #include "core/DebugDraw.h"
  26. #include "core/EntityManager.h"
  27. #include "core/EntityModel.h"
  28. #include "core/InputManager.h"
  29. #include "core/Logger.h"
  30. #include "core/ScriptManager.h"
  31. #include "core/Timer.h"
  32. #include "core/DialogsManager.h"
  33. /**
  34. * Entity manager singleton.
  35. */
  36. /**
  37. * Priority of the script that runs when the player presses OK in front of an entity.
  38. *
  39. * It has to run before the scripts that fields leave running on an entity (the loops that play an
  40. * animation, requested with priority 5 or 6), or the entity could not be talked to. But it can't
  41. * be the highest: a script of the same entity that is requested with a higher priority (3 or
  42. * smaller) has to be able to run while the talk script waits for it, as in the scenes where a
  43. * talk script asks its own entity to do something and waits for it to start.
  44. */
  45. static const int INTERACT_SCRIPT_PRIORITY = 4;
  46. template<>EntityManager *Ogre::Singleton<EntityManager>::msSingleton = nullptr;
  47. ConfigVar cv_debug_grid("debug_grid", "Draw debug grid", "false");
  48. ConfigVar cv_debug_axis("debug_axis", "Draw debug axis", "false");
  49. ConfigVar cv_encounter_multiplier(
  50. "encounter_multiplier", "Multiplier of the random encounter rate (0 disables them)", "1"
  51. );
  52. ConfigVar cv_debug_encounters("debug_encounters", "Log random encounter checks", "false");
  53. /**
  54. * Frames of walking (at 30 frames per second) between two encounter checks. The original game
  55. * checks every 8 frames.
  56. */
  57. static const float ENCOUNTER_CHECK_FRAMES = 8.0f;
  58. /**
  59. * Value added to the encounter accumulator in each check, before dividing it by the rate of the
  60. * table. The original game uses the speed of the player, which is not known here, so this is tuned
  61. * to a battle every 15-30 seconds of walking in most fields. The encounter_multiplier cvar scales
  62. * it.
  63. */
  64. static const float ENCOUNTER_STEP_VALUE = 5.0f;
  65. const float EntityManager::SCENE_SCALE = 1.0f / 255.0f;
  66. const unsigned int EntityManager::BATTLE_BACKGROUND_ID = 1000;
  67. const unsigned int EntityManager::WORLD_MAP_BACKGROUND_ID = 1001;
  68. float EntityManager::GetTriangleHeight(int triangle, float x, float y, float fallback) const{
  69. if (IsBattleModule() || triangle < 0 || triangle >= walkmesh_.GetNumberOfTriangles())
  70. return fallback;
  71. const float height = PointElevation(
  72. Ogre::Vector2(x, y), walkmesh_.GetA(triangle), walkmesh_.GetB(triangle),
  73. walkmesh_.GetC(triangle)
  74. );
  75. return std::isfinite(height) ? height : fallback;
  76. }
  77. float EntityManager::PointElevation(
  78. const Ogre::Vector2& point, const Ogre::Vector3& a, const Ogre::Vector3& b, const Ogre::Vector3& c
  79. ){
  80. float _a = a.z * (b.y - c.y) + b.z * (c.y - a.y) + c.z * (a.y - b.y);
  81. float _b = a.y * (b.x - c.x) + b.y * (c.x - a.x) + c.y * (a.x - b.x);
  82. float _c = a.x * (b.z - c.z) + b.x * (c.z - a.z) + c.x * (a.z - b.z);
  83. float _d
  84. = a.x * (b.z * c.y - c.z * b.y) + b.x * (c.z * a.y - a.z * c.y)
  85. + c.x * (a.z * b.y - b.z * a.y);
  86. return (_d - _c * point.y - _a * point.x) / _b;
  87. }
  88. float EntityManager::SideOfVector(
  89. const Ogre::Vector2& point, const Ogre::Vector2& p1, const Ogre::Vector2& p2
  90. ){
  91. Ogre::Vector2 AB = p2 - p1;
  92. Ogre::Vector2 AP = point - p1;
  93. return AB.x * AP.y - AB.y * AP.x;
  94. }
  95. float EntityManager::SquareDistanceToLine(
  96. const Ogre::Vector3& point, const Ogre::Vector3& point_a, const Ogre::Vector3& point_b,
  97. Ogre::Vector3& proj
  98. ){
  99. float temp =
  100. -((point_a.x - point.x) * (point_b.x - point_a.x) + (point_a.y - point.y)
  101. * (point_b.y - point_a.y) + (point_a.z - point.z) * (point_b.z - point_a.z))
  102. / ((point_b.x - point_a.x) * (point_b.x - point_a.x) + (point_b.y - point_a.y)
  103. * (point_b.y - point_a.y) + (point_b.z - point_a.z) * (point_b.z - point_a.z));
  104. proj.x = temp * (point_b.x - point_a.x) + point_a.x;
  105. proj.y = temp * (point_b.y - point_a.y) + point_a.y;
  106. proj.z = temp * (point_b.z - point_a.z) + point_a.z;
  107. if (
  108. ((point_a.x >= proj.x && point_b.x <= proj.x) || (point_a.x < proj.x && point_b.x >= proj.x))
  109. && (
  110. (point_a.y >= proj.y && point_b.y <= proj.y) || (point_a.y < proj.y && point_b.y >= proj.y)
  111. )
  112. ){
  113. return (proj.x - point.x) * (proj.x - point.x) + (proj.y - point.y)
  114. * (proj.y - point.y) + (proj.z - point.z) * (proj.z - point.z);
  115. }
  116. return -1;
  117. }
  118. Ogre::Degree EntityManager::GetDirectionToPoint(
  119. const Ogre::Vector3& current_point, const Ogre::Vector3& direction_point
  120. ){
  121. // TODO: Declare function in header file.
  122. Ogre::Vector2 up(0.0f, -1.0f);
  123. Ogre::Vector2 dir(direction_point.x - current_point.x, direction_point.y - current_point.y);
  124. // Angle between vectors
  125. Ogre::Degree angle(Ogre::Radian(SafeAcos(dir.dotProduct(up), dir.length() * up.length())));
  126. return (dir.x < 0) ? Ogre::Degree(360) - angle : angle;
  127. }
  128. EntityManager::EntityManager():
  129. background_3d_(nullptr),
  130. player_entity_(nullptr),
  131. player_move_(Ogre::Vector3::ZERO),
  132. player_move_rotation_(0),
  133. player_lock_(false),
  134. player_run_(false),
  135. random_encounters_(false),
  136. encounter_rate_(0),
  137. encounter_table_(1),
  138. encounter_distance_(0.0f),
  139. encounter_last_position_(Ogre::Vector3::ZERO),
  140. encounter_last_position_valid_(false),
  141. encounter_safe_steps_(0)
  142. {
  143. LOG_TRIVIAL("EntityManager created.");
  144. scene_node_ = Ogre::Root::getSingleton().getSceneManager("Scene")
  145. ->getRootSceneNode()->createChildSceneNode("EntityManager");
  146. //grid_ = Ogre::Root::getSingleton().getSceneManager("Scene")
  147. // ->createEntity("Grid", "system/grid.mesh");
  148. grid_ = Ogre::Root::getSingleton().getSceneManager("Scene")->createEntity("Grid", "grid.mesh");
  149. scene_node_->attachObject(grid_);
  150. //axis_ = Ogre::Root::getSingleton().getSceneManager("Scene")
  151. // ->createEntity("Axis", "system/axis.mesh");
  152. axis_ = Ogre::Root::getSingleton().getSceneManager("Scene")->createEntity("Axis", "axis.mesh");
  153. scene_node_->attachObject(axis_);
  154. }
  155. EntityManager::~EntityManager(){
  156. if (grid_ != nullptr) Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(grid_);
  157. if (axis_ != nullptr) Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(axis_);
  158. Clear();
  159. Ogre::Root::getSingleton().getSceneManager("Scene")->getRootSceneNode()->removeAndDestroyChild(
  160. "EntityManager"
  161. );
  162. LOG_TRIVIAL("EntityManager destroyed.");
  163. }
  164. void EntityManager::Input(const VGears::Event& event){
  165. background_2d_.InputDebug(event);
  166. if (paused_ == true) return;
  167. if (ignore_held_walk_){
  168. InputManager& input = InputManager::getSingleton();
  169. if (
  170. !input.IsGameEventPressed("walk_left") && !input.IsGameEventPressed("walk_right")
  171. && !input.IsGameEventPressed("walk_up") && !input.IsGameEventPressed("walk_down")
  172. ) ignore_held_walk_ = false;
  173. }
  174. if (player_entity_ != NULL && player_lock_ == false){
  175. // Keys held since the world map are ignored until they are released.
  176. const bool key_ignored = ignore_held_walk_ && (
  177. event.event == "walk_left" || event.event == "walk_right" || event.event == "walk_up"
  178. || event.event == "walk_down" || event.event == "run"
  179. );
  180. if (!key_ignored){
  181. if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_left") player_move_.x = -1;
  182. else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_right")
  183. player_move_.x = 1;
  184. if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_down") player_move_.y = -1;
  185. else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_up")
  186. player_move_.y = 1;
  187. if (event.type == VGears::ET_KEY_REPEAT && event.event == "run") player_run_ = true;
  188. }
  189. if (event.type == VGears::ET_KEY_PRESS && event.event == "CONFIRM"){
  190. CheckEntityInteract();
  191. for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
  192. if (
  193. entity_triggers_[i]->IsEnabled() == true
  194. && entity_triggers_[i]->CheckApproached() == true
  195. ){
  196. ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
  197. ScriptManager::ENTITY, entity_triggers_[i]->GetName()
  198. );
  199. bool added = ScriptManager::getSingleton().ScriptRequest(
  200. scr_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
  201. );
  202. if (added == false){
  203. LOG_WARNING(
  204. "Script 'on_interact' for entity '" + entity_triggers_[i]->GetName()
  205. + "' doesn't exist."
  206. );
  207. }
  208. }
  209. }
  210. }
  211. }
  212. }
  213. void EntityManager::UpdateField(){
  214. // Update all entity scripts
  215. ScriptManager::getSingleton().Update(ScriptManager::ENTITY);
  216. // The player is walking if there is a move set by the input.
  217. const bool walked = player_entity_ != nullptr && player_move_ != Ogre::Vector3::ZERO;
  218. // Set move point for player entity
  219. if (player_entity_ != nullptr && player_move_ != Ogre::Vector3::ZERO){
  220. Entity::State state = player_entity_->GetState();
  221. if (state == Entity::WALKMESH || state == Entity::NONE){
  222. // The directional keys are relative to the screen. Rotate them to the field's move
  223. // rotation here, once per frame. This can't be done in Input, which runs once for each
  224. // event, so the rotation would be applied several times when there is more than one
  225. // event in the frame (diagonals, running, ...). player_move_ stays as the raw input,
  226. // which is what ladders need.
  227. // A scripted walk of an entity that isn't the player keeps the last triangle when it
  228. // goes over an edge, so the stored triangle can be far from the position. Reattach to
  229. // the walkmesh before moving manually, otherwise every move would be blocked.
  230. const int current_triangle = player_entity_->GetMoveTriangleId();
  231. bool in_current_triangle = false;
  232. if (current_triangle >= 0 && current_triangle < walkmesh_.GetNumberOfTriangles()){
  233. const Ogre::Vector3 position = player_entity_->GetPosition();
  234. const Ogre::Vector3 A = walkmesh_.GetA(current_triangle);
  235. const Ogre::Vector3 B = walkmesh_.GetB(current_triangle);
  236. const Ogre::Vector3 C = walkmesh_.GetC(current_triangle);
  237. in_current_triangle = Ogre::Math::pointInTri2D(
  238. Ogre::Vector2(position.x, position.y), Ogre::Vector2(A.x, A.y),
  239. Ogre::Vector2(B.x, B.y), Ogre::Vector2(C.x, C.y)
  240. );
  241. }
  242. if (!in_current_triangle) SetEntityOnWalkmesh(player_entity_);
  243. Ogre::Quaternion rotation;
  244. rotation.FromAngleAxis(player_move_rotation_, Ogre::Vector3::UNIT_Z);
  245. // Normalized, so diagonals aren't faster than straight moves.
  246. Ogre::Vector3 input = player_move_;
  247. input.normalise();
  248. const Ogre::Vector3 walk_move = rotation * input
  249. * (player_entity_->GetMoveWalkSpeed() * Timer::getSingleton().GetGameTimeDelta());
  250. player_entity_->SetMovePosition(player_entity_->GetPosition() + walk_move);
  251. player_entity_->SetState(Entity::WALKMESH);
  252. }
  253. // HACK: If manually moving, make playable entity solid.
  254. // Some scripts 'forget' to make the playable entity solid at the end
  255. // of them, and if it remains non-solid, it can't interact with lines
  256. // (i.e. it cant' use gateways).
  257. player_entity_->SetSolid(true);
  258. }
  259. for (unsigned int i = 0; i < entity_.size(); ++ i){
  260. entity_[i]->Update();
  261. // It's not needed to update movements it delta time == 0 (for example
  262. // if time is stopped)
  263. if (Timer::getSingleton().GetGameTimeDelta() == 0) continue;
  264. // Update screen scroll.
  265. Entity* scroll_entity = background_2d_.GetAutoScrollEntity();
  266. if (scroll_entity == entity_[i])
  267. background_2d_.SetScroll(background_2d_.GetEntityScroll(scroll_entity));
  268. // Update offset.
  269. if (entity_[i]->GetOffsetType() != AT_NONE) SetNextOffsetStep(entity_[i]);
  270. // Update turn.
  271. if (entity_[i]->GetTurnType() != AT_NONE) SetNextTurnStep(entity_[i]);
  272. // Update movement.
  273. switch(entity_[i]->GetState()){
  274. case Entity::WALKMESH:
  275. {
  276. // Try set entity on walkmesh if it's still don't has triangle.
  277. if (entity_[i]->GetMoveTriangleId() == -1){
  278. if (SetEntityOnWalkmesh(entity_[i]) == false){
  279. LOG_TRIVIAL(
  280. "Can't set entity '" + entity_[i]->GetName()
  281. + "' on walkmesh. Finish move."
  282. );
  283. entity_[i]->UnsetMove();
  284. }
  285. }
  286. // Perform move
  287. if (entity_[i]->GetState() == Entity::WALKMESH){
  288. float speed = 0;
  289. if (player_lock_ == false && player_entity_ == entity_[i]){
  290. speed = entity_[i]->GetMoveWalkSpeed();
  291. // TODO: Set as a constant.
  292. // Or even better, as a configurable variable.
  293. // The run key inverts the default movement.
  294. if (player_run_ != player_default_run_) speed *= 4;
  295. }
  296. else speed = entity_[i]->GetMoveAutoSpeed();
  297. float remaining_time = Timer::getSingleton().GetGameTimeDelta();
  298. bool is_move = false;
  299. if (entity_[i]->IsScriptedMove() && speed > 0.0f){
  300. const float max_step_time = 0.2f / speed;
  301. while (remaining_time > 0.0f && entity_[i]->GetState() == Entity::WALKMESH){
  302. const float step_time = std::min(remaining_time, max_step_time);
  303. const bool moved = PerformWalkmeshMove(entity_[i], speed, step_time);
  304. is_move = is_move || moved;
  305. if (!moved) break;
  306. remaining_time -= step_time;
  307. }
  308. }
  309. else is_move = PerformWalkmeshMove(entity_[i], speed, remaining_time);
  310. // The scripts set the animation of a scene as the default one (DFANM) and
  311. // don't set it back, but the player stands normally again as soon as they
  312. // walk in the original game (blin67_3, where Cloud ends the scene crouched).
  313. if (
  314. is_move == true && player_lock_ == false && player_entity_ == entity_[i]
  315. && entity_[i]->GetDefaultAnimationName() != "Idle"
  316. ){
  317. entity_[i]->ScriptSetDefaultAnimation("Idle");
  318. }
  319. if (entity_[i]->GetMoveAutoAnimation() == true){
  320. if (is_move == true){
  321. if (speed >= entity_[i]->GetMoveRunSpeed()){
  322. entity_[i]->PlayAnimationContinue(
  323. entity_[i]->GetMoveAnimationRunName()
  324. );
  325. }
  326. else{
  327. entity_[i]->PlayAnimationContinue(
  328. entity_[i]->GetMoveAnimationWalkName()
  329. );
  330. }
  331. }
  332. else if (
  333. entity_[i]->GetAnimationState() != Entity::REQUESTED_ANIMATION
  334. ){
  335. entity_[i]->PlayAnimationContinue(
  336. entity_[i]->GetDefaultAnimationName()
  337. );
  338. }
  339. }
  340. }
  341. }
  342. break;
  343. case Entity::LINEAR:
  344. CheckTriggers(entity_[i], entity_[i]->GetPosition());
  345. SetNextLinearStep(entity_[i]);
  346. break;
  347. case Entity::JUMP:
  348. SetNextJumpStep(entity_[i]);
  349. break;
  350. case Entity::NEEDS_TO_REATTACH:
  351. if (SetEntityOnWalkmesh(entity_[i])) entity_[i]->SetState(Entity::WALKMESH);
  352. else entity_[i]->SetState(Entity::NONE);
  353. case Entity::NONE:
  354. CheckTriggers(entity_[i], entity_[i]->GetPosition());
  355. if (entity_[i]->GetAnimationState() != Entity::REQUESTED_ANIMATION)
  356. entity_[i]->PlayAnimationContinue(entity_[i]->GetDefaultAnimationName());
  357. break;
  358. }
  359. }
  360. CheckEntityContacts();
  361. // Reset player move. It already must be handled in update
  362. player_move_ = Ogre::Vector3::ZERO;
  363. player_run_ = false;
  364. if (background_2d_.GetScrollType() != Background2D::NONE) SetNextScrollStep();
  365. background_2d_.Update();
  366. // This can start a battle and change the module, so it's the last thing to do.
  367. UpdateEncounters(walked);
  368. // The movie follows the speed of the game, so the scenes that are timed with it stay in sync.
  369. // Its sound doesn't, so at any other speed they drift apart.
  370. movie_player_.Update(Timer::getSingleton().GetGameTimeDelta());
  371. screen_fade_.Update(Timer::getSingleton().GetGameTimeDelta());
  372. }
  373. void EntityManager::UpdateBattle(){
  374. ScriptManager::getSingleton().Update(ScriptManager::BATTLE);
  375. if (background_3d_ != nullptr){
  376. background_3d_->Update();
  377. background_3d_->PlayAnimationContinue(background_3d_->GetDefaultAnimationName());
  378. }
  379. for (unsigned int i = 0; i < battle_entity_.size(); ++ i){
  380. battle_entity_[i]->Update();
  381. // Go back to the default animation, unless an animation has been requested. Requested
  382. // animations that are not looped go back to the default one by themselves when they end.
  383. if (battle_entity_[i]->GetAnimationState() != Entity::REQUESTED_ANIMATION){
  384. battle_entity_[i]->PlayAnimationContinue(battle_entity_[i]->GetDefaultAnimationName());
  385. }
  386. }
  387. //CameraManager::getSingleton().GetCurrentCamera()->roll(Ogre::Radian(0.01));
  388. }
  389. void EntityManager::UpdateWorld(){
  390. ScriptManager::getSingleton().Update(ScriptManager::ENTITY);
  391. for (Entity* entity : entity_){
  392. entity->Update();
  393. }
  394. player_move_ = Ogre::Vector3::ZERO;
  395. player_run_ = false;
  396. }
  397. void EntityManager::AddFieldOrWorldMapEntity(
  398. const Ogre::String& name, const Ogre::String& file_name, const Ogre::Vector3& position,
  399. const Ogre::Degree& rotation, const Ogre::Vector3& scale,
  400. const Ogre::Quaternion& root_orientation, const int index
  401. ){
  402. if (module_ != Module::FIELD){
  403. LOG_ERROR("Tried to add field or world Entity but the EntityManager is in battle mode.");
  404. return;
  405. }
  406. Ogre::SceneNode* node = scene_node_->createChildSceneNode("Model_" + name);
  407. EntityModel* entity = new EntityModel(name, file_name, node);
  408. entity->SetPosition(position);
  409. entity->SetRotation(rotation);
  410. entity->setScale(scale);
  411. entity->SetIndex(index);
  412. entity->setRootOrientation(root_orientation);
  413. // The models of a field are visible, solid and talkable until a script changes it (VISI 0,
  414. // SOLID 1, TLKON 1). Many entities, such as the doors of mds6_2 or the people of mrkt2, are
  415. // never turned on by a script. Setting a position doesn't turn them on.
  416. entity->SetVisible(true);
  417. entity->SetSolid(true);
  418. entity->SetTalkable(true);
  419. entity_.push_back(entity);
  420. ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, entity->GetName(), entity);
  421. }
  422. EntityModel* EntityManager::AddWorldMapEntity(
  423. const Ogre::String& name, const Ogre::String& file_name,
  424. const Ogre::Vector3& position, const Ogre::Degree& rotation,
  425. const Ogre::Vector3& scale, const Ogre::String& resource_group
  426. ){
  427. if (!IsWorldModule()){
  428. LOG_ERROR("Tried to add a world-map entity outside world-map mode.");
  429. return nullptr;
  430. }
  431. if (GetEntity(name) != nullptr){
  432. LOG_ERROR("Tried to add duplicate world-map entity '" + name + "'.");
  433. return nullptr;
  434. }
  435. Ogre::SceneNode* node = scene_node_->createChildSceneNode("Model_" + name);
  436. EntityModel* entity = new EntityModel(name, file_name, node, resource_group);
  437. entity->SetPosition(position);
  438. entity->SetRotation(rotation);
  439. entity->setScale(scale);
  440. entity->SetVisible(true);
  441. entity_.push_back(entity);
  442. ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, entity->GetName(), entity);
  443. return entity;
  444. }
  445. void EntityManager::AddBattleEntity(
  446. const Ogre::String& name, const Ogre::String& file_name, const Ogre::Vector3& position,
  447. const Ogre::Degree& rotation, const Ogre::Vector3& scale,
  448. const Ogre::Quaternion& root_orientation, const int index
  449. ){
  450. if (module_ != Module::BATTLE){
  451. LOG_ERROR("Tried to add battle Entity but the EntityManager is not in battle mode.");
  452. return;
  453. }
  454. Ogre::SceneNode* node = scene_node_->createChildSceneNode("Battle_" + name);
  455. // Battle models must be reoriented.
  456. node->setOrientation(root_orientation);
  457. EntityModel* entity = new EntityModel(name, file_name, node);
  458. entity->SetPosition(position);
  459. entity->SetRotation(rotation);
  460. entity->setScale(scale);
  461. entity->SetIndex(index);
  462. entity->SetVisible(true);
  463. battle_entity_.push_back(entity);
  464. ScriptManager::getSingleton().AddEntity(ScriptManager::BATTLE, entity->GetName(), entity);
  465. /*std::cout << "BATTLE ANIMATIONS FOR " << name << std::endl;
  466. const std::map<Ogre::String, Ogre::AnimationState*>& anims
  467. = entity->GetModel()->getAllAnimationStates()->getAnimationStates();
  468. int size = anims.size();
  469. std::cout << " " << std::to_string(size) << " TOTAL " << std::endl;
  470. for (auto anim = anims.begin(); anim != anims.end(); ++ anim){
  471. std::cout << " - " << anim->first << ", " << anim->second << std::endl;
  472. }*/
  473. /* Animations have the following names:
  474. * XX_00,
  475. * XX_01,
  476. * XX_02,
  477. * ...
  478. * where XX is the first two characters of file_name, without the path.
  479. */
  480. Ogre::String anim = file_name.substr(file_name.find_last_of("/\\") + 1).substr(0, 2) + "_00";
  481. //std::cout << " Playing " << anim << std::endl;
  482. entity->ScriptSetDefaultAnimation(anim.c_str());
  483. }
  484. void EntityManager::RemoveBattleEntity(const Ogre::String& name){
  485. if (module_ != Module::BATTLE) return;
  486. for (auto it = battle_entity_.begin(); it != battle_entity_.end(); ++ it){
  487. Entity* entity = *it;
  488. if (entity->GetName() != name) continue;
  489. ScriptManager::getSingleton().RemoveEntity(ScriptManager::BATTLE, name);
  490. battle_entity_.erase(it);
  491. // The entity is not deleted, as its destructor would destroy the model again, like in
  492. // ClearBattle. So what the model holds (a weapon) has to be destroyed here.
  493. entity->ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
  494. Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(name);
  495. scene_node_->removeAndDestroyChild("Battle_" + name);
  496. entity->ReleaseResources();
  497. return;
  498. }
  499. }
  500. void EntityManager::RemoveWorldMapEntity(const Ogre::String& name){
  501. if (!IsWorldModule()) return;
  502. for (auto it = entity_.begin(); it != entity_.end(); ++ it){
  503. Entity* entity = *it;
  504. if (entity->GetName() != name) continue;
  505. if (entity == player_entity_) return;
  506. ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, name);
  507. entity_.erase(it);
  508. // The destructor of the model destroys it.
  509. delete entity;
  510. scene_node_->removeAndDestroyChild("Model_" + name);
  511. return;
  512. }
  513. }
  514. Entity* EntityManager::GetBackground3D() const{
  515. if (IsFieldModule()){
  516. LOG_WARNING("Tried to retrieve a 3D background while the EntityManager is in field mode.");
  517. return nullptr;
  518. }
  519. return background_3d_;
  520. }
  521. void EntityManager::SetBackground3D(const Ogre::String& name, const Ogre::String& file_name){
  522. if (IsFieldModule()){
  523. LOG_ERROR("Tried to add a 3D background while the EntityManager is in field mode.");
  524. return;
  525. }
  526. Ogre::SceneNode* node = scene_node_->createChildSceneNode("bg_" + name);
  527. background_3d_ = new EntityModel(name, file_name, node);
  528. background_3d_->SetPosition(Ogre::Vector3(0, 0, 0));
  529. background_3d_->SetRotation(Ogre::Degree(0));
  530. background_3d_->setScale(Ogre::Vector3(SCENE_SCALE, SCENE_SCALE, SCENE_SCALE));
  531. background_3d_->SetIndex(IsBattleModule() ? BATTLE_BACKGROUND_ID : WORLD_MAP_BACKGROUND_ID);
  532. background_3d_->SetVisible(true);
  533. // Backgrounds must be reoriented.
  534. node->setOrientation(1, 1, 0, 0);
  535. // Probably don't need a script for the 3d background.
  536. /*ScriptManager::getSingleton().AddEntity(
  537. ScriptManager::BATTLE, background_3d_->GetName(), background_3d_
  538. );*/
  539. }
  540. void EntityManager::UpdateDebug(){
  541. // Only the world map fades the debug text with the distance to the camera.
  542. DEBUG_DRAW.SetFadeEnabled(module_ == Module::WORLD);
  543. grid_->setVisible(cv_debug_grid.GetB());
  544. axis_->setVisible(cv_debug_axis.GetB());
  545. if (module_ == Module::BATTLE){
  546. if (background_3d_ != nullptr) background_3d_->UpdateDebug();
  547. for (unsigned int i = 0; i < battle_entity_.size(); ++ i) battle_entity_[i]->UpdateDebug();
  548. }
  549. else{
  550. for (unsigned int i = 0; i < entity_.size(); ++ i) entity_[i]->UpdateDebug();
  551. for (unsigned int i = 0; i < entity_triggers_.size(); ++ i)
  552. entity_triggers_[i]->UpdateDebug();
  553. for (unsigned int i = 0; i < entity_points_.size(); ++ i) entity_points_[i]->UpdateDebug();
  554. walkmesh_.UpdateDebug();
  555. background_2d_.UpdateDebug();
  556. }
  557. }
  558. void EntityManager::OnResize(){background_2d_.OnResize();}
  559. void EntityManager::ClearField(){
  560. ClearEncounterTables();
  561. entities_hidden_by_battle_.clear();
  562. entities_in_contact_.clear();
  563. walkmesh_.Clear();
  564. background_2d_.Clear();
  565. screen_fade_.Clear();
  566. player_slip_ = true;
  567. DialogsManager::getSingleton().Clear();
  568. for (unsigned int i = 0; i < entity_.size(); ++ i){
  569. ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, entity_[i]->GetName());
  570. delete entity_[i];
  571. }
  572. entity_.clear();
  573. player_entity_ = nullptr;
  574. player_move_ = Ogre::Vector3::ZERO;
  575. player_move_rotation_ = 0;
  576. player_lock_ = false;
  577. for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
  578. ScriptManager::getSingleton().RemoveEntity(
  579. ScriptManager::ENTITY, entity_triggers_[i]->GetName()
  580. );
  581. delete entity_triggers_[i];
  582. }
  583. entity_triggers_.clear();
  584. for (unsigned int i = 0; i < entity_points_.size(); ++ i) delete entity_points_[i];
  585. entity_points_.clear();
  586. for (unsigned int i = 0; i < entity_scripts_.size(); ++ i)
  587. ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, entity_scripts_[i]);
  588. scene_node_->removeAndDestroyAllChildren();
  589. }
  590. void EntityManager::ClearBattle(){
  591. for (unsigned int i = 0; i < battle_entity_.size(); ++ i){
  592. ScriptManager::getSingleton().RemoveEntity(
  593. ScriptManager::ENTITY, battle_entity_[i]->GetName()
  594. );
  595. // The model held in a bone (a weapon) is another Ogre entity, and the next battle creates
  596. // one with the same name.
  597. battle_entity_[i]->ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
  598. Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(
  599. battle_entity_[i]->GetName()
  600. );
  601. scene_node_->removeAndDestroyChild("Battle_" + battle_entity_[i]->GetName());
  602. }
  603. battle_entity_.clear();
  604. if (background_3d_ != nullptr){
  605. Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(
  606. "bg_" + background_3d_->GetName()
  607. );
  608. /*ScriptManager::getSingleton().RemoveEntity(
  609. ScriptManager::ENTITY, background_3d_->GetName()
  610. );*/
  611. scene_node_->getChild("bg_" + background_3d_->GetName())->removeAllChildren();
  612. scene_node_->removeAndDestroyChild("bg_" + background_3d_->GetName());
  613. Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(
  614. background_3d_->GetName()
  615. );
  616. background_3d_ = nullptr;
  617. }
  618. }
  619. void EntityManager::ClearWorld(){
  620. walkmesh_.Clear();
  621. for (Entity* entity : entity_){
  622. ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, entity->GetName());
  623. delete entity;
  624. }
  625. entity_.clear();
  626. player_entity_ = nullptr;
  627. player_move_ = Ogre::Vector3::ZERO;
  628. player_move_rotation_ = 0;
  629. player_lock_ = false;
  630. player_run_ = false;
  631. for (EntityTrigger* trigger : entity_triggers_){
  632. ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, trigger->GetName());
  633. delete trigger;
  634. }
  635. entity_triggers_.clear();
  636. for (EntityPoint* point : entity_points_) delete point;
  637. entity_points_.clear();
  638. for (const Ogre::String& script : entity_scripts_){
  639. ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, script);
  640. }
  641. entity_scripts_.clear();
  642. scene_node_->removeAndDestroyAllChildren();
  643. }
  644. Walkmesh* EntityManager::GetWalkmesh(){return &walkmesh_;}
  645. bool EntityManager::IsWorldPositionBlocked(
  646. const Entity* moving_entity, const Ogre::Vector3& position
  647. ) const{
  648. if (!IsWorldModule() || moving_entity == nullptr) return false;
  649. for (const Entity* other : entity_){
  650. if (other == moving_entity || !other->IsSolid()) continue;
  651. const Ogre::Vector3 other_position = other->GetPosition();
  652. const Ogre::Real dx = position.x - other_position.x;
  653. const Ogre::Real dz = position.z - other_position.z;
  654. const Ogre::Real radius = moving_entity->GetSolidRadius() + other->GetSolidRadius();
  655. if (dx * dx + dz * dz >= radius * radius) continue;
  656. const Ogre::Real moving_top = position.y + moving_entity->GetHeight();
  657. const Ogre::Real other_top = other_position.y + other->GetHeight();
  658. if (position.y < other_top && other_position.y < moving_top) return true;
  659. }
  660. return false;
  661. }
  662. Background2D* EntityManager::GetBackground2D(){return &background_2d_;}
  663. ScreenFade* EntityManager::GetScreenFade(){return &screen_fade_;}
  664. MoviePlayer* EntityManager::GetMoviePlayer(){return &movie_player_;}
  665. void EntityManager::AddEntity(
  666. const Ogre::String& name, const Ogre::String& file_name,
  667. const Ogre::Vector3& position, const Ogre::Degree& rotation, int index
  668. ){
  669. AddEntity(
  670. name, file_name, position, rotation,
  671. Ogre::Vector3::UNIT_SCALE, Ogre::Quaternion::IDENTITY, index
  672. );
  673. }
  674. void EntityManager::AddEntity(
  675. const Ogre::String& name, const Ogre::String& file_name, const Ogre::Vector3& position,
  676. const Ogre::Degree& rotation, const Ogre::Vector3& scale,
  677. const Ogre::Quaternion& root_orientation, const int index
  678. ){
  679. if (IsBattleModule())
  680. AddBattleEntity(name, file_name, position, rotation, scale, root_orientation, index);
  681. else
  682. AddFieldOrWorldMapEntity(
  683. name, file_name, position, rotation, scale, root_orientation, index
  684. );
  685. }
  686. void EntityManager::ScriptAddEntity(
  687. const char* name, const char* file_name,
  688. const float x, const float y, const float z, const float rotation, int index
  689. ){AddEntity(name, file_name, Ogre::Vector3(x, y, z), Ogre::Degree(rotation), index);}
  690. void EntityManager::AddEntityTrigger(
  691. const Ogre::String& name,
  692. const Ogre::Vector3& point1, const Ogre::Vector3& point2, const bool enabled
  693. ){
  694. if (IsBattleModule()){
  695. LOG_WARNING("Tried to add an entity trigger but the EntityManager is in battle mode.");
  696. return;
  697. }
  698. EntityTrigger* trigger = new EntityTrigger(name);
  699. trigger->SetPoints(point1, point2);
  700. trigger->SetEnabled(enabled);
  701. entity_triggers_.push_back(trigger);
  702. ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, trigger->GetName(), nullptr);
  703. }
  704. void EntityManager::AddEntityPoint(
  705. const Ogre::String& name, const Ogre::Vector3& position, const float rotation
  706. ){
  707. if (IsBattleModule()){
  708. LOG_WARNING("Tried to add an entity point but the EntityManager is in battle mode.");
  709. return;
  710. }
  711. EntityPoint* entity_point = new EntityPoint(name);
  712. entity_point->SetPosition(position);
  713. entity_point->SetRotation(rotation);
  714. entity_points_.push_back(entity_point);
  715. }
  716. void EntityManager::AddEntityScript(const Ogre::String& name){
  717. // TODO: Should call to this be prevented while in battle mode?
  718. entity_scripts_.push_back(name);
  719. ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, name, nullptr);
  720. }
  721. void EntityManager::ScriptAddEntityScript(const char* name){AddEntityScript(name);}
  722. Entity* EntityManager::GetEntity(const Ogre::String& name) const{
  723. if (IsBattleModule()){
  724. for (unsigned int i = 0; i < battle_entity_.size(); ++ i)
  725. if (battle_entity_[i]->GetName() == name) return battle_entity_[i];
  726. }
  727. else{
  728. for (unsigned int i = 0; i < entity_.size(); ++ i)
  729. if (entity_[i]->GetName() == name) return entity_[i];
  730. }
  731. return nullptr;
  732. }
  733. Entity* EntityManager::GetEntityFromIndex(const int index) const{
  734. if (IsBattleModule()){
  735. if (background_3d_ != nullptr && background_3d_->GetIndex() == index)
  736. return background_3d_;
  737. for (unsigned int i = 0; i < battle_entity_.size(); ++ i)
  738. if (battle_entity_[i]->GetIndex() == index) return battle_entity_[i];
  739. }
  740. else{
  741. for (unsigned int i = 0; i < entity_.size(); ++ i)
  742. if (entity_[i]->GetIndex() == index) return entity_[i];
  743. }
  744. return nullptr;
  745. }
  746. Entity* EntityManager::GetEntityFromCharacterId(const int id) const{
  747. if (IsBattleModule()){
  748. for (unsigned int i = 0; i < battle_entity_.size(); ++ i)
  749. if (battle_entity_[i]->IsCharacter() && battle_entity_[i]->GetCharacterId() == id)
  750. return battle_entity_[i];
  751. }
  752. else{
  753. for (unsigned int i = 0; i < entity_.size(); ++ i)
  754. if (entity_[i]->IsCharacter() && entity_[i]->GetCharacterId() == id) return entity_[i];
  755. }
  756. return nullptr;
  757. }
  758. Entity* EntityManager::ScriptGetEntity(const char* name) const{
  759. return GetEntity(Ogre::String(name));
  760. }
  761. EntityPoint* EntityManager::ScriptGetEntityPoint(const char* name) const{
  762. for (unsigned int i = 0; i < entity_points_.size(); ++ i)
  763. if (entity_points_[i]->GetName() == name) return entity_points_[i];
  764. return nullptr;
  765. }
  766. void EntityManager::ScriptSetPlayerEntity(const char* name){
  767. if (IsBattleModule()){
  768. LOG_WARNING("Tried to set a player entity but the EntityManager is in battle mode.");
  769. return;
  770. }
  771. for (unsigned int i = 0; i < entity_.size(); ++ i){
  772. if (entity_[i]->GetName() == name){
  773. // A script can read the walkmesh triangle of the player right after this, so if it was
  774. // placed by position the triangle has to be known. Done before it's the player entity
  775. // so that the entity not being on the walkmesh yet isn't logged as an error.
  776. if (entity_[i]->GetMoveTriangleId() == -1 && entity_[i]->GetPosition().isZeroLength()){
  777. // A model that has no position of its own (the fields put the dressed Cloud away
  778. // until a script makes it the player) takes the place of the previous player,
  779. // which is where the field entry put the party, as in the original game.
  780. if (player_entity_ != nullptr && player_entity_ != entity_[i]){
  781. entity_[i]->SetPosition(player_entity_->GetPosition());
  782. entity_[i]->SetRotation(player_entity_->GetRotation());
  783. }
  784. }
  785. if (entity_[i]->GetMoveTriangleId() == -1) SetEntityOnWalkmesh(entity_[i]);
  786. LOG_TRIVIAL("Player entity set to '" + std::string(name) + "'.");
  787. // The camera that follows the player keeps following it when another entity takes over
  788. // (Cloud and the dressed Cloud, for example); a camera that follows some other entity
  789. // is left as it is.
  790. if (player_entity_ != nullptr && background_2d_.GetAutoScrollEntity() == player_entity_)
  791. background_2d_.ScriptAutoScrollToEntity(entity_[i]);
  792. // The camera follows the player when no script has said anything about it (the fields
  793. // without a Director, such as ujunon1, have no opcode that starts it).
  794. else if (!background_2d_.HasScrollControl())
  795. background_2d_.ScriptAutoScrollToEntity(entity_[i]);
  796. player_entity_ = entity_[i];
  797. // Also, make it non-talkable. Visibility and solidity are left to the scripts, as in
  798. // the original game: some fields use hidden helper entities (like the 'camera') as
  799. // the player entity to scroll the screen, and they must stay invisible and
  800. // non-solid. When the player moves manually, UpdateField makes it solid anyway.
  801. entity_[i]->SetTalkable(false);
  802. }
  803. }
  804. }
  805. void EntityManager::ScriptPlacePlayerAtFieldEntry(
  806. const float x, const float y, const int triangle_id, const float direction
  807. ){
  808. if (player_entity_ == nullptr || walkmesh_.GetNumberOfTriangles() <= 0) return;
  809. int safe_triangle_id = triangle_id;
  810. if (safe_triangle_id < 0 || safe_triangle_id >= walkmesh_.GetNumberOfTriangles()){
  811. LOG_WARNING("World-map field entry has an invalid walkmesh triangle; using triangle 0.");
  812. safe_triangle_id = 0;
  813. }
  814. player_entity_->SetPosition(Ogre::Vector3(
  815. x, y, walkmesh_.GetA(static_cast<unsigned int>(safe_triangle_id)).z
  816. ));
  817. player_entity_->SetRotation(Ogre::Degree(direction));
  818. player_entity_->SetMoveTriangleId(safe_triangle_id);
  819. // In the WALKMESH state the entity walks to its move position: without this one it walks to
  820. // whatever it had (the origin of the field), and the player enters the town walking.
  821. player_entity_->SetMovePosition(player_entity_->GetPosition());
  822. player_entity_->SetState(Entity::WALKMESH);
  823. // The player starts standing still: no move or run from the world map, and the held keys
  824. // don't count until they are released.
  825. player_move_ = Ogre::Vector3::ZERO;
  826. player_run_ = false;
  827. ignore_held_walk_ = true;
  828. player_entity_->PlayAnimationContinue(player_entity_->GetDefaultAnimationName());
  829. }
  830. Entity* EntityManager::ScriptGetPlayerEntity() const{
  831. if (IsBattleModule()){
  832. LOG_WARNING("Tried to set a player entity but the EntityManager is in battle mode.");
  833. return nullptr;
  834. }
  835. return player_entity_;
  836. }
  837. void EntityManager::ScriptUnsetPlayerEntity(){
  838. if (IsBattleModule()){
  839. LOG_WARNING("Tried to unset a player entity but the EntityManager is in battle mode.");
  840. return;
  841. }
  842. player_entity_ = nullptr;
  843. }
  844. void EntityManager::ScriptSetPlayerSlip(const bool slip){player_slip_ = slip;}
  845. void EntityManager::ScriptPlayerLock(const bool lock){
  846. if (IsBattleModule()){
  847. LOG_WARNING("Tried to set player lock but the EntityManager is in battle mode.");
  848. return;
  849. }
  850. player_lock_ = lock;
  851. if (lock == true) player_move_ = Ogre::Vector3::ZERO;
  852. // A field with no entity for the leader of the party (the parade of junonr4, where the player
  853. // is a soldier that no PC opcode names) gives the control to the entity whose script lets go
  854. // of it.
  855. else if (player_entity_ == nullptr && IsFieldModule()){
  856. const ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
  857. Entity* entity = GetEntity(script.entity);
  858. if (entity != nullptr && !entity->IsLine()){
  859. LOG_TRIVIAL("The control goes to '" + script.entity + "', there is no player entity.");
  860. ScriptSetPlayerEntity(script.entity.c_str());
  861. if (!background_2d_.HasScrollControl()) background_2d_.ScriptAutoScrollToEntity(entity);
  862. }
  863. }
  864. }
  865. bool EntityManager::IsPlayerLocked() const{return player_lock_;}
  866. void EntityManager::SetPlayerDefaultRun(const bool run){player_default_run_ = run;}
  867. void EntityManager::SetPlayerMoveRotation(const Ogre::Radian rotation){
  868. if (IsBattleModule()){
  869. LOG_WARNING("Tried to set player move rotation the EntityManager is in battle mode.");
  870. return;
  871. }
  872. player_move_rotation_ = rotation;
  873. }
  874. bool EntityManager::GetRandomEncounters(){return random_encounters_;}
  875. float EntityManager::GetEncounterMultiplier() const{return cv_encounter_multiplier.GetF();}
  876. bool EntityManager::IsDebugEncounters() const{return cv_debug_encounters.GetB();}
  877. void EntityManager::SetRandomEncounters(bool active){random_encounters_ = active;}
  878. float EntityManager::GetEncounterRate(){return encounter_rate_;}
  879. void EntityManager::HideFieldEntities(){
  880. entities_hidden_by_battle_.clear();
  881. for (Entity* entity : entity_){
  882. if (entity->IsVisible()){
  883. entities_hidden_by_battle_.push_back(entity);
  884. entity->SetVisible(false);
  885. }
  886. }
  887. }
  888. void EntityManager::ShowFieldEntities(){
  889. // Only the ones that still exist: the field could have been changed during the battle.
  890. for (Entity* hidden : entities_hidden_by_battle_){
  891. if (std::find(entity_.begin(), entity_.end(), hidden) != entity_.end()) hidden->SetVisible(true);
  892. }
  893. entities_hidden_by_battle_.clear();
  894. }
  895. void EntityManager::ClearEncounterTables(){
  896. encounter_tables_.clear();
  897. encounter_table_ = 1;
  898. encounter_distance_ = 0.0f;
  899. encounter_last_position_valid_ = false;
  900. encounter_accumulator_ = 0;
  901. encounter_last_battle_ = -1;
  902. }
  903. void EntityManager::AddEncounterTable(
  904. const int id, const int rate, const std::vector<std::pair<int, int>>& battles,
  905. const std::vector<std::pair<int, int>>& specials
  906. ){
  907. EncounterTable table;
  908. table.rate = rate;
  909. table.battles = battles;
  910. table.specials = specials;
  911. encounter_tables_[id] = table;
  912. }
  913. void EntityManager::ScriptSetEncounterTable(const int id){encounter_table_ = id;}
  914. int EntityManager::ScriptRollEncounterBattle() const{
  915. auto found = encounter_tables_.find(encounter_table_);
  916. if (found == encounter_tables_.end()) return -1;
  917. const EncounterTable& table = found->second;
  918. // Like the original game: a roll out of 64 is checked against the special battles one after
  919. // the other (each one adds its probability). If none is hit, a new roll chooses a standard
  920. // battle, the last one being the default.
  921. int roll = std::rand() % 64;
  922. int sum = 0;
  923. for (const auto& special : table.specials){
  924. sum += special.second;
  925. if (roll < sum) return special.first;
  926. }
  927. if (table.battles.empty()) return -1;
  928. roll = std::rand() % 64;
  929. sum = 0;
  930. for (const auto& battle : table.battles){
  931. sum += battle.second;
  932. if (roll < sum) return battle.first;
  933. }
  934. return table.battles.back().first;
  935. }
  936. void EntityManager::UpdateEncounters(const bool walked){
  937. if (player_entity_ == nullptr){
  938. encounter_last_position_valid_ = false;
  939. return;
  940. }
  941. const Ogre::Vector3 position = player_entity_->GetPosition();
  942. const float distance
  943. = encounter_last_position_valid_ ? (position - encounter_last_position_).length() : 0.0f;
  944. encounter_last_position_ = position;
  945. encounter_last_position_valid_ = true;
  946. // Only walking counts: not scripted movements, and not jumps to another place.
  947. if (!walked || player_lock_ || distance > 2.0f) return;
  948. if (!random_encounters_ || encounter_tables_.empty()) return;
  949. auto found = encounter_tables_.find(encounter_table_);
  950. if (found == encounter_tables_.end()) return;
  951. const float multiplier = cv_encounter_multiplier.GetF();
  952. if (multiplier <= 0.0f) return;
  953. // Same as the original game. Every few frames of walking the accumulator grows by a value
  954. // divided by the rate (the lower the rate, the more often the encounters), and an encounter
  955. // starts if a random number is lower than the accumulator.
  956. const int rate = found->second.rate;
  957. if (rate <= 0) return;
  958. encounter_distance_ += Timer::getSingleton().GetGameTimeDelta() * 30.0f;
  959. while (encounter_distance_ >= ENCOUNTER_CHECK_FRAMES){
  960. encounter_distance_ -= ENCOUNTER_CHECK_FRAMES;
  961. // Enemy Away and Enemy Lure materia change the rate of the party (see Party.get_encounter_modifier).
  962. const float materia_multiplier
  963. = ScriptManager::getSingleton().EvaluateNumber("Party.get_encounter_modifier()", 1.0f);
  964. encounter_accumulator_ += static_cast<int>(ENCOUNTER_STEP_VALUE * multiplier * materia_multiplier * 256.0f) / rate;
  965. const int roll = std::rand() % 256 * 256;
  966. if (cv_debug_encounters.GetB()){
  967. LOG_TRIVIAL(
  968. "Encounter check: rate " + std::to_string(rate) + ", accumulator "
  969. + std::to_string(encounter_accumulator_ / 256.0f) + "/256, roll "
  970. + std::to_string(roll / 256)
  971. );
  972. }
  973. if (roll >= encounter_accumulator_) continue;
  974. int battle = ScriptRollEncounterBattle();
  975. // The same battle is not repeated: it's rolled again once.
  976. if (battle == encounter_last_battle_) battle = ScriptRollEncounterBattle();
  977. if (battle < 0) return;
  978. encounter_distance_ = 0.0f;
  979. encounter_accumulator_ = 0;
  980. encounter_last_battle_ = battle;
  981. LOG_TRIVIAL("Random encounter: battle " + std::to_string(battle));
  982. // The battle is started by a script, as it has to change the module of every manager.
  983. ScriptManager::getSingleton().RunString("Encounter.start(" + std::to_string(battle) + ")");
  984. return;
  985. }
  986. }
  987. void EntityManager::SetEncounterRate(float rate){
  988. if (rate >= 1.0f) encounter_rate_ = 1.0f;
  989. else if (rate <= 0.0f) encounter_rate_ = 0.0f;
  990. else encounter_rate_ = rate;
  991. }
  992. bool EntityManager::IsStartKeyRead() const{
  993. return std::chrono::steady_clock::now() - start_key_read_time_ < std::chrono::milliseconds(300);
  994. }
  995. bool EntityManager::IsKeyOn(unsigned int key_code){
  996. if (key_code & 2048) start_key_read_time_ = std::chrono::steady_clock::now();
  997. // The keys are read even if the player is locked: scenes lock the player and still ask for a
  998. // button, as the minigames that need to be pressed at the right time do. The scripts that
  999. // must not read the keys at some point (while a message is open, for example) have their own
  1000. // flag for it. The triggers that check keys aren't run while the player is locked.
  1001. // The key code of the scripts is a mask of the pad buttons, and the check is true if any of
  1002. // them is pressed. Translate each to its game event (see bind_game_event in config.cfg), so
  1003. // the keys chosen in the controller settings are the ones that count. For example 32 is
  1004. // "Circle/Action", the OK button.
  1005. static const struct{unsigned int mask; const char* event;} BUTTONS[] = {
  1006. {1, "L2"}, {2, "R2"}, {4, "L1"}, {8, "R1"}, {16, "MENU"}, {32, "CONFIRM"}, {64, "CANCEL"},
  1007. {128, "EXTRA"}, {256, "SELECT"}, {2048, "START"},
  1008. {4096, "Up"}, {8192, "Right"}, {16384, "Down"}, {32768, "Left"}
  1009. };
  1010. for (const auto& entry : BUTTONS)
  1011. if ((key_code & entry.mask) && InputManager::getSingleton().IsGameEventPressed(entry.event))
  1012. return true;
  1013. // TODO: In the original game the button that makes the player run is the Cancel button (64),
  1014. // so scripts that check Cancel are checking if the player runs (the sneak out of ealin_2, for
  1015. // example). Here running has its own game event, "run", so it counts as Cancel too. Scripts
  1016. // that really want the Cancel button would see it pressed while running. Check which scripts
  1017. // need which, and maybe split them.
  1018. if ((key_code & 64) && InputManager::getSingleton().IsGameEventPressed("run")) return true;
  1019. return false;
  1020. }
  1021. bool EntityManager::IsKeyOff(unsigned int key_code){return !IsKeyOn(key_code);}
  1022. void EntityManager::SetEntityToCharacter(const char* entity_name, unsigned int char_id){
  1023. if (IsBattleModule()){
  1024. for (unsigned int i = 0; i < battle_entity_.size(); ++ i){
  1025. if (battle_entity_[i]->GetName() == entity_name){
  1026. battle_entity_[i]->SetCharacter(char_id);
  1027. return;
  1028. }
  1029. }
  1030. }
  1031. else{
  1032. for (unsigned int i = 0; i < entity_.size(); ++ i){
  1033. if (entity_[i]->GetName() == entity_name){
  1034. entity_[i]->SetCharacter(char_id);
  1035. return;
  1036. }
  1037. }
  1038. }
  1039. LOG_WARNING(
  1040. "Unabe to assigne character ID " + std::to_string(char_id) + " to entity '" + entity_name
  1041. + "'. No entity by that name exists."
  1042. );
  1043. }
  1044. bool EntityManager::SetEntityOnWalkmesh(Entity* entity){
  1045. if (IsBattleModule()){
  1046. LOG_WARNING("Tried to set entity on the walkmesh, but the EntityManager is in battle mode");
  1047. return false;
  1048. }
  1049. Ogre::Vector3 position3 = entity->GetPosition();
  1050. Ogre::Vector2 position2;
  1051. position2.x = position3.x;
  1052. position2.y = position3.y;
  1053. std::vector<std::pair<int, float>> triangles;
  1054. // Search for possible triangles.
  1055. for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
  1056. Ogre::Vector3 A3 = walkmesh_.GetA(i);
  1057. Ogre::Vector3 B3 = walkmesh_.GetB(i);
  1058. Ogre::Vector3 C3 = walkmesh_.GetC(i);
  1059. Ogre::Vector2 A2(A3.x, A3.y);
  1060. Ogre::Vector2 B2(B3.x, B3.y);
  1061. Ogre::Vector2 C2(C3.x, C3.y);
  1062. if (Ogre::Math::pointInTri2D(position2, A2, B2, C2) == true){
  1063. triangles.push_back(std::make_pair(i, PointElevation(
  1064. position2, walkmesh_.GetA(i), walkmesh_.GetB(i), walkmesh_.GetC(i)
  1065. )));
  1066. }
  1067. }
  1068. // If the coordinates doesn't match any triangle, exit.
  1069. if (triangles.size() == 0 && entity == player_entity_){
  1070. LOG_ERROR(
  1071. "Can't find any triangle to place entity '" + entity->GetName() + "' on walkmesh."
  1072. );
  1073. return false;
  1074. }
  1075. // From the possible triangles, select the closest one (on the Z edge).
  1076. int closest_z_triangle = -1;
  1077. float closest_z_distance = 9999.0f;
  1078. float pos_z = position3.z;
  1079. for (size_t i = 0; i < triangles.size(); ++ i){
  1080. if (std::abs(pos_z - triangles[i].second) < closest_z_distance){
  1081. closest_z_triangle = triangles[i].first;
  1082. closest_z_distance = std::abs(pos_z - triangles[i].second);
  1083. }
  1084. }
  1085. if (closest_z_triangle == -1 && entity == player_entity_){
  1086. LOG_ERROR(
  1087. "Can't find nearby triangle to place entity '" + entity->GetName() + "' on walkmesh."
  1088. );
  1089. return false;
  1090. }
  1091. entity->SetPosition(Ogre::Vector3(position2.x, position2.y, pos_z));
  1092. entity->SetMoveTriangleId(closest_z_triangle);
  1093. return true;
  1094. }
  1095. float EntityManager::TriggerReach(float solid_radius){
  1096. // The radius an entity has when a script doesn't change it.
  1097. const float default_radius = 0.21f;
  1098. return solid_radius < 0.01f ? default_radius : solid_radius;
  1099. }
  1100. bool EntityManager::WalkmeshEdgeBlocks(bool is_player, bool scripted_move){
  1101. return is_player || !scripted_move;
  1102. }
  1103. bool EntityManager::IsBetterInteractionTarget(
  1104. float angle, float distance, float best_angle, float best_distance
  1105. ){
  1106. const float same_angle = 0.001f;
  1107. if (angle < best_angle - same_angle) return true;
  1108. return std::fabs(angle - best_angle) <= same_angle && distance < best_distance;
  1109. }
  1110. float EntityManager::ScriptedMoveStep(float distance, float stop_distance, float max_step){
  1111. return std::min(max_step, std::max(0.0f, distance - stop_distance));
  1112. }
  1113. bool EntityManager::PerformWalkmeshMove(Entity* entity, const float speed, const float delta_time){
  1114. if (IsBattleModule()){
  1115. LOG_WARNING("Tried to perform a walkmesh move, but the EntityManager is in battle mode");
  1116. return false;
  1117. }
  1118. Ogre::Vector3 start_point = entity->GetPosition();
  1119. Ogre::Vector3 move_vector = entity->GetMovePosition() - start_point;
  1120. Ogre::Vector2 direction(move_vector.x, move_vector.y);
  1121. const float distance_to_target = direction.length();
  1122. const bool scripted_move = entity->IsScriptedMove();
  1123. const float stop_distance = entity->GetMoveStopDistance();
  1124. if (scripted_move && distance_to_target <= stop_distance + 0.0001f){
  1125. entity->UnsetMove();
  1126. return false;
  1127. }
  1128. direction.normalise();
  1129. direction *= delta_time;
  1130. direction *= speed;
  1131. if (scripted_move && !direction.isZeroLength()){
  1132. direction.normalise();
  1133. direction *= ScriptedMoveStep(
  1134. distance_to_target, stop_distance, speed * delta_time
  1135. );
  1136. }
  1137. // If movement is still needed but speed or time don't allow it, just return for now.
  1138. if (direction.isZeroLength() == true){
  1139. if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
  1140. return false;
  1141. }
  1142. int current_triangle = entity->GetMoveTriangleId();
  1143. // A character that is not on the walkmesh (Jenova of shpin_3, that is placed outside it and
  1144. // moves with FMOVE) is walked in a straight line, or the scene that waits for it would never go
  1145. // on.
  1146. if (current_triangle == -1 && scripted_move && entity != player_entity_){
  1147. const float step = std::min(direction.length(), distance_to_target);
  1148. Ogre::Vector2 move = direction;
  1149. if (!move.isZeroLength()) move.normalise();
  1150. move *= step;
  1151. entity->SetPosition(Ogre::Vector3(start_point.x + move.x, start_point.y + move.y, start_point.z));
  1152. if (distance_to_target - step <= stop_distance + 0.0001f) entity->UnsetMove();
  1153. return step > 0.0f;
  1154. }
  1155. if (current_triangle == -1){
  1156. // The entities that a scene places later (the soldiers of the parade of junonr4) are asked
  1157. // to move before it, and wait. Only the player has to be on the walkmesh.
  1158. if (entity == player_entity_)
  1159. LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
  1160. return false;
  1161. }
  1162. Ogre::Vector3 rotation(0.0f, 0.0f, 0.0f);
  1163. Ogre::Quaternion q1(0.0f, 0.0f, 0.0f, 1.0f);
  1164. Ogre::Vector3 end_point(0.0f, 0.0f, 0.0f);
  1165. Ogre::Vector3 end_point2(0.0f, 0.0f, 0.0f);
  1166. bool first_triangle_check = false;
  1167. bool second_triangle_check = false;
  1168. bool third_triangle_check = false;
  1169. bool last_triangle_check = false;
  1170. bool first_entity_check = false;
  1171. bool second_entity_check = false;
  1172. bool third_entity_check = false;
  1173. // Shorten move vector by triangle angle
  1174. end_point.x = start_point.x + direction.x;
  1175. end_point.y = start_point.y + direction.y;
  1176. Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
  1177. Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
  1178. Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
  1179. end_point.z = PointElevation(Ogre::Vector2(end_point.x, end_point.y), A3, B3, C3);
  1180. Ogre::Vector3 temp = end_point - start_point;
  1181. temp.normalise();
  1182. temp = temp * direction.length();
  1183. direction.x = temp.x;
  1184. direction.y = temp.y;
  1185. // Set the direction for the entity if it has to move.
  1186. if (entity->GetMoveAutoRotation() == true){
  1187. Ogre::Vector2 up(0.0f, -1.0f);
  1188. // Angle between vectors
  1189. Ogre::Degree angle(Ogre::Radian(SafeAcos(
  1190. direction.dotProduct(up), direction.length() * up.length()
  1191. )));
  1192. angle = (direction.x < 0) ? Ogre::Degree(360) - angle : angle;
  1193. entity->SetRotation(Ogre::Degree(angle));
  1194. }
  1195. // A scripted walk (also of the player entity, while a scene has it locked) must end, or the
  1196. // scene waiting for it would never go on. Several scripts place solid entities next to where
  1197. // another one has to walk to, so they don't block it: only the walkmesh does. A manual move
  1198. // of the player is never scripted.
  1199. // The same goes for the points around the end of the step: they are there for the player and
  1200. // NPCs to slide along walls, and a destination next to an edge of the walkmesh would never be
  1201. // reached. The end point itself is still checked.
  1202. const bool check_probes = !scripted_move;
  1203. float solid = (entity->IsSolid() == true) ? entity->GetSolidRadius() : 0.01f;
  1204. // For not playable entities, be a bit more lenient with solid collisions.
  1205. // Don't use the solid radius.
  1206. if (entity != player_entity_) solid /= 10;
  1207. // Get ending point.
  1208. end_point.z = start_point.z;
  1209. for (
  1210. int i = 0;
  1211. (entity == player_entity_ && i < 16)
  1212. || (entity == player_entity_ && i < 3)
  1213. || (entity != player_entity_ && i <= 16);
  1214. ++ i
  1215. ){
  1216. end_point = Ogre::Vector3(
  1217. start_point.x + direction.x, start_point.y + direction.y, start_point.z
  1218. );
  1219. // 1st check.
  1220. // Rotate move_vector +45.
  1221. q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(45)), Ogre::Vector3::UNIT_Z);
  1222. rotation.x = direction.x;
  1223. rotation.y = direction.y;
  1224. rotation.z = 0;
  1225. rotation.normalise();
  1226. rotation = q1 * rotation;
  1227. // Multiply move_vector by solid range
  1228. rotation = rotation * solid;
  1229. end_point2.x = end_point.x + rotation.x;
  1230. end_point2.y = end_point.y + rotation.y;
  1231. // Check_triangle.
  1232. first_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
  1233. entity->SetMoveTriangleId(current_triangle);
  1234. // Model check.
  1235. first_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
  1236. // 2nd check.
  1237. // Rotate move_vector +45.
  1238. q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-45)), Ogre::Vector3::UNIT_Z);
  1239. rotation.x = direction.x;
  1240. rotation.y = direction.y;
  1241. rotation.z = 0;
  1242. rotation.normalise();
  1243. rotation = q1 * rotation;
  1244. // Multiply move_vector by solid range.
  1245. rotation = rotation * solid;
  1246. end_point2.x = end_point.x + rotation.x;
  1247. end_point2.y = end_point.y + rotation.y;
  1248. // Check triangle.
  1249. second_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
  1250. entity->SetMoveTriangleId(current_triangle);
  1251. // Model check.
  1252. second_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
  1253. // 3rd check.
  1254. rotation.x = direction.x;
  1255. rotation.y = direction.y;
  1256. rotation.z = 0;
  1257. rotation.normalise();
  1258. rotation = rotation * solid;
  1259. end_point2.x = end_point.x + rotation.x;
  1260. end_point2.y = end_point.y + rotation.y;
  1261. // Check triangle.
  1262. third_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
  1263. entity->SetMoveTriangleId(current_triangle);
  1264. // Model check.
  1265. third_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
  1266. // Check condition and modify move_vector.
  1267. if (
  1268. first_triangle_check != false || second_triangle_check != false
  1269. || third_triangle_check != false || first_entity_check != false
  1270. || second_entity_check != false || third_entity_check != false
  1271. ){
  1272. // Only for NPC.
  1273. if (entity != player_entity_){
  1274. // If the entity collides only directly into a triangle border.
  1275. if (
  1276. first_triangle_check == false
  1277. && second_triangle_check == false
  1278. && third_triangle_check != false
  1279. ){
  1280. q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-7)), Ogre::Vector3::UNIT_Z);
  1281. rotation.x = direction.x;
  1282. rotation.y = direction.y;
  1283. rotation = q1 * rotation;
  1284. direction.x = rotation.x;
  1285. direction.y = rotation.y;
  1286. }
  1287. // Or if the entity only collides into other entity directly.
  1288. else if (
  1289. first_entity_check == false && second_entity_check == false
  1290. && third_entity_check != false
  1291. ){
  1292. q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z);
  1293. rotation.x = direction.x;
  1294. rotation.y = direction.y;
  1295. rotation = q1 * rotation;
  1296. direction.x = rotation.x;
  1297. direction.y = rotation.y;
  1298. }
  1299. // If not both left and right check failed.
  1300. if (first_triangle_check == false || second_triangle_check == false){
  1301. if (
  1302. (first_triangle_check == false && first_entity_check != false)
  1303. || (first_triangle_check != false && second_triangle_check == false)
  1304. ){
  1305. q1.FromAngleAxis(
  1306. Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
  1307. );
  1308. rotation.x = direction.x;
  1309. rotation.y = direction.y;
  1310. rotation = q1 * rotation;
  1311. direction.x = rotation.x;
  1312. direction.y = rotation.y;
  1313. }
  1314. if (
  1315. first_triangle_check == false
  1316. && first_entity_check == false
  1317. && (second_triangle_check != false || second_entity_check != false
  1318. )
  1319. ){
  1320. q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z);
  1321. rotation.x = direction.x;
  1322. rotation.y = direction.y;
  1323. rotation = q1 * rotation;
  1324. direction.x = rotation.x;
  1325. direction.y = rotation.y;
  1326. }
  1327. continue;
  1328. }
  1329. break;
  1330. }
  1331. // Only for playable character.
  1332. else{
  1333. if (
  1334. first_entity_check == false
  1335. && second_entity_check == false
  1336. && third_entity_check == false
  1337. ){
  1338. // If not both left and right check failed
  1339. if (first_triangle_check == false || second_triangle_check == false){
  1340. // With SLIP off the move is not turned along the wall: it stays blocked.
  1341. if (!player_slip_) break;
  1342. if (first_triangle_check != false && second_triangle_check == false){
  1343. q1.FromAngleAxis(
  1344. Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
  1345. );
  1346. rotation.x = direction.x;
  1347. rotation.y = direction.y;
  1348. rotation = q1 * rotation;
  1349. direction.x = rotation.x;
  1350. direction.y = rotation.y;
  1351. }
  1352. if (first_triangle_check == false && second_triangle_check != false){
  1353. q1.FromAngleAxis(
  1354. Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z
  1355. );
  1356. rotation.x = direction.x;
  1357. rotation.y = direction.y;
  1358. rotation = q1 * rotation;
  1359. direction.x = rotation.x;
  1360. direction.y = rotation.y;
  1361. }
  1362. continue;
  1363. }
  1364. break;
  1365. }
  1366. }
  1367. }
  1368. }
  1369. // Set new X, Y and Z
  1370. last_triangle_check = WalkmeshBorderCross(entity, end_point, direction);
  1371. if (
  1372. first_triangle_check != false || second_triangle_check != false
  1373. || third_triangle_check != false || last_triangle_check != false
  1374. || first_entity_check != false || second_entity_check != false
  1375. || third_entity_check != false
  1376. ){
  1377. // Event if the entity can't move, check for triggers, but use current position.
  1378. if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
  1379. return false;
  1380. }
  1381. // Check triggers before set entity position because move line is checked.
  1382. if (player_entity_ == entity) CheckTriggers(entity, end_point);
  1383. entity->SetPosition(end_point);
  1384. // If the entity has come to destination point, finish movement.
  1385. Ogre::Vector3 final = entity->GetMovePosition() - end_point;
  1386. const float tolerance = scripted_move ? 0.0001f : speed / 10;
  1387. if (Ogre::Vector2(final.x, final.y).length() <= stop_distance + tolerance)
  1388. entity->UnsetMove();
  1389. return true;
  1390. }
  1391. bool EntityManager::WalkmeshBorderCross(
  1392. Entity* entity, Ogre::Vector3& position, const Ogre::Vector2& move_vector
  1393. ){
  1394. if (IsBattleModule()){
  1395. LOG_WARNING("Tried to check for walkmesh cross, but the EntityManager is in battle mode");
  1396. return false;
  1397. }
  1398. int current_triangle = entity->GetMoveTriangleId();
  1399. if (current_triangle == -1) return true;
  1400. // While a scene has the player locked, the scene walks the player like any other character,
  1401. // and it can lead over the edge of the walkmesh.
  1402. const bool free_walk = !WalkmeshEdgeBlocks(
  1403. entity == player_entity_ && !player_lock_, entity->IsScriptedMove()
  1404. );
  1405. Ogre::Vector2 pos = Ogre::Vector2(position.x, position.y);
  1406. bool searched_other_triangle = false;
  1407. for (;;){
  1408. Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
  1409. Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
  1410. Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
  1411. Ogre::Vector2 A(A3.x, A3.y);
  1412. Ogre::Vector2 B(B3.x, B3.y);
  1413. Ogre::Vector2 C(C3.x, C3.y);
  1414. float sign1 = SideOfVector(pos, B, A);
  1415. float sign2 = SideOfVector(pos, C, B);
  1416. float sign3 = SideOfVector(pos, A, C);
  1417. int next_triangle = -1;
  1418. if (sign1 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 0);
  1419. else if (sign2 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 1);
  1420. else if (sign3 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 2);
  1421. else{
  1422. position.z = PointElevation(pos, A3, B3, C3);
  1423. entity->SetMoveTriangleId(current_triangle);
  1424. return false;
  1425. }
  1426. if (next_triangle >= 0){
  1427. bool lock = walkmesh_.IsLocked(next_triangle);
  1428. if (lock == false || free_walk){
  1429. current_triangle = next_triangle;
  1430. continue;
  1431. }
  1432. }
  1433. // A walk of a script goes on over the edge: it keeps the last triangle, unless the point is
  1434. // inside another one (the triangles apart from the rest, that scenes use to put a character
  1435. // higher than the floor, are not joined to it: the character would keep that height after
  1436. // leaving it).
  1437. if (free_walk && !searched_other_triangle){
  1438. searched_other_triangle = true;
  1439. int other_triangle = -1;
  1440. float other_distance = 9999.0f;
  1441. for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
  1442. if (i == current_triangle) continue;
  1443. const Ogre::Vector3 a = walkmesh_.GetA(i);
  1444. const Ogre::Vector3 b = walkmesh_.GetB(i);
  1445. const Ogre::Vector3 c = walkmesh_.GetC(i);
  1446. if (!Ogre::Math::pointInTri2D(
  1447. pos, Ogre::Vector2(a.x, a.y), Ogre::Vector2(b.x, b.y), Ogre::Vector2(c.x, c.y)
  1448. )) continue;
  1449. const float distance = std::abs(position.z - PointElevation(pos, a, b, c));
  1450. if (distance < other_distance){
  1451. other_distance = distance;
  1452. other_triangle = i;
  1453. }
  1454. }
  1455. if (other_triangle >= 0){
  1456. current_triangle = other_triangle;
  1457. continue;
  1458. }
  1459. }
  1460. position.z = PointElevation(pos, A3, B3, C3);
  1461. entity->SetMoveTriangleId(current_triangle);
  1462. // A walk of a script goes on over the edge, keeping the last triangle.
  1463. return !free_walk;
  1464. }
  1465. }
  1466. bool EntityManager::CheckSolidCollisions(Entity* entity, Ogre::Vector3& position){
  1467. if (IsBattleModule()){
  1468. LOG_WARNING("Tried to check for solid collisions, but the EntityManager is in battle mode");
  1469. return false;
  1470. }
  1471. if (entity->IsSolid() == false) return false;
  1472. for (size_t i = 0; i < entity_.size(); ++ i){
  1473. if (entity_[i]->IsSolid() == false) continue;
  1474. if (entity_[i] == entity) continue;
  1475. Ogre::Vector3 pos1 = entity_[i]->GetPosition();
  1476. float solid_range = entity_[i]->GetSolidRadius();
  1477. solid_range *= solid_range;
  1478. float height = (pos1.z < position.z) ? entity_[i]->GetHeight() : entity->GetHeight();
  1479. if (
  1480. ((pos1.z - position.z + height) < (height * 2)) && ((pos1.z - position.z + height) >= 0)
  1481. ){
  1482. float distance
  1483. = (pos1.x - position.x) * (pos1.x - position.x)
  1484. + (pos1.y - position.y) * (pos1.y - position.y);
  1485. if (distance < solid_range) return true;
  1486. }
  1487. }
  1488. return false;
  1489. }
  1490. void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position){
  1491. if (IsBattleModule()){
  1492. LOG_WARNING("Tried to check for triggers, but the EntityManager is in battle mode");
  1493. return;
  1494. }
  1495. if (entity->IsSolid() == false) return;
  1496. if (player_entity_ != entity) return;
  1497. if (player_entity_->IsSolid() == false) return;
  1498. if (player_lock_) return;
  1499. bool is_moving = true;
  1500. if (
  1501. std::fabs(entity->GetPosition().x - position.x) < 0.005f
  1502. && std::fabs(entity->GetPosition().y - position.y) < 0.005f
  1503. && std::fabs(entity->GetPosition().z - position.z) < 0.005f
  1504. ){
  1505. is_moving = false;
  1506. }
  1507. for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
  1508. ScriptEntity* trigger = ScriptManager::getSingleton().GetScriptEntityByName(
  1509. ScriptManager::ENTITY, entity_triggers_[i]->GetName()
  1510. );
  1511. if (trigger != nullptr && entity_triggers_[i]->IsEnabled() == true){
  1512. Ogre::Vector3 point_a = entity_triggers_[i]->GetPoint1();
  1513. Ogre::Vector3 point_b = entity_triggers_[i]->GetPoint2();
  1514. Ogre::Vector3 entity_position = entity->GetPosition();
  1515. Ogre::Vector3 proj;
  1516. // Calculate distance
  1517. float square_dist = SquareDistanceToLine(entity_position, point_a, point_b, proj);
  1518. float solid_radius = TriggerReach(entity->GetSolidRadius());
  1519. // Calculate direction.
  1520. const Ogre::Degree direction_to_line = GetDirectionToPoint(entity_position, proj);
  1521. const Ogre::Degree destination_direction_to_line = GetDirectionToPoint(position, proj);
  1522. const Ogre::Degree movement_direction = entity->GetRotation();
  1523. Ogre::Degree angle = direction_to_line - movement_direction + Ogre::Degree(90);
  1524. angle = (angle > Ogre::Degree(360)) ? angle - Ogre::Degree(360) : angle;
  1525. // Check on enter line.
  1526. // Must happen only once when the solid radius touches the line, while facing the line,
  1527. // while the entity is manually moving, and only if not already triggered.
  1528. if (
  1529. square_dist != -1 && square_dist <= solid_radius * solid_radius
  1530. && angle < Ogre::Degree(180) && angle > Ogre::Degree(0)
  1531. && entity_triggers_[i]->CheckApproached() == false
  1532. && is_moving
  1533. ){
  1534. entity_triggers_[i]->SetApproached(true);
  1535. //std::cout << " [TRIGGER] " << entity->GetName() << " on_approach "
  1536. // << entity_triggers_[i]->GetName() << std::endl;
  1537. ScriptManager::getSingleton().ScriptRequest(
  1538. trigger, "on_approach", 1, entity->GetName(), "", false, false
  1539. );
  1540. }
  1541. // Check on move to line.
  1542. // Must happen only once when the entity center touches the line, if the entity has
  1543. // previously entered the line.
  1544. if (
  1545. square_dist != -1 && square_dist < 1
  1546. && entity_triggers_[i]->CheckCrossed() == false
  1547. && entity_triggers_[i]->CheckApproached() == true
  1548. ){
  1549. entity_triggers_[i]->SetCrossed(true);
  1550. //std::cout << " [TRIGGER] " << entity->GetName() << " on_cross "
  1551. // << entity_triggers_[i]->GetName() << std::endl;
  1552. ScriptManager::getSingleton().ScriptRequest(
  1553. trigger, "on_cross", 1, entity->GetName(), "", false, false
  1554. );
  1555. }
  1556. // Check on cross line.
  1557. // Must happen on every frame while the entity solid radius collides with the line, if
  1558. // the entity has previously entered the line.
  1559. if (
  1560. square_dist != -1 && square_dist <= solid_radius * solid_radius
  1561. && entity_triggers_[i]->CheckApproached() == true
  1562. ){
  1563. // TODO: Fix this hack.
  1564. // After the on_near script is run, set a cooltime of 5 frames before running
  1565. // it again. This is because most of the time this trigger checks for a key, and
  1566. // if its pressed, is run multiple times.
  1567. if (entity_triggers_[i]->GetNearEventCooldown() == 0){
  1568. //std::cout << " [TRIGGER] " << entity->GetName()
  1569. // << " on_near " << entity_triggers_[i]->GetName() << std::endl;
  1570. ScriptManager::getSingleton().ScriptRequest(
  1571. trigger, "on_near", 1, entity->GetName(), "", true, true
  1572. );
  1573. entity_triggers_[i]->ResetNearEventCooldown();
  1574. }
  1575. else entity_triggers_[i]->DecreaseNearEventCooldown();
  1576. }
  1577. // Check on cross line once.
  1578. // The same as on cross line, but only once.
  1579. if (
  1580. square_dist != -1 && square_dist < solid_radius * solid_radius
  1581. && entity_triggers_[i]->CheckNearSingleEventTriggered() == false
  1582. && entity_triggers_[i]->CheckApproached() == true
  1583. ){
  1584. entity_triggers_[i]->SetNearSingleEventTriggered(true);
  1585. //std::cout << " [TRIGGER] " << entity->GetName()
  1586. // << " on_near_once " << entity_triggers_[i]->GetName() << std::endl;
  1587. ScriptManager::getSingleton().ScriptRequest(
  1588. trigger, "on_near_once", 1, entity->GetName(), "", false, false
  1589. );
  1590. }
  1591. // Check on leave line.
  1592. // Must be triggered once when the line is not in the entity solid radius, but only if
  1593. // on enter script has been triggered previously.
  1594. if (
  1595. square_dist != -1 && square_dist > solid_radius * solid_radius
  1596. && entity_triggers_[i]->CheckApproached()
  1597. ){
  1598. //std::cout << " [TRIGGER] " << entity->GetName() << " on_leave "
  1599. // << entity_triggers_[i]->GetName() << std::endl;
  1600. ScriptManager::getSingleton().ScriptRequest(
  1601. trigger, "on_leave", 1, entity->GetName(), "", false, false
  1602. );
  1603. }
  1604. // If the entity is far enough from the line, mark every trigger as inactive
  1605. if (square_dist == -1 || square_dist > solid_radius * solid_radius){
  1606. entity_triggers_[i]->Clear();
  1607. //std::cout << " [TRIGGER] " << entity->GetName() << " clear of "
  1608. // << entity_triggers_[i]->GetName() << std::endl;
  1609. }
  1610. }
  1611. }
  1612. }
  1613. void EntityManager::ScriptSetLine(
  1614. const char* name, const float x1, const float y1, const float z1, const float x2, const float y2,
  1615. const float z2
  1616. ){
  1617. for (EntityTrigger* trigger : entity_triggers_){
  1618. if (trigger->GetName() == name){
  1619. trigger->SetPoints(Ogre::Vector3(x1, y1, z1), Ogre::Vector3(x2, y2, z2));
  1620. return;
  1621. }
  1622. }
  1623. }
  1624. void EntityManager::CheckEntityContacts(){
  1625. if (IsBattleModule() || !IsFieldModule()) return;
  1626. if (player_entity_ == nullptr || player_lock_ || !player_entity_->IsSolid()){
  1627. entities_in_contact_.clear();
  1628. return;
  1629. }
  1630. const Ogre::Vector3 player_position = player_entity_->GetPosition();
  1631. for (Entity* entity : entity_){
  1632. if (entity == player_entity_ || entity->IsLine() || !entity->IsSolid()) continue;
  1633. const Ogre::Vector3 position = entity->GetPosition();
  1634. const float height = (position.z < player_position.z)
  1635. ? entity->GetHeight() : player_entity_->GetHeight();
  1636. const float distance_z = position.z - player_position.z + height;
  1637. bool touching = false;
  1638. if (distance_z < height * 2 && distance_z >= 0){
  1639. const float reach = player_entity_->GetSolidRadius() + entity->GetSolidRadius() + 0.05f;
  1640. const float dx = position.x - player_position.x;
  1641. const float dy = position.y - player_position.y;
  1642. touching = dx * dx + dy * dy < reach * reach;
  1643. }
  1644. if (!touching){
  1645. entities_in_contact_.erase(entity);
  1646. continue;
  1647. }
  1648. if (!entities_in_contact_.insert(entity).second) continue;
  1649. ScriptEntity* script_entity = ScriptManager::getSingleton().GetScriptEntityByName(
  1650. ScriptManager::ENTITY, entity->GetName()
  1651. );
  1652. // Most entities have no script for it: nothing to say then.
  1653. if (script_entity != nullptr){
  1654. ScriptManager::getSingleton().ScriptRequest(
  1655. script_entity, "script_2", INTERACT_SCRIPT_PRIORITY, "", "", false, false
  1656. );
  1657. }
  1658. }
  1659. }
  1660. void EntityManager::CheckEntityInteract(){
  1661. if (IsBattleModule()){
  1662. LOG_WARNING(
  1663. "Tried to check for entity interaction, but the EntityManager is in battle mode"
  1664. );
  1665. return;
  1666. }
  1667. if (player_entity_ == NULL || player_lock_ == true || player_entity_->IsSolid() == false)
  1668. return;
  1669. Ogre::Degree angle_pc = player_entity_->GetRotation();
  1670. Entity* entity_to_interact = NULL;
  1671. Ogre::Degree less_angle(90);
  1672. float best_distance = std::numeric_limits<float>::max();
  1673. Ogre::Real nearest_worldmap_distance = -1.0f;
  1674. for (unsigned int i = 0; i < entity_.size(); ++ i){
  1675. if (entity_[i]->IsTalkable() == false) continue;
  1676. if (entity_[i] == player_entity_) continue;
  1677. Ogre::Vector3 pos1 = entity_[i]->GetPosition();
  1678. float interact_range = entity_[i]->GetTalkRadius();
  1679. Ogre::Vector3 pos2 = player_entity_->GetPosition();
  1680. float solid_range = player_entity_->GetSolidRadius();
  1681. if (IsWorldModule()){
  1682. const Ogre::Real target_bottom = pos1.y;
  1683. const Ogre::Real player_bottom = pos2.y;
  1684. const Ogre::Real talk_range
  1685. = interact_range + solid_range + 0.05f;
  1686. const Ogre::Real distance
  1687. = (pos1.x - pos2.x) * (pos1.x - pos2.x)
  1688. + (pos1.z - pos2.z) * (pos1.z - pos2.z);
  1689. const bool height_overlap
  1690. = player_bottom <= target_bottom + entity_[i]->GetHeight()
  1691. && player_bottom + player_entity_->GetHeight() >= target_bottom;
  1692. if (
  1693. height_overlap && distance <= talk_range * talk_range
  1694. && (nearest_worldmap_distance < 0 || distance < nearest_worldmap_distance)
  1695. ){
  1696. entity_to_interact = entity_[i];
  1697. nearest_worldmap_distance = distance;
  1698. }
  1699. continue;
  1700. }
  1701. int height = (pos1.z < pos2.z) ? entity_[i]->GetHeight() : player_entity_->GetHeight();
  1702. if (((pos1.z - pos2.z + height) < (height * 2)) && ((pos1.z - pos2.z + height) >= 0)){
  1703. interact_range = (interact_range + solid_range) * (interact_range + solid_range);
  1704. float distance
  1705. = (pos1.x - pos2.x) * (pos1.x - pos2.x) + (pos1.y - pos2.y) * (pos1.y - pos2.y);
  1706. if (distance < interact_range + solid_range){
  1707. Ogre::Degree angle_to_model = GetDirectionToPoint(pos2, pos1);
  1708. Ogre::Degree angle = angle_pc - angle_to_model;
  1709. angle = (angle < Ogre::Degree(0)) ? -angle : angle;
  1710. angle = (angle >= Ogre::Degree(180)) ? Ogre::Degree(360) - angle : angle;
  1711. // With several entities in range, interact with the one the player faces most.
  1712. // Nobody 90 degrees or more away from where the player faces is considered.
  1713. if (
  1714. angle < Ogre::Degree(90) && IsBetterInteractionTarget(
  1715. angle.valueDegrees(), distance, less_angle.valueDegrees(), best_distance
  1716. )
  1717. ){
  1718. less_angle = angle;
  1719. best_distance = distance;
  1720. entity_to_interact = entity_[i];
  1721. }
  1722. }
  1723. }
  1724. }
  1725. if (entity_to_interact != NULL && entity_to_interact->IsLine() == false){
  1726. Ogre::String name = entity_to_interact->GetName();
  1727. ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
  1728. ScriptManager::ENTITY, name
  1729. );
  1730. bool added = ScriptManager::getSingleton().ScriptRequest(
  1731. scr_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
  1732. );
  1733. if (added == false){
  1734. LOG_WARNING("Script 'on_interact' for entity '" + name + "' doesn't exist.");
  1735. }
  1736. }
  1737. }
  1738. void EntityManager::SetNextOffsetStep(Entity* entity){
  1739. // TODO: Allow this while on battle mode?
  1740. ActionType type = entity->GetOffsetType();
  1741. float total = entity->GetOffsetSeconds();
  1742. float current = entity->GetOffsetCurrentSeconds();
  1743. current += Timer::getSingleton().GetGameTimeDelta();
  1744. current = (current > total) ? total : current;
  1745. Ogre::Vector3 start = entity->GetOffsetPositionStart();
  1746. Ogre::Vector3 end = entity->GetOffsetPositionEnd();
  1747. // An offset of zero seconds is done at once. Dividing would give NaN.
  1748. float x = (total > 0.0f) ? current / total : 1.0f;
  1749. if (std::isnan(x)) x = 0.0f;
  1750. float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
  1751. Ogre::Vector3 offset = start + (end - start) * smooth_modifier;
  1752. entity->SetOffset(offset);
  1753. if (current == total) entity->UnsetOffset();
  1754. else entity->SetOffsetCurrentSeconds(current);
  1755. }
  1756. void EntityManager::SetNextTurnStep(Entity* entity){
  1757. // TODO: Allow this while on battle mode?
  1758. ActionType type = entity->GetTurnType();
  1759. float total = entity->GetTurnSeconds();
  1760. float current = entity->GetTurnCurrentSeconds();
  1761. current += Timer::getSingleton().GetGameTimeDelta();
  1762. current = (current > total) ? total : current;
  1763. Ogre::Degree start = entity->GetTurnDirectionStart();
  1764. Ogre::Degree end = entity->GetTurnDirectionEnd();
  1765. // A turn of zero seconds is done at once. Dividing would give NaN, and a NaN rotation breaks
  1766. // the bounding box of the entity.
  1767. float x = (total > 0.0f) ? current / total : 1.0f;
  1768. float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
  1769. Ogre::Degree rotation = start + (end - start) * smooth_modifier;
  1770. entity->SetRotation(rotation);
  1771. if (current == total) entity->UnsetTurn();
  1772. else entity->SetTurnCurrentSeconds(current);
  1773. }
  1774. void EntityManager::SetNextLinearStep(Entity* entity){
  1775. if (IsBattleModule()){
  1776. LOG_WARNING("Tried to set next linear step, but the EntityManager is in battle mode");
  1777. return;
  1778. }
  1779. bool to_end = true;
  1780. bool is_move = false;
  1781. Ogre::Vector3 start = entity->GetLinearStart();
  1782. Ogre::Vector3 end = entity->GetLinearEnd();
  1783. Ogre::Vector3 current = entity->GetPosition();
  1784. float delta = Timer::getSingleton().GetGameTimeDelta();
  1785. // The player climbs a ladder with the directional keys. While a scene has the player locked
  1786. // the keys have no effect, and the scene makes the player move on its own, as with any other
  1787. // entity.
  1788. if (entity == player_entity_ && !player_lock_){
  1789. LinearMovement move = entity->GetLinearMovement();
  1790. if (move == LM_DOWN_TO_UP || move == LM_UP_TO_DOWN){
  1791. if (player_move_.y > 0){ // move up
  1792. to_end = (move == LM_DOWN_TO_UP) ? true : false;
  1793. is_move = true;
  1794. }
  1795. else if (player_move_.y < 0){ // move down
  1796. to_end = (move == LM_DOWN_TO_UP) ? false : true;
  1797. is_move = true;
  1798. }
  1799. }
  1800. else if (move == LM_LEFT_TO_RIGHT || move == LM_RIGHT_TO_LEFT){
  1801. if (player_move_.x > 0){ // move right
  1802. to_end = (move == LM_LEFT_TO_RIGHT) ? true : false;
  1803. is_move = true;
  1804. }
  1805. else if (player_move_.x < 0){ // move left
  1806. to_end = (move == LM_LEFT_TO_RIGHT) ? false : true;
  1807. is_move = true;
  1808. }
  1809. }
  1810. }
  1811. else is_move = true;
  1812. if (is_move == true && (end - start).length() < 0.0001f){
  1813. // Start and end are the same place, so there is nothing to walk. Dividing by the time to
  1814. // cross the line (zero) would give a NaN position. Just finish the move.
  1815. entity->UnsetLinear();
  1816. if (to_end == true) entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
  1817. SetEntityOnWalkmesh(entity);
  1818. entity->SetPosition(to_end ? end : start);
  1819. }
  1820. else if (is_move == true){
  1821. Ogre::Vector3 position;
  1822. if (to_end == true){
  1823. Ogre::Vector3 end_start = end - start;
  1824. // Move across the whole line by this number of seconds.
  1825. float time = end_start.length() / 1.2f;
  1826. position.x = current.x + (end_start.x / time) * delta;
  1827. position.y = current.y + (end_start.y / time) * delta;
  1828. position.z = current.z + (end_start.z / time) * delta;
  1829. position.x = (end_start.x < 0)
  1830. ? std::max(position.x, end.x) : std::min(position.x, end.x);
  1831. position.y = (end_start.y < 0)
  1832. ? std::max(position.y, end.y) : std::min(position.y, end.y);
  1833. position.z = (end_start.z < 0)
  1834. ? std::max(position.z, end.z) : std::min(position.z, end.z);
  1835. // Compared with a tolerance: if the entity starts a bit off the end in one of the
  1836. // axes (the entry points are written with a few digits only), that axis could move
  1837. // less than the precision of a float per frame and never be exactly equal.
  1838. if ((position - end).length() < 0.0001f){
  1839. position = end;
  1840. entity->UnsetLinear();
  1841. entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
  1842. SetEntityOnWalkmesh(entity);
  1843. }
  1844. }
  1845. else{
  1846. Ogre::Vector3 end_start = start - end;
  1847. // Move across the whole line by this number of seconds.
  1848. float time = end_start.length() / 1.2f;
  1849. position.x = current.x + (end_start.x / time) * delta;
  1850. position.y = current.y + (end_start.y / time) * delta;
  1851. position.z = current.z + (end_start.z / time) * delta;
  1852. position.x = (end_start.x < 0)
  1853. ? std::max(position.x, start.x) : std::min(position.x, start.x);
  1854. position.y = (end_start.y < 0)
  1855. ? std::max(position.y, start.y) : std::min(position.y, start.y);
  1856. position.z = (end_start.z < 0)
  1857. ? std::max(position.z, start.z) : std::min(position.z, start.z);
  1858. if ((position - start).length() < 0.0001f){
  1859. position = start;
  1860. entity->UnsetLinear();
  1861. SetEntityOnWalkmesh(entity);
  1862. }
  1863. }
  1864. entity->SetPosition(position);
  1865. entity->UpdateAnimation((to_end == true) ? delta : -delta);
  1866. }
  1867. }
  1868. void EntityManager::SetNextJumpStep(Entity* entity){
  1869. if (IsBattleModule()){
  1870. LOG_WARNING("Tried to set next jump step, but the EntityManager is in battle mode");
  1871. return;
  1872. }
  1873. float total = entity->GetJumpSeconds();
  1874. float current = entity->GetJumpCurrentSeconds();
  1875. current += Timer::getSingleton().GetGameTimeDelta();
  1876. // A jump of zero seconds lands at once, without dividing by zero.
  1877. if (total <= 0.0f) total = 0.0001f;
  1878. current = (current > total) ? total : current;
  1879. Ogre::Vector3 start_position = entity->GetJumpStart();
  1880. Ogre::Vector3 end_position = entity->GetJumpEnd();
  1881. Ogre::Vector3 position;
  1882. position.x = start_position.x + ((end_position.x - start_position.x) / total) * current;
  1883. position.y = start_position.y + ((end_position.y - start_position.y) / total) * current;
  1884. position.z = current * current * -1.0f + current
  1885. * ((end_position.z - start_position.z) / total + total * 1.0f) + start_position.z;
  1886. entity->SetPosition(position);
  1887. if (total == current){
  1888. entity->UnsetJump();
  1889. entity->SetMoveTriangleId(entity->GetJumpDestTriangle());
  1890. SetEntityOnWalkmesh(entity);
  1891. // The scripts set the animation of the jump as the default one (DFANM) and don't set it
  1892. // back, but the player stands normally after landing in the original game (the scene of
  1893. // mds6_2 where Cloud jumps down, for example). The scripts that do set it, do it after
  1894. // the jump, so they aren't affected.
  1895. if (entity == player_entity_){
  1896. entity->ScriptSetDefaultAnimation("Idle");
  1897. entity->PlayAnimationContinue("Idle");
  1898. }
  1899. }
  1900. else entity->SetJumpCurrentSeconds(current);
  1901. }
  1902. void EntityManager::SetNextScrollStep(){
  1903. // TODO: Allow this on battle mode?
  1904. background_2d_.UpdateScrollTarget();
  1905. Background2D::SCROLL_TYPE type = background_2d_.GetScrollType();
  1906. float total = background_2d_.GetScrollSeconds();
  1907. float current = background_2d_.GetScrollCurrentSeconds();
  1908. current += Timer::getSingleton().GetGameTimeDelta();
  1909. current = (current > total) ? total : current;
  1910. Ogre::Vector2 start = background_2d_.GetScrollPositionStart();
  1911. Ogre::Vector2 end = background_2d_.GetScrollPositionEnd();
  1912. float x = (total > 0.0f) ? current / total : 1.0f;
  1913. float smooth_modifier = (type == Background2D::SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
  1914. Ogre::Vector2 scroll = start + (end - start) * smooth_modifier;
  1915. background_2d_.SetScroll(scroll);
  1916. if (current == total) background_2d_.UnsetScroll();
  1917. else background_2d_.SetScrollCurrentSeconds(current);
  1918. }