2
0

PriorityEvaluator.cpp 57 KB

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