BattleInfo.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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. const CStack * BattleInfo::getNextStack() const
  18. {
  19. std::vector<const CStack *> hlp;
  20. battleGetStackQueue(hlp, 1, -1);
  21. if(hlp.size())
  22. return hlp[0];
  23. else
  24. return nullptr;
  25. }
  26. int BattleInfo::getAvaliableHex(CreatureID creID, ui8 side, int initialPos) const
  27. {
  28. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  29. //bool flying = VLC->creh->creatures[creID]->isFlying();
  30. int pos;
  31. if (initialPos > -1)
  32. pos = initialPos;
  33. else //summon elementals depending on player side
  34. {
  35. if(side == BattleSide::ATTACKER)
  36. pos = 0; //top left
  37. else
  38. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  39. }
  40. auto accessibility = getAccesibility();
  41. std::set<BattleHex> occupyable;
  42. for(int i = 0; i < accessibility.size(); i++)
  43. if(accessibility.accessible(i, twoHex, side))
  44. occupyable.insert(i);
  45. if (occupyable.empty())
  46. {
  47. return BattleHex::INVALID; //all tiles are covered
  48. }
  49. return BattleHex::getClosestTile(side, pos, occupyable);
  50. }
  51. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, const CStack * stack)
  52. {
  53. auto reachability = getReachability(stack);
  54. if(reachability.predecessors[dest] == -1) //cannot reach destination
  55. {
  56. return std::make_pair(std::vector<BattleHex>(), 0);
  57. }
  58. //making the Path
  59. std::vector<BattleHex> path;
  60. BattleHex curElem = dest;
  61. while(curElem != start)
  62. {
  63. path.push_back(curElem);
  64. curElem = reachability.predecessors[curElem];
  65. }
  66. return std::make_pair(path, reachability.distances[dest]);
  67. }
  68. ui32 BattleInfo::calculateDmg(const CStack * attacker, const CStack * defender,
  69. bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg, CRandomGenerator & rand)
  70. {
  71. BattleAttackInfo bai(attacker, defender, shooting);
  72. bai.chargedFields = charge;
  73. bai.luckyHit = lucky;
  74. bai.unluckyHit = unlucky;
  75. bai.deathBlow = deathBlow;
  76. bai.ballistaDoubleDamage = ballistaDoubleDmg;
  77. TDmgRange range = calculateDmgRange(bai);
  78. if(range.first != range.second)
  79. {
  80. ui32 sum = 0;
  81. ui32 howManyToAv = std::min<ui32>(10, attacker->getCount());
  82. for(int g=0; g<howManyToAv; ++g)
  83. sum += (ui32)rand.nextInt(range.first, range.second);
  84. return sum / howManyToAv;
  85. }
  86. else
  87. return range.first;
  88. }
  89. void BattleInfo::calculateCasualties(std::map<ui32,si32> * casualties) const
  90. {
  91. for(auto & elem : stacks)//setting casualties
  92. {
  93. const CStack * const st = elem;
  94. si32 killed = st->getKilled();
  95. if(killed > 0)
  96. casualties[st->side][st->getCreature()->idNumber] += killed;
  97. }
  98. }
  99. CStack * BattleInfo::generateNewStack(const CStackInstance & base, ui8 side, SlotID slot, BattleHex position) const
  100. {
  101. int stackID = getIdForNewStack();
  102. PlayerColor owner = sides[side].color;
  103. assert((owner >= PlayerColor::PLAYER_LIMIT) ||
  104. (base.armyObj && base.armyObj->tempOwner == owner));
  105. auto ret = new CStack(&base, owner, stackID, side, slot);
  106. ret->position = getAvaliableHex(base.getCreatureID(), side, position); //TODO: what if no free tile on battlefield was found?
  107. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  108. return ret;
  109. }
  110. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor & base, ui8 side, SlotID slot, BattleHex position) const
  111. {
  112. int stackID = getIdForNewStack();
  113. PlayerColor owner = sides[side].color;
  114. auto ret = new CStack(&base, owner, stackID, side, slot);
  115. ret->position = position;
  116. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  117. return ret;
  118. }
  119. void BattleInfo::localInit()
  120. {
  121. for(int i = 0; i < 2; i++)
  122. {
  123. auto armyObj = battleGetArmyObject(i);
  124. armyObj->battle = this;
  125. armyObj->attachTo(this);
  126. }
  127. for(CStack * s : stacks)
  128. s->localInit(this);
  129. exportBonuses();
  130. }
  131. namespace CGH
  132. {
  133. static void readBattlePositions(const JsonNode &node, std::vector< std::vector<int> > & dest)
  134. {
  135. for(const JsonNode &level : node.Vector())
  136. {
  137. std::vector<int> pom;
  138. for(const JsonNode &value : level.Vector())
  139. {
  140. pom.push_back(value.Float());
  141. }
  142. dest.push_back(pom);
  143. }
  144. }
  145. }
  146. //RNG that works like H3 one
  147. struct RandGen
  148. {
  149. int seed;
  150. void srand(int s)
  151. {
  152. seed = s;
  153. }
  154. void srand(int3 pos)
  155. {
  156. srand(110291 * pos.x + 167801 * pos.y + 81569);
  157. }
  158. int rand()
  159. {
  160. seed = 214013 * seed + 2531011;
  161. return (seed >> 16) & 0x7FFF;
  162. }
  163. int rand(int min, int max)
  164. {
  165. if(min == max)
  166. return min;
  167. if(min > max)
  168. return min;
  169. return min + rand() % (max - min + 1);
  170. }
  171. };
  172. struct RangeGenerator
  173. {
  174. class ExhaustedPossibilities : public std::exception
  175. {
  176. };
  177. RangeGenerator(int _min, int _max, std::function<int()> _myRand):
  178. min(_min),
  179. remainingCount(_max - _min + 1),
  180. remaining(remainingCount, true),
  181. myRand(_myRand)
  182. {
  183. }
  184. int generateNumber()
  185. {
  186. if(!remainingCount)
  187. throw ExhaustedPossibilities();
  188. if(remainingCount == 1)
  189. return 0;
  190. return myRand() % remainingCount;
  191. }
  192. //get number fulfilling predicate. Never gives the same number twice.
  193. int getSuchNumber(std::function<bool(int)> goodNumberPred = nullptr)
  194. {
  195. int ret = -1;
  196. do
  197. {
  198. int n = generateNumber();
  199. int i = 0;
  200. for(;;i++)
  201. {
  202. assert(i < (int)remaining.size());
  203. if(!remaining[i])
  204. continue;
  205. if(!n)
  206. break;
  207. n--;
  208. }
  209. remainingCount--;
  210. remaining[i] = false;
  211. ret = i + min;
  212. } while(goodNumberPred && !goodNumberPred(ret));
  213. return ret;
  214. }
  215. int min, remainingCount;
  216. std::vector<bool> remaining;
  217. std::function<int()> myRand;
  218. };
  219. BattleInfo * BattleInfo::setupBattle(int3 tile, ETerrainType terrain, BFieldType battlefieldType, const CArmedInstance * armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance * town)
  220. {
  221. CMP_stack cmpst;
  222. auto curB = new BattleInfo();
  223. for(auto i = 0u; i < curB->sides.size(); i++)
  224. curB->sides[i].init(heroes[i], armies[i]);
  225. std::vector<CStack*> & stacks = (curB->stacks);
  226. curB->tile = tile;
  227. curB->battlefieldType = battlefieldType;
  228. curB->round = -2;
  229. curB->activeStack = -1;
  230. if(town)
  231. {
  232. curB->town = town;
  233. curB->terrainType = VLC->townh->factions[town->subID]->nativeTerrain;
  234. }
  235. else
  236. {
  237. curB->town = nullptr;
  238. curB->terrainType = terrain;
  239. }
  240. //setting up siege obstacles
  241. if (town && town->hasFort())
  242. {
  243. curB->si.gateState = EGateState::CLOSED;
  244. for (int b = 0; b < curB->si.wallState.size(); ++b)
  245. {
  246. curB->si.wallState[b] = EWallState::INTACT;
  247. }
  248. if (!town->hasBuilt(BuildingID::CITADEL))
  249. {
  250. curB->si.wallState[EWallPart::KEEP] = EWallState::NONE;
  251. }
  252. if (!town->hasBuilt(BuildingID::CASTLE))
  253. {
  254. curB->si.wallState[EWallPart::UPPER_TOWER] = EWallState::NONE;
  255. curB->si.wallState[EWallPart::BOTTOM_TOWER] = EWallState::NONE;
  256. }
  257. }
  258. //randomize obstacles
  259. if (town == nullptr && !creatureBank) //do it only when it's not siege and not creature bank
  260. {
  261. const int ABSOLUTE_OBSTACLES_COUNT = 34, USUAL_OBSTACLES_COUNT = 91; //shouldn't be changes if we want H3-like obstacle placement
  262. RandGen r;
  263. auto ourRand = [&]{ return r.rand(); };
  264. r.srand(tile);
  265. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  266. int tilesToBlock = r.rand(5,12);
  267. const int specialBattlefield = battlefieldTypeToBI(battlefieldType);
  268. std::vector<BattleHex> blockedTiles;
  269. auto appropriateAbsoluteObstacle = [&](int id)
  270. {
  271. return VLC->heroh->absoluteObstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  272. };
  273. auto appropriateUsualObstacle = [&](int id) -> bool
  274. {
  275. return VLC->heroh->obstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  276. };
  277. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  278. {
  279. RangeGenerator obidgen(0, ABSOLUTE_OBSTACLES_COUNT-1, ourRand);
  280. try
  281. {
  282. auto obstPtr = std::make_shared<CObstacleInstance>();
  283. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  284. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  285. obstPtr->uniqueID = curB->obstacles.size();
  286. curB->obstacles.push_back(obstPtr);
  287. for(BattleHex blocked : obstPtr->getBlockedTiles())
  288. blockedTiles.push_back(blocked);
  289. tilesToBlock -= VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
  290. }
  291. catch(RangeGenerator::ExhaustedPossibilities &)
  292. {
  293. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  294. }
  295. }
  296. RangeGenerator obidgen(0, USUAL_OBSTACLES_COUNT-1, ourRand);
  297. try
  298. {
  299. while(tilesToBlock > 0)
  300. {
  301. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  302. const CObstacleInfo &obi = VLC->heroh->obstacles[obid];
  303. auto validPosition = [&](BattleHex pos) -> bool
  304. {
  305. if(obi.height >= pos.getY())
  306. return false;
  307. if(pos.getX() == 0)
  308. return false;
  309. if(pos.getX() + obi.width > 15)
  310. return false;
  311. if(vstd::contains(blockedTiles, pos))
  312. return false;
  313. for(BattleHex blocked : obi.getBlocked(pos))
  314. {
  315. if(vstd::contains(blockedTiles, blocked))
  316. return false;
  317. int x = blocked.getX();
  318. if(x <= 2 || x >= 14)
  319. return false;
  320. }
  321. return true;
  322. };
  323. RangeGenerator posgenerator(18, 168, ourRand);
  324. auto obstPtr = std::make_shared<CObstacleInstance>();
  325. obstPtr->ID = obid;
  326. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  327. obstPtr->uniqueID = curB->obstacles.size();
  328. curB->obstacles.push_back(obstPtr);
  329. for(BattleHex blocked : obstPtr->getBlockedTiles())
  330. blockedTiles.push_back(blocked);
  331. tilesToBlock -= obi.blockedTiles.size();
  332. }
  333. }
  334. catch(RangeGenerator::ExhaustedPossibilities &)
  335. {
  336. }
  337. }
  338. //reading battleStartpos - add creatures AFTER random obstacles are generated
  339. //TODO: parse once to some structure
  340. std::vector< std::vector<int> > looseFormations[2], tightFormations[2], creBankFormations[2];
  341. std::vector <int> commanderField, commanderBank;
  342. const JsonNode config(ResourceID("config/battleStartpos.json"));
  343. const JsonVector &positions = config["battle_positions"].Vector();
  344. CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
  345. CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
  346. CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
  347. CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
  348. CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
  349. CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
  350. for (auto position : config["commanderPositions"]["field"].Vector())
  351. {
  352. commanderField.push_back (position.Float());
  353. }
  354. for (auto position : config["commanderPositions"]["creBank"].Vector())
  355. {
  356. commanderBank.push_back (position.Float());
  357. }
  358. //adding war machines
  359. if(!creatureBank)
  360. {
  361. //Checks if hero has artifact and create appropriate stack
  362. auto handleWarMachine= [&](int side, ArtifactPosition artslot, BattleHex hex)
  363. {
  364. const CArtifactInstance * warMachineArt = heroes[side]->getArt(artslot);
  365. if(nullptr != warMachineArt)
  366. {
  367. CreatureID cre = warMachineArt->artType->warMachine;
  368. if(cre != CreatureID::NONE)
  369. stacks.push_back(curB->generateNewStack(CStackBasicDescriptor(cre, 1), side, SlotID::WAR_MACHINES_SLOT, hex));
  370. }
  371. };
  372. if(heroes[0])
  373. {
  374. handleWarMachine(0, ArtifactPosition::MACH1, 52);
  375. handleWarMachine(0, ArtifactPosition::MACH2, 18);
  376. handleWarMachine(0, ArtifactPosition::MACH3, 154);
  377. if(town && town->hasFort())
  378. handleWarMachine(0, ArtifactPosition::MACH4, 120);
  379. }
  380. if(heroes[1])
  381. {
  382. if(!town) //defending hero shouldn't receive ballista (bug #551)
  383. handleWarMachine(1, ArtifactPosition::MACH1, 66);
  384. handleWarMachine(1, ArtifactPosition::MACH2, 32);
  385. handleWarMachine(1, ArtifactPosition::MACH3, 168);
  386. }
  387. }
  388. //war machines added
  389. //battleStartpos read
  390. for(int side = 0; side < 2; side++)
  391. {
  392. int formationNo = armies[side]->stacksCount() - 1;
  393. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  394. int k = 0; //stack serial
  395. for(auto i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  396. {
  397. std::vector<int> *formationVector = nullptr;
  398. if(creatureBank)
  399. formationVector = &creBankFormations[side][formationNo];
  400. else if(armies[side]->formation)
  401. formationVector = &tightFormations[side][formationNo];
  402. else
  403. formationVector = &looseFormations[side][formationNo];
  404. BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
  405. if(creatureBank && i->second->type->isDoubleWide())
  406. pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
  407. CStack * stack = curB->generateNewStack(*i->second, side, i->first, pos);
  408. stacks.push_back(stack);
  409. }
  410. }
  411. //adding commanders
  412. for (int i = 0; i < 2; ++i)
  413. {
  414. if (heroes[i] && heroes[i]->commander && heroes[i]->commander->alive)
  415. {
  416. CStack * stack = curB->generateNewStack (*heroes[i]->commander, i, SlotID::COMMANDER_SLOT_PLACEHOLDER,
  417. creatureBank ? commanderBank[i] : commanderField[i]);
  418. stacks.push_back(stack);
  419. }
  420. }
  421. if (curB->town && curB->town->fortLevel() >= CGTownInstance::CITADEL)
  422. {
  423. // keep tower
  424. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -2);
  425. stacks.push_back(stack);
  426. if (curB->town->fortLevel() >= CGTownInstance::CASTLE)
  427. {
  428. // lower tower + upper tower
  429. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -4);
  430. stacks.push_back(stack);
  431. stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -3);
  432. stacks.push_back(stack);
  433. }
  434. //moat
  435. auto moat = std::make_shared<MoatObstacle>();
  436. moat->ID = curB->town->subID;
  437. moat->obstacleType = CObstacleInstance::MOAT;
  438. moat->uniqueID = curB->obstacles.size();
  439. curB->obstacles.push_back(moat);
  440. }
  441. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  442. //spell level limiting bonus
  443. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  444. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  445. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  446. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  447. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  448. //giving terrain overlay premies
  449. int bonusSubtype = -1;
  450. switch(battlefieldType)
  451. {
  452. case BFieldType::MAGIC_PLAINS:
  453. {
  454. bonusSubtype = 0;
  455. }
  456. case BFieldType::FIERY_FIELDS:
  457. {
  458. if(bonusSubtype == -1) bonusSubtype = 1;
  459. }
  460. case BFieldType::ROCKLANDS:
  461. {
  462. if(bonusSubtype == -1) bonusSubtype = 8;
  463. }
  464. case BFieldType::MAGIC_CLOUDS:
  465. {
  466. if(bonusSubtype == -1) bonusSubtype = 2;
  467. }
  468. case BFieldType::LUCID_POOLS:
  469. {
  470. if(bonusSubtype == -1) bonusSubtype = 4;
  471. }
  472. { //common part for cases 9, 14, 15, 16, 17
  473. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, battlefieldType, bonusSubtype));
  474. break;
  475. }
  476. case BFieldType::HOLY_GROUND:
  477. {
  478. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, +1, battlefieldType, 0)->addLimiter(good));
  479. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, -1, battlefieldType, 0)->addLimiter(evil));
  480. break;
  481. }
  482. case BFieldType::CLOVER_FIELD:
  483. { //+2 luck bonus for neutral creatures
  484. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::LUCK, Bonus::TERRAIN_OVERLAY, +2, battlefieldType, 0)->addLimiter(neutral));
  485. break;
  486. }
  487. case BFieldType::EVIL_FOG:
  488. {
  489. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, -1, battlefieldType, 0)->addLimiter(good));
  490. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, +1, battlefieldType, 0)->addLimiter(evil));
  491. break;
  492. }
  493. case BFieldType::CURSED_GROUND:
  494. {
  495. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::NO_MORALE, Bonus::TERRAIN_OVERLAY, 0, battlefieldType, 0));
  496. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::NO_LUCK, Bonus::TERRAIN_OVERLAY, 0, battlefieldType, 0));
  497. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::BLOCK_MAGIC_ABOVE, Bonus::TERRAIN_OVERLAY, 1, battlefieldType, 0, Bonus::INDEPENDENT_MIN));
  498. break;
  499. }
  500. }
  501. //overlay premies given
  502. //native terrain bonuses
  503. auto nativeTerrain = std::make_shared<CreatureNativeTerrainLimiter>(curB->terrainType);
  504. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::STACKS_SPEED, Bonus::TERRAIN_NATIVE, 1, 0, 0)->addLimiter(nativeTerrain));
  505. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::ATTACK)->addLimiter(nativeTerrain));
  506. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::DEFENSE)->addLimiter(nativeTerrain));
  507. //////////////////////////////////////////////////////////////////////////
  508. //tactics
  509. bool isTacticsAllowed = !creatureBank; //no tactics in creature banks
  510. int tacticLvls[2] = {0};
  511. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  512. {
  513. if(heroes[i])
  514. tacticLvls[i] += heroes[i]->getSecSkillLevel(SecondarySkill::TACTICS);
  515. }
  516. int tacticsSkillDiff = tacticLvls[0] - tacticLvls[1];
  517. if(tacticsSkillDiff && isTacticsAllowed)
  518. {
  519. curB->tacticsSide = tacticsSkillDiff < 0;
  520. curB->tacticDistance = std::abs(tacticsSkillDiff)*2 + 1;
  521. }
  522. else
  523. curB->tacticDistance = 0;
  524. // workaround — bonuses affecting only enemy - DOES NOT WORK
  525. for(int i = 0; i < 2; i++)
  526. {
  527. TNodes nodes;
  528. curB->battleGetArmyObject(i)->getRedAncestors(nodes);
  529. for(CBonusSystemNode *n : nodes)
  530. {
  531. for(auto b : n->getExportedBonusList())
  532. {
  533. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  534. {
  535. auto bCopy = std::make_shared<Bonus>(*b);
  536. bCopy->effectRange = Bonus::NO_LIMIT;
  537. bCopy->propagator.reset();
  538. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i].color));
  539. curB->addNewBonus(bCopy);
  540. }
  541. }
  542. }
  543. }
  544. return curB;
  545. }
  546. const CGHeroInstance * BattleInfo::getHero(PlayerColor player) const
  547. {
  548. for(int i = 0; i < sides.size(); i++)
  549. if(sides[i].color == player)
  550. return sides[i].hero;
  551. logGlobal->errorStream() << "Player " << player << " is not in battle!";
  552. return nullptr;
  553. }
  554. PlayerColor BattleInfo::theOtherPlayer(PlayerColor player) const
  555. {
  556. return sides[!whatSide(player)].color;
  557. }
  558. ui8 BattleInfo::whatSide(PlayerColor player) const
  559. {
  560. for(int i = 0; i < sides.size(); i++)
  561. if(sides[i].color == player)
  562. return i;
  563. logGlobal->warnStream() << "BattleInfo::whatSide: Player " << player << " is not in battle!";
  564. return -1;
  565. }
  566. int BattleInfo::getIdForNewStack() const
  567. {
  568. if(stacks.size())
  569. {
  570. //stacks vector may be sorted not by ID and they may be not contiguous -> find stack with max ID
  571. auto highestIDStack = *std::max_element(stacks.begin(), stacks.end(),
  572. [](const CStack *a, const CStack *b) { return a->ID < b->ID; });
  573. return highestIDStack->ID + 1;
  574. }
  575. return 0;
  576. }
  577. std::shared_ptr<CObstacleInstance> BattleInfo::getObstacleOnTile(BattleHex tile) const
  578. {
  579. for(auto &obs : obstacles)
  580. if(vstd::contains(obs->getAffectedTiles(), tile))
  581. return obs;
  582. return std::shared_ptr<CObstacleInstance>();
  583. }
  584. BattlefieldBI::BattlefieldBI BattleInfo::battlefieldTypeToBI(BFieldType bfieldType)
  585. {
  586. static const std::map<BFieldType, BattlefieldBI::BattlefieldBI> theMap =
  587. {
  588. {BFieldType::CLOVER_FIELD, BattlefieldBI::CLOVER_FIELD},
  589. {BFieldType::CURSED_GROUND, BattlefieldBI::CURSED_GROUND},
  590. {BFieldType::EVIL_FOG, BattlefieldBI::EVIL_FOG},
  591. {BFieldType::FAVORABLE_WINDS, BattlefieldBI::NONE},
  592. {BFieldType::FIERY_FIELDS, BattlefieldBI::FIERY_FIELDS},
  593. {BFieldType::HOLY_GROUND, BattlefieldBI::HOLY_GROUND},
  594. {BFieldType::LUCID_POOLS, BattlefieldBI::LUCID_POOLS},
  595. {BFieldType::MAGIC_CLOUDS, BattlefieldBI::MAGIC_CLOUDS},
  596. {BFieldType::MAGIC_PLAINS, BattlefieldBI::MAGIC_PLAINS},
  597. {BFieldType::ROCKLANDS, BattlefieldBI::ROCKLANDS},
  598. {BFieldType::SAND_SHORE, BattlefieldBI::COASTAL}
  599. };
  600. auto itr = theMap.find(bfieldType);
  601. if(itr != theMap.end())
  602. return itr->second;
  603. return BattlefieldBI::NONE;
  604. }
  605. CStack * BattleInfo::getStack(int stackID, bool onlyAlive /*= true*/)
  606. {
  607. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  608. }
  609. BattleInfo::BattleInfo()
  610. : round(-1), activeStack(-1), selectedStack(-1), town(nullptr), tile(-1,-1,-1),
  611. battlefieldType(BFieldType::NONE), terrainType(ETerrainType::WRONG),
  612. tacticsSide(0), tacticDistance(0)
  613. {
  614. setBattle(this);
  615. setNodeType(BATTLE);
  616. }
  617. CArmedInstance * BattleInfo::battleGetArmyObject(ui8 side) const
  618. {
  619. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  620. }
  621. CGHeroInstance * BattleInfo::battleGetFightingHero(ui8 side) const
  622. {
  623. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  624. }
  625. bool CMP_stack::operator()(const CStack* a, const CStack* b)
  626. {
  627. switch(phase)
  628. {
  629. case 0: //catapult moves after turrets
  630. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  631. case 1: //fastest first, upper slot first
  632. {
  633. int as = a->Speed(turn), bs = b->Speed(turn);
  634. if(as != bs)
  635. return as > bs;
  636. else
  637. return a->slot < b->slot;
  638. }
  639. case 2: //fastest last, upper slot first
  640. //TODO: should be replaced with order of receiving morale!
  641. case 3: //fastest last, upper slot first
  642. {
  643. int as = a->Speed(turn), bs = b->Speed(turn);
  644. if(as != bs)
  645. return as < bs;
  646. else
  647. return a->slot < b->slot;
  648. }
  649. default:
  650. assert(0);
  651. return false;
  652. }
  653. }
  654. CMP_stack::CMP_stack(int Phase /*= 1*/, int Turn)
  655. {
  656. phase = Phase;
  657. turn = Turn;
  658. }