PriorityEvaluator.cpp 48 KB

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