BattleInfo.cpp 27 KB

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