MapViewController.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. /*
  2. * MapViewController.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 "MapViewController.h"
  12. #include "MapRendererContext.h"
  13. #include "MapRendererContextState.h"
  14. #include "MapViewCache.h"
  15. #include "MapViewModel.h"
  16. #include "../CPlayerInterface.h"
  17. #include "../adventureMap/AdventureMapInterface.h"
  18. #include "../gui/CGuiHandler.h"
  19. #include "../gui/WindowHandler.h"
  20. #include "../eventsSDL/InputHandler.h"
  21. #include "../../lib/CConfigHandler.h"
  22. #include "../../lib/mapObjects/CGHeroInstance.h"
  23. #include "../../lib/mapObjects/MiscObjects.h"
  24. #include "../../lib/pathfinder/CGPathNode.h"
  25. #include "../../lib/spells/ViewSpellInt.h"
  26. void MapViewController::setViewCenter(const int3 & position)
  27. {
  28. setViewCenter(Point(position) * model->getSingleTileSize() + model->getSingleTileSize() / 2, position.z);
  29. }
  30. void MapViewController::setViewCenter(const Point & position, int level)
  31. {
  32. Point upperLimit = Point(context->getMapSize()) * model->getSingleTileSize();
  33. Point lowerLimit = Point(0, 0);
  34. if(worldViewContext)
  35. {
  36. Point area = model->getPixelsVisibleDimensions();
  37. Point mapCenter = upperLimit / 2;
  38. Point desiredLowerLimit = lowerLimit + area / 2;
  39. Point desiredUpperLimit = upperLimit - area / 2;
  40. Point actualLowerLimit{
  41. std::min(desiredLowerLimit.x, mapCenter.x),
  42. std::min(desiredLowerLimit.y, mapCenter.y)
  43. };
  44. Point actualUpperLimit{
  45. std::max(desiredUpperLimit.x, mapCenter.x),
  46. std::max(desiredUpperLimit.y, mapCenter.y)
  47. };
  48. upperLimit = actualUpperLimit;
  49. lowerLimit = actualLowerLimit;
  50. }
  51. Point betterPosition = {std::clamp(position.x, lowerLimit.x, upperLimit.x), std::clamp(position.y, lowerLimit.y, upperLimit.y)};
  52. model->setViewCenter(betterPosition);
  53. model->setLevel(std::clamp(level, 0, context->getMapSize().z));
  54. if(adventureInt && !puzzleMapContext) // may be called before adventureInt is initialized
  55. adventureInt->onMapViewMoved(model->getTilesTotalRect(), model->getLevel());
  56. }
  57. void MapViewController::setTileSize(const Point & tileSize)
  58. {
  59. Point oldSize = model->getSingleTileSize();
  60. model->setTileSize(tileSize);
  61. double scaleChangeX = 1.0 * tileSize.x / oldSize.x;
  62. double scaleChangeY = 1.0 * tileSize.y / oldSize.y;
  63. Point newViewCenter {
  64. static_cast<int>(std::round(model->getMapViewCenter().x * scaleChangeX)),
  65. static_cast<int>(std::round(model->getMapViewCenter().y * scaleChangeY))
  66. };
  67. // force update of view center since changing tile size may invalidated it
  68. setViewCenter(newViewCenter, model->getLevel());
  69. }
  70. void MapViewController::modifyTileSize(int stepsChange)
  71. {
  72. // we want to zoom in/out in fixed 10% steps, to allow player to return back to exactly 100% zoom just by scrolling
  73. // so, zooming in for 5 steps will put game at 1.1^5 = 1.61 scale
  74. // try to determine current zooming level and change it by requested number of steps
  75. double currentZoomFactor = targetTileSize.x / static_cast<double>(defaultTileSize);
  76. double currentZoomSteps = std::round(std::log(currentZoomFactor) / std::log(1.01));
  77. double newZoomSteps = stepsChange != 0 ? currentZoomSteps + stepsChange : stepsChange;
  78. double newZoomFactor = std::pow(1.01, newZoomSteps);
  79. Point currentZoom = targetTileSize;
  80. Point desiredZoom = Point(defaultTileSize,defaultTileSize) * newZoomFactor;
  81. if (desiredZoom == currentZoom && stepsChange < 0)
  82. desiredZoom -= Point(1,1);
  83. if (desiredZoom == currentZoom && stepsChange > 0)
  84. desiredZoom += Point(1,1);
  85. Point minimal = model->getSingleTileSizeLowerLimit();
  86. Point maximal = model->getSingleTileSizeUpperLimit();
  87. Point actualZoom = {
  88. std::clamp(desiredZoom.x, minimal.x, maximal.x),
  89. std::clamp(desiredZoom.y, minimal.y, maximal.y)
  90. };
  91. if (actualZoom != currentZoom)
  92. {
  93. targetTileSize = actualZoom;
  94. if(actualZoom.x >= defaultTileSize - zoomTileDeadArea && actualZoom.x <= defaultTileSize + zoomTileDeadArea)
  95. actualZoom.x = defaultTileSize;
  96. if(actualZoom.y >= defaultTileSize - zoomTileDeadArea && actualZoom.y <= defaultTileSize + zoomTileDeadArea)
  97. actualZoom.y = defaultTileSize;
  98. bool isInDeadZone = targetTileSize != actualZoom || actualZoom == Point(defaultTileSize, defaultTileSize);
  99. if(!wasInDeadZone && isInDeadZone)
  100. GH.input().hapticFeedback();
  101. wasInDeadZone = isInDeadZone;
  102. setTileSize(actualZoom);
  103. }
  104. }
  105. MapViewController::MapViewController(std::shared_ptr<MapViewModel> model, std::shared_ptr<MapViewCache> view)
  106. : state(new MapRendererContextState())
  107. , model(std::move(model))
  108. , view(view)
  109. {
  110. adventureContext = std::make_shared<MapRendererAdventureContext>(*state);
  111. context = adventureContext;
  112. }
  113. std::shared_ptr<IMapRendererContext> MapViewController::getContext() const
  114. {
  115. return context;
  116. }
  117. void MapViewController::tick(uint32_t timeDelta)
  118. {
  119. // confirmed to match H3 for
  120. // - hero embarking on boat (500 ms)
  121. // - hero disembarking from boat (500 ms)
  122. // - TODO: picking up resources
  123. // - TODO: killing mosters
  124. // - teleporting ( 250 ms)
  125. static const double fadeOutDuration = 500;
  126. static const double fadeInDuration = 500;
  127. static const double heroTeleportDuration = 250;
  128. if(movementContext)
  129. {
  130. const auto * object = context->getObject(movementContext->target);
  131. const auto * hero = dynamic_cast<const CGHeroInstance *>(object);
  132. const auto * boat = dynamic_cast<const CGBoat *>(object);
  133. assert(boat || hero);
  134. if(!hero)
  135. hero = boat->hero;
  136. double heroMoveTime = LOCPLINT->playerID == hero->getOwner() ?
  137. settings["adventure"]["heroMoveTime"].Float() :
  138. settings["adventure"]["enemyMoveTime"].Float();
  139. movementContext->progress += timeDelta / heroMoveTime;
  140. movementContext->progress = std::min( 1.0, movementContext->progress);
  141. Point positionFrom = Point(hero->convertToVisitablePos(movementContext->tileFrom)) * model->getSingleTileSize() + model->getSingleTileSize() / 2;
  142. Point positionDest = Point(hero->convertToVisitablePos(movementContext->tileDest)) * model->getSingleTileSize() + model->getSingleTileSize() / 2;
  143. Point positionCurr = vstd::lerp(positionFrom, positionDest, movementContext->progress);
  144. setViewCenter(positionCurr, movementContext->tileDest.z);
  145. }
  146. if(teleportContext)
  147. {
  148. teleportContext->progress += timeDelta / heroTeleportDuration;
  149. teleportContext->progress = std::min( 1.0, teleportContext->progress);
  150. }
  151. if(fadingOutContext)
  152. {
  153. fadingOutContext->progress -= timeDelta / fadeOutDuration;
  154. fadingOutContext->progress = std::max( 0.0, fadingOutContext->progress);
  155. }
  156. if(fadingInContext)
  157. {
  158. fadingInContext->progress += timeDelta / fadeInDuration;
  159. fadingInContext->progress = std::min( 1.0, fadingInContext->progress);
  160. }
  161. if (adventureContext)
  162. adventureContext->animationTime += timeDelta;
  163. updateState();
  164. }
  165. void MapViewController::updateState()
  166. {
  167. if(adventureContext)
  168. {
  169. adventureContext->settingsSessionSpectate = settings["session"]["spectate"].Bool();
  170. adventureContext->settingsAdventureObjectAnimation = settings["adventure"]["objectAnimation"].Bool();
  171. adventureContext->settingsAdventureTerrainAnimation = settings["adventure"]["terrainAnimation"].Bool();
  172. adventureContext->settingShowGrid = settings["gameTweaks"]["showGrid"].Bool();
  173. adventureContext->settingShowVisitable = settings["session"]["showVisitable"].Bool();
  174. adventureContext->settingShowBlocked = settings["session"]["showBlocked"].Bool();
  175. adventureContext->settingSpellRange = settings["session"]["showSpellRange"].Bool();
  176. }
  177. }
  178. void MapViewController::afterRender()
  179. {
  180. if(movementContext)
  181. {
  182. const auto * object = context->getObject(movementContext->target);
  183. const auto * hero = dynamic_cast<const CGHeroInstance *>(object);
  184. const auto * boat = dynamic_cast<const CGBoat *>(object);
  185. assert(boat || hero);
  186. if(!hero)
  187. hero = boat->hero;
  188. if(movementContext->progress >= 0.999)
  189. {
  190. logGlobal->debug("Ending movement animation");
  191. setViewCenter(hero->getSightCenter());
  192. removeObject(context->getObject(movementContext->target));
  193. addObject(context->getObject(movementContext->target));
  194. activateAdventureContext(movementContext->animationTime);
  195. }
  196. }
  197. if(teleportContext && teleportContext->progress >= 0.999)
  198. {
  199. logGlobal->debug("Ending teleport animation");
  200. activateAdventureContext(teleportContext->animationTime);
  201. }
  202. if(fadingOutContext && fadingOutContext->progress <= 0.001)
  203. {
  204. logGlobal->debug("Ending fade out animation");
  205. removeObject(context->getObject(fadingOutContext->target));
  206. activateAdventureContext(fadingOutContext->animationTime);
  207. }
  208. if(fadingInContext && fadingInContext->progress >= 0.999)
  209. {
  210. logGlobal->debug("Ending fade in animation");
  211. activateAdventureContext(fadingInContext->animationTime);
  212. }
  213. }
  214. bool MapViewController::isEventInstant(const CGObjectInstance * obj, const PlayerColor & initiator)
  215. {
  216. if (!isEventVisible(obj, initiator))
  217. return true;
  218. if(initiator != LOCPLINT->playerID && settings["adventure"]["enemyMoveTime"].Float() <= 0)
  219. return true; // instant movement speed
  220. if(initiator == LOCPLINT->playerID && settings["adventure"]["heroMoveTime"].Float() <= 0)
  221. return true; // instant movement speed
  222. return false;
  223. }
  224. bool MapViewController::isEventVisible(const CGObjectInstance * obj, const PlayerColor & initiator)
  225. {
  226. if(adventureContext == nullptr)
  227. return false;
  228. if(initiator != LOCPLINT->playerID && settings["adventure"]["enemyMoveTime"].Float() < 0)
  229. return false; // enemy move speed set to "hidden/none"
  230. if(!GH.windows().isTopWindow(adventureInt))
  231. return false;
  232. // do not focus on actions of other players during our turn (e.g. simturns)
  233. if (LOCPLINT->makingTurn && initiator != LOCPLINT->playerID)
  234. return false;
  235. if(obj->isVisitable())
  236. return context->isVisible(obj->visitablePos());
  237. else
  238. return context->isVisible(obj->pos);
  239. }
  240. bool MapViewController::isEventVisible(const CGHeroInstance * obj, const int3 & from, const int3 & dest)
  241. {
  242. if(adventureContext == nullptr)
  243. return false;
  244. if(obj->getOwner() != LOCPLINT->playerID && settings["adventure"]["enemyMoveTime"].Float() < 0)
  245. return false; // enemy move speed set to "hidden/none"
  246. if(!GH.windows().isTopWindow(adventureInt))
  247. return false;
  248. // do not focus on actions of other players during our turn (e.g. simturns)
  249. if (LOCPLINT->makingTurn && obj->getOwner() != LOCPLINT->playerID)
  250. return false;
  251. if(context->isVisible(obj->convertToVisitablePos(from)))
  252. return true;
  253. if(context->isVisible(obj->convertToVisitablePos(dest)))
  254. return true;
  255. return false;
  256. }
  257. void MapViewController::fadeOutObject(const CGObjectInstance * obj)
  258. {
  259. logGlobal->debug("Starting fade out animation");
  260. fadingOutContext = std::make_shared<MapRendererAdventureFadingContext>(*state);
  261. fadingOutContext->animationTime = adventureContext->animationTime;
  262. adventureContext = fadingOutContext;
  263. context = fadingOutContext;
  264. const CGObjectInstance * movingObject = obj;
  265. if (obj->ID == Obj::HERO)
  266. {
  267. auto * hero = dynamic_cast<const CGHeroInstance*>(obj);
  268. if (hero->boat)
  269. movingObject = hero->boat;
  270. }
  271. fadingOutContext->target = movingObject->id;
  272. fadingOutContext->progress = 1.0;
  273. }
  274. void MapViewController::fadeInObject(const CGObjectInstance * obj)
  275. {
  276. logGlobal->debug("Starting fade in animation");
  277. fadingInContext = std::make_shared<MapRendererAdventureFadingContext>(*state);
  278. fadingInContext->animationTime = adventureContext->animationTime;
  279. adventureContext = fadingInContext;
  280. context = fadingInContext;
  281. const CGObjectInstance * movingObject = obj;
  282. if (obj->ID == Obj::HERO)
  283. {
  284. auto * hero = dynamic_cast<const CGHeroInstance*>(obj);
  285. if (hero->boat)
  286. movingObject = hero->boat;
  287. }
  288. fadingInContext->target = movingObject->id;
  289. fadingInContext->progress = 0.0;
  290. }
  291. void MapViewController::removeObject(const CGObjectInstance * obj)
  292. {
  293. if (obj->ID == Obj::BOAT)
  294. {
  295. auto * boat = dynamic_cast<const CGBoat*>(obj);
  296. if (boat->hero)
  297. {
  298. view->invalidate(context, boat->hero->id);
  299. state->removeObject(boat->hero);
  300. }
  301. }
  302. if (obj->ID == Obj::HERO)
  303. {
  304. auto * hero = dynamic_cast<const CGHeroInstance*>(obj);
  305. if (hero->boat)
  306. {
  307. view->invalidate(context, hero->boat->id);
  308. state->removeObject(hero->boat);
  309. }
  310. }
  311. view->invalidate(context, obj->id);
  312. state->removeObject(obj);
  313. }
  314. void MapViewController::addObject(const CGObjectInstance * obj)
  315. {
  316. state->addObject(obj);
  317. view->invalidate(context, obj->id);
  318. }
  319. void MapViewController::onBeforeHeroEmbark(const CGHeroInstance * obj, const int3 & from, const int3 & dest)
  320. {
  321. if(isEventVisible(obj, from, dest))
  322. {
  323. if (!isEventInstant(obj, obj->getOwner()))
  324. fadeOutObject(obj);
  325. setViewCenter(obj->getSightCenter());
  326. }
  327. else
  328. removeObject(obj);
  329. }
  330. void MapViewController::onAfterHeroEmbark(const CGHeroInstance * obj, const int3 & from, const int3 & dest)
  331. {
  332. if(isEventVisible(obj, from, dest))
  333. setViewCenter(obj->getSightCenter());
  334. }
  335. void MapViewController::onBeforeHeroDisembark(const CGHeroInstance * obj, const int3 & from, const int3 & dest)
  336. {
  337. if(isEventVisible(obj, from, dest))
  338. setViewCenter(obj->getSightCenter());
  339. }
  340. void MapViewController::onAfterHeroDisembark(const CGHeroInstance * obj, const int3 & from, const int3 & dest)
  341. {
  342. if(isEventVisible(obj, from, dest))
  343. {
  344. if (!isEventInstant(obj, obj->getOwner()))
  345. fadeInObject(obj);
  346. setViewCenter(obj->getSightCenter());
  347. }
  348. addObject(obj);
  349. }
  350. void MapViewController::onObjectFadeIn(const CGObjectInstance * obj, const PlayerColor & initiator)
  351. {
  352. assert(!hasOngoingAnimations());
  353. if(isEventVisible(obj, initiator) && !isEventInstant(obj, initiator) )
  354. fadeInObject(obj);
  355. addObject(obj);
  356. }
  357. void MapViewController::onObjectFadeOut(const CGObjectInstance * obj, const PlayerColor & initiator)
  358. {
  359. assert(!hasOngoingAnimations());
  360. if(isEventVisible(obj, initiator) && !isEventInstant(obj, initiator) )
  361. fadeOutObject(obj);
  362. else
  363. removeObject(obj);
  364. }
  365. void MapViewController::onObjectInstantAdd(const CGObjectInstance * obj, const PlayerColor & initiator)
  366. {
  367. addObject(obj);
  368. };
  369. void MapViewController::onObjectInstantRemove(const CGObjectInstance * obj, const PlayerColor & initiator)
  370. {
  371. removeObject(obj);
  372. };
  373. void MapViewController::onBeforeHeroTeleported(const CGHeroInstance * obj, const int3 & from, const int3 & dest)
  374. {
  375. assert(!hasOngoingAnimations());
  376. if(isEventVisible(obj, from, dest))
  377. {
  378. setViewCenter(obj->getSightCenter());
  379. view->createTransitionSnapshot(context);
  380. }
  381. }
  382. void MapViewController::onAfterHeroTeleported(const CGHeroInstance * obj, const int3 & from, const int3 & dest)
  383. {
  384. assert(!hasOngoingAnimations());
  385. const CGObjectInstance * movingObject = obj;
  386. if(obj->boat)
  387. movingObject = obj->boat;
  388. removeObject(movingObject);
  389. addObject(movingObject);
  390. if(isEventVisible(obj, from, dest))
  391. {
  392. logGlobal->debug("Starting teleport animation");
  393. teleportContext = std::make_shared<MapRendererAdventureTransitionContext>(*state);
  394. teleportContext->animationTime = adventureContext->animationTime;
  395. adventureContext = teleportContext;
  396. context = teleportContext;
  397. setViewCenter(movingObject->getSightCenter());
  398. }
  399. }
  400. void MapViewController::onHeroMoved(const CGHeroInstance * obj, const int3 & from, const int3 & dest)
  401. {
  402. assert(!hasOngoingAnimations());
  403. // revisiting via spacebar, no need to animate
  404. if(from == dest)
  405. return;
  406. const CGObjectInstance * movingObject = obj;
  407. if(obj->boat)
  408. movingObject = obj->boat;
  409. removeObject(movingObject);
  410. if(!isEventVisible(obj, from, dest))
  411. {
  412. addObject(movingObject);
  413. return;
  414. }
  415. double movementTime = LOCPLINT->playerID == obj->tempOwner ?
  416. settings["adventure"]["heroMoveTime"].Float() :
  417. settings["adventure"]["enemyMoveTime"].Float();
  418. if(movementTime > 1)
  419. {
  420. logGlobal->debug("Starting movement animation");
  421. movementContext = std::make_shared<MapRendererAdventureMovingContext>(*state);
  422. movementContext->animationTime = adventureContext->animationTime;
  423. adventureContext = movementContext;
  424. context = movementContext;
  425. state->addMovingObject(movingObject, from, dest);
  426. movementContext->target = movingObject->id;
  427. movementContext->tileFrom = from;
  428. movementContext->tileDest = dest;
  429. movementContext->progress = 0.0;
  430. }
  431. else // instant movement
  432. {
  433. addObject(movingObject);
  434. setViewCenter(movingObject->visitablePos());
  435. }
  436. }
  437. bool MapViewController::hasOngoingAnimations()
  438. {
  439. if(movementContext)
  440. return true;
  441. if(fadingOutContext)
  442. return true;
  443. if(fadingInContext)
  444. return true;
  445. if(teleportContext)
  446. return true;
  447. return false;
  448. }
  449. void MapViewController::activateAdventureContext(uint32_t animationTime)
  450. {
  451. resetContext();
  452. adventureContext = std::make_shared<MapRendererAdventureContext>(*state);
  453. adventureContext->animationTime = animationTime;
  454. context = adventureContext;
  455. updateState();
  456. }
  457. void MapViewController::activateAdventureContext()
  458. {
  459. activateAdventureContext(0);
  460. }
  461. void MapViewController::activateWorldViewContext()
  462. {
  463. if(worldViewContext)
  464. return;
  465. resetContext();
  466. worldViewContext = std::make_shared<MapRendererWorldViewContext>(*state);
  467. context = worldViewContext;
  468. }
  469. void MapViewController::activateSpellViewContext()
  470. {
  471. if(spellViewContext)
  472. return;
  473. resetContext();
  474. spellViewContext = std::make_shared<MapRendererSpellViewContext>(*state);
  475. worldViewContext = spellViewContext;
  476. context = spellViewContext;
  477. }
  478. void MapViewController::activatePuzzleMapContext(const int3 & grailPosition)
  479. {
  480. resetContext();
  481. puzzleMapContext = std::make_shared<MapRendererPuzzleMapContext>(*state);
  482. context = puzzleMapContext;
  483. CGPathNode fakeNode;
  484. fakeNode.coord = grailPosition;
  485. puzzleMapContext->grailPos = std::make_unique<CGPath>();
  486. // create two nodes since 1st one is normally not visible
  487. puzzleMapContext->grailPos->nodes.push_back(fakeNode);
  488. puzzleMapContext->grailPos->nodes.push_back(fakeNode);
  489. }
  490. void MapViewController::resetContext()
  491. {
  492. adventureContext.reset();
  493. movementContext.reset();
  494. fadingOutContext.reset();
  495. fadingInContext.reset();
  496. teleportContext.reset();
  497. worldViewContext.reset();
  498. spellViewContext.reset();
  499. puzzleMapContext.reset();
  500. }
  501. void MapViewController::setTerrainVisibility(bool showAllTerrain)
  502. {
  503. assert(spellViewContext);
  504. spellViewContext->showAllTerrain = showAllTerrain;
  505. }
  506. void MapViewController::setOverlayVisibility(const std::vector<ObjectPosInfo> & objectPositions)
  507. {
  508. assert(spellViewContext);
  509. spellViewContext->additionalOverlayIcons = objectPositions;
  510. }