BattleFieldController.cpp 28 KB

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