BattleInfo.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. /*
  2. * BattleInfo.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "BattleInfo.h"
  12. #include "../CStack.h"
  13. #include "../CHeroHandler.h"
  14. #include "../NetPacks.h"
  15. #include "../filesystem/Filesystem.h"
  16. #include "../mapObjects/CGTownInstance.h"
  17. #include "../CGeneralTextHandler.h"
  18. ///BattleInfo
  19. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, const CStack * stack)
  20. {
  21. auto reachability = getReachability(stack);
  22. if(reachability.predecessors[dest] == -1) //cannot reach destination
  23. {
  24. return std::make_pair(std::vector<BattleHex>(), 0);
  25. }
  26. //making the Path
  27. std::vector<BattleHex> path;
  28. BattleHex curElem = dest;
  29. while(curElem != start)
  30. {
  31. path.push_back(curElem);
  32. curElem = reachability.predecessors[curElem];
  33. }
  34. return std::make_pair(path, reachability.distances[dest]);
  35. }
  36. void BattleInfo::calculateCasualties(std::map<ui32,si32> * casualties) const
  37. {
  38. for(auto & elem : stacks)//setting casualties
  39. {
  40. const CStack * const st = elem;
  41. si32 killed = st->getKilled();
  42. if(killed > 0)
  43. casualties[st->side][st->getCreature()->idNumber] += killed;
  44. }
  45. }
  46. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackInstance & base, ui8 side, SlotID slot, BattleHex position)
  47. {
  48. PlayerColor owner = sides[side].color;
  49. assert((owner >= PlayerColor::PLAYER_LIMIT) ||
  50. (base.armyObj && base.armyObj->tempOwner == owner));
  51. auto ret = new CStack(&base, owner, id, side, slot);
  52. ret->initialPosition = getAvaliableHex(base.getCreatureID(), side, position); //TODO: what if no free tile on battlefield was found?
  53. stacks.push_back(ret);
  54. return ret;
  55. }
  56. CStack * BattleInfo::generateNewStack(uint32_t id, const CStackBasicDescriptor & base, ui8 side, SlotID slot, BattleHex position)
  57. {
  58. PlayerColor owner = sides[side].color;
  59. auto ret = new CStack(&base, owner, id, side, slot);
  60. ret->initialPosition = position;
  61. stacks.push_back(ret);
  62. return ret;
  63. }
  64. void BattleInfo::localInit()
  65. {
  66. for(int i = 0; i < 2; i++)
  67. {
  68. auto armyObj = battleGetArmyObject(i);
  69. armyObj->battle = this;
  70. armyObj->attachTo(this);
  71. }
  72. for(CStack * s : stacks)
  73. s->localInit(this);
  74. exportBonuses();
  75. }
  76. namespace CGH
  77. {
  78. static void readBattlePositions(const JsonNode &node, std::vector< std::vector<int> > & dest)
  79. {
  80. for(const JsonNode &level : node.Vector())
  81. {
  82. std::vector<int> pom;
  83. for(const JsonNode &value : level.Vector())
  84. {
  85. pom.push_back(value.Float());
  86. }
  87. dest.push_back(pom);
  88. }
  89. }
  90. }
  91. //RNG that works like H3 one
  92. struct RandGen
  93. {
  94. int seed;
  95. void srand(int s)
  96. {
  97. seed = s;
  98. }
  99. void srand(int3 pos)
  100. {
  101. srand(110291 * pos.x + 167801 * pos.y + 81569);
  102. }
  103. int rand()
  104. {
  105. seed = 214013 * seed + 2531011;
  106. return (seed >> 16) & 0x7FFF;
  107. }
  108. int rand(int min, int max)
  109. {
  110. if(min == max)
  111. return min;
  112. if(min > max)
  113. return min;
  114. return min + rand() % (max - min + 1);
  115. }
  116. };
  117. struct RangeGenerator
  118. {
  119. class ExhaustedPossibilities : public std::exception
  120. {
  121. };
  122. RangeGenerator(int _min, int _max, std::function<int()> _myRand):
  123. min(_min),
  124. remainingCount(_max - _min + 1),
  125. remaining(remainingCount, true),
  126. myRand(_myRand)
  127. {
  128. }
  129. int generateNumber()
  130. {
  131. if(!remainingCount)
  132. throw ExhaustedPossibilities();
  133. if(remainingCount == 1)
  134. return 0;
  135. return myRand() % remainingCount;
  136. }
  137. //get number fulfilling predicate. Never gives the same number twice.
  138. int getSuchNumber(std::function<bool(int)> goodNumberPred = nullptr)
  139. {
  140. int ret = -1;
  141. do
  142. {
  143. int n = generateNumber();
  144. int i = 0;
  145. for(;;i++)
  146. {
  147. assert(i < (int)remaining.size());
  148. if(!remaining[i])
  149. continue;
  150. if(!n)
  151. break;
  152. n--;
  153. }
  154. remainingCount--;
  155. remaining[i] = false;
  156. ret = i + min;
  157. } while(goodNumberPred && !goodNumberPred(ret));
  158. return ret;
  159. }
  160. int min, remainingCount;
  161. std::vector<bool> remaining;
  162. std::function<int()> myRand;
  163. };
  164. BattleInfo * BattleInfo::setupBattle(int3 tile, ETerrainType terrain, BFieldType battlefieldType, const CArmedInstance * armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance * town)
  165. {
  166. CMP_stack cmpst;
  167. auto curB = new BattleInfo();
  168. for(auto i = 0u; i < curB->sides.size(); i++)
  169. curB->sides[i].init(heroes[i], armies[i]);
  170. std::vector<CStack*> & stacks = (curB->stacks);
  171. curB->tile = tile;
  172. curB->battlefieldType = battlefieldType;
  173. curB->round = -2;
  174. curB->activeStack = -1;
  175. if(town)
  176. {
  177. curB->town = town;
  178. curB->terrainType = VLC->townh->factions[town->subID]->nativeTerrain;
  179. }
  180. else
  181. {
  182. curB->town = nullptr;
  183. curB->terrainType = terrain;
  184. }
  185. //setting up siege obstacles
  186. if (town && town->hasFort())
  187. {
  188. curB->si.gateState = EGateState::CLOSED;
  189. for (int b = 0; b < curB->si.wallState.size(); ++b)
  190. {
  191. curB->si.wallState[b] = EWallState::INTACT;
  192. }
  193. if (!town->hasBuilt(BuildingID::CITADEL))
  194. {
  195. curB->si.wallState[EWallPart::KEEP] = EWallState::NONE;
  196. }
  197. if (!town->hasBuilt(BuildingID::CASTLE))
  198. {
  199. curB->si.wallState[EWallPart::UPPER_TOWER] = EWallState::NONE;
  200. curB->si.wallState[EWallPart::BOTTOM_TOWER] = EWallState::NONE;
  201. }
  202. }
  203. //randomize obstacles
  204. if (town == nullptr && !creatureBank) //do it only when it's not siege and not creature bank
  205. {
  206. const int ABSOLUTE_OBSTACLES_COUNT = 34, USUAL_OBSTACLES_COUNT = 91; //shouldn't be changes if we want H3-like obstacle placement
  207. RandGen r;
  208. auto ourRand = [&](){ return r.rand(); };
  209. r.srand(tile);
  210. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  211. int tilesToBlock = r.rand(5,12);
  212. const int specialBattlefield = battlefieldTypeToBI(battlefieldType);
  213. std::vector<BattleHex> blockedTiles;
  214. auto appropriateAbsoluteObstacle = [&](int id)
  215. {
  216. return VLC->heroh->absoluteObstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  217. };
  218. auto appropriateUsualObstacle = [&](int id) -> bool
  219. {
  220. return VLC->heroh->obstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  221. };
  222. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  223. {
  224. RangeGenerator obidgen(0, ABSOLUTE_OBSTACLES_COUNT-1, ourRand);
  225. try
  226. {
  227. auto obstPtr = std::make_shared<CObstacleInstance>();
  228. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  229. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  230. obstPtr->uniqueID = curB->obstacles.size();
  231. curB->obstacles.push_back(obstPtr);
  232. for(BattleHex blocked : obstPtr->getBlockedTiles())
  233. blockedTiles.push_back(blocked);
  234. tilesToBlock -= VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
  235. }
  236. catch(RangeGenerator::ExhaustedPossibilities &)
  237. {
  238. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  239. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occured - cannot place absolute obstacle");
  240. }
  241. }
  242. RangeGenerator obidgen(0, USUAL_OBSTACLES_COUNT-1, ourRand);
  243. try
  244. {
  245. while(tilesToBlock > 0)
  246. {
  247. auto tileAccessibility = curB->getAccesibility();
  248. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  249. const CObstacleInfo &obi = VLC->heroh->obstacles[obid];
  250. auto validPosition = [&](BattleHex pos) -> bool
  251. {
  252. if(obi.height >= pos.getY())
  253. return false;
  254. if(pos.getX() == 0)
  255. return false;
  256. if(pos.getX() + obi.width > 15)
  257. return false;
  258. if(vstd::contains(blockedTiles, pos))
  259. return false;
  260. for(BattleHex blocked : obi.getBlocked(pos))
  261. {
  262. if(tileAccessibility[blocked] == EAccessibility::UNAVAILABLE) //for ship-to-ship battlefield - exclude hardcoded unavailable tiles
  263. return false;
  264. if(vstd::contains(blockedTiles, blocked))
  265. return false;
  266. int x = blocked.getX();
  267. if(x <= 2 || x >= 14)
  268. return false;
  269. }
  270. return true;
  271. };
  272. RangeGenerator posgenerator(18, 168, ourRand);
  273. auto obstPtr = std::make_shared<CObstacleInstance>();
  274. obstPtr->ID = obid;
  275. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  276. obstPtr->uniqueID = curB->obstacles.size();
  277. curB->obstacles.push_back(obstPtr);
  278. for(BattleHex blocked : obstPtr->getBlockedTiles())
  279. blockedTiles.push_back(blocked);
  280. tilesToBlock -= obi.blockedTiles.size();
  281. }
  282. }
  283. catch(RangeGenerator::ExhaustedPossibilities &)
  284. {
  285. logGlobal->debug("RangeGenerator::ExhaustedPossibilities exception occured - cannot place usual obstacle");
  286. }
  287. }
  288. //reading battleStartpos - add creatures AFTER random obstacles are generated
  289. //TODO: parse once to some structure
  290. std::vector< std::vector<int> > looseFormations[2], tightFormations[2], creBankFormations[2];
  291. std::vector <int> commanderField, commanderBank;
  292. const JsonNode config(ResourceID("config/battleStartpos.json"));
  293. const JsonVector &positions = config["battle_positions"].Vector();
  294. CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
  295. CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
  296. CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
  297. CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
  298. CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
  299. CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
  300. for (auto position : config["commanderPositions"]["field"].Vector())
  301. {
  302. commanderField.push_back (position.Float());
  303. }
  304. for (auto position : config["commanderPositions"]["creBank"].Vector())
  305. {
  306. commanderBank.push_back (position.Float());
  307. }
  308. //adding war machines
  309. if(!creatureBank)
  310. {
  311. //Checks if hero has artifact and create appropriate stack
  312. auto handleWarMachine= [&](int side, ArtifactPosition artslot, BattleHex hex)
  313. {
  314. const CArtifactInstance * warMachineArt = heroes[side]->getArt(artslot);
  315. if(nullptr != warMachineArt)
  316. {
  317. CreatureID cre = warMachineArt->artType->warMachine;
  318. if(cre != CreatureID::NONE)
  319. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(cre, 1), side, SlotID::WAR_MACHINES_SLOT, hex);
  320. }
  321. };
  322. if(heroes[0])
  323. {
  324. handleWarMachine(0, ArtifactPosition::MACH1, 52);
  325. handleWarMachine(0, ArtifactPosition::MACH2, 18);
  326. handleWarMachine(0, ArtifactPosition::MACH3, 154);
  327. if(town && town->hasFort())
  328. handleWarMachine(0, ArtifactPosition::MACH4, 120);
  329. }
  330. if(heroes[1])
  331. {
  332. if(!town) //defending hero shouldn't receive ballista (bug #551)
  333. handleWarMachine(1, ArtifactPosition::MACH1, 66);
  334. handleWarMachine(1, ArtifactPosition::MACH2, 32);
  335. handleWarMachine(1, ArtifactPosition::MACH3, 168);
  336. }
  337. }
  338. //war machines added
  339. //battleStartpos read
  340. for(int side = 0; side < 2; side++)
  341. {
  342. int formationNo = armies[side]->stacksCount() - 1;
  343. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  344. int k = 0; //stack serial
  345. for(auto i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  346. {
  347. std::vector<int> *formationVector = nullptr;
  348. if(creatureBank)
  349. formationVector = &creBankFormations[side][formationNo];
  350. else if(armies[side]->formation)
  351. formationVector = &tightFormations[side][formationNo];
  352. else
  353. formationVector = &looseFormations[side][formationNo];
  354. BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
  355. if(creatureBank && i->second->type->isDoubleWide())
  356. pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
  357. curB->generateNewStack(curB->nextUnitId(), *i->second, side, i->first, pos);
  358. }
  359. }
  360. //adding commanders
  361. for (int i = 0; i < 2; ++i)
  362. {
  363. if (heroes[i] && heroes[i]->commander && heroes[i]->commander->alive)
  364. {
  365. curB->generateNewStack(curB->nextUnitId(), *heroes[i]->commander, i, SlotID::COMMANDER_SLOT_PLACEHOLDER, creatureBank ? commanderBank[i] : commanderField[i]);
  366. }
  367. }
  368. if (curB->town && curB->town->fortLevel() >= CGTownInstance::CITADEL)
  369. {
  370. // keep tower
  371. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -2);
  372. if (curB->town->fortLevel() >= CGTownInstance::CASTLE)
  373. {
  374. // lower tower + upper tower
  375. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -4);
  376. curB->generateNewStack(curB->nextUnitId(), CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), 1, SlotID::ARROW_TOWERS_SLOT, -3);
  377. }
  378. //moat
  379. auto moat = std::make_shared<MoatObstacle>();
  380. moat->ID = curB->town->subID;
  381. moat->obstacleType = CObstacleInstance::MOAT;
  382. moat->uniqueID = curB->obstacles.size();
  383. curB->obstacles.push_back(moat);
  384. }
  385. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  386. auto neutral = std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL);
  387. auto good = std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD);
  388. auto evil = std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL);
  389. //giving terrain overlay premies
  390. int bonusSubtype = -1;
  391. switch(battlefieldType)
  392. {
  393. case BFieldType::MAGIC_PLAINS:
  394. {
  395. bonusSubtype = 0;
  396. }
  397. FALLTHROUGH
  398. case BFieldType::FIERY_FIELDS:
  399. {
  400. if(bonusSubtype == -1) bonusSubtype = 1;
  401. }
  402. FALLTHROUGH
  403. case BFieldType::ROCKLANDS:
  404. {
  405. if(bonusSubtype == -1) bonusSubtype = 8;
  406. }
  407. FALLTHROUGH
  408. case BFieldType::MAGIC_CLOUDS:
  409. {
  410. if(bonusSubtype == -1) bonusSubtype = 2;
  411. }
  412. FALLTHROUGH
  413. case BFieldType::LUCID_POOLS:
  414. {
  415. if(bonusSubtype == -1) bonusSubtype = 4;
  416. }
  417. { //common part for cases 9, 14, 15, 16, 17
  418. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, battlefieldType, bonusSubtype));
  419. break;
  420. }
  421. case BFieldType::HOLY_GROUND:
  422. {
  423. std::string goodArmyDesc = VLC->generaltexth->arraytxt[123];
  424. goodArmyDesc.erase(goodArmyDesc.size() - 2, 2); //omitting hardcoded +1 in description
  425. std::string evilArmyDesc = VLC->generaltexth->arraytxt[124];
  426. evilArmyDesc.erase(evilArmyDesc.size() - 2, 2);
  427. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, +1, battlefieldType, goodArmyDesc, 0)->addLimiter(good));
  428. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, -1, battlefieldType, evilArmyDesc, 0)->addLimiter(evil));
  429. break;
  430. }
  431. case BFieldType::CLOVER_FIELD:
  432. { //+2 luck bonus for neutral creatures
  433. std::string desc = VLC->generaltexth->arraytxt[83];
  434. desc.erase(desc.size() - 2, 2);
  435. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::LUCK, Bonus::TERRAIN_OVERLAY, +2, battlefieldType, desc, 0)->addLimiter(neutral));
  436. break;
  437. }
  438. case BFieldType::EVIL_FOG:
  439. {
  440. std::string goodArmyDesc = VLC->generaltexth->arraytxt[126];
  441. goodArmyDesc.erase(goodArmyDesc.size() - 2, 2);
  442. std::string evilArmyDesc = VLC->generaltexth->arraytxt[125];
  443. evilArmyDesc.erase(evilArmyDesc.size() - 2, 2);
  444. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, -1, battlefieldType, goodArmyDesc, 0)->addLimiter(good));
  445. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::MORALE, Bonus::TERRAIN_OVERLAY, +1, battlefieldType, evilArmyDesc, 0)->addLimiter(evil));
  446. break;
  447. }
  448. case BFieldType::CURSED_GROUND:
  449. {
  450. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::NO_MORALE, Bonus::TERRAIN_OVERLAY, 0, battlefieldType, VLC->generaltexth->arraytxt[112], 0));
  451. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::NO_LUCK, Bonus::TERRAIN_OVERLAY, 0, battlefieldType, VLC->generaltexth->arraytxt[81], 0));
  452. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::BLOCK_MAGIC_ABOVE, Bonus::TERRAIN_OVERLAY, 1, battlefieldType, 0, Bonus::INDEPENDENT_MIN));
  453. break;
  454. }
  455. }
  456. //overlay premies given
  457. //native terrain bonuses
  458. auto nativeTerrain = std::make_shared<CreatureNativeTerrainLimiter>(curB->terrainType);
  459. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::STACKS_SPEED, Bonus::TERRAIN_NATIVE, 1, 0, 0)->addLimiter(nativeTerrain));
  460. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::ATTACK)->addLimiter(nativeTerrain));
  461. curB->addNewBonus(std::make_shared<Bonus>(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::TERRAIN_NATIVE, 1, 0, PrimarySkill::DEFENSE)->addLimiter(nativeTerrain));
  462. //////////////////////////////////////////////////////////////////////////
  463. //tactics
  464. bool isTacticsAllowed = !creatureBank; //no tactics in creature banks
  465. int tacticLvls[2] = {0};
  466. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  467. {
  468. if(heroes[i])
  469. tacticLvls[i] += heroes[i]->valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::TACTICS));
  470. }
  471. int tacticsSkillDiff = tacticLvls[0] - tacticLvls[1];
  472. if(tacticsSkillDiff && isTacticsAllowed)
  473. {
  474. curB->tacticsSide = tacticsSkillDiff < 0;
  475. //bonus specifies distance you can move beyond base row; this allows 100% compatibility with HMM3 mechanics
  476. curB->tacticDistance = 1 + std::abs(tacticsSkillDiff);
  477. }
  478. else
  479. curB->tacticDistance = 0;
  480. // workaround — bonuses affecting only enemy - DOES NOT WORK
  481. for(int i = 0; i < 2; i++)
  482. {
  483. TNodes nodes;
  484. curB->battleGetArmyObject(i)->getRedAncestors(nodes);
  485. for(CBonusSystemNode *n : nodes)
  486. {
  487. for(auto b : n->getExportedBonusList())
  488. {
  489. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  490. {
  491. auto bCopy = std::make_shared<Bonus>(*b);
  492. bCopy->effectRange = Bonus::NO_LIMIT;
  493. bCopy->propagator.reset();
  494. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i].color));
  495. curB->addNewBonus(bCopy);
  496. }
  497. }
  498. }
  499. }
  500. return curB;
  501. }
  502. const CGHeroInstance * BattleInfo::getHero(PlayerColor player) const
  503. {
  504. for(int i = 0; i < sides.size(); i++)
  505. if(sides[i].color == player)
  506. return sides[i].hero;
  507. logGlobal->error("Player %s is not in battle!", player.getStr());
  508. return nullptr;
  509. }
  510. ui8 BattleInfo::whatSide(PlayerColor player) const
  511. {
  512. for(int i = 0; i < sides.size(); i++)
  513. if(sides[i].color == player)
  514. return i;
  515. logGlobal->warn("BattleInfo::whatSide: Player %s is not in battle!", player.getStr());
  516. return -1;
  517. }
  518. BattlefieldBI::BattlefieldBI BattleInfo::battlefieldTypeToBI(BFieldType bfieldType)
  519. {
  520. static const std::map<BFieldType, BattlefieldBI::BattlefieldBI> theMap =
  521. {
  522. {BFieldType::CLOVER_FIELD, BattlefieldBI::CLOVER_FIELD},
  523. {BFieldType::CURSED_GROUND, BattlefieldBI::CURSED_GROUND},
  524. {BFieldType::EVIL_FOG, BattlefieldBI::EVIL_FOG},
  525. {BFieldType::FAVORABLE_WINDS, BattlefieldBI::NONE},
  526. {BFieldType::FIERY_FIELDS, BattlefieldBI::FIERY_FIELDS},
  527. {BFieldType::HOLY_GROUND, BattlefieldBI::HOLY_GROUND},
  528. {BFieldType::LUCID_POOLS, BattlefieldBI::LUCID_POOLS},
  529. {BFieldType::MAGIC_CLOUDS, BattlefieldBI::MAGIC_CLOUDS},
  530. {BFieldType::MAGIC_PLAINS, BattlefieldBI::MAGIC_PLAINS},
  531. {BFieldType::ROCKLANDS, BattlefieldBI::ROCKLANDS},
  532. {BFieldType::SAND_SHORE, BattlefieldBI::COASTAL}
  533. };
  534. auto itr = theMap.find(bfieldType);
  535. if(itr != theMap.end())
  536. return itr->second;
  537. return BattlefieldBI::NONE;
  538. }
  539. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  540. {
  541. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  542. }
  543. BattleInfo::BattleInfo()
  544. : round(-1), activeStack(-1), town(nullptr), tile(-1,-1,-1),
  545. battlefieldType(BFieldType::NONE), terrainType(ETerrainType::WRONG),
  546. tacticsSide(0), tacticDistance(0)
  547. {
  548. setBattle(this);
  549. setNodeType(BATTLE);
  550. }
  551. BattleInfo::~BattleInfo() = default;
  552. int32_t BattleInfo::getActiveStackID() const
  553. {
  554. return activeStack;
  555. }
  556. TStacks BattleInfo::getStacksIf(TStackFilter predicate) const
  557. {
  558. TStacks ret;
  559. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  560. return ret;
  561. }
  562. battle::Units BattleInfo::getUnitsIf(battle::UnitFilter predicate) const
  563. {
  564. battle::Units ret;
  565. vstd::copy_if(stacks, std::back_inserter(ret), predicate);
  566. return ret;
  567. }
  568. BFieldType BattleInfo::getBattlefieldType() const
  569. {
  570. return battlefieldType;
  571. }
  572. ETerrainType BattleInfo::getTerrainType() const
  573. {
  574. return terrainType;
  575. }
  576. IBattleInfo::ObstacleCList BattleInfo::getAllObstacles() const
  577. {
  578. ObstacleCList ret;
  579. for(auto iter = obstacles.cbegin(); iter != obstacles.cend(); iter++)
  580. ret.push_back(*iter);
  581. return ret;
  582. }
  583. PlayerColor BattleInfo::getSidePlayer(ui8 side) const
  584. {
  585. return sides.at(side).color;
  586. }
  587. const CArmedInstance * BattleInfo::getSideArmy(ui8 side) const
  588. {
  589. return sides.at(side).armyObject;
  590. }
  591. const CGHeroInstance * BattleInfo::getSideHero(ui8 side) const
  592. {
  593. return sides.at(side).hero;
  594. }
  595. ui8 BattleInfo::getTacticDist() const
  596. {
  597. return tacticDistance;
  598. }
  599. ui8 BattleInfo::getTacticsSide() const
  600. {
  601. return tacticsSide;
  602. }
  603. const CGTownInstance * BattleInfo::getDefendedTown() const
  604. {
  605. return town;
  606. }
  607. si8 BattleInfo::getWallState(int partOfWall) const
  608. {
  609. return si.wallState.at(partOfWall);
  610. }
  611. EGateState BattleInfo::getGateState() const
  612. {
  613. return si.gateState;
  614. }
  615. uint32_t BattleInfo::getCastSpells(ui8 side) const
  616. {
  617. return sides.at(side).castSpellsCount;
  618. }
  619. int32_t BattleInfo::getEnchanterCounter(ui8 side) const
  620. {
  621. return sides.at(side).enchanterCounter;
  622. }
  623. const IBonusBearer * BattleInfo::asBearer() const
  624. {
  625. return this;
  626. }
  627. int64_t BattleInfo::getActualDamage(const TDmgRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  628. {
  629. if(damage.first != damage.second)
  630. {
  631. int64_t sum = 0;
  632. auto howManyToAv = std::min<int32_t>(10, attackerCount);
  633. auto rangeGen = rng.getInt64Range(damage.first, damage.second);
  634. for(int32_t g = 0; g < howManyToAv; ++g)
  635. sum += rangeGen();
  636. return sum / howManyToAv;
  637. }
  638. else
  639. {
  640. return damage.first;
  641. }
  642. }
  643. void BattleInfo::nextRound(int32_t roundNr)
  644. {
  645. for(int i = 0; i < 2; ++i)
  646. {
  647. sides.at(i).castSpellsCount = 0;
  648. vstd::amax(--sides.at(i).enchanterCounter, 0);
  649. }
  650. round = roundNr;
  651. for(CStack * s : stacks)
  652. {
  653. // new turn effects
  654. s->reduceBonusDurations(Bonus::NTurns);
  655. s->afterNewRound();
  656. }
  657. for(auto & obst : obstacles)
  658. obst->battleTurnPassed();
  659. }
  660. void BattleInfo::nextTurn(uint32_t unitId)
  661. {
  662. activeStack = unitId;
  663. CStack * st = getStack(activeStack);
  664. //remove bonuses that last until when stack gets new turn
  665. st->popBonuses(Bonus::UntilGetsTurn);
  666. st->afterGetsTurn();
  667. }
  668. void BattleInfo::addUnit(uint32_t id, const JsonNode & data)
  669. {
  670. battle::UnitInfo info;
  671. info.load(id, data);
  672. CStackBasicDescriptor base(info.type, info.count);
  673. PlayerColor owner = getSidePlayer(info.side);
  674. auto ret = new CStack(&base, owner, info.id, info.side, SlotID::SUMMONED_SLOT_PLACEHOLDER);
  675. ret->initialPosition = info.position;
  676. stacks.push_back(ret);
  677. ret->summoned = info.summoned;
  678. ret->localInit(this);
  679. }
  680. void BattleInfo::moveUnit(uint32_t id, BattleHex destination)
  681. {
  682. auto sta = getStack(id);
  683. if(!sta)
  684. {
  685. logGlobal->error("Cannot find stack %d", id);
  686. return;
  687. }
  688. for(auto & oi : obstacles)
  689. {
  690. if((oi->obstacleType == CObstacleInstance::SPELL_CREATED) && vstd::contains(oi->getAffectedTiles(), destination))
  691. {
  692. SpellCreatedObstacle * obstacle = dynamic_cast<SpellCreatedObstacle*>(oi.get());
  693. assert(obstacle);
  694. if(obstacle->casterSide != sta->unitSide() && obstacle->hidden)
  695. obstacle->revealed = true;
  696. }
  697. }
  698. sta->position = destination;
  699. }
  700. void BattleInfo::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  701. {
  702. CStack * changedStack = getStack(id, false);
  703. if(!changedStack)
  704. throw std::runtime_error("Invalid unit id in BattleInfo update");
  705. if(!changedStack->alive() && healthDelta > 0)
  706. {
  707. //checking if we resurrect a stack that is under a living stack
  708. auto accessibility = getAccesibility();
  709. if(!accessibility.accessible(changedStack->getPosition(), changedStack))
  710. {
  711. logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->getPosition().hex);
  712. return; //position is already occupied
  713. }
  714. }
  715. bool killed = (-healthDelta) >= changedStack->getAvailableHealth();//todo: check using alive state once rebirth will be handled separately
  716. bool resurrected = !changedStack->alive() && healthDelta > 0;
  717. //applying changes
  718. changedStack->load(data);
  719. if(healthDelta < 0)
  720. {
  721. changedStack->popBonuses(Bonus::UntilBeingAttacked);
  722. }
  723. resurrected = resurrected || (killed && changedStack->alive());
  724. if(killed)
  725. {
  726. if(changedStack->cloneID >= 0)
  727. {
  728. //remove clone as well
  729. CStack * clone = getStack(changedStack->cloneID);
  730. if(clone)
  731. clone->makeGhost();
  732. changedStack->cloneID = -1;
  733. }
  734. }
  735. if(resurrected || killed)
  736. {
  737. //removing all spells effects
  738. auto selector = [](const Bonus * b)
  739. {
  740. //Special case: DISRUPTING_RAY is absolutely permanent
  741. if(b->source == Bonus::SPELL_EFFECT)
  742. return b->sid != SpellID::DISRUPTING_RAY;
  743. else
  744. return false;
  745. };
  746. changedStack->popBonuses(selector);
  747. }
  748. if(!changedStack->alive() && changedStack->isClone())
  749. {
  750. for(CStack * s : stacks)
  751. {
  752. if(s->cloneID == changedStack->unitId())
  753. s->cloneID = -1;
  754. }
  755. }
  756. }
  757. void BattleInfo::removeUnit(uint32_t id)
  758. {
  759. std::set<uint32_t> ids;
  760. ids.insert(id);
  761. while(!ids.empty())
  762. {
  763. auto toRemoveId = *ids.begin();
  764. auto toRemove = getStack(toRemoveId, false);
  765. if(!toRemove)
  766. {
  767. logGlobal->error("Cannot find stack %d", toRemoveId);
  768. return;
  769. }
  770. if(!toRemove->ghost)
  771. {
  772. toRemove->onRemoved();
  773. toRemove->detachFromAll();
  774. //stack may be removed instantly (not being killed first)
  775. //handle clone remove also here
  776. if(toRemove->cloneID >= 0)
  777. {
  778. ids.insert(toRemove->cloneID);
  779. toRemove->cloneID = -1;
  780. }
  781. //cleanup remaining clone links if any
  782. for(auto s : stacks)
  783. {
  784. if(s->cloneID == toRemoveId)
  785. s->cloneID = -1;
  786. }
  787. }
  788. ids.erase(toRemoveId);
  789. }
  790. }
  791. void BattleInfo::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  792. {
  793. CStack * sta = getStack(id, false);
  794. if(!sta)
  795. {
  796. logGlobal->error("Cannot find stack %d", id);
  797. return;
  798. }
  799. for(const Bonus & b : bonus)
  800. addOrUpdateUnitBonus(sta, b, true);
  801. }
  802. void BattleInfo::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  803. {
  804. CStack * sta = getStack(id, false);
  805. if(!sta)
  806. {
  807. logGlobal->error("Cannot find stack %d", id);
  808. return;
  809. }
  810. for(const Bonus & b : bonus)
  811. addOrUpdateUnitBonus(sta, b, false);
  812. }
  813. void BattleInfo::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  814. {
  815. CStack * sta = getStack(id, false);
  816. if(!sta)
  817. {
  818. logGlobal->error("Cannot find stack %d", id);
  819. return;
  820. }
  821. for(const Bonus & one : bonus)
  822. {
  823. auto selector = [one](const Bonus * b)
  824. {
  825. //compare everything but turnsRemain, limiter and propagator
  826. return one.duration == b->duration
  827. && one.type == b->type
  828. && one.subtype == b->subtype
  829. && one.source == b->source
  830. && one.val == b->val
  831. && one.sid == b->sid
  832. && one.valType == b->valType
  833. && one.additionalInfo == b->additionalInfo
  834. && one.effectRange == b->effectRange
  835. && one.description == b->description;
  836. };
  837. sta->popBonuses(selector);
  838. }
  839. }
  840. uint32_t BattleInfo::nextUnitId() const
  841. {
  842. return stacks.size();
  843. }
  844. void BattleInfo::addOrUpdateUnitBonus(CStack * sta, const Bonus & value, bool forceAdd)
  845. {
  846. if(forceAdd || !sta->hasBonus(Selector::source(Bonus::SPELL_EFFECT, value.sid).And(Selector::typeSubtype(value.type, value.subtype))))
  847. {
  848. //no such effect or cumulative - add new
  849. logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), value.Description());
  850. sta->addNewBonus(std::make_shared<Bonus>(value));
  851. }
  852. else
  853. {
  854. logBonus->trace("%s updated bonus: %s", sta->nodeName(), value.Description());
  855. for(auto stackBonus : sta->getExportedBonusList()) //TODO: optimize
  856. {
  857. if(stackBonus->source == value.source && stackBonus->sid == value.sid && stackBonus->type == value.type && stackBonus->subtype == value.subtype)
  858. {
  859. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, value.turnsRemain);
  860. }
  861. }
  862. CBonusSystemNode::treeHasChanged();
  863. }
  864. }
  865. void BattleInfo::setWallState(int partOfWall, si8 state)
  866. {
  867. si.wallState.at(partOfWall) = state;
  868. }
  869. void BattleInfo::addObstacle(const ObstacleChanges & changes)
  870. {
  871. std::shared_ptr<SpellCreatedObstacle> obstacle = std::make_shared<SpellCreatedObstacle>();
  872. obstacle->fromInfo(changes);
  873. obstacles.push_back(obstacle);
  874. }
  875. void BattleInfo::removeObstacle(uint32_t id)
  876. {
  877. for(int i=0; i < obstacles.size(); ++i)
  878. {
  879. if(obstacles[i]->uniqueID == id) //remove this obstacle
  880. {
  881. obstacles.erase(obstacles.begin() + i);
  882. break;
  883. }
  884. }
  885. }
  886. CArmedInstance * BattleInfo::battleGetArmyObject(ui8 side) const
  887. {
  888. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  889. }
  890. CGHeroInstance * BattleInfo::battleGetFightingHero(ui8 side) const
  891. {
  892. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  893. }
  894. bool CMP_stack::operator()(const battle::Unit * a, const battle::Unit * b)
  895. {
  896. switch(phase)
  897. {
  898. case 0: //catapult moves after turrets
  899. return a->creatureIndex() > b->creatureIndex(); //catapult is 145 and turrets are 149
  900. case 1: //fastest first, upper slot first
  901. {
  902. int as = a->getInitiative(turn), bs = b->getInitiative(turn);
  903. if(as != bs)
  904. return as > bs;
  905. else
  906. return a->unitSlot() < b->unitSlot(); //FIXME: what about summoned stacks?
  907. }
  908. case 2: //fastest last, upper slot first
  909. //TODO: should be replaced with order of receiving morale!
  910. case 3: //fastest last, upper slot first
  911. {
  912. int as = a->getInitiative(turn), bs = b->getInitiative(turn);
  913. if(as != bs)
  914. return as < bs;
  915. else
  916. return a->unitSlot() < b->unitSlot();
  917. }
  918. default:
  919. assert(0);
  920. return false;
  921. }
  922. }
  923. CMP_stack::CMP_stack(int Phase, int Turn)
  924. {
  925. phase = Phase;
  926. turn = Turn;
  927. }