BattleFieldController.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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/Canvas.h"
  24. #include "../render/IImage.h"
  25. #include "../renderSDL/SDL_Extensions.h"
  26. #include "../gui/CGuiHandler.h"
  27. #include "../gui/CursorHandler.h"
  28. #include "../adventureMap/CInGameConsole.h"
  29. #include "../../CCallback.h"
  30. #include "../../lib/BattleFieldHandler.h"
  31. #include "../../lib/CConfigHandler.h"
  32. #include "../../lib/CStack.h"
  33. #include "../../lib/spells/ISpellMechanics.h"
  34. BattleFieldController::BattleFieldController(BattleInterface & owner):
  35. owner(owner)
  36. {
  37. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  38. strongInterest = true;
  39. //preparing cells and hexes
  40. cellBorder = IImage::createFromFile("CCELLGRD.BMP", EImageBlitMode::COLORKEY);
  41. cellShade = IImage::createFromFile("CCELLSHD.BMP");
  42. if(!owner.siegeController)
  43. {
  44. auto bfieldType = owner.curInt->cb->battleGetBattlefieldType();
  45. if(bfieldType == BattleField::NONE)
  46. logGlobal->error("Invalid battlefield returned for current battle");
  47. else
  48. background = IImage::createFromFile(bfieldType.getInfo()->graphics, EImageBlitMode::OPAQUE);
  49. }
  50. else
  51. {
  52. std::string backgroundName = owner.siegeController->getBattleBackgroundName();
  53. background = IImage::createFromFile(backgroundName, EImageBlitMode::OPAQUE);
  54. }
  55. pos.w = background->width();
  56. pos.h = background->height();
  57. backgroundWithHexes = std::make_unique<Canvas>(Point(background->width(), background->height()));
  58. updateAccessibleHexes();
  59. addUsedEvents(LCLICK | RCLICK | MOVE);
  60. LOCPLINT->cingconsole->pos = this->pos;
  61. }
  62. void BattleFieldController::createHeroes()
  63. {
  64. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  65. // create heroes as part of our constructor for correct positioning inside battlefield
  66. if(owner.attackingHeroInstance)
  67. owner.attackingHero = std::make_shared<BattleHero>(owner, owner.attackingHeroInstance, false);
  68. if(owner.defendingHeroInstance)
  69. owner.defendingHero = std::make_shared<BattleHero>(owner, owner.defendingHeroInstance, true);
  70. }
  71. void BattleFieldController::mouseMoved(const Point & cursorPosition)
  72. {
  73. if (!pos.isInside(cursorPosition))
  74. {
  75. owner.actionsController->onHoverEnded();
  76. return;
  77. }
  78. BattleHex selectedHex = getHoveredHex();
  79. owner.actionsController->onHexHovered(selectedHex);
  80. }
  81. void BattleFieldController::clickLeft(tribool down, bool previousState)
  82. {
  83. if(!down)
  84. {
  85. BattleHex selectedHex = getHoveredHex();
  86. if (selectedHex != BattleHex::INVALID)
  87. owner.actionsController->onHexLeftClicked(selectedHex);
  88. }
  89. }
  90. void BattleFieldController::clickRight(tribool down, bool previousState)
  91. {
  92. if(down)
  93. {
  94. BattleHex selectedHex = getHoveredHex();
  95. if (selectedHex != BattleHex::INVALID)
  96. owner.actionsController->onHexRightClicked(selectedHex);
  97. }
  98. }
  99. void BattleFieldController::renderBattlefield(Canvas & canvas)
  100. {
  101. Canvas clippedCanvas(canvas, pos);
  102. showBackground(clippedCanvas);
  103. BattleRenderer renderer(owner);
  104. renderer.execute(clippedCanvas);
  105. owner.projectilesController->showProjectiles(clippedCanvas);
  106. }
  107. void BattleFieldController::showBackground(Canvas & canvas)
  108. {
  109. if (owner.stacksController->getActiveStack() != nullptr ) //&& creAnims[stacksController->getActiveStack()->ID]->isIdle() //show everything with range
  110. showBackgroundImageWithHexes(canvas);
  111. else
  112. showBackgroundImage(canvas);
  113. showHighlightedHexes(canvas);
  114. }
  115. void BattleFieldController::showBackgroundImage(Canvas & canvas)
  116. {
  117. canvas.draw(background, Point(0, 0));
  118. owner.obstacleController->showAbsoluteObstacles(canvas);
  119. if ( owner.siegeController )
  120. owner.siegeController->showAbsoluteObstacles(canvas);
  121. if (settings["battle"]["cellBorders"].Bool())
  122. {
  123. for (int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  124. {
  125. if ( i % GameConstants::BFIELD_WIDTH == 0)
  126. continue;
  127. if ( i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  128. continue;
  129. canvas.draw(cellBorder, hexPositionLocal(i).topLeft());
  130. }
  131. }
  132. }
  133. void BattleFieldController::showBackgroundImageWithHexes(Canvas & canvas)
  134. {
  135. canvas.draw(*backgroundWithHexes.get(), Point(0, 0));
  136. }
  137. void BattleFieldController::redrawBackgroundWithHexes()
  138. {
  139. const CStack *activeStack = owner.stacksController->getActiveStack();
  140. std::vector<BattleHex> attackableHexes;
  141. if (activeStack)
  142. occupyableHexes = owner.curInt->cb->battleGetAvailableHexes(activeStack, true, &attackableHexes);
  143. //prepare background graphic with hexes and shaded hexes
  144. backgroundWithHexes->draw(background, Point(0,0));
  145. owner.obstacleController->showAbsoluteObstacles(*backgroundWithHexes);
  146. if ( owner.siegeController )
  147. owner.siegeController->showAbsoluteObstacles(*backgroundWithHexes);
  148. if (settings["battle"]["stackRange"].Bool())
  149. {
  150. std::vector<BattleHex> hexesToShade = occupyableHexes;
  151. hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
  152. for (BattleHex hex : hexesToShade)
  153. {
  154. backgroundWithHexes->draw(cellShade, hexPositionLocal(hex).topLeft());
  155. }
  156. }
  157. if(settings["battle"]["cellBorders"].Bool())
  158. {
  159. for (int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  160. {
  161. if ( i % GameConstants::BFIELD_WIDTH == 0)
  162. continue;
  163. if ( i % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1)
  164. continue;
  165. backgroundWithHexes->draw(cellBorder, hexPositionLocal(i).topLeft());
  166. }
  167. }
  168. }
  169. void BattleFieldController::showHighlightedHex(Canvas & canvas, BattleHex hex, bool darkBorder)
  170. {
  171. Point hexPos = hexPositionLocal(hex).topLeft();
  172. canvas.draw(cellShade, hexPos);
  173. if(!darkBorder && settings["battle"]["cellBorders"].Bool())
  174. canvas.draw(cellBorder, hexPos);
  175. }
  176. std::set<BattleHex> BattleFieldController::getHighlightedHexesStackRange()
  177. {
  178. std::set<BattleHex> result;
  179. if ( !owner.stacksController->getActiveStack())
  180. return result;
  181. if ( !settings["battle"]["stackRange"].Bool())
  182. return result;
  183. auto hoveredHex = getHoveredHex();
  184. std::set<BattleHex> set = owner.curInt->cb->battleGetAttackedHexes(owner.stacksController->getActiveStack(), hoveredHex, attackingHex);
  185. for(BattleHex hex : set)
  186. result.insert(hex);
  187. // display the movement shadow of stack under mouse
  188. const CStack * const hoveredStack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  189. if(hoveredStack && hoveredStack != owner.stacksController->getActiveStack())
  190. {
  191. std::vector<BattleHex> v = owner.curInt->cb->battleGetAvailableHexes(hoveredStack, true, nullptr);
  192. for(BattleHex hex : v)
  193. result.insert(hex);
  194. }
  195. return result;
  196. }
  197. std::set<BattleHex> BattleFieldController::getHighlightedHexesSpellRange()
  198. {
  199. std::set<BattleHex> result;
  200. auto hoveredHex = getHoveredHex();
  201. if(!settings["battle"]["mouseShadow"].Bool())
  202. return result;
  203. const spells::Caster *caster = nullptr;
  204. const CSpell *spell = nullptr;
  205. spells::Mode mode = owner.actionsController->getCurrentCastMode();
  206. spell = owner.actionsController->getCurrentSpell(hoveredHex);
  207. caster = owner.actionsController->getCurrentSpellcaster();
  208. if(caster && spell) //when casting spell
  209. {
  210. // printing shaded hex(es)
  211. spells::BattleCast event(owner.curInt->cb.get(), caster, mode, spell);
  212. auto shaded = spell->battleMechanics(&event)->rangeInHexes(hoveredHex);
  213. for(BattleHex shadedHex : shaded)
  214. {
  215. if((shadedHex.getX() != 0) && (shadedHex.getX() != GameConstants::BFIELD_WIDTH - 1))
  216. result.insert(shadedHex);
  217. }
  218. }
  219. return result;
  220. }
  221. std::set<BattleHex> BattleFieldController::getHighlightedHexesMovementTarget()
  222. {
  223. const CStack * stack = owner.stacksController->getActiveStack();
  224. auto hoveredHex = getHoveredHex();
  225. if (stack)
  226. {
  227. std::vector<BattleHex> v = owner.curInt->cb->battleGetAvailableHexes(stack, false, nullptr);
  228. auto hoveredStack = owner.curInt->cb->battleGetStackByPos(hoveredHex, true);
  229. if(owner.curInt->cb->battleCanAttack(stack, hoveredStack, hoveredHex))
  230. {
  231. if (isTileAttackable(hoveredHex))
  232. {
  233. BattleHex attackFromHex = fromWhichHexAttack(hoveredHex);
  234. if (stack->doubleWide())
  235. return {attackFromHex, stack->occupiedHex(attackFromHex)};
  236. else
  237. return {attackFromHex};
  238. }
  239. }
  240. if (vstd::contains(v,hoveredHex))
  241. {
  242. if (stack->doubleWide())
  243. return {hoveredHex, stack->occupiedHex(hoveredHex)};
  244. else
  245. return {hoveredHex};
  246. }
  247. if (stack->doubleWide())
  248. {
  249. for (auto const & hex : v)
  250. {
  251. if (stack->occupiedHex(hex) == hoveredHex)
  252. return { hoveredHex, hex };
  253. }
  254. }
  255. }
  256. return {};
  257. }
  258. void BattleFieldController::showHighlightedHexes(Canvas & canvas)
  259. {
  260. std::set<BattleHex> hoveredStack = getHighlightedHexesStackRange();
  261. std::set<BattleHex> hoveredSpell = getHighlightedHexesSpellRange();
  262. std::set<BattleHex> hoveredMove = getHighlightedHexesMovementTarget();
  263. if (getHoveredHex() == BattleHex::INVALID)
  264. return;
  265. auto const & hoveredMouse = owner.actionsController->currentActionSpellcasting(getHoveredHex()) ? hoveredSpell : hoveredMove;
  266. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  267. {
  268. bool stack = hoveredStack.count(b);
  269. bool mouse = hoveredMouse.count(b);
  270. if ( stack && mouse )
  271. {
  272. // area where enemy stack can move AND affected by mouse cursor - create darker highlight by blitting twice
  273. showHighlightedHex(canvas, b, true);
  274. showHighlightedHex(canvas, b, true);
  275. }
  276. if ( !stack && mouse )
  277. {
  278. showHighlightedHex(canvas, b, true);
  279. }
  280. if ( stack && !mouse )
  281. {
  282. showHighlightedHex(canvas, b, false);
  283. }
  284. }
  285. }
  286. Rect BattleFieldController::hexPositionLocal(BattleHex hex) const
  287. {
  288. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX();
  289. int y = 86 + 42 *hex.getY();
  290. int w = cellShade->width();
  291. int h = cellShade->height();
  292. return Rect(x, y, w, h);
  293. }
  294. Rect BattleFieldController::hexPositionAbsolute(BattleHex hex) const
  295. {
  296. return hexPositionLocal(hex) + pos.topLeft();
  297. }
  298. bool BattleFieldController::isPixelInHex(Point const & position)
  299. {
  300. return !cellShade->isTransparent(position);
  301. }
  302. BattleHex BattleFieldController::getHoveredHex()
  303. {
  304. Point hoverPos = GH.getCursorPosition();
  305. if (owner.attackingHero)
  306. {
  307. if (owner.attackingHero->pos.isInside(hoverPos))
  308. return BattleHex::HERO_ATTACKER;
  309. }
  310. if (owner.defendingHero)
  311. {
  312. if (owner.attackingHero->pos.isInside(hoverPos))
  313. return BattleHex::HERO_DEFENDER;
  314. }
  315. for (int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  316. {
  317. Rect hexPosition = hexPositionAbsolute(h);
  318. if (!hexPosition.isInside(hoverPos))
  319. continue;
  320. if (isPixelInHex(hoverPos - hexPosition.topLeft()))
  321. return h;
  322. }
  323. return BattleHex::INVALID;
  324. }
  325. void BattleFieldController::setBattleCursor(BattleHex myNumber)
  326. {
  327. Point cursorPos = CCS->curh->position();
  328. std::vector<Cursor::Combat> sectorCursor = {
  329. Cursor::Combat::HIT_SOUTHEAST,
  330. Cursor::Combat::HIT_SOUTHWEST,
  331. Cursor::Combat::HIT_WEST,
  332. Cursor::Combat::HIT_NORTHWEST,
  333. Cursor::Combat::HIT_NORTHEAST,
  334. Cursor::Combat::HIT_EAST,
  335. Cursor::Combat::HIT_SOUTH,
  336. Cursor::Combat::HIT_NORTH,
  337. };
  338. auto direction = static_cast<size_t>(selectAttackDirection(myNumber, cursorPos));
  339. assert(direction != -1);
  340. if (direction != -1)
  341. CCS->curh->set(sectorCursor[direction]);
  342. }
  343. BattleHex::EDir BattleFieldController::selectAttackDirection(BattleHex myNumber, const Point & cursorPos)
  344. {
  345. const bool doubleWide = owner.stacksController->getActiveStack()->doubleWide();
  346. auto neighbours = myNumber.allNeighbouringTiles();
  347. // 0 1
  348. // 5 x 2
  349. // 4 3
  350. // if true - our current stack can move into this hex (and attack)
  351. std::array<bool, 8> attackAvailability;
  352. if (doubleWide)
  353. {
  354. // For double-hexes we need to ensure that both hexes needed for this direction are occupyable:
  355. // | -0- | -1- | -2- | -3- | -4- | -5- | -6- | -7-
  356. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  357. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  358. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  359. for (size_t i : { 1, 2, 3})
  360. attackAvailability[i] = vstd::contains(occupyableHexes, neighbours[i]) && vstd::contains(occupyableHexes, neighbours[i].cloneInDirection(BattleHex::RIGHT, false));
  361. for (size_t i : { 4, 5, 0})
  362. attackAvailability[i] = vstd::contains(occupyableHexes, neighbours[i]) && vstd::contains(occupyableHexes, neighbours[i].cloneInDirection(BattleHex::LEFT, false));
  363. attackAvailability[6] = vstd::contains(occupyableHexes, neighbours[0]) && vstd::contains(occupyableHexes, neighbours[1]);
  364. attackAvailability[7] = vstd::contains(occupyableHexes, neighbours[3]) && vstd::contains(occupyableHexes, neighbours[4]);
  365. }
  366. else
  367. {
  368. for (size_t i = 0; i < 6; ++i)
  369. attackAvailability[i] = vstd::contains(occupyableHexes, neighbours[i]);
  370. attackAvailability[6] = false;
  371. attackAvailability[7] = false;
  372. }
  373. // Zero available tiles to attack from
  374. if ( vstd::find(attackAvailability, true) == attackAvailability.end())
  375. {
  376. logGlobal->error("Error: cannot find a hex to attack hex %d from!", myNumber);
  377. return BattleHex::NONE;
  378. }
  379. // For each valid direction, select position to test against
  380. std::array<Point, 8> testPoint;
  381. for (size_t i = 0; i < 6; ++i)
  382. if (attackAvailability[i])
  383. testPoint[i] = hexPositionAbsolute(neighbours[i]).center();
  384. // For bottom/top directions select central point, but move it a bit away from true center to reduce zones allocated to them
  385. if (attackAvailability[6])
  386. testPoint[6] = (hexPositionAbsolute(neighbours[0]).center() + hexPositionAbsolute(neighbours[1]).center()) / 2 + Point(0, -5);
  387. if (attackAvailability[7])
  388. testPoint[7] = (hexPositionAbsolute(neighbours[3]).center() + hexPositionAbsolute(neighbours[4]).center()) / 2 + Point(0, 5);
  389. // Compute distance between tested position & cursor position and pick nearest
  390. std::array<int, 8> distance2;
  391. for (size_t i = 0; i < 8; ++i)
  392. if (attackAvailability[i])
  393. distance2[i] = (testPoint[i].y - cursorPos.y)*(testPoint[i].y - cursorPos.y) + (testPoint[i].x - cursorPos.x)*(testPoint[i].x - cursorPos.x);
  394. size_t nearest = -1;
  395. for (size_t i = 0; i < 8; ++i)
  396. if (attackAvailability[i] && (nearest == -1 || distance2[i] < distance2[nearest]) )
  397. nearest = i;
  398. assert(nearest != -1);
  399. return BattleHex::EDir(nearest);
  400. }
  401. BattleHex BattleFieldController::fromWhichHexAttack(BattleHex attackTarget)
  402. {
  403. BattleHex::EDir direction = selectAttackDirection(attackTarget, CCS->curh->position());
  404. const CStack * attacker = owner.stacksController->getActiveStack();
  405. assert(direction != BattleHex::NONE);
  406. assert(attacker);
  407. if (!attacker->doubleWide())
  408. {
  409. assert(direction != BattleHex::BOTTOM);
  410. assert(direction != BattleHex::TOP);
  411. return attackTarget.cloneInDirection(direction);
  412. }
  413. else
  414. {
  415. // We need to find position of right hex of double-hex creature (or left for defending side)
  416. // | TOP_LEFT |TOP_RIGHT | RIGHT |BOTTOM_RIGHT|BOTTOM_LEFT| LEFT | TOP |BOTTOM
  417. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  418. // | - x - | - x - | - x o o| - x - | - x - |o o x - | - x - | - x -
  419. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  420. switch (direction)
  421. {
  422. case BattleHex::TOP_LEFT:
  423. case BattleHex::LEFT:
  424. case BattleHex::BOTTOM_LEFT:
  425. {
  426. if ( attacker->side == BattleSide::ATTACKER )
  427. return attackTarget.cloneInDirection(direction);
  428. else
  429. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::LEFT);
  430. }
  431. case BattleHex::TOP_RIGHT:
  432. case BattleHex::RIGHT:
  433. case BattleHex::BOTTOM_RIGHT:
  434. {
  435. if ( attacker->side == BattleSide::ATTACKER )
  436. return attackTarget.cloneInDirection(direction).cloneInDirection(BattleHex::RIGHT);
  437. else
  438. return attackTarget.cloneInDirection(direction);
  439. }
  440. case BattleHex::TOP:
  441. {
  442. if ( attacker->side == BattleSide::ATTACKER )
  443. return attackTarget.cloneInDirection(BattleHex::TOP_RIGHT);
  444. else
  445. return attackTarget.cloneInDirection(BattleHex::TOP_LEFT);
  446. }
  447. case BattleHex::BOTTOM:
  448. {
  449. if ( attacker->side == BattleSide::ATTACKER )
  450. return attackTarget.cloneInDirection(BattleHex::BOTTOM_RIGHT);
  451. else
  452. return attackTarget.cloneInDirection(BattleHex::BOTTOM_LEFT);
  453. }
  454. default:
  455. assert(0);
  456. return BattleHex::INVALID;
  457. }
  458. }
  459. }
  460. bool BattleFieldController::isTileAttackable(const BattleHex & number) const
  461. {
  462. for (auto & elem : occupyableHexes)
  463. {
  464. if (BattleHex::mutualPosition(elem, number) != -1 || elem == number)
  465. return true;
  466. }
  467. return false;
  468. }
  469. void BattleFieldController::updateAccessibleHexes()
  470. {
  471. auto accessibility = owner.curInt->cb->getAccesibility();
  472. for(int i = 0; i < accessibility.size(); i++)
  473. stackCountOutsideHexes[i] = (accessibility[i] == EAccessibility::ACCESSIBLE || (accessibility[i] == EAccessibility::SIDE_COLUMN));
  474. }
  475. bool BattleFieldController::stackCountOutsideHex(const BattleHex & number) const
  476. {
  477. return stackCountOutsideHexes[number];
  478. }
  479. void BattleFieldController::showAll(SDL_Surface * to)
  480. {
  481. show(to);
  482. }
  483. void BattleFieldController::show(SDL_Surface * to)
  484. {
  485. updateAccessibleHexes();
  486. owner.stacksController->update();
  487. owner.obstacleController->update();
  488. Canvas canvas(to);
  489. CSDL_Ext::CClipRectGuard guard(to, pos);
  490. renderBattlefield(canvas);
  491. }