HeroMovementController.cpp 13 KB

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