AIUtility.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. /*
  2. * AIUtility.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 "AIUtility.h"
  12. #include "AIGateway.h"
  13. #include "Goals/Goals.h"
  14. #include "../../lib/UnlockGuard.h"
  15. #include "../../lib/CConfigHandler.h"
  16. #include "../../lib/mapObjects/MapObjects.h"
  17. #include "../../lib/mapObjects/CQuest.h"
  18. #include "../../lib/mapping/CMapDefines.h"
  19. #include "../../lib/gameState/QuestInfo.h"
  20. #include "../../lib/IGameSettings.h"
  21. #include "../../lib/bonuses/Limiters.h"
  22. #include "../../lib/bonuses/Propagators.h"
  23. #include <vcmi/CreatureService.h>
  24. namespace NKAI
  25. {
  26. const CGObjectInstance * ObjectIdRef::operator->() const
  27. {
  28. return cb->getObj(id, false);
  29. }
  30. ObjectIdRef::operator const CGObjectInstance *() const
  31. {
  32. return cb->getObj(id, false);
  33. }
  34. ObjectIdRef::operator bool() const
  35. {
  36. return cb->getObj(id, false);
  37. }
  38. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id)
  39. : id(_id)
  40. {
  41. }
  42. ObjectIdRef::ObjectIdRef(const CGObjectInstance * obj)
  43. : id(obj->id)
  44. {
  45. }
  46. bool ObjectIdRef::operator<(const ObjectIdRef & rhs) const
  47. {
  48. return id < rhs.id;
  49. }
  50. HeroPtr::HeroPtr(const CGHeroInstance * H)
  51. {
  52. if(!H)
  53. {
  54. //init from nullptr should equal to default init
  55. *this = HeroPtr();
  56. return;
  57. }
  58. h = H;
  59. hid = H->id;
  60. // infosCount[ai->playerID][hid]++;
  61. }
  62. HeroPtr::HeroPtr()
  63. {
  64. h = nullptr;
  65. hid = ObjectInstanceID();
  66. }
  67. HeroPtr::~HeroPtr()
  68. {
  69. // if(hid >= 0)
  70. // infosCount[ai->playerID][hid]--;
  71. }
  72. bool HeroPtr::operator<(const HeroPtr & rhs) const
  73. {
  74. return hid < rhs.hid;
  75. }
  76. std::string HeroPtr::name() const
  77. {
  78. if (h)
  79. return h->getNameTextID();
  80. else
  81. return "<NO HERO>";
  82. }
  83. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull) const
  84. {
  85. return get(cb, doWeExpectNull);
  86. }
  87. const CGHeroInstance * HeroPtr::get(const CPlayerSpecificInfoCallback * cb, bool doWeExpectNull) const
  88. {
  89. //TODO? check if these all assertions every time we get info about hero affect efficiency
  90. //
  91. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  92. assert(doWeExpectNull || h);
  93. if(h)
  94. {
  95. auto obj = cb->getObj(hid);
  96. //const bool owned = obj && obj->tempOwner == ai->playerID;
  97. if(doWeExpectNull && !obj)
  98. {
  99. return nullptr;
  100. }
  101. else
  102. {
  103. assert(obj);
  104. //assert(owned);
  105. }
  106. }
  107. return h;
  108. }
  109. const CGHeroInstance * HeroPtr::operator->() const
  110. {
  111. return get();
  112. }
  113. bool HeroPtr::validAndSet() const
  114. {
  115. return get(true);
  116. }
  117. const CGHeroInstance * HeroPtr::operator*() const
  118. {
  119. return get();
  120. }
  121. bool HeroPtr::operator==(const HeroPtr & rhs) const
  122. {
  123. return h == rhs.get(true);
  124. }
  125. bool isSafeToVisit(const CGHeroInstance * h, const CCreatureSet * heroArmy, uint64_t dangerStrength, float safeAttackRatio)
  126. {
  127. const ui64 heroStrength = h->getHeroStrength() * heroArmy->getArmyStrength();
  128. if(dangerStrength)
  129. {
  130. return heroStrength > dangerStrength * safeAttackRatio;
  131. }
  132. return true; //there's no danger
  133. }
  134. bool isSafeToVisit(const CGHeroInstance * h, uint64_t dangerStrength, float safeAttackRatio)
  135. {
  136. return isSafeToVisit(h, h, dangerStrength, safeAttackRatio);
  137. }
  138. bool isObjectRemovable(const CGObjectInstance * obj)
  139. {
  140. //FIXME: move logic to object property!
  141. switch (obj->ID)
  142. {
  143. case Obj::MONSTER:
  144. case Obj::RESOURCE:
  145. case Obj::CAMPFIRE:
  146. case Obj::TREASURE_CHEST:
  147. case Obj::ARTIFACT:
  148. case Obj::BORDERGUARD:
  149. case Obj::FLOTSAM:
  150. case Obj::PANDORAS_BOX:
  151. case Obj::OCEAN_BOTTLE:
  152. case Obj::SEA_CHEST:
  153. case Obj::SHIPWRECK_SURVIVOR:
  154. case Obj::SPELL_SCROLL:
  155. return true;
  156. break;
  157. default:
  158. return false;
  159. break;
  160. }
  161. }
  162. bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater)
  163. {
  164. // TODO: Such information should be provided by pathfinder
  165. // Tile must be free or with unoccupied boat
  166. if(!t->blocked())
  167. {
  168. return true;
  169. }
  170. else if(!fromWater) // do not try to board when in water sector
  171. {
  172. if(t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT)
  173. return true;
  174. }
  175. return false;
  176. }
  177. bool isObjectPassable(const Nullkiller * ai, const CGObjectInstance * obj)
  178. {
  179. return isObjectPassable(obj, ai->playerID, ai->cb->getPlayerRelations(obj->tempOwner, ai->playerID));
  180. }
  181. // Pathfinder internal helper
  182. bool isObjectPassable(const CGObjectInstance * obj, PlayerColor playerColor, PlayerRelations objectRelations)
  183. {
  184. if((obj->ID == Obj::GARRISON || obj->ID == Obj::GARRISON2)
  185. && objectRelations != PlayerRelations::ENEMIES)
  186. return true;
  187. if(obj->ID == Obj::BORDER_GATE)
  188. {
  189. auto quest = dynamic_cast<const CGKeys *>(obj);
  190. if(quest->wasMyColorVisited(playerColor))
  191. return true;
  192. }
  193. return false;
  194. }
  195. bool isBlockVisitObj(const int3 & pos)
  196. {
  197. if(auto obj = cb->getTopObj(pos))
  198. {
  199. if(obj->isBlockedVisitable()) //we can't stand on that object
  200. return true;
  201. }
  202. return false;
  203. }
  204. creInfo infoFromDC(const dwellingContent & dc)
  205. {
  206. creInfo ci;
  207. ci.count = dc.first;
  208. ci.creID = dc.second.size() ? dc.second.back() : CreatureID(-1); //should never be accessed
  209. if (ci.creID != CreatureID::NONE)
  210. {
  211. ci.level = ci.creID.toCreature()->getLevel(); //this is creature tier, while tryRealize expects dwelling level. Ignore.
  212. }
  213. else
  214. {
  215. ci.level = 0;
  216. }
  217. return ci;
  218. }
  219. bool compareHeroStrength(const CGHeroInstance * h1, const CGHeroInstance * h2)
  220. {
  221. return h1->getTotalStrength() < h2->getTotalStrength();
  222. }
  223. bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2)
  224. {
  225. return a1->getArmyStrength() < a2->getArmyStrength();
  226. }
  227. double getArtifactBonusRelevance(const CGHeroInstance * hero, const std::shared_ptr<Bonus> & bonus)
  228. {
  229. if (bonus->propagator && bonus->limiter && bonus->propagator->getPropagatorType() == CBonusSystemNode::BATTLE)
  230. {
  231. // assume that this is battle wide / other side propagator+limiter
  232. // consider it as fully relevant since we don't know about future combat when equipping artifacts
  233. return 1.0;
  234. }
  235. const auto & getArmyRatioAffectedByLimiter = [&]()
  236. {
  237. if (!bonus->limiter)
  238. return 1.0;
  239. uint64_t totalStrength = 0;
  240. uint64_t affectedStrength = 0;
  241. const BonusList stillUndecided;
  242. for (const auto & slot : hero->Slots())
  243. {
  244. const auto allBonuses = slot.second->getAllBonuses(Selector::all, Selector::all);
  245. BonusLimitationContext context = {*bonus, *slot.second, *allBonuses, stillUndecided};
  246. uint64_t unitStrength = slot.second->getPower();
  247. if (bonus->limiter->limit(context) == ILimiter::EDecision::ACCEPT)
  248. affectedStrength += unitStrength;
  249. totalStrength += unitStrength;
  250. }
  251. if (totalStrength == 0)
  252. return 0.0;
  253. return static_cast<double>(affectedStrength) / totalStrength;
  254. };
  255. const auto & getArmyPercentageWithBonus = [&](BonusType type)
  256. {
  257. uint64_t totalStrength = 0;
  258. uint64_t affectedStrength = 0;
  259. for (const auto & slot : hero->Slots())
  260. {
  261. uint64_t unitStrength = slot.second->getPower();
  262. if (slot.second->hasBonusOfType(type))
  263. affectedStrength += unitStrength;
  264. totalStrength += unitStrength;
  265. }
  266. if (totalStrength == 0)
  267. return 0.0;
  268. return static_cast<double>(affectedStrength) / totalStrength;
  269. };
  270. const auto & getSpellSchoolKnownSpellsFactor = [&](SpellSchool school)
  271. {
  272. uint64_t totalWeight = 0;
  273. uint64_t knownWeight = 0;
  274. for (auto spellID : LIBRARY->spellh->getDefaultAllowed())
  275. {
  276. auto spell = spellID.toEntity(LIBRARY);
  277. if (!spell->hasSchool(school))
  278. continue;
  279. uint64_t spellLevel = spell->getLevel();
  280. uint64_t spellWeight = spellLevel * spellLevel;
  281. if (!hero->spellbookContainsSpell(spellID))
  282. knownWeight += spellWeight;
  283. totalWeight += spellWeight;
  284. }
  285. if (totalWeight == 0)
  286. return 0.0;
  287. return static_cast<double>(knownWeight) / totalWeight;
  288. };
  289. const auto & getSpellLevelKnownSpellsFactor = [&](int level)
  290. {
  291. uint64_t totalWeight = 0;
  292. uint64_t knownWeight = 0;
  293. for (auto spellID : LIBRARY->spellh->getDefaultAllowed())
  294. {
  295. auto spell = spellID.toEntity(LIBRARY);
  296. if (spell->getLevel() != level)
  297. continue;
  298. if (!hero->spellbookContainsSpell(spellID))
  299. knownWeight += 1;
  300. totalWeight += 1;
  301. }
  302. if (totalWeight == 0)
  303. return 0.0;
  304. return static_cast<double>(knownWeight) / totalWeight;
  305. };
  306. constexpr double notRelevant = 0.0; // artifact is not useful in current conditions
  307. constexpr double relevant = 1.0;
  308. constexpr double veryRelevant = 2.0; // for very situational artifacts, e.g. skill-specific, or army composition-specific
  309. switch (bonus->type)
  310. {
  311. case BonusType::MOVEMENT:
  312. if (hero->boat && bonus->subtype == BonusCustomSubtype::heroMovementSea)
  313. return veryRelevant;
  314. if (!hero->boat && bonus->subtype == BonusCustomSubtype::heroMovementLand)
  315. return relevant;
  316. return notRelevant;
  317. case BonusType::STACKS_SPEED:
  318. case BonusType::STACK_HEALTH:
  319. return getArmyRatioAffectedByLimiter();
  320. case BonusType::MORALE:
  321. return getArmyRatioAffectedByLimiter() * (1 - getArmyPercentageWithBonus(BonusType::UNDEAD)); // TODO: other unaffected, e.g. Golems
  322. case BonusType::LUCK:
  323. return getArmyRatioAffectedByLimiter(); // Do we have luck?
  324. case BonusType::PRIMARY_SKILL:
  325. if (bonus->subtype == PrimarySkill::ATTACK || bonus->subtype == PrimarySkill::DEFENSE)
  326. return getArmyRatioAffectedByLimiter(); // e.g. Vial of Dragonblood - consider only affected unit
  327. else
  328. return relevant; // spellpower / knowledge - always relevant
  329. case BonusType::WATER_WALKING:
  330. case BonusType::FLYING_MOVEMENT:
  331. return hero->boat ? notRelevant : relevant; // boat can't fly
  332. case BonusType::WHIRLPOOL_PROTECTION:
  333. return hero->boat ? relevant : notRelevant;
  334. case BonusType::UNDEAD_RAISE_PERCENTAGE:
  335. return hero->hasBonusOfType(BonusType::IMPROVED_NECROMANCY) ? veryRelevant : notRelevant;
  336. case BonusType::SPELL_DAMAGE:
  337. case BonusType::SPELL_DURATION:
  338. return hero->hasSpellbook() ? relevant : notRelevant;
  339. case BonusType::PERCENTAGE_DAMAGE_BOOST:
  340. if (bonus->subtype == BonusCustomSubtype::damageTypeRanged)
  341. return veryRelevant * getArmyPercentageWithBonus(BonusType::SHOOTER);
  342. if (bonus->subtype == BonusCustomSubtype::damageTypeMelee)
  343. return veryRelevant * (1 - getArmyPercentageWithBonus(BonusType::SHOOTER));
  344. return 0;
  345. case BonusType::FULL_MANA_REGENERATION:
  346. case BonusType::MANA_REGENERATION:
  347. return hero->mana < hero->manaLimit() ? relevant : notRelevant;
  348. case BonusType::LEARN_BATTLE_SPELL_CHANCE:
  349. return hero->hasBonusOfType(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT) ? relevant : notRelevant;
  350. case BonusType::NO_DISTANCE_PENALTY:
  351. case BonusType::NO_WALL_PENALTY:
  352. return getArmyPercentageWithBonus(BonusType::SHOOTER) * veryRelevant;
  353. case BonusType::SPELLS_OF_SCHOOL:
  354. if (!hero->hasSpellbook())
  355. return notRelevant;
  356. return 1 - getSpellSchoolKnownSpellsFactor(bonus->subtype.as<SpellSchool>());
  357. case BonusType::SPELLS_OF_LEVEL:
  358. if (!hero->hasSpellbook())
  359. return notRelevant;
  360. return 1 - getSpellLevelKnownSpellsFactor(bonus->subtype.getNum());
  361. // Potential TODO's
  362. // case BonusType::MAGIC_RESISTANCE:
  363. // case BonusType::FREE_SHIP_BOARDING:
  364. // case BonusType::GENERATE_RESOURCE:
  365. // case BonusType::CREATURE_GROWTH:
  366. //
  367. // case BonusType::SPELLS_OF_LEVEL:
  368. // case BonusType::SIGHT_RADIUS:
  369. }
  370. return 1.0;
  371. }
  372. int32_t getArtifactBonusScoreImpl(const std::shared_ptr<Bonus> & bonus)
  373. {
  374. switch (bonus->type)
  375. {
  376. case BonusType::MOVEMENT:
  377. if (bonus->subtype == BonusCustomSubtype::heroMovementLand)
  378. return bonus->val * 20;
  379. if (bonus->subtype == BonusCustomSubtype::heroMovementSea)
  380. return bonus->val * 10;
  381. return 0;
  382. case BonusType::STACKS_SPEED:
  383. return bonus->val * 8000;
  384. case BonusType::MORALE:
  385. return bonus->val * 1500;
  386. case BonusType::LUCK:
  387. return bonus->val * 1000;
  388. case BonusType::PRIMARY_SKILL:
  389. return bonus->val * 1000;
  390. case BonusType::SURRENDER_DISCOUNT:
  391. return 0; // irrelevant in gameplay
  392. case BonusType::WATER_WALKING:
  393. return 5000;
  394. case BonusType::FREE_SHIP_BOARDING:
  395. return 10000;
  396. case BonusType::WHIRLPOOL_PROTECTION:
  397. return 5000;
  398. case BonusType::FLYING_MOVEMENT:
  399. return 20000;
  400. case BonusType::UNDEAD_RAISE_PERCENTAGE:
  401. return bonus->val * 400;
  402. case BonusType::GENERATE_RESOURCE:
  403. return bonus->val * LIBRARY->objh->resVals.at(bonus->subtype.as<GameResID>().getNum()) * 10;
  404. case BonusType::SPELL_DURATION:
  405. return bonus->val * 200;
  406. case BonusType::MAGIC_RESISTANCE:
  407. return bonus->val * 400;
  408. case BonusType::PERCENTAGE_DAMAGE_BOOST:
  409. if (bonus->subtype == BonusCustomSubtype::damageTypeRanged)
  410. return bonus->val * 200;
  411. if (bonus->subtype == BonusCustomSubtype::damageTypeMelee)
  412. return bonus->val * 500;
  413. return 0;
  414. case BonusType::CREATURE_GROWTH:
  415. return (1+bonus->subtype.getNum()) * bonus->val * 400;
  416. case BonusType::FULL_MANA_REGENERATION:
  417. return 15000;
  418. case BonusType::MANA_REGENERATION:
  419. return bonus->val * 500;
  420. case BonusType::SPELLS_OF_SCHOOL:
  421. return 20000;
  422. case BonusType::SPELLS_OF_LEVEL:
  423. return bonus->subtype.getNum() * 6000;
  424. case BonusType::SPELL_DAMAGE:
  425. return bonus->val * 120;
  426. case BonusType::SIGHT_RADIUS:
  427. return bonus->val * 1000;
  428. case BonusType::LEARN_BATTLE_SPELL_CHANCE:
  429. return 0; // irrelevant in gameplay
  430. case BonusType::STACK_HEALTH:
  431. return bonus->val * 5000;
  432. case BonusType::NO_DISTANCE_PENALTY:
  433. return 10000;
  434. case BonusType::NO_WALL_PENALTY:
  435. return 5000;
  436. }
  437. return 0;
  438. // Additional bonuses to consider from H3 artifacts:
  439. // MIND_IMMUNITY
  440. // BLOCK_MAGIC_ABOVE
  441. // SPELL_IMMUNITY
  442. // NEGATE_ALL_NATURAL_IMMUNITIES
  443. // SPELL_RESISTANCE_AURA
  444. // SPELL
  445. // BATTLE_NO_FLEEING
  446. // BLOCK_ALL_MAGIC
  447. // NONEVIL_ALIGNMENT_MIX
  448. // OPENING_BATTLE_SPELL
  449. // IMPROVED_NECROMANCY
  450. // HP_REGENERATION
  451. // CREATURE_GROWTH_PERCENT
  452. // LEVEL_SPELL_IMMUNITY
  453. // FREE_SHOOTING
  454. // FULL_MANA_REGENERATION
  455. }
  456. int32_t getArtifactBonusScore(const std::shared_ptr<Bonus> & bonus)
  457. {
  458. if (bonus->propagator && bonus->propagator->getPropagatorType() == CBonusSystemNode::BATTLE)
  459. {
  460. if (bonus->limiter)
  461. {
  462. // assume that this is battle wide / other side propagator+limiter -> invert value
  463. return -getArtifactBonusScoreImpl(bonus);
  464. }
  465. else
  466. {
  467. return 0; // TODO? How to consider battle-wide bonuses that affect everyone?
  468. }
  469. }
  470. else
  471. {
  472. return getArtifactBonusScoreImpl(bonus);
  473. }
  474. }
  475. int64_t getPotentialArtifactScore(const CArtifact * type)
  476. {
  477. int64_t totalScore = 0;
  478. for (const auto & bonus : type->getExportedBonusList())
  479. totalScore += getArtifactBonusScore(bonus);
  480. if (type->hasParts())
  481. {
  482. for (const auto & part : type->getConstituents())
  483. {
  484. for (const auto & bonus : part->getExportedBonusList())
  485. totalScore += getArtifactBonusScore(bonus);
  486. }
  487. }
  488. int64_t finalScore = std::max<int64_t>(type->getPrice() / 5, totalScore );
  489. return finalScore;
  490. }
  491. int64_t getArtifactScoreForHero(const CGHeroInstance * hero, const CArtifactInstance * artifact)
  492. {
  493. if (artifact->isScroll())
  494. {
  495. auto spellID = artifact->getScrollSpellID();
  496. auto spell = spellID.toEntity(LIBRARY);
  497. if (hero->getSpellsInSpellbook().count(spellID))
  498. return 0;
  499. else
  500. return spell->getLevel() * 100;
  501. }
  502. const CArtifact * type = artifact->getType();
  503. int64_t totalScore = 0;
  504. if (type->getId() == ArtifactID::SPELLBOOK)
  505. return 0;
  506. for (const auto & bonus : type->getExportedBonusList())
  507. totalScore += getArtifactBonusRelevance(hero, bonus) * getArtifactBonusScore(bonus);
  508. if (type->hasParts())
  509. {
  510. for (const auto & part : type->getConstituents())
  511. {
  512. for (const auto & bonus : part->getExportedBonusList())
  513. totalScore += getArtifactBonusRelevance(hero, bonus) * getArtifactBonusScore(bonus);
  514. }
  515. }
  516. return totalScore;
  517. }
  518. bool isWeeklyRevisitable(const Nullkiller * ai, const CGObjectInstance * obj)
  519. {
  520. if(!obj)
  521. return false;
  522. //TODO: allow polling of remaining creatures in dwelling
  523. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
  524. return rewardable->configuration.getResetDuration() == 7;
  525. if(dynamic_cast<const CGDwelling *>(obj))
  526. return true;
  527. switch(obj->ID)
  528. {
  529. case Obj::HILL_FORT:
  530. return true;
  531. case Obj::BORDER_GATE:
  532. case Obj::BORDERGUARD:
  533. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  534. }
  535. return false;
  536. }
  537. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  538. {
  539. auto end = std::chrono::high_resolution_clock::now();
  540. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  541. }
  542. int getDuplicatingSlots(const CArmedInstance * army)
  543. {
  544. int duplicatingSlots = 0;
  545. for(const auto & stack : army->Slots())
  546. {
  547. if(stack.second->getCreature() && army->getSlotFor(stack.second->getCreature()) != stack.first)
  548. duplicatingSlots++;
  549. }
  550. return duplicatingSlots;
  551. }
  552. // todo: move to obj manager
  553. bool shouldVisit(const Nullkiller * ai, const CGHeroInstance * h, const CGObjectInstance * obj)
  554. {
  555. auto relations = ai->cb->getPlayerRelations(obj->tempOwner, h->tempOwner);
  556. switch(obj->ID)
  557. {
  558. case Obj::TOWN:
  559. case Obj::HERO: //never visit our heroes at random
  560. return relations == PlayerRelations::ENEMIES; //do not visit our towns at random
  561. case Obj::BORDER_GATE:
  562. {
  563. for(auto q : ai->cb->getMyQuests())
  564. {
  565. if(q.obj == obj->id)
  566. {
  567. return false; // do not visit guards or gates when wandering
  568. }
  569. }
  570. return true; //we don't have this quest yet
  571. }
  572. case Obj::BORDERGUARD: //open borderguard if possible
  573. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  574. case Obj::SEER_HUT:
  575. {
  576. for(auto q : ai->cb->getMyQuests())
  577. {
  578. if(q.obj == obj->id)
  579. {
  580. if(q.getQuest(cb)->checkQuest(h))
  581. return true; //we completed the quest
  582. else
  583. return false; //we can't complete this quest
  584. }
  585. }
  586. return true; //we don't have this quest yet
  587. }
  588. case Obj::CREATURE_GENERATOR1:
  589. {
  590. if(relations == PlayerRelations::ENEMIES)
  591. return true; //flag just in case
  592. if(relations == PlayerRelations::ALLIES)
  593. return false;
  594. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  595. auto duplicatingSlotsCount = getDuplicatingSlots(h);
  596. for(auto level : d->creatures)
  597. {
  598. for(auto c : level.second)
  599. {
  600. if(level.first
  601. && (h->getSlotFor(CreatureID(c)) != SlotID() || duplicatingSlotsCount > 0)
  602. && ai->cb->getResourceAmount().canAfford(c.toCreature()->getFullRecruitCost()))
  603. {
  604. return true;
  605. }
  606. }
  607. }
  608. return false;
  609. }
  610. case Obj::HILL_FORT:
  611. {
  612. for(const auto & slot : h->Slots())
  613. {
  614. if(slot.second->getType()->hasUpgrades())
  615. return true; //TODO: check price?
  616. }
  617. return false;
  618. }
  619. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  620. case Obj::MONOLITH_ONE_WAY_EXIT:
  621. case Obj::MONOLITH_TWO_WAY:
  622. case Obj::WHIRLPOOL:
  623. return false;
  624. case Obj::SCHOOL_OF_MAGIC:
  625. case Obj::SCHOOL_OF_WAR:
  626. {
  627. if(ai->getFreeGold() < 1000)
  628. return false;
  629. break;
  630. }
  631. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  632. if(h->level < 10)
  633. return false;
  634. break;
  635. case Obj::TREE_OF_KNOWLEDGE:
  636. {
  637. if(ai->heroManager->getHeroRole(h) == HeroRole::SCOUT)
  638. return false;
  639. TResources myRes = ai->getFreeResources();
  640. if(myRes[EGameResID::GOLD] < 2000 || myRes[EGameResID::GEMS] < 10)
  641. return false;
  642. break;
  643. }
  644. case Obj::MAGIC_WELL:
  645. return h->mana < h->manaLimit();
  646. case Obj::PRISON:
  647. return !ai->heroManager->heroCapReached();
  648. case Obj::TAVERN:
  649. case Obj::EYE_OF_MAGI:
  650. case Obj::BOAT:
  651. case Obj::SIGN:
  652. return false;
  653. }
  654. if(obj->wasVisited(h))
  655. return false;
  656. auto rewardable = dynamic_cast<const Rewardable::Interface *>(obj);
  657. if(rewardable && rewardable->getAvailableRewards(h, Rewardable::EEventType::EVENT_FIRST_VISIT).empty())
  658. {
  659. return false;
  660. }
  661. return true;
  662. }
  663. bool townHasFreeTavern(const CGTownInstance * town)
  664. {
  665. if(!town->hasBuilt(BuildingID::TAVERN)) return false;
  666. if(!town->getVisitingHero()) return true;
  667. bool canMoveVisitingHeroToGarrison = !town->getUpperArmy()->stacksCount();
  668. return canMoveVisitingHeroToGarrison;
  669. }
  670. uint64_t getHeroArmyStrengthWithCommander(const CGHeroInstance * hero, const CCreatureSet * heroArmy, int fortLevel)
  671. {
  672. auto armyStrength = heroArmy->getArmyStrength(fortLevel);
  673. if(hero && hero->getCommander() && hero->getCommander()->alive)
  674. {
  675. armyStrength += 100 * hero->getCommander()->level;
  676. }
  677. return armyStrength;
  678. }
  679. }