BattleFieldController.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. /*
  2. * BattleFieldController.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 "BattleFieldController.h"
  12. #include "BattleInterface.h"
  13. #include "BattleActionsController.h"
  14. #include "BattleInterfaceClasses.h"
  15. #include "BattleEffectsController.h"
  16. #include "BattleSiegeController.h"
  17. #include "BattleStacksController.h"
  18. #include "BattleObstacleController.h"
  19. #include "BattleProjectileController.h"
  20. #include "BattleRenderer.h"
  21. #include "../CGameInfo.h"
  22. #include "../CPlayerInterface.h"
  23. #include "../render/CAnimation.h"
  24. #include "../render/Canvas.h"
  25. #include "../render/IImage.h"
  26. #include "../renderSDL/SDL_Extensions.h"
  27. #include "../gui/CGuiHandler.h"
  28. #include "../gui/CursorHandler.h"
  29. #include "../adventureMap/CInGameConsole.h"
  30. #include "../../CCallback.h"
  31. #include "../../lib/BattleFieldHandler.h"
  32. #include "../../lib/CConfigHandler.h"
  33. #include "../../lib/CStack.h"
  34. #include "../../lib/spells/ISpellMechanics.h"
  35. BattleFieldController::BattleFieldController(BattleInterface & owner):
  36. owner(owner)
  37. {
  38. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  39. //preparing cells and hexes
  40. cellBorder = IImage::createFromFile("CCELLGRD.BMP", EImageBlitMode::COLORKEY);
  41. cellShade = IImage::createFromFile("CCELLSHD.BMP");
  42. cellUnitMovementHighlight = IImage::createFromFile("UnitMovementHighlight.PNG", EImageBlitMode::COLORKEY);
  43. cellUnitMaxMovementHighlight = IImage::createFromFile("UnitMaxMovementHighlight.PNG", EImageBlitMode::COLORKEY);
  44. attackCursors = std::make_shared<CAnimation>("CRCOMBAT");
  45. attackCursors->preload();
  46. // load single edges
  47. fullDamageRangeLimitImages[0b000001] = IImage::createFromFile("rangeHighlights/green/topLeft.PNG", EImageBlitMode::COLORKEY);
  48. fullDamageRangeLimitImages[0b000010] = IImage::createFromFile("rangeHighlights/green/topRight.PNG", EImageBlitMode::COLORKEY);
  49. fullDamageRangeLimitImages[0b000100] = IImage::createFromFile("rangeHighlights/green/right.PNG", EImageBlitMode::COLORKEY);
  50. fullDamageRangeLimitImages[0b001000] = IImage::createFromFile("rangeHighlights/green/bottomRight.PNG", EImageBlitMode::COLORKEY);
  51. fullDamageRangeLimitImages[0b010000] = IImage::createFromFile("rangeHighlights/green/bottomLeft.PNG", EImageBlitMode::COLORKEY);
  52. fullDamageRangeLimitImages[0b100000] = IImage::createFromFile("rangeHighlights/green/left.PNG", EImageBlitMode::COLORKEY);
  53. // load double edges
  54. fullDamageRangeLimitImages[0b000011] = IImage::createFromFile("rangeHighlights/green/top.PNG", EImageBlitMode::COLORKEY);
  55. fullDamageRangeLimitImages[0b011000] = IImage::createFromFile("rangeHighlights/green/bottom.PNG", EImageBlitMode::COLORKEY);
  56. fullDamageRangeLimitImages[0b000110] = IImage::createFromFile("rangeHighlights/green/topRightHalfCorner.PNG", EImageBlitMode::COLORKEY);
  57. fullDamageRangeLimitImages[0b001100] = IImage::createFromFile("rangeHighlights/green/bottomRightHalfCorner.PNG", EImageBlitMode::COLORKEY);
  58. fullDamageRangeLimitImages[0b110000] = IImage::createFromFile("rangeHighlights/green/bottomLeftHalfCorner.PNG", EImageBlitMode::COLORKEY);
  59. fullDamageRangeLimitImages[0b100001] = IImage::createFromFile("rangeHighlights/green/topLeftHalfCorner.PNG", EImageBlitMode::COLORKEY);
  60. // load halves
  61. fullDamageRangeLimitImages[0b001110] = IImage::createFromFile("rangeHighlights/green/rightHalf.PNG", EImageBlitMode::COLORKEY);
  62. fullDamageRangeLimitImages[0b110001] = IImage::createFromFile("rangeHighlights/green/leftHalf.PNG", EImageBlitMode::COLORKEY);
  63. // load corners
  64. fullDamageRangeLimitImages[0b000111] = IImage::createFromFile("rangeHighlights/green/topRightCorner.PNG", EImageBlitMode::COLORKEY);
  65. fullDamageRangeLimitImages[0b011100] = IImage::createFromFile("rangeHighlights/green/bottomRightCorner.PNG", EImageBlitMode::COLORKEY);
  66. fullDamageRangeLimitImages[0b111000] = IImage::createFromFile("rangeHighlights/green/bottomLeftCorner.PNG", EImageBlitMode::COLORKEY);
  67. fullDamageRangeLimitImages[0b100011] = IImage::createFromFile("rangeHighlights/green/topLeftCorner.PNG", EImageBlitMode::COLORKEY);
  68. if(!owner.siegeController)
  69. {
  70. auto bfieldType = owner.curInt->cb->battleGetBattlefieldType();
  71. if(bfieldType == BattleField::NONE)
  72. logGlobal->error("Invalid battlefield returned for current battle");
  73. else
  74. background = IImage::createFromFile(bfieldType.getInfo()->graphics, EImageBlitMode::OPAQUE);
  75. }
  76. else
  77. {
  78. std::string backgroundName = owner.siegeController->getBattleBackgroundName();
  79. background = IImage::createFromFile(backgroundName, EImageBlitMode::OPAQUE);
  80. }
  81. pos.w = background->width();
  82. pos.h = background->height();
  83. backgroundWithHexes = std::make_unique<Canvas>(Point(background->width(), background->height()));
  84. updateAccessibleHexes();
  85. addUsedEvents(LCLICK | RCLICK | MOVE | TIME | GESTURE_PANNING);
  86. }
  87. void BattleFieldController::activate()
  88. {
  89. LOCPLINT->cingconsole->pos = this->pos;
  90. CIntObject::activate();
  91. }
  92. void BattleFieldController::createHeroes()
  93. {
  94. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  95. // create heroes as part of our constructor for correct positioning inside battlefield
  96. if(owner.attackingHeroInstance)
  97. owner.attackingHero = std::make_shared<BattleHero>(owner, owner.attackingHeroInstance, false);
  98. if(owner.defendingHeroInstance)
  99. owner.defendingHero = std::make_shared<BattleHero>(owner, owner.defendingHeroInstance, true);
  100. }
  101. void BattleFieldController::panning(bool on, const Point & initialPosition, const Point & finalPosition)
  102. {
  103. if (!on && pos.isInside(finalPosition))
  104. clickLeft(false, false);
  105. }
  106. void BattleFieldController::gesturePanning(const Point & initialPosition, const Point & currentPosition, const Point & lastUpdateDistance)
  107. {
  108. Point distance = currentPosition - initialPosition;
  109. if (distance.length() < settings["battle"]["swipeAttackDistance"].Float())
  110. hoveredHex = getHexAtPosition(initialPosition);
  111. else
  112. hoveredHex = BattleHex::INVALID;
  113. currentAttackOriginPoint = currentPosition;
  114. if (pos.isInside(initialPosition))
  115. owner.actionsController->onHexHovered(getHoveredHex());
  116. }
  117. void BattleFieldController::mouseMoved(const Point & cursorPosition)
  118. {
  119. hoveredHex = getHexAtPosition(cursorPosition);
  120. currentAttackOriginPoint = cursorPosition;
  121. if (pos.isInside(cursorPosition))
  122. owner.actionsController->onHexHovered(getHoveredHex());
  123. else
  124. owner.actionsController->onHoverEnded();
  125. }
  126. void BattleFieldController::clickLeft(tribool down, bool previousState)
  127. {
  128. if(!down)
  129. {
  130. BattleHex selectedHex = getHoveredHex();
  131. if (selectedHex != BattleHex::INVALID)
  132. owner.actionsController->onHexLeftClicked(selectedHex);
  133. }
  134. }
  135. void BattleFieldController::clickRight(tribool down, bool previousState)
  136. {
  137. if(down)
  138. {
  139. BattleHex selectedHex = getHoveredHex();
  140. if (selectedHex != BattleHex::INVALID)
  141. owner.actionsController->onHexRightClicked(selectedHex);
  142. }
  143. }
  144. void BattleFieldController::renderBattlefield(Canvas & canvas)
  145. {
  146. Canvas clippedCanvas(canvas, pos);
  147. showBackground(clippedCanvas);
  148. BattleRenderer renderer(owner);
  149. renderer.execute(clippedCanvas);
  150. owner.projectilesController->render(clippedCanvas);
  151. }
  152. void BattleFieldController::showBackground(Canvas & canvas)
  153. {
  154. if (owner.stacksController->getActiveStack() != nullptr )
  155. showBackgroundImageWithHexes(canvas);
  156. else
  157. showBackgroundImage(canvas);
  158. showHighlightedHexes(canvas);
  159. }
  160. void BattleFieldController::showBackgroundImage(Canvas & canvas)
  161. {
  162. canvas.draw(background, Point(0, 0));
  163. owner.obstacleController->showAbsoluteObstacles(canvas);
  164. if ( owner.siegeController )
  165. owner.siegeController->showAbsoluteObstacles(canvas);
  166. if (settings["battle"]["cellBorders"].Bool())
  167. {
  168. for (int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  169. {
  170. if ( i % GameConstants::BFIELD_WIDTH == 0)
  171. continue;
  172. if ( i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  173. continue;
  174. canvas.draw(cellBorder, hexPositionLocal(i).topLeft());
  175. }
  176. }
  177. }
  178. void BattleFieldController::showBackgroundImageWithHexes(Canvas & canvas)
  179. {
  180. canvas.draw(*backgroundWithHexes, Point(0, 0));
  181. }
  182. void BattleFieldController::redrawBackgroundWithHexes()
  183. {
  184. const CStack *activeStack = owner.stacksController->getActiveStack();
  185. std::vector<BattleHex> attackableHexes;
  186. if(activeStack)
  187. occupiableHexes = owner.curInt->cb->battleGetAvailableHexes(activeStack, false, true, &attackableHexes);
  188. // prepare background graphic with hexes and shaded hexes
  189. backgroundWithHexes->draw(background, Point(0,0));
  190. owner.obstacleController->showAbsoluteObstacles(*backgroundWithHexes);
  191. if(owner.siegeController)
  192. owner.siegeController->showAbsoluteObstacles(*backgroundWithHexes);
  193. // show shaded hexes for active's stack valid movement and the hexes that it can attack
  194. if(settings["battle"]["stackRange"].Bool())
  195. {
  196. std::vector<BattleHex> hexesToShade = occupiableHexes;
  197. hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
  198. for(BattleHex hex : hexesToShade)
  199. {
  200. showHighlightedHex(*backgroundWithHexes, cellShade, hex, false);
  201. }
  202. }
  203. // draw cell borders
  204. if(settings["battle"]["cellBorders"].Bool())
  205. {
  206. for(int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  207. {
  208. if(i % GameConstants::BFIELD_WIDTH == 0)
  209. continue;
  210. if(i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  211. continue;
  212. backgroundWithHexes->draw(cellBorder, hexPositionLocal(i).topLeft());
  213. }
  214. }
  215. }
  216. void BattleFieldController::showHighlightedHex(Canvas & canvas, std::shared_ptr<IImage> highlight, BattleHex hex, bool darkBorder)
  217. {
  218. Point hexPos = hexPositionLocal(hex).topLeft();
  219. canvas.draw(highlight, hexPos);
  220. if(!darkBorder && settings["battle"]["cellBorders"].Bool())
  221. canvas.draw(cellBorder, hexPos);
  222. }
  223. std::set<BattleHex> BattleFieldController::getHighlightedHexesForActiveStack()
  224. {
  225. std::set<BattleHex> result;
  226. if(!owner.stacksController->getActiveStack())
  227. return result;
  228. if(!settings["battle"]["stackRange"].Bool())
  229. return result;
  230. auto hoveredHex = getHoveredHex();
  231. std::set<BattleHex> set = owner.curInt->cb->battleGetAttackedHexes(owner.stacksController->getActiveStack(), hoveredHex);
  232. for(BattleHex hex : set)
  233. result.insert(hex);
  234. return result;
  235. }
  236. std::set<BattleHex> BattleFieldController::getMovementRangeForHoveredStack()
  237. {
  238. std::set<BattleHex> result;
  239. if (!owner.stacksController->getActiveStack())
  240. return result;
  241. if (!settings["battle"]["movementHighlightOnHover"].Bool() && !GH.isKeyboardShiftDown())
  242. return result;
  243. auto hoveredHex = getHoveredHex();
  244. // add possible movement hexes for stack under mouse
  245. const CStack * const hoveredStack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  246. if(hoveredStack)
  247. {
  248. std::vector<BattleHex> v = owner.curInt->cb->battleGetAvailableHexes(hoveredStack, true, true, nullptr);
  249. for(BattleHex hex : v)
  250. result.insert(hex);
  251. }
  252. return result;
  253. }
  254. std::set<BattleHex> BattleFieldController::getHighlightedHexesForSpellRange()
  255. {
  256. std::set<BattleHex> result;
  257. auto hoveredHex = getHoveredHex();
  258. if(!settings["battle"]["mouseShadow"].Bool())
  259. return result;
  260. const spells::Caster *caster = nullptr;
  261. const CSpell *spell = nullptr;
  262. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  263. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  264. caster = owner.actionsController->getCurrentSpellcaster();
  265. if(caster && spell) //when casting spell
  266. {
  267. // printing shaded hex(es)
  268. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  269. auto shadedHexes = spell->battleMechanics(&event)->rangeInHexes(hoveredHex);
  270. for(BattleHex shadedHex : shadedHexes)
  271. {
  272. if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
  273. result.insert(shadedHex);
  274. }
  275. }
  276. return result;
  277. }
  278. std::set<BattleHex> BattleFieldController::getHighlightedHexesForMovementTarget()
  279. {
  280. const CStack * stack = owner.stacksController->getActiveStack();
  281. auto hoveredHex = getHoveredHex();
  282. if(!stack)
  283. return {};
  284. std::vector<BattleHex> availableHexes = owner.curInt->cb->battleGetAvailableHexes(stack, false, false, nullptr);
  285. auto hoveredStack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  286. if(owner.curInt->cb->battleCanAttack(stack, hoveredStack, hoveredHex))
  287. {
  288. if(isTileAttackable(hoveredHex))
  289. {
  290. BattleHex attackFromHex = fromWhichHexAttack(hoveredHex);
  291. if(stack->doubleWide())
  292. return {attackFromHex, stack->occupiedHex(attackFromHex)};
  293. else
  294. return {attackFromHex};
  295. }
  296. }
  297. if(vstd::contains(availableHexes, hoveredHex))
  298. {
  299. if(stack->doubleWide())
  300. return {hoveredHex, stack->occupiedHex(hoveredHex)};
  301. else
  302. return {hoveredHex};
  303. }
  304. if(stack->doubleWide())
  305. {
  306. for(auto const & hex : availableHexes)
  307. {
  308. if(stack->occupiedHex(hex) == hoveredHex)
  309. return {hoveredHex, hex};
  310. }
  311. }
  312. return {};
  313. }
  314. std::vector<BattleHex> BattleFieldController::getRangedFullDamageHexes()
  315. {
  316. std::vector<BattleHex> rangedFullDamageHexes; // used for return
  317. // if not a hovered arcer unit -> return
  318. auto hoveredHex = getHoveredHex();
  319. const CStack * hoveredStack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  320. if (!settings["battle"]["rangedFullDamageLimitHighlightOnHover"].Bool() && !GH.isKeyboardShiftDown())
  321. return rangedFullDamageHexes;
  322. if(!(hoveredStack && hoveredStack->isShooter()))
  323. return rangedFullDamageHexes;
  324. auto rangedFullDamageDistance = GameConstants::BATTLE_PENALTY_DISTANCE;
  325. // overwrite full ranged damage distance from Additional info field of LIMITED_SHOOTING_RANGE bonus
  326. auto bonus = hoveredStack->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  327. if(bonus != nullptr && bonus->additionalInfo != CAddInfo::NONE)
  328. rangedFullDamageDistance = bonus->additionalInfo[0];
  329. // get only battlefield hexes that are in full range damage distance
  330. std::set<BattleHex> fullRangeLimit;
  331. for(auto i = 0; i < GameConstants::BFIELD_SIZE; i++)
  332. {
  333. BattleHex hex(i);
  334. if(hex.isAvailable() && BattleHex::getDistance(hoveredHex, hex) <= rangedFullDamageDistance)
  335. rangedFullDamageHexes.push_back(hex);
  336. }
  337. return rangedFullDamageHexes;
  338. }
  339. std::vector<BattleHex> BattleFieldController::getRangedFullDamageLimitHexes(std::vector<BattleHex> rangedFullDamageHexes)
  340. {
  341. std::vector<BattleHex> rangedFullDamageLimitHexes; // used for return
  342. // if not a hovered arcer unit -> return
  343. auto hoveredHex = getHoveredHex();
  344. const CStack * hoveredStack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  345. if(!(hoveredStack && hoveredStack->isShooter()))
  346. return rangedFullDamageLimitHexes;
  347. auto rangedFullDamageDistance = GameConstants::BATTLE_PENALTY_DISTANCE;
  348. // overwrite full ranged damage distance from Additional info field of LIMITED_SHOOTING_RANGE bonus
  349. auto bonus = hoveredStack->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  350. if(bonus != nullptr && bonus->additionalInfo != CAddInfo::NONE)
  351. rangedFullDamageDistance = bonus->additionalInfo[0];
  352. // from ranged full damage hexes get only the ones at the limit
  353. for(auto & hex : rangedFullDamageHexes)
  354. {
  355. if(BattleHex::getDistance(hoveredHex, hex) == rangedFullDamageDistance)
  356. rangedFullDamageLimitHexes.push_back(hex);
  357. }
  358. return rangedFullDamageLimitHexes;
  359. }
  360. std::vector<std::vector<BattleHex::EDir>> BattleFieldController::getOutsideNeighbourDirectionsForLimitHexes(std::vector<BattleHex> rangedFullDamageHexes, std::vector<BattleHex> rangedFullDamageLimitHexes)
  361. {
  362. std::vector<std::vector<BattleHex::EDir>> output;
  363. if(rangedFullDamageHexes.empty())
  364. return output;
  365. for(auto & hex : rangedFullDamageLimitHexes)
  366. {
  367. // get all neighbours and their directions
  368. auto neighbours = hex.neighbouringTilesWithDirection();
  369. std::vector<BattleHex::EDir> outsideNeighbourDirections;
  370. // for each neighbour add to output only the ones not found in rangedFullDamageHexes
  371. for(auto & neighbour : neighbours)
  372. {
  373. auto it = std::find(rangedFullDamageHexes.begin(), rangedFullDamageHexes.end(), neighbour.second);
  374. if(it == rangedFullDamageHexes.end())
  375. outsideNeighbourDirections.push_back(neighbour.first); // push direction
  376. }
  377. output.push_back(outsideNeighbourDirections);
  378. }
  379. return output;
  380. }
  381. std::vector<std::shared_ptr<IImage>> BattleFieldController::calculateFullRangedDamageHighlightImages(std::vector<std::vector<BattleHex::EDir>> fullRangedDamageLimitHexesNeighbourDirections)
  382. {
  383. std::vector<std::shared_ptr<IImage>> output; // if no image is to be shown an empty image is still added to help with traverssing the range
  384. if(fullRangedDamageLimitHexesNeighbourDirections.empty())
  385. return output;
  386. for(auto & directions : fullRangedDamageLimitHexesNeighbourDirections)
  387. {
  388. std::bitset<6> mask;
  389. // convert directions to mask
  390. for(auto direction : directions)
  391. mask.set(direction);
  392. uint8_t imageKey = static_cast<uint8_t>(mask.to_ulong());
  393. output.push_back(fullDamageRangeLimitImages[imageKey]);
  394. }
  395. return output;
  396. }
  397. void BattleFieldController::showHighlightedHexes(Canvas & canvas)
  398. {
  399. std::set<BattleHex> hoveredStackMovementRangeHexes = getMovementRangeForHoveredStack();
  400. std::set<BattleHex> hoveredSpellHexes = getHighlightedHexesForSpellRange();
  401. std::set<BattleHex> hoveredMoveHexes = getHighlightedHexesForMovementTarget();
  402. if(getHoveredHex() == BattleHex::INVALID)
  403. return;
  404. // calculate array with highlight images for ranged full damage limit
  405. std::vector<BattleHex> rangedFullDamageHexes = getRangedFullDamageHexes();
  406. std::vector<BattleHex> rangedFullDamageLimitHexes = getRangedFullDamageLimitHexes(rangedFullDamageHexes);
  407. std::vector<std::vector<BattleHex::EDir>> rangedFullDamageLimitHexesNeighbourDirections = getOutsideNeighbourDirectionsForLimitHexes(rangedFullDamageHexes, rangedFullDamageLimitHexes);
  408. std::vector<std::shared_ptr<IImage>> rangedFullDamageLimitHexesHighligts = calculateFullRangedDamageHighlightImages(rangedFullDamageLimitHexesNeighbourDirections);
  409. auto const & hoveredMouseHexes = owner.actionsController->currentActionSpellcasting(getHoveredHex()) ? hoveredSpellHexes : hoveredMoveHexes;
  410. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; ++hex)
  411. {
  412. bool stackMovement = hoveredStackMovementRangeHexes.count(hex);
  413. bool mouse = hoveredMouseHexes.count(hex);
  414. // calculate if hex is Ranged Full Damage Limit and its position in highlight array
  415. bool isRangedFullDamageLimit = false;
  416. int hexIndexInRangedFullDamageLimit = 0;
  417. if(!rangedFullDamageLimitHexes.empty())
  418. {
  419. auto pos = std::find(rangedFullDamageLimitHexes.begin(), rangedFullDamageLimitHexes.end(), hex);
  420. hexIndexInRangedFullDamageLimit = std::distance(rangedFullDamageLimitHexes.begin(), pos);
  421. isRangedFullDamageLimit = pos != rangedFullDamageLimitHexes.end();
  422. }
  423. if(stackMovement && mouse) // area where hovered stackMovement can move shown with highlight. Because also affected by mouse cursor, shade as well
  424. {
  425. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  426. showHighlightedHex(canvas, cellShade, hex, true);
  427. }
  428. if(!stackMovement && mouse) // hexes affected only at mouse cursor shown as shaded
  429. {
  430. showHighlightedHex(canvas, cellShade, hex, true);
  431. }
  432. if(stackMovement && !mouse) // hexes where hovered stackMovement can move shown with highlight
  433. {
  434. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  435. }
  436. if(isRangedFullDamageLimit)
  437. {
  438. showHighlightedHex(canvas, rangedFullDamageLimitHexesHighligts[hexIndexInRangedFullDamageLimit], hex, false);
  439. }
  440. }
  441. }
  442. Rect BattleFieldController::hexPositionLocal(BattleHex hex) const
  443. {
  444. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX();
  445. int y = 86 + 42 *hex.getY();
  446. int w = cellShade->width();
  447. int h = cellShade->height();
  448. return Rect(x, y, w, h);
  449. }
  450. Rect BattleFieldController::hexPositionAbsolute(BattleHex hex) const
  451. {
  452. return hexPositionLocal(hex) + pos.topLeft();
  453. }
  454. bool BattleFieldController::isPixelInHex(Point const & position)
  455. {
  456. return !cellShade->isTransparent(position);
  457. }
  458. BattleHex BattleFieldController::getHoveredHex()
  459. {
  460. return hoveredHex;
  461. }
  462. BattleHex BattleFieldController::getHexAtPosition(Point hoverPos)
  463. {
  464. if (owner.attackingHero)
  465. {
  466. if (owner.attackingHero->pos.isInside(hoverPos))
  467. return BattleHex::HERO_ATTACKER;
  468. }
  469. if (owner.defendingHero)
  470. {
  471. if (owner.attackingHero->pos.isInside(hoverPos))
  472. return BattleHex::HERO_DEFENDER;
  473. }
  474. for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  475. {
  476. Rect hexPosition = hexPositionAbsolute(h);
  477. if (!hexPosition.isInside(hoverPos))
  478. continue;
  479. if (isPixelInHex(hoverPos - hexPosition.topLeft()))
  480. return h;
  481. }
  482. return BattleHex::INVALID;
  483. }
  484. BattleHex::EDir BattleFieldController::selectAttackDirection(BattleHex myNumber)
  485. {
  486. const bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
  487. auto neighbours = myNumber.allNeighbouringTiles();
  488. // 0 1
  489. // 5 x 2
  490. // 4 3
  491. // if true - our current stack can move into this hex (and attack)
  492. std::array<bool, 8> attackAvailability;
  493. if (doubleWide)
  494. {
  495. // For double-hexes we need to ensure that both hexes needed for this direction are occupyable:
  496. // | -0- | -1- | -2- | -3- | -4- | -5- | -6- | -7-
  497. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  498. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  499. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  500. for (size_t i : { 1, 2, 3})
  501. attackAvailability[i] = vstd::contains(occupiableHexes, neighbours[i]) && vstd::contains(occupiableHexes, neighbours[i].cloneInDirection(BattleHex::RIGHT, false));
  502. for (size_t i : { 4, 5, 0})
  503. attackAvailability[i] = vstd::contains(occupiableHexes, neighbours[i]) && vstd::contains(occupiableHexes, neighbours[i].cloneInDirection(BattleHex::LEFT, false));
  504. attackAvailability[6] = vstd::contains(occupiableHexes, neighbours[0]) && vstd::contains(occupiableHexes, neighbours[1]);
  505. attackAvailability[7] = vstd::contains(occupiableHexes, neighbours[3]) && vstd::contains(occupiableHexes, neighbours[4]);
  506. }
  507. else
  508. {
  509. for (size_t i = 0; i < 6; ++i)
  510. attackAvailability[i] = vstd::contains(occupiableHexes, neighbours[i]);
  511. attackAvailability[6] = false;
  512. attackAvailability[7] = false;
  513. }
  514. // Zero available tiles to attack from
  515. if ( vstd::find(attackAvailability, true) == attackAvailability.end())
  516. {
  517. logGlobal->error("Error: cannot find a hex to attack hex %d from!", myNumber);
  518. return BattleHex::NONE;
  519. }
  520. // For each valid direction, select position to test against
  521. std::array<Point, 8> testPoint;
  522. for (size_t i = 0; i < 6; ++i)
  523. if (attackAvailability[i])
  524. testPoint[i] = hexPositionAbsolute(neighbours[i]).center();
  525. // For bottom/top directions select central point, but move it a bit away from true center to reduce zones allocated to them
  526. if (attackAvailability[6])
  527. testPoint[6] = (hexPositionAbsolute(neighbours[0]).center() + hexPositionAbsolute(neighbours[1]).center()) / 2 + Point(0, -5);
  528. if (attackAvailability[7])
  529. testPoint[7] = (hexPositionAbsolute(neighbours[3]).center() + hexPositionAbsolute(neighbours[4]).center()) / 2 + Point(0, 5);
  530. // Compute distance between tested position & cursor position and pick nearest
  531. std::array<int, 8> distance2;
  532. for (size_t i = 0; i < 8; ++i)
  533. if (attackAvailability[i])
  534. distance2[i] = (testPoint[i].y - currentAttackOriginPoint.y)*(testPoint[i].y - currentAttackOriginPoint.y) + (testPoint[i].x - currentAttackOriginPoint.x)*(testPoint[i].x - currentAttackOriginPoint.x);
  535. size_t nearest = -1;
  536. for (size_t i = 0; i < 8; ++i)
  537. if (attackAvailability[i] && (nearest == -1 || distance2[i] < distance2[nearest]) )
  538. nearest = i;
  539. assert(nearest != -1);
  540. return BattleHex::EDir(nearest);
  541. }
  542. BattleHex BattleFieldController::fromWhichHexAttack(BattleHex attackTarget)
  543. {
  544. BattleHex::EDir direction = selectAttackDirection(getHoveredHex());
  545. const CStack * attacker = owner.stacksController->getActiveStack();
  546. assert(direction != BattleHex::NONE);
  547. assert(attacker);
  548. if (!attacker->doubleWide())
  549. {
  550. assert(direction != BattleHex::BOTTOM);
  551. assert(direction != BattleHex::TOP);
  552. return attackTarget.cloneInDirection(direction);
  553. }
  554. else
  555. {
  556. // We need to find position of right hex of double-hex creature (or left for defending side)
  557. // | TOP_LEFT |TOP_RIGHT | RIGHT |BOTTOM_RIGHT|BOTTOM_LEFT| LEFT | TOP |BOTTOM
  558. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  559. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  560. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  561. switch (direction)
  562. {
  563. case BattleHex::TOP_LEFT:
  564. case BattleHex::LEFT:
  565. case BattleHex::BOTTOM_LEFT:
  566. {
  567. if ( attacker->unitSide() == BattleSide::ATTACKER )
  568. return attackTarget.cloneInDirection(direction);
  569. else
  570. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::LEFT);
  571. }
  572. case BattleHex::TOP_RIGHT:
  573. case BattleHex::RIGHT:
  574. case BattleHex::BOTTOM_RIGHT:
  575. {
  576. if ( attacker->unitSide() == BattleSide::ATTACKER )
  577. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::RIGHT);
  578. else
  579. return attackTarget.cloneInDirection(direction);
  580. }
  581. case BattleHex::TOP:
  582. {
  583. if ( attacker->unitSide() == BattleSide::ATTACKER )
  584. return attackTarget.cloneInDirection(BattleHex::TOP_RIGHT);
  585. else
  586. return attackTarget.cloneInDirection(BattleHex::TOP_LEFT);
  587. }
  588. case BattleHex::BOTTOM:
  589. {
  590. if ( attacker->unitSide() == BattleSide::ATTACKER )
  591. return attackTarget.cloneInDirection(BattleHex::BOTTOM_RIGHT);
  592. else
  593. return attackTarget.cloneInDirection(BattleHex::BOTTOM_LEFT);
  594. }
  595. default:
  596. assert(0);
  597. return BattleHex::INVALID;
  598. }
  599. }
  600. }
  601. bool BattleFieldController::isTileAttackable(const BattleHex & number) const
  602. {
  603. for (auto & elem : occupiableHexes)
  604. {
  605. if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
  606. return true;
  607. }
  608. return false;
  609. }
  610. void BattleFieldController::updateAccessibleHexes()
  611. {
  612. auto accessibility = owner.curInt->cb->getAccesibility();
  613. for(int i = 0; i < accessibility.size(); i++)
  614. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE || (accessibility[i] == EAccessibility::SIDE_COLUMN));
  615. }
  616. bool BattleFieldController::stackCountOutsideHex(const BattleHex & number) const
  617. {
  618. return stackCountOutsideHexes[number];
  619. }
  620. void BattleFieldController::showAll(Canvas & to)
  621. {
  622. show(to);
  623. }
  624. void BattleFieldController::tick(uint32_t msPassed)
  625. {
  626. updateAccessibleHexes();
  627. owner.stacksController->tick(msPassed);
  628. owner.obstacleController->tick(msPassed);
  629. owner.projectilesController->tick(msPassed);
  630. }
  631. void BattleFieldController::show(Canvas & to)
  632. {
  633. CSDL_Ext::CClipRectGuard guard(to.getInternalSurface(), pos);
  634. renderBattlefield(to);
  635. if (isActive() && isPanning() && getHoveredHex() != BattleHex::INVALID)
  636. {
  637. auto cursorIndex = CCS->curh->get<Cursor::Combat>();
  638. auto imageIndex = static_cast<size_t>(cursorIndex);
  639. to.draw(attackCursors->getImage(imageIndex), hexPositionAbsolute(getHoveredHex()).center() - CCS->curh->getPivotOffsetCombat(imageIndex));
  640. }
  641. }
  642. bool BattleFieldController::receiveEvent(const Point & position, int eventType) const
  643. {
  644. if (eventType == HOVER)
  645. return true;
  646. return CIntObject::receiveEvent(position, eventType);
  647. }