BattleFieldController.cpp 28 KB

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