BattleInfo.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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 "../callback/IGameInfoCallback.h"
  18. #include "../entities/artifact/CArtifact.h"
  19. #include "../entities/building/TownFortifications.h"
  20. #include "../filesystem/Filesystem.h"
  21. #include "../spells/CSpellHandler.h"
  22. #include "../GameLibrary.h"
  23. #include "../mapObjects/CGTownInstance.h"
  24. #include "../texts/CGeneralTextHandler.h"
  25. #include "../BattleFieldHandler.h"
  26. #include "../ObstacleHandler.h"
  27. #include <vstd/RNG.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(IGameInfoCallback *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], i == BattleSide::RIGHT_SIDE ? town : nullptr);
  145. currentBattle->tile = tile;
  146. currentBattle->terrainType = terrain;
  147. currentBattle->battlefieldType = battlefieldType;
  148. currentBattle->round = 0;
  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. else
  295. logMod->warn("Invalid battlefield layout! Failed to find position for unit %d for %s", k, side == BattleSide::ATTACKER ? "attacker" : "defender");
  296. }
  297. }
  298. //adding commanders
  299. for(BattleSide i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  300. {
  301. if (heroes[i] && heroes[i]->getCommander() && heroes[i]->getCommander()->alive)
  302. {
  303. currentBattle->generateNewStack(currentBattle->nextUnitId(), *heroes[i]->getCommander(), i, SlotID::COMMANDER_SLOT_PLACEHOLDER, layout.commanders.at(i));
  304. }
  305. }
  306. if (currentBattle->townID.hasValue())
  307. {
  308. if (currentBattle->getDefendedTown()->fortificationsLevel().citadelHealth != 0)
  309. currentBattle->generateNewStack(currentBattle->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_CENTRAL_TOWER);
  310. if (currentBattle->getDefendedTown()->fortificationsLevel().upperTowerHealth != 0)
  311. currentBattle->generateNewStack(currentBattle->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_UPPER_TOWER);
  312. if (currentBattle->getDefendedTown()->fortificationsLevel().lowerTowerHealth != 0)
  313. currentBattle->generateNewStack(currentBattle->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), BattleSide::DEFENDER, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_BOTTOM_TOWER);
  314. //Moat generating is done on server
  315. }
  316. std::stable_sort(currentBattle->stacks.begin(), currentBattle->stacks.end(), [cmpst](const auto & left, const auto & right){ return cmpst(left.get(), right.get());});
  317. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  318. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  319. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  320. const auto * bgInfo = LIBRARY->battlefields()->getById(battlefieldType);
  321. for(const std::shared_ptr<Bonus> & bonus : bgInfo->bonuses)
  322. {
  323. currentBattle->addNewBonus(bonus);
  324. }
  325. //native terrain bonuses
  326. auto nativeTerrain = std::make_shared<AllOfLimiter>();
  327. nativeTerrain->add(std::make_shared<TerrainLimiter>());
  328. nativeTerrain->add(std::make_shared<CreatureLevelLimiter>()); // creature only limiter - exclude hero
  329. currentBattle->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::STACKS_SPEED, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID())->addLimiter(nativeTerrain));
  330. currentBattle->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::ATTACK))->addLimiter(nativeTerrain));
  331. currentBattle->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE))->addLimiter(nativeTerrain));
  332. //////////////////////////////////////////////////////////////////////////
  333. //tactics
  334. BattleSideArray<int> battleRepositionHex = {};
  335. BattleSideArray<int> battleRepositionHexBlock = {};
  336. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  337. {
  338. if(heroes[i])
  339. {
  340. if(heroes[i]->tacticFormationEnabled)
  341. battleRepositionHex[i] += heroes[i]->valOfBonuses(BonusType::BEFORE_BATTLE_REPOSITION);
  342. battleRepositionHexBlock[i] += heroes[i]->valOfBonuses(BonusType::BEFORE_BATTLE_REPOSITION_BLOCK);
  343. }
  344. }
  345. int tacticsSkillDiffAttacker = battleRepositionHex[BattleSide::ATTACKER] - battleRepositionHexBlock[BattleSide::DEFENDER];
  346. int tacticsSkillDiffDefender = battleRepositionHex[BattleSide::DEFENDER] - battleRepositionHexBlock[BattleSide::ATTACKER];
  347. /* for current tactics, we need to choose one side, so, we will choose side when first - second > 0, and ignore sides
  348. when first - second <= 0. If there will be situations when both > 0, attacker will be chosen. Anyway, in OH3 this
  349. will not happen because tactics block opposite tactics on same value.
  350. TODO: For now, it is an error to use BEFORE_BATTLE_REPOSITION bonus without counterpart, but it can be changed if
  351. double tactics will be implemented.
  352. */
  353. if(layout.tacticsAllowed)
  354. {
  355. if(tacticsSkillDiffAttacker > 0 && tacticsSkillDiffDefender > 0)
  356. logGlobal->warn("Double tactics is not implemented, only attacker will have tactics!");
  357. if(tacticsSkillDiffAttacker > 0)
  358. {
  359. currentBattle->tacticsSide = BattleSide::ATTACKER;
  360. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  361. currentBattle->tacticDistance = 1 + tacticsSkillDiffAttacker;
  362. }
  363. else if(tacticsSkillDiffDefender > 0)
  364. {
  365. currentBattle->tacticsSide = BattleSide::DEFENDER;
  366. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  367. currentBattle->tacticDistance = 1 + tacticsSkillDiffDefender;
  368. }
  369. else
  370. currentBattle->tacticDistance = 0;
  371. }
  372. return currentBattle;
  373. }
  374. const CGHeroInstance * BattleInfo::getHero(const PlayerColor & player) const
  375. {
  376. for(const auto & side : sides)
  377. if(side.color == player)
  378. return side.getHero();
  379. logGlobal->error("Player %s is not in battle!", player.toString());
  380. return nullptr;
  381. }
  382. BattleSide BattleInfo::whatSide(const PlayerColor & player) const
  383. {
  384. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  385. if(sides[i].color == player)
  386. return i;
  387. logGlobal->warn("BattleInfo::whatSide: Player %s is not in battle!", player.toString());
  388. return BattleSide::NONE;
  389. }
  390. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  391. {
  392. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  393. }
  394. BattleInfo::BattleInfo(IGameInfoCallback *cb, const BattleLayout & layout):
  395. BattleInfo(cb)
  396. {
  397. *this->layout = layout;
  398. }
  399. BattleInfo::BattleInfo(IGameInfoCallback *cb)
  400. :CBonusSystemNode(BonusNodeType::BATTLE_WIDE),
  401. GameCallbackHolder(cb),
  402. sides({SideInBattle(cb), SideInBattle(cb)}),
  403. layout(std::make_unique<BattleLayout>()),
  404. round(-1),
  405. activeStack(-1),
  406. tile(-1,-1,-1),
  407. battlefieldType(BattleField::NONE),
  408. tacticsSide(BattleSide::NONE),
  409. tacticDistance(0)
  410. {
  411. }
  412. BattleLayout BattleInfo::getLayout() const
  413. {
  414. return *layout;
  415. }
  416. BattleID BattleInfo::getBattleID() const
  417. {
  418. return battleID;
  419. }
  420. const IBattleInfo * BattleInfo::getBattle() const
  421. {
  422. return this;
  423. }
  424. std::optional<PlayerColor> BattleInfo::getPlayerID() const
  425. {
  426. return std::nullopt;
  427. }
  428. BattleInfo::~BattleInfo()
  429. {
  430. stacks.clear();
  431. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  432. if(auto * _armyObj = battleGetArmyObject(i))
  433. _armyObj->battle = nullptr;
  434. }
  435. int32_t BattleInfo::getActiveStackID() const
  436. {
  437. return activeStack;
  438. }
  439. TStacks BattleInfo::getStacksIf(const TStackFilter & predicate) const
  440. {
  441. TStacks ret;
  442. for (const auto & stack : stacks)
  443. if (predicate(stack.get()))
  444. ret.push_back(stack.get());
  445. return ret;
  446. }
  447. battle::Units BattleInfo::getUnitsIf(const battle::UnitFilter & predicate) const
  448. {
  449. battle::Units ret;
  450. for (const auto & stack : stacks)
  451. if (predicate(stack.get()))
  452. ret.push_back(stack.get());
  453. return ret;
  454. }
  455. BattleField BattleInfo::getBattlefieldType() const
  456. {
  457. return battlefieldType;
  458. }
  459. TerrainId BattleInfo::getTerrainType() const
  460. {
  461. return terrainType;
  462. }
  463. IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
  464. {
  465. ObstacleCList ret;
  466. for(const auto & obstacle : obstacles)
  467. ret.push_back(obstacle);
  468. return ret;
  469. }
  470. PlayerColor BattleInfo::getSidePlayer(BattleSide side) const
  471. {
  472. return getSide(side).color;
  473. }
  474. const CArmedInstance * BattleInfo::getSideArmy(BattleSide side) const
  475. {
  476. return getSide(side).getArmy();
  477. }
  478. const CGHeroInstance * BattleInfo::getSideHero(BattleSide side) const
  479. {
  480. return getSide(side).getHero();
  481. }
  482. uint8_t BattleInfo::getTacticDist() const
  483. {
  484. return tacticDistance;
  485. }
  486. BattleSide BattleInfo::getTacticsSide() const
  487. {
  488. return tacticsSide;
  489. }
  490. int32_t BattleInfo::getRound() const
  491. {
  492. return round;
  493. }
  494. const CGTownInstance * BattleInfo::getDefendedTown() const
  495. {
  496. if (townID.hasValue())
  497. return cb->getTown(townID);
  498. return nullptr;
  499. }
  500. EWallState BattleInfo::getWallState(EWallPart partOfWall) const
  501. {
  502. return si.wallState.at(partOfWall);
  503. }
  504. EGateState BattleInfo::getGateState() const
  505. {
  506. return si.gateState;
  507. }
  508. int32_t BattleInfo::getCastSpells(BattleSide side) const
  509. {
  510. return getSide(side).castSpellsCount;
  511. }
  512. int32_t BattleInfo::getEnchanterCounter(BattleSide side) const
  513. {
  514. return getSide(side).enchanterCounter;
  515. }
  516. const IBonusBearer * BattleInfo::getBonusBearer() const
  517. {
  518. return this;
  519. }
  520. int64_t BattleInfo::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  521. {
  522. if(damage.min != damage.max)
  523. {
  524. int64_t sum = 0;
  525. auto howManyToAv = std::min<int32_t>(10, attackerCount);
  526. for(int32_t g = 0; g < howManyToAv; ++g)
  527. sum += rng.nextInt64(damage.min, damage.max);
  528. return sum / howManyToAv;
  529. }
  530. else
  531. {
  532. return damage.min;
  533. }
  534. }
  535. int3 BattleInfo::getLocation() const
  536. {
  537. return tile;
  538. }
  539. std::vector<SpellID> BattleInfo::getUsedSpells(BattleSide side) const
  540. {
  541. return getSide(side).usedSpellsHistory;
  542. }
  543. void BattleInfo::nextRound()
  544. {
  545. for(auto i : {BattleSide::ATTACKER, BattleSide::DEFENDER})
  546. {
  547. sides.at(i).castSpellsCount = 0;
  548. vstd::amax(--sides.at(i).enchanterCounter, 0);
  549. }
  550. round += 1;
  551. for(auto & s : stacks)
  552. {
  553. // new turn effects
  554. s->reduceBonusDurations(Bonus::NTurns);
  555. s->afterNewRound();
  556. }
  557. for(auto & obst : obstacles)
  558. obst->battleTurnPassed();
  559. }
  560. void BattleInfo::nextTurn(uint32_t unitId, BattleUnitTurnReason reason)
  561. {
  562. activeStack = unitId;
  563. CStack * st = getStack(activeStack);
  564. if (reason != BattleUnitTurnReason::UNIT_SPELLCAST)
  565. {
  566. //remove bonuses that last until when stack gets new turn
  567. st->removeBonusesRecursive(Bonus::UntilGetsTurn);
  568. }
  569. st->afterGetsTurn(reason);
  570. }
  571. void BattleInfo::addUnit(uint32_t id, const JsonNode & data)
  572. {
  573. battle::UnitInfo info;
  574. info.load(id, data);
  575. CStackBasicDescriptor base(info.type, info.count);
  576. PlayerColor owner = getSidePlayer(info.side);
  577. auto ret = std::make_unique<CStack>(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  578. ret->initialPosition = info.position;
  579. stacks.push_back(std::move(ret));
  580. stacks.back()->localInit(this);
  581. stacks.back()->summoned = info.summoned;
  582. }
  583. void BattleInfo::moveUnit(uint32_t id, const BattleHex & destination)
  584. {
  585. auto * sta = getStack(id);
  586. if(!sta)
  587. {
  588. logGlobal->error("Cannot find stack %d", id);
  589. return;
  590. }
  591. sta->position = destination;
  592. //Bonuses can be limited by unit placement, so, change tree version
  593. //to force updating a bonus. TODO: update version only when such bonuses are present
  594. nodeHasChanged();
  595. }
  596. void BattleInfo::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  597. {
  598. CStack * changedStack = getStack(id, false);
  599. if(!changedStack)
  600. throw std::runtime_error("Invalid unit id in BattleInfo update");
  601. if(!changedStack->alive() && healthDelta > 0)
  602. {
  603. //checking if we resurrect a stack that is under a living stack
  604. auto accessibility = getAccessibility();
  605. if(!accessibility.accessible(changedStack->getPosition(), changedStack))
  606. {
  607. logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->getPosition());
  608. return; //position is already occupied
  609. }
  610. }
  611. bool killed = (-healthDelta) >= changedStack->getAvailableHealth();//todo: check using alive state once rebirth will be handled separately
  612. bool resurrected = !changedStack->alive() && healthDelta > 0;
  613. //applying changes
  614. changedStack->load(data);
  615. if(healthDelta < 0)
  616. {
  617. changedStack->removeBonusesRecursive(Bonus::UntilBeingAttacked);
  618. }
  619. if(healthDelta < 0)
  620. {
  621. changedStack->nodeHasChanged(); //bonuses with TIMES_STACK_SIZE updater may change
  622. }
  623. resurrected = resurrected || (killed && changedStack->alive());
  624. if(killed)
  625. {
  626. if(changedStack->cloneID >= 0)
  627. {
  628. //remove clone as well
  629. CStack * clone = getStack(changedStack->cloneID);
  630. if(clone)
  631. clone->makeGhost();
  632. changedStack->cloneID = -1;
  633. }
  634. }
  635. if(resurrected || killed)
  636. {
  637. //removing all spells effects
  638. auto selector = [](const Bonus * b)
  639. {
  640. //Special case: DISRUPTING_RAY is absolutely permanent
  641. return b->source == BonusSource::SPELL_EFFECT && b->sid.as<SpellID>().toSpell()->isPersistent();
  642. };
  643. changedStack->removeBonusesRecursive(selector);
  644. }
  645. if(!changedStack->alive() && changedStack->isClone())
  646. {
  647. for(auto & s : stacks)
  648. {
  649. if(s->cloneID == changedStack->unitId())
  650. s->cloneID = -1;
  651. }
  652. }
  653. }
  654. void BattleInfo::removeUnit(uint32_t id)
  655. {
  656. std::set<uint32_t> ids;
  657. ids.insert(id);
  658. while(!ids.empty())
  659. {
  660. auto toRemoveId = *ids.begin();
  661. auto * toRemove = getStack(toRemoveId, false);
  662. if(!toRemove)
  663. {
  664. logGlobal->error("Cannot find stack %d", toRemoveId);
  665. return;
  666. }
  667. if(!toRemove->ghost)
  668. {
  669. toRemove->onRemoved();
  670. toRemove->detachFromAll();
  671. //stack may be removed instantly (not being killed first)
  672. //handle clone remove also here
  673. if(toRemove->cloneID >= 0)
  674. {
  675. ids.insert(toRemove->cloneID);
  676. toRemove->cloneID = -1;
  677. }
  678. //cleanup remaining clone links if any
  679. for(const auto & s : stacks)
  680. {
  681. if(s->cloneID == toRemoveId)
  682. s->cloneID = -1;
  683. }
  684. }
  685. ids.erase(toRemoveId);
  686. }
  687. }
  688. void BattleInfo::updateUnit(uint32_t id, const JsonNode & data)
  689. {
  690. //TODO
  691. }
  692. void BattleInfo::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  693. {
  694. CStack * sta = getStack(id, false);
  695. if(!sta)
  696. {
  697. logGlobal->error("Cannot find stack %d", id);
  698. return;
  699. }
  700. for(const Bonus & b : bonus)
  701. addOrUpdateUnitBonus(sta, b, true);
  702. }
  703. void BattleInfo::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  704. {
  705. CStack * sta = getStack(id, false);
  706. if(!sta)
  707. {
  708. logGlobal->error("Cannot find stack %d", id);
  709. return;
  710. }
  711. for(const Bonus & b : bonus)
  712. addOrUpdateUnitBonus(sta, b, false);
  713. }
  714. void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  715. {
  716. CStack * sta = getStack(id, false);
  717. if(!sta)
  718. {
  719. logGlobal->error("Cannot find stack %d", id);
  720. return;
  721. }
  722. for(const Bonus & one : bonus)
  723. {
  724. auto selector = [one](const Bonus * b)
  725. {
  726. //compare everything but turnsRemain, limiter and propagator
  727. return one.duration == b->duration
  728. && one.type == b->type
  729. && one.subtype == b->subtype
  730. && one.source == b->source
  731. && one.val == b->val
  732. && one.sid == b->sid
  733. && one.valType == b->valType
  734. && one.effectRange == b->effectRange;
  735. };
  736. sta->removeBonusesRecursive(selector);
  737. }
  738. }
  739. uint32_t BattleInfo::nextUnitId() const
  740. {
  741. return static_cast<uint32_t>(stacks.size());
  742. }
  743. void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)
  744. {
  745. if(forceAdd || !sta->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, value.sid).And(Selector::typeSubtypeValueType(value.type, value.subtype, value.valType))))
  746. {
  747. //no such effect or cumulative - add new
  748. logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), value.Description(nullptr));
  749. sta->addNewBonus(std::make_shared<Bonus>(value));
  750. }
  751. else
  752. {
  753. logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description(nullptr));
  754. for(const auto & stackBonus : sta->getExportedBonusList()) //TODO: optimize
  755. {
  756. if(stackBonus->source == value.source && stackBonus->sid == value.sid && stackBonus->type == value.type && stackBonus->subtype == value.subtype && stackBonus->valType == value.valType)
  757. {
  758. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, value.turnsRemain);
  759. }
  760. }
  761. sta->nodeHasChanged();
  762. }
  763. }
  764. void BattleInfo::setWallState(EWallPart partOfWall, EWallState state)
  765. {
  766. si.wallState[partOfWall] = state;
  767. }
  768. void BattleInfo::addObstacle(const ObstacleChanges & changes)
  769. {
  770. auto obstacle = std::make_shared<SpellCreatedObstacle>();
  771. obstacle->fromInfo(changes);
  772. obstacles.push_back(obstacle);
  773. }
  774. void BattleInfo::updateObstacle(const ObstacleChanges& changes)
  775. {
  776. auto changedObstacle = std::make_shared<SpellCreatedObstacle>();
  777. changedObstacle->fromInfo(changes);
  778. for(auto & obstacle : obstacles)
  779. {
  780. if(obstacle->uniqueID == changes.id) // update this obstacle
  781. {
  782. auto * spellObstacle = dynamic_cast<SpellCreatedObstacle *>(obstacle.get());
  783. assert(spellObstacle);
  784. // Currently we only support to update the "revealed" property
  785. spellObstacle->revealed = changedObstacle->revealed;
  786. break;
  787. }
  788. }
  789. }
  790. void BattleInfo::removeObstacle(uint32_t id)
  791. {
  792. for(int i=0; i < obstacles.size(); ++i)
  793. {
  794. if(obstacles[i]->uniqueID == id) //remove this obstacle
  795. {
  796. obstacles.erase(obstacles.begin() + i);
  797. break;
  798. }
  799. }
  800. }
  801. CArmedInstance * BattleInfo::battleGetArmyObject(BattleSide side) const
  802. {
  803. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  804. }
  805. CGHeroInstance * BattleInfo::battleGetFightingHero(BattleSide side) const
  806. {
  807. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  808. }
  809. void BattleInfo::postDeserialize()
  810. {
  811. for (const auto & unit : stacks)
  812. unit->postDeserialize(getSideArmy(unit->unitSide()));
  813. }
  814. #if SCRIPTING_ENABLED
  815. scripting::Pool * BattleInfo::getContextPool() const
  816. {
  817. //this is real battle, use global scripting context pool
  818. //TODO: make this line not ugly
  819. return battleGetFightingHero(BattleSide::ATTACKER)->cb->getGlobalContextPool();
  820. }
  821. #endif
  822. bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b) const
  823. {
  824. switch(phase)
  825. {
  826. case 0: //catapult moves after turrets
  827. return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
  828. case 1:
  829. case 2:
  830. case 3:
  831. {
  832. int as = a->getInitiative(turn);
  833. int bs = b->getInitiative(turn);
  834. if(as != bs)
  835. return as > bs;
  836. if(a->unitSide() == b->unitSide())
  837. return a->unitSlot() < b->unitSlot();
  838. return (a->unitSide() == side || b->unitSide() == side)
  839. ? a->unitSide() != side
  840. : a->unitSide() < b->unitSide();
  841. }
  842. default:
  843. assert(false);
  844. return false;
  845. }
  846. assert(false);
  847. return false;
  848. }
  849. CMP_stack::CMP_stack(int Phase, int Turn, BattleSide Side):
  850. phase(Phase),
  851. turn(Turn),
  852. side(Side)
  853. {
  854. }
  855. VCMI_LIB_NAMESPACE_END