AdventureMapInterface.cpp 30 KB

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