BattleFieldController.cpp 31 KB

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