BattleInfo.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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 CStack * stack)
  25. {
  26. auto reachability = getReachability(stack);
  27. if(reachability.predecessors[dest] == -1) //cannot reach destination
  28. {
  29. return std::make_pair(std::vector<BattleHex>(), 0);
  30. }
  31. //making the Path
  32. std::vector<BattleHex> path;
  33. BattleHex curElem = dest;
  34. while(curElem != start)
  35. {
  36. path.push_back(curElem);
  37. curElem = reachability.predecessors[curElem];
  38. }
  39. return std::make_pair(path, reachability.distances[dest]);
  40. }
  41. void BattleInfo::calculateCasualties(std::map<ui32,si32> * casualties) const
  42. {
  43. for(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
  389. auto moat = std::make_shared<MoatObstacle>();
  390. moat->ID = curB->town->subID;
  391. moat->obstacleType = CObstacleInstance::MOAT;
  392. moat->uniqueID = static_cast<si32>(curB->obstacles.size());
  393. curB->obstacles.push_back(moat);
  394. }
  395. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  396. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  397. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  398. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  399. const auto * bgInfo = VLC->battlefields()->getById(battlefieldType);
  400. for(const std::shared_ptr<Bonus> & bonus : bgInfo->bonuses)
  401. {
  402. curB->addNewBonus(bonus);
  403. }
  404. //native terrain bonuses
  405. static auto nativeTerrain = std::make_shared<CreatureTerrainLimiter>();
  406. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::STACKS_SPEED, Bonus::TERRAIN_NATIVE, 1, 0, 0)->addLimiter(nativeTerrain));
  407. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::ATTACK)->addLimiter(nativeTerrain));
  408. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::DEFENSE)->addLimiter(nativeTerrain));
  409. //////////////////////////////////////////////////////////////////////////
  410. //tactics
  411. bool isTacticsAllowed = !creatureBank; //no tactics in creature banks
  412. constexpr int sideSize = 2;
  413. std::array<int, sideSize> battleRepositionHex = {};
  414. std::array<int, sideSize> battleRepositionHexBlock = {};
  415. for(int i = 0; i < sideSize; i++)
  416. {
  417. if(heroes[i])
  418. {
  419. battleRepositionHex[i] += heroes[i]->valOfBonuses(Selector::type()(Bonus::BEFORE_BATTLE_REPOSITION));
  420. battleRepositionHexBlock[i] += heroes[i]->valOfBonuses(Selector::type()(Bonus::BEFORE_BATTLE_REPOSITION_BLOCK));
  421. }
  422. }
  423. int tacticsSkillDiffAttacker = battleRepositionHex[BattleSide::ATTACKER] - battleRepositionHexBlock[BattleSide::DEFENDER];
  424. int tacticsSkillDiffDefender = battleRepositionHex[BattleSide::DEFENDER] - battleRepositionHexBlock[BattleSide::ATTACKER];
  425. /* for current tactics, we need to choose one side, so, we will choose side when first - second > 0, and ignore sides
  426. when first - second <= 0. If there will be situations when both > 0, attacker will be chosen. Anyway, in OH3 this
  427. will not happen because tactics block opposite tactics on same value.
  428. TODO: For now, it is an error to use BEFORE_BATTLE_REPOSITION bonus without counterpart, but it can be changed if
  429. double tactics will be implemented.
  430. */
  431. if(isTacticsAllowed)
  432. {
  433. if(tacticsSkillDiffAttacker > 0 && tacticsSkillDiffDefender > 0)
  434. logGlobal->warn("Double tactics is not implemented, only attacker will have tactics!");
  435. if(tacticsSkillDiffAttacker > 0)
  436. {
  437. curB->tacticsSide = BattleSide::ATTACKER;
  438. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  439. curB->tacticDistance = 1 + tacticsSkillDiffAttacker;
  440. }
  441. else if(tacticsSkillDiffDefender > 0)
  442. {
  443. curB->tacticsSide = BattleSide::DEFENDER;
  444. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  445. curB->tacticDistance = 1 + tacticsSkillDiffDefender;
  446. }
  447. else
  448. curB->tacticDistance = 0;
  449. }
  450. return curB;
  451. }
  452. const CGHeroInstance * BattleInfo::getHero(const PlayerColor & player) const
  453. {
  454. for(const auto & side : sides)
  455. if(side.color == player)
  456. return side.hero;
  457. logGlobal->error("Player %s is not in battle!", player.getStr());
  458. return nullptr;
  459. }
  460. ui8 BattleInfo::whatSide(const PlayerColor & player) const
  461. {
  462. for(int i = 0; i < sides.size(); i++)
  463. if(sides[i].color == player)
  464. return i;
  465. logGlobal->warn("BattleInfo::whatSide: Player %s is not in battle!", player.getStr());
  466. return -1;
  467. }
  468. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  469. {
  470. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  471. }
  472. BattleInfo::BattleInfo():
  473. round(-1),
  474. activeStack(-1),
  475. town(nullptr),
  476. tile(-1,-1,-1),
  477. battlefieldType(BattleField::NONE),
  478. tacticsSide(0),
  479. tacticDistance(0)
  480. {
  481. setBattle(this);
  482. setNodeType(BATTLE);
  483. }
  484. BattleInfo::~BattleInfo() = default;
  485. int32_t BattleInfo::getActiveStackID() const
  486. {
  487. return activeStack;
  488. }
  489. TStacks BattleInfo::getStacksIf(TStackFilter predicate) const
  490. {
  491. TStacks ret;
  492. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  493. return ret;
  494. }
  495. battle::Units BattleInfo::getUnitsIf(battle::UnitFilter predicate) const
  496. {
  497. battle::Units ret;
  498. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  499. return ret;
  500. }
  501. BattleField BattleInfo::getBattlefieldType() const
  502. {
  503. return battlefieldType;
  504. }
  505. TerrainId BattleInfo::getTerrainType() const
  506. {
  507. return terrainType;
  508. }
  509. IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
  510. {
  511. ObstacleCList ret;
  512. for(const auto & obstacle : obstacles)
  513. ret.push_back(obstacle);
  514. return ret;
  515. }
  516. PlayerColor BattleInfo::getSidePlayer(ui8 side) const
  517. {
  518. return sides.at(side).color;
  519. }
  520. const CArmedInstance * BattleInfo::getSideArmy(ui8 side) const
  521. {
  522. return sides.at(side).armyObject;
  523. }
  524. const CGHeroInstance * BattleInfo::getSideHero(ui8 side) const
  525. {
  526. return sides.at(side).hero;
  527. }
  528. ui8 BattleInfo::getTacticDist() const
  529. {
  530. return tacticDistance;
  531. }
  532. ui8 BattleInfo::getTacticsSide() const
  533. {
  534. return tacticsSide;
  535. }
  536. const CGTownInstance * BattleInfo::getDefendedTown() const
  537. {
  538. return town;
  539. }
  540. EWallState BattleInfo::getWallState(EWallPart partOfWall) const
  541. {
  542. return si.wallState.at(partOfWall);
  543. }
  544. EGateState BattleInfo::getGateState() const
  545. {
  546. return si.gateState;
  547. }
  548. uint32_t BattleInfo::getCastSpells(ui8 side) const
  549. {
  550. return sides.at(side).castSpellsCount;
  551. }
  552. int32_t BattleInfo::getEnchanterCounter(ui8 side) const
  553. {
  554. return sides.at(side).enchanterCounter;
  555. }
  556. const IBonusBearer * BattleInfo::asBearer() const
  557. {
  558. return this;
  559. }
  560. int64_t BattleInfo::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  561. {
  562. if(damage.min != damage.max)
  563. {
  564. int64_t sum = 0;
  565. auto howManyToAv = std::min<int32_t>(10, attackerCount);
  566. auto rangeGen = rng.getInt64Range(damage.min, damage.max);
  567. for(int32_t g = 0; g < howManyToAv; ++g)
  568. sum += rangeGen();
  569. return sum / howManyToAv;
  570. }
  571. else
  572. {
  573. return damage.min;
  574. }
  575. }
  576. void BattleInfo::nextRound(int32_t roundNr)
  577. {
  578. for(int i = 0; i < 2; ++i)
  579. {
  580. sides.at(i).castSpellsCount = 0;
  581. vstd::amax(--sides.at(i).enchanterCounter, 0);
  582. }
  583. round = roundNr;
  584. for(CStack * s : stacks)
  585. {
  586. // new turn effects
  587. s->reduceBonusDurations(Bonus::NTurns);
  588. s->afterNewRound();
  589. }
  590. for(auto & obst : obstacles)
  591. obst->battleTurnPassed();
  592. }
  593. void BattleInfo::nextTurn(uint32_t unitId)
  594. {
  595. activeStack = unitId;
  596. CStack * st = getStack(activeStack);
  597. //remove bonuses that last until when stack gets new turn
  598. st->removeBonusesRecursive(Bonus::UntilGetsTurn);
  599. st->afterGetsTurn();
  600. }
  601. void BattleInfo::addUnit(uint32_t id, const JsonNode & data)
  602. {
  603. battle::UnitInfo info;
  604. info.load(id, data);
  605. CStackBasicDescriptor base(info.type, info.count);
  606. PlayerColor owner = getSidePlayer(info.side);
  607. auto * ret = new CStack(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  608. ret->initialPosition = info.position;
  609. stacks.push_back(ret);
  610. ret->localInit(this);
  611. ret->summoned = info.summoned;
  612. }
  613. void BattleInfo::moveUnit(uint32_t id, BattleHex destination)
  614. {
  615. auto * sta = getStack(id);
  616. if(!sta)
  617. {
  618. logGlobal->error("Cannot find stack %d", id);
  619. return;
  620. }
  621. sta->position = destination;
  622. //Bonuses can be limited by unit placement, so, change tree version
  623. //to force updating a bonus. TODO: update version only when such bonuses are present
  624. CBonusSystemNode::treeHasChanged();
  625. }
  626. void BattleInfo::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  627. {
  628. CStack * changedStack = getStack(id, false);
  629. if(!changedStack)
  630. throw std::runtime_error("Invalid unit id in BattleInfo update");
  631. if(!changedStack->alive() && healthDelta > 0)
  632. {
  633. //checking if we resurrect a stack that is under a living stack
  634. auto accessibility = getAccesibility();
  635. if(!accessibility.accessible(changedStack->getPosition(), changedStack))
  636. {
  637. logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->getPosition().hex);
  638. return; //position is already occupied
  639. }
  640. }
  641. bool killed = (-healthDelta) >= changedStack->getAvailableHealth();//todo: check using alive state once rebirth will be handled separately
  642. bool resurrected = !changedStack->alive() && healthDelta > 0;
  643. //applying changes
  644. changedStack->load(data);
  645. if(healthDelta < 0)
  646. {
  647. changedStack->removeBonusesRecursive(Bonus::UntilBeingAttacked);
  648. }
  649. resurrected = resurrected || (killed && changedStack->alive());
  650. if(killed)
  651. {
  652. if(changedStack->cloneID >= 0)
  653. {
  654. //remove clone as well
  655. CStack * clone = getStack(changedStack->cloneID);
  656. if(clone)
  657. clone->makeGhost();
  658. changedStack->cloneID = -1;
  659. }
  660. }
  661. if(resurrected || killed)
  662. {
  663. //removing all spells effects
  664. auto selector = [](const Bonus * b)
  665. {
  666. //Special case: DISRUPTING_RAY is absolutely permanent
  667. return b->source == Bonus::SPELL_EFFECT && b->sid != SpellID::DISRUPTING_RAY;
  668. };
  669. changedStack->removeBonusesRecursive(selector);
  670. }
  671. if(!changedStack->alive() && changedStack->isClone())
  672. {
  673. for(CStack * s : stacks)
  674. {
  675. if(s->cloneID == changedStack->unitId())
  676. s->cloneID = -1;
  677. }
  678. }
  679. }
  680. void BattleInfo::removeUnit(uint32_t id)
  681. {
  682. std::set<uint32_t> ids;
  683. ids.insert(id);
  684. while(!ids.empty())
  685. {
  686. auto toRemoveId = *ids.begin();
  687. auto * toRemove = getStack(toRemoveId, false);
  688. if(!toRemove)
  689. {
  690. logGlobal->error("Cannot find stack %d", toRemoveId);
  691. return;
  692. }
  693. if(!toRemove->ghost)
  694. {
  695. toRemove->onRemoved();
  696. toRemove->detachFromAll();
  697. //stack may be removed instantly (not being killed first)
  698. //handle clone remove also here
  699. if(toRemove->cloneID >= 0)
  700. {
  701. ids.insert(toRemove->cloneID);
  702. toRemove->cloneID = -1;
  703. }
  704. //cleanup remaining clone links if any
  705. for(auto * s : stacks)
  706. {
  707. if(s->cloneID == toRemoveId)
  708. s->cloneID = -1;
  709. }
  710. }
  711. ids.erase(toRemoveId);
  712. }
  713. }
  714. void BattleInfo::updateUnit(uint32_t id, const JsonNode & data)
  715. {
  716. //TODO
  717. }
  718. void BattleInfo::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  719. {
  720. CStack * sta = getStack(id, false);
  721. if(!sta)
  722. {
  723. logGlobal->error("Cannot find stack %d", id);
  724. return;
  725. }
  726. for(const Bonus & b : bonus)
  727. addOrUpdateUnitBonus(sta, b, true);
  728. }
  729. void BattleInfo::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  730. {
  731. CStack * sta = getStack(id, false);
  732. if(!sta)
  733. {
  734. logGlobal->error("Cannot find stack %d", id);
  735. return;
  736. }
  737. for(const Bonus & b : bonus)
  738. addOrUpdateUnitBonus(sta, b, false);
  739. }
  740. void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  741. {
  742. CStack * sta = getStack(id, false);
  743. if(!sta)
  744. {
  745. logGlobal->error("Cannot find stack %d", id);
  746. return;
  747. }
  748. for(const Bonus & one : bonus)
  749. {
  750. auto selector = [one](const Bonus * b)
  751. {
  752. //compare everything but turnsRemain, limiter and propagator
  753. return one.duration == b->duration
  754. && one.type == b->type
  755. && one.subtype == b->subtype
  756. && one.source == b->source
  757. && one.val == b->val
  758. && one.sid == b->sid
  759. && one.valType == b->valType
  760. && one.additionalInfo == b->additionalInfo
  761. && one.effectRange == b->effectRange
  762. && one.description == b->description;
  763. };
  764. sta->removeBonusesRecursive(selector);
  765. }
  766. }
  767. uint32_t BattleInfo::nextUnitId() const
  768. {
  769. return static_cast<uint32_t>(stacks.size());
  770. }
  771. void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)
  772. {
  773. if(forceAdd || !sta->hasBonus(Selector::source(Bonus::SPELL_EFFECT, value.sid).And(Selector::typeSubtype(value.type, value.subtype))))
  774. {
  775. //no such effect or cumulative - add new
  776. logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), value.Description());
  777. sta->addNewBonus(std::make_shared<Bonus>(value));
  778. }
  779. else
  780. {
  781. logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description());
  782. for(const auto & stackBonus : sta->getExportedBonusList()) //TODO: optimize
  783. {
  784. if(stackBonus->source == value.source && stackBonus->sid == value.sid && stackBonus->type == value.type && stackBonus->subtype == value.subtype)
  785. {
  786. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, value.turnsRemain);
  787. }
  788. }
  789. CBonusSystemNode::treeHasChanged();
  790. }
  791. }
  792. void BattleInfo::setWallState(EWallPart partOfWall, EWallState state)
  793. {
  794. si.wallState[partOfWall] = state;
  795. }
  796. void BattleInfo::addObstacle(const ObstacleChanges & changes)
  797. {
  798. std::shared_ptr<SpellCreatedObstacle> obstacle = std::make_shared<SpellCreatedObstacle>();
  799. obstacle->fromInfo(changes);
  800. obstacles.push_back(obstacle);
  801. }
  802. void BattleInfo::updateObstacle(const ObstacleChanges& changes)
  803. {
  804. std::shared_ptr<SpellCreatedObstacle> changedObstacle = std::make_shared<SpellCreatedObstacle>();
  805. changedObstacle->fromInfo(changes);
  806. for(auto & obstacle : obstacles)
  807. {
  808. if(obstacle->uniqueID == changes.id) // update this obstacle
  809. {
  810. auto * spellObstacle = dynamic_cast<SpellCreatedObstacle *>(obstacle.get());
  811. assert(spellObstacle);
  812. // Currently we only support to update the "revealed" property
  813. spellObstacle->revealed = changedObstacle->revealed;
  814. break;
  815. }
  816. }
  817. }
  818. void BattleInfo::removeObstacle(uint32_t id)
  819. {
  820. for(int i=0; i < obstacles.size(); ++i)
  821. {
  822. if(obstacles[i]->uniqueID == id) //remove this obstacle
  823. {
  824. obstacles.erase(obstacles.begin() + i);
  825. break;
  826. }
  827. }
  828. }
  829. CArmedInstance * BattleInfo::battleGetArmyObject(ui8 side) const
  830. {
  831. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  832. }
  833. CGHeroInstance * BattleInfo::battleGetFightingHero(ui8 side) const
  834. {
  835. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  836. }
  837. #if SCRIPTING_ENABLED
  838. scripting::Pool * BattleInfo::getContextPool() const
  839. {
  840. //this is real battle, use global scripting context pool
  841. //TODO: make this line not ugly
  842. return IObjectInterface::cb->getGlobalContextPool();
  843. }
  844. #endif
  845. bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b) const
  846. {
  847. switch(phase)
  848. {
  849. case 0: //catapult moves after turrets
  850. return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
  851. case 1:
  852. case 2:
  853. case 3:
  854. {
  855. int as = a->getInitiative(turn);
  856. int bs = b->getInitiative(turn);
  857. if(as != bs)
  858. return as > bs;
  859. if(a->unitSide() == b->unitSide())
  860. return a->unitSlot() < b->unitSlot();
  861. return (a->unitSide() == side || b->unitSide() == side)
  862. ? a->unitSide() != side
  863. : a->unitSide() < b->unitSide();
  864. }
  865. default:
  866. assert(false);
  867. return false;
  868. }
  869. assert(false);
  870. return false;
  871. }
  872. CMP_stack::CMP_stack(int Phase, int Turn, uint8_t Side):
  873. phase(Phase),
  874. turn(Turn),
  875. side(Side)
  876. {
  877. }
  878. VCMI_LIB_NAMESPACE_END