PriorityEvaluator.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  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* aiNk)
  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(aiNk),
  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. /// @return between 0-1.0f
  320. float RewardEvaluator::getNowResourceRequirementStrength(GameResID resType) const
  321. {
  322. TResources requiredResources = aiNk->buildAnalyzer->getResourcesRequiredNow();
  323. TResources dailyIncome = aiNk->buildAnalyzer->getDailyIncome();
  324. if(requiredResources[resType] == 0)
  325. return 0;
  326. if(dailyIncome[resType] == 0)
  327. return 1.0f;
  328. return 0.8f;
  329. }
  330. /// @return between 0-1.0f
  331. float RewardEvaluator::getTotalResourceRequirementStrength(GameResID resType) const
  332. {
  333. TResources requiredResources = aiNk->buildAnalyzer->getTotalResourcesRequired();
  334. TResources dailyIncome = aiNk->buildAnalyzer->getDailyIncome();
  335. if(requiredResources[resType] == 0)
  336. return 0;
  337. if(dailyIncome[resType] == 0)
  338. return 1.0f;
  339. return 0.8f;
  340. }
  341. uint64_t RewardEvaluator::townArmyGrowth(const CGTownInstance * town) const
  342. {
  343. uint64_t result = 0;
  344. for(auto creatureInfo : town->creatures)
  345. {
  346. if(creatureInfo.second.empty())
  347. continue;
  348. auto creature = creatureInfo.second.back().toCreature();
  349. result += creature->getAIValue() * town->getGrowthInfo(creature->getLevel() - 1).totalGrowth();
  350. }
  351. return result;
  352. }
  353. float RewardEvaluator::getManaRecoveryArmyReward(const CGHeroInstance * hero) const
  354. {
  355. return aiNk->heroManager->getMagicStrength(hero) * 10000 * (1.0f - std::sqrt(static_cast<float>(hero->mana) / hero->manaLimit()));
  356. }
  357. /// @return between 0-1.0f
  358. float RewardEvaluator::getCombinedResourceRequirementStrength(const TResources & res) const
  359. {
  360. float sum = 0.0f;
  361. for(TResources::nziterator it(res); it.valid(); it++)
  362. {
  363. auto calculation = 0.5f * getNowResourceRequirementStrength(it->resType)
  364. + 0.5f * getTotalResourceRequirementStrength(it->resType);
  365. // Even not required resources should be valuable because they shouldn't be left for the enemies to collect
  366. sum += std::min(MINIMUM_STRATEGICAL_VALUE_NON_TOWN, calculation);
  367. }
  368. return sum;
  369. }
  370. float RewardEvaluator::getStrategicalValue(const CGObjectInstance * target, const CGHeroInstance * hero) const
  371. {
  372. if(!target)
  373. return 0;
  374. switch(target->ID)
  375. {
  376. case Obj::MINE:
  377. {
  378. auto mine = dynamic_cast<const CGMine *>(target);
  379. TResources res;
  380. res[mine->producedResource] = mine->producedQuantity;
  381. // Mines should have higher priority than resources
  382. return 1.0f + getCombinedResourceRequirementStrength(res);
  383. }
  384. case Obj::RESOURCE:
  385. {
  386. auto resource = dynamic_cast<const CGResource *>(target);
  387. TResources res;
  388. res[resource->resourceID()] = resource->getAmount();
  389. return getCombinedResourceRequirementStrength(res);
  390. }
  391. case Obj::TOWN:
  392. {
  393. if(aiNk->buildAnalyzer->getDevelopmentInfo().empty())
  394. return 10.0f;
  395. auto town = dynamic_cast<const CGTownInstance *>(target);
  396. if(town->getOwner() == aiNk->playerID)
  397. {
  398. auto armyIncome = townArmyGrowth(town);
  399. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  400. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  401. }
  402. auto fortLevel = town->fortLevel();
  403. auto booster = isAnotherAi(town, *aiNk->cc) ? 0.4f : 1.0f;
  404. if(town->hasCapitol())
  405. return booster * 1.5;
  406. if(fortLevel < CGTownInstance::CITADEL)
  407. return booster * (town->hasFort() ? 1.0 : 0.8);
  408. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  409. }
  410. case Obj::HERO:
  411. return aiNk->cc->getPlayerRelations(target->tempOwner, aiNk->playerID) == PlayerRelations::ENEMIES
  412. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  413. : 0;
  414. case Obj::KEYMASTER:
  415. return 0.6f;
  416. default:
  417. break;
  418. }
  419. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  420. if(rewardable && hero)
  421. {
  422. auto resourceReward = 0.0f;
  423. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  424. {
  425. resourceReward += getCombinedResourceRequirementStrength(rewardable->configuration.info[index].reward.resources);
  426. }
  427. return resourceReward;
  428. }
  429. return 0;
  430. }
  431. float RewardEvaluator::getConquestValue(const CGObjectInstance* target) const
  432. {
  433. if (!target)
  434. return 0;
  435. if (target->getOwner() == aiNk->playerID)
  436. return 0;
  437. switch (target->ID)
  438. {
  439. case Obj::TOWN:
  440. {
  441. if (aiNk->buildAnalyzer->getDevelopmentInfo().empty())
  442. return 10.0f;
  443. auto town = dynamic_cast<const CGTownInstance*>(target);
  444. if (town->getOwner() == aiNk->playerID)
  445. {
  446. auto armyIncome = townArmyGrowth(town);
  447. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  448. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  449. }
  450. auto fortLevel = town->fortLevel();
  451. auto booster = 1.0f;
  452. if (town->hasCapitol())
  453. return booster * 1.5;
  454. if (fortLevel < CGTownInstance::CITADEL)
  455. return booster * (town->hasFort() ? 1.0 : 0.8);
  456. else
  457. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  458. }
  459. case Obj::HERO:
  460. return aiNk->cc->getPlayerRelations(target->tempOwner, aiNk->playerID) == PlayerRelations::ENEMIES
  461. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance*>(target))
  462. : 0;
  463. default:
  464. return 0;
  465. }
  466. }
  467. float RewardEvaluator::evaluateWitchHutSkillScore(const CGObjectInstance * hut, const CGHeroInstance * hero, HeroRole role) const
  468. {
  469. auto rewardable = dynamic_cast<const CRewardableObject *>(hut);
  470. assert(rewardable);
  471. auto skill = SecondarySkill(*rewardable->configuration.getVariable("secondarySkill", "gainedSkill"));
  472. if(!hut->wasVisited(hero->tempOwner))
  473. return role == HeroRole::SCOUT ? 2 : 0;
  474. if(hero->getSecSkillLevel(skill) != MasteryLevel::NONE
  475. || static_cast<int>(hero->secSkills.size()) >= ccTl->getSettings().getInteger(EGameSettings::HEROES_SKILL_PER_HERO))
  476. return 0;
  477. auto score = aiNk->heroManager->evaluateSecSkill(skill, hero);
  478. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  479. }
  480. float RewardEvaluator::getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role) const
  481. {
  482. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  483. if(!target)
  484. return 0;
  485. switch(target->ID)
  486. {
  487. case Obj::STAR_AXIS:
  488. case Obj::SCHOLAR:
  489. case Obj::SCHOOL_OF_MAGIC:
  490. case Obj::SCHOOL_OF_WAR:
  491. case Obj::GARDEN_OF_REVELATION:
  492. case Obj::MARLETTO_TOWER:
  493. case Obj::MERCENARY_CAMP:
  494. case Obj::TREE_OF_KNOWLEDGE:
  495. return 1;
  496. case Obj::LEARNING_STONE:
  497. return 1.0f / std::sqrt(hero->level);
  498. case Obj::ARENA:
  499. return 2;
  500. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  501. return 0.25f;
  502. case Obj::SHRINE_OF_MAGIC_GESTURE:
  503. return 1.0f;
  504. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  505. return 2.0f;
  506. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  507. return 8;
  508. case Obj::WITCH_HUT:
  509. return evaluateWitchHutSkillScore(target, hero, role);
  510. case Obj::PANDORAS_BOX:
  511. //Can contains experience, spells, or skills (only on custom maps)
  512. return 2.5f;
  513. case Obj::HERO:
  514. return aiNk->cc->getPlayerRelations(target->tempOwner, aiNk->playerID) == PlayerRelations::ENEMIES
  515. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  516. : 0;
  517. default:
  518. break;
  519. }
  520. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  521. if(rewardable)
  522. {
  523. auto totalValue = 0.0f;
  524. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  525. {
  526. auto & info = rewardable->configuration.info[index];
  527. auto rewardValue = 0.0f;
  528. if(!info.reward.spells.empty())
  529. {
  530. for(auto spellID : info.reward.spells)
  531. {
  532. const spells::Spell * spell = LIBRARY->spells()->getById(spellID);
  533. if(hero->canLearnSpell(spell) && !hero->spellbookContainsSpell(spellID))
  534. {
  535. rewardValue += std::sqrt(spell->getLevel()) / 4.0f;
  536. }
  537. }
  538. totalValue += rewardValue / info.reward.spells.size();
  539. }
  540. if(!info.reward.primary.empty())
  541. {
  542. for(auto value : info.reward.primary)
  543. {
  544. totalValue += value;
  545. }
  546. }
  547. }
  548. return totalValue;
  549. }
  550. return 0;
  551. }
  552. const HitMapInfo & RewardEvaluator::getEnemyHeroDanger(const int3 & tile, uint8_t turn) const
  553. {
  554. auto & threatNode = aiNk->dangerHitMap->getTileThreat(tile);
  555. if(threatNode.maximumDanger.danger == 0)
  556. return HitMapInfo::NoThreat;
  557. if(threatNode.maximumDanger.turn <= turn)
  558. return threatNode.maximumDanger;
  559. return threatNode.fastestDanger.turn <= turn ? threatNode.fastestDanger : HitMapInfo::NoThreat;
  560. }
  561. int32_t getArmyCost(const CArmedInstance * army)
  562. {
  563. int32_t value = 0;
  564. for(const auto & stack : army->Slots())
  565. {
  566. value += stack.second->getCreatureID().toCreature()->getFullRecruitCost().marketValue() * stack.second->getCount();
  567. }
  568. return value;
  569. }
  570. int32_t RewardEvaluator::getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero) const
  571. {
  572. if(!target)
  573. return 0;
  574. auto relations = aiNk->cc->getPlayerRelations(target->tempOwner, hero->tempOwner);
  575. const int dailyIncomeMultiplier = 5;
  576. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  577. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  578. switch(target->ID)
  579. {
  580. case Obj::RESOURCE:
  581. {
  582. auto * res = dynamic_cast<const CGResource*>(target);
  583. return res && res->resourceID() == GameResID::GOLD ? 600 : 100;
  584. }
  585. case Obj::TREASURE_CHEST:
  586. return 1500;
  587. case Obj::WATER_WHEEL:
  588. return 1000;
  589. case Obj::TOWN:
  590. return dailyIncomeMultiplier * estimateTownIncome(aiNk->cc.get(), target, hero);
  591. case Obj::MINE:
  592. case Obj::ABANDONED_MINE:
  593. {
  594. auto * mine = dynamic_cast<const CGMine*>(target);
  595. return dailyIncomeMultiplier * (mine->producedResource == GameResID::GOLD ? 1000 : 75);
  596. }
  597. case Obj::PANDORAS_BOX:
  598. return 2500;
  599. case Obj::PRISON:
  600. //Objectively saves us 2500 to hire hero
  601. return GameConstants::HERO_GOLD_COST;
  602. case Obj::HERO:
  603. return relations == PlayerRelations::ENEMIES
  604. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  605. : 0;
  606. default:
  607. break;
  608. }
  609. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  610. if(rewardable)
  611. {
  612. auto goldReward = 0;
  613. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  614. {
  615. auto & info = rewardable->configuration.info[index];
  616. goldReward += getResourcesGoldReward(info.reward.resources);
  617. }
  618. return goldReward;
  619. }
  620. return 0;
  621. }
  622. class HeroExchangeEvaluator : public IEvaluationContextBuilder
  623. {
  624. public:
  625. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  626. {
  627. if(task->goalType != Goals::HERO_EXCHANGE)
  628. return;
  629. Goals::HeroExchange & heroExchange = dynamic_cast<Goals::HeroExchange &>(*task);
  630. uint64_t armyStrength = heroExchange.getReinforcementArmyStrength(evaluationContext.evaluator.aiNk);
  631. evaluationContext.addNonCriticalStrategicalValue(2.0f * armyStrength / (float)heroExchange.hero->getArmyStrength());
  632. evaluationContext.conquestValue += 2.0f * armyStrength / (float)heroExchange.hero->getArmyStrength();
  633. evaluationContext.heroRole = evaluationContext.evaluator.aiNk->heroManager->getHeroRole(HeroPtr(heroExchange.hero));
  634. evaluationContext.isExchange = true;
  635. }
  636. };
  637. class ArmyUpgradeEvaluator : public IEvaluationContextBuilder
  638. {
  639. public:
  640. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  641. {
  642. if(task->goalType != Goals::ARMY_UPGRADE)
  643. return;
  644. Goals::ArmyUpgrade & armyUpgrade = dynamic_cast<Goals::ArmyUpgrade &>(*task);
  645. uint64_t upgradeValue = armyUpgrade.getUpgradeValue();
  646. evaluationContext.armyReward += upgradeValue;
  647. evaluationContext.addNonCriticalStrategicalValue(upgradeValue / (float)armyUpgrade.hero->getArmyStrength());
  648. evaluationContext.isArmyUpgrade = true;
  649. }
  650. };
  651. class ExplorePointEvaluator : public IEvaluationContextBuilder
  652. {
  653. public:
  654. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  655. {
  656. if(task->goalType != Goals::EXPLORATION_POINT)
  657. return;
  658. int tilesDiscovered = task->value;
  659. evaluationContext.addNonCriticalStrategicalValue(0.03f * tilesDiscovered);
  660. for (auto obj : evaluationContext.evaluator.aiNk->cc->getVisitableObjs(task->tile))
  661. {
  662. switch (obj->ID.num)
  663. {
  664. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  665. case Obj::MONOLITH_TWO_WAY:
  666. case Obj::SUBTERRANEAN_GATE:
  667. evaluationContext.explorePriority = 1;
  668. break;
  669. case Obj::REDWOOD_OBSERVATORY:
  670. case Obj::PILLAR_OF_FIRE:
  671. evaluationContext.explorePriority = 2;
  672. break;
  673. }
  674. }
  675. if(evaluationContext.evaluator.aiNk->cc->getTile(task->tile)->roadType != RoadId::NO_ROAD)
  676. evaluationContext.explorePriority = 1;
  677. if (evaluationContext.explorePriority == 0)
  678. evaluationContext.explorePriority = 3;
  679. }
  680. };
  681. class StayAtTownManaRecoveryEvaluator : public IEvaluationContextBuilder
  682. {
  683. public:
  684. void buildEvaluationContext(EvaluationContext& evaluationContext, Goals::TSubgoal task) const override
  685. {
  686. if (task->goalType != Goals::STAY_AT_TOWN)
  687. return;
  688. Goals::StayAtTown& stayAtTown = dynamic_cast<Goals::StayAtTown&>(*task);
  689. if (stayAtTown.getHero() != nullptr && stayAtTown.getHero()->movementPointsRemaining() < 100)
  690. {
  691. return;
  692. }
  693. if(stayAtTown.town->mageGuildLevel() > 0)
  694. evaluationContext.armyReward += evaluationContext.evaluator.getManaRecoveryArmyReward(stayAtTown.getHero());
  695. if (vstd::isAlmostZero(evaluationContext.armyReward))
  696. evaluationContext.isDefend = true;
  697. else
  698. {
  699. evaluationContext.movementCost += stayAtTown.getMovementWasted();
  700. evaluationContext.movementCostByRole[evaluationContext.heroRole] += stayAtTown.getMovementWasted();
  701. }
  702. }
  703. };
  704. void addTileDanger(EvaluationContext & evaluationContext, const int3 & tile, uint8_t turn, uint64_t ourStrength)
  705. {
  706. HitMapInfo enemyDanger = evaluationContext.evaluator.getEnemyHeroDanger(tile, turn);
  707. if(enemyDanger.danger)
  708. {
  709. auto dangerRatio = enemyDanger.danger / (double)ourStrength;
  710. vstd::amax(evaluationContext.enemyHeroDangerRatio, dangerRatio);
  711. vstd::amax(evaluationContext.threat, enemyDanger.threat);
  712. }
  713. }
  714. class DefendTownEvaluator : public IEvaluationContextBuilder
  715. {
  716. public:
  717. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  718. {
  719. if(task->goalType != Goals::DEFEND_TOWN)
  720. return;
  721. Goals::DefendTown & defendTown = dynamic_cast<Goals::DefendTown &>(*task);
  722. const CGTownInstance * town = defendTown.town;
  723. auto & threat = defendTown.getThreat();
  724. auto strategicalValue = evaluationContext.evaluator.getStrategicalValue(town);
  725. float multiplier = 1;
  726. if(threat.turn < defendTown.getTurn())
  727. multiplier /= 1 + (defendTown.getTurn() - threat.turn);
  728. multiplier /= 1.0f + threat.turn / 5.0f;
  729. if(defendTown.getTurn() > 0 && defendTown.isCounterAttack())
  730. {
  731. auto ourSpeed = defendTown.hero->movementPointsLimit(true);
  732. auto enemySpeed = threat.heroPtr.get(evaluationContext.evaluator.aiNk->cc.get())->movementPointsLimit(true);
  733. if(enemySpeed > ourSpeed) multiplier *= 0.7f;
  734. }
  735. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  736. auto armyGrowth = evaluationContext.evaluator.townArmyGrowth(town);
  737. evaluationContext.armyGrowth += armyGrowth * multiplier;
  738. evaluationContext.goldReward += dailyIncome * 5 * multiplier;
  739. if(evaluationContext.evaluator.aiNk->buildAnalyzer->getDevelopmentInfo().size() == 1)
  740. vstd::amax(evaluationContext.strategicalValue, 2.5f * multiplier * strategicalValue);
  741. else
  742. evaluationContext.addNonCriticalStrategicalValue(1.7f * multiplier * strategicalValue);
  743. evaluationContext.defenseValue = town->fortLevel();
  744. evaluationContext.isDefend = true;
  745. evaluationContext.threatTurns = threat.turn;
  746. vstd::amax(evaluationContext.danger, defendTown.getThreat().danger);
  747. addTileDanger(evaluationContext, town->visitablePos(), defendTown.getTurn(), defendTown.getDefenceStrength());
  748. }
  749. };
  750. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  751. {
  752. private:
  753. const Nullkiller * aiNk;
  754. public:
  755. ExecuteHeroChainEvaluationContextBuilder(const Nullkiller * aiNk) : aiNk(aiNk) {}
  756. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  757. {
  758. if(task->goalType != Goals::EXECUTE_HERO_CHAIN)
  759. return;
  760. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  761. const AIPath & path = chain.getPath();
  762. if (vstd::isAlmostZero(path.movementCost()))
  763. return;
  764. vstd::amax(evaluationContext.danger, path.getTotalDanger());
  765. evaluationContext.movementCost += path.movementCost();
  766. evaluationContext.closestWayRatio = chain.closestWayRatio;
  767. std::map<const CGHeroInstance *, float> costsPerHero;
  768. for(auto & node : path.nodes)
  769. {
  770. vstd::amax(costsPerHero[node.targetHero], node.cost);
  771. if (node.layer == EPathfindingLayer::SAIL)
  772. evaluationContext.involvesSailing = true;
  773. }
  774. float highestCostForSingleHero = 0;
  775. for(auto pair : costsPerHero)
  776. {
  777. auto role = evaluationContext.evaluator.aiNk->heroManager->getHeroRole(HeroPtr(pair.first));
  778. evaluationContext.movementCostByRole[role] += pair.second;
  779. if (pair.second > highestCostForSingleHero)
  780. highestCostForSingleHero = pair.second;
  781. }
  782. if (highestCostForSingleHero > 1 && costsPerHero.size() > 1)
  783. {
  784. //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.
  785. return;
  786. }
  787. evaluationContext.movementCost *= costsPerHero.size(); //further deincentivise chaining as it often involves bringing back the army afterwards
  788. auto hero = task->hero;
  789. bool checkGold = evaluationContext.danger == 0;
  790. auto army = path.heroArmy;
  791. const CGObjectInstance * target = aiNk->cc->getObj((ObjectInstanceID)task->objid, false);
  792. auto heroRole = evaluationContext.evaluator.aiNk->heroManager->getHeroRole(HeroPtr(hero));
  793. if(heroRole == HeroRole::MAIN)
  794. evaluationContext.heroRole = heroRole;
  795. // Assuming Slots() returns a collection of slots with slot.second->getCreatureID() and slot.second->getPower()
  796. float heroPower = 0;
  797. float totalPower = 0;
  798. // Map to store the aggregated power of creatures by CreatureID
  799. std::map<CreatureID, float> totalPowerByCreatureID;
  800. // Calculate hero power and total power by CreatureID
  801. for (const auto & slot : hero->Slots())
  802. {
  803. CreatureID creatureID = slot.second->getCreatureID();
  804. float slotPower = slot.second->getPower();
  805. // Add the power of this slot to the heroPower
  806. heroPower += slotPower;
  807. // Accumulate the total power for the specific CreatureID
  808. if (totalPowerByCreatureID.find(creatureID) == totalPowerByCreatureID.end())
  809. {
  810. // First time encountering this CreatureID, retrieve total creatures' power
  811. totalPowerByCreatureID[creatureID] = aiNk->armyManager->getTotalCreaturesAvailable(creatureID).power;
  812. }
  813. }
  814. // Calculate total power based on unique CreatureIDs
  815. for (const auto& entry : totalPowerByCreatureID)
  816. {
  817. totalPower += entry.second;
  818. }
  819. // Compute the power ratio if total power is greater than zero
  820. if (totalPower > 0)
  821. {
  822. evaluationContext.powerRatio = heroPower / totalPower;
  823. }
  824. if (target)
  825. {
  826. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero);
  827. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold);
  828. evaluationContext.armyGrowth += evaluationContext.evaluator.getArmyGrowth(target, hero, army);
  829. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, heroRole);
  830. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target));
  831. evaluationContext.conquestValue += evaluationContext.evaluator.getConquestValue(target);
  832. if (target->ID == Obj::HERO)
  833. evaluationContext.isHero = true;
  834. if (target->getOwner().isValidPlayer() && aiNk->cc->getPlayerRelations(aiNk->playerID, target->getOwner()) == PlayerRelations::ENEMIES)
  835. evaluationContext.isEnemy = true;
  836. if (target->ID == Obj::TOWN)
  837. evaluationContext.defenseValue = dynamic_cast<const CGTownInstance*>(target)->fortLevel();
  838. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army);
  839. if(evaluationContext.danger > 0)
  840. evaluationContext.skillReward += (float)evaluationContext.danger / (float)hero->getArmyStrength();
  841. }
  842. evaluationContext.armyInvolvement += army->getArmyCost();
  843. vstd::amax(evaluationContext.armyLossRatio, (float)path.getTotalArmyLoss() / (float)army->getArmyStrength());
  844. addTileDanger(evaluationContext, path.targetTile(), path.turn(), path.getHeroStrength());
  845. vstd::amax(evaluationContext.turn, path.turn());
  846. }
  847. };
  848. class ClusterEvaluationContextBuilder : public IEvaluationContextBuilder
  849. {
  850. public:
  851. ClusterEvaluationContextBuilder(const Nullkiller * aiNk) {}
  852. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  853. {
  854. if(task->goalType != Goals::UNLOCK_CLUSTER)
  855. return;
  856. Goals::UnlockCluster & clusterGoal = dynamic_cast<Goals::UnlockCluster &>(*task);
  857. std::shared_ptr<ObjectCluster> cluster = clusterGoal.getCluster();
  858. auto hero = clusterGoal.hero;
  859. auto role = evaluationContext.evaluator.aiNk->heroManager->getHeroRole(HeroPtr(hero));
  860. std::vector<std::pair<ObjectInstanceID, ClusterObjectInfo>> objects(cluster->objects.begin(), cluster->objects.end());
  861. std::sort(objects.begin(), objects.end(), [](std::pair<ObjectInstanceID, ClusterObjectInfo> o1, std::pair<ObjectInstanceID, ClusterObjectInfo> o2) -> bool
  862. {
  863. return o1.second.priority > o2.second.priority;
  864. });
  865. int boost = 1;
  866. for(auto & objInfo : objects)
  867. {
  868. auto target = evaluationContext.evaluator.aiNk->cc->getObj(objInfo.first);
  869. bool checkGold = objInfo.second.danger == 0;
  870. auto army = hero;
  871. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero) / boost;
  872. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold) / boost;
  873. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, role) / boost;
  874. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target) / boost);
  875. evaluationContext.conquestValue += evaluationContext.evaluator.getConquestValue(target);
  876. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army) / boost;
  877. evaluationContext.movementCostByRole[role] += objInfo.second.movementCost / boost;
  878. evaluationContext.movementCost += objInfo.second.movementCost / boost;
  879. vstd::amax(evaluationContext.turn, objInfo.second.turn / boost);
  880. boost <<= 1;
  881. if(boost > 8)
  882. break;
  883. }
  884. }
  885. };
  886. class ExchangeSwapTownHeroesContextBuilder : public IEvaluationContextBuilder
  887. {
  888. public:
  889. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  890. {
  891. if(task->goalType != Goals::EXCHANGE_SWAP_TOWN_HEROES)
  892. return;
  893. Goals::ExchangeSwapTownHeroes & swapCommand = dynamic_cast<Goals::ExchangeSwapTownHeroes &>(*task);
  894. const CGHeroInstance * garrisonHero = swapCommand.getGarrisonHero();
  895. logAi->trace("buildEvaluationContext ExchangeSwapTownHeroesContextBuilder %s affected objects: %d", swapCommand.toString(), swapCommand.getAffectedObjects().size());
  896. for (auto obj : swapCommand.getAffectedObjects())
  897. {
  898. logAi->trace("affected object: %s", evaluationContext.evaluator.aiNk->cc->getObj(obj)->getObjectName());
  899. }
  900. if (garrisonHero)
  901. logAi->debug("with %s and %d", garrisonHero->getNameTranslated(), int(swapCommand.getLockingReason()));
  902. if(garrisonHero && swapCommand.getLockingReason() == HeroLockedReason::DEFENCE)
  903. {
  904. auto defenderRole = evaluationContext.evaluator.aiNk->heroManager->getHeroRole(HeroPtr(garrisonHero));
  905. auto mpLeft = garrisonHero->movementPointsRemaining() / (float)garrisonHero->movementPointsLimit(true);
  906. evaluationContext.movementCost += mpLeft;
  907. evaluationContext.movementCostByRole[defenderRole] += mpLeft;
  908. evaluationContext.heroRole = defenderRole;
  909. evaluationContext.isDefend = true;
  910. evaluationContext.armyInvolvement = garrisonHero->getArmyStrength();
  911. logAi->debug("evaluationContext.isDefend: %d", evaluationContext.isDefend);
  912. }
  913. }
  914. };
  915. class DismissHeroContextBuilder : public IEvaluationContextBuilder
  916. {
  917. private:
  918. const Nullkiller * aiNk;
  919. public:
  920. DismissHeroContextBuilder(const Nullkiller * aiNk) : aiNk(aiNk) {}
  921. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  922. {
  923. if(task->goalType != Goals::DISMISS_HERO)
  924. return;
  925. Goals::DismissHero & dismissCommand = dynamic_cast<Goals::DismissHero &>(*task);
  926. const CGHeroInstance * dismissedHero = dismissCommand.getHero();
  927. auto role = aiNk->heroManager->getHeroRole(HeroPtr(dismissedHero));
  928. auto mpLeft = dismissedHero->movementPointsRemaining();
  929. evaluationContext.movementCost += mpLeft;
  930. evaluationContext.movementCostByRole[role] += mpLeft;
  931. evaluationContext.goldCost += GameConstants::HERO_GOLD_COST + getArmyCost(dismissedHero);
  932. }
  933. };
  934. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  935. {
  936. public:
  937. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  938. {
  939. if(task->goalType != Goals::BUILD_STRUCTURE)
  940. return;
  941. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  942. auto & bi = buildThis.buildingInfo;
  943. evaluationContext.goldReward += 7 * bi.dailyIncome.marketValue() / 2; // 7 day income but half we already have
  944. evaluationContext.heroRole = HeroRole::MAIN;
  945. evaluationContext.movementCostByRole[evaluationContext.heroRole] += bi.prerequisitesCount;
  946. int32_t cost = bi.buildCost[EGameResID::GOLD];
  947. evaluationContext.goldCost += cost;
  948. evaluationContext.closestWayRatio = 1;
  949. evaluationContext.buildingCost += bi.buildCostWithPrerequisites;
  950. bool alreadyOwn = false;
  951. int highestMageGuildPossible = BuildingID::MAGES_GUILD_3;
  952. for (auto town : evaluationContext.evaluator.aiNk->cc->getTownsInfo())
  953. {
  954. if (town->hasBuilt(bi.id))
  955. alreadyOwn = true;
  956. if (evaluationContext.evaluator.aiNk->cc->canBuildStructure(town, BuildingID::MAGES_GUILD_5) != EBuildingState::FORBIDDEN)
  957. highestMageGuildPossible = BuildingID::MAGES_GUILD_5;
  958. else if (evaluationContext.evaluator.aiNk->cc->canBuildStructure(town, BuildingID::MAGES_GUILD_4) != EBuildingState::FORBIDDEN)
  959. highestMageGuildPossible = BuildingID::MAGES_GUILD_4;
  960. }
  961. if (bi.id == BuildingID::MARKETPLACE || bi.dailyIncome[EGameResID::WOOD] > 0)
  962. evaluationContext.isTradeBuilding = true;
  963. #if NK2AI_TRACE_LEVEL >= 1
  964. logAi->trace("Building costs for %s : %s MarketValue: %d",bi.toString(), evaluationContext.buildingCost.toString(), evaluationContext.buildingCost.marketValue());
  965. #endif
  966. if(bi.creatureID != CreatureID::NONE)
  967. {
  968. evaluationContext.addNonCriticalStrategicalValue(buildThis.townInfo.armyStrength / 50000.0);
  969. if(bi.baseCreatureID == bi.creatureID)
  970. {
  971. evaluationContext.addNonCriticalStrategicalValue((0.5f + 0.1f * bi.creatureLevel) / (float)bi.prerequisitesCount);
  972. evaluationContext.armyReward += bi.armyStrength * 1.5;
  973. }
  974. else
  975. {
  976. auto potentialUpgradeValue = evaluationContext.evaluator.getUpgradeArmyReward(buildThis.town, bi);
  977. evaluationContext.addNonCriticalStrategicalValue(potentialUpgradeValue / 10000.0f / (float)bi.prerequisitesCount);
  978. if(bi.id.isDwelling())
  979. evaluationContext.armyReward += bi.armyStrength - evaluationContext.evaluator.aiNk->armyManager->evaluateStackPower(bi.baseCreatureID.toCreature(), bi.creatureGrowth);
  980. else //This is for prerequisite-buildings
  981. evaluationContext.armyReward += evaluationContext.evaluator.aiNk->armyManager->evaluateStackPower(bi.baseCreatureID.toCreature(), bi.creatureGrowth);
  982. if(alreadyOwn)
  983. evaluationContext.armyReward /= bi.buildCostWithPrerequisites.marketValue();
  984. }
  985. }
  986. else if(bi.id == BuildingID::CITADEL || bi.id == BuildingID::CASTLE)
  987. {
  988. evaluationContext.addNonCriticalStrategicalValue(buildThis.town->creatures.size() * 0.2f);
  989. evaluationContext.armyReward += buildThis.townInfo.armyStrength / 2;
  990. }
  991. else if(bi.id >= BuildingID::MAGES_GUILD_1 && bi.id <= BuildingID::MAGES_GUILD_5)
  992. {
  993. evaluationContext.skillReward += 2 * bi.id.getMagesGuildLevel();
  994. if (!alreadyOwn && evaluationContext.evaluator.aiNk->cc->canBuildStructure(buildThis.town, highestMageGuildPossible) != EBuildingState::FORBIDDEN)
  995. {
  996. for (auto hero : evaluationContext.evaluator.aiNk->cc->getHeroesInfo())
  997. {
  998. if(hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + hero->getPrimSkillLevel(PrimarySkill::KNOWLEDGE) > hero->getPrimSkillLevel(PrimarySkill::ATTACK) + hero->getPrimSkillLevel(PrimarySkill::DEFENSE)
  999. && hero->manaLimit() > 30)
  1000. evaluationContext.armyReward += hero->getArmyCost();
  1001. }
  1002. }
  1003. }
  1004. int sameTownBonus = 0;
  1005. for (auto town : evaluationContext.evaluator.aiNk->cc->getTownsInfo())
  1006. {
  1007. if (buildThis.town->getFaction() == town->getFaction())
  1008. sameTownBonus += town->getTownLevel();
  1009. }
  1010. evaluationContext.armyReward *= sameTownBonus;
  1011. if(evaluationContext.goldReward)
  1012. {
  1013. auto goldPressure = evaluationContext.evaluator.aiNk->buildAnalyzer->getGoldPressure();
  1014. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.goldReward * goldPressure / 3500.0f / bi.prerequisitesCount);
  1015. }
  1016. if(bi.isMissingResources && bi.prerequisitesCount == 1)
  1017. {
  1018. evaluationContext.strategicalValue /= 3;
  1019. evaluationContext.movementCostByRole[evaluationContext.heroRole] += 5;
  1020. evaluationContext.turn += 5;
  1021. }
  1022. }
  1023. };
  1024. uint64_t RewardEvaluator::getUpgradeArmyReward(const CGTownInstance * town, const BuildingInfo & bi) const
  1025. {
  1026. if(aiNk->buildAnalyzer->isBuilt(town->getFactionID(), bi.id))
  1027. return 0;
  1028. auto creaturesToUpgrade = aiNk->armyManager->getTotalCreaturesAvailable(bi.baseCreatureID);
  1029. auto upgradedPower = aiNk->armyManager->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  1030. return upgradedPower - creaturesToUpgrade.power;
  1031. }
  1032. PriorityEvaluator::PriorityEvaluator(const Nullkiller * aiNk)
  1033. :aiNk(aiNk)
  1034. {
  1035. initVisitTile();
  1036. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>(aiNk));
  1037. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  1038. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>(aiNk));
  1039. evaluationContextBuilders.push_back(std::make_shared<HeroExchangeEvaluator>());
  1040. evaluationContextBuilders.push_back(std::make_shared<ArmyUpgradeEvaluator>());
  1041. evaluationContextBuilders.push_back(std::make_shared<DefendTownEvaluator>());
  1042. evaluationContextBuilders.push_back(std::make_shared<ExchangeSwapTownHeroesContextBuilder>());
  1043. evaluationContextBuilders.push_back(std::make_shared<DismissHeroContextBuilder>(aiNk));
  1044. evaluationContextBuilders.push_back(std::make_shared<StayAtTownManaRecoveryEvaluator>());
  1045. evaluationContextBuilders.push_back(std::make_shared<ExplorePointEvaluator>());
  1046. }
  1047. EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  1048. {
  1049. Goals::TGoalVec parts;
  1050. EvaluationContext context(aiNk);
  1051. if(goal->goalType == Goals::COMPOSITION)
  1052. {
  1053. parts = goal->decompose(aiNk);
  1054. }
  1055. else
  1056. {
  1057. parts.push_back(goal);
  1058. }
  1059. for(auto subgoal : parts)
  1060. {
  1061. context.goldCost += subgoal->goldCost;
  1062. context.buildingCost += subgoal->buildingCost;
  1063. for(auto builder : evaluationContextBuilders)
  1064. {
  1065. builder->buildEvaluationContext(context, subgoal);
  1066. }
  1067. }
  1068. return context;
  1069. }
  1070. float PriorityEvaluator::evaluate(Goals::TSubgoal task, int priorityTier)
  1071. {
  1072. auto evaluationContext = buildEvaluationContext(task);
  1073. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  1074. + (evaluationContext.armyReward > 0 ? 1 : 0)
  1075. + (evaluationContext.skillReward > 0 ? 1 : 0)
  1076. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  1077. float goldRewardVsMovement = evaluationContext.goldReward / std::log2f(2 + evaluationContext.movementCost * 10);
  1078. double result = 0;
  1079. if (aiNk->settings->isUseFuzzy())
  1080. {
  1081. float fuzzyResult = 0;
  1082. try
  1083. {
  1084. armyLossRatioVariable->setValue(evaluationContext.armyLossRatio);
  1085. heroRoleVariable->setValue(evaluationContext.heroRole);
  1086. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  1087. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  1088. goldRewardVsMovementVariable->setValue(goldRewardVsMovement);
  1089. armyRewardVariable->setValue(evaluationContext.armyReward);
  1090. armyGrowthVariable->setValue(evaluationContext.armyGrowth);
  1091. skillRewardVariable->setValue(evaluationContext.skillReward);
  1092. dangerVariable->setValue(evaluationContext.danger);
  1093. rewardTypeVariable->setValue(rewardType);
  1094. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  1095. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  1096. goldPressureVariable->setValue(aiNk->buildAnalyzer->getGoldPressure());
  1097. goldCostVariable->setValue(evaluationContext.goldCost / ((float)aiNk->getFreeResources()[EGameResID::GOLD] + (float)aiNk->buildAnalyzer->getDailyIncome()[EGameResID::GOLD] + 1.0f));
  1098. turnVariable->setValue(evaluationContext.turn);
  1099. fearVariable->setValue(evaluationContext.enemyHeroDangerRatio);
  1100. engine->process();
  1101. fuzzyResult = value->getValue();
  1102. }
  1103. catch (fl::Exception& fe)
  1104. {
  1105. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  1106. }
  1107. result = fuzzyResult;
  1108. }
  1109. else
  1110. {
  1111. float score = 0;
  1112. bool currentPositionThreatened = false;
  1113. if (task->hero)
  1114. {
  1115. auto currentTileThreat = aiNk->dangerHitMap->getTileThreat(task->hero->visitablePos());
  1116. if (currentTileThreat.fastestDanger.turn < 1 && currentTileThreat.fastestDanger.danger > task->hero->getTotalStrength())
  1117. currentPositionThreatened = true;
  1118. }
  1119. if (priorityTier == PriorityTier::FAR_HUNTER_GATHER && currentPositionThreatened == true)
  1120. {
  1121. #if NK2AI_TRACE_LEVEL >= 2
  1122. logAi->trace("Skip FAR_HUNTER_GATHER because hero would be threatened.");
  1123. #endif
  1124. return 0;
  1125. }
  1126. const bool amIInDanger = aiNk->cc->getTownsInfo().empty();
  1127. // TODO: Mircea: Shouldn't it default to 0 instead of 1.0 in the end?
  1128. const float maxWillingToLose = amIInDanger ? 1 : aiNk->settings->getMaxArmyLossTarget() * evaluationContext.powerRatio > 0 ? aiNk->settings->getMaxArmyLossTarget() * evaluationContext.powerRatio : 1.0;
  1129. float dangerThreshold = 1;
  1130. dangerThreshold *= evaluationContext.powerRatio > 0 ? evaluationContext.powerRatio : 1.0;
  1131. bool arriveNextWeek = false;
  1132. if (aiNk->cc->getDate(Date::DAY_OF_WEEK) + evaluationContext.turn > 7 && priorityTier < PriorityTier::FAR_KILL)
  1133. arriveNextWeek = true;
  1134. #if NK2AI_TRACE_LEVEL >= 2
  1135. 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",
  1136. priorityTier,
  1137. task->toString(),
  1138. evaluationContext.armyLossRatio,
  1139. maxWillingToLose,
  1140. (int)evaluationContext.turn,
  1141. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1142. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1143. evaluationContext.armyInvolvement,
  1144. goldRewardVsMovement,
  1145. evaluationContext.goldCost,
  1146. evaluationContext.armyReward,
  1147. evaluationContext.armyGrowth,
  1148. evaluationContext.skillReward,
  1149. evaluationContext.danger,
  1150. evaluationContext.threatTurns,
  1151. evaluationContext.threat,
  1152. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1153. evaluationContext.strategicalValue,
  1154. evaluationContext.conquestValue,
  1155. evaluationContext.closestWayRatio,
  1156. evaluationContext.enemyHeroDangerRatio,
  1157. dangerThreshold,
  1158. evaluationContext.explorePriority,
  1159. evaluationContext.isDefend,
  1160. evaluationContext.isEnemy,
  1161. arriveNextWeek,
  1162. evaluationContext.powerRatio);
  1163. #endif
  1164. switch (priorityTier)
  1165. {
  1166. case PriorityTier::INSTAKILL: //Take towns / kill heroes in immediate reach
  1167. {
  1168. if (evaluationContext.turn > 0 || evaluationContext.isExchange)
  1169. return 0;
  1170. if (evaluationContext.movementCost >= 1)
  1171. return 0;
  1172. if (evaluationContext.defenseValue < 2 && evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1173. return 0;
  1174. if(evaluationContext.conquestValue > 0)
  1175. score = evaluationContext.armyInvolvement;
  1176. if (vstd::isAlmostZero(score) || (evaluationContext.enemyHeroDangerRatio > dangerThreshold && (evaluationContext.turn > 0 || evaluationContext.isExchange) && !aiNk->cc->getTownsInfo().empty()))
  1177. return 0;
  1178. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1179. return 0;
  1180. if (evaluationContext.movementCost > 0)
  1181. score /= evaluationContext.movementCost;
  1182. break;
  1183. }
  1184. case PriorityTier::INSTADEFEND: //Defend immediately threatened towns
  1185. {
  1186. //No point defending if we don't have defensive-structures
  1187. if (evaluationContext.defenseValue < 2)
  1188. return 0;
  1189. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1190. return 0;
  1191. if (evaluationContext.closestWayRatio < 1.0)
  1192. return 0;
  1193. if (evaluationContext.isEnemy && evaluationContext.turn > 0)
  1194. return 0;
  1195. if (evaluationContext.isDefend && evaluationContext.threatTurns <= evaluationContext.turn)
  1196. {
  1197. const float OPTIMAL_PERCENTAGE = 0.75f; // We want army to be 75% of the threat
  1198. float optimalStrength = evaluationContext.threat * OPTIMAL_PERCENTAGE;
  1199. // Calculate how far the army is from optimal strength
  1200. float deviation = std::abs(evaluationContext.armyInvolvement - optimalStrength);
  1201. // Convert deviation to a percentage of the threat to normalize it
  1202. float deviationPercentage = deviation / evaluationContext.threat;
  1203. // Calculate score: 1.0 is perfect, decreasing as deviation increases
  1204. score = 1.0f / (1.0f + deviationPercentage);
  1205. // Apply turn penalty to still prefer earlier moves when scores are close
  1206. score = score / (evaluationContext.turn + 1);
  1207. }
  1208. break;
  1209. }
  1210. case PriorityTier::KILL: //Take towns / kill heroes that are further away
  1211. //FALL_THROUGH
  1212. case PriorityTier::FAR_KILL:
  1213. {
  1214. if (evaluationContext.defenseValue < 2 && evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1215. return 0;
  1216. if (evaluationContext.turn > 0 && evaluationContext.isHero)
  1217. return 0;
  1218. if (arriveNextWeek && evaluationContext.isEnemy)
  1219. return 0;
  1220. if (evaluationContext.conquestValue > 0)
  1221. score = evaluationContext.armyInvolvement;
  1222. if (vstd::isAlmostZero(score) || (evaluationContext.enemyHeroDangerRatio > dangerThreshold && (evaluationContext.turn > 0 || evaluationContext.isExchange) && !aiNk->cc->getTownsInfo().empty()))
  1223. return 0;
  1224. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1225. return 0;
  1226. score *= evaluationContext.closestWayRatio;
  1227. if (evaluationContext.movementCost > 0)
  1228. score /= evaluationContext.movementCost;
  1229. break;
  1230. }
  1231. case PriorityTier::HIGH_PRIO_EXPLORE:
  1232. {
  1233. if (evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1234. return 0;
  1235. if (evaluationContext.explorePriority != 1)
  1236. return 0;
  1237. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1238. return 0;
  1239. if (vstd::isAlmostZero(evaluationContext.armyLossRatio) && evaluationContext.closestWayRatio < 1.0)
  1240. return 0;
  1241. score = 1000;
  1242. if (evaluationContext.movementCost > 0)
  1243. score /= evaluationContext.movementCost;
  1244. break;
  1245. }
  1246. case PriorityTier::HUNTER_GATHER: //Collect guarded stuff
  1247. //FALL_THROUGH
  1248. case PriorityTier::FAR_HUNTER_GATHER:
  1249. // TODO: Mircea: 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
  1250. // task.get()->hero->getSlotFor(creature, 7) == false (not sure I get to know which creature is there in Orc Tower building)
  1251. // /// 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
  1252. // task.get()->hero->getFreeSlots(7) == 7
  1253. // getDuplicatingSlots(task.get()->hero) == false
  1254. {
  1255. if (evaluationContext.enemyHeroDangerRatio > dangerThreshold && !evaluationContext.isDefend && priorityTier != PriorityTier::FAR_HUNTER_GATHER)
  1256. {
  1257. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 1");
  1258. return 0;
  1259. }
  1260. if (evaluationContext.buildingCost.marketValue() > 0)
  1261. {
  1262. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 2");
  1263. return 0;
  1264. }
  1265. if (priorityTier != PriorityTier::FAR_HUNTER_GATHER && evaluationContext.isDefend && (evaluationContext.enemyHeroDangerRatio > dangerThreshold || evaluationContext.threatTurns > 0 || evaluationContext.turn > 0))
  1266. {
  1267. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 3");
  1268. return 0;
  1269. }
  1270. if (evaluationContext.explorePriority == 3)
  1271. {
  1272. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 4");
  1273. return 0;
  1274. }
  1275. if (priorityTier != PriorityTier::FAR_HUNTER_GATHER && ((evaluationContext.enemyHeroDangerRatio > 0 && arriveNextWeek) || evaluationContext.enemyHeroDangerRatio > dangerThreshold))
  1276. {
  1277. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 5");
  1278. return 0;
  1279. }
  1280. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1281. {
  1282. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 6");
  1283. return 0;
  1284. }
  1285. if (vstd::isAlmostZero(evaluationContext.armyLossRatio) && evaluationContext.closestWayRatio < 1.0)
  1286. {
  1287. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 7");
  1288. return 0;
  1289. }
  1290. score += evaluationContext.strategicalValue * 1000;
  1291. score += evaluationContext.goldReward;
  1292. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossRatio) * 0.05;
  1293. score += evaluationContext.armyReward;
  1294. score += evaluationContext.armyGrowth;
  1295. score -= evaluationContext.goldCost / 2; // don't include the full cost of School of Magic or others because those locations are beneficial
  1296. score -= evaluationContext.armyInvolvement * evaluationContext.armyLossRatio * 0.1;
  1297. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER score %f, strategicalValue %f, goldReward %f, skillRewardMultiplied %f, armyReward %f, armyGrowth %f, goldCost -%f, armyInvolvementMultiplied -%f, "
  1298. "armyLossPersentage %f, movementCost %f, enemyHeroDangerRatio %f",
  1299. score, evaluationContext.strategicalValue, evaluationContext.goldReward, evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossRatio) * 0.05,
  1300. evaluationContext.armyReward, evaluationContext.armyGrowth, evaluationContext.goldCost, evaluationContext.armyInvolvement * evaluationContext.armyLossRatio,
  1301. evaluationContext.armyLossRatio, evaluationContext.movementCost, evaluationContext.enemyHeroDangerRatio);
  1302. if (score > 0)
  1303. {
  1304. // score = 1000;
  1305. if (evaluationContext.movementCost > 0)
  1306. {
  1307. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 8");
  1308. score -= evaluationContext.movementCost / 20 * score; // we expect movement won't be over 20 turns
  1309. }
  1310. // TODO: Mircea: This doesn't make sense at it always seems to be 0. To test
  1311. if(evaluationContext.enemyHeroDangerRatio > 0)
  1312. {
  1313. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 9");
  1314. score *= 1 - evaluationContext.enemyHeroDangerRatio;
  1315. }
  1316. if(evaluationContext.armyLossRatio > 0)
  1317. {
  1318. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER if 10");
  1319. score *= 1 - evaluationContext.armyLossRatio;
  1320. }
  1321. }
  1322. logAi->trace("case PriorityTier::FAR_HUNTER_GATHER score final %f", score);
  1323. break;
  1324. }
  1325. case PriorityTier::LOW_PRIO_EXPLORE:
  1326. {
  1327. if (evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1328. return 0;
  1329. if (evaluationContext.explorePriority != 3)
  1330. return 0;
  1331. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1332. return 0;
  1333. if (evaluationContext.closestWayRatio < 1.0)
  1334. return 0;
  1335. score = 1000;
  1336. if (evaluationContext.movementCost > 0)
  1337. score /= evaluationContext.movementCost;
  1338. break;
  1339. }
  1340. case PriorityTier::DEFEND: //Defend whatever if nothing else is to do
  1341. {
  1342. if (evaluationContext.enemyHeroDangerRatio > dangerThreshold)
  1343. return 0;
  1344. if (evaluationContext.isDefend || evaluationContext.isArmyUpgrade)
  1345. score = evaluationContext.armyInvolvement;
  1346. score /= (evaluationContext.turn + 1);
  1347. break;
  1348. }
  1349. case PriorityTier::BUILDINGS: //For buildings and buying army
  1350. {
  1351. if (maxWillingToLose - evaluationContext.armyLossRatio < 0)
  1352. return 0;
  1353. //If we already have locked resources, we don't look at other buildings
  1354. if (aiNk->getLockedResources().marketValue() > 0)
  1355. return 0;
  1356. score += evaluationContext.conquestValue * 1000;
  1357. score += evaluationContext.strategicalValue * 1000;
  1358. score += evaluationContext.goldReward;
  1359. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossRatio) * 0.05;
  1360. score += evaluationContext.armyReward;
  1361. score += evaluationContext.armyGrowth;
  1362. if (evaluationContext.buildingCost.marketValue() > 0)
  1363. {
  1364. if (!evaluationContext.isTradeBuilding && aiNk->getFreeResources()[EGameResID::WOOD] - evaluationContext.buildingCost[EGameResID::WOOD] < 5 && aiNk->buildAnalyzer->getDailyIncome()[EGameResID::WOOD] < 1)
  1365. {
  1366. logAi->trace("Should make sure to build market-place instead of %s", task->toString());
  1367. for (auto town : aiNk->cc->getTownsInfo())
  1368. {
  1369. if (!town->hasBuiltSomeTradeBuilding())
  1370. return 0;
  1371. }
  1372. }
  1373. score += 1000;
  1374. auto resourcesAvailable = evaluationContext.evaluator.aiNk->getFreeResources();
  1375. auto income = aiNk->buildAnalyzer->getDailyIncome();
  1376. if(aiNk->buildAnalyzer->isGoldPressureOverMax())
  1377. score /= evaluationContext.buildingCost.marketValue();
  1378. if (!resourcesAvailable.canAfford(evaluationContext.buildingCost))
  1379. {
  1380. TResources needed = evaluationContext.buildingCost - resourcesAvailable;
  1381. needed.positive();
  1382. int turnsTo = needed.maxPurchasableCount(income);
  1383. bool haveEverythingButGold = true;
  1384. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1385. {
  1386. if (i != GameResID::GOLD && resourcesAvailable[i] < evaluationContext.buildingCost[i])
  1387. haveEverythingButGold = false;
  1388. }
  1389. if (turnsTo == INT_MAX)
  1390. return 0;
  1391. if (!haveEverythingButGold)
  1392. score /= turnsTo;
  1393. }
  1394. }
  1395. else
  1396. {
  1397. if (evaluationContext.enemyHeroDangerRatio > 1 && !evaluationContext.isDefend && vstd::isAlmostZero(evaluationContext.conquestValue))
  1398. return 0;
  1399. }
  1400. break;
  1401. }
  1402. }
  1403. result = score;
  1404. //TODO: Figure out the root cause for why evaluationContext.closestWayRatio has become -nan(ind).
  1405. if (std::isnan(result))
  1406. return 0;
  1407. }
  1408. #if NK2AI_TRACE_LEVEL >= 2
  1409. logAi->trace("priorityTier %d, Evaluated %s, loss: %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, result %f",
  1410. priorityTier,
  1411. task->toString(),
  1412. evaluationContext.armyLossRatio,
  1413. (int)evaluationContext.turn,
  1414. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1415. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1416. evaluationContext.armyInvolvement,
  1417. goldRewardVsMovement,
  1418. evaluationContext.goldCost,
  1419. evaluationContext.armyReward,
  1420. evaluationContext.armyGrowth,
  1421. evaluationContext.skillReward,
  1422. evaluationContext.danger,
  1423. evaluationContext.threatTurns,
  1424. evaluationContext.threat,
  1425. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1426. evaluationContext.strategicalValue,
  1427. evaluationContext.conquestValue,
  1428. evaluationContext.closestWayRatio,
  1429. evaluationContext.enemyHeroDangerRatio,
  1430. result);
  1431. #endif
  1432. return result;
  1433. }
  1434. }