BattleInfo.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. /*
  2. * BattleInfo.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "BattleInfo.h"
  12. #include "BattleLayout.h"
  13. #include "CObstacleInstance.h"
  14. #include "bonuses/Limiters.h"
  15. #include "bonuses/Updaters.h"
  16. #include "../CStack.h"
  17. #include "../entities/building/TownFortifications.h"
  18. #include "../filesystem/Filesystem.h"
  19. #include "../mapObjects/CGTownInstance.h"
  20. #include "../texts/CGeneralTextHandler.h"
  21. #include "../BattleFieldHandler.h"
  22. #include "../ObstacleHandler.h"
  23. #include <vstd/RNG.h>
  24. //TODO: remove
  25. #include "../IGameCallback.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. const SideInBattle & BattleInfo::getSide(BattleSide side) const
  28. {
  29. return sides.at(side);
  30. }
  31. SideInBattle & BattleInfo::getSide(BattleSide side)
  32. {
  33. return sides.at(side);
  34. }
  35. ///BattleInfo
  36. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackInstance & base, BattleSide side, const SlotID & slot, const BattleHex & position)
  37. {
  38. PlayerColor owner = getSide(side).color;
  39. assert(!owner.isValidPlayer() || (base.armyObj && base.armyObj->tempOwner == owner));
  40. auto * ret = new CStack(&base, owner, id, side, slot);
  41. ret->initialPosition = getAvailableHex(base.getCreatureID(), side, position.toInt()); //TODO: what if no free tile on battlefield was found?
  42. stacks.push_back(ret);
  43. return ret;
  44. }
  45. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackBasicDescriptor & base, BattleSide side, const SlotID & slot, const BattleHex & position)
  46. {
  47. PlayerColor owner = getSide(side).color;
  48. auto * ret = new CStack(&base, owner, id, side, slot);
  49. ret->initialPosition = position;
  50. stacks.push_back(ret);
  51. return ret;
  52. }
  53. void BattleInfo::localInit()
  54. {
  55. for(BattleSide i : { BattleSide::ATTACKER, BattleSide::DEFENDER})
  56. {
  57. auto * armyObj = battleGetArmyObject(i);
  58. armyObj->battle = this;
  59. armyObj->attachTo(*this);
  60. }
  61. for(CStack * s : stacks)
  62. s->localInit(this);
  63. exportBonuses();
  64. }
  65. //RNG that works like H3 one
  66. struct RandGen
  67. {
  68. ui32 seed;
  69. void srand(ui32 s)
  70. {
  71. seed = s;
  72. }
  73. void srand(const int3 & pos)
  74. {
  75. srand(110291 * static_cast<ui32>(pos.x) + 167801 * static_cast<ui32>(pos.y) + 81569);
  76. }
  77. int rand()
  78. {
  79. seed = 214013 * seed + 2531011;
  80. return (seed >> 16) & 0x7FFF;
  81. }
  82. int rand(int min, int max)
  83. {
  84. if(min == max)
  85. return min;
  86. if(min > max)
  87. return min;
  88. return min + rand() % (max - min + 1);
  89. }
  90. };
  91. struct RangeGenerator
  92. {
  93. class ExhaustedPossibilities : public std::exception
  94. {
  95. };
  96. RangeGenerator(int _min, int _max, std::function<int()> _myRand):
  97. min(_min),
  98. remainingCount(_max - _min + 1),
  99. remaining(remainingCount, true),
  100. myRand(std::move(_myRand))
  101. {
  102. }
  103. int generateNumber() const
  104. {
  105. if(!remainingCount)
  106. throw ExhaustedPossibilities();
  107. if(remainingCount == 1)
  108. return 0;
  109. return myRand() % remainingCount;
  110. }
  111. //get number fulfilling predicate. Never gives the same number twice.
  112. int getSuchNumber(const std::function<bool(int)> & goodNumberPred = nullptr)
  113. {
  114. int ret = -1;
  115. do
  116. {
  117. int n = generateNumber();
  118. int i = 0;
  119. for(;;i++)
  120. {
  121. assert(i < (int)remaining.size());
  122. if(!remaining[i])
  123. continue;
  124. if(!n)
  125. break;
  126. n--;
  127. }
  128. remainingCount--;
  129. remaining[i] = false;
  130. ret = i + min;
  131. } while(goodNumberPred && !goodNumberPred(ret));
  132. return ret;
  133. }
  134. int min;
  135. int remainingCount;
  136. std::vector<bool> remaining;
  137. std::function<int()> myRand;
  138. };
  139. BattleInfo * BattleInfo::setupBattle(const int3 & tile, TerrainId terrain, const BattleField & battlefieldType, BattleSideArray<const CArmedInstance *> armies, BattleSideArray<const CGHeroInstance *> heroes, const BattleLayout & layout, const CGTownInstance * town)
  140. {
  141. CMP_stack cmpst;
  142. auto * currentBattle = new BattleInfo(layout);
  143. for(auto i : { BattleSide::LEFT_SIDE, BattleSide::RIGHT_SIDE})
  144. currentBattle->sides[i].init(heroes[i], armies[i]);
  145. std::vector<CStack*> & stacks = (currentBattle->stacks);
  146. currentBattle->tile = tile;
  147. currentBattle->terrainType = terrain;
  148. currentBattle->battlefieldType = battlefieldType;
  149. currentBattle->round = -2;
  150. currentBattle->activeStack = -1;
  151. currentBattle->replayAllowed = false;
  152. currentBattle->town = town;
  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->town)
  305. {
  306. if (currentBattle->town->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->town->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->town->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(stacks.begin(),stacks.end(),cmpst);
  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.hero;
  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(const BattleLayout & layout):
  390. BattleInfo()
  391. {
  392. *this->layout = layout;
  393. }
  394. BattleInfo::BattleInfo():
  395. layout(std::make_unique<BattleLayout>()),
  396. round(-1),
  397. activeStack(-1),
  398. town(nullptr),
  399. tile(-1,-1,-1),
  400. battlefieldType(BattleField::NONE),
  401. tacticsSide(BattleSide::NONE),
  402. tacticDistance(0)
  403. {
  404. setNodeType(BATTLE);
  405. }
  406. BattleLayout BattleInfo::getLayout() const
  407. {
  408. return *layout;
  409. }
  410. BattleID BattleInfo::getBattleID() const
  411. {
  412. return battleID;
  413. }
  414. const IBattleInfo * BattleInfo::getBattle() const
  415. {
  416. return this;
  417. }
  418. std::optional<PlayerColor> BattleInfo::getPlayerID() const
  419. {
  420. return std::nullopt;
  421. }
  422. BattleInfo::~BattleInfo()
  423. {
  424. for (auto & elem : stacks)
  425. delete elem;
  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. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  438. return ret;
  439. }
  440. battle::Units BattleInfo::getUnitsIf(const battle::UnitFilter & predicate) const
  441. {
  442. battle::Units ret;
  443. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  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(CStack * 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 = new CStack(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  560. ret->initialPosition = info.position;
  561. stacks.push_back(ret);
  562. ret->localInit(this);
  563. ret->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(CStack * 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