BattleInfo.cpp 26 KB

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