AIUtility.cpp 20 KB

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