PriorityEvaluator.cpp 30 KB

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