BattleInfo.cpp 28 KB

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