BattleInfo.cpp 29 KB

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