HeroMovementController.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /*
  2. * HeroMovementController.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "HeroMovementController.h"
  12. #include "CGameInfo.h"
  13. #include "CMusicHandler.h"
  14. #include "CPlayerInterface.h"
  15. #include "PlayerLocalState.h"
  16. #include "adventureMap/AdventureMapInterface.h"
  17. #include "eventsSDL/InputHandler.h"
  18. #include "gui/CGuiHandler.h"
  19. #include "gui/CursorHandler.h"
  20. #include "mapView/mapHandler.h"
  21. #include "../CCallback.h"
  22. #include "../lib/CondSh.h"
  23. #include "../lib/pathfinder/CGPathNode.h"
  24. #include "../lib/mapObjects/CGHeroInstance.h"
  25. #include "../lib/networkPacks/PacksForClient.h"
  26. #include "../lib/RoadHandler.h"
  27. #include "../lib/TerrainHandler.h"
  28. bool HeroMovementController::isHeroMovingThroughGarrison(const CGHeroInstance * hero, const CArmedInstance * garrison) const
  29. {
  30. if(!duringMovement)
  31. return false;
  32. if(!LOCPLINT->localState->hasPath(hero))
  33. return false;
  34. if(garrison->visitableAt(LOCPLINT->localState->getPath(hero).lastNode().coord))
  35. return false; // hero want to enter garrison, not pass through it
  36. return true;
  37. }
  38. bool HeroMovementController::isHeroMoving() const
  39. {
  40. return duringMovement;
  41. }
  42. void HeroMovementController::onPlayerTurnStarted()
  43. {
  44. assert(duringMovement == false);
  45. assert(stoppingMovement == false);
  46. duringMovement = false;
  47. currentlyMovingHero = nullptr;
  48. }
  49. void HeroMovementController::onBattleStarted()
  50. {
  51. // when battle starts, game will send battleStart pack *before* movement confirmation
  52. // and since network thread wait for battle intro to play, movement confirmation will only happen after intro
  53. // leading to several bugs, such as blocked input during intro
  54. requestMovementAbort();
  55. }
  56. void HeroMovementController::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  57. {
  58. if (impassable || exits.empty()) //FIXME: why we even have this dialog in such case?
  59. {
  60. LOCPLINT->cb->selectionMade(-1, askID);
  61. return;
  62. }
  63. // Player entered teleporter
  64. // Check whether hero that has entered teleporter has paths that goes through teleporter and select appropriate exit
  65. // othervice, ask server to select one randomly by sending invalid (-1) value as answer
  66. assert(waitingForQueryApplyReply == false);
  67. waitingForQueryApplyReply = true;
  68. if(!LOCPLINT->localState->hasPath(hero))
  69. {
  70. // Hero enters teleporter without specifying exit - select it randomly
  71. LOCPLINT->cb->selectionMade(-1, askID);
  72. return;
  73. }
  74. const auto & heroPath = LOCPLINT->localState->getPath(hero);
  75. const auto & nextNode = heroPath.nextNode();
  76. for(size_t i = 0; i < exits.size(); ++i)
  77. {
  78. const auto * teleporter = LOCPLINT->cb->getObj(exits[i].first);
  79. if(teleporter && teleporter->visitableAt(nextNode.coord))
  80. {
  81. // Remove this node from path - it will be covered by teleportation
  82. //LOCPLINT->localState->removeLastNode(hero);
  83. LOCPLINT->cb->selectionMade(i, askID);
  84. return;
  85. }
  86. }
  87. // may happen when hero has path but does not moves alongside it
  88. // for example, while standing on teleporter set path that does not leads throught teleporter and press space
  89. LOCPLINT->cb->selectionMade(-1, askID);
  90. return;
  91. }
  92. void HeroMovementController::updatePath(const CGHeroInstance * hero, const TryMoveHero & details)
  93. {
  94. // Once hero moved (or attempted to move) we need to update path
  95. // to make sure that it is still valid or remove it completely if destination has been reached
  96. if(hero->tempOwner != LOCPLINT->playerID)
  97. return;
  98. if(!LOCPLINT->localState->hasPath(hero))
  99. return; // may happen when hero teleports
  100. assert(LOCPLINT->makingTurn);
  101. bool directlyAttackingCreature = details.attackedFrom.has_value() && LOCPLINT->localState->getPath(hero).lastNode().coord == details.attackedFrom;
  102. int3 desiredTarget = LOCPLINT->localState->getPath(hero).nextNode().coord;
  103. int3 actualTarget = hero->convertToVisitablePos(details.end);
  104. //don't erase path when revisiting with spacebar
  105. bool heroChangedTile = details.start != details.end;
  106. if(heroChangedTile)
  107. {
  108. if(desiredTarget != actualTarget)
  109. {
  110. //invalidate path - movement was not along current path
  111. //possible reasons: teleport, visit of object with "blocking visit" property
  112. LOCPLINT->localState->erasePath(hero);
  113. }
  114. else
  115. {
  116. //movement along desired path - remove one node and keep rest of path
  117. LOCPLINT->localState->removeLastNode(hero);
  118. }
  119. if(directlyAttackingCreature)
  120. LOCPLINT->localState->erasePath(hero);
  121. }
  122. }
  123. void HeroMovementController::onTryMoveHero(const CGHeroInstance * hero, const TryMoveHero & details)
  124. {
  125. // Server initiated movement -> start movement animation
  126. // Note that this movement is not necessarily of owned heroes - other players movement will also pass through this method
  127. if(details.result == TryMoveHero::EMBARK || details.result == TryMoveHero::DISEMBARK)
  128. {
  129. if(hero->getRemovalSound() && hero->tempOwner == LOCPLINT->playerID)
  130. CCS->soundh->playSound(hero->getRemovalSound().value());
  131. }
  132. bool directlyAttackingCreature =
  133. details.attackedFrom.has_value() &&
  134. LOCPLINT->localState->hasPath(hero) &&
  135. LOCPLINT->localState->getPath(hero).lastNode().coord == details.attackedFrom;
  136. std::unordered_set<int3> changedTiles {
  137. hero->convertToVisitablePos(details.start),
  138. hero->convertToVisitablePos(details.end)
  139. };
  140. adventureInt->onMapTilesChanged(changedTiles);
  141. adventureInt->onHeroMovementStarted(hero);
  142. updatePath(hero, details);
  143. if(details.stopMovement())
  144. {
  145. if(duringMovement)
  146. endMove(hero);
  147. return;
  148. }
  149. // We are in network thread
  150. // Block netpack processing until movement animation is over
  151. CGI->mh->waitForOngoingAnimations();
  152. //move finished
  153. adventureInt->onHeroChanged(hero);
  154. // Hero attacked creature, set direction to face it.
  155. if(directlyAttackingCreature)
  156. {
  157. // Get direction to attacker.
  158. int3 posOffset = *details.attackedFrom - details.end + int3(2, 1, 0);
  159. static const ui8 dirLookup[3][3] =
  160. {
  161. { 1, 2, 3 },
  162. { 8, 0, 4 },
  163. { 7, 6, 5 }
  164. };
  165. //FIXME: better handling of this case without const_cast
  166. const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
  167. }
  168. }
  169. void HeroMovementController::onQueryReplyApplied()
  170. {
  171. waitingForQueryApplyReply = false;
  172. // Server accepted our TeleportDialog query reply and moved hero
  173. // Continue moving alongside our path, if any
  174. if(duringMovement)
  175. onMoveHeroApplied();
  176. }
  177. void HeroMovementController::onMoveHeroApplied()
  178. {
  179. // at this point, server have finished processing of hero movement request
  180. // as well as all side effectes from movement, such as object visit or combat start
  181. // this was request to move alongside path from player, but either another player or teleport action
  182. if(!duringMovement)
  183. return;
  184. // hero has moved onto teleporter and activated it
  185. // in this case next movement should be done only after query reply has been acknowledged
  186. // and hero has been moved to teleport destination
  187. if(waitingForQueryApplyReply)
  188. return;
  189. if(GH.input().ignoreEventsUntilInput())
  190. stoppingMovement = true;
  191. assert(currentlyMovingHero);
  192. const auto * hero = currentlyMovingHero;
  193. bool canMove = LOCPLINT->localState->hasPath(hero) && LOCPLINT->localState->getPath(hero).nextNode().turns == 0 && !LOCPLINT->showingDialog->get();
  194. bool wantStop = stoppingMovement;
  195. bool canStop = !canMove || canHeroStopAtNode(LOCPLINT->localState->getPath(hero).currNode());
  196. if(!canMove || (wantStop && canStop))
  197. {
  198. endMove(hero);
  199. }
  200. else
  201. {
  202. sendMovementRequest(hero, LOCPLINT->localState->getPath(hero));
  203. }
  204. }
  205. void HeroMovementController::requestMovementAbort()
  206. {
  207. if(duringMovement)
  208. endMove(currentlyMovingHero);
  209. }
  210. void HeroMovementController::endMove(const CGHeroInstance * hero)
  211. {
  212. assert(duringMovement == true);
  213. assert(currentlyMovingHero != nullptr);
  214. duringMovement = false;
  215. stoppingMovement = false;
  216. currentlyMovingHero = nullptr;
  217. stopMovementSound();
  218. adventureInt->onHeroChanged(hero);
  219. CCS->curh->show();
  220. }
  221. AudioPath HeroMovementController::getMovementSoundFor(const CGHeroInstance * hero, int3 posPrev, int3 posNext, EPathNodeAction moveType)
  222. {
  223. if(moveType == EPathNodeAction::TELEPORT_BATTLE || moveType == EPathNodeAction::TELEPORT_BLOCKING_VISIT || moveType == EPathNodeAction::TELEPORT_NORMAL)
  224. return {};
  225. if(moveType == EPathNodeAction::EMBARK || moveType == EPathNodeAction::DISEMBARK)
  226. return {};
  227. if(moveType == EPathNodeAction::BLOCKING_VISIT)
  228. return {};
  229. // flying movement sound
  230. if(hero->hasBonusOfType(BonusType::FLYING_MOVEMENT))
  231. return AudioPath::builtin("HORSE10.wav");
  232. auto prevTile = LOCPLINT->cb->getTile(posPrev);
  233. auto nextTile = LOCPLINT->cb->getTile(posNext);
  234. auto prevRoad = prevTile->roadType;
  235. auto nextRoad = nextTile->roadType;
  236. bool movingOnRoad = prevRoad->getId() != Road::NO_ROAD && nextRoad->getId() != Road::NO_ROAD;
  237. if(movingOnRoad)
  238. return nextTile->terType->horseSound;
  239. else
  240. return nextTile->terType->horseSoundPenalty;
  241. };
  242. void HeroMovementController::updateMovementSound(const CGHeroInstance * h, int3 posPrev, int3 nextCoord, EPathNodeAction moveType)
  243. {
  244. // Start a new sound for the hero movement or let the existing one carry on.
  245. AudioPath newSoundName = getMovementSoundFor(h, posPrev, nextCoord, moveType);
  246. if(newSoundName != currentMovementSoundName)
  247. {
  248. currentMovementSoundName = newSoundName;
  249. if(currentMovementSoundChannel != -1)
  250. CCS->soundh->stopSound(currentMovementSoundChannel);
  251. if(!currentMovementSoundName.empty())
  252. currentMovementSoundChannel = CCS->soundh->playSound(currentMovementSoundName, -1, true);
  253. else
  254. currentMovementSoundChannel = -1;
  255. }
  256. }
  257. void HeroMovementController::stopMovementSound()
  258. {
  259. if(currentMovementSoundChannel != -1)
  260. CCS->soundh->stopSound(currentMovementSoundChannel);
  261. currentMovementSoundChannel = -1;
  262. currentMovementSoundName = AudioPath();
  263. }
  264. bool HeroMovementController::canHeroStopAtNode(const CGPathNode & node) const
  265. {
  266. if(node.layer != EPathfindingLayer::LAND && node.layer != EPathfindingLayer::SAIL)
  267. return false;
  268. if(node.accessible != EPathAccessibility::ACCESSIBLE)
  269. return false;
  270. return true;
  271. }
  272. void HeroMovementController::requestMovementStart(const CGHeroInstance * h, const CGPath & path)
  273. {
  274. assert(duringMovement == false);
  275. duringMovement = true;
  276. currentlyMovingHero = h;
  277. CCS->curh->hide();
  278. sendMovementRequest(h, path);
  279. }
  280. void HeroMovementController::sendMovementRequest(const CGHeroInstance * h, const CGPath & path)
  281. {
  282. assert(duringMovement == true);
  283. int heroMovementSpeed = settings["adventure"]["heroMoveTime"].Integer();
  284. bool useMovementBatching = heroMovementSpeed == 0;
  285. const auto & currNode = path.currNode();
  286. const auto & nextNode = path.nextNode();
  287. assert(nextNode.turns == 0);
  288. assert(currNode.coord == h->visitablePos());
  289. if(nextNode.isTeleportAction())
  290. {
  291. stopMovementSound();
  292. logGlobal->trace("Requesting hero teleportation to %s", nextNode.coord.toString());
  293. LOCPLINT->cb->moveHero(h, h->pos, false);
  294. return;
  295. }
  296. if (!useMovementBatching)
  297. {
  298. updateMovementSound(h, currNode.coord, nextNode.coord, nextNode.action);
  299. assert(h->pos.z == nextNode.coord.z); // Z should change only if it's movement via teleporter and in this case this code shouldn't be executed at all
  300. logGlobal->trace("Requesting hero movement to %s", nextNode.coord.toString());
  301. bool useTransit = nextNode.layer == EPathfindingLayer::AIR || nextNode.layer == EPathfindingLayer::WATER;
  302. int3 nextCoord = h->convertFromVisitablePos(nextNode.coord);
  303. LOCPLINT->cb->moveHero(h, nextCoord, useTransit);
  304. return;
  305. }
  306. bool useTransitAtStart = path.nextNode().layer == EPathfindingLayer::AIR || path.nextNode().layer == EPathfindingLayer::WATER;
  307. std::vector<int3> pathToMove;
  308. for (auto const & node : boost::adaptors::reverse(path.nodes))
  309. {
  310. if (node.coord == h->visitablePos())
  311. continue; // first node, ignore - this is hero current position
  312. if(node.isTeleportAction())
  313. break; // pause after monolith / subterra gates
  314. if (node.turns != 0)
  315. break; // ran out of move points
  316. bool useTransitHere = node.layer == EPathfindingLayer::AIR || node.layer == EPathfindingLayer::WATER;
  317. if (useTransitHere != useTransitAtStart)
  318. break;
  319. int3 coord = h->convertFromVisitablePos(node.coord);
  320. pathToMove.push_back(coord);
  321. if (LOCPLINT->cb->guardingCreaturePosition(node.coord) != int3(-1, -1, -1))
  322. break; // we reached zone-of-control of wandering monster
  323. if (!LOCPLINT->cb->getVisitableObjs(node.coord).empty())
  324. break; // we reached event, garrison or some other visitable object - end this movement batch
  325. }
  326. assert(!pathToMove.empty());
  327. if (!pathToMove.empty())
  328. {
  329. updateMovementSound(h, currNode.coord, nextNode.coord, nextNode.action);
  330. LOCPLINT->cb->moveHero(h, pathToMove, useTransitAtStart);
  331. }
  332. }