BattleFieldController.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. rangedFullDamageLimitImages = ENGINE->renderHandler().loadAnimation(AnimationPath::builtin("battle/rangeHighlights/rangeHighlightsGreen.json"), EImageBlitMode::COLORKEY);
  109. shootingRangeLimitImages = ENGINE->renderHandler().loadAnimation(AnimationPath::builtin("battle/rangeHighlights/rangeHighlightsRed.json"), EImageBlitMode::COLORKEY);
  110. if(!owner.siegeController)
  111. {
  112. auto bfieldType = owner.getBattle()->battleGetBattlefieldType();
  113. if(bfieldType == BattleField::NONE)
  114. logGlobal->error("Invalid battlefield returned for current battle");
  115. else
  116. background = ENGINE->renderHandler().loadImage(bfieldType.getInfo()->graphics, EImageBlitMode::OPAQUE);
  117. }
  118. else
  119. {
  120. auto backgroundName = owner.siegeController->getBattleBackgroundName();
  121. background = ENGINE->renderHandler().loadImage(backgroundName, EImageBlitMode::OPAQUE);
  122. }
  123. pos.w = background->width();
  124. pos.h = background->height();
  125. backgroundWithHexes = std::make_unique<Canvas>(Point(background->width(), background->height()), CanvasScalingPolicy::AUTO);
  126. updateAccessibleHexes();
  127. addUsedEvents(LCLICK | SHOW_POPUP | MOVE | TIME | GESTURE);
  128. }
  129. void BattleFieldController::activate()
  130. {
  131. GAME->interface()->cingconsole->pos = this->pos;
  132. CIntObject::activate();
  133. }
  134. void BattleFieldController::createHeroes()
  135. {
  136. OBJECT_CONSTRUCTION;
  137. // create heroes as part of our constructor for correct positioning inside battlefield
  138. if(owner.attackingHeroInstance)
  139. owner.attackingHero = std::make_shared<BattleHero>(owner, owner.attackingHeroInstance, false);
  140. if(owner.defendingHeroInstance)
  141. owner.defendingHero = std::make_shared<BattleHero>(owner, owner.defendingHeroInstance, true);
  142. }
  143. void BattleFieldController::gesture(bool on, const Point & initialPosition, const Point & finalPosition)
  144. {
  145. if (!on && pos.isInside(finalPosition))
  146. clickPressed(finalPosition);
  147. }
  148. void BattleFieldController::gesturePanning(const Point & initialPosition, const Point & currentPosition, const Point & lastUpdateDistance)
  149. {
  150. Point distance = currentPosition - initialPosition;
  151. if (distance.length() < settings["battle"]["swipeAttackDistance"].Float())
  152. hoveredHex = getHexAtPosition(initialPosition);
  153. else
  154. hoveredHex = BattleHex::INVALID;
  155. currentAttackOriginPoint = currentPosition;
  156. if (pos.isInside(initialPosition))
  157. owner.actionsController->onHexHovered(getHoveredHex());
  158. }
  159. void BattleFieldController::mouseMoved(const Point & cursorPosition, const Point & lastUpdateDistance)
  160. {
  161. hoveredHex = getHexAtPosition(cursorPosition);
  162. currentAttackOriginPoint = cursorPosition;
  163. if (pos.isInside(cursorPosition))
  164. owner.actionsController->onHexHovered(getHoveredHex());
  165. else
  166. owner.actionsController->onHoverEnded();
  167. }
  168. void BattleFieldController::clickPressed(const Point & cursorPosition)
  169. {
  170. BattleHex selectedHex = getHoveredHex();
  171. if (selectedHex != BattleHex::INVALID)
  172. owner.actionsController->onHexLeftClicked(selectedHex);
  173. }
  174. void BattleFieldController::showPopupWindow(const Point & cursorPosition)
  175. {
  176. BattleHex selectedHex = getHoveredHex();
  177. if (selectedHex != BattleHex::INVALID)
  178. owner.actionsController->onHexRightClicked(selectedHex);
  179. }
  180. void BattleFieldController::renderBattlefield(Canvas & canvas)
  181. {
  182. Canvas clippedCanvas(canvas, pos);
  183. showBackground(clippedCanvas);
  184. BattleRenderer renderer(owner);
  185. renderer.execute(clippedCanvas);
  186. owner.projectilesController->render(clippedCanvas);
  187. }
  188. void BattleFieldController::showBackground(Canvas & canvas)
  189. {
  190. if (owner.stacksController->getActiveStack() != nullptr )
  191. showBackgroundImageWithHexes(canvas);
  192. else
  193. showBackgroundImage(canvas);
  194. showHighlightedHexes(canvas);
  195. }
  196. void BattleFieldController::showBackgroundImage(Canvas & canvas)
  197. {
  198. canvas.draw(background, Point(0, 0));
  199. owner.obstacleController->showAbsoluteObstacles(canvas);
  200. if ( owner.siegeController )
  201. owner.siegeController->showAbsoluteObstacles(canvas);
  202. if (settings["battle"]["cellBorders"].Bool())
  203. {
  204. for (int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  205. {
  206. if ( i % GameConstants::BFIELD_WIDTH == 0)
  207. continue;
  208. if ( i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  209. continue;
  210. canvas.draw(cellBorder, hexPositionLocal(i).topLeft());
  211. }
  212. }
  213. }
  214. void BattleFieldController::showBackgroundImageWithHexes(Canvas & canvas)
  215. {
  216. canvas.draw(*backgroundWithHexes, Point(0, 0));
  217. }
  218. void BattleFieldController::redrawBackgroundWithHexes()
  219. {
  220. const CStack *activeStack = owner.stacksController->getActiveStack();
  221. if(activeStack)
  222. availableHexes = owner.getBattle()->battleGetAvailableHexes(activeStack, false);
  223. else
  224. availableHexes.clear();
  225. // prepare background graphic with hexes and shaded hexes
  226. backgroundWithHexes->draw(background, Point(0,0));
  227. owner.obstacleController->showAbsoluteObstacles(*backgroundWithHexes);
  228. if(owner.siegeController)
  229. owner.siegeController->showAbsoluteObstacles(*backgroundWithHexes);
  230. // show shaded hexes for active's stack valid movement and the hexes that it can attack
  231. if(activeStack && settings["battle"]["stackRange"].Bool())
  232. {
  233. auto occupiableHexes = owner.getBattle()->battleGetOccupiableHexes(availableHexes, activeStack);
  234. for(si16 hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  235. {
  236. //shade occupiable and attackable hexes
  237. if (occupiableHexes.contains(hex) ||
  238. (owner.getBattle()->battleCanAttackUnit(activeStack, owner.getBattle()->battleGetStackByPos(hex, true)) &&
  239. owner.getBattle()->battleCanAttackHex(availableHexes, activeStack, hex)) ||
  240. (owner.getBattle()->battleGetStackByPos(hex, true) &&
  241. owner.getBattle()->battleCanShoot(activeStack, hex)))
  242. showHighlightedHex(*backgroundWithHexes, cellShade, hex, false);
  243. }
  244. }
  245. // draw cell borders
  246. if(settings["battle"]["cellBorders"].Bool())
  247. {
  248. for(int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  249. {
  250. if(i % GameConstants::BFIELD_WIDTH == 0)
  251. continue;
  252. if(i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  253. continue;
  254. backgroundWithHexes->draw(cellBorder, hexPositionLocal(i).topLeft());
  255. }
  256. }
  257. }
  258. void BattleFieldController::showHighlightedHex(Canvas & canvas, std::shared_ptr<IImage> highlight, const BattleHex & hex, bool darkBorder)
  259. {
  260. Point hexPos = hexPositionLocal(hex).topLeft();
  261. canvas.draw(highlight, hexPos);
  262. if(!darkBorder && settings["battle"]["cellBorders"].Bool())
  263. canvas.draw(cellBorder, hexPos);
  264. }
  265. BattleHexArray BattleFieldController::getHighlightedHexesForActiveStack()
  266. {
  267. if(!owner.stacksController->getActiveStack())
  268. return BattleHexArray();
  269. if(!settings["battle"]["stackRange"].Bool())
  270. return BattleHexArray();
  271. auto hoveredHex = getHoveredHex();
  272. return owner.getBattle()->battleGetAttackedHexes(owner.stacksController->getActiveStack(), hoveredHex);
  273. }
  274. BattleHexArray BattleFieldController::getMovementRangeForHoveredStack()
  275. {
  276. if (!owner.stacksController->getActiveStack())
  277. return BattleHexArray();
  278. if (!settings["battle"]["movementHighlightOnHover"].Bool() && !ENGINE->isKeyboardShiftDown())
  279. return BattleHexArray();
  280. auto hoveredStack = getHoveredStack();
  281. return hoveredStack ? owner.getBattle()->battleGetOccupiableHexes(hoveredStack, true) : BattleHexArray();
  282. }
  283. BattleHexArray BattleFieldController::getHighlightedHexesForSpellRange()
  284. {
  285. BattleHexArray result;
  286. auto hoveredHex = getHoveredHex();
  287. const spells::Caster *caster = nullptr;
  288. const CSpell *spell = nullptr;
  289. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  290. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  291. caster = owner.actionsController->getCurrentSpellcaster();
  292. if(caster && spell) //when casting spell
  293. {
  294. // printing shaded hex(es)
  295. spells::BattleCast event(owner.getBattle().get(), caster, mode, spell);
  296. auto shadedHexes = spell->battleMechanics(&event)->rangeInHexes(hoveredHex);
  297. for(const BattleHex & shadedHex : shadedHexes)
  298. {
  299. if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
  300. result.insert(shadedHex);
  301. }
  302. }
  303. return result;
  304. }
  305. BattleHexArray BattleFieldController::getHighlightedHexesForMovementTarget()
  306. {
  307. const CStack * stack = owner.stacksController->getActiveStack();
  308. auto hoveredHex = getHoveredHex();
  309. if(!stack)
  310. return {};
  311. auto hoveredStack = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  312. if(owner.getBattle()->battleCanAttackUnit(stack, hoveredStack) && owner.getBattle()->battleCanAttackHex(availableHexes, stack, hoveredHex))
  313. {
  314. BattleHex fromHex = owner.getBattle()->fromWhichHexAttack(stack, hoveredHex, selectAttackDirection(hoveredHex));
  315. assert(fromHex.isValid());
  316. if(stack->doubleWide())
  317. return {fromHex, stack->occupiedHex(fromHex)};
  318. return {fromHex};
  319. }
  320. auto toHex = owner.getBattle()->toWhichHexMove(availableHexes, stack, hoveredHex);
  321. if (!toHex.isValid())
  322. return {};
  323. if (stack->doubleWide())
  324. return {toHex, stack->occupiedHex(toHex)};
  325. else
  326. return {toHex};
  327. }
  328. // Range limit highlight helpers
  329. BattleHexArray BattleFieldController::getRangeHexes(const BattleHex & sourceHex, uint8_t distance) const
  330. {
  331. BattleHexArray rangeHexes;
  332. if (!settings["battle"]["rangeLimitHighlightOnHover"].Bool() && !ENGINE->isKeyboardShiftDown())
  333. return rangeHexes;
  334. // get only battlefield hexes that are within the given distance
  335. for(auto i = 0; i < GameConstants::BFIELD_SIZE; i++)
  336. {
  337. BattleHex hex(i);
  338. if(hex.isAvailable() && BattleHex::getDistance(sourceHex, hex) <= distance)
  339. rangeHexes.insert(hex);
  340. }
  341. return rangeHexes;
  342. }
  343. BattleHexArray BattleFieldController::getRangeLimitHexes(const BattleHex & sourceHex, const BattleHexArray & rangeHexes, uint8_t distanceToLimit) const
  344. {
  345. BattleHexArray rangeLimitHexes;
  346. // from range hexes get only the ones at the limit
  347. for(auto & hex : rangeHexes)
  348. {
  349. if(BattleHex::getDistance(sourceHex, hex) == distanceToLimit)
  350. rangeLimitHexes.insert(hex);
  351. }
  352. return rangeLimitHexes;
  353. }
  354. bool BattleFieldController::isHexInRangeLimit(const BattleHex & hex, const BattleHexArray & rangeLimitHexes, int * hexIndexInRangeLimit) const
  355. {
  356. bool hexInRangeLimit = false;
  357. if(!rangeLimitHexes.empty())
  358. {
  359. auto pos = std::find(rangeLimitHexes.begin(), rangeLimitHexes.end(), hex);
  360. *hexIndexInRangeLimit = std::distance(rangeLimitHexes.begin(), pos);
  361. hexInRangeLimit = pos != rangeLimitHexes.end();
  362. }
  363. return hexInRangeLimit;
  364. }
  365. std::vector<std::vector<BattleHex::EDir>> BattleFieldController::getOutsideNeighbourDirectionsForLimitHexes(
  366. const BattleHexArray & wholeRangeHexes, const BattleHexArray & rangeLimitHexes) const
  367. {
  368. std::vector<std::vector<BattleHex::EDir>> output;
  369. if(wholeRangeHexes.empty())
  370. return output;
  371. for(const auto & hex : rangeLimitHexes)
  372. {
  373. // get all neighbours and their directions
  374. const BattleHexArray & neighbouringTiles = hex.getAllNeighbouringTiles();
  375. std::vector<BattleHex::EDir> outsideNeighbourDirections;
  376. // for each neighbour add to output only the valid ones and only that are not found in range Hexes
  377. for(auto direction = 0; direction < 6; direction++)
  378. {
  379. if(!neighbouringTiles[direction].isAvailable())
  380. continue;
  381. if(!wholeRangeHexes.contains(neighbouringTiles[direction]))
  382. outsideNeighbourDirections.push_back(BattleHex::EDir(direction)); // push direction
  383. }
  384. output.push_back(outsideNeighbourDirections);
  385. }
  386. return output;
  387. }
  388. std::vector<std::shared_ptr<IImage>> BattleFieldController::calculateRangeLimitHighlightImages(std::vector<std::vector<BattleHex::EDir>> hexesNeighbourDirections, std::shared_ptr<CAnimation> limitImages)
  389. {
  390. 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
  391. if(hexesNeighbourDirections.empty())
  392. return output;
  393. for(auto & directions : hexesNeighbourDirections)
  394. {
  395. std::bitset<6> mask;
  396. // convert directions to mask
  397. for(auto direction : directions)
  398. mask.set(direction);
  399. uint8_t imageKey = static_cast<uint8_t>(mask.to_ulong());
  400. output.push_back(limitImages->getImage(hexEdgeMaskToFrameIndex.at(imageKey)));
  401. }
  402. return output;
  403. }
  404. void BattleFieldController::calculateRangeLimitAndHighlightImages(uint8_t distance, std::shared_ptr<CAnimation> rangeLimitImages, BattleHexArray & rangeLimitHexes, std::vector<std::shared_ptr<IImage>> & rangeLimitHexesHighlights)
  405. {
  406. BattleHexArray rangeHexes = getRangeHexes(hoveredHex, distance);
  407. rangeLimitHexes = getRangeLimitHexes(hoveredHex, rangeHexes, distance);
  408. std::vector<std::vector<BattleHex::EDir>> rangeLimitNeighbourDirections = getOutsideNeighbourDirectionsForLimitHexes(rangeHexes, rangeLimitHexes);
  409. rangeLimitHexesHighlights = calculateRangeLimitHighlightImages(rangeLimitNeighbourDirections, rangeLimitImages);
  410. }
  411. void BattleFieldController::showHighlightedHexes(Canvas & canvas)
  412. {
  413. BattleHexArray rangedFullDamageLimitHexes;
  414. BattleHexArray shootingRangeLimitHexes;
  415. std::vector<std::shared_ptr<IImage>> rangedFullDamageLimitHexesHighlights;
  416. std::vector<std::shared_ptr<IImage>> shootingRangeLimitHexesHighlights;
  417. BattleHexArray hoveredStackMovementRangeHexes = getMovementRangeForHoveredStack();
  418. BattleHexArray hoveredSpellHexes = getHighlightedHexesForSpellRange();
  419. BattleHexArray hoveredMoveHexes = getHighlightedHexesForMovementTarget();
  420. BattleHex hoveredHex = getHoveredHex();
  421. BattleHexArray hoveredMouseHex = hoveredHex.isAvailable() ? BattleHexArray({ hoveredHex }) : BattleHexArray();
  422. const CStack * hoveredStack = getHoveredStack();
  423. if(!hoveredStack && hoveredHex == BattleHex::INVALID)
  424. return;
  425. // skip range limit calculations if unit hovered is not a shooter
  426. if(hoveredStack && hoveredStack->isShooter())
  427. {
  428. // calculate array with highlight images for ranged full damage limit
  429. auto rangedFullDamageDistance = hoveredStack->getRangedFullDamageDistance();
  430. calculateRangeLimitAndHighlightImages(rangedFullDamageDistance, rangedFullDamageLimitImages, rangedFullDamageLimitHexes, rangedFullDamageLimitHexesHighlights);
  431. // calculate array with highlight images for shooting range limit
  432. auto shootingRangeDistance = hoveredStack->getShootingRangeDistance();
  433. calculateRangeLimitAndHighlightImages(shootingRangeDistance, shootingRangeLimitImages, shootingRangeLimitHexes, shootingRangeLimitHexesHighlights);
  434. }
  435. bool useSpellRangeForMouse = hoveredHex != BattleHex::INVALID
  436. && (owner.actionsController->currentActionSpellcasting(getHoveredHex())
  437. || owner.actionsController->creatureSpellcastingModeActive()); //at least shooting with SPELL_LIKE_ATTACK can operate in spellcasting mode without being actual spellcast
  438. bool useMoveRangeForMouse = !hoveredMoveHexes.empty() || !settings["battle"]["mouseShadow"].Bool();
  439. const auto & hoveredMouseHexes = useSpellRangeForMouse ? hoveredSpellHexes : ( useMoveRangeForMouse ? hoveredMoveHexes : hoveredMouseHex);
  440. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; ++hex)
  441. {
  442. bool stackMovement = hoveredStackMovementRangeHexes.contains(hex);
  443. bool mouse = hoveredMouseHexes.contains(hex);
  444. // calculate if hex is Ranged Full Damage Limit and its position in highlight array
  445. int hexIndexInRangedFullDamageLimit = 0;
  446. bool hexInRangedFullDamageLimit = isHexInRangeLimit(hex, rangedFullDamageLimitHexes, &hexIndexInRangedFullDamageLimit);
  447. // calculate if hex is Shooting Range Limit and its position in highlight array
  448. int hexIndexInShootingRangeLimit = 0;
  449. bool hexInShootingRangeLimit = isHexInRangeLimit(hex, shootingRangeLimitHexes, &hexIndexInShootingRangeLimit);
  450. if(stackMovement && mouse) // area where hovered stackMovement can move shown with highlight. Because also affected by mouse cursor, shade as well
  451. {
  452. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  453. showHighlightedHex(canvas, cellShade, hex, true);
  454. }
  455. if(!stackMovement && mouse) // hexes affected only at mouse cursor shown as shaded
  456. {
  457. showHighlightedHex(canvas, cellShade, hex, true);
  458. }
  459. if(stackMovement && !mouse) // hexes where hovered stackMovement can move shown with highlight
  460. {
  461. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  462. }
  463. if(hexInRangedFullDamageLimit)
  464. {
  465. showHighlightedHex(canvas, rangedFullDamageLimitHexesHighlights[hexIndexInRangedFullDamageLimit], hex, false);
  466. }
  467. if(hexInShootingRangeLimit)
  468. {
  469. showHighlightedHex(canvas, shootingRangeLimitHexesHighlights[hexIndexInShootingRangeLimit], hex, false);
  470. }
  471. }
  472. }
  473. Rect BattleFieldController::hexPositionLocal(const BattleHex & hex) const
  474. {
  475. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX();
  476. int y = 86 + 42 *hex.getY();
  477. int w = cellShade->width();
  478. int h = cellShade->height();
  479. return Rect(x, y, w, h);
  480. }
  481. Rect BattleFieldController::hexPositionAbsolute(const BattleHex & hex) const
  482. {
  483. return hexPositionLocal(hex) + pos.topLeft();
  484. }
  485. bool BattleFieldController::isPixelInHex(Point const & position)
  486. {
  487. return !cellShade->isTransparent(position);
  488. }
  489. BattleHex BattleFieldController::getHoveredHex()
  490. {
  491. return hoveredHex;
  492. }
  493. const CStack* BattleFieldController::getHoveredStack()
  494. {
  495. auto hoveredHex = getHoveredHex();
  496. const CStack* hoveredStack = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  497. if(owner.windowObject->getQueueHoveredUnitId().has_value())
  498. {
  499. auto stacks = owner.getBattle()->battleGetAllStacks();
  500. for(const CStack * stack : stacks)
  501. if(stack->unitId() == *owner.windowObject->getQueueHoveredUnitId())
  502. hoveredStack = stack;
  503. }
  504. return hoveredStack;
  505. }
  506. BattleHex BattleFieldController::getHexAtPosition(Point hoverPos)
  507. {
  508. if (owner.attackingHero)
  509. {
  510. if (owner.attackingHero->pos.isInside(hoverPos))
  511. return BattleHex::HERO_ATTACKER;
  512. }
  513. if (owner.defendingHero)
  514. {
  515. if (owner.attackingHero->pos.isInside(hoverPos))
  516. return BattleHex::HERO_DEFENDER;
  517. }
  518. for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  519. {
  520. Rect hexPosition = hexPositionAbsolute(h);
  521. if (!hexPosition.isInside(hoverPos))
  522. continue;
  523. if (isPixelInHex(hoverPos - hexPosition.topLeft()))
  524. return h;
  525. }
  526. return BattleHex::INVALID;
  527. }
  528. BattleHex::EDir BattleFieldController::selectAttackDirection(const BattleHex & myNumber) const
  529. {
  530. auto attacker = owner.stacksController->getActiveStack();
  531. assert(attacker);
  532. const BattleHexArray & neighbours = myNumber.getAllNeighbouringTiles();
  533. // For each valid direction, select position to test against
  534. std::array<Point, 8> testPoint;
  535. testPoint.fill(Point::makeInvalid());
  536. for (size_t i = 0; i < 6; ++i)
  537. if (owner.getBattle()->battleCanAttackHex(availableHexes, attacker, myNumber, BattleHex::EDir(i)))
  538. testPoint[i] = hexPositionAbsolute(neighbours[i]).center();
  539. // For bottom/top directions select central point, but move it a bit away from true center to reduce zones allocated to them
  540. if (owner.getBattle()->battleCanAttackHex(availableHexes, attacker, myNumber, BattleHex::EDir(6)))
  541. testPoint[6] = (hexPositionAbsolute(neighbours[0]).center() + hexPositionAbsolute(neighbours[1]).center()) / 2 + Point(0, -5);
  542. if (owner.getBattle()->battleCanAttackHex(availableHexes, attacker, myNumber, BattleHex::EDir(7)))
  543. testPoint[7] = (hexPositionAbsolute(neighbours[3]).center() + hexPositionAbsolute(neighbours[4]).center()) / 2 + Point(0, 5);
  544. // Compute distance between tested position & cursor position and pick nearest
  545. int nearestDistance = std::numeric_limits<int>::max();
  546. size_t nearest = -1;
  547. for (size_t i = 0; i < 8; ++i)
  548. {
  549. if (testPoint[i].isValid())
  550. {
  551. int distance = (testPoint[i].y - currentAttackOriginPoint.y)*(testPoint[i].y - currentAttackOriginPoint.y) + (testPoint[i].x - currentAttackOriginPoint.x)*(testPoint[i].x - currentAttackOriginPoint.x);
  552. if (nearest == -1 || distance < nearestDistance)
  553. {
  554. nearestDistance = distance;
  555. nearest = i;
  556. }
  557. }
  558. }
  559. if (nearest == -1)
  560. // Zero available tiles to attack from
  561. logGlobal->error("Error: cannot find a hex to attack hex %d from!", myNumber);
  562. return BattleHex::EDir(nearest);
  563. }
  564. void BattleFieldController::updateAccessibleHexes()
  565. {
  566. auto accessibility = owner.getBattle()->getAccessibility();
  567. for(int i = 0; i < accessibility.size(); i++)
  568. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE || (accessibility[i] == EAccessibility::SIDE_COLUMN));
  569. }
  570. bool BattleFieldController::stackCountOutsideHex(const BattleHex & number) const
  571. {
  572. return stackCountOutsideHexes[number.toInt()];
  573. }
  574. void BattleFieldController::showAll(Canvas & to)
  575. {
  576. show(to);
  577. }
  578. void BattleFieldController::tick(uint32_t msPassed)
  579. {
  580. updateAccessibleHexes();
  581. owner.stacksController->tick(msPassed);
  582. owner.obstacleController->tick(msPassed);
  583. owner.projectilesController->tick(msPassed);
  584. }
  585. void BattleFieldController::show(Canvas & to)
  586. {
  587. CanvasClipRectGuard guard(to, pos);
  588. renderBattlefield(to);
  589. if (isActive() && isGesturing() && getHoveredHex() != BattleHex::INVALID)
  590. to.draw(ENGINE->cursor().getCurrentImage(), hexPositionAbsolute(getHoveredHex()).center() - ENGINE->cursor().getPivotOffset());
  591. }
  592. bool BattleFieldController::receiveEvent(const Point & position, int eventType) const
  593. {
  594. if (eventType == HOVER)
  595. return true;
  596. return CIntObject::receiveEvent(position, eventType);
  597. }