AdventureMapInterface.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. /*
  2. * AdventureMapInterface.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 "AdventureMapInterface.h"
  12. #include "AdventureOptions.h"
  13. #include "AdventureState.h"
  14. #include "CInGameConsole.h"
  15. #include "CMinimap.h"
  16. #include "CList.h"
  17. #include "CInfoBar.h"
  18. #include "MapAudioPlayer.h"
  19. #include "TurnTimerWidget.h"
  20. #include "AdventureMapWidget.h"
  21. #include "AdventureMapShortcuts.h"
  22. #include "../mapView/mapHandler.h"
  23. #include "../mapView/MapView.h"
  24. #include "../windows/InfoWindows.h"
  25. #include "../widgets/RadialMenu.h"
  26. #include "../gui/CursorHandler.h"
  27. #include "../GameEngine.h"
  28. #include "../GameInstance.h"
  29. #include "../gui/Shortcut.h"
  30. #include "../gui/WindowHandler.h"
  31. #include "../render/Canvas.h"
  32. #include "../render/IImage.h"
  33. #include "../render/IRenderHandler.h"
  34. #include "../render/IScreenHandler.h"
  35. #include "../PlayerLocalState.h"
  36. #include "../CPlayerInterface.h"
  37. #include "../../lib/GameLibrary.h"
  38. #include "../../lib/IGameSettings.h"
  39. #include "../../lib/StartInfo.h"
  40. #include "../../lib/callback/CCallback.h"
  41. #include "../../lib/texts/CGeneralTextHandler.h"
  42. #include "../../lib/spells/CSpellHandler.h"
  43. #include "../../lib/mapObjects/CGHeroInstance.h"
  44. #include "../../lib/mapObjects/CGTownInstance.h"
  45. #include "../../lib/pathfinder/CGPathNode.h"
  46. #include "../../lib/pathfinder/TurnInfo.h"
  47. #include "../../lib/spells/adventure/AdventureSpellEffect.h"
  48. #include "../../lib/spells/ISpellMechanics.h"
  49. #include "../../lib/spells/Problem.h"
  50. std::shared_ptr<AdventureMapInterface> adventureInt;
  51. AdventureMapInterface::AdventureMapInterface():
  52. mapAudio(new MapAudioPlayer()),
  53. spellBeingCasted(nullptr),
  54. scrollingWasActive(false),
  55. scrollingWasBlocked(false),
  56. backgroundDimLevel(settings["adventure"]["backgroundDimLevel"].Integer())
  57. {
  58. OBJECT_CONSTRUCTION;
  59. pos.x = pos.y = 0;
  60. pos.w = ENGINE->screenDimensions().x;
  61. pos.h = ENGINE->screenDimensions().y;
  62. shortcuts = std::make_shared<AdventureMapShortcuts>(*this);
  63. widget = std::make_shared<AdventureMapWidget>(shortcuts);
  64. shortcuts->setState(EAdventureState::MAKING_TURN);
  65. widget->getMapView()->onViewMapActivated();
  66. if(GAME->interface()->cb->getStartInfo()->turnTimerInfo.turnTimer != 0)
  67. watches = std::make_shared<TurnTimerWidget>(Point(24, 24));
  68. addUsedEvents(KEYBOARD | TIME);
  69. }
  70. void AdventureMapInterface::onMapViewMoved(const Rect & visibleArea, int mapLevel)
  71. {
  72. shortcuts->onMapViewMoved(visibleArea, mapLevel);
  73. widget->getMinimap()->onMapViewMoved(visibleArea, mapLevel);
  74. widget->onMapViewMoved(visibleArea, mapLevel);
  75. }
  76. void AdventureMapInterface::onAudioResumed()
  77. {
  78. mapAudio->onAudioResumed();
  79. }
  80. void AdventureMapInterface::onAudioPaused()
  81. {
  82. mapAudio->onAudioPaused();
  83. }
  84. void AdventureMapInterface::onHeroMovementStarted(const CGHeroInstance * hero)
  85. {
  86. if (shortcuts->optionMapViewActive())
  87. {
  88. widget->getInfoBar()->popAll();
  89. widget->getInfoBar()->showSelection();
  90. }
  91. }
  92. void AdventureMapInterface::onHeroChanged(const CGHeroInstance *h)
  93. {
  94. widget->getHeroList()->updateElement(h);
  95. if (h && h == GAME->interface()->localState->getCurrentHero() && !widget->getInfoBar()->showingComponents())
  96. widget->getInfoBar()->showSelection();
  97. widget->updateActiveState();
  98. }
  99. void AdventureMapInterface::onTownChanged(const CGTownInstance * town)
  100. {
  101. widget->getTownList()->updateElement(town);
  102. if (town && town == GAME->interface()->localState->getCurrentTown() && !widget->getInfoBar()->showingComponents())
  103. widget->getInfoBar()->showSelection();
  104. }
  105. void AdventureMapInterface::showInfoBoxMessage(const std::vector<Component> & components, std::string message, int timer)
  106. {
  107. widget->getInfoBar()->pushComponents(components, message, timer);
  108. }
  109. void AdventureMapInterface::activate()
  110. {
  111. CIntObject::activate();
  112. adjustActiveness();
  113. if(GAME->interface())
  114. {
  115. GAME->interface()->cingconsole->activate();
  116. GAME->interface()->cingconsole->pos = this->pos;
  117. }
  118. ENGINE->fakeMouseMove(); //to restore the cursor
  119. // workaround for an edge case:
  120. // if player unequips Angel Wings / Boots of Levitation of currently active hero
  121. // game will correctly invalidate paths but current route will not be updated since verifyPath() is not called for current hero
  122. if (GAME->interface()->makingTurn && GAME->interface()->localState->getCurrentHero())
  123. GAME->interface()->localState->verifyPath(GAME->interface()->localState->getCurrentHero());
  124. }
  125. void AdventureMapInterface::deactivate()
  126. {
  127. CIntObject::deactivate();
  128. ENGINE->cursor().set(Cursor::Map::POINTER);
  129. if(GAME->interface())
  130. GAME->interface()->cingconsole->deactivate();
  131. }
  132. void AdventureMapInterface::showAll(Canvas & to)
  133. {
  134. CIntObject::showAll(to);
  135. dim(to);
  136. GAME->interface()->cingconsole->show(to);
  137. }
  138. void AdventureMapInterface::show(Canvas & to)
  139. {
  140. CIntObject::show(to);
  141. dim(to);
  142. GAME->interface()->cingconsole->show(to);
  143. }
  144. void AdventureMapInterface::dim(Canvas & to)
  145. {
  146. auto const isBigWindow = [&](std::shared_ptr<CIntObject> window) { return window->pos.w >= 800 && window->pos.h >= 600; }; // OH3 fullscreen
  147. if(settings["adventure"]["hideBackground"].Bool())
  148. for (auto window : ENGINE->windows().findWindows<CIntObject>())
  149. {
  150. if(!std::dynamic_pointer_cast<AdventureMapInterface>(window) && std::dynamic_pointer_cast<CIntObject>(window) && isBigWindow(window))
  151. {
  152. to.fillTexture(ENGINE->renderHandler().loadImage(ImagePath::builtin("DiBoxBck"), EImageBlitMode::OPAQUE));
  153. return;
  154. }
  155. }
  156. for (auto window : ENGINE->windows().findWindows<CIntObject>())
  157. {
  158. if (!std::dynamic_pointer_cast<AdventureMapInterface>(window) && !std::dynamic_pointer_cast<RadialMenu>(window) && !window->isPopupWindow() && (settings["adventure"]["backgroundDimSmallWindows"].Bool() || isBigWindow(window) || shortcuts->getState() == EAdventureState::HOTSEAT_WAIT))
  159. {
  160. Rect targetRect(0, 0, ENGINE->screenDimensions().x, ENGINE->screenDimensions().y);
  161. ColorRGBA colorToFill(0, 0, 0, std::clamp<int>(backgroundDimLevel, 0, 255));
  162. if(backgroundDimLevel > 0)
  163. to.drawColorBlended(targetRect, colorToFill);
  164. return;
  165. }
  166. }
  167. }
  168. void AdventureMapInterface::tick(uint32_t msPassed)
  169. {
  170. handleMapScrollingUpdate(msPassed);
  171. // we want animations to be active during enemy turn but map itself to be non-interactive
  172. // so call timer update directly on inactive element
  173. widget->getMapView()->tick(msPassed);
  174. }
  175. void AdventureMapInterface::handleMapScrollingUpdate(uint32_t timePassed)
  176. {
  177. /// Width of window border, in pixels, that triggers map scrolling
  178. static constexpr int32_t borderScrollWidth = 15;
  179. int32_t scrollSpeedPixels = settings["adventure"]["scrollSpeedPixels"].Float();
  180. int32_t scrollDistance = scrollSpeedPixels * timePassed / 1000;
  181. Point cursorPosition = ENGINE->getCursorPosition();
  182. Point scrollDirection;
  183. if (cursorPosition.x < borderScrollWidth)
  184. scrollDirection.x = -1;
  185. if (cursorPosition.x > ENGINE->screenDimensions().x - borderScrollWidth)
  186. scrollDirection.x = +1;
  187. if (cursorPosition.y < borderScrollWidth)
  188. scrollDirection.y = -1;
  189. if (cursorPosition.y > ENGINE->screenDimensions().y - borderScrollWidth)
  190. scrollDirection.y = +1;
  191. Point scrollDelta = scrollDirection * scrollDistance;
  192. bool cursorInScrollArea = scrollDelta != Point(0,0);
  193. bool scrollingActive = cursorInScrollArea && shortcuts->optionMapScrollingActive() && !scrollingWasBlocked;
  194. bool scrollingBlocked = ENGINE->isKeyboardCtrlDown() || !settings["adventure"]["borderScroll"].Bool() || !ENGINE->screenHandler().hasFocus();
  195. if (!scrollingWasActive && scrollingBlocked)
  196. {
  197. scrollingWasBlocked = true;
  198. return;
  199. }
  200. if (!cursorInScrollArea && scrollingWasBlocked)
  201. {
  202. scrollingWasBlocked = false;
  203. return;
  204. }
  205. if (scrollingActive)
  206. widget->getMapView()->onMapScrolled(scrollDelta);
  207. if (!scrollingActive && !scrollingWasActive)
  208. return;
  209. if(scrollDelta.x > 0)
  210. {
  211. if(scrollDelta.y < 0)
  212. ENGINE->cursor().set(Cursor::Map::SCROLL_NORTHEAST);
  213. if(scrollDelta.y > 0)
  214. ENGINE->cursor().set(Cursor::Map::SCROLL_SOUTHEAST);
  215. if(scrollDelta.y == 0)
  216. ENGINE->cursor().set(Cursor::Map::SCROLL_EAST);
  217. }
  218. if(scrollDelta.x < 0)
  219. {
  220. if(scrollDelta.y < 0)
  221. ENGINE->cursor().set(Cursor::Map::SCROLL_NORTHWEST);
  222. if(scrollDelta.y > 0)
  223. ENGINE->cursor().set(Cursor::Map::SCROLL_SOUTHWEST);
  224. if(scrollDelta.y == 0)
  225. ENGINE->cursor().set(Cursor::Map::SCROLL_WEST);
  226. }
  227. if (scrollDelta.x == 0)
  228. {
  229. if(scrollDelta.y < 0)
  230. ENGINE->cursor().set(Cursor::Map::SCROLL_NORTH);
  231. if(scrollDelta.y > 0)
  232. ENGINE->cursor().set(Cursor::Map::SCROLL_SOUTH);
  233. if(scrollDelta.y == 0)
  234. ENGINE->cursor().set(Cursor::Map::POINTER);
  235. }
  236. scrollingWasActive = scrollingActive;
  237. }
  238. void AdventureMapInterface::centerOnTile(int3 on)
  239. {
  240. widget->getMapView()->onCenteredTile(on);
  241. }
  242. void AdventureMapInterface::centerOnObject(const CGObjectInstance * obj)
  243. {
  244. widget->getMapView()->onCenteredObject(obj);
  245. }
  246. void AdventureMapInterface::keyPressed(EShortcut key)
  247. {
  248. if (key == EShortcut::GLOBAL_CANCEL && spellBeingCasted)
  249. hotkeyAbortCastingMode();
  250. //fake mouse use to trigger onTileHovered()
  251. ENGINE->fakeMouseMove();
  252. }
  253. void AdventureMapInterface::onSelectionChanged(const CArmedInstance *sel)
  254. {
  255. assert(sel);
  256. widget->getInfoBar()->popAll();
  257. mapAudio->onSelectionChanged(sel);
  258. bool centerView = !settings["session"]["autoSkip"].Bool();
  259. if (centerView)
  260. centerOnObject(sel);
  261. if(sel->ID==Obj::TOWN)
  262. {
  263. auto town = dynamic_cast<const CGTownInstance*>(sel);
  264. widget->getInfoBar()->showTownSelection(town);
  265. widget->getTownList()->updateWidget();
  266. widget->getTownList()->select(town);
  267. widget->getHeroList()->select(nullptr);
  268. onHeroChanged(nullptr);
  269. }
  270. else //hero selected
  271. {
  272. auto hero = dynamic_cast<const CGHeroInstance*>(sel);
  273. widget->getInfoBar()->showHeroSelection(hero);
  274. widget->getHeroList()->select(hero);
  275. widget->getTownList()->select(nullptr);
  276. GAME->interface()->localState->verifyPath(hero);
  277. onHeroChanged(hero);
  278. }
  279. widget->updateActiveState();
  280. widget->getHeroList()->redraw();
  281. widget->getTownList()->redraw();
  282. }
  283. void AdventureMapInterface::onTownOrderChanged()
  284. {
  285. widget->getTownList()->updateWidget();
  286. }
  287. void AdventureMapInterface::onHeroOrderChanged()
  288. {
  289. widget->getHeroList()->updateWidget();
  290. }
  291. void AdventureMapInterface::onMapTilesChanged(boost::optional<FowTilesType> positions)
  292. {
  293. if (positions)
  294. widget->getMinimap()->updateTiles(*positions);
  295. else
  296. widget->getMinimap()->update();
  297. }
  298. void AdventureMapInterface::onHotseatWaitStarted(PlayerColor playerID)
  299. {
  300. backgroundDimLevel = 255;
  301. widget->getMinimap()->setAIRadar(true);
  302. onCurrentPlayerChanged(playerID);
  303. setState(EAdventureState::HOTSEAT_WAIT);
  304. }
  305. void AdventureMapInterface::onEnemyTurnStarted(PlayerColor playerID, bool isHuman)
  306. {
  307. if(settings["session"]["spectate"].Bool())
  308. return;
  309. mapAudio->onEnemyTurnStarted();
  310. widget->getMinimap()->setAIRadar(!isHuman);
  311. widget->getInfoBar()->startEnemyTurn(playerID);
  312. setState(isHuman ? EAdventureState::MAKING_TURN : EAdventureState::AI_PLAYER_TURN);
  313. }
  314. void AdventureMapInterface::setState(EAdventureState state)
  315. {
  316. shortcuts->setState(state);
  317. adjustActiveness();
  318. widget->updateActiveState();
  319. }
  320. void AdventureMapInterface::adjustActiveness()
  321. {
  322. bool widgetMustBeActive = isActive() && shortcuts->optionSidePanelActive();
  323. bool mapViewMustBeActive = isActive() && (shortcuts->optionMapViewActive());
  324. widget->setInputEnabled(widgetMustBeActive);
  325. widget->getMapView()->setInputEnabled(mapViewMustBeActive);
  326. }
  327. void AdventureMapInterface::onCurrentPlayerChanged(PlayerColor playerID)
  328. {
  329. if (playerID == currentPlayerID)
  330. return;
  331. currentPlayerID = playerID;
  332. widget->setPlayerColor(playerID);
  333. }
  334. void AdventureMapInterface::onPlayerTurnStarted(PlayerColor playerID)
  335. {
  336. backgroundDimLevel = settings["adventure"]["backgroundDimLevel"].Integer();
  337. onCurrentPlayerChanged(playerID);
  338. setState(EAdventureState::MAKING_TURN);
  339. if(playerID == GAME->interface()->playerID || settings["session"]["spectate"].Bool())
  340. {
  341. widget->getMinimap()->setAIRadar(false);
  342. widget->getInfoBar()->showSelection();
  343. }
  344. widget->getHeroList()->updateWidget();
  345. widget->getTownList()->updateWidget();
  346. const CGHeroInstance * heroToSelect = nullptr;
  347. // find first non-sleeping hero
  348. for (auto hero : GAME->interface()->localState->getWanderingHeroes())
  349. {
  350. if (!GAME->interface()->localState->isHeroSleeping(hero))
  351. {
  352. heroToSelect = hero;
  353. break;
  354. }
  355. }
  356. //select first hero if available.
  357. if (heroToSelect != nullptr)
  358. {
  359. GAME->interface()->localState->setSelection(heroToSelect);
  360. }
  361. else if (GAME->interface()->localState->getOwnedTowns().size())
  362. {
  363. GAME->interface()->localState->setSelection(GAME->interface()->localState->getOwnedTown(0));
  364. }
  365. else
  366. {
  367. GAME->interface()->localState->setSelection(GAME->interface()->localState->getWanderingHero(0));
  368. }
  369. onSelectionChanged(GAME->interface()->localState->getCurrentArmy());
  370. //show new day animation and sound on infobar, except for 1st day of the game
  371. if (GAME->interface()->cb->getDate(Date::DAY) != 1)
  372. widget->getInfoBar()->showDate();
  373. onHeroChanged(nullptr);
  374. ENGINE->windows().totalRedraw();
  375. mapAudio->onPlayerTurnStarted();
  376. if(settings["session"]["autoSkip"].Bool() && !ENGINE->isKeyboardShiftDown())
  377. {
  378. if(auto iw = ENGINE->windows().topWindow<CInfoWindow>())
  379. iw->close();
  380. ENGINE->dispatchMainThread([this]()
  381. {
  382. hotkeyEndingTurn();
  383. });
  384. }
  385. }
  386. void AdventureMapInterface::hotkeyEndingTurn()
  387. {
  388. if(settings["session"]["spectate"].Bool())
  389. return;
  390. if(!settings["general"]["startTurnAutosave"].Bool())
  391. {
  392. GAME->interface()->performAutosave();
  393. }
  394. GAME->interface()->makingTurn = false;
  395. GAME->interface()->cb->endTurn();
  396. mapAudio->onPlayerTurnEnded();
  397. // Normally, game will receive PlayerStartsTurn call almost instantly with new player ID that will switch UI to waiting mode
  398. // However, when simturns are active it is possible for such call not to come because another player is still acting
  399. // So find first player other than ours that is acting at the moment and update UI as if he had started turn
  400. for (auto player = PlayerColor(0); player < PlayerColor::PLAYER_LIMIT; ++player)
  401. {
  402. if (player != GAME->interface()->playerID && GAME->interface()->cb->isPlayerMakingTurn(player))
  403. {
  404. onEnemyTurnStarted(player, GAME->interface()->cb->getStartInfo()->playerInfos.at(player).isControlledByHuman());
  405. break;
  406. }
  407. }
  408. }
  409. const CGObjectInstance* AdventureMapInterface::getActiveObject(const int3 &mapPos)
  410. {
  411. std::vector < const CGObjectInstance * > bobjs = GAME->interface()->cb->getBlockingObjs(mapPos); //blocking objects at tile
  412. if (bobjs.empty())
  413. return nullptr;
  414. return *boost::range::max_element(bobjs, &CMapHandler::compareObjectBlitOrder);
  415. }
  416. void AdventureMapInterface::onTileLeftClicked(const int3 &targetPosition)
  417. {
  418. if(!shortcuts->optionMapViewActive())
  419. return;
  420. const CGObjectInstance *topBlocking = GAME->interface()->cb->isVisible(targetPosition) ? getActiveObject(targetPosition) : nullptr;
  421. if(spellBeingCasted)
  422. {
  423. assert(shortcuts->optionSpellcasting());
  424. if(isValidAdventureSpellTarget(targetPosition))
  425. performSpellcasting(targetPosition);
  426. return;
  427. }
  428. if(!GAME->interface()->cb->isVisible(targetPosition))
  429. return;
  430. //check if we can select this object
  431. bool canSelect = topBlocking && topBlocking->ID == Obj::HERO && topBlocking->tempOwner == GAME->interface()->playerID;
  432. canSelect |= topBlocking && topBlocking->ID == Obj::TOWN && GAME->interface()->cb->getPlayerRelations(GAME->interface()->playerID, topBlocking->tempOwner) != PlayerRelations::ENEMIES;
  433. if(GAME->interface()->localState->getCurrentArmy()->ID != Obj::HERO) //hero is not selected (presumably town)
  434. {
  435. if(GAME->interface()->localState->getCurrentArmy() == topBlocking) //selected town clicked
  436. GAME->interface()->openTownWindow(static_cast<const CGTownInstance*>(topBlocking));
  437. else if(canSelect)
  438. GAME->interface()->localState->setSelection(static_cast<const CArmedInstance*>(topBlocking));
  439. }
  440. else if(const CGHeroInstance * currentHero = GAME->interface()->localState->getCurrentHero()) //hero is selected
  441. {
  442. const CGPathNode *pn = GAME->interface()->getPathsInfo(currentHero)->getPathInfo(targetPosition);
  443. const auto shipyard = dynamic_cast<const IShipyard *>(topBlocking);
  444. if(currentHero == topBlocking) //clicked selected hero
  445. {
  446. GAME->interface()->openHeroWindow(currentHero);
  447. return;
  448. }
  449. else if(canSelect && pn->turns == 255 ) //selectable object at inaccessible tile
  450. {
  451. GAME->interface()->localState->setSelection(static_cast<const CArmedInstance*>(topBlocking));
  452. return;
  453. }
  454. else if(shipyard != nullptr && pn->turns == 255 && GAME->interface()->cb->getPlayerRelations(GAME->interface()->playerID, topBlocking->tempOwner) != PlayerRelations::ENEMIES)
  455. {
  456. GAME->interface()->showShipyardDialogOrProblemPopup(shipyard);
  457. }
  458. else //still here? we need to move hero if we clicked end of already selected path or calculate a new path otherwise
  459. {
  460. int3 destinationTile = targetPosition;
  461. if(topBlocking && topBlocking->isVisitable() && !topBlocking->visitableAt(destinationTile) && settings["gameTweaks"]["simpleObjectSelection"].Bool())
  462. destinationTile = topBlocking->visitablePos();
  463. if(!settings["adventure"]["showMovePath"].Bool())
  464. {
  465. GAME->interface()->localState->setPath(currentHero, destinationTile);
  466. onHeroChanged(currentHero);
  467. }
  468. if(GAME->interface()->localState->hasPath(currentHero) &&
  469. GAME->interface()->localState->getPath(currentHero).endPos() == destinationTile &&
  470. !ENGINE->isKeyboardShiftDown())//we'll be moving
  471. {
  472. assert(!GAME->map().hasOngoingAnimations());
  473. if(!GAME->map().hasOngoingAnimations() && GAME->interface()->localState->getPath(currentHero).nextNode().turns == 0)
  474. GAME->interface()->moveHero(currentHero, GAME->interface()->localState->getPath(currentHero));
  475. return;
  476. }
  477. else
  478. {
  479. if(ENGINE->isKeyboardShiftDown()) //normal click behaviour (as no hero selected)
  480. {
  481. if(canSelect)
  482. GAME->interface()->localState->setSelection(static_cast<const CArmedInstance*>(topBlocking));
  483. }
  484. else //remove old path and find a new one if we clicked on accessible tile
  485. {
  486. GAME->interface()->localState->setPath(currentHero, destinationTile);
  487. onHeroChanged(currentHero);
  488. }
  489. }
  490. }
  491. } //end of hero is selected "case"
  492. else
  493. {
  494. throw std::runtime_error("Nothing is selected...");
  495. }
  496. }
  497. void AdventureMapInterface::onTileHovered(const int3 &targetPosition)
  498. {
  499. if(!shortcuts->optionMapViewActive())
  500. return;
  501. //may occur just at the start of game (fake move before full initialization)
  502. if(!GAME->interface()->localState->getCurrentArmy())
  503. return;
  504. bool isTargetPositionVisible = GAME->interface()->cb->isVisible(targetPosition);
  505. const CGObjectInstance *objAtTile = isTargetPositionVisible ? getActiveObject(targetPosition) : nullptr;
  506. if(spellBeingCasted)
  507. {
  508. const auto * hero = GAME->interface()->localState->getCurrentHero();
  509. const auto * spellEffect = spellBeingCasted->getAdventureMechanics().getEffectAs<AdventureSpellRangedEffect>(hero);
  510. spells::detail::ProblemImpl problem;
  511. if(spellEffect && spellEffect->canBeCastAtImpl(problem, GAME->interface()->cb.get(), hero, targetPosition))
  512. ENGINE->cursor().set(spellEffect->getCursorForTarget(GAME->interface()->cb.get(), hero, targetPosition));
  513. else
  514. ENGINE->cursor().set(Cursor::Map::POINTER);
  515. return;
  516. }
  517. if(!isTargetPositionVisible)
  518. {
  519. ENGINE->cursor().set(Cursor::Map::POINTER);
  520. return;
  521. }
  522. auto objRelations = PlayerRelations::ALLIES;
  523. if(objAtTile)
  524. {
  525. objRelations = GAME->interface()->cb->getPlayerRelations(GAME->interface()->playerID, objAtTile->tempOwner);
  526. std::string text = GAME->interface()->localState->getCurrentHero() ? objAtTile->getHoverText(GAME->interface()->localState->getCurrentHero()) : objAtTile->getHoverText(GAME->interface()->playerID);
  527. boost::replace_all(text,"\n"," ");
  528. if (ENGINE->isKeyboardCmdDown())
  529. text.append(" (" + std::to_string(targetPosition.x) + ", " + std::to_string(targetPosition.y) + ")");
  530. ENGINE->statusbar()->write(text);
  531. }
  532. else if(isTargetPositionVisible)
  533. {
  534. std::string tileTooltipText = GAME->map().getTerrainDescr(targetPosition, false);
  535. if (ENGINE->isKeyboardCmdDown())
  536. tileTooltipText.append(" (" + std::to_string(targetPosition.x) + ", " + std::to_string(targetPosition.y) + ")");
  537. ENGINE->statusbar()->write(tileTooltipText);
  538. }
  539. if(GAME->interface()->localState->getCurrentArmy()->ID == Obj::TOWN || ENGINE->isKeyboardShiftDown())
  540. {
  541. if(objAtTile)
  542. {
  543. if(objAtTile->ID == Obj::TOWN && objRelations != PlayerRelations::ENEMIES)
  544. ENGINE->cursor().set(Cursor::Map::TOWN);
  545. else if(objAtTile->ID == Obj::HERO && objRelations == PlayerRelations::SAME_PLAYER)
  546. ENGINE->cursor().set(Cursor::Map::HERO);
  547. else
  548. ENGINE->cursor().set(Cursor::Map::POINTER);
  549. }
  550. else
  551. ENGINE->cursor().set(Cursor::Map::POINTER);
  552. }
  553. else if(const CGHeroInstance * hero = GAME->interface()->localState->getCurrentHero())
  554. {
  555. std::array<Cursor::Map, 4> cursorMove = { Cursor::Map::T1_MOVE, Cursor::Map::T2_MOVE, Cursor::Map::T3_MOVE, Cursor::Map::T4_MOVE, };
  556. std::array<Cursor::Map, 4> cursorAttack = { Cursor::Map::T1_ATTACK, Cursor::Map::T2_ATTACK, Cursor::Map::T3_ATTACK, Cursor::Map::T4_ATTACK, };
  557. std::array<Cursor::Map, 4> cursorSail = { Cursor::Map::T1_SAIL, Cursor::Map::T2_SAIL, Cursor::Map::T3_SAIL, Cursor::Map::T4_SAIL, };
  558. std::array<Cursor::Map, 4> cursorDisembark = { Cursor::Map::T1_DISEMBARK, Cursor::Map::T2_DISEMBARK, Cursor::Map::T3_DISEMBARK, Cursor::Map::T4_DISEMBARK, };
  559. std::array<Cursor::Map, 4> cursorExchange = { Cursor::Map::T1_EXCHANGE, Cursor::Map::T2_EXCHANGE, Cursor::Map::T3_EXCHANGE, Cursor::Map::T4_EXCHANGE, };
  560. std::array<Cursor::Map, 4> cursorVisit = { Cursor::Map::T1_VISIT, Cursor::Map::T2_VISIT, Cursor::Map::T3_VISIT, Cursor::Map::T4_VISIT, };
  561. std::array<Cursor::Map, 4> cursorSailVisit = { Cursor::Map::T1_SAIL_VISIT, Cursor::Map::T2_SAIL_VISIT, Cursor::Map::T3_SAIL_VISIT, Cursor::Map::T4_SAIL_VISIT, };
  562. const CGPathNode * pathNode = GAME->interface()->getPathsInfo(hero)->getPathInfo(targetPosition);
  563. assert(pathNode);
  564. if((ENGINE->isKeyboardAltDown() || settings["gameTweaks"]["forceMovementInfo"].Bool()) && pathNode->reachable()) //overwrite status bar text with movement info
  565. {
  566. showMoveDetailsInStatusbar(*hero, *pathNode);
  567. }
  568. if (objAtTile && pathNode->action == EPathNodeAction::UNKNOWN)
  569. {
  570. if(objAtTile->ID == Obj::TOWN && objRelations != PlayerRelations::ENEMIES)
  571. {
  572. ENGINE-> cursor().set(Cursor::Map::TOWN);
  573. return;
  574. }
  575. else if(objAtTile->ID == Obj::HERO && objRelations == PlayerRelations::SAME_PLAYER)
  576. {
  577. ENGINE-> cursor().set(Cursor::Map::HERO);
  578. return;
  579. }
  580. else if (objAtTile->ID == Obj::SHIPYARD && objRelations != PlayerRelations::ENEMIES)
  581. {
  582. ENGINE-> cursor().set(Cursor::Map::T1_SAIL);
  583. return;
  584. }
  585. if(objAtTile->isVisitable() && !objAtTile->visitableAt(targetPosition) && settings["gameTweaks"]["simpleObjectSelection"].Bool())
  586. pathNode = GAME->interface()->getPathsInfo(hero)->getPathInfo(objAtTile->visitablePos());
  587. }
  588. int turns = pathNode->turns;
  589. vstd::amin(turns, 3);
  590. switch(pathNode->action)
  591. {
  592. case EPathNodeAction::NORMAL:
  593. case EPathNodeAction::TELEPORT_NORMAL:
  594. if(pathNode->layer == EPathfindingLayer::LAND)
  595. ENGINE->cursor().set(cursorMove[turns]);
  596. else
  597. ENGINE->cursor().set(cursorSail[turns]);
  598. break;
  599. case EPathNodeAction::VISIT:
  600. case EPathNodeAction::BLOCKING_VISIT:
  601. case EPathNodeAction::TELEPORT_BLOCKING_VISIT:
  602. if(objAtTile && objAtTile->ID == Obj::HERO)
  603. {
  604. if(GAME->interface()->localState->getCurrentArmy() == objAtTile)
  605. ENGINE->cursor().set(Cursor::Map::HERO);
  606. else
  607. ENGINE->cursor().set(cursorExchange[turns]);
  608. }
  609. else if(pathNode->layer == EPathfindingLayer::LAND)
  610. ENGINE->cursor().set(cursorVisit[turns]);
  611. else if (pathNode->layer == EPathfindingLayer::SAIL &&
  612. objAtTile &&
  613. objAtTile->isCoastVisitable() &&
  614. pathNode->theNodeBefore &&
  615. pathNode->theNodeBefore->layer == EPathfindingLayer::LAND )
  616. {
  617. // exception - when visiting shipwreck located on coast from land - show 'horse' cursor, not 'ship' cursor
  618. ENGINE->cursor().set(cursorVisit[turns]);
  619. }
  620. else
  621. ENGINE->cursor().set(cursorSailVisit[turns]);
  622. break;
  623. case EPathNodeAction::BATTLE:
  624. case EPathNodeAction::TELEPORT_BATTLE:
  625. ENGINE->cursor().set(cursorAttack[turns]);
  626. break;
  627. case EPathNodeAction::EMBARK:
  628. ENGINE->cursor().set(cursorSail[turns]);
  629. break;
  630. case EPathNodeAction::DISEMBARK:
  631. ENGINE->cursor().set(cursorDisembark[turns]);
  632. break;
  633. default:
  634. ENGINE->cursor().set(Cursor::Map::POINTER);
  635. break;
  636. }
  637. }
  638. }
  639. void AdventureMapInterface::showMoveDetailsInStatusbar(const CGHeroInstance & hero, const CGPathNode & pathNode)
  640. {
  641. const int maxMovementPointsAtStartOfLastTurn = pathNode.turns > 0 ? hero.movementPointsLimit(pathNode.layer == EPathfindingLayer::LAND) : hero.movementPointsRemaining();
  642. const int movementPointsLastTurnCost = maxMovementPointsAtStartOfLastTurn - pathNode.moveRemains;
  643. const int remainingPointsAfterMove = pathNode.moveRemains;
  644. int totalMovementCost = hero.movementPointsRemaining();
  645. for (int i = 1; i <= pathNode.turns; ++i)
  646. {
  647. auto turnInfo = hero.getTurnInfo(i);
  648. if (pathNode.layer == EPathfindingLayer::SAIL)
  649. totalMovementCost += turnInfo->getMovePointsLimitWater();
  650. else
  651. totalMovementCost += turnInfo->getMovePointsLimitLand();
  652. }
  653. totalMovementCost -= pathNode.moveRemains;
  654. std::string result = LIBRARY->generaltexth->translate("vcmi.adventureMap", pathNode.turns > 0 ? "moveCostDetails" : "moveCostDetailsNoTurns");
  655. boost::replace_first(result, "%TURNS", std::to_string(pathNode.turns));
  656. boost::replace_first(result, "%POINTS", std::to_string(movementPointsLastTurnCost));
  657. boost::replace_first(result, "%REMAINING", std::to_string(remainingPointsAfterMove));
  658. boost::replace_first(result, "%TOTAL", std::to_string(totalMovementCost));
  659. ENGINE->statusbar()->write(result);
  660. }
  661. void AdventureMapInterface::onTileRightClicked(const int3 &mapPos)
  662. {
  663. if(!shortcuts->optionMapViewActive())
  664. return;
  665. if(spellBeingCasted)
  666. {
  667. hotkeyAbortCastingMode();
  668. return;
  669. }
  670. if(!GAME->interface()->cb->isVisible(mapPos))
  671. {
  672. CRClickPopup::createAndPush(LIBRARY->generaltexth->allTexts[61]); //Uncharted Territory
  673. return;
  674. }
  675. const CGObjectInstance * obj = getActiveObject(mapPos);
  676. if(!obj)
  677. {
  678. // Bare or undiscovered terrain
  679. const TerrainTile * tile = GAME->interface()->cb->getTile(mapPos);
  680. if(tile)
  681. {
  682. std::string hlp = GAME->map().getTerrainDescr(mapPos, true);
  683. CRClickPopup::createAndPush(hlp);
  684. }
  685. return;
  686. }
  687. CRClickPopup::createAndPush(obj, ENGINE->getCursorPosition(), ETextAlignment::CENTER);
  688. }
  689. void AdventureMapInterface::enterCastingMode(const CSpell * sp)
  690. {
  691. spellBeingCasted = sp;
  692. GAME->interface()->localState->setCurrentSpell(sp->id);
  693. setState(EAdventureState::CASTING_SPELL);
  694. }
  695. void AdventureMapInterface::exitCastingMode()
  696. {
  697. assert(spellBeingCasted);
  698. spellBeingCasted = nullptr;
  699. setState(EAdventureState::MAKING_TURN);
  700. GAME->interface()->localState->setCurrentSpell(SpellID::NONE);
  701. }
  702. void AdventureMapInterface::hotkeyAbortCastingMode()
  703. {
  704. exitCastingMode();
  705. GAME->interface()->showInfoDialog(LIBRARY->generaltexth->allTexts[731]); //Spell cancelled
  706. }
  707. void AdventureMapInterface::performSpellcasting(const int3 & dest)
  708. {
  709. SpellID id = spellBeingCasted->id;
  710. exitCastingMode();
  711. GAME->interface()->cb->castSpell(GAME->interface()->localState->getCurrentHero(), id, dest);
  712. }
  713. Rect AdventureMapInterface::terrainAreaPixels() const
  714. {
  715. return widget->getMapView()->pos;
  716. }
  717. void AdventureMapInterface::hotkeyExitWorldView()
  718. {
  719. setState(EAdventureState::MAKING_TURN);
  720. widget->getMapView()->onViewMapActivated();
  721. }
  722. void AdventureMapInterface::openWorldView(int tileSize)
  723. {
  724. setState(EAdventureState::WORLD_VIEW);
  725. widget->getMapView()->onViewWorldActivated(tileSize);
  726. }
  727. void AdventureMapInterface::openWorldView()
  728. {
  729. openWorldView(11);
  730. }
  731. void AdventureMapInterface::openWorldView(const std::vector<ObjectPosInfo>& objectPositions, bool showTerrain)
  732. {
  733. openWorldView(11);
  734. widget->getMapView()->onViewSpellActivated(11, objectPositions, showTerrain);
  735. }
  736. void AdventureMapInterface::hotkeyNextTown()
  737. {
  738. widget->getTownList()->selectNext();
  739. }
  740. void AdventureMapInterface::hotkeySwitchMapLevel()
  741. {
  742. widget->getMapView()->onMapLevelSwitched();
  743. }
  744. void AdventureMapInterface::hotkeyZoom(int delta, bool useDeadZone)
  745. {
  746. widget->getMapView()->onMapZoomLevelChanged(delta, useDeadZone);
  747. }
  748. void AdventureMapInterface::onScreenResize()
  749. {
  750. OBJECT_CONSTRUCTION;
  751. // remember our activation state and reactive after reconstruction
  752. // since othervice activate() calls for created elements will bypass virtual dispatch
  753. // and will call directly CIntObject::activate() instead of dispatching virtual function call
  754. bool widgetActive = isActive();
  755. if (widgetActive)
  756. deactivate();
  757. widget.reset();
  758. pos.x = pos.y = 0;
  759. pos.w = ENGINE->screenDimensions().x;
  760. pos.h = ENGINE->screenDimensions().y;
  761. widget = std::make_shared<AdventureMapWidget>(shortcuts);
  762. widget->getMapView()->onViewMapActivated();
  763. widget->setPlayerColor(currentPlayerID);
  764. widget->updateActiveState();
  765. widget->getMinimap()->update();
  766. widget->getInfoBar()->showSelection();
  767. if (GAME->interface() && GAME->interface()->localState->getCurrentArmy())
  768. widget->getMapView()->onCenteredObject(GAME->interface()->localState->getCurrentArmy());
  769. adjustActiveness();
  770. if (widgetActive)
  771. activate();
  772. }
  773. bool AdventureMapInterface::isValidAdventureSpellTarget(int3 targetPosition) const
  774. {
  775. spells::detail::ProblemImpl problem;
  776. return spellBeingCasted->getAdventureMechanics().canBeCastAt(problem, GAME->interface()->cb.get(), GAME->interface()->localState->getCurrentHero(), targetPosition);
  777. }