BattleInfo.cpp 28 KB

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