PriorityEvaluator.cpp 49 KB

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