PriorityEvaluator.cpp 55 KB

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