BattleFieldController.cpp 29 KB

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