AdventureMapInterface.cpp 28 KB

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