BattleInfo.cpp 28 KB

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