PriorityEvaluator.cpp 50 KB

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