BattleInfo.cpp 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  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 "CObstacleInstance.h"
  13. #include "bonuses/Limiters.h"
  14. #include "bonuses/Updaters.h"
  15. #include "../CStack.h"
  16. #include "../CHeroHandler.h"
  17. #include "../filesystem/Filesystem.h"
  18. #include "../mapObjects/CGTownInstance.h"
  19. #include "../CGeneralTextHandler.h"
  20. #include "../BattleFieldHandler.h"
  21. #include "../ObstacleHandler.h"
  22. //TODO: remove
  23. #include "../IGameCallback.h"
  24. VCMI_LIB_NAMESPACE_BEGIN
  25. ///BattleInfo
  26. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackInstance & base, ui8 side, const SlotID & slot, BattleHex position)
  27. {
  28. PlayerColor owner = sides[side].color;
  29. assert(!owner.isValidPlayer() || (base.armyObj && base.armyObj->tempOwner == owner));
  30. auto * ret = new CStack(&base, owner, id, side, slot);
  31. ret->initialPosition = getAvaliableHex(base.getCreatureID(), side, position); //TODO: what if no free tile on battlefield was found?
  32. stacks.push_back(ret);
  33. return ret;
  34. }
  35. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackBasicDescriptor & base, ui8 side, const SlotID & slot, BattleHex position)
  36. {
  37. PlayerColor owner = sides[side].color;
  38. auto * ret = new CStack(&base, owner, id, side, slot);
  39. ret->initialPosition = position;
  40. stacks.push_back(ret);
  41. return ret;
  42. }
  43. void BattleInfo::localInit()
  44. {
  45. for(int i = 0; i < 2; i++)
  46. {
  47. auto * armyObj = battleGetArmyObject(i);
  48. armyObj->battle = this;
  49. armyObj->attachTo(*this);
  50. }
  51. for(CStack * s : stacks)
  52. s->localInit(this);
  53. exportBonuses();
  54. }
  55. namespace CGH
  56. {
  57. static void readBattlePositions(const JsonNode &node, std::vector< std::vector<int> > & dest)
  58. {
  59. for(const JsonNode &level : node.Vector())
  60. {
  61. std::vector<int> pom;
  62. for(const JsonNode &value : level.Vector())
  63. {
  64. pom.push_back(static_cast<int>(value.Float()));
  65. }
  66. dest.push_back(pom);
  67. }
  68. }
  69. }
  70. //RNG that works like H3 one
  71. struct RandGen
  72. {
  73. ui32 seed;
  74. void srand(ui32 s)
  75. {
  76. seed = s;
  77. }
  78. void srand(const int3 & pos)
  79. {
  80. srand(110291 * static_cast<ui32>(pos.x) + 167801 * static_cast<ui32>(pos.y) + 81569);
  81. }
  82. int rand()
  83. {
  84. seed = 214013 * seed + 2531011;
  85. return (seed >> 16) & 0x7FFF;
  86. }
  87. int rand(int min, int max)
  88. {
  89. if(min == max)
  90. return min;
  91. if(min > max)
  92. return min;
  93. return min + rand() % (max - min + 1);
  94. }
  95. };
  96. struct RangeGenerator
  97. {
  98. class ExhaustedPossibilities : public std::exception
  99. {
  100. };
  101. RangeGenerator(int _min, int _max, std::function<int()> _myRand):
  102. min(_min),
  103. remainingCount(_max - _min + 1),
  104. remaining(remainingCount, true),
  105. myRand(std::move(_myRand))
  106. {
  107. }
  108. int generateNumber() const
  109. {
  110. if(!remainingCount)
  111. throw ExhaustedPossibilities();
  112. if(remainingCount == 1)
  113. return 0;
  114. return myRand() % remainingCount;
  115. }
  116. //get number fulfilling predicate. Never gives the same number twice.
  117. int getSuchNumber(const std::function<bool(int)> & goodNumberPred = nullptr)
  118. {
  119. int ret = -1;
  120. do
  121. {
  122. int n = generateNumber();
  123. int i = 0;
  124. for(;;i++)
  125. {
  126. assert(i < (int)remaining.size());
  127. if(!remaining[i])
  128. continue;
  129. if(!n)
  130. break;
  131. n--;
  132. }
  133. remainingCount--;
  134. remaining[i] = false;
  135. ret = i + min;
  136. } while(goodNumberPred && !goodNumberPred(ret));
  137. return ret;
  138. }
  139. int min;
  140. int remainingCount;
  141. std::vector<bool> remaining;
  142. std::function<int()> myRand;
  143. };
  144. BattleInfo * BattleInfo::setupBattle(const int3 & tile, TerrainId terrain, const BattleField & battlefieldType, const CArmedInstance * armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance * town)
  145. {
  146. CMP_stack cmpst;
  147. auto * curB = new BattleInfo();
  148. for(auto i = 0u; i < curB->sides.size(); i++)
  149. curB->sides[i].init(heroes[i], armies[i]);
  150. std::vector<CStack*> & stacks = (curB->stacks);
  151. curB->tile = tile;
  152. curB->battlefieldType = battlefieldType;
  153. curB->round = -2;
  154. curB->activeStack = -1;
  155. curB->creatureBank = creatureBank;
  156. curB->replayAllowed = false;
  157. if(town)
  158. {
  159. curB->town = town;
  160. curB->terrainType = town->getNativeTerrain();
  161. }
  162. else
  163. {
  164. curB->town = nullptr;
  165. curB->terrainType = terrain;
  166. }
  167. //setting up siege obstacles
  168. if (town && town->hasFort())
  169. {
  170. curB->si.gateState = EGateState::CLOSED;
  171. curB->si.wallState[EWallPart::GATE] = EWallState::INTACT;
  172. for(const auto wall : {EWallPart::BOTTOM_WALL, EWallPart::BELOW_GATE, EWallPart::OVER_GATE, EWallPart::UPPER_WALL})
  173. {
  174. if (town->hasBuilt(BuildingID::CASTLE))
  175. curB->si.wallState[wall] = EWallState::REINFORCED;
  176. else
  177. curB->si.wallState[wall] = EWallState::INTACT;
  178. }
  179. if (town->hasBuilt(BuildingID::CITADEL))
  180. curB->si.wallState[EWallPart::KEEP] = EWallState::INTACT;
  181. if (town->hasBuilt(BuildingID::CASTLE))
  182. {
  183. curB->si.wallState[EWallPart::UPPER_TOWER] = EWallState::INTACT;
  184. curB->si.wallState[EWallPart::BOTTOM_TOWER] = EWallState::INTACT;
  185. }
  186. }
  187. //randomize obstacles
  188. if (town == nullptr && !creatureBank) //do it only when it's not siege and not creature bank
  189. {
  190. RandGen r{};
  191. auto ourRand = [&](){ return r.rand(); };
  192. r.srand(tile);
  193. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  194. int tilesToBlock = r.rand(5,12);
  195. std::vector<BattleHex> blockedTiles;
  196. auto appropriateAbsoluteObstacle = [&](int id)
  197. {
  198. const auto * info = Obstacle(id).getInfo();
  199. return info && info->isAbsoluteObstacle && info->isAppropriate(curB->terrainType, battlefieldType);
  200. };
  201. auto appropriateUsualObstacle = [&](int id)
  202. {
  203. const auto * info = Obstacle(id).getInfo();
  204. return info && !info->isAbsoluteObstacle && info->isAppropriate(curB->terrainType, battlefieldType);
  205. };
  206. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  207. {
  208. try
  209. {
  210. RangeGenerator obidgen(0, VLC->obstacleHandler->size() - 1, ourRand);
  211. auto obstPtr = std::make_shared<CObstacleInstance>();
  212. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  213. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  214. obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
  215. curB->obstacles.push_back(obstPtr);
  216. for(BattleHex blocked : obstPtr->getBlockedTiles())
  217. blockedTiles.push_back(blocked);
  218. tilesToBlock -= Obstacle(obstPtr->ID).getInfo()->blockedTiles.size() / 2;
  219. }
  220. catch(RangeGenerator::ExhaustedPossibilities &)
  221. {
  222. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  223. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occurred - cannot place absolute obstacle");
  224. }
  225. }
  226. try
  227. {
  228. while(tilesToBlock > 0)
  229. {
  230. RangeGenerator obidgen(0, VLC->obstacleHandler->size() - 1, ourRand);
  231. auto tileAccessibility = curB->getAccesibility();
  232. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  233. const ObstacleInfo &obi = *Obstacle(obid).getInfo();
  234. auto validPosition = [&](BattleHex pos) -> bool
  235. {
  236. if(obi.height >= pos.getY())
  237. return false;
  238. if(pos.getX() == 0)
  239. return false;
  240. if(pos.getX() + obi.width > 15)
  241. return false;
  242. if(vstd::contains(blockedTiles, pos))
  243. return false;
  244. for(BattleHex blocked : obi.getBlocked(pos))
  245. {
  246. if(tileAccessibility[blocked] == EAccessibility::UNAVAILABLE) //for ship-to-ship battlefield - exclude hardcoded unavailable tiles
  247. return false;
  248. if(vstd::contains(blockedTiles, blocked))
  249. return false;
  250. int x = blocked.getX();
  251. if(x <= 2 || x >= 14)
  252. return false;
  253. }
  254. return true;
  255. };
  256. RangeGenerator posgenerator(18, 168, ourRand);
  257. auto obstPtr = std::make_shared<CObstacleInstance>();
  258. obstPtr->ID = obid;
  259. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  260. obstPtr->uniqueID = static_cast<si32>(curB->obstacles.size());
  261. curB->obstacles.push_back(obstPtr);
  262. for(BattleHex blocked : obstPtr->getBlockedTiles())
  263. blockedTiles.push_back(blocked);
  264. tilesToBlock -= static_cast<int>(obi.blockedTiles.size());
  265. }
  266. }
  267. catch(RangeGenerator::ExhaustedPossibilities &)
  268. {
  269. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occurred - cannot place usual obstacle");
  270. }
  271. }
  272. //reading battleStartpos - add creatures AFTER random obstacles are generated
  273. //TODO: parse once to some structure
  274. std::vector<std::vector<int>> looseFormations[2];
  275. std::vector<std::vector<int>> tightFormations[2];
  276. std::vector<std::vector<int>> creBankFormations[2];
  277. std::vector<int> commanderField;
  278. std::vector<int> commanderBank;
  279. const JsonNode config(JsonPath::builtin("config/battleStartpos.json"));
  280. const JsonVector &positions = config["battle_positions"].Vector();
  281. CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
  282. CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
  283. CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
  284. CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
  285. CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
  286. CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
  287. for (auto position : config["commanderPositions"]["field"].Vector())
  288. {
  289. commanderField.push_back(static_cast<int>(position.Float()));
  290. }
  291. for (auto position : config["commanderPositions"]["creBank"].Vector())
  292. {
  293. commanderBank.push_back(static_cast<int>(position.Float()));
  294. }
  295. //adding war machines
  296. if(!creatureBank)
  297. {
  298. //Checks if hero has artifact and create appropriate stack
  299. auto handleWarMachine = [&](int side, const ArtifactPosition & artslot, BattleHex hex)
  300. {
  301. const CArtifactInstance * warMachineArt = heroes[side]->getArt(artslot);
  302. if(nullptr != warMachineArt)
  303. {
  304. CreatureID cre = warMachineArt->artType->getWarMachine();
  305. if(cre != CreatureID::NONE)
  306. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(cre, 1), side, SlotID::WAR_MACHINES_SLOT, hex);
  307. }
  308. };
  309. if(heroes[0])
  310. {
  311. handleWarMachine(0, ArtifactPosition::MACH1, 52);
  312. handleWarMachine(0, ArtifactPosition::MACH2, 18);
  313. handleWarMachine(0, ArtifactPosition::MACH3, 154);
  314. if(town && town->hasFort())
  315. handleWarMachine(0, ArtifactPosition::MACH4, 120);
  316. }
  317. if(heroes[1])
  318. {
  319. if(!town) //defending hero shouldn't receive ballista (bug #551)
  320. handleWarMachine(1, ArtifactPosition::MACH1, 66);
  321. handleWarMachine(1, ArtifactPosition::MACH2, 32);
  322. handleWarMachine(1, ArtifactPosition::MACH3, 168);
  323. }
  324. }
  325. //war machines added
  326. //battleStartpos read
  327. for(int side = 0; side < 2; side++)
  328. {
  329. int formationNo = armies[side]->stacksCount() - 1;
  330. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  331. int k = 0; //stack serial
  332. for(auto i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  333. {
  334. std::vector<int> *formationVector = nullptr;
  335. if(armies[side]->formation == EArmyFormation::TIGHT )
  336. formationVector = &tightFormations[side][formationNo];
  337. else
  338. formationVector = &looseFormations[side][formationNo];
  339. if(creatureBank)
  340. formationVector = &creBankFormations[side][formationNo];
  341. BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
  342. if(creatureBank && i->second->type->isDoubleWide())
  343. pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
  344. curB->generateNewStack(curB->nextUnitId(), *i->second, side, i->first, pos);
  345. }
  346. }
  347. //adding commanders
  348. for (int i = 0; i < 2; ++i)
  349. {
  350. if (heroes[i] && heroes[i]->commander && heroes[i]->commander->alive)
  351. {
  352. curB->generateNewStack(curB->nextUnitId(), *heroes[i]->commander, i, SlotID::COMMANDER_SLOT_PLACEHOLDER, creatureBank ? commanderBank[i] : commanderField[i]);
  353. }
  354. }
  355. if (curB->town && curB->town->fortLevel() >= CGTownInstance::CITADEL)
  356. {
  357. // keep tower
  358. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_CENTRAL_TOWER);
  359. if (curB->town->fortLevel() >= CGTownInstance::CASTLE)
  360. {
  361. // lower tower + upper tower
  362. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_UPPER_TOWER);
  363. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, BattleHex::CASTLE_BOTTOM_TOWER);
  364. }
  365. //Moat generating is done on server
  366. }
  367. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  368. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  369. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  370. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  371. const auto * bgInfo = VLC->battlefields()->getById(battlefieldType);
  372. for(const std::shared_ptr<Bonus> & bonus : bgInfo->bonuses)
  373. {
  374. curB->addNewBonus(bonus);
  375. }
  376. //native terrain bonuses
  377. static auto nativeTerrain = std::make_shared<CreatureTerrainLimiter>();
  378. curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::STACKS_SPEED, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID())->addLimiter(nativeTerrain));
  379. curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::ATTACK))->addLimiter(nativeTerrain));
  380. curB->addNewBonus(std::make_shared<Bonus>(BonusDuration::ONE_BATTLE, BonusType::PRIMARY_SKILL, BonusSource::TERRAIN_NATIVE, 1, BonusSourceID(), BonusSubtypeID(PrimarySkill::DEFENSE))->addLimiter(nativeTerrain));
  381. //////////////////////////////////////////////////////////////////////////
  382. //tactics
  383. bool isTacticsAllowed = !creatureBank; //no tactics in creature banks
  384. constexpr int sideSize = 2;
  385. std::array<int, sideSize> battleRepositionHex = {};
  386. std::array<int, sideSize> battleRepositionHexBlock = {};
  387. for(int i = 0; i < sideSize; i++)
  388. {
  389. if(heroes[i])
  390. {
  391. battleRepositionHex[i] += heroes[i]->valOfBonuses(Selector::type()(BonusType::BEFORE_BATTLE_REPOSITION));
  392. battleRepositionHexBlock[i] += heroes[i]->valOfBonuses(Selector::type()(BonusType::BEFORE_BATTLE_REPOSITION_BLOCK));
  393. }
  394. }
  395. int tacticsSkillDiffAttacker = battleRepositionHex[BattleSide::ATTACKER] - battleRepositionHexBlock[BattleSide::DEFENDER];
  396. int tacticsSkillDiffDefender = battleRepositionHex[BattleSide::DEFENDER] - battleRepositionHexBlock[BattleSide::ATTACKER];
  397. /* for current tactics, we need to choose one side, so, we will choose side when first - second > 0, and ignore sides
  398. when first - second <= 0. If there will be situations when both > 0, attacker will be chosen. Anyway, in OH3 this
  399. will not happen because tactics block opposite tactics on same value.
  400. TODO: For now, it is an error to use BEFORE_BATTLE_REPOSITION bonus without counterpart, but it can be changed if
  401. double tactics will be implemented.
  402. */
  403. if(isTacticsAllowed)
  404. {
  405. if(tacticsSkillDiffAttacker > 0 && tacticsSkillDiffDefender > 0)
  406. logGlobal->warn("Double tactics is not implemented, only attacker will have tactics!");
  407. if(tacticsSkillDiffAttacker > 0)
  408. {
  409. curB->tacticsSide = BattleSide::ATTACKER;
  410. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  411. curB->tacticDistance = 1 + tacticsSkillDiffAttacker;
  412. }
  413. else if(tacticsSkillDiffDefender > 0)
  414. {
  415. curB->tacticsSide = BattleSide::DEFENDER;
  416. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  417. curB->tacticDistance = 1 + tacticsSkillDiffDefender;
  418. }
  419. else
  420. curB->tacticDistance = 0;
  421. }
  422. return curB;
  423. }
  424. const CGHeroInstance * BattleInfo::getHero(const PlayerColor & player) const
  425. {
  426. for(const auto & side : sides)
  427. if(side.color == player)
  428. return side.hero;
  429. logGlobal->error("Player %s is not in battle!", player.toString());
  430. return nullptr;
  431. }
  432. ui8 BattleInfo::whatSide(const PlayerColor & player) const
  433. {
  434. for(int i = 0; i < sides.size(); i++)
  435. if(sides[i].color == player)
  436. return i;
  437. logGlobal->warn("BattleInfo::whatSide: Player %s is not in battle!", player.toString());
  438. return -1;
  439. }
  440. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  441. {
  442. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  443. }
  444. BattleInfo::BattleInfo():
  445. round(-1),
  446. activeStack(-1),
  447. town(nullptr),
  448. tile(-1,-1,-1),
  449. battlefieldType(BattleField::NONE),
  450. tacticsSide(0),
  451. tacticDistance(0)
  452. {
  453. setNodeType(BATTLE);
  454. }
  455. BattleID BattleInfo::getBattleID() const
  456. {
  457. return battleID;
  458. }
  459. const IBattleInfo * BattleInfo::getBattle() const
  460. {
  461. return this;
  462. }
  463. std::optional<PlayerColor> BattleInfo::getPlayerID() const
  464. {
  465. return std::nullopt;
  466. }
  467. BattleInfo::~BattleInfo()
  468. {
  469. for (auto & elem : stacks)
  470. delete elem;
  471. for(int i = 0; i < 2; i++)
  472. if(auto * _armyObj = battleGetArmyObject(i))
  473. _armyObj->battle = nullptr;
  474. }
  475. int32_t BattleInfo::getActiveStackID() const
  476. {
  477. return activeStack;
  478. }
  479. TStacks BattleInfo::getStacksIf(const TStackFilter & predicate) const
  480. {
  481. TStacks ret;
  482. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  483. return ret;
  484. }
  485. battle::Units BattleInfo::getUnitsIf(const battle::UnitFilter & predicate) const
  486. {
  487. battle::Units ret;
  488. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  489. return ret;
  490. }
  491. BattleField BattleInfo::getBattlefieldType() const
  492. {
  493. return battlefieldType;
  494. }
  495. TerrainId BattleInfo::getTerrainType() const
  496. {
  497. return terrainType;
  498. }
  499. IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
  500. {
  501. ObstacleCList ret;
  502. for(const auto & obstacle : obstacles)
  503. ret.push_back(obstacle);
  504. return ret;
  505. }
  506. PlayerColor BattleInfo::getSidePlayer(ui8 side) const
  507. {
  508. return sides.at(side).color;
  509. }
  510. const CArmedInstance * BattleInfo::getSideArmy(ui8 side) const
  511. {
  512. return sides.at(side).armyObject;
  513. }
  514. const CGHeroInstance * BattleInfo::getSideHero(ui8 side) const
  515. {
  516. return sides.at(side).hero;
  517. }
  518. ui8 BattleInfo::getTacticDist() const
  519. {
  520. return tacticDistance;
  521. }
  522. ui8 BattleInfo::getTacticsSide() const
  523. {
  524. return tacticsSide;
  525. }
  526. const CGTownInstance * BattleInfo::getDefendedTown() const
  527. {
  528. return town;
  529. }
  530. EWallState BattleInfo::getWallState(EWallPart partOfWall) const
  531. {
  532. return si.wallState.at(partOfWall);
  533. }
  534. EGateState BattleInfo::getGateState() const
  535. {
  536. return si.gateState;
  537. }
  538. uint32_t BattleInfo::getCastSpells(ui8 side) const
  539. {
  540. return sides.at(side).castSpellsCount;
  541. }
  542. int32_t BattleInfo::getEnchanterCounter(ui8 side) const
  543. {
  544. return sides.at(side).enchanterCounter;
  545. }
  546. const IBonusBearer * BattleInfo::getBonusBearer() const
  547. {
  548. return this;
  549. }
  550. int64_t BattleInfo::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  551. {
  552. if(damage.min != damage.max)
  553. {
  554. int64_t sum = 0;
  555. auto howManyToAv = std::min<int32_t>(10, attackerCount);
  556. auto rangeGen = rng.getInt64Range(damage.min, damage.max);
  557. for(int32_t g = 0; g < howManyToAv; ++g)
  558. sum += rangeGen();
  559. return sum / howManyToAv;
  560. }
  561. else
  562. {
  563. return damage.min;
  564. }
  565. }
  566. int3 BattleInfo::getLocation() const
  567. {
  568. return tile;
  569. }
  570. bool BattleInfo::isCreatureBank() const
  571. {
  572. return creatureBank;
  573. }
  574. std::vector<SpellID> BattleInfo::getUsedSpells(ui8 side) const
  575. {
  576. return sides.at(side).usedSpellsHistory;
  577. }
  578. void BattleInfo::nextRound()
  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 += 1;
  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 == BonusSource::SPELL_EFFECT && b->sid.as<SpellID>() != 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(BonusSource::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. auto obstacle = std::make_shared<SpellCreatedObstacle>();
  801. obstacle->fromInfo(changes);
  802. obstacles.push_back(obstacle);
  803. }
  804. void BattleInfo::updateObstacle(const ObstacleChanges& changes)
  805. {
  806. auto 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 battleGetFightingHero(0)->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