BattleInfo.cpp 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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), activeStack(-1), town(nullptr), tile(-1,-1,-1),
  445. battlefieldType(BattleField::NONE), terrainType(),
  446. tacticsSide(0), tacticDistance(0)
  447. {
  448. setBattle(this);
  449. setNodeType(BATTLE);
  450. }
  451. BattleInfo::~BattleInfo() = default;
  452. int32_t BattleInfo::getActiveStackID() const
  453. {
  454. return activeStack;
  455. }
  456. TStacks BattleInfo::getStacksIf(TStackFilter predicate) const
  457. {
  458. TStacks ret;
  459. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  460. return ret;
  461. }
  462. battle::Units BattleInfo::getUnitsIf(battle::UnitFilter predicate) const
  463. {
  464. battle::Units ret;
  465. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  466. return ret;
  467. }
  468. BattleField BattleInfo::getBattlefieldType() const
  469. {
  470. return battlefieldType;
  471. }
  472. Terrain BattleInfo::getTerrainType() const
  473. {
  474. return terrainType;
  475. }
  476. IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
  477. {
  478. ObstacleCList ret;
  479. for(auto iter = obstacles.cbegin(); iter != obstacles.cend(); iter++)
  480. ret.push_back(*iter);
  481. return ret;
  482. }
  483. PlayerColor BattleInfo::getSidePlayer(ui8 side) const
  484. {
  485. return sides.at(side).color;
  486. }
  487. const CArmedInstance * BattleInfo::getSideArmy(ui8 side) const
  488. {
  489. return sides.at(side).armyObject;
  490. }
  491. const CGHeroInstance * BattleInfo::getSideHero(ui8 side) const
  492. {
  493. return sides.at(side).hero;
  494. }
  495. ui8 BattleInfo::getTacticDist() const
  496. {
  497. return tacticDistance;
  498. }
  499. ui8 BattleInfo::getTacticsSide() const
  500. {
  501. return tacticsSide;
  502. }
  503. const CGTownInstance * BattleInfo::getDefendedTown() const
  504. {
  505. return town;
  506. }
  507. si8 BattleInfo::getWallState(int partOfWall) const
  508. {
  509. return si.wallState.at(partOfWall);
  510. }
  511. EGateState BattleInfo::getGateState() const
  512. {
  513. return si.gateState;
  514. }
  515. uint32_t BattleInfo::getCastSpells(ui8 side) const
  516. {
  517. return sides.at(side).castSpellsCount;
  518. }
  519. int32_t BattleInfo::getEnchanterCounter(ui8 side) const
  520. {
  521. return sides.at(side).enchanterCounter;
  522. }
  523. const IBonusBearer * BattleInfo::asBearer() const
  524. {
  525. return this;
  526. }
  527. int64_t BattleInfo::getActualDamage(const TDmgRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  528. {
  529. if(damage.first != damage.second)
  530. {
  531. int64_t sum = 0;
  532. auto howManyToAv = std::min<int32_t>(10, attackerCount);
  533. auto rangeGen = rng.getInt64Range(damage.first, damage.second);
  534. for(int32_t g = 0; g < howManyToAv; ++g)
  535. sum += rangeGen();
  536. return sum / howManyToAv;
  537. }
  538. else
  539. {
  540. return damage.first;
  541. }
  542. }
  543. void BattleInfo::nextRound(int32_t roundNr)
  544. {
  545. for(int i = 0; i < 2; ++i)
  546. {
  547. sides.at(i).castSpellsCount = 0;
  548. vstd::amax(--sides.at(i).enchanterCounter, 0);
  549. }
  550. round = roundNr;
  551. for(CStack * s : stacks)
  552. {
  553. // new turn effects
  554. s->reduceBonusDurations(Bonus::NTurns);
  555. s->afterNewRound();
  556. }
  557. for(auto & obst : obstacles)
  558. obst->battleTurnPassed();
  559. }
  560. void BattleInfo::nextTurn(uint32_t unitId)
  561. {
  562. activeStack = unitId;
  563. CStack * st = getStack(activeStack);
  564. //remove bonuses that last until when stack gets new turn
  565. st->removeBonusesRecursive(Bonus::UntilGetsTurn);
  566. st->afterGetsTurn();
  567. }
  568. void BattleInfo::addUnit(uint32_t id, const JsonNode & data)
  569. {
  570. battle::UnitInfo info;
  571. info.load(id, data);
  572. CStackBasicDescriptor base(info.type, info.count);
  573. PlayerColor owner = getSidePlayer(info.side);
  574. auto ret = new CStack(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  575. ret->initialPosition = info.position;
  576. stacks.push_back(ret);
  577. ret->localInit(this);
  578. ret->summoned = info.summoned;
  579. }
  580. void BattleInfo::moveUnit(uint32_t id, BattleHex destination)
  581. {
  582. auto sta = getStack(id);
  583. if(!sta)
  584. {
  585. logGlobal->error("Cannot find stack %d", id);
  586. return;
  587. }
  588. sta->position = destination;
  589. }
  590. void BattleInfo::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  591. {
  592. CStack * changedStack = getStack(id, false);
  593. if(!changedStack)
  594. throw std::runtime_error("Invalid unit id in BattleInfo update");
  595. if(!changedStack->alive() && healthDelta > 0)
  596. {
  597. //checking if we resurrect a stack that is under a living stack
  598. auto accessibility = getAccesibility();
  599. if(!accessibility.accessible(changedStack->getPosition(), changedStack))
  600. {
  601. logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->getPosition().hex);
  602. return; //position is already occupied
  603. }
  604. }
  605. bool killed = (-healthDelta) >= changedStack->getAvailableHealth();//todo: check using alive state once rebirth will be handled separately
  606. bool resurrected = !changedStack->alive() && healthDelta > 0;
  607. //applying changes
  608. changedStack->load(data);
  609. if(healthDelta < 0)
  610. {
  611. changedStack->removeBonusesRecursive(Bonus::UntilBeingAttacked);
  612. }
  613. resurrected = resurrected || (killed && changedStack->alive());
  614. if(killed)
  615. {
  616. if(changedStack->cloneID >= 0)
  617. {
  618. //remove clone as well
  619. CStack * clone = getStack(changedStack->cloneID);
  620. if(clone)
  621. clone->makeGhost();
  622. changedStack->cloneID = -1;
  623. }
  624. }
  625. if(resurrected || killed)
  626. {
  627. //removing all spells effects
  628. auto selector = [](const Bonus * b)
  629. {
  630. //Special case: DISRUPTING_RAY is absolutely permanent
  631. return b->source == Bonus::SPELL_EFFECT && b->sid != SpellID::DISRUPTING_RAY;
  632. };
  633. changedStack->removeBonusesRecursive(selector);
  634. }
  635. if(!changedStack->alive() && changedStack->isClone())
  636. {
  637. for(CStack * s : stacks)
  638. {
  639. if(s->cloneID == changedStack->unitId())
  640. s->cloneID = -1;
  641. }
  642. }
  643. }
  644. void BattleInfo::removeUnit(uint32_t id)
  645. {
  646. std::set<uint32_t> ids;
  647. ids.insert(id);
  648. while(!ids.empty())
  649. {
  650. auto toRemoveId = *ids.begin();
  651. auto toRemove = getStack(toRemoveId, false);
  652. if(!toRemove)
  653. {
  654. logGlobal->error("Cannot find stack %d", toRemoveId);
  655. return;
  656. }
  657. if(!toRemove->ghost)
  658. {
  659. toRemove->onRemoved();
  660. toRemove->detachFromAll();
  661. //stack may be removed instantly (not being killed first)
  662. //handle clone remove also here
  663. if(toRemove->cloneID >= 0)
  664. {
  665. ids.insert(toRemove->cloneID);
  666. toRemove->cloneID = -1;
  667. }
  668. //cleanup remaining clone links if any
  669. for(auto s : stacks)
  670. {
  671. if(s->cloneID == toRemoveId)
  672. s->cloneID = -1;
  673. }
  674. }
  675. ids.erase(toRemoveId);
  676. }
  677. }
  678. void BattleInfo::updateUnit(uint32_t id, const JsonNode & data)
  679. {
  680. //TODO
  681. }
  682. void BattleInfo::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  683. {
  684. CStack * sta = getStack(id, false);
  685. if(!sta)
  686. {
  687. logGlobal->error("Cannot find stack %d", id);
  688. return;
  689. }
  690. for(const Bonus & b : bonus)
  691. addOrUpdateUnitBonus(sta, b, true);
  692. }
  693. void BattleInfo::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  694. {
  695. CStack * sta = getStack(id, false);
  696. if(!sta)
  697. {
  698. logGlobal->error("Cannot find stack %d", id);
  699. return;
  700. }
  701. for(const Bonus & b : bonus)
  702. addOrUpdateUnitBonus(sta, b, false);
  703. }
  704. void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  705. {
  706. CStack * sta = getStack(id, false);
  707. if(!sta)
  708. {
  709. logGlobal->error("Cannot find stack %d", id);
  710. return;
  711. }
  712. for(const Bonus & one : bonus)
  713. {
  714. auto selector = [one](const Bonus * b)
  715. {
  716. //compare everything but turnsRemain, limiter and propagator
  717. return one.duration == b->duration
  718. && one.type == b->type
  719. && one.subtype == b->subtype
  720. && one.source == b->source
  721. && one.val == b->val
  722. && one.sid == b->sid
  723. && one.valType == b->valType
  724. && one.additionalInfo == b->additionalInfo
  725. && one.effectRange == b->effectRange
  726. && one.description == b->description;
  727. };
  728. sta->removeBonusesRecursive(selector);
  729. }
  730. }
  731. uint32_t BattleInfo::nextUnitId() const
  732. {
  733. return static_cast<uint32_t>(stacks.size());
  734. }
  735. void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)
  736. {
  737. if(forceAdd || !sta->hasBonus(Selector::source(Bonus::SPELL_EFFECT, value.sid).And(Selector::typeSubtype(value.type, value.subtype))))
  738. {
  739. //no such effect or cumulative - add new
  740. logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), value.Description());
  741. sta->addNewBonus(std::make_shared<Bonus>(value));
  742. }
  743. else
  744. {
  745. logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description());
  746. for(auto stackBonus : sta->getExportedBonusList()) //TODO: optimize
  747. {
  748. if(stackBonus->source == value.source && stackBonus->sid == value.sid && stackBonus->type == value.type && stackBonus->subtype == value.subtype)
  749. {
  750. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, value.turnsRemain);
  751. }
  752. }
  753. CBonusSystemNode::treeHasChanged();
  754. }
  755. }
  756. void BattleInfo::setWallState(int partOfWall, si8 state)
  757. {
  758. si.wallState.at(partOfWall) = state;
  759. }
  760. void BattleInfo::addObstacle(const ObstacleChanges & changes)
  761. {
  762. std::shared_ptr<SpellCreatedObstacle> obstacle = std::make_shared<SpellCreatedObstacle>();
  763. obstacle->fromInfo(changes);
  764. obstacles.push_back(obstacle);
  765. }
  766. void BattleInfo::updateObstacle(const ObstacleChanges& changes)
  767. {
  768. std::shared_ptr<SpellCreatedObstacle> changedObstacle = std::make_shared<SpellCreatedObstacle>();
  769. changedObstacle->fromInfo(changes);
  770. for(int i = 0; i < obstacles.size(); ++i)
  771. {
  772. if(obstacles[i]->uniqueID == changes.id) // update this obstacle
  773. {
  774. SpellCreatedObstacle * spellObstacle = dynamic_cast<SpellCreatedObstacle *>(obstacles[i].get());
  775. assert(spellObstacle);
  776. // Currently we only support to update the "revealed" property
  777. spellObstacle->revealed = changedObstacle->revealed;
  778. break;
  779. }
  780. }
  781. }
  782. void BattleInfo::removeObstacle(uint32_t id)
  783. {
  784. for(int i=0; i < obstacles.size(); ++i)
  785. {
  786. if(obstacles[i]->uniqueID == id) //remove this obstacle
  787. {
  788. obstacles.erase(obstacles.begin() + i);
  789. break;
  790. }
  791. }
  792. }
  793. CArmedInstance * BattleInfo::battleGetArmyObject(ui8 side) const
  794. {
  795. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  796. }
  797. CGHeroInstance * BattleInfo::battleGetFightingHero(ui8 side) const
  798. {
  799. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  800. }
  801. scripting::Pool * BattleInfo::getContextPool() const
  802. {
  803. //this is real battle, use global scripting context pool
  804. //TODO: make this line not ugly
  805. return IObjectInterface::cb->getGlobalContextPool();
  806. }
  807. bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b)
  808. {
  809. switch(phase)
  810. {
  811. case 0: //catapult moves after turrets
  812. return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
  813. case 1:
  814. case 2:
  815. case 3:
  816. {
  817. int as = a->getInitiative(turn), bs = b->getInitiative(turn);
  818. if(as != bs)
  819. return as > bs;
  820. if(a->unitSide() == b->unitSide())
  821. return a->unitSlot() < b->unitSlot();
  822. return (a->unitSide() == side || b->unitSide() == side)
  823. ? a->unitSide() != side
  824. : a->unitSide() < b->unitSide();
  825. }
  826. default:
  827. assert(false);
  828. return false;
  829. }
  830. assert(false);
  831. return false;
  832. }
  833. CMP_stack::CMP_stack(int Phase, int Turn, uint8_t Side)
  834. {
  835. phase = Phase;
  836. turn = Turn;
  837. side = Side;
  838. }