BattleInfo.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. /*
  2. * BattleInfo.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 "BattleInfo.h"
  12. #include "BattleLayout.h"
  13. #include "CObstacleInstance.h"
  14. #include "bonuses/Limiters.h"
  15. #include "bonuses/Updaters.h"
  16. #include "../CStack.h"
  17. #include "../entities/building/TownFortifications.h"
  18. #include "../filesystem/Filesystem.h"
  19. #include "../mapObjects/CGTownInstance.h"
  20. #include "../texts/CGeneralTextHandler.h"
  21. #include "../BattleFieldHandler.h"
  22. #include "../ObstacleHandler.h"
  23. #include <vstd/RNG.h>
  24. //TODO: remove
  25. #include "../IGameCallback.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. const SideInBattle & BattleInfo::getSide(BattleSide side) const
  28. {
  29. return sides.at(side);
  30. }
  31. SideInBattle & BattleInfo::getSide(BattleSide side)
  32. {
  33. return sides.at(side);
  34. }
  35. ///BattleInfo
  36. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackInstance & base, BattleSide side, const SlotID & slot, BattleHex position)
  37. {
  38. PlayerColor owner = getSide(side).color;
  39. assert(!owner.isValidPlayer() || (base.armyObj && base.armyObj->tempOwner == owner));
  40. auto * ret = new CStack(&base, owner, id, side, slot);
  41. ret->initialPosition = getAvailableHex(base.getCreatureID(), side, position); //TODO: what if no free tile on battlefield was found?
  42. stacks.push_back(ret);
  43. return ret;
  44. }
  45. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackBasicDescriptor & base, BattleSide side, const SlotID & slot, BattleHex position)
  46. {
  47. PlayerColor owner = getSide(side).color;
  48. auto * ret = new CStack(&base, owner, id, side, slot);
  49. ret->initialPosition = position;
  50. stacks.push_back(ret);
  51. return ret;
  52. }
  53. void BattleInfo::localInit()
  54. {
  55. for(BattleSide i : { BattleSide::ATTACKER, BattleSide::DEFENDER})
  56. {
  57. auto * armyObj = battleGetArmyObject(i);
  58. armyObj->battle = this;
  59. armyObj->attachTo(*this);
  60. }
  61. for(CStack * s : stacks)
  62. s->localInit(this);
  63. exportBonuses();
  64. }
  65. //RNG that works like H3 one
  66. struct RandGen
  67. {
  68. ui32 seed;
  69. void srand(ui32 s)
  70. {
  71. seed = s;
  72. }
  73. void srand(const int3 & pos)
  74. {
  75. srand(110291 * static_cast<ui32>(pos.x) + 167801 * static_cast<ui32>(pos.y) + 81569);
  76. }
  77. int rand()
  78. {
  79. seed = 214013 * seed + 2531011;
  80. return (seed >> 16) & 0x7FFF;
  81. }
  82. int rand(int min, int max)
  83. {
  84. if(min == max)
  85. return min;
  86. if(min > max)
  87. return min;
  88. return min + rand() % (max - min + 1);
  89. }
  90. };
  91. struct RangeGenerator
  92. {
  93. class ExhaustedPossibilities : public std::exception
  94. {
  95. };
  96. RangeGenerator(int _min, int _max, std::function<int()> _myRand):
  97. min(_min),
  98. remainingCount(_max - _min + 1),
  99. remaining(remainingCount, true),
  100. myRand(std::move(_myRand))
  101. {
  102. }
  103. int generateNumber() const
  104. {
  105. if(!remainingCount)
  106. throw ExhaustedPossibilities();
  107. if(remainingCount == 1)
  108. return 0;
  109. return myRand() % remainingCount;
  110. }
  111. //get number fulfilling predicate. Never gives the same number twice.
  112. int getSuchNumber(const std::function<bool(int)> & goodNumberPred = nullptr)
  113. {
  114. int ret = -1;
  115. do
  116. {
  117. int n = generateNumber();
  118. int i = 0;
  119. for(;;i++)
  120. {
  121. assert(i < (int)remaining.size());
  122. if(!remaining[i])
  123. continue;
  124. if(!n)
  125. break;
  126. n--;
  127. }
  128. remainingCount--;
  129. remaining[i] = false;
  130. ret = i + min;
  131. } while(goodNumberPred && !goodNumberPred(ret));
  132. return ret;
  133. }
  134. int min;
  135. int remainingCount;
  136. std::vector<bool> remaining;
  137. std::function<int()> myRand;
  138. };
  139. BattleInfo * BattleInfo::setupBattle(const int3 & tile, TerrainId terrain, const BattleField & battlefieldType, BattleSideArray<const CArmedInstance *> armies, BattleSideArray<const CGHeroInstance *> heroes, const BattleLayout & layout, const CGTownInstance * town)
  140. {
  141. CMP_stack cmpst;
  142. auto * curB = new BattleInfo(layout);
  143. for(auto i : { BattleSide::LEFT_SIDE, BattleSide::RIGHT_SIDE})
  144. curB->sides[i].init(heroes[i], armies[i]);
  145. std::vector<CStack*> & stacks = (curB->stacks);
  146. curB->tile = tile;
  147. curB->battlefieldType = battlefieldType;
  148. curB->round = -2;
  149. curB->activeStack = -1;
  150. curB->replayAllowed = false;
  151. if(town)
  152. {
  153. curB->town = town;
  154. curB->terrainType = town->getNativeTerrain();
  155. }
  156. else
  157. {
  158. curB->town = nullptr;
  159. curB->terrainType = terrain;
  160. }
  161. //setting up siege obstacles
  162. if (town && town->fortificationsLevel().wallsHealth != 0)
  163. {
  164. auto fortification = town->fortificationsLevel();
  165. curB->si.gateState = EGateState::CLOSED;
  166. curB->si.wallState[EWallPart::GATE] = EWallState::INTACT;
  167. for(const auto wall : {EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL})
  168. curB->si.wallState[wall] = static_cast<EWallState>(fortification.wallsHealth);
  169. if (fortification.citadelHealth != 0)
  170. curB->si.wallState[EWallPart::KEEP] = static_cast<EWallState>(fortification.citadelHealth);
  171. if (fortification.upperTowerHealth != 0)
  172. curB->si.wallState[EWallPart::UPPER_TOWER] = static_cast<EWallState>(fortification.upperTowerHealth);
  173. if (fortification.lowerTowerHealth != 0)
  174. curB->si.wallState[EWallPart::BOTTOM_TOWER] = static_cast<EWallState>(fortification.lowerTowerHealth);
  175. }
  176. //randomize obstacles
  177. if (layout.obstaclesAllowed && !town)
  178. {
  179. RandGen r{};
  180. auto ourRand = [&](){ return r.rand(); };
  181. r.srand(tile);
  182. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  183. int tilesToBlock = r.rand(5,12);
  184. std::vector<BattleHex> blockedTiles;
  185. auto appropriateAbsoluteObstacle = [&](int id)
  186. {
  187. const auto * info = Obstacle(id).getInfo();
  188. return info && info->isAbsoluteObstacle && info->isAppropriate(curB->terrainType, battlefieldType);
  189. };
  190. auto appropriateUsualObstacle = [&](int id)
  191. {
  192. const auto * info = Obstacle(id).getInfo();
  193. return info && !info->isAbsoluteObstacle && info->isAppropriate(curB->terrainType, battlefieldType);
  194. };
  195. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  196. {
  197. try
  198. {
  199. RangeGenerator obidgen(0, VLC->obstacleHandler->size() - 1, ourRand);
  200. auto obstPtr = std::make_shared<CObstacleInstance>();
  201. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  202. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  203. obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
  204. curB->obstacles.push_back(obstPtr);
  205. for(BattleHex blocked : obstPtr->getBlockedTiles())
  206. blockedTiles.push_back(blocked);
  207. tilesToBlock -= Obstacle(obstPtr->ID).getInfo()->blockedTiles.size() / 2;
  208. }
  209. catch(RangeGenerator::ExhaustedPossibilities &)
  210. {
  211. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  212. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occurred - cannot place absolute obstacle");
  213. }
  214. }
  215. try
  216. {
  217. while(tilesToBlock > 0)
  218. {
  219. RangeGenerator obidgen(0, VLC->obstacleHandler->size() - 1, ourRand);
  220. auto tileAccessibility = curB->getAccessibility();
  221. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  222. const ObstacleInfo &obi = *Obstacle(obid).getInfo();
  223. auto validPosition = [&](BattleHex pos) -> bool
  224. {
  225. if(obi.height >= pos.getY())
  226. return false;
  227. if(pos.getX() == 0)
  228. return false;
  229. if(pos.getX() + obi.width > 15)
  230. return false;
  231. if(vstd::contains(blockedTiles, pos))
  232. return false;
  233. for(BattleHex blocked : obi.getBlocked(pos))
  234. {
  235. if(tileAccessibility[blocked] == EAccessibility::UNAVAILABLE) //for ship-to-ship battlefield - exclude hardcoded unavailable tiles
  236. return false;
  237. if(vstd::contains(blockedTiles, blocked))
  238. return false;
  239. int x = blocked.getX();
  240. if(x <= 2 || x >= 14)
  241. return false;
  242. }
  243. return true;
  244. };
  245. RangeGenerator posgenerator(18, 168, ourRand);
  246. auto obstPtr = std::make_shared<CObstacleInstance>();
  247. obstPtr->ID = obid;
  248. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  249. obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
  250. curB->obstacles.push_back(obstPtr);
  251. for(BattleHex blocked : obstPtr->getBlockedTiles())
  252. blockedTiles.push_back(blocked);
  253. tilesToBlock -= static_cast<int>(obi.blockedTiles.size());
  254. }
  255. }
  256. catch(RangeGenerator::ExhaustedPossibilities &)
  257. {
  258. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occurred - cannot place usual obstacle");
  259. }
  260. }
  261. //adding war machines
  262. //Checks if hero has artifact and create appropriate stack
  263. auto handleWarMachine = [&](BattleSide side, const ArtifactPosition & artslot, BattleHex hex)
  264. {
  265. const CArtifactInstance * warMachineArt = heroes[side]->getArt(artslot);
  266. if(nullptr != warMachineArt && hex.isValid())
  267. {
  268. CreatureID cre = warMachineArt->artType->getWarMachine();
  269. if(cre != CreatureID::NONE)
  270. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(cre, 1), side, SlotID::WAR_MACHINES_SLOT, hex);
  271. }
  272. };
  273. if(heroes[BattleSide::ATTACKER])
  274. {
  275. auto warMachineHexes = layout.warMachines.at(BattleSide::ATTACKER);
  276. handleWarMachine(BattleSide::ATTACKER, ArtifactPosition::MACH1, warMachineHexes.at(0));
  277. handleWarMachine(BattleSide::ATTACKER, ArtifactPosition::MACH2, warMachineHexes.at(1));
  278. handleWarMachine(BattleSide::ATTACKER, ArtifactPosition::MACH3, warMachineHexes.at(2));
  279. if(town && town->fortificationsLevel().wallsHealth > 0)
  280. handleWarMachine(BattleSide::ATTACKER, ArtifactPosition::MACH4, warMachineHexes.at(3));
  281. }
  282. if(heroes[BattleSide::DEFENDER])
  283. {
  284. auto warMachineHexes = layout.warMachines.at(BattleSide::DEFENDER);
  285. if(!town) //defending hero shouldn't receive ballista (bug #551)
  286. handleWarMachine(BattleSide::DEFENDER, ArtifactPosition::MACH1, warMachineHexes.at(0));
  287. handleWarMachine(BattleSide::DEFENDER, ArtifactPosition::MACH2, warMachineHexes.at(1));
  288. handleWarMachine(BattleSide::DEFENDER, ArtifactPosition::MACH3, warMachineHexes.at(2));
  289. }
  290. //war machines added
  291. //battleStartpos read
  292. for(BattleSide side : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  293. {
  294. int formationNo = armies[side]->stacksCount() - 1;
  295. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  296. int k = 0; //stack serial
  297. for(auto i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  298. {
  299. const BattleHex & pos = layout.units.at(side).at(k);
  300. if (pos.isValid())
  301. curB->generateNewStack(curB->nextUnitId(), *i->second, side, i->first, pos);
  302. }
  303. }
  304. //adding commanders
  305. for(BattleSide i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  306. {
  307. if (heroes[i] && heroes[i]->commander && heroes[i]->commander->alive)
  308. {
  309. curB->generateNewStack(curB->nextUnitId(), *heroes[i]->commander, i, SlotID::COMMANDER_SLOT_PLACEHOLDER, layout.commanders.at(i));
  310. }
  311. }
  312. if (curB->town)
  313. {
  314. if (curB->town->fortificationsLevel().citadelHealth != 0)
  315. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_CENTRAL_TOWER);
  316. if (curB->town->fortificationsLevel().upperTowerHealth != 0)
  317. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_UPPER_TOWER);
  318. if (curB->town->fortificationsLevel().lowerTowerHealth != 0)
  319. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_BOTTOM_TOWER);
  320. //Moat generating is done on server
  321. }
  322. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  323. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  324. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  325. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  326. const auto * bgInfo = VLC->battlefields()->getById(battlefieldType);
  327. for(const std::shared_ptr<Bonus> & bonus : bgInfo->bonuses)
  328. {
  329. curB->addNewBonus(bonus);
  330. }
  331. //native terrain bonuses
  332. auto nativeTerrain = std::make_shared<CreatureTerrainLimiter>();
  333. curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::STACKS_SPEED, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID())->addLimiter(nativeTerrain));
  334. curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::ATTACK))->addLimiter(nativeTerrain));
  335. curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE))->addLimiter(nativeTerrain));
  336. //////////////////////////////////////////////////////////////////////////
  337. //tactics
  338. BattleSideArray<int> battleRepositionHex = {};
  339. BattleSideArray<int> battleRepositionHexBlock = {};
  340. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  341. {
  342. if(heroes[i])
  343. {
  344. battleRepositionHex[i] += heroes[i]->valOfBonuses(Selector::type()(BonusType::BEFORE_BATTLE_REPOSITION));
  345. battleRepositionHexBlock[i] += heroes[i]->valOfBonuses(Selector::type()(BonusType::BEFORE_BATTLE_REPOSITION_BLOCK));
  346. }
  347. }
  348. int tacticsSkillDiffAttacker = battleRepositionHex[BattleSide::ATTACKER] - battleRepositionHexBlock[BattleSide::DEFENDER];
  349. int tacticsSkillDiffDefender = battleRepositionHex[BattleSide::DEFENDER] - battleRepositionHexBlock[BattleSide::ATTACKER];
  350. /* for current tactics, we need to choose one side, so, we will choose side when first - second > 0, and ignore sides
  351. when first - second <= 0. If there will be situations when both > 0, attacker will be chosen. Anyway, in OH3 this
  352. will not happen because tactics block opposite tactics on same value.
  353. TODO: For now, it is an error to use BEFORE_BATTLE_REPOSITION bonus without counterpart, but it can be changed if
  354. double tactics will be implemented.
  355. */
  356. if(layout.tacticsAllowed)
  357. {
  358. if(tacticsSkillDiffAttacker > 0 && tacticsSkillDiffDefender > 0)
  359. logGlobal->warn("Double tactics is not implemented, only attacker will have tactics!");
  360. if(tacticsSkillDiffAttacker > 0)
  361. {
  362. curB->tacticsSide = BattleSide::ATTACKER;
  363. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  364. curB->tacticDistance = 1 + tacticsSkillDiffAttacker;
  365. }
  366. else if(tacticsSkillDiffDefender > 0)
  367. {
  368. curB->tacticsSide = BattleSide::DEFENDER;
  369. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  370. curB->tacticDistance = 1 + tacticsSkillDiffDefender;
  371. }
  372. else
  373. curB->tacticDistance = 0;
  374. }
  375. return curB;
  376. }
  377. const CGHeroInstance * BattleInfo::getHero(const PlayerColor & player) const
  378. {
  379. for(const auto & side : sides)
  380. if(side.color == player)
  381. return side.hero;
  382. logGlobal->error("Player %s is not in battle!", player.toString());
  383. return nullptr;
  384. }
  385. BattleSide BattleInfo::whatSide(const PlayerColor & player) const
  386. {
  387. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  388. if(sides[i].color == player)
  389. return i;
  390. logGlobal->warn("BattleInfo::whatSide: Player %s is not in battle!", player.toString());
  391. return BattleSide::NONE;
  392. }
  393. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  394. {
  395. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  396. }
  397. BattleInfo::BattleInfo(const BattleLayout & layout):
  398. BattleInfo()
  399. {
  400. *this->layout = layout;
  401. }
  402. BattleInfo::BattleInfo():
  403. layout(std::make_unique<BattleLayout>()),
  404. round(-1),
  405. activeStack(-1),
  406. town(nullptr),
  407. tile(-1,-1,-1),
  408. battlefieldType(BattleField::NONE),
  409. tacticsSide(BattleSide::NONE),
  410. tacticDistance(0)
  411. {
  412. setNodeType(BATTLE);
  413. }
  414. BattleLayout BattleInfo::getLayout() const
  415. {
  416. return *layout;
  417. }
  418. BattleID BattleInfo::getBattleID() const
  419. {
  420. return battleID;
  421. }
  422. const IBattleInfo * BattleInfo::getBattle() const
  423. {
  424. return this;
  425. }
  426. std::optional<PlayerColor> BattleInfo::getPlayerID() const
  427. {
  428. return std::nullopt;
  429. }
  430. BattleInfo::~BattleInfo()
  431. {
  432. for (auto & elem : stacks)
  433. delete elem;
  434. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  435. if(auto * _armyObj = battleGetArmyObject(i))
  436. _armyObj->battle = nullptr;
  437. }
  438. int32_t BattleInfo::getActiveStackID() const
  439. {
  440. return activeStack;
  441. }
  442. TStacks BattleInfo::getStacksIf(const TStackFilter & predicate) const
  443. {
  444. TStacks ret;
  445. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  446. return ret;
  447. }
  448. battle::Units BattleInfo::getUnitsIf(const battle::UnitFilter & predicate) const
  449. {
  450. battle::Units ret;
  451. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  452. return ret;
  453. }
  454. BattleField BattleInfo::getBattlefieldType() const
  455. {
  456. return battlefieldType;
  457. }
  458. TerrainId BattleInfo::getTerrainType() const
  459. {
  460. return terrainType;
  461. }
  462. IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
  463. {
  464. ObstacleCList ret;
  465. for(const auto & obstacle : obstacles)
  466. ret.push_back(obstacle);
  467. return ret;
  468. }
  469. PlayerColor BattleInfo::getSidePlayer(BattleSide side) const
  470. {
  471. return getSide(side).color;
  472. }
  473. const CArmedInstance * BattleInfo::getSideArmy(BattleSide side) const
  474. {
  475. return getSide(side).armyObject;
  476. }
  477. const CGHeroInstance * BattleInfo::getSideHero(BattleSide side) const
  478. {
  479. return getSide(side).hero;
  480. }
  481. uint8_t BattleInfo::getTacticDist() const
  482. {
  483. return tacticDistance;
  484. }
  485. BattleSide BattleInfo::getTacticsSide() const
  486. {
  487. return tacticsSide;
  488. }
  489. const CGTownInstance * BattleInfo::getDefendedTown() const
  490. {
  491. return town;
  492. }
  493. EWallState BattleInfo::getWallState(EWallPart partOfWall) const
  494. {
  495. return si.wallState.at(partOfWall);
  496. }
  497. EGateState BattleInfo::getGateState() const
  498. {
  499. return si.gateState;
  500. }
  501. uint32_t BattleInfo::getCastSpells(BattleSide side) const
  502. {
  503. return getSide(side).castSpellsCount;
  504. }
  505. int32_t BattleInfo::getEnchanterCounter(BattleSide side) const
  506. {
  507. return getSide(side).enchanterCounter;
  508. }
  509. const IBonusBearer * BattleInfo::getBonusBearer() const
  510. {
  511. return this;
  512. }
  513. int64_t BattleInfo::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  514. {
  515. if(damage.min != damage.max)
  516. {
  517. int64_t sum = 0;
  518. auto howManyToAv = std::min<int32_t>(10, attackerCount);
  519. for(int32_t g = 0; g < howManyToAv; ++g)
  520. sum += rng.nextInt64(damage.min, damage.max);
  521. return sum / howManyToAv;
  522. }
  523. else
  524. {
  525. return damage.min;
  526. }
  527. }
  528. int3 BattleInfo::getLocation() const
  529. {
  530. return tile;
  531. }
  532. std::vector<SpellID> BattleInfo::getUsedSpells(BattleSide side) const
  533. {
  534. return getSide(side).usedSpellsHistory;
  535. }
  536. void BattleInfo::nextRound()
  537. {
  538. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  539. {
  540. sides.at(i).castSpellsCount = 0;
  541. vstd::amax(--sides.at(i).enchanterCounter, 0);
  542. }
  543. round += 1;
  544. for(CStack * s : stacks)
  545. {
  546. // new turn effects
  547. s->reduceBonusDurations(Bonus::NTurns);
  548. s->afterNewRound();
  549. }
  550. for(auto & obst : obstacles)
  551. obst->battleTurnPassed();
  552. }
  553. void BattleInfo::nextTurn(uint32_t unitId)
  554. {
  555. activeStack = unitId;
  556. CStack * st = getStack(activeStack);
  557. //remove bonuses that last until when stack gets new turn
  558. st->removeBonusesRecursive(Bonus::UntilGetsTurn);
  559. st->afterGetsTurn();
  560. }
  561. void BattleInfo::addUnit(uint32_t id, const JsonNode & data)
  562. {
  563. battle::UnitInfo info;
  564. info.load(id, data);
  565. CStackBasicDescriptor base(info.type, info.count);
  566. PlayerColor owner = getSidePlayer(info.side);
  567. auto * ret = new CStack(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  568. ret->initialPosition = info.position;
  569. stacks.push_back(ret);
  570. ret->localInit(this);
  571. ret->summoned = info.summoned;
  572. }
  573. void BattleInfo::moveUnit(uint32_t id, BattleHex destination)
  574. {
  575. auto * sta = getStack(id);
  576. if(!sta)
  577. {
  578. logGlobal->error("Cannot find stack %d", id);
  579. return;
  580. }
  581. sta->position = destination;
  582. //Bonuses can be limited by unit placement, so, change tree version
  583. //to force updating a bonus. TODO: update version only when such bonuses are present
  584. CBonusSystemNode::treeHasChanged();
  585. }
  586. void BattleInfo::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  587. {
  588. CStack * changedStack = getStack(id, false);
  589. if(!changedStack)
  590. throw std::runtime_error("Invalid unit id in BattleInfo update");
  591. if(!changedStack->alive() && healthDelta > 0)
  592. {
  593. //checking if we resurrect a stack that is under a living stack
  594. auto accessibility = getAccessibility();
  595. if(!accessibility.accessible(changedStack->getPosition(), changedStack))
  596. {
  597. logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->getPosition().hex);
  598. return; //position is already occupied
  599. }
  600. }
  601. bool killed = (-healthDelta) >= changedStack->getAvailableHealth();//todo: check using alive state once rebirth will be handled separately
  602. bool resurrected = !changedStack->alive() && healthDelta > 0;
  603. //applying changes
  604. changedStack->load(data);
  605. if(healthDelta < 0)
  606. {
  607. changedStack->removeBonusesRecursive(Bonus::UntilBeingAttacked);
  608. }
  609. resurrected = resurrected || (killed && changedStack->alive());
  610. if(killed)
  611. {
  612. if(changedStack->cloneID >= 0)
  613. {
  614. //remove clone as well
  615. CStack * clone = getStack(changedStack->cloneID);
  616. if(clone)
  617. clone->makeGhost();
  618. changedStack->cloneID = -1;
  619. }
  620. }
  621. if(resurrected || killed)
  622. {
  623. //removing all spells effects
  624. auto selector = [](const Bonus * b)
  625. {
  626. //Special case: DISRUPTING_RAY is absolutely permanent
  627. return b->source == BonusSource::SPELL_EFFECT && b->sid.as<SpellID>() != SpellID::DISRUPTING_RAY;
  628. };
  629. changedStack->removeBonusesRecursive(selector);
  630. }
  631. if(!changedStack->alive() && changedStack->isClone())
  632. {
  633. for(CStack * s : stacks)
  634. {
  635. if(s->cloneID == changedStack->unitId())
  636. s->cloneID = -1;
  637. }
  638. }
  639. }
  640. void BattleInfo::removeUnit(uint32_t id)
  641. {
  642. std::set<uint32_t> ids;
  643. ids.insert(id);
  644. while(!ids.empty())
  645. {
  646. auto toRemoveId = *ids.begin();
  647. auto * toRemove = getStack(toRemoveId, false);
  648. if(!toRemove)
  649. {
  650. logGlobal->error("Cannot find stack %d", toRemoveId);
  651. return;
  652. }
  653. if(!toRemove->ghost)
  654. {
  655. toRemove->onRemoved();
  656. toRemove->detachFromAll();
  657. //stack may be removed instantly (not being killed first)
  658. //handle clone remove also here
  659. if(toRemove->cloneID >= 0)
  660. {
  661. ids.insert(toRemove->cloneID);
  662. toRemove->cloneID = -1;
  663. }
  664. //cleanup remaining clone links if any
  665. for(auto * s : stacks)
  666. {
  667. if(s->cloneID == toRemoveId)
  668. s->cloneID = -1;
  669. }
  670. }
  671. ids.erase(toRemoveId);
  672. }
  673. }
  674. void BattleInfo::updateUnit(uint32_t id, const JsonNode & data)
  675. {
  676. //TODO
  677. }
  678. void BattleInfo::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  679. {
  680. CStack * sta = getStack(id, false);
  681. if(!sta)
  682. {
  683. logGlobal->error("Cannot find stack %d", id);
  684. return;
  685. }
  686. for(const Bonus & b : bonus)
  687. addOrUpdateUnitBonus(sta, b, true);
  688. }
  689. void BattleInfo::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  690. {
  691. CStack * sta = getStack(id, false);
  692. if(!sta)
  693. {
  694. logGlobal->error("Cannot find stack %d", id);
  695. return;
  696. }
  697. for(const Bonus & b : bonus)
  698. addOrUpdateUnitBonus(sta, b, false);
  699. }
  700. void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  701. {
  702. CStack * sta = getStack(id, false);
  703. if(!sta)
  704. {
  705. logGlobal->error("Cannot find stack %d", id);
  706. return;
  707. }
  708. for(const Bonus & one : bonus)
  709. {
  710. auto selector = [one](const Bonus * b)
  711. {
  712. //compare everything but turnsRemain, limiter and propagator
  713. return one.duration == b->duration
  714. && one.type == b->type
  715. && one.subtype == b->subtype
  716. && one.source == b->source
  717. && one.val == b->val
  718. && one.sid == b->sid
  719. && one.valType == b->valType
  720. && one.additionalInfo == b->additionalInfo
  721. && one.effectRange == b->effectRange;
  722. };
  723. sta->removeBonusesRecursive(selector);
  724. }
  725. }
  726. uint32_t BattleInfo::nextUnitId() const
  727. {
  728. return static_cast<uint32_t>(stacks.size());
  729. }
  730. void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)
  731. {
  732. if(forceAdd || !sta->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, value.sid).And(Selector::typeSubtypeValueType(value.type, value.subtype, value.valType))))
  733. {
  734. //no such effect or cumulative - add new
  735. logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), value.Description(nullptr));
  736. sta->addNewBonus(std::make_shared<Bonus>(value));
  737. }
  738. else
  739. {
  740. logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description(nullptr));
  741. for(const auto & stackBonus : sta->getExportedBonusList()) //TODO: optimize
  742. {
  743. if(stackBonus->source == value.source && stackBonus->sid == value.sid && stackBonus->type == value.type && stackBonus->subtype == value.subtype && stackBonus->valType == value.valType)
  744. {
  745. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, value.turnsRemain);
  746. }
  747. }
  748. CBonusSystemNode::treeHasChanged();
  749. }
  750. }
  751. void BattleInfo::setWallState(EWallPart partOfWall, EWallState state)
  752. {
  753. si.wallState[partOfWall] = state;
  754. }
  755. void BattleInfo::addObstacle(const ObstacleChanges & changes)
  756. {
  757. auto obstacle = std::make_shared<SpellCreatedObstacle>();
  758. obstacle->fromInfo(changes);
  759. obstacles.push_back(obstacle);
  760. }
  761. void BattleInfo::updateObstacle(const ObstacleChanges& changes)
  762. {
  763. auto changedObstacle = std::make_shared<SpellCreatedObstacle>();
  764. changedObstacle->fromInfo(changes);
  765. for(auto & obstacle : obstacles)
  766. {
  767. if(obstacle->uniqueID == changes.id) // update this obstacle
  768. {
  769. auto * spellObstacle = dynamic_cast<SpellCreatedObstacle *>(obstacle.get());
  770. assert(spellObstacle);
  771. // Currently we only support to update the "revealed" property
  772. spellObstacle->revealed = changedObstacle->revealed;
  773. break;
  774. }
  775. }
  776. }
  777. void BattleInfo::removeObstacle(uint32_t id)
  778. {
  779. for(int i=0; i < obstacles.size(); ++i)
  780. {
  781. if(obstacles[i]->uniqueID == id) //remove this obstacle
  782. {
  783. obstacles.erase(obstacles.begin() + i);
  784. break;
  785. }
  786. }
  787. }
  788. CArmedInstance * BattleInfo::battleGetArmyObject(BattleSide side) const
  789. {
  790. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  791. }
  792. CGHeroInstance * BattleInfo::battleGetFightingHero(BattleSide side) const
  793. {
  794. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  795. }
  796. #if SCRIPTING_ENABLED
  797. scripting::Pool * BattleInfo::getContextPool() const
  798. {
  799. //this is real battle, use global scripting context pool
  800. //TODO: make this line not ugly
  801. return battleGetFightingHero(BattleSide::ATTACKER)->cb->getGlobalContextPool();
  802. }
  803. #endif
  804. bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b) const
  805. {
  806. switch(phase)
  807. {
  808. case 0: //catapult moves after turrets
  809. return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
  810. case 1:
  811. case 2:
  812. case 3:
  813. {
  814. int as = a->getInitiative(turn);
  815. int bs = b->getInitiative(turn);
  816. if(as != bs)
  817. return as > bs;
  818. if(a->unitSide() == b->unitSide())
  819. return a->unitSlot() < b->unitSlot();
  820. return (a->unitSide() == side || b->unitSide() == side)
  821. ? a->unitSide() != side
  822. : a->unitSide() < b->unitSide();
  823. }
  824. default:
  825. assert(false);
  826. return false;
  827. }
  828. assert(false);
  829. return false;
  830. }
  831. CMP_stack::CMP_stack(int Phase, int Turn, BattleSide Side):
  832. phase(Phase),
  833. turn(Turn),
  834. side(Side)
  835. {
  836. }
  837. VCMI_LIB_NAMESPACE_END