BattleInfo.cpp 28 KB

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