BattleInfo.cpp 23 KB

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