HeroMovementController.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 "ConditionalWait.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. if(exits[i].second == nextNode.coord)
  79. {
  80. // Remove this node from path - it will be covered by teleportation
  81. //LOCPLINT->localState->removeLastNode(hero);
  82. LOCPLINT->cb->selectionMade(i, askID);
  83. return;
  84. }
  85. }
  86. // may happen when hero has path but does not moves alongside it
  87. // for example, while standing on teleporter set path that does not leads throught teleporter and press space
  88. LOCPLINT->cb->selectionMade(-1, askID);
  89. return;
  90. }
  91. void HeroMovementController::updatePath(const CGHeroInstance * hero, const TryMoveHero & details)
  92. {
  93. // Once hero moved (or attempted to move) we need to update path
  94. // to make sure that it is still valid or remove it completely if destination has been reached
  95. if(hero->tempOwner != LOCPLINT->playerID)
  96. return;
  97. if(!LOCPLINT->localState->hasPath(hero))
  98. return; // may happen when hero teleports
  99. assert(LOCPLINT->makingTurn);
  100. bool directlyAttackingCreature = details.attackedFrom.has_value() && LOCPLINT->localState->getPath(hero).lastNode().coord == details.attackedFrom;
  101. int3 desiredTarget = LOCPLINT->localState->getPath(hero).nextNode().coord;
  102. int3 actualTarget = hero->convertToVisitablePos(details.end);
  103. //don't erase path when revisiting with spacebar
  104. bool heroChangedTile = details.start != details.end;
  105. if(heroChangedTile)
  106. {
  107. if(desiredTarget != actualTarget)
  108. {
  109. //invalidate path - movement was not along current path
  110. //possible reasons: teleport, visit of object with "blocking visit" property
  111. LOCPLINT->localState->erasePath(hero);
  112. }
  113. else
  114. {
  115. //movement along desired path - remove one node and keep rest of path
  116. LOCPLINT->localState->removeLastNode(hero);
  117. }
  118. if(directlyAttackingCreature)
  119. LOCPLINT->localState->erasePath(hero);
  120. }
  121. }
  122. void HeroMovementController::onTryMoveHero(const CGHeroInstance * hero, const TryMoveHero & details)
  123. {
  124. // Server initiated movement -> start movement animation
  125. // Note that this movement is not necessarily of owned heroes - other players movement will also pass through this method
  126. if(details.result == TryMoveHero::EMBARK || details.result == TryMoveHero::DISEMBARK)
  127. {
  128. if(hero->getRemovalSound() && hero->tempOwner == LOCPLINT->playerID)
  129. CCS->soundh->playSound(hero->getRemovalSound().value());
  130. }
  131. bool directlyAttackingCreature =
  132. details.attackedFrom.has_value() &&
  133. LOCPLINT->localState->hasPath(hero) &&
  134. LOCPLINT->localState->getPath(hero).lastNode().coord == details.attackedFrom;
  135. std::unordered_set<int3> changedTiles {
  136. hero->convertToVisitablePos(details.start),
  137. hero->convertToVisitablePos(details.end)
  138. };
  139. adventureInt->onMapTilesChanged(changedTiles);
  140. adventureInt->onHeroMovementStarted(hero);
  141. updatePath(hero, details);
  142. if(details.stopMovement())
  143. {
  144. if(duringMovement)
  145. endMove(hero);
  146. return;
  147. }
  148. // We are in network thread
  149. // Block netpack processing until movement animation is over
  150. CGI->mh->waitForOngoingAnimations();
  151. //move finished
  152. adventureInt->onHeroChanged(hero);
  153. // Hero attacked creature, set direction to face it.
  154. if(directlyAttackingCreature)
  155. {
  156. // Get direction to attacker.
  157. int3 posOffset = *details.attackedFrom - details.end + int3(2, 1, 0);
  158. static const ui8 dirLookup[3][3] =
  159. {
  160. { 1, 2, 3 },
  161. { 8, 0, 4 },
  162. { 7, 6, 5 }
  163. };
  164. //FIXME: better handling of this case without const_cast
  165. const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
  166. }
  167. }
  168. void HeroMovementController::onQueryReplyApplied()
  169. {
  170. if (!waitingForQueryApplyReply)
  171. return;
  172. waitingForQueryApplyReply = false;
  173. // Server accepted our TeleportDialog query reply and moved hero
  174. // Continue moving alongside our path, if any
  175. if(duringMovement)
  176. onMoveHeroApplied();
  177. }
  178. void HeroMovementController::onMoveHeroApplied()
  179. {
  180. // at this point, server have finished processing of hero movement request
  181. // as well as all side effectes from movement, such as object visit or combat start
  182. // this was request to move alongside path from player, but either another player or teleport action
  183. if(!duringMovement)
  184. return;
  185. // hero has moved onto teleporter and activated it
  186. // in this case next movement should be done only after query reply has been acknowledged
  187. // and hero has been moved to teleport destination
  188. if(waitingForQueryApplyReply)
  189. return;
  190. if(GH.input().ignoreEventsUntilInput())
  191. stoppingMovement = true;
  192. assert(currentlyMovingHero);
  193. const auto * hero = currentlyMovingHero;
  194. bool canMove = LOCPLINT->localState->hasPath(hero) && LOCPLINT->localState->getPath(hero).nextNode().turns == 0 && !LOCPLINT->showingDialog->isBusy();
  195. bool wantStop = stoppingMovement;
  196. bool canStop = !canMove || canHeroStopAtNode(LOCPLINT->localState->getPath(hero).currNode());
  197. if(!canMove || (wantStop && canStop))
  198. {
  199. endMove(hero);
  200. }
  201. else
  202. {
  203. sendMovementRequest(hero, LOCPLINT->localState->getPath(hero));
  204. }
  205. }
  206. void HeroMovementController::requestMovementAbort()
  207. {
  208. if(duringMovement)
  209. endMove(currentlyMovingHero);
  210. }
  211. void HeroMovementController::endMove(const CGHeroInstance * hero)
  212. {
  213. assert(duringMovement == true);
  214. assert(currentlyMovingHero != nullptr);
  215. duringMovement = false;
  216. stoppingMovement = false;
  217. currentlyMovingHero = nullptr;
  218. stopMovementSound();
  219. adventureInt->onHeroChanged(hero);
  220. CCS->curh->show();
  221. }
  222. AudioPath HeroMovementController::getMovementSoundFor(const CGHeroInstance * hero, int3 posPrev, int3 posNext, EPathNodeAction moveType)
  223. {
  224. if(moveType == EPathNodeAction::TELEPORT_BATTLE || moveType == EPathNodeAction::TELEPORT_BLOCKING_VISIT || moveType == EPathNodeAction::TELEPORT_NORMAL)
  225. return {};
  226. if(moveType == EPathNodeAction::EMBARK || moveType == EPathNodeAction::DISEMBARK)
  227. return {};
  228. if(moveType == EPathNodeAction::BLOCKING_VISIT)
  229. return {};
  230. // flying movement sound
  231. if(hero->hasBonusOfType(BonusType::FLYING_MOVEMENT))
  232. return AudioPath::builtin("HORSE10.wav");
  233. auto prevTile = LOCPLINT->cb->getTile(posPrev);
  234. auto nextTile = LOCPLINT->cb->getTile(posNext);
  235. auto prevRoad = prevTile->roadType;
  236. auto nextRoad = nextTile->roadType;
  237. bool movingOnRoad = prevRoad->getId() != Road::NO_ROAD && nextRoad->getId() != Road::NO_ROAD;
  238. if(movingOnRoad)
  239. return nextTile->terType->horseSound;
  240. else
  241. return nextTile->terType->horseSoundPenalty;
  242. };
  243. void HeroMovementController::updateMovementSound(const CGHeroInstance * h, int3 posPrev, int3 nextCoord, EPathNodeAction moveType)
  244. {
  245. // Start a new sound for the hero movement or let the existing one carry on.
  246. AudioPath newSoundName = getMovementSoundFor(h, posPrev, nextCoord, moveType);
  247. if(newSoundName != currentMovementSoundName)
  248. {
  249. currentMovementSoundName = newSoundName;
  250. if(currentMovementSoundChannel != -1)
  251. CCS->soundh->stopSound(currentMovementSoundChannel);
  252. if(!currentMovementSoundName.empty())
  253. currentMovementSoundChannel = CCS->soundh->playSound(currentMovementSoundName, -1, true);
  254. else
  255. currentMovementSoundChannel = -1;
  256. }
  257. }
  258. void HeroMovementController::stopMovementSound()
  259. {
  260. if(currentMovementSoundChannel != -1)
  261. CCS->soundh->stopSound(currentMovementSoundChannel);
  262. currentMovementSoundChannel = -1;
  263. currentMovementSoundName = AudioPath();
  264. }
  265. bool HeroMovementController::canHeroStopAtNode(const CGPathNode & node) const
  266. {
  267. if(node.layer != EPathfindingLayer::LAND && node.layer != EPathfindingLayer::SAIL)
  268. return false;
  269. if(node.accessible != EPathAccessibility::ACCESSIBLE)
  270. return false;
  271. return true;
  272. }
  273. void HeroMovementController::requestMovementStart(const CGHeroInstance * h, const CGPath & path)
  274. {
  275. assert(duringMovement == false);
  276. duringMovement = true;
  277. currentlyMovingHero = h;
  278. CCS->curh->hide();
  279. sendMovementRequest(h, path);
  280. }
  281. void HeroMovementController::sendMovementRequest(const CGHeroInstance * h, const CGPath & path)
  282. {
  283. assert(duringMovement == true);
  284. int heroMovementSpeed = settings["adventure"]["heroMoveTime"].Integer();
  285. bool useMovementBatching = heroMovementSpeed == 0;
  286. const auto & currNode = path.currNode();
  287. const auto & nextNode = path.nextNode();
  288. assert(nextNode.turns == 0);
  289. assert(currNode.coord == h->visitablePos());
  290. if(nextNode.isTeleportAction())
  291. {
  292. stopMovementSound();
  293. logGlobal->trace("Requesting hero teleportation to %s", nextNode.coord.toString());
  294. LOCPLINT->cb->moveHero(h, h->pos, false);
  295. return;
  296. }
  297. if (!useMovementBatching)
  298. {
  299. updateMovementSound(h, currNode.coord, nextNode.coord, nextNode.action);
  300. 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
  301. logGlobal->trace("Requesting hero movement to %s", nextNode.coord.toString());
  302. bool useTransit = nextNode.layer == EPathfindingLayer::AIR || nextNode.layer == EPathfindingLayer::WATER;
  303. int3 nextCoord = h->convertFromVisitablePos(nextNode.coord);
  304. LOCPLINT->cb->moveHero(h, nextCoord, useTransit);
  305. return;
  306. }
  307. bool useTransitAtStart = path.nextNode().layer == EPathfindingLayer::AIR || path.nextNode().layer == EPathfindingLayer::WATER;
  308. std::vector<int3> pathToMove;
  309. for (auto const & node : boost::adaptors::reverse(path.nodes))
  310. {
  311. if (node.coord == h->visitablePos())
  312. continue; // first node, ignore - this is hero current position
  313. if(node.isTeleportAction())
  314. break; // pause after monolith / subterra gates
  315. if (node.turns != 0)
  316. break; // ran out of move points
  317. bool useTransitHere = node.layer == EPathfindingLayer::AIR || node.layer == EPathfindingLayer::WATER;
  318. if (useTransitHere != useTransitAtStart)
  319. break;
  320. int3 coord = h->convertFromVisitablePos(node.coord);
  321. pathToMove.push_back(coord);
  322. if (LOCPLINT->cb->guardingCreaturePosition(node.coord) != int3(-1, -1, -1))
  323. break; // we reached zone-of-control of wandering monster
  324. if (!LOCPLINT->cb->getVisitableObjs(node.coord).empty())
  325. break; // we reached event, garrison or some other visitable object - end this movement batch
  326. }
  327. assert(!pathToMove.empty());
  328. if (!pathToMove.empty())
  329. {
  330. updateMovementSound(h, currNode.coord, nextNode.coord, nextNode.action);
  331. LOCPLINT->cb->moveHero(h, pathToMove, useTransitAtStart);
  332. }
  333. }