BattleFieldController.cpp 30 KB

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