AdventureMapInterface.cpp 29 KB

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