PriorityEvaluator.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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/ExchangeSwapTownHeroes.h"
  25. #include "../Goals/DismissHero.h"
  26. #include "../Markers/UnlockCluster.h"
  27. #include "../Markers/HeroExchange.h"
  28. #include "../Markers/ArmyUpgrade.h"
  29. #include "../Markers/DefendTown.h"
  30. namespace NKAI
  31. {
  32. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  33. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  34. const 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. evaluator(ai),
  50. enemyHeroDangerRatio(0),
  51. armyGrowth(0)
  52. {
  53. }
  54. void EvaluationContext::addNonCriticalStrategicalValue(float value)
  55. {
  56. vstd::amax(strategicalValue, std::min(value, MIN_CRITICAL_VALUE));
  57. }
  58. PriorityEvaluator::~PriorityEvaluator()
  59. {
  60. delete engine;
  61. }
  62. void PriorityEvaluator::initVisitTile()
  63. {
  64. auto file = CResourceHandler::get()->load(ResourceID("config/ai/object-priorities.txt"))->readAll();
  65. std::string str = std::string((char *)file.first.get(), file.second);
  66. engine = fl::FllImporter().fromString(str);
  67. armyLossPersentageVariable = engine->getInputVariable("armyLoss");
  68. armyGrowthVariable = engine->getInputVariable("armyGrowth");
  69. heroRoleVariable = engine->getInputVariable("heroRole");
  70. dangerVariable = engine->getInputVariable("danger");
  71. turnVariable = engine->getInputVariable("turn");
  72. mainTurnDistanceVariable = engine->getInputVariable("mainTurnDistance");
  73. scoutTurnDistanceVariable = engine->getInputVariable("scoutTurnDistance");
  74. goldRewardVariable = engine->getInputVariable("goldReward");
  75. armyRewardVariable = engine->getInputVariable("armyReward");
  76. skillRewardVariable = engine->getInputVariable("skillReward");
  77. rewardTypeVariable = engine->getInputVariable("rewardType");
  78. closestHeroRatioVariable = engine->getInputVariable("closestHeroRatio");
  79. strategicalValueVariable = engine->getInputVariable("strategicalValue");
  80. goldPreasureVariable = engine->getInputVariable("goldPreasure");
  81. goldCostVariable = engine->getInputVariable("goldCost");
  82. fearVariable = engine->getInputVariable("fear");
  83. value = engine->getOutputVariable("Value");
  84. }
  85. bool isAnotherAi(const CGObjectInstance * obj, const CPlayerSpecificInfoCallback & cb)
  86. {
  87. return obj->getOwner().isValidPlayer()
  88. && cb.getStartInfo()->getIthPlayersSettings(obj->getOwner()).isControlledByAI();
  89. }
  90. int32_t estimateTownIncome(CCallback * cb, const CGObjectInstance * target, const CGHeroInstance * hero)
  91. {
  92. auto relations = cb->getPlayerRelations(hero->tempOwner, target->tempOwner);
  93. if(relations != PlayerRelations::ENEMIES)
  94. return 0; // if we already own it, no additional reward will be received by just visiting it
  95. auto booster = isAnotherAi(target, *cb) ? 1 : 2;
  96. auto town = cb->getTown(target->id);
  97. auto fortLevel = town->fortLevel();
  98. if(town->hasCapitol()) return booster * 2000;
  99. // probably well developed town will have city hall
  100. if(fortLevel == CGTownInstance::CASTLE) return booster * 750;
  101. return booster * (town->hasFort() && town->tempOwner != PlayerColor::NEUTRAL ? booster * 500 : 250);
  102. }
  103. TResources getCreatureBankResources(const CGObjectInstance * target, const CGHeroInstance * hero)
  104. {
  105. //Fixme: unused variable hero
  106. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  107. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  108. auto resources = bankInfo->getPossibleResourcesReward();
  109. TResources result = TResources();
  110. int sum = 0;
  111. for(auto & reward : resources)
  112. {
  113. result += reward.data * reward.chance;
  114. sum += reward.chance;
  115. }
  116. return sum > 1 ? result / sum : result;
  117. }
  118. uint64_t getCreatureBankArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  119. {
  120. auto objectInfo = VLC->objtypeh->getHandlerFor(target->ID, target->subID)->getObjectInfo(target->appearance);
  121. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  122. auto creatures = bankInfo->getPossibleCreaturesReward();
  123. uint64_t result = 0;
  124. const auto& slots = hero->Slots();
  125. ui64 weakestStackPower = 0;
  126. if (slots.size() >= GameConstants::ARMY_SIZE)
  127. {
  128. //No free slot, we might discard our weakest stack
  129. weakestStackPower = std::numeric_limits<ui64>().max();
  130. for (const auto & stack : slots)
  131. {
  132. vstd::amin(weakestStackPower, stack.second->getPower());
  133. }
  134. }
  135. for (auto c : creatures)
  136. {
  137. //Only if hero has slot for this creature in the army
  138. auto ccre = dynamic_cast<const CCreature*>(c.data.type);
  139. if (hero->getSlotFor(ccre).validSlot())
  140. {
  141. result += (c.data.type->getAIValue() * c.data.count) * c.chance;
  142. }
  143. else
  144. {
  145. //we will need to discard the weakest stack
  146. result += (c.data.type->getAIValue() * c.data.count - weakestStackPower) * c.chance;
  147. }
  148. }
  149. result /= 100; //divide by total chance
  150. return result;
  151. }
  152. uint64_t getDwellingArmyValue(CCallback * cb, const CGObjectInstance * target, bool checkGold)
  153. {
  154. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  155. uint64_t score = 0;
  156. for(auto & creLevel : dwelling->creatures)
  157. {
  158. if(creLevel.first && creLevel.second.size())
  159. {
  160. auto creature = creLevel.second.back().toCreature();
  161. auto creaturesAreFree = creature->getLevel() == 1;
  162. if(!creaturesAreFree && checkGold && !cb->getResourceAmount().canAfford(creature->getFullRecruitCost() * creLevel.first))
  163. continue;
  164. score += creature->getAIValue() * creLevel.first;
  165. }
  166. }
  167. return score;
  168. }
  169. uint64_t getDwellingArmyGrowth(CCallback * cb, const CGObjectInstance * target, PlayerColor myColor)
  170. {
  171. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  172. uint64_t score = 0;
  173. if(dwelling->getOwner() == myColor)
  174. return 0;
  175. for(auto & creLevel : dwelling->creatures)
  176. {
  177. if(creLevel.second.size())
  178. {
  179. auto creature = creLevel.second.back().toCreature();
  180. score += creature->getAIValue() * creature->getGrowth();
  181. }
  182. }
  183. return score;
  184. }
  185. int getDwellingArmyCost(const CGObjectInstance * target)
  186. {
  187. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  188. int cost = 0;
  189. for(auto & creLevel : dwelling->creatures)
  190. {
  191. if(creLevel.first && creLevel.second.size())
  192. {
  193. auto creature = creLevel.second.back().toCreature();
  194. auto creaturesAreFree = creature->getLevel() == 1;
  195. if(!creaturesAreFree)
  196. cost += creature->getRecruitCost(EGameResID::GOLD) * creLevel.first;
  197. }
  198. }
  199. return cost;
  200. }
  201. uint64_t evaluateArtifactArmyValue(CArtifactInstance * art)
  202. {
  203. if(art->artType->getId() == ArtifactID::SPELL_SCROLL)
  204. return 1500;
  205. auto statsValue =
  206. 10 * art->valOfBonuses(BonusType::MOVEMENT, 1)
  207. + 1200 * art->valOfBonuses(BonusType::STACKS_SPEED)
  208. + 700 * art->valOfBonuses(BonusType::MORALE)
  209. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, PrimarySkill::ATTACK)
  210. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, PrimarySkill::DEFENSE)
  211. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, PrimarySkill::KNOWLEDGE)
  212. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, PrimarySkill::SPELL_POWER)
  213. + 500 * art->valOfBonuses(BonusType::LUCK);
  214. auto classValue = 0;
  215. switch(art->artType->aClass)
  216. {
  217. case CArtifact::EartClass::ART_MINOR:
  218. classValue = 1000;
  219. break;
  220. case CArtifact::EartClass::ART_MAJOR:
  221. classValue = 3000;
  222. break;
  223. case CArtifact::EartClass::ART_RELIC:
  224. case CArtifact::EartClass::ART_SPECIAL:
  225. classValue = 8000;
  226. break;
  227. }
  228. return statsValue > classValue ? statsValue : classValue;
  229. }
  230. uint64_t RewardEvaluator::getArmyReward(
  231. const CGObjectInstance * target,
  232. const CGHeroInstance * hero,
  233. const CCreatureSet * army,
  234. bool checkGold) const
  235. {
  236. const float enemyArmyEliminationRewardRatio = 0.5f;
  237. if(!target)
  238. return 0;
  239. switch(target->ID)
  240. {
  241. case Obj::TOWN:
  242. {
  243. auto town = dynamic_cast<const CGTownInstance *>(target);
  244. auto fortLevel = town->fortLevel();
  245. auto booster = isAnotherAi(town, *ai->cb) ? 1 : 2;
  246. if(fortLevel < CGTownInstance::CITADEL)
  247. return town->hasFort() ? booster * 500 : 0;
  248. else
  249. return booster * (fortLevel == CGTownInstance::CASTLE ? 5000 : 2000);
  250. }
  251. case Obj::HILL_FORT:
  252. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeValue;
  253. case Obj::CREATURE_BANK:
  254. return getCreatureBankArmyReward(target, hero);
  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::CRYPT:
  261. case Obj::SHIPWRECK:
  262. case Obj::SHIPWRECK_SURVIVOR:
  263. case Obj::WARRIORS_TOMB:
  264. return 1000;
  265. case Obj::ARTIFACT:
  266. return evaluateArtifactArmyValue(dynamic_cast<const CGArtifact *>(target)->storedArtifact);
  267. case Obj::DRAGON_UTOPIA:
  268. return 10000;
  269. case Obj::HERO:
  270. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  271. ? enemyArmyEliminationRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->getArmyStrength()
  272. : 0;
  273. case Obj::PANDORAS_BOX:
  274. return 5000;
  275. default:
  276. return 0;
  277. }
  278. }
  279. uint64_t RewardEvaluator::getArmyGrowth(
  280. const CGObjectInstance * target,
  281. const CGHeroInstance * hero,
  282. const CCreatureSet * army) const
  283. {
  284. const float enemyArmyEliminationRewardRatio = 0.5f;
  285. if(!target)
  286. return 0;
  287. switch(target->ID)
  288. {
  289. case Obj::TOWN:
  290. {
  291. auto town = dynamic_cast<const CGTownInstance *>(target);
  292. auto fortLevel = town->fortLevel();
  293. auto neutral = !town->getOwner().isValidPlayer();
  294. auto booster = isAnotherAi(town, *ai->cb) || neutral ? 1 : 2;
  295. if(fortLevel < CGTownInstance::CITADEL)
  296. return town->hasFort() ? booster * 500 : 0;
  297. else
  298. return booster * (fortLevel == CGTownInstance::CASTLE ? 5000 : 2000);
  299. }
  300. case Obj::CREATURE_GENERATOR1:
  301. case Obj::CREATURE_GENERATOR2:
  302. case Obj::CREATURE_GENERATOR3:
  303. case Obj::CREATURE_GENERATOR4:
  304. return getDwellingArmyGrowth(ai->cb.get(), target, hero->getOwner());
  305. case Obj::ARTIFACT:
  306. // 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.
  307. return 0;
  308. default:
  309. return 0;
  310. }
  311. }
  312. int RewardEvaluator::getGoldCost(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army) const
  313. {
  314. if(!target)
  315. return 0;
  316. if(auto * m = dynamic_cast<const IMarket *>(target))
  317. {
  318. if(m->allowsTrade(EMarketMode::RESOURCE_SKILL))
  319. return 2000;
  320. }
  321. switch(target->ID)
  322. {
  323. case Obj::HILL_FORT:
  324. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeCost[EGameResID::GOLD];
  325. case Obj::SCHOOL_OF_MAGIC:
  326. case Obj::SCHOOL_OF_WAR:
  327. return 1000;
  328. case Obj::CREATURE_GENERATOR1:
  329. case Obj::CREATURE_GENERATOR2:
  330. case Obj::CREATURE_GENERATOR3:
  331. case Obj::CREATURE_GENERATOR4:
  332. return getDwellingArmyCost(target);
  333. default:
  334. return 0;
  335. }
  336. }
  337. float RewardEvaluator::getEnemyHeroStrategicalValue(const CGHeroInstance * enemy) const
  338. {
  339. auto objectsUnderTreat = ai->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  340. float objectValue = 0;
  341. for(auto obj : objectsUnderTreat)
  342. {
  343. vstd::amax(objectValue, getStrategicalValue(obj));
  344. }
  345. /*
  346. 1. If an enemy hero can attack nearby object, it's not useful to capture the object on our own.
  347. Killing the hero is almost as important (0.9) as capturing the object itself.
  348. 2. The formula quickly approaches 1.0 as hero level increases,
  349. but higher level always means higher value and the minimal value for level 1 hero is 0.5
  350. */
  351. return std::min(1.5f, objectValue * 0.9f + (1.5f - (1.5f / (1 + enemy->level))));
  352. }
  353. float RewardEvaluator::getResourceRequirementStrength(int resType) const
  354. {
  355. TResources requiredResources = ai->buildAnalyzer->getResourcesRequiredNow();
  356. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  357. if(requiredResources[resType] == 0)
  358. return 0;
  359. if(dailyIncome[resType] == 0)
  360. return 1.0f;
  361. float ratio = (float)requiredResources[resType] / dailyIncome[resType] / 2;
  362. return std::min(ratio, 1.0f);
  363. }
  364. float RewardEvaluator::getTotalResourceRequirementStrength(int resType) const
  365. {
  366. TResources requiredResources = ai->buildAnalyzer->getTotalResourcesRequired();
  367. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  368. if(requiredResources[resType] == 0)
  369. return 0;
  370. float ratio = dailyIncome[resType] == 0
  371. ? (float)requiredResources[resType] / 50.0f
  372. : (float)requiredResources[resType] / dailyIncome[resType] / 50.0f;
  373. return std::min(ratio, 1.0f);
  374. }
  375. float RewardEvaluator::getStrategicalValue(const CGObjectInstance * target) const
  376. {
  377. if(!target)
  378. return 0;
  379. switch(target->ID)
  380. {
  381. case Obj::MINE:
  382. return target->subID == GameResID(EGameResID::GOLD)
  383. ? 0.5f
  384. : 0.4f * getTotalResourceRequirementStrength(target->subID) + 0.1f * getResourceRequirementStrength(target->subID);
  385. case Obj::RESOURCE:
  386. return target->subID == GameResID(EGameResID::GOLD)
  387. ? 0
  388. : 0.2f * getTotalResourceRequirementStrength(target->subID) + 0.4f * getResourceRequirementStrength(target->subID);
  389. case Obj::CREATURE_BANK:
  390. {
  391. auto resourceReward = getCreatureBankResources(target, nullptr);
  392. float sum = 0.0f;
  393. for (TResources::nziterator it (resourceReward); it.valid(); it++)
  394. {
  395. //Evaluate resources used for construction. Gold is evaluated separately.
  396. if (it->resType != EGameResID::GOLD)
  397. {
  398. sum += 0.1f * getResourceRequirementStrength(it->resType);
  399. }
  400. }
  401. return sum;
  402. }
  403. case Obj::TOWN:
  404. {
  405. if(ai->buildAnalyzer->getDevelopmentInfo().empty())
  406. return 1;
  407. auto town = dynamic_cast<const CGTownInstance *>(target);
  408. auto fortLevel = town->fortLevel();
  409. auto booster = isAnotherAi(town, *ai->cb) ? 0.3 : 1;
  410. if(town->hasCapitol()) return 1;
  411. if(fortLevel < CGTownInstance::CITADEL)
  412. return booster * (town->hasFort() ? 0.6 : 0.4);
  413. else
  414. return booster * (fortLevel == CGTownInstance::CASTLE ? 0.9 : 0.8);
  415. }
  416. case Obj::HERO:
  417. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  418. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  419. : 0;
  420. default:
  421. return 0;
  422. }
  423. }
  424. float RewardEvaluator::evaluateWitchHutSkillScore(const CGWitchHut * hut, const CGHeroInstance * hero, HeroRole role) const
  425. {
  426. if(!hut->wasVisited(hero->tempOwner))
  427. return role == HeroRole::SCOUT ? 2 : 0;
  428. auto skill = SecondarySkill(hut->ability);
  429. if(hero->getSecSkillLevel(skill) != SecSkillLevel::NONE
  430. || hero->secSkills.size() >= GameConstants::SKILL_PER_HERO)
  431. return 0;
  432. auto score = ai->heroManager->evaluateSecSkill(skill, hero);
  433. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  434. }
  435. float RewardEvaluator::getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role) const
  436. {
  437. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  438. if(!target)
  439. return 0;
  440. switch(target->ID)
  441. {
  442. case Obj::STAR_AXIS:
  443. case Obj::SCHOLAR:
  444. case Obj::SCHOOL_OF_MAGIC:
  445. case Obj::SCHOOL_OF_WAR:
  446. case Obj::GARDEN_OF_REVELATION:
  447. case Obj::MARLETTO_TOWER:
  448. case Obj::MERCENARY_CAMP:
  449. case Obj::SHRINE_OF_MAGIC_GESTURE:
  450. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  451. case Obj::TREE_OF_KNOWLEDGE:
  452. return 1;
  453. case Obj::LEARNING_STONE:
  454. return 1.0f / std::sqrt(hero->level);
  455. case Obj::ARENA:
  456. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  457. return 2;
  458. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  459. return 8;
  460. case Obj::WITCH_HUT:
  461. return evaluateWitchHutSkillScore(dynamic_cast<const CGWitchHut *>(target), hero, role);
  462. case Obj::PANDORAS_BOX:
  463. //Can contains experience, spells, or skills (only on custom maps)
  464. return 2.5f;
  465. case Obj::HERO:
  466. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  467. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  468. : 0;
  469. default:
  470. return 0;
  471. }
  472. }
  473. const HitMapInfo & RewardEvaluator::getEnemyHeroDanger(const int3 & tile, uint8_t turn) const
  474. {
  475. auto & treatNode = ai->dangerHitMap->getTileTreat(tile);
  476. if(treatNode.maximumDanger.danger == 0)
  477. return HitMapInfo::NoTreat;
  478. if(treatNode.maximumDanger.turn <= turn)
  479. return treatNode.maximumDanger;
  480. return treatNode.fastestDanger.turn <= turn ? treatNode.fastestDanger : HitMapInfo::NoTreat;
  481. }
  482. int32_t getArmyCost(const CArmedInstance * army)
  483. {
  484. int32_t value = 0;
  485. for(auto stack : army->Slots())
  486. {
  487. value += stack.second->getCreatureID().toCreature()->getRecruitCost(EGameResID::GOLD) * stack.second->count;
  488. }
  489. return value;
  490. }
  491. /// Gets aproximated reward in gold. Daily income is multiplied by 5
  492. int32_t RewardEvaluator::getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero) const
  493. {
  494. if(!target)
  495. return 0;
  496. const int dailyIncomeMultiplier = 5;
  497. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  498. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  499. auto isGold = target->subID == GameResID(EGameResID::GOLD); // TODO: other resorces could be sold but need to evaluate market power
  500. switch(target->ID)
  501. {
  502. case Obj::RESOURCE:
  503. return isGold ? 600 : 100;
  504. case Obj::TREASURE_CHEST:
  505. return 1500;
  506. case Obj::WATER_WHEEL:
  507. return 1000;
  508. case Obj::TOWN:
  509. return dailyIncomeMultiplier * estimateTownIncome(ai->cb.get(), target, hero);
  510. case Obj::MINE:
  511. case Obj::ABANDONED_MINE:
  512. return dailyIncomeMultiplier * (isGold ? 1000 : 75);
  513. case Obj::MYSTICAL_GARDEN:
  514. case Obj::WINDMILL:
  515. return 100;
  516. case Obj::CAMPFIRE:
  517. return 800;
  518. case Obj::WAGON:
  519. return 100;
  520. case Obj::CREATURE_BANK:
  521. return getCreatureBankResources(target, hero)[EGameResID::GOLD];
  522. case Obj::CRYPT:
  523. case Obj::DERELICT_SHIP:
  524. return 3000;
  525. case Obj::DRAGON_UTOPIA:
  526. return 10000;
  527. case Obj::SEA_CHEST:
  528. return 1500;
  529. case Obj::PANDORAS_BOX:
  530. return 2500;
  531. case Obj::PRISON:
  532. //Objectively saves us 2500 to hire hero
  533. return GameConstants::HERO_GOLD_COST;
  534. case Obj::HERO:
  535. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  536. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  537. : 0;
  538. default:
  539. return 0;
  540. }
  541. }
  542. class HeroExchangeEvaluator : public IEvaluationContextBuilder
  543. {
  544. public:
  545. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  546. {
  547. if(task->goalType != Goals::HERO_EXCHANGE)
  548. return;
  549. Goals::HeroExchange & heroExchange = dynamic_cast<Goals::HeroExchange &>(*task);
  550. uint64_t armyStrength = heroExchange.getReinforcementArmyStrength();
  551. evaluationContext.addNonCriticalStrategicalValue(2.0f * armyStrength / (float)heroExchange.hero.get()->getArmyStrength());
  552. evaluationContext.heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(heroExchange.hero.get());
  553. }
  554. };
  555. class ArmyUpgradeEvaluator : public IEvaluationContextBuilder
  556. {
  557. public:
  558. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  559. {
  560. if(task->goalType != Goals::ARMY_UPGRADE)
  561. return;
  562. Goals::ArmyUpgrade & armyUpgrade = dynamic_cast<Goals::ArmyUpgrade &>(*task);
  563. uint64_t upgradeValue = armyUpgrade.getUpgradeValue();
  564. evaluationContext.armyReward += upgradeValue;
  565. evaluationContext.addNonCriticalStrategicalValue(upgradeValue / (float)armyUpgrade.hero->getArmyStrength());
  566. }
  567. };
  568. void addTileDanger(EvaluationContext & evaluationContext, const int3 & tile, uint8_t turn, uint64_t ourStrength)
  569. {
  570. HitMapInfo enemyDanger = evaluationContext.evaluator.getEnemyHeroDanger(tile, turn);
  571. if(enemyDanger.danger)
  572. {
  573. auto dangerRatio = enemyDanger.danger / (double)ourStrength;
  574. auto enemyHero = evaluationContext.evaluator.ai->cb->getObj(enemyDanger.hero.hid, false);
  575. bool isAI = enemyHero && isAnotherAi(enemyHero, *evaluationContext.evaluator.ai->cb);
  576. if(isAI)
  577. {
  578. dangerRatio *= 1.5; // lets make AI bit more afraid of other AI.
  579. }
  580. vstd::amax(evaluationContext.enemyHeroDangerRatio, dangerRatio);
  581. }
  582. }
  583. class DefendTownEvaluator : public IEvaluationContextBuilder
  584. {
  585. private:
  586. uint64_t townArmyIncome(const CGTownInstance * town) const
  587. {
  588. uint64_t result = 0;
  589. for(auto creatureInfo : town->creatures)
  590. {
  591. if(creatureInfo.second.empty())
  592. continue;
  593. auto creature = creatureInfo.second.back().toCreature();
  594. result += creature->getAIValue() * town->getGrowthInfo(creature->getLevel() - 1).totalGrowth();
  595. }
  596. return result;
  597. }
  598. public:
  599. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  600. {
  601. if(task->goalType != Goals::DEFEND_TOWN)
  602. return;
  603. Goals::DefendTown & defendTown = dynamic_cast<Goals::DefendTown &>(*task);
  604. const CGTownInstance * town = defendTown.town;
  605. auto & treat = defendTown.getTreat();
  606. auto armyIncome = townArmyIncome(town);
  607. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  608. auto strategicalValue = std::sqrt(armyIncome / 60000.0f) + dailyIncome / 10000.0f;
  609. if(evaluationContext.evaluator.ai->buildAnalyzer->getDevelopmentInfo().size() == 1)
  610. vstd::amax(evaluationContext.strategicalValue, 10.0);
  611. float multiplier = 1;
  612. if(treat.turn < defendTown.getTurn())
  613. multiplier /= 1 + (defendTown.getTurn() - treat.turn);
  614. multiplier /= 1.0f + treat.turn / 5.0f;
  615. evaluationContext.armyGrowth += armyIncome * multiplier;
  616. evaluationContext.goldReward += dailyIncome * 5 * multiplier;
  617. evaluationContext.addNonCriticalStrategicalValue(strategicalValue * multiplier);
  618. vstd::amax(evaluationContext.danger, defendTown.getTreat().danger);
  619. addTileDanger(evaluationContext, town->visitablePos(), defendTown.getTurn(), defendTown.getDefenceStrength());
  620. }
  621. };
  622. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  623. {
  624. private:
  625. const Nullkiller * ai;
  626. public:
  627. ExecuteHeroChainEvaluationContextBuilder(const Nullkiller * ai) : ai(ai) {}
  628. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  629. {
  630. if(task->goalType != Goals::EXECUTE_HERO_CHAIN)
  631. return;
  632. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  633. const AIPath & path = chain.getPath();
  634. vstd::amax(evaluationContext.danger, path.getTotalDanger());
  635. evaluationContext.movementCost += path.movementCost();
  636. evaluationContext.closestWayRatio = chain.closestWayRatio;
  637. std::map<const CGHeroInstance *, float> costsPerHero;
  638. for(auto & node : path.nodes)
  639. {
  640. vstd::amax(costsPerHero[node.targetHero], node.cost);
  641. }
  642. for(auto pair : costsPerHero)
  643. {
  644. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(pair.first);
  645. evaluationContext.movementCostByRole[role] += pair.second;
  646. }
  647. auto heroPtr = task->hero;
  648. auto hero = heroPtr.get(ai->cb.get());
  649. bool checkGold = evaluationContext.danger == 0;
  650. auto army = path.heroArmy;
  651. const CGObjectInstance * target = ai->cb->getObj((ObjectInstanceID)task->objid, false);
  652. auto heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(heroPtr);
  653. if(heroRole == HeroRole::MAIN)
  654. evaluationContext.heroRole = heroRole;
  655. if (target && ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner) == PlayerRelations::ENEMIES)
  656. {
  657. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero);
  658. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold);
  659. evaluationContext.armyGrowth += evaluationContext.evaluator.getArmyGrowth(target, hero, army);
  660. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, heroRole);
  661. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target));
  662. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army);
  663. }
  664. vstd::amax(evaluationContext.armyLossPersentage, path.getTotalArmyLoss() / (double)path.getHeroStrength());
  665. addTileDanger(evaluationContext, path.targetTile(), path.turn(), path.getHeroStrength());
  666. vstd::amax(evaluationContext.turn, path.turn());
  667. }
  668. };
  669. class ClusterEvaluationContextBuilder : public IEvaluationContextBuilder
  670. {
  671. public:
  672. ClusterEvaluationContextBuilder(const Nullkiller * ai) {}
  673. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  674. {
  675. if(task->goalType != Goals::UNLOCK_CLUSTER)
  676. return;
  677. Goals::UnlockCluster & clusterGoal = dynamic_cast<Goals::UnlockCluster &>(*task);
  678. std::shared_ptr<ObjectCluster> cluster = clusterGoal.getCluster();
  679. auto hero = clusterGoal.hero.get();
  680. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(clusterGoal.hero);
  681. std::vector<std::pair<const CGObjectInstance *, ClusterObjectInfo>> objects(cluster->objects.begin(), cluster->objects.end());
  682. std::sort(objects.begin(), objects.end(), [](std::pair<const CGObjectInstance *, ClusterObjectInfo> o1, std::pair<const CGObjectInstance *, ClusterObjectInfo> o2) -> bool
  683. {
  684. return o1.second.priority > o2.second.priority;
  685. });
  686. int boost = 1;
  687. for(auto objInfo : objects)
  688. {
  689. auto target = objInfo.first;
  690. bool checkGold = objInfo.second.danger == 0;
  691. auto army = hero;
  692. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero) / boost;
  693. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold) / boost;
  694. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, role) / boost;
  695. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target) / boost);
  696. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army) / boost;
  697. evaluationContext.movementCostByRole[role] += objInfo.second.movementCost / boost;
  698. evaluationContext.movementCost += objInfo.second.movementCost / boost;
  699. vstd::amax(evaluationContext.turn, objInfo.second.turn / boost);
  700. boost <<= 1;
  701. if(boost > 8)
  702. break;
  703. }
  704. }
  705. };
  706. class ExchangeSwapTownHeroesContextBuilder : public IEvaluationContextBuilder
  707. {
  708. public:
  709. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  710. {
  711. if(task->goalType != Goals::EXCHANGE_SWAP_TOWN_HEROES)
  712. return;
  713. Goals::ExchangeSwapTownHeroes & swapCommand = dynamic_cast<Goals::ExchangeSwapTownHeroes &>(*task);
  714. const CGHeroInstance * garrisonHero = swapCommand.getGarrisonHero();
  715. if(garrisonHero && swapCommand.getLockingReason() == HeroLockedReason::DEFENCE)
  716. {
  717. auto defenderRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(garrisonHero);
  718. auto mpLeft = garrisonHero->movementPointsRemaining() / (float)garrisonHero->movementPointsLimit(true);
  719. evaluationContext.movementCost += mpLeft;
  720. evaluationContext.movementCostByRole[defenderRole] += mpLeft;
  721. evaluationContext.heroRole = defenderRole;
  722. }
  723. }
  724. };
  725. class DismissHeroContextBuilder : public IEvaluationContextBuilder
  726. {
  727. private:
  728. const Nullkiller * ai;
  729. public:
  730. DismissHeroContextBuilder(const Nullkiller * ai) : ai(ai) {}
  731. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  732. {
  733. if(task->goalType != Goals::DISMISS_HERO)
  734. return;
  735. Goals::DismissHero & dismissCommand = dynamic_cast<Goals::DismissHero &>(*task);
  736. const CGHeroInstance * dismissedHero = dismissCommand.getHero().get();
  737. auto role = ai->heroManager->getHeroRole(dismissedHero);
  738. auto mpLeft = dismissedHero->movement;
  739. evaluationContext.movementCost += mpLeft;
  740. evaluationContext.movementCostByRole[role] += mpLeft;
  741. evaluationContext.goldCost += GameConstants::HERO_GOLD_COST + getArmyCost(dismissedHero);
  742. }
  743. };
  744. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  745. {
  746. public:
  747. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  748. {
  749. if(task->goalType != Goals::BUILD_STRUCTURE)
  750. return;
  751. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  752. auto & bi = buildThis.buildingInfo;
  753. evaluationContext.goldReward += 7 * bi.dailyIncome[EGameResID::GOLD] / 2; // 7 day income but half we already have
  754. evaluationContext.heroRole = HeroRole::MAIN;
  755. evaluationContext.movementCostByRole[evaluationContext.heroRole] += bi.prerequisitesCount;
  756. evaluationContext.goldCost += bi.buildCostWithPrerequisits[EGameResID::GOLD];
  757. if(bi.creatureID != CreatureID::NONE)
  758. {
  759. evaluationContext.addNonCriticalStrategicalValue(buildThis.townInfo.armyStrength / 50000.0);
  760. if(bi.baseCreatureID == bi.creatureID)
  761. {
  762. evaluationContext.addNonCriticalStrategicalValue((0.5f + 0.1f * bi.creatureLevel) / (float)bi.prerequisitesCount);
  763. evaluationContext.armyReward += bi.armyStrength;
  764. }
  765. else
  766. {
  767. auto potentialUpgradeValue = evaluationContext.evaluator.getUpgradeArmyReward(buildThis.town, bi);
  768. evaluationContext.addNonCriticalStrategicalValue(potentialUpgradeValue / 10000.0f / (float)bi.prerequisitesCount);
  769. evaluationContext.armyReward += potentialUpgradeValue / (float)bi.prerequisitesCount;
  770. }
  771. }
  772. else if(bi.id == BuildingID::CITADEL || bi.id == BuildingID::CASTLE)
  773. {
  774. evaluationContext.addNonCriticalStrategicalValue(buildThis.town->creatures.size() * 0.2f);
  775. evaluationContext.armyReward += buildThis.townInfo.armyStrength / 2;
  776. }
  777. else
  778. {
  779. auto goldPreasure = evaluationContext.evaluator.ai->buildAnalyzer->getGoldPreasure();
  780. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.goldReward * goldPreasure / 3500.0f / bi.prerequisitesCount);
  781. }
  782. if(bi.notEnoughRes && bi.prerequisitesCount == 1)
  783. {
  784. evaluationContext.strategicalValue /= 2;
  785. }
  786. }
  787. };
  788. uint64_t RewardEvaluator::getUpgradeArmyReward(const CGTownInstance * town, const BuildingInfo & bi) const
  789. {
  790. if(ai->buildAnalyzer->hasAnyBuilding(town->subID, bi.id))
  791. return 0;
  792. auto creaturesToUpgrade = ai->armyManager->getTotalCreaturesAvailable(bi.baseCreatureID);
  793. auto upgradedPower = ai->armyManager->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  794. return upgradedPower - creaturesToUpgrade.power;
  795. }
  796. PriorityEvaluator::PriorityEvaluator(const Nullkiller * ai)
  797. :ai(ai)
  798. {
  799. initVisitTile();
  800. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>(ai));
  801. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  802. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>(ai));
  803. evaluationContextBuilders.push_back(std::make_shared<HeroExchangeEvaluator>());
  804. evaluationContextBuilders.push_back(std::make_shared<ArmyUpgradeEvaluator>());
  805. evaluationContextBuilders.push_back(std::make_shared<DefendTownEvaluator>());
  806. evaluationContextBuilders.push_back(std::make_shared<ExchangeSwapTownHeroesContextBuilder>());
  807. evaluationContextBuilders.push_back(std::make_shared<DismissHeroContextBuilder>(ai));
  808. }
  809. EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  810. {
  811. Goals::TGoalVec parts;
  812. EvaluationContext context(ai);
  813. if(goal->goalType == Goals::COMPOSITION)
  814. {
  815. parts = goal->decompose();
  816. }
  817. else
  818. {
  819. parts.push_back(goal);
  820. }
  821. for(auto subgoal : parts)
  822. {
  823. context.goldCost += subgoal->goldCost;
  824. for(auto builder : evaluationContextBuilders)
  825. {
  826. builder->buildEvaluationContext(context, subgoal);
  827. }
  828. }
  829. return context;
  830. }
  831. float PriorityEvaluator::evaluate(Goals::TSubgoal task)
  832. {
  833. auto evaluationContext = buildEvaluationContext(task);
  834. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  835. + (evaluationContext.armyReward > 0 ? 1 : 0)
  836. + (evaluationContext.skillReward > 0 ? 1 : 0)
  837. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  838. double result = 0;
  839. try
  840. {
  841. armyLossPersentageVariable->setValue(evaluationContext.armyLossPersentage);
  842. heroRoleVariable->setValue(evaluationContext.heroRole);
  843. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  844. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  845. goldRewardVariable->setValue(evaluationContext.goldReward);
  846. armyRewardVariable->setValue(evaluationContext.armyReward);
  847. armyGrowthVariable->setValue(evaluationContext.armyGrowth);
  848. skillRewardVariable->setValue(evaluationContext.skillReward);
  849. dangerVariable->setValue(evaluationContext.danger);
  850. rewardTypeVariable->setValue(rewardType);
  851. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  852. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  853. goldPreasureVariable->setValue(ai->buildAnalyzer->getGoldPreasure());
  854. goldCostVariable->setValue(evaluationContext.goldCost / ((float)ai->getFreeResources()[EGameResID::GOLD] + (float)ai->buildAnalyzer->getDailyIncome()[EGameResID::GOLD] + 1.0f));
  855. turnVariable->setValue(evaluationContext.turn);
  856. fearVariable->setValue(evaluationContext.enemyHeroDangerRatio);
  857. engine->process();
  858. result = value->getValue();
  859. }
  860. catch(fl::Exception & fe)
  861. {
  862. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  863. }
  864. #if NKAI_TRACE_LEVEL >= 2
  865. logAi->trace("Evaluated %s, loss: %f, turn: %d, turns main: %f, scout: %f, gold: %d, cost: %d, army gain: %d, danger: %d, role: %s, strategical value: %f, cwr: %f, fear: %f, result %f",
  866. task->toString(),
  867. evaluationContext.armyLossPersentage,
  868. (int)evaluationContext.turn,
  869. evaluationContext.movementCostByRole[HeroRole::MAIN],
  870. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  871. evaluationContext.goldReward,
  872. evaluationContext.goldCost,
  873. evaluationContext.armyReward,
  874. evaluationContext.danger,
  875. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  876. evaluationContext.strategicalValue,
  877. evaluationContext.closestWayRatio,
  878. evaluationContext.enemyHeroDangerRatio,
  879. result);
  880. #endif
  881. return result;
  882. }
  883. }