BattleInfo.cpp 27 KB

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