BattleFieldController.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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::SIMPLE);
  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()), CanvasScalingPolicy::AUTO);
  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. BattleHexArray 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. BattleHexArray hexesToShade = occupiableHexes;
  236. hexesToShade.insert(attackableHexes);
  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. BattleHexArray BattleFieldController::getHighlightedHexesForActiveStack()
  263. {
  264. BattleHexArray result;
  265. if(!owner.stacksController->getActiveStack())
  266. return result;
  267. if(!settings["battle"]["stackRange"].Bool())
  268. return result;
  269. auto hoveredHex = getHoveredHex();
  270. BattleHexArray set = owner.getBattle()->battleGetAttackedHexes(owner.stacksController->getActiveStack(), hoveredHex);
  271. for(BattleHex hex : set)
  272. result.insert(hex);
  273. return result;
  274. }
  275. BattleHexArray BattleFieldController::getMovementRangeForHoveredStack()
  276. {
  277. BattleHexArray 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. BattleHexArray v = owner.getBattle()->battleGetAvailableHexes(hoveredStack, true, true, nullptr);
  286. for(BattleHex hex : v)
  287. result.insert(hex);
  288. }
  289. return result;
  290. }
  291. BattleHexArray BattleFieldController::getHighlightedHexesForSpellRange()
  292. {
  293. BattleHexArray 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. BattleHexArray BattleFieldController::getHighlightedHexesForMovementTarget()
  314. {
  315. const CStack * stack = owner.stacksController->getActiveStack();
  316. auto hoveredHex = getHoveredHex();
  317. if(!stack)
  318. return {};
  319. BattleHexArray 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(availableHexes.contains(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 hex : availableHexes)
  342. {
  343. if(stack->occupiedHex(hex) == hoveredHex)
  344. return {hoveredHex, hex};
  345. }
  346. }
  347. return {};
  348. }
  349. // Range limit highlight helpers
  350. BattleHexArray BattleFieldController::getRangeHexes(BattleHex sourceHex, uint8_t distance)
  351. {
  352. BattleHexArray 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.insert(hex);
  361. }
  362. return rangeHexes;
  363. }
  364. BattleHexArray BattleFieldController::getRangeLimitHexes(BattleHex hoveredHex, const BattleHexArray & rangeHexes, uint8_t distanceToLimit)
  365. {
  366. BattleHexArray 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.insert(hex);
  372. }
  373. return rangeLimitHexes;
  374. }
  375. bool BattleFieldController::IsHexInRangeLimit(BattleHex hex, const BattleHexArray & 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(
  387. const BattleHexArray & wholeRangeHexes, const BattleHexArray & rangeLimitHexes)
  388. {
  389. std::vector<std::vector<BattleHex::EDir>> output;
  390. if(wholeRangeHexes.empty())
  391. return output;
  392. for(auto hex : rangeLimitHexes)
  393. {
  394. // get all neighbours and their directions
  395. const BattleHexArray & neighbouringTiles = hex.getAllNeighbouringTiles();
  396. std::vector<BattleHex::EDir> outsideNeighbourDirections;
  397. // for each neighbour add to output only the valid ones and only that are not found in range Hexes
  398. for(auto direction = 0; direction < 6; direction++)
  399. {
  400. if(!neighbouringTiles[direction].isAvailable())
  401. continue;
  402. if(!wholeRangeHexes.contains(neighbouringTiles[direction]))
  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, BattleHexArray & rangeLimitHexes, std::vector<std::shared_ptr<IImage>> & rangeLimitHexesHighlights)
  426. {
  427. BattleHexArray 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. BattleHexArray rangedFullDamageLimitHexes;
  435. BattleHexArray shootingRangeLimitHexes;
  436. std::vector<std::shared_ptr<IImage>> rangedFullDamageLimitHexesHighlights;
  437. std::vector<std::shared_ptr<IImage>> shootingRangeLimitHexesHighlights;
  438. BattleHexArray hoveredStackMovementRangeHexes = getMovementRangeForHoveredStack();
  439. BattleHexArray hoveredSpellHexes = getHighlightedHexesForSpellRange();
  440. BattleHexArray hoveredMoveHexes = getHighlightedHexesForMovementTarget();
  441. BattleHex hoveredHex = getHoveredHex();
  442. BattleHexArray hoveredMouseHex = hoveredHex.isValid() ? BattleHexArray({ hoveredHex }) : BattleHexArray();
  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
  457. && (owner.actionsController->currentActionSpellcasting(getHoveredHex())
  458. || owner.actionsController->creatureSpellcastingModeActive()); //at least shooting with SPELL_LIKE_ATTACK can operate in spellcasting mode without being actual spellcast
  459. bool useMoveRangeForMouse = !hoveredMoveHexes.empty() || !settings["battle"]["mouseShadow"].Bool();
  460. const auto & hoveredMouseHexes = useSpellRangeForMouse ? hoveredSpellHexes : ( useMoveRangeForMouse ? hoveredMoveHexes : hoveredMouseHex);
  461. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; ++hex)
  462. {
  463. bool stackMovement = hoveredStackMovementRangeHexes.contains(hex);
  464. bool mouse = hoveredMouseHexes.contains(hex);
  465. // calculate if hex is Ranged Full Damage Limit and its position in highlight array
  466. int hexIndexInRangedFullDamageLimit = 0;
  467. bool hexInRangedFullDamageLimit = IsHexInRangeLimit(hex, rangedFullDamageLimitHexes, &hexIndexInRangedFullDamageLimit);
  468. // calculate if hex is Shooting Range Limit and its position in highlight array
  469. int hexIndexInShootingRangeLimit = 0;
  470. bool hexInShootingRangeLimit = IsHexInRangeLimit(hex, shootingRangeLimitHexes, &hexIndexInShootingRangeLimit);
  471. if(stackMovement && mouse) // area where hovered stackMovement can move shown with highlight. Because also affected by mouse cursor, shade as well
  472. {
  473. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  474. showHighlightedHex(canvas, cellShade, hex, true);
  475. }
  476. if(!stackMovement && mouse) // hexes affected only at mouse cursor shown as shaded
  477. {
  478. showHighlightedHex(canvas, cellShade, hex, true);
  479. }
  480. if(stackMovement && !mouse) // hexes where hovered stackMovement can move shown with highlight
  481. {
  482. showHighlightedHex(canvas, cellUnitMovementHighlight, hex, false);
  483. }
  484. if(hexInRangedFullDamageLimit)
  485. {
  486. showHighlightedHex(canvas, rangedFullDamageLimitHexesHighlights[hexIndexInRangedFullDamageLimit], hex, false);
  487. }
  488. if(hexInShootingRangeLimit)
  489. {
  490. showHighlightedHex(canvas, shootingRangeLimitHexesHighlights[hexIndexInShootingRangeLimit], hex, false);
  491. }
  492. }
  493. }
  494. Rect BattleFieldController::hexPositionLocal(BattleHex hex) const
  495. {
  496. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX();
  497. int y = 86 + 42 *hex.getY();
  498. int w = cellShade->width();
  499. int h = cellShade->height();
  500. return Rect(x, y, w, h);
  501. }
  502. Rect BattleFieldController::hexPositionAbsolute(BattleHex hex) const
  503. {
  504. return hexPositionLocal(hex) + pos.topLeft();
  505. }
  506. bool BattleFieldController::isPixelInHex(Point const & position)
  507. {
  508. return !cellShade->isTransparent(position);
  509. }
  510. BattleHex BattleFieldController::getHoveredHex()
  511. {
  512. return hoveredHex;
  513. }
  514. const CStack* BattleFieldController::getHoveredStack()
  515. {
  516. auto hoveredHex = getHoveredHex();
  517. const CStack* hoveredStack = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  518. if(owner.windowObject->getQueueHoveredUnitId().has_value())
  519. {
  520. auto stacks = owner.getBattle()->battleGetAllStacks();
  521. for(const CStack * stack : stacks)
  522. if(stack->unitId() == *owner.windowObject->getQueueHoveredUnitId())
  523. hoveredStack = stack;
  524. }
  525. return hoveredStack;
  526. }
  527. BattleHex BattleFieldController::getHexAtPosition(Point hoverPos)
  528. {
  529. if (owner.attackingHero)
  530. {
  531. if (owner.attackingHero->pos.isInside(hoverPos))
  532. return BattleHex::HERO_ATTACKER;
  533. }
  534. if (owner.defendingHero)
  535. {
  536. if (owner.attackingHero->pos.isInside(hoverPos))
  537. return BattleHex::HERO_DEFENDER;
  538. }
  539. for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  540. {
  541. Rect hexPosition = hexPositionAbsolute(h);
  542. if (!hexPosition.isInside(hoverPos))
  543. continue;
  544. if (isPixelInHex(hoverPos - hexPosition.topLeft()))
  545. return h;
  546. }
  547. return BattleHex::INVALID;
  548. }
  549. BattleHex::EDir BattleFieldController::selectAttackDirection(BattleHex myNumber)
  550. {
  551. const bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
  552. const BattleHexArray & neighbours = myNumber.getAllNeighbouringTiles();
  553. // 0 1
  554. // 5 x 2
  555. // 4 3
  556. // if true - our current stack can move into this hex (and attack)
  557. std::array<bool, 8> attackAvailability;
  558. if (doubleWide)
  559. {
  560. // For double-hexes we need to ensure that both hexes needed for this direction are occupyable:
  561. // | -0- | -1- | -2- | -3- | -4- | -5- | -6- | -7-
  562. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  563. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  564. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  565. for (size_t i : { 1, 2, 3})
  566. attackAvailability[i] = occupiableHexes.contains(neighbours[i]) && occupiableHexes.contains(neighbours[i].cloneInDirection(BattleHex::RIGHT, false));
  567. for (size_t i : { 4, 5, 0})
  568. attackAvailability[i] = occupiableHexes.contains(neighbours[i]) && occupiableHexes.contains(neighbours[i].cloneInDirection(BattleHex::LEFT, false));
  569. attackAvailability[6] = occupiableHexes.contains(neighbours[0]) && occupiableHexes.contains(neighbours[1]);
  570. attackAvailability[7] = occupiableHexes.contains(neighbours[3]) && occupiableHexes.contains(neighbours[4]);
  571. }
  572. else
  573. {
  574. for (size_t i = 0; i < 6; ++i)
  575. attackAvailability[i] = occupiableHexes.contains(neighbours[i]);
  576. attackAvailability[6] = false;
  577. attackAvailability[7] = false;
  578. }
  579. // Zero available tiles to attack from
  580. if ( vstd::find(attackAvailability, true) == attackAvailability.end())
  581. {
  582. logGlobal->error("Error: cannot find a hex to attack hex %d from!", myNumber);
  583. return BattleHex::NONE;
  584. }
  585. // For each valid direction, select position to test against
  586. std::array<Point, 8> testPoint;
  587. for (size_t i = 0; i < 6; ++i)
  588. if (attackAvailability[i])
  589. testPoint[i] = hexPositionAbsolute(neighbours[i]).center();
  590. // For bottom/top directions select central point, but move it a bit away from true center to reduce zones allocated to them
  591. if (attackAvailability[6])
  592. testPoint[6] = (hexPositionAbsolute(neighbours[0]).center() + hexPositionAbsolute(neighbours[1]).center()) / 2 + Point(0, -5);
  593. if (attackAvailability[7])
  594. testPoint[7] = (hexPositionAbsolute(neighbours[3]).center() + hexPositionAbsolute(neighbours[4]).center()) / 2 + Point(0, 5);
  595. // Compute distance between tested position & cursor position and pick nearest
  596. std::array<int, 8> distance2;
  597. for (size_t i = 0; i < 8; ++i)
  598. if (attackAvailability[i])
  599. distance2[i] = (testPoint[i].y - currentAttackOriginPoint.y)*(testPoint[i].y - currentAttackOriginPoint.y) + (testPoint[i].x - currentAttackOriginPoint.x)*(testPoint[i].x - currentAttackOriginPoint.x);
  600. size_t nearest = -1;
  601. for (size_t i = 0; i < 8; ++i)
  602. if (attackAvailability[i] && (nearest == -1 || distance2[i] < distance2[nearest]) )
  603. nearest = i;
  604. assert(nearest != -1);
  605. return BattleHex::EDir(nearest);
  606. }
  607. BattleHex BattleFieldController::fromWhichHexAttack(BattleHex attackTarget)
  608. {
  609. BattleHex::EDir direction = selectAttackDirection(getHoveredHex());
  610. const CStack * attacker = owner.stacksController->getActiveStack();
  611. assert(direction != BattleHex::NONE);
  612. assert(attacker);
  613. if (!attacker->doubleWide())
  614. {
  615. assert(direction != BattleHex::BOTTOM);
  616. assert(direction != BattleHex::TOP);
  617. return attackTarget.cloneInDirection(direction);
  618. }
  619. else
  620. {
  621. // We need to find position of right hex of double-hex creature (or left for defending side)
  622. // | TOP_LEFT |TOP_RIGHT | RIGHT |BOTTOM_RIGHT|BOTTOM_LEFT| LEFT | TOP |BOTTOM
  623. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  624. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  625. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  626. switch (direction)
  627. {
  628. case BattleHex::TOP_LEFT:
  629. case BattleHex::LEFT:
  630. case BattleHex::BOTTOM_LEFT:
  631. {
  632. if ( attacker->unitSide() == BattleSide::ATTACKER )
  633. return attackTarget.cloneInDirection(direction);
  634. else
  635. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::LEFT);
  636. }
  637. case BattleHex::TOP_RIGHT:
  638. case BattleHex::RIGHT:
  639. case BattleHex::BOTTOM_RIGHT:
  640. {
  641. if ( attacker->unitSide() == BattleSide::ATTACKER )
  642. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::RIGHT);
  643. else
  644. return attackTarget.cloneInDirection(direction);
  645. }
  646. case BattleHex::TOP:
  647. {
  648. if ( attacker->unitSide() == BattleSide::ATTACKER )
  649. return attackTarget.cloneInDirection(BattleHex::TOP_RIGHT);
  650. else
  651. return attackTarget.cloneInDirection(BattleHex::TOP_LEFT);
  652. }
  653. case BattleHex::BOTTOM:
  654. {
  655. if ( attacker->unitSide() == BattleSide::ATTACKER )
  656. return attackTarget.cloneInDirection(BattleHex::BOTTOM_RIGHT);
  657. else
  658. return attackTarget.cloneInDirection(BattleHex::BOTTOM_LEFT);
  659. }
  660. default:
  661. assert(0);
  662. return BattleHex::INVALID;
  663. }
  664. }
  665. }
  666. bool BattleFieldController::isTileAttackable(const BattleHex & number) const
  667. {
  668. if(!number.isValid())
  669. return false;
  670. for (auto & elem : occupiableHexes)
  671. {
  672. if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
  673. return true;
  674. }
  675. return false;
  676. }
  677. void BattleFieldController::updateAccessibleHexes()
  678. {
  679. auto accessibility = owner.getBattle()->getAccessibility();
  680. for(int i = 0; i < accessibility.size(); i++)
  681. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE || (accessibility[i] == EAccessibility::SIDE_COLUMN));
  682. }
  683. bool BattleFieldController::stackCountOutsideHex(const BattleHex & number) const
  684. {
  685. return stackCountOutsideHexes[number.toInt()];
  686. }
  687. void BattleFieldController::showAll(Canvas & to)
  688. {
  689. show(to);
  690. }
  691. void BattleFieldController::tick(uint32_t msPassed)
  692. {
  693. updateAccessibleHexes();
  694. owner.stacksController->tick(msPassed);
  695. owner.obstacleController->tick(msPassed);
  696. owner.projectilesController->tick(msPassed);
  697. }
  698. void BattleFieldController::show(Canvas & to)
  699. {
  700. CSDL_Ext::CClipRectGuard guard(to.getInternalSurface(), pos);
  701. renderBattlefield(to);
  702. if (isActive() && isGesturing() && getHoveredHex() != BattleHex::INVALID)
  703. {
  704. auto combatCursorIndex = CCS->curh->get<Cursor::Combat>();
  705. if (combatCursorIndex)
  706. {
  707. auto combatImageIndex = static_cast<size_t>(*combatCursorIndex);
  708. to.draw(attackCursors->getImage(combatImageIndex), hexPositionAbsolute(getHoveredHex()).center() - CCS->curh->getPivotOffsetCombat(combatImageIndex));
  709. return;
  710. }
  711. auto spellCursorIndex = CCS->curh->get<Cursor::Spellcast>();
  712. if (spellCursorIndex)
  713. {
  714. auto spellImageIndex = static_cast<size_t>(*spellCursorIndex);
  715. to.draw(spellCursors->getImage(spellImageIndex), hexPositionAbsolute(getHoveredHex()).center() - CCS->curh->getPivotOffsetSpellcast());
  716. return;
  717. }
  718. }
  719. }
  720. bool BattleFieldController::receiveEvent(const Point & position, int eventType) const
  721. {
  722. if (eventType == HOVER)
  723. return true;
  724. return CIntObject::receiveEvent(position, eventType);
  725. }