BattleInfo.cpp 26 KB

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