BattleInfo.cpp 28 KB

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