PriorityEvaluator.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  1. /*
  2. * PriorityEvaluator.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 <limits>
  12. #include "Nullkiller.h"
  13. #include "../../../lib/mapObjectConstructors/AObjectTypeHandler.h"
  14. #include "../../../lib/mapObjectConstructors/CObjectClassesHandler.h"
  15. #include "../../../lib/mapObjectConstructors/CBankInstanceConstructor.h"
  16. #include "../../../lib/mapObjects/MapObjects.h"
  17. #include "../../../lib/mapping/CMapDefines.h"
  18. #include "../../../lib/RoadHandler.h"
  19. #include "../../../lib/CCreatureHandler.h"
  20. #include "../../../lib/VCMI_Lib.h"
  21. #include "../../../lib/StartInfo.h"
  22. #include "../../../CCallback.h"
  23. #include "../../../lib/filesystem/Filesystem.h"
  24. #include "../Goals/ExecuteHeroChain.h"
  25. #include "../Goals/BuildThis.h"
  26. #include "../Goals/StayAtTown.h"
  27. #include "../Goals/ExchangeSwapTownHeroes.h"
  28. #include "../Goals/DismissHero.h"
  29. #include "../Markers/UnlockCluster.h"
  30. #include "../Markers/HeroExchange.h"
  31. #include "../Markers/ArmyUpgrade.h"
  32. #include "../Markers/DefendTown.h"
  33. namespace NKAI
  34. {
  35. constexpr float MIN_CRITICAL_VALUE = 2.0f;
  36. EvaluationContext::EvaluationContext(const Nullkiller* ai)
  37. : movementCost(0.0),
  38. manaCost(0),
  39. danger(0),
  40. closestWayRatio(1),
  41. movementCostByRole(),
  42. skillReward(0),
  43. goldReward(0),
  44. goldCost(0),
  45. armyReward(0),
  46. armyLossPersentage(0),
  47. heroRole(HeroRole::SCOUT),
  48. turn(0),
  49. strategicalValue(0),
  50. conquestValue(0),
  51. evaluator(ai),
  52. enemyHeroDangerRatio(0),
  53. threat(0),
  54. armyGrowth(0),
  55. armyInvolvement(0),
  56. defenseValue(0),
  57. isDefend(false),
  58. threatTurns(INT_MAX),
  59. involvesSailing(false),
  60. isTradeBuilding(false),
  61. isExchange(false),
  62. isArmyUpgrade(false),
  63. isHero(false),
  64. isEnemy(false),
  65. explorePriority(0)
  66. {
  67. }
  68. void EvaluationContext::addNonCriticalStrategicalValue(float value)
  69. {
  70. vstd::amax(strategicalValue, std::min(value, MIN_CRITICAL_VALUE));
  71. }
  72. PriorityEvaluator::~PriorityEvaluator()
  73. {
  74. delete engine;
  75. }
  76. void PriorityEvaluator::initVisitTile()
  77. {
  78. auto file = CResourceHandler::get()->load(ResourcePath("config/ai/nkai/object-priorities.txt"))->readAll();
  79. std::string str = std::string((char *)file.first.get(), file.second);
  80. engine = fl::FllImporter().fromString(str);
  81. armyLossPersentageVariable = engine->getInputVariable("armyLoss");
  82. armyGrowthVariable = engine->getInputVariable("armyGrowth");
  83. heroRoleVariable = engine->getInputVariable("heroRole");
  84. dangerVariable = engine->getInputVariable("danger");
  85. turnVariable = engine->getInputVariable("turn");
  86. mainTurnDistanceVariable = engine->getInputVariable("mainTurnDistance");
  87. scoutTurnDistanceVariable = engine->getInputVariable("scoutTurnDistance");
  88. goldRewardVariable = engine->getInputVariable("goldReward");
  89. armyRewardVariable = engine->getInputVariable("armyReward");
  90. skillRewardVariable = engine->getInputVariable("skillReward");
  91. rewardTypeVariable = engine->getInputVariable("rewardType");
  92. closestHeroRatioVariable = engine->getInputVariable("closestHeroRatio");
  93. strategicalValueVariable = engine->getInputVariable("strategicalValue");
  94. goldPressureVariable = engine->getInputVariable("goldPressure");
  95. goldCostVariable = engine->getInputVariable("goldCost");
  96. fearVariable = engine->getInputVariable("fear");
  97. value = engine->getOutputVariable("Value");
  98. }
  99. bool isAnotherAi(const CGObjectInstance * obj, const CPlayerSpecificInfoCallback & cb)
  100. {
  101. return obj->getOwner().isValidPlayer()
  102. && cb.getStartInfo()->getIthPlayersSettings(obj->getOwner()).isControlledByAI();
  103. }
  104. int32_t estimateTownIncome(CCallback * cb, const CGObjectInstance * target, const CGHeroInstance * hero)
  105. {
  106. auto relations = cb->getPlayerRelations(hero->tempOwner, target->tempOwner);
  107. if(relations != PlayerRelations::ENEMIES)
  108. return 0; // if we already own it, no additional reward will be received by just visiting it
  109. auto booster = isAnotherAi(target, *cb) ? 1 : 2;
  110. auto town = cb->getTown(target->id);
  111. auto fortLevel = town->fortLevel();
  112. if(town->hasCapitol())
  113. return booster * 2000;
  114. // probably well developed town will have city hall
  115. if(fortLevel == CGTownInstance::CASTLE) return booster * 750;
  116. return booster * (town->hasFort() && town->tempOwner != PlayerColor::NEUTRAL ? booster * 500 : 250);
  117. }
  118. int32_t getResourcesGoldReward(const TResources & res)
  119. {
  120. int32_t result = 0;
  121. for(auto r : GameResID::ALL_RESOURCES())
  122. {
  123. if(res[r] > 0)
  124. result += r == EGameResID::GOLD ? res[r] : res[r] * 100;
  125. }
  126. return result;
  127. }
  128. uint64_t getCreatureBankArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  129. {
  130. auto objectInfo = target->getObjectHandler()->getObjectInfo(target->appearance);
  131. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  132. auto creatures = bankInfo->getPossibleCreaturesReward(target->cb);
  133. uint64_t result = 0;
  134. const auto& slots = hero->Slots();
  135. ui64 weakestStackPower = 0;
  136. int duplicatingSlots = getDuplicatingSlots(hero);
  137. if (slots.size() >= GameConstants::ARMY_SIZE)
  138. {
  139. //No free slot, we might discard our weakest stack
  140. weakestStackPower = std::numeric_limits<ui64>().max();
  141. for (const auto & stack : slots)
  142. {
  143. vstd::amin(weakestStackPower, stack.second->getPower());
  144. }
  145. }
  146. for (auto c : creatures)
  147. {
  148. //Only if hero has slot for this creature in the army
  149. auto ccre = dynamic_cast<const CCreature*>(c.data.getType());
  150. if (hero->getSlotFor(ccre).validSlot() || duplicatingSlots > 0)
  151. {
  152. result += (c.data.getType()->getAIValue() * c.data.count) * c.chance;
  153. }
  154. /*else
  155. {
  156. //we will need to discard the weakest stack
  157. result += (c.data.type->getAIValue() * c.data.count - weakestStackPower) * c.chance;
  158. }*/
  159. }
  160. result /= 100; //divide by total chance
  161. return result;
  162. }
  163. uint64_t getDwellingArmyValue(CCallback * cb, const CGObjectInstance * target, bool checkGold)
  164. {
  165. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  166. uint64_t score = 0;
  167. for(auto & creLevel : dwelling->creatures)
  168. {
  169. if(creLevel.first && creLevel.second.size())
  170. {
  171. auto creature = creLevel.second.back().toCreature();
  172. auto creaturesAreFree = creature->getLevel() == 1;
  173. if(!creaturesAreFree && checkGold && !cb->getResourceAmount().canAfford(creature->getFullRecruitCost() * creLevel.first))
  174. continue;
  175. score += creature->getAIValue() * creLevel.first;
  176. }
  177. }
  178. return score;
  179. }
  180. uint64_t getDwellingArmyGrowth(CCallback * cb, const CGObjectInstance * target, PlayerColor myColor)
  181. {
  182. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  183. uint64_t score = 0;
  184. if(dwelling->getOwner() == myColor)
  185. return 0;
  186. for(auto & creLevel : dwelling->creatures)
  187. {
  188. if(creLevel.second.size())
  189. {
  190. auto creature = creLevel.second.back().toCreature();
  191. score += creature->getAIValue() * creature->getGrowth();
  192. }
  193. }
  194. return score;
  195. }
  196. int getDwellingArmyCost(const CGObjectInstance * target)
  197. {
  198. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  199. int cost = 0;
  200. for(auto & creLevel : dwelling->creatures)
  201. {
  202. if(creLevel.first && creLevel.second.size())
  203. {
  204. auto creature = creLevel.second.back().toCreature();
  205. auto creaturesAreFree = creature->getLevel() == 1;
  206. if(!creaturesAreFree)
  207. cost += creature->getFullRecruitCost().marketValue() * creLevel.first;
  208. }
  209. }
  210. return cost;
  211. }
  212. static uint64_t evaluateArtifactArmyValue(const CArtifact * art)
  213. {
  214. if(art->getId() == ArtifactID::SPELL_SCROLL)
  215. return 1500;
  216. return getPotentialArtifactScore(art);
  217. }
  218. uint64_t RewardEvaluator::getArmyReward(
  219. const CGObjectInstance * target,
  220. const CGHeroInstance * hero,
  221. const CCreatureSet * army,
  222. bool checkGold) const
  223. {
  224. const float enemyArmyEliminationRewardRatio = 0.5f;
  225. auto relations = ai->cb->getPlayerRelations(target->tempOwner, ai->playerID);
  226. if(!target)
  227. return 0;
  228. switch(target->ID)
  229. {
  230. case Obj::HILL_FORT:
  231. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeValue;
  232. case Obj::CREATURE_GENERATOR1:
  233. case Obj::CREATURE_GENERATOR2:
  234. case Obj::CREATURE_GENERATOR3:
  235. case Obj::CREATURE_GENERATOR4:
  236. return getDwellingArmyValue(ai->cb.get(), target, checkGold);
  237. case Obj::SPELL_SCROLL:
  238. //FALL_THROUGH
  239. case Obj::ARTIFACT:
  240. return evaluateArtifactArmyValue(dynamic_cast<const CGArtifact *>(target)->storedArtifact->getType());
  241. case Obj::HERO:
  242. return relations == PlayerRelations::ENEMIES
  243. ? enemyArmyEliminationRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->getArmyStrength()
  244. : 0;
  245. case Obj::PANDORAS_BOX:
  246. return 5000;
  247. case Obj::MAGIC_WELL:
  248. case Obj::MAGIC_SPRING:
  249. return getManaRecoveryArmyReward(hero);
  250. default:
  251. break;
  252. }
  253. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  254. if(rewardable)
  255. {
  256. auto totalValue = 0;
  257. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  258. {
  259. auto & info = rewardable->configuration.info[index];
  260. auto rewardValue = 0;
  261. if(!info.reward.artifacts.empty())
  262. {
  263. for(auto artID : info.reward.artifacts)
  264. {
  265. const auto * art = dynamic_cast<const CArtifact *>(VLC->artifacts()->getById(artID));
  266. rewardValue += evaluateArtifactArmyValue(art);
  267. }
  268. }
  269. if(!info.reward.creatures.empty())
  270. {
  271. for(const auto & stackInfo : info.reward.creatures)
  272. {
  273. rewardValue += stackInfo.getType()->getAIValue() * stackInfo.getCount();
  274. }
  275. }
  276. totalValue += rewardValue > 0 ? rewardValue / (info.reward.artifacts.size() + info.reward.creatures.size()) : 0;
  277. }
  278. return totalValue;
  279. }
  280. return 0;
  281. }
  282. uint64_t RewardEvaluator::getArmyGrowth(
  283. const CGObjectInstance * target,
  284. const CGHeroInstance * hero,
  285. const CCreatureSet * army) const
  286. {
  287. if(!target)
  288. return 0;
  289. auto relations = ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner);
  290. if(relations != PlayerRelations::ENEMIES)
  291. return 0;
  292. switch(target->ID)
  293. {
  294. case Obj::TOWN:
  295. {
  296. auto town = dynamic_cast<const CGTownInstance *>(target);
  297. auto fortLevel = town->fortLevel();
  298. auto neutral = !town->getOwner().isValidPlayer();
  299. auto booster = isAnotherAi(town, *ai->cb) || neutral ? 1 : 2;
  300. if(fortLevel < CGTownInstance::CITADEL)
  301. return town->hasFort() ? booster * 500 : 0;
  302. else
  303. return booster * (fortLevel == CGTownInstance::CASTLE ? 5000 : 2000);
  304. }
  305. case Obj::CREATURE_GENERATOR1:
  306. case Obj::CREATURE_GENERATOR2:
  307. case Obj::CREATURE_GENERATOR3:
  308. case Obj::CREATURE_GENERATOR4:
  309. return getDwellingArmyGrowth(ai->cb.get(), target, hero->getOwner());
  310. case Obj::ARTIFACT:
  311. // it is not supported now because hero will not sit in town on 7th day but later parts of legion may be counted as army growth as well.
  312. return 0;
  313. default:
  314. return 0;
  315. }
  316. }
  317. int RewardEvaluator::getGoldCost(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army) const
  318. {
  319. if(!target)
  320. return 0;
  321. if(auto * m = dynamic_cast<const IMarket *>(target))
  322. {
  323. if(m->allowsTrade(EMarketMode::RESOURCE_SKILL))
  324. return 2000;
  325. }
  326. switch(target->ID)
  327. {
  328. case Obj::HILL_FORT:
  329. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeCost[EGameResID::GOLD];
  330. case Obj::SCHOOL_OF_MAGIC:
  331. case Obj::SCHOOL_OF_WAR:
  332. return 1000;
  333. case Obj::CREATURE_GENERATOR1:
  334. case Obj::CREATURE_GENERATOR2:
  335. case Obj::CREATURE_GENERATOR3:
  336. case Obj::CREATURE_GENERATOR4:
  337. return getDwellingArmyCost(target);
  338. default:
  339. return 0;
  340. }
  341. }
  342. float RewardEvaluator::getEnemyHeroStrategicalValue(const CGHeroInstance * enemy) const
  343. {
  344. auto objectsUnderTreat = ai->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  345. float objectValue = 0;
  346. for(auto obj : objectsUnderTreat)
  347. {
  348. vstd::amax(objectValue, getStrategicalValue(obj));
  349. }
  350. /*
  351. 1. If an enemy hero can attack nearby object, it's not useful to capture the object on our own.
  352. Killing the hero is almost as important (0.9) as capturing the object itself.
  353. 2. The formula quickly approaches 1.0 as hero level increases,
  354. but higher level always means higher value and the minimal value for level 1 hero is 0.5
  355. */
  356. return std::min(1.5f, objectValue * 0.9f + (1.5f - (1.5f / (1 + enemy->level))));
  357. }
  358. float RewardEvaluator::getResourceRequirementStrength(int resType) const
  359. {
  360. TResources requiredResources = ai->buildAnalyzer->getResourcesRequiredNow();
  361. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  362. if(requiredResources[resType] == 0)
  363. return 0;
  364. if(dailyIncome[resType] == 0)
  365. return 1.0f;
  366. float ratio = (float)requiredResources[resType] / dailyIncome[resType] / 2;
  367. return std::min(ratio, 1.0f);
  368. }
  369. float RewardEvaluator::getTotalResourceRequirementStrength(int resType) const
  370. {
  371. TResources requiredResources = ai->buildAnalyzer->getTotalResourcesRequired();
  372. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  373. if(requiredResources[resType] == 0)
  374. return 0;
  375. float ratio = dailyIncome[resType] == 0
  376. ? (float)requiredResources[resType] / 10.0f
  377. : (float)requiredResources[resType] / dailyIncome[resType] / 20.0f;
  378. return std::min(ratio, 2.0f);
  379. }
  380. uint64_t RewardEvaluator::townArmyGrowth(const CGTownInstance * town) const
  381. {
  382. uint64_t result = 0;
  383. for(auto creatureInfo : town->creatures)
  384. {
  385. if(creatureInfo.second.empty())
  386. continue;
  387. auto creature = creatureInfo.second.back().toCreature();
  388. result += creature->getAIValue() * town->getGrowthInfo(creature->getLevel() - 1).totalGrowth();
  389. }
  390. return result;
  391. }
  392. float RewardEvaluator::getManaRecoveryArmyReward(const CGHeroInstance * hero) const
  393. {
  394. return ai->heroManager->getMagicStrength(hero) * 10000 * (1.0f - std::sqrt(static_cast<float>(hero->mana) / hero->manaLimit()));
  395. }
  396. float RewardEvaluator::getResourceRequirementStrength(const TResources & res) const
  397. {
  398. float sum = 0.0f;
  399. for(TResources::nziterator it(res); it.valid(); it++)
  400. {
  401. //Evaluate resources used for construction. Gold is evaluated separately.
  402. if(it->resType != EGameResID::GOLD)
  403. {
  404. sum += 0.1f * it->resVal * getResourceRequirementStrength(it->resType)
  405. + 0.05f * it->resVal * getTotalResourceRequirementStrength(it->resType);
  406. }
  407. }
  408. return sum;
  409. }
  410. float RewardEvaluator::getStrategicalValue(const CGObjectInstance * target, const CGHeroInstance * hero) const
  411. {
  412. if(!target)
  413. return 0;
  414. switch(target->ID)
  415. {
  416. case Obj::MINE:
  417. {
  418. auto mine = dynamic_cast<const CGMine *>(target);
  419. return mine->producedResource == EGameResID::GOLD
  420. ? 0.5f
  421. : 0.4f * getTotalResourceRequirementStrength(mine->producedResource) + 0.1f * getResourceRequirementStrength(mine->producedResource);
  422. }
  423. case Obj::RESOURCE:
  424. {
  425. auto resource = dynamic_cast<const CGResource *>(target);
  426. TResources res;
  427. res[resource->resourceID()] = resource->amount;
  428. return getResourceRequirementStrength(res);
  429. }
  430. case Obj::TOWN:
  431. {
  432. if(ai->buildAnalyzer->getDevelopmentInfo().empty())
  433. return 10.0f;
  434. auto town = dynamic_cast<const CGTownInstance *>(target);
  435. if(town->getOwner() == ai->playerID)
  436. {
  437. auto armyIncome = townArmyGrowth(town);
  438. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  439. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  440. }
  441. auto fortLevel = town->fortLevel();
  442. auto booster = isAnotherAi(town, *ai->cb) ? 0.4f : 1.0f;
  443. if(town->hasCapitol())
  444. return booster * 1.5;
  445. if(fortLevel < CGTownInstance::CITADEL)
  446. return booster * (town->hasFort() ? 1.0 : 0.8);
  447. else
  448. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  449. }
  450. case Obj::HERO:
  451. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  452. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  453. : 0;
  454. case Obj::KEYMASTER:
  455. return 0.6f;
  456. default:
  457. break;
  458. }
  459. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  460. if(rewardable && hero)
  461. {
  462. auto resourceReward = 0.0f;
  463. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  464. {
  465. resourceReward += getResourceRequirementStrength(rewardable->configuration.info[index].reward.resources);
  466. }
  467. return resourceReward;
  468. }
  469. return 0;
  470. }
  471. float RewardEvaluator::getConquestValue(const CGObjectInstance* target) const
  472. {
  473. if (!target)
  474. return 0;
  475. if (target->getOwner() == ai->playerID)
  476. return 0;
  477. switch (target->ID)
  478. {
  479. case Obj::TOWN:
  480. {
  481. if (ai->buildAnalyzer->getDevelopmentInfo().empty())
  482. return 10.0f;
  483. auto town = dynamic_cast<const CGTownInstance*>(target);
  484. if (town->getOwner() == ai->playerID)
  485. {
  486. auto armyIncome = townArmyGrowth(town);
  487. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  488. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  489. }
  490. auto fortLevel = town->fortLevel();
  491. auto booster = 1.0f;
  492. if (town->hasCapitol())
  493. return booster * 1.5;
  494. if (fortLevel < CGTownInstance::CITADEL)
  495. return booster * (town->hasFort() ? 1.0 : 0.8);
  496. else
  497. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  498. }
  499. case Obj::HERO:
  500. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  501. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance*>(target))
  502. : 0;
  503. case Obj::KEYMASTER:
  504. return 0.6f;
  505. default:
  506. return 0;
  507. }
  508. }
  509. float RewardEvaluator::evaluateWitchHutSkillScore(const CGObjectInstance * hut, const CGHeroInstance * hero, HeroRole role) const
  510. {
  511. auto rewardable = dynamic_cast<const CRewardableObject *>(hut);
  512. assert(rewardable);
  513. auto skill = SecondarySkill(*rewardable->configuration.getVariable("secondarySkill", "gainedSkill"));
  514. if(!hut->wasVisited(hero->tempOwner))
  515. return role == HeroRole::SCOUT ? 2 : 0;
  516. if(hero->getSecSkillLevel(skill) != MasteryLevel::NONE
  517. || hero->secSkills.size() >= GameConstants::SKILL_PER_HERO)
  518. return 0;
  519. auto score = ai->heroManager->evaluateSecSkill(skill, hero);
  520. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  521. }
  522. float RewardEvaluator::getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role) const
  523. {
  524. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  525. if(!target)
  526. return 0;
  527. switch(target->ID)
  528. {
  529. case Obj::STAR_AXIS:
  530. case Obj::SCHOLAR:
  531. case Obj::SCHOOL_OF_MAGIC:
  532. case Obj::SCHOOL_OF_WAR:
  533. case Obj::GARDEN_OF_REVELATION:
  534. case Obj::MARLETTO_TOWER:
  535. case Obj::MERCENARY_CAMP:
  536. case Obj::TREE_OF_KNOWLEDGE:
  537. return 1;
  538. case Obj::LEARNING_STONE:
  539. return 1.0f / std::sqrt(hero->level);
  540. case Obj::ARENA:
  541. return 2;
  542. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  543. return 0.25f;
  544. case Obj::SHRINE_OF_MAGIC_GESTURE:
  545. return 1.0f;
  546. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  547. return 2.0f;
  548. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  549. return 8;
  550. case Obj::WITCH_HUT:
  551. return evaluateWitchHutSkillScore(target, hero, role);
  552. case Obj::PANDORAS_BOX:
  553. //Can contains experience, spells, or skills (only on custom maps)
  554. return 2.5f;
  555. case Obj::HERO:
  556. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  557. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  558. : 0;
  559. default:
  560. break;
  561. }
  562. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  563. if(rewardable)
  564. {
  565. auto totalValue = 0.0f;
  566. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  567. {
  568. auto & info = rewardable->configuration.info[index];
  569. auto rewardValue = 0.0f;
  570. if(!info.reward.spells.empty())
  571. {
  572. for(auto spellID : info.reward.spells)
  573. {
  574. const spells::Spell * spell = VLC->spells()->getById(spellID);
  575. if(hero->canLearnSpell(spell) && !hero->spellbookContainsSpell(spellID))
  576. {
  577. rewardValue += std::sqrt(spell->getLevel()) / 4.0f;
  578. }
  579. }
  580. totalValue += rewardValue / info.reward.spells.size();
  581. }
  582. if(!info.reward.primary.empty())
  583. {
  584. for(auto value : info.reward.primary)
  585. {
  586. totalValue += value;
  587. }
  588. }
  589. }
  590. return totalValue;
  591. }
  592. return 0;
  593. }
  594. const HitMapInfo & RewardEvaluator::getEnemyHeroDanger(const int3 & tile, uint8_t turn) const
  595. {
  596. auto & treatNode = ai->dangerHitMap->getTileThreat(tile);
  597. if(treatNode.maximumDanger.danger == 0)
  598. return HitMapInfo::NoThreat;
  599. if(treatNode.maximumDanger.turn <= turn)
  600. return treatNode.maximumDanger;
  601. return treatNode.fastestDanger.turn <= turn ? treatNode.fastestDanger : HitMapInfo::NoThreat;
  602. }
  603. int32_t getArmyCost(const CArmedInstance * army)
  604. {
  605. int32_t value = 0;
  606. for(auto stack : army->Slots())
  607. {
  608. value += stack.second->getCreatureID().toCreature()->getFullRecruitCost().marketValue() * stack.second->count;
  609. }
  610. return value;
  611. }
  612. int32_t RewardEvaluator::getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero) const
  613. {
  614. if(!target)
  615. return 0;
  616. auto relations = ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner);
  617. const int dailyIncomeMultiplier = 5;
  618. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  619. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  620. switch(target->ID)
  621. {
  622. case Obj::RESOURCE:
  623. {
  624. auto * res = dynamic_cast<const CGResource*>(target);
  625. return res && res->resourceID() == GameResID::GOLD ? 600 : 100;
  626. }
  627. case Obj::TREASURE_CHEST:
  628. return 1500;
  629. case Obj::WATER_WHEEL:
  630. return 1000;
  631. case Obj::TOWN:
  632. return dailyIncomeMultiplier * estimateTownIncome(ai->cb.get(), target, hero);
  633. case Obj::MINE:
  634. case Obj::ABANDONED_MINE:
  635. {
  636. auto * mine = dynamic_cast<const CGMine*>(target);
  637. return dailyIncomeMultiplier * (mine->producedResource == GameResID::GOLD ? 1000 : 75);
  638. }
  639. case Obj::PANDORAS_BOX:
  640. return 2500;
  641. case Obj::PRISON:
  642. //Objectively saves us 2500 to hire hero
  643. return GameConstants::HERO_GOLD_COST;
  644. case Obj::HERO:
  645. return relations == PlayerRelations::ENEMIES
  646. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  647. : 0;
  648. default:
  649. break;
  650. }
  651. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  652. if(rewardable)
  653. {
  654. auto goldReward = 0;
  655. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  656. {
  657. auto & info = rewardable->configuration.info[index];
  658. goldReward += getResourcesGoldReward(info.reward.resources);
  659. }
  660. return goldReward;
  661. }
  662. return 0;
  663. }
  664. class HeroExchangeEvaluator : public IEvaluationContextBuilder
  665. {
  666. public:
  667. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  668. {
  669. if(task->goalType != Goals::HERO_EXCHANGE)
  670. return;
  671. Goals::HeroExchange & heroExchange = dynamic_cast<Goals::HeroExchange &>(*task);
  672. uint64_t armyStrength = heroExchange.getReinforcementArmyStrength(evaluationContext.evaluator.ai);
  673. evaluationContext.addNonCriticalStrategicalValue(2.0f * armyStrength / (float)heroExchange.hero->getArmyStrength());
  674. evaluationContext.conquestValue += 2.0f * armyStrength / (float)heroExchange.hero->getArmyStrength();
  675. evaluationContext.heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(heroExchange.hero);
  676. evaluationContext.isExchange = true;
  677. }
  678. };
  679. class ArmyUpgradeEvaluator : public IEvaluationContextBuilder
  680. {
  681. public:
  682. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  683. {
  684. if(task->goalType != Goals::ARMY_UPGRADE)
  685. return;
  686. Goals::ArmyUpgrade & armyUpgrade = dynamic_cast<Goals::ArmyUpgrade &>(*task);
  687. uint64_t upgradeValue = armyUpgrade.getUpgradeValue();
  688. evaluationContext.armyReward += upgradeValue;
  689. evaluationContext.addNonCriticalStrategicalValue(upgradeValue / (float)armyUpgrade.hero->getArmyStrength());
  690. evaluationContext.isArmyUpgrade = true;
  691. }
  692. };
  693. class ExplorePointEvaluator : public IEvaluationContextBuilder
  694. {
  695. public:
  696. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  697. {
  698. if(task->goalType != Goals::EXPLORATION_POINT)
  699. return;
  700. int tilesDiscovered = task->value;
  701. evaluationContext.addNonCriticalStrategicalValue(0.03f * tilesDiscovered);
  702. for (auto obj : evaluationContext.evaluator.ai->cb->getVisitableObjs(task->tile))
  703. {
  704. switch (obj->ID.num)
  705. {
  706. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  707. case Obj::MONOLITH_TWO_WAY:
  708. case Obj::SUBTERRANEAN_GATE:
  709. evaluationContext.explorePriority = 1;
  710. break;
  711. case Obj::REDWOOD_OBSERVATORY:
  712. case Obj::PILLAR_OF_FIRE:
  713. evaluationContext.explorePriority = 2;
  714. break;
  715. }
  716. }
  717. if(evaluationContext.evaluator.ai->cb->getTile(task->tile)->roadType != RoadId::NO_ROAD)
  718. evaluationContext.explorePriority = 1;
  719. if (evaluationContext.explorePriority == 0)
  720. evaluationContext.explorePriority = 3;
  721. }
  722. };
  723. class StayAtTownManaRecoveryEvaluator : public IEvaluationContextBuilder
  724. {
  725. public:
  726. void buildEvaluationContext(EvaluationContext& evaluationContext, Goals::TSubgoal task) const override
  727. {
  728. if (task->goalType != Goals::STAY_AT_TOWN)
  729. return;
  730. Goals::StayAtTown& stayAtTown = dynamic_cast<Goals::StayAtTown&>(*task);
  731. evaluationContext.armyReward += evaluationContext.evaluator.getManaRecoveryArmyReward(stayAtTown.getHero());
  732. if (evaluationContext.armyReward == 0)
  733. evaluationContext.isDefend = true;
  734. else
  735. {
  736. evaluationContext.movementCost += stayAtTown.getMovementWasted();
  737. evaluationContext.movementCostByRole[evaluationContext.heroRole] += stayAtTown.getMovementWasted();
  738. }
  739. }
  740. };
  741. void addTileDanger(EvaluationContext & evaluationContext, const int3 & tile, uint8_t turn, uint64_t ourStrength)
  742. {
  743. HitMapInfo enemyDanger = evaluationContext.evaluator.getEnemyHeroDanger(tile, turn);
  744. if(enemyDanger.danger)
  745. {
  746. auto dangerRatio = enemyDanger.danger / (double)ourStrength;
  747. vstd::amax(evaluationContext.enemyHeroDangerRatio, dangerRatio);
  748. vstd::amax(evaluationContext.threat, enemyDanger.threat);
  749. }
  750. }
  751. class DefendTownEvaluator : public IEvaluationContextBuilder
  752. {
  753. public:
  754. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  755. {
  756. if(task->goalType != Goals::DEFEND_TOWN)
  757. return;
  758. Goals::DefendTown & defendTown = dynamic_cast<Goals::DefendTown &>(*task);
  759. const CGTownInstance * town = defendTown.town;
  760. auto & treat = defendTown.getTreat();
  761. auto strategicalValue = evaluationContext.evaluator.getStrategicalValue(town);
  762. float multiplier = 1;
  763. if(treat.turn < defendTown.getTurn())
  764. multiplier /= 1 + (defendTown.getTurn() - treat.turn);
  765. multiplier /= 1.0f + treat.turn / 5.0f;
  766. if(defendTown.getTurn() > 0 && defendTown.isCounterAttack())
  767. {
  768. auto ourSpeed = defendTown.hero->movementPointsLimit(true);
  769. auto enemySpeed = treat.hero.get(evaluationContext.evaluator.ai->cb.get())->movementPointsLimit(true);
  770. if(enemySpeed > ourSpeed) multiplier *= 0.7f;
  771. }
  772. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  773. auto armyGrowth = evaluationContext.evaluator.townArmyGrowth(town);
  774. evaluationContext.armyGrowth += armyGrowth * multiplier;
  775. evaluationContext.goldReward += dailyIncome * 5 * multiplier;
  776. if(evaluationContext.evaluator.ai->buildAnalyzer->getDevelopmentInfo().size() == 1)
  777. vstd::amax(evaluationContext.strategicalValue, 2.5f * multiplier * strategicalValue);
  778. else
  779. evaluationContext.addNonCriticalStrategicalValue(1.7f * multiplier * strategicalValue);
  780. evaluationContext.defenseValue = town->fortLevel();
  781. evaluationContext.isDefend = true;
  782. evaluationContext.threatTurns = treat.turn;
  783. vstd::amax(evaluationContext.danger, defendTown.getTreat().danger);
  784. addTileDanger(evaluationContext, town->visitablePos(), defendTown.getTurn(), defendTown.getDefenceStrength());
  785. }
  786. };
  787. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  788. {
  789. private:
  790. const Nullkiller * ai;
  791. public:
  792. ExecuteHeroChainEvaluationContextBuilder(const Nullkiller * ai) : ai(ai) {}
  793. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  794. {
  795. if(task->goalType != Goals::EXECUTE_HERO_CHAIN)
  796. return;
  797. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  798. const AIPath & path = chain.getPath();
  799. if (vstd::isAlmostZero(path.movementCost()))
  800. return;
  801. vstd::amax(evaluationContext.danger, path.getTotalDanger());
  802. evaluationContext.movementCost += path.movementCost();
  803. evaluationContext.closestWayRatio = chain.closestWayRatio;
  804. std::map<const CGHeroInstance *, float> costsPerHero;
  805. for(auto & node : path.nodes)
  806. {
  807. vstd::amax(costsPerHero[node.targetHero], node.cost);
  808. if (node.layer == EPathfindingLayer::SAIL)
  809. evaluationContext.involvesSailing = true;
  810. }
  811. float highestCostForSingleHero = 0;
  812. for(auto pair : costsPerHero)
  813. {
  814. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(pair.first);
  815. evaluationContext.movementCostByRole[role] += pair.second;
  816. if (pair.second > highestCostForSingleHero)
  817. highestCostForSingleHero = pair.second;
  818. }
  819. if (highestCostForSingleHero > 1 && costsPerHero.size() > 1)
  820. {
  821. //Chains that involve more than 1 hero doing something for more than a turn are too expensive in my book. They often involved heroes doing nothing just standing there waiting to fulfill their part of the chain.
  822. return;
  823. }
  824. evaluationContext.movementCost *= costsPerHero.size(); //further deincentivise chaining as it often involves bringing back the army afterwards
  825. auto hero = task->hero;
  826. bool checkGold = evaluationContext.danger == 0;
  827. auto army = path.heroArmy;
  828. const CGObjectInstance * target = ai->cb->getObj((ObjectInstanceID)task->objid, false);
  829. auto heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(hero);
  830. if(heroRole == HeroRole::MAIN)
  831. evaluationContext.heroRole = heroRole;
  832. if (target)
  833. {
  834. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero);
  835. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold);
  836. evaluationContext.armyGrowth += evaluationContext.evaluator.getArmyGrowth(target, hero, army);
  837. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, heroRole);
  838. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target));
  839. evaluationContext.conquestValue += evaluationContext.evaluator.getConquestValue(target);
  840. if (target->ID == Obj::HERO)
  841. evaluationContext.isHero = true;
  842. if (target->getOwner().isValidPlayer() && ai->cb->getPlayerRelations(ai->playerID, target->getOwner()) == PlayerRelations::ENEMIES)
  843. evaluationContext.isEnemy = true;
  844. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army);
  845. if(evaluationContext.danger > 0)
  846. evaluationContext.skillReward += (float)evaluationContext.danger / (float)hero->getArmyStrength();
  847. }
  848. evaluationContext.armyInvolvement += army->getArmyCost();
  849. vstd::amax(evaluationContext.armyLossPersentage, (float)path.getTotalArmyLoss() / (float)army->getArmyStrength());
  850. addTileDanger(evaluationContext, path.targetTile(), path.turn(), path.getHeroStrength());
  851. vstd::amax(evaluationContext.turn, path.turn());
  852. }
  853. };
  854. class ClusterEvaluationContextBuilder : public IEvaluationContextBuilder
  855. {
  856. public:
  857. ClusterEvaluationContextBuilder(const Nullkiller * ai) {}
  858. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  859. {
  860. if(task->goalType != Goals::UNLOCK_CLUSTER)
  861. return;
  862. Goals::UnlockCluster & clusterGoal = dynamic_cast<Goals::UnlockCluster &>(*task);
  863. std::shared_ptr<ObjectCluster> cluster = clusterGoal.getCluster();
  864. auto hero = clusterGoal.hero;
  865. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(hero);
  866. std::vector<std::pair<ObjectInstanceID, ClusterObjectInfo>> objects(cluster->objects.begin(), cluster->objects.end());
  867. std::sort(objects.begin(), objects.end(), [](std::pair<ObjectInstanceID, ClusterObjectInfo> o1, std::pair<ObjectInstanceID, ClusterObjectInfo> o2) -> bool
  868. {
  869. return o1.second.priority > o2.second.priority;
  870. });
  871. int boost = 1;
  872. for(auto & objInfo : objects)
  873. {
  874. auto target = evaluationContext.evaluator.ai->cb->getObj(objInfo.first);
  875. bool checkGold = objInfo.second.danger == 0;
  876. auto army = hero;
  877. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero) / boost;
  878. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold) / boost;
  879. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, role) / boost;
  880. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target) / boost);
  881. evaluationContext.conquestValue += evaluationContext.evaluator.getConquestValue(target);
  882. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army) / boost;
  883. evaluationContext.movementCostByRole[role] += objInfo.second.movementCost / boost;
  884. evaluationContext.movementCost += objInfo.second.movementCost / boost;
  885. vstd::amax(evaluationContext.turn, objInfo.second.turn / boost);
  886. boost <<= 1;
  887. if(boost > 8)
  888. break;
  889. }
  890. }
  891. };
  892. class ExchangeSwapTownHeroesContextBuilder : public IEvaluationContextBuilder
  893. {
  894. public:
  895. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  896. {
  897. if(task->goalType != Goals::EXCHANGE_SWAP_TOWN_HEROES)
  898. return;
  899. Goals::ExchangeSwapTownHeroes & swapCommand = dynamic_cast<Goals::ExchangeSwapTownHeroes &>(*task);
  900. const CGHeroInstance * garrisonHero = swapCommand.getGarrisonHero();
  901. logAi->trace("buildEvaluationContext ExchangeSwapTownHeroesContextBuilder %s affected objects: %d", swapCommand.toString(), swapCommand.getAffectedObjects().size());
  902. for (auto obj : swapCommand.getAffectedObjects())
  903. {
  904. logAi->trace("affected object: %s", evaluationContext.evaluator.ai->cb->getObj(obj)->getObjectName());
  905. }
  906. if (garrisonHero)
  907. logAi->debug("with %s and %d", garrisonHero->getNameTranslated(), int(swapCommand.getLockingReason()));
  908. if(garrisonHero && swapCommand.getLockingReason() == HeroLockedReason::DEFENCE)
  909. {
  910. auto defenderRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(garrisonHero);
  911. auto mpLeft = garrisonHero->movementPointsRemaining() / (float)garrisonHero->movementPointsLimit(true);
  912. evaluationContext.movementCost += mpLeft;
  913. evaluationContext.movementCostByRole[defenderRole] += mpLeft;
  914. evaluationContext.heroRole = defenderRole;
  915. evaluationContext.isDefend = true;
  916. evaluationContext.armyInvolvement = garrisonHero->getArmyStrength();
  917. logAi->debug("evaluationContext.isDefend: %d", evaluationContext.isDefend);
  918. }
  919. }
  920. };
  921. class DismissHeroContextBuilder : public IEvaluationContextBuilder
  922. {
  923. private:
  924. const Nullkiller * ai;
  925. public:
  926. DismissHeroContextBuilder(const Nullkiller * ai) : ai(ai) {}
  927. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  928. {
  929. if(task->goalType != Goals::DISMISS_HERO)
  930. return;
  931. Goals::DismissHero & dismissCommand = dynamic_cast<Goals::DismissHero &>(*task);
  932. const CGHeroInstance * dismissedHero = dismissCommand.getHero();
  933. auto role = ai->heroManager->getHeroRole(dismissedHero);
  934. auto mpLeft = dismissedHero->movementPointsRemaining();
  935. evaluationContext.movementCost += mpLeft;
  936. evaluationContext.movementCostByRole[role] += mpLeft;
  937. evaluationContext.goldCost += GameConstants::HERO_GOLD_COST + getArmyCost(dismissedHero);
  938. }
  939. };
  940. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  941. {
  942. public:
  943. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  944. {
  945. if(task->goalType != Goals::BUILD_STRUCTURE)
  946. return;
  947. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  948. auto & bi = buildThis.buildingInfo;
  949. evaluationContext.goldReward += 7 * bi.dailyIncome.marketValue() / 2; // 7 day income but half we already have
  950. evaluationContext.heroRole = HeroRole::MAIN;
  951. evaluationContext.movementCostByRole[evaluationContext.heroRole] += bi.prerequisitesCount;
  952. int32_t cost = bi.buildCost[EGameResID::GOLD];
  953. evaluationContext.goldCost += cost;
  954. evaluationContext.closestWayRatio = 1;
  955. evaluationContext.buildingCost += bi.buildCostWithPrerequisites;
  956. if (bi.id == BuildingID::MARKETPLACE || bi.dailyIncome[EGameResID::WOOD] > 0)
  957. evaluationContext.isTradeBuilding = true;
  958. #if NKAI_TRACE_LEVEL >= 1
  959. logAi->trace("Building costs for %s : %s MarketValue: %d",bi.toString(), evaluationContext.buildingCost.toString(), evaluationContext.buildingCost.marketValue());
  960. #endif
  961. if(bi.creatureID != CreatureID::NONE)
  962. {
  963. evaluationContext.addNonCriticalStrategicalValue(buildThis.townInfo.armyStrength / 50000.0);
  964. if(bi.baseCreatureID == bi.creatureID)
  965. {
  966. evaluationContext.addNonCriticalStrategicalValue((0.5f + 0.1f * bi.creatureLevel) / (float)bi.prerequisitesCount);
  967. evaluationContext.armyReward += bi.armyStrength;
  968. }
  969. else
  970. {
  971. auto potentialUpgradeValue = evaluationContext.evaluator.getUpgradeArmyReward(buildThis.town, bi);
  972. evaluationContext.addNonCriticalStrategicalValue(potentialUpgradeValue / 10000.0f / (float)bi.prerequisitesCount);
  973. evaluationContext.armyReward += potentialUpgradeValue / (float)bi.prerequisitesCount;
  974. }
  975. }
  976. else if(bi.id == BuildingID::CITADEL || bi.id == BuildingID::CASTLE)
  977. {
  978. evaluationContext.addNonCriticalStrategicalValue(buildThis.town->creatures.size() * 0.2f);
  979. evaluationContext.armyReward += buildThis.townInfo.armyStrength / 2;
  980. }
  981. else if(bi.id >= BuildingID::MAGES_GUILD_1 && bi.id <= BuildingID::MAGES_GUILD_5)
  982. {
  983. evaluationContext.skillReward += 2 * (bi.id - BuildingID::MAGES_GUILD_1);
  984. for (auto hero : evaluationContext.evaluator.ai->cb->getHeroesInfo())
  985. {
  986. evaluationContext.armyInvolvement += hero->getArmyCost();
  987. }
  988. }
  989. int sameTownBonus = 0;
  990. for (auto town : evaluationContext.evaluator.ai->cb->getTownsInfo())
  991. {
  992. if (buildThis.town->getFaction() == town->getFaction())
  993. sameTownBonus += town->getTownLevel();
  994. }
  995. evaluationContext.armyReward *= sameTownBonus;
  996. if(evaluationContext.goldReward)
  997. {
  998. auto goldPressure = evaluationContext.evaluator.ai->buildAnalyzer->getGoldPressure();
  999. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.goldReward * goldPressure / 3500.0f / bi.prerequisitesCount);
  1000. }
  1001. if(bi.notEnoughRes && bi.prerequisitesCount == 1)
  1002. {
  1003. evaluationContext.strategicalValue /= 3;
  1004. evaluationContext.movementCostByRole[evaluationContext.heroRole] += 5;
  1005. evaluationContext.turn += 5;
  1006. }
  1007. }
  1008. };
  1009. uint64_t RewardEvaluator::getUpgradeArmyReward(const CGTownInstance * town, const BuildingInfo & bi) const
  1010. {
  1011. if(ai->buildAnalyzer->hasAnyBuilding(town->getFactionID(), bi.id))
  1012. return 0;
  1013. auto creaturesToUpgrade = ai->armyManager->getTotalCreaturesAvailable(bi.baseCreatureID);
  1014. auto upgradedPower = ai->armyManager->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  1015. return upgradedPower - creaturesToUpgrade.power;
  1016. }
  1017. PriorityEvaluator::PriorityEvaluator(const Nullkiller * ai)
  1018. :ai(ai)
  1019. {
  1020. initVisitTile();
  1021. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>(ai));
  1022. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  1023. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>(ai));
  1024. evaluationContextBuilders.push_back(std::make_shared<HeroExchangeEvaluator>());
  1025. evaluationContextBuilders.push_back(std::make_shared<ArmyUpgradeEvaluator>());
  1026. evaluationContextBuilders.push_back(std::make_shared<DefendTownEvaluator>());
  1027. evaluationContextBuilders.push_back(std::make_shared<ExchangeSwapTownHeroesContextBuilder>());
  1028. evaluationContextBuilders.push_back(std::make_shared<DismissHeroContextBuilder>(ai));
  1029. evaluationContextBuilders.push_back(std::make_shared<StayAtTownManaRecoveryEvaluator>());
  1030. evaluationContextBuilders.push_back(std::make_shared<ExplorePointEvaluator>());
  1031. }
  1032. EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  1033. {
  1034. Goals::TGoalVec parts;
  1035. EvaluationContext context(ai);
  1036. if(goal->goalType == Goals::COMPOSITION)
  1037. {
  1038. parts = goal->decompose(ai);
  1039. }
  1040. else
  1041. {
  1042. parts.push_back(goal);
  1043. }
  1044. for(auto subgoal : parts)
  1045. {
  1046. context.goldCost += subgoal->goldCost;
  1047. context.buildingCost += subgoal->buildingCost;
  1048. for(auto builder : evaluationContextBuilders)
  1049. {
  1050. builder->buildEvaluationContext(context, subgoal);
  1051. }
  1052. }
  1053. return context;
  1054. }
  1055. float PriorityEvaluator::evaluate(Goals::TSubgoal task, int priorityTier)
  1056. {
  1057. auto evaluationContext = buildEvaluationContext(task);
  1058. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  1059. + (evaluationContext.armyReward > 0 ? 1 : 0)
  1060. + (evaluationContext.skillReward > 0 ? 1 : 0)
  1061. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  1062. float goldRewardPerTurn = evaluationContext.goldReward / std::log2f(2 + evaluationContext.movementCost * 10);
  1063. double result = 0;
  1064. if (ai->settings->isUseFuzzy())
  1065. {
  1066. float fuzzyResult = 0;
  1067. try
  1068. {
  1069. armyLossPersentageVariable->setValue(evaluationContext.armyLossPersentage);
  1070. heroRoleVariable->setValue(evaluationContext.heroRole);
  1071. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  1072. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  1073. goldRewardVariable->setValue(goldRewardPerTurn);
  1074. armyRewardVariable->setValue(evaluationContext.armyReward);
  1075. armyGrowthVariable->setValue(evaluationContext.armyGrowth);
  1076. skillRewardVariable->setValue(evaluationContext.skillReward);
  1077. dangerVariable->setValue(evaluationContext.danger);
  1078. rewardTypeVariable->setValue(rewardType);
  1079. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  1080. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  1081. goldPressureVariable->setValue(ai->buildAnalyzer->getGoldPressure());
  1082. goldCostVariable->setValue(evaluationContext.goldCost / ((float)ai->getFreeResources()[EGameResID::GOLD] + (float)ai->buildAnalyzer->getDailyIncome()[EGameResID::GOLD] + 1.0f));
  1083. turnVariable->setValue(evaluationContext.turn);
  1084. fearVariable->setValue(evaluationContext.enemyHeroDangerRatio);
  1085. engine->process();
  1086. fuzzyResult = value->getValue();
  1087. }
  1088. catch (fl::Exception& fe)
  1089. {
  1090. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  1091. }
  1092. result = fuzzyResult;
  1093. }
  1094. else
  1095. {
  1096. float score = 0;
  1097. const bool amIInDanger = ai->cb->getTownsInfo().empty() || (evaluationContext.isDefend && evaluationContext.threatTurns == 0);
  1098. const float maxWillingToLose = amIInDanger ? 1 : ai->settings->getMaxArmyLossTarget();
  1099. bool arriveNextWeek = false;
  1100. if (ai->cb->getDate(Date::DAY_OF_WEEK) + evaluationContext.turn > 7 && priorityTier < PriorityTier::FAR_KILL)
  1101. arriveNextWeek = true;
  1102. #if NKAI_TRACE_LEVEL >= 2
  1103. logAi->trace("BEFORE: priorityTier %d, Evaluated %s, loss: %f, turn: %d, turns main: %f, scout: %f, army-involvement: %f, gold: %f, cost: %d, army gain: %f, army growth: %f skill: %f danger: %d, threatTurns: %d, threat: %d, role: %s, strategical value: %f, conquest value: %f cwr: %f, fear: %f, explorePriority: %d isDefend: %d isEnemy: %d arriveNextWeek: %d",
  1104. priorityTier,
  1105. task->toString(),
  1106. evaluationContext.armyLossPersentage,
  1107. (int)evaluationContext.turn,
  1108. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1109. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1110. evaluationContext.armyInvolvement,
  1111. goldRewardPerTurn,
  1112. evaluationContext.goldCost,
  1113. evaluationContext.armyReward,
  1114. evaluationContext.armyGrowth,
  1115. evaluationContext.skillReward,
  1116. evaluationContext.danger,
  1117. evaluationContext.threatTurns,
  1118. evaluationContext.threat,
  1119. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1120. evaluationContext.strategicalValue,
  1121. evaluationContext.conquestValue,
  1122. evaluationContext.closestWayRatio,
  1123. evaluationContext.enemyHeroDangerRatio,
  1124. evaluationContext.explorePriority,
  1125. evaluationContext.isDefend,
  1126. evaluationContext.isEnemy,
  1127. arriveNextWeek);
  1128. #endif
  1129. switch (priorityTier)
  1130. {
  1131. case PriorityTier::INSTAKILL: //Take towns / kill heroes in immediate reach
  1132. {
  1133. if (evaluationContext.turn > 0)
  1134. return 0;
  1135. if (evaluationContext.movementCost >= 1)
  1136. return 0;
  1137. if(evaluationContext.conquestValue > 0)
  1138. score = evaluationContext.armyInvolvement;
  1139. if (vstd::isAlmostZero(score) || (evaluationContext.enemyHeroDangerRatio > 1 && (evaluationContext.turn > 0 || evaluationContext.isExchange) && !ai->cb->getTownsInfo().empty()))
  1140. return 0;
  1141. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1142. return 0;
  1143. if (evaluationContext.movementCost > 0)
  1144. score /= evaluationContext.movementCost;
  1145. break;
  1146. }
  1147. case PriorityTier::INSTADEFEND: //Defend immediately threatened towns
  1148. {
  1149. if (evaluationContext.isDefend && evaluationContext.threatTurns == 0 && evaluationContext.turn == 0)
  1150. score = evaluationContext.armyInvolvement;
  1151. if (evaluationContext.isEnemy && maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1152. return 0;
  1153. break;
  1154. }
  1155. case PriorityTier::KILL: //Take towns / kill heroes that are further away
  1156. //FALL_THROUGH
  1157. case PriorityTier::FAR_KILL:
  1158. {
  1159. if (evaluationContext.turn > 0 && evaluationContext.isHero)
  1160. return 0;
  1161. if (arriveNextWeek && evaluationContext.isEnemy)
  1162. return 0;
  1163. if (evaluationContext.conquestValue > 0)
  1164. score = evaluationContext.armyInvolvement;
  1165. if (vstd::isAlmostZero(score) || (evaluationContext.enemyHeroDangerRatio > 1 && (evaluationContext.turn > 0 || evaluationContext.isExchange) && !ai->cb->getTownsInfo().empty()))
  1166. return 0;
  1167. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1168. return 0;
  1169. score *= evaluationContext.closestWayRatio;
  1170. if (evaluationContext.movementCost > 0)
  1171. score /= evaluationContext.movementCost;
  1172. break;
  1173. }
  1174. case PriorityTier::UPGRADE:
  1175. {
  1176. if (!evaluationContext.isArmyUpgrade)
  1177. return 0;
  1178. if (evaluationContext.enemyHeroDangerRatio > 1)
  1179. return 0;
  1180. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1181. return 0;
  1182. if (vstd::isAlmostZero(evaluationContext.armyLossPersentage) && evaluationContext.closestWayRatio < 1.0)
  1183. return 0;
  1184. score = 1000;
  1185. if (evaluationContext.movementCost > 0)
  1186. score /= evaluationContext.movementCost;
  1187. break;
  1188. }
  1189. case PriorityTier::HIGH_PRIO_EXPLORE:
  1190. {
  1191. if (evaluationContext.enemyHeroDangerRatio > 1)
  1192. return 0;
  1193. if (evaluationContext.explorePriority != 1)
  1194. return 0;
  1195. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1196. return 0;
  1197. if (vstd::isAlmostZero(evaluationContext.armyLossPersentage) && evaluationContext.closestWayRatio < 1.0)
  1198. return 0;
  1199. score = 1000;
  1200. if (evaluationContext.movementCost > 0)
  1201. score /= evaluationContext.movementCost;
  1202. break;
  1203. }
  1204. case PriorityTier::HUNTER_GATHER: //Collect guarded stuff
  1205. //FALL_THROUGH
  1206. case PriorityTier::FAR_HUNTER_GATHER:
  1207. {
  1208. if (evaluationContext.enemyHeroDangerRatio > 1 && !evaluationContext.isDefend)
  1209. return 0;
  1210. if (evaluationContext.buildingCost.marketValue() > 0)
  1211. return 0;
  1212. if (evaluationContext.isDefend && (evaluationContext.enemyHeroDangerRatio < 1 || evaluationContext.threatTurns > 0 || evaluationContext.turn > 0))
  1213. return 0;
  1214. if (evaluationContext.explorePriority == 3)
  1215. return 0;
  1216. if (evaluationContext.isArmyUpgrade)
  1217. return 0;
  1218. if ((evaluationContext.enemyHeroDangerRatio > 0 && arriveNextWeek) || evaluationContext.enemyHeroDangerRatio > 1)
  1219. return 0;
  1220. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1221. return 0;
  1222. if (vstd::isAlmostZero(evaluationContext.armyLossPersentage) && evaluationContext.closestWayRatio < 1.0)
  1223. return 0;
  1224. score += evaluationContext.strategicalValue * 1000;
  1225. score += evaluationContext.goldReward;
  1226. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossPersentage) * 0.05;
  1227. score += evaluationContext.armyReward;
  1228. score += evaluationContext.armyGrowth;
  1229. score -= evaluationContext.goldCost;
  1230. score -= evaluationContext.armyInvolvement * evaluationContext.armyLossPersentage;
  1231. if (score > 0)
  1232. {
  1233. score = 1000;
  1234. if (evaluationContext.movementCost > 0)
  1235. score /= evaluationContext.movementCost;
  1236. }
  1237. break;
  1238. }
  1239. case PriorityTier::LOW_PRIO_EXPLORE:
  1240. {
  1241. if (evaluationContext.enemyHeroDangerRatio > 1)
  1242. return 0;
  1243. if (evaluationContext.explorePriority != 3)
  1244. return 0;
  1245. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1246. return 0;
  1247. if (evaluationContext.closestWayRatio < 1.0)
  1248. return 0;
  1249. score = 1000;
  1250. if (evaluationContext.movementCost > 0)
  1251. score /= evaluationContext.movementCost;
  1252. break;
  1253. }
  1254. case PriorityTier::DEFEND: //Defend whatever if nothing else is to do
  1255. {
  1256. if (evaluationContext.enemyHeroDangerRatio > 1 && evaluationContext.isExchange)
  1257. return 0;
  1258. if (evaluationContext.isDefend || evaluationContext.isArmyUpgrade)
  1259. score = evaluationContext.armyInvolvement;
  1260. score /= (evaluationContext.turn + 1);
  1261. break;
  1262. }
  1263. case PriorityTier::BUILDINGS: //For buildings and buying army
  1264. {
  1265. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1266. return 0;
  1267. //If we already have locked resources, we don't look at other buildings
  1268. if (ai->getLockedResources().marketValue() > 0)
  1269. return 0;
  1270. score += evaluationContext.conquestValue * 1000;
  1271. score += evaluationContext.strategicalValue * 1000;
  1272. score += evaluationContext.goldReward;
  1273. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossPersentage) * 0.05;
  1274. score += evaluationContext.armyReward;
  1275. score += evaluationContext.armyGrowth;
  1276. if (evaluationContext.buildingCost.marketValue() > 0)
  1277. {
  1278. if (!evaluationContext.isTradeBuilding && ai->getFreeResources()[EGameResID::WOOD] - evaluationContext.buildingCost[EGameResID::WOOD] < 5 && ai->buildAnalyzer->getDailyIncome()[EGameResID::WOOD] < 1)
  1279. {
  1280. logAi->trace("Should make sure to build market-place instead of %s", task->toString());
  1281. for (auto town : ai->cb->getTownsInfo())
  1282. {
  1283. if (!town->hasBuiltSomeTradeBuilding())
  1284. return 0;
  1285. }
  1286. }
  1287. score += 1000;
  1288. auto resourcesAvailable = evaluationContext.evaluator.ai->getFreeResources();
  1289. auto income = ai->buildAnalyzer->getDailyIncome();
  1290. if(ai->buildAnalyzer->isGoldPressureHigh())
  1291. score /= evaluationContext.buildingCost.marketValue();
  1292. if (!resourcesAvailable.canAfford(evaluationContext.buildingCost))
  1293. {
  1294. TResources needed = evaluationContext.buildingCost - resourcesAvailable;
  1295. needed.positive();
  1296. int turnsTo = needed.maxPurchasableCount(income);
  1297. if (turnsTo == INT_MAX)
  1298. return 0;
  1299. else
  1300. score /= turnsTo;
  1301. }
  1302. }
  1303. else
  1304. {
  1305. if (evaluationContext.enemyHeroDangerRatio > 1 && !evaluationContext.isDefend && vstd::isAlmostZero(evaluationContext.conquestValue))
  1306. return 0;
  1307. }
  1308. break;
  1309. }
  1310. }
  1311. result = score;
  1312. //TODO: Figure out the root cause for why evaluationContext.closestWayRatio has become -nan(ind).
  1313. if (std::isnan(result))
  1314. return 0;
  1315. }
  1316. #if NKAI_TRACE_LEVEL >= 2
  1317. logAi->trace("priorityTier %d, Evaluated %s, loss: %f, turn: %d, turns main: %f, scout: %f, army-involvement: %f, gold: %f, cost: %d, army gain: %f, army growth: %f skill: %f danger: %d, threatTurns: %d, threat: %d, role: %s, strategical value: %f, conquest value: %f cwr: %f, fear: %f, result %f",
  1318. priorityTier,
  1319. task->toString(),
  1320. evaluationContext.armyLossPersentage,
  1321. (int)evaluationContext.turn,
  1322. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1323. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1324. evaluationContext.armyInvolvement,
  1325. goldRewardPerTurn,
  1326. evaluationContext.goldCost,
  1327. evaluationContext.armyReward,
  1328. evaluationContext.armyGrowth,
  1329. evaluationContext.skillReward,
  1330. evaluationContext.danger,
  1331. evaluationContext.threatTurns,
  1332. evaluationContext.threat,
  1333. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1334. evaluationContext.strategicalValue,
  1335. evaluationContext.conquestValue,
  1336. evaluationContext.closestWayRatio,
  1337. evaluationContext.enemyHeroDangerRatio,
  1338. result);
  1339. #endif
  1340. return result;
  1341. }
  1342. }