AIUtility.cpp 20 KB

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