PriorityEvaluator.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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. if(auto * m = dynamic_cast<const IMarket *>(target))
  260. {
  261. if(m->allowsTrade(EMarketMode::RESOURCE_SKILL))
  262. return 2000;
  263. }
  264. switch(target->ID)
  265. {
  266. case Obj::HILL_FORT:
  267. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeCost[EGameResID::GOLD];
  268. case Obj::SCHOOL_OF_MAGIC:
  269. case Obj::SCHOOL_OF_WAR:
  270. return 1000;
  271. case Obj::CREATURE_GENERATOR1:
  272. case Obj::CREATURE_GENERATOR2:
  273. case Obj::CREATURE_GENERATOR3:
  274. case Obj::CREATURE_GENERATOR4:
  275. return getDwellingArmyCost(target);
  276. default:
  277. return 0;
  278. }
  279. }
  280. float RewardEvaluator::getEnemyHeroStrategicalValue(const CGHeroInstance * enemy) const
  281. {
  282. auto objectsUnderTreat = ai->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  283. float objectValue = 0;
  284. for(auto obj : objectsUnderTreat)
  285. {
  286. vstd::amax(objectValue, getStrategicalValue(obj));
  287. }
  288. /*
  289. 1. If an enemy hero can attack nearby object, it's not useful to capture the object on our own.
  290. Killing the hero is almost as important (0.9) as capturing the object itself.
  291. 2. The formula quickly approaches 1.0 as hero level increases,
  292. but higher level always means higher value and the minimal value for level 1 hero is 0.5
  293. */
  294. return std::min(1.0f, objectValue * 0.9f + (1.0f - (1.0f / (1 + enemy->level))));
  295. }
  296. float RewardEvaluator::getResourceRequirementStrength(int resType) const
  297. {
  298. TResources requiredResources = ai->buildAnalyzer->getResourcesRequiredNow();
  299. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  300. if(requiredResources[resType] == 0)
  301. return 0;
  302. if(dailyIncome[resType] == 0)
  303. return 1.0f;
  304. float ratio = (float)requiredResources[resType] / dailyIncome[resType] / 2;
  305. return std::min(ratio, 1.0f);
  306. }
  307. float RewardEvaluator::getTotalResourceRequirementStrength(int resType) const
  308. {
  309. TResources requiredResources = ai->buildAnalyzer->getTotalResourcesRequired();
  310. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  311. if(requiredResources[resType] == 0)
  312. return 0;
  313. float ratio = dailyIncome[resType] == 0
  314. ? (float)requiredResources[resType] / 50.0f
  315. : (float)requiredResources[resType] / dailyIncome[resType] / 50.0f;
  316. return std::min(ratio, 1.0f);
  317. }
  318. float RewardEvaluator::getStrategicalValue(const CGObjectInstance * target) const
  319. {
  320. if(!target)
  321. return 0;
  322. switch(target->ID)
  323. {
  324. case Obj::MINE:
  325. return target->subID == GameResID(EGameResID::GOLD)
  326. ? 0.5f
  327. : 0.4f * getTotalResourceRequirementStrength(target->subID) + 0.1f * getResourceRequirementStrength(target->subID);
  328. case Obj::RESOURCE:
  329. return target->subID == GameResID(EGameResID::GOLD)
  330. ? 0
  331. : 0.2f * getTotalResourceRequirementStrength(target->subID) + 0.4f * getResourceRequirementStrength(target->subID);
  332. case Obj::CREATURE_BANK:
  333. {
  334. auto resourceReward = getCreatureBankResources(target, nullptr);
  335. float sum = 0.0f;
  336. for (TResources::nziterator it (resourceReward); it.valid(); it++)
  337. {
  338. //Evaluate resources used for construction. Gold is evaluated separately.
  339. if (it->resType != EGameResID::GOLD)
  340. {
  341. sum += 0.1f * getResourceRequirementStrength(it->resType);
  342. }
  343. }
  344. return sum;
  345. }
  346. case Obj::TOWN:
  347. {
  348. if(ai->buildAnalyzer->getDevelopmentInfo().empty())
  349. return 1;
  350. auto town = dynamic_cast<const CGTownInstance *>(target);
  351. auto fortLevel = town->fortLevel();
  352. auto booster = isAnotherAi(town, *ai->cb) ? 0.3 : 1;
  353. if(town->hasCapitol()) return 1;
  354. if(fortLevel < CGTownInstance::CITADEL)
  355. return booster * (town->hasFort() ? 0.6 : 0.4);
  356. else
  357. return booster * (fortLevel == CGTownInstance::CASTLE ? 0.9 : 0.8);
  358. }
  359. case Obj::HERO:
  360. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  361. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  362. : 0;
  363. default:
  364. return 0;
  365. }
  366. }
  367. float RewardEvaluator::evaluateWitchHutSkillScore(const CGWitchHut * hut, const CGHeroInstance * hero, HeroRole role) const
  368. {
  369. if(!hut->wasVisited(hero->tempOwner))
  370. return role == HeroRole::SCOUT ? 2 : 0;
  371. auto skill = SecondarySkill(hut->ability);
  372. if(hero->getSecSkillLevel(skill) != SecSkillLevel::NONE
  373. || hero->secSkills.size() >= GameConstants::SKILL_PER_HERO)
  374. return 0;
  375. auto score = ai->heroManager->evaluateSecSkill(skill, hero);
  376. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  377. }
  378. float RewardEvaluator::getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role) const
  379. {
  380. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  381. if(!target)
  382. return 0;
  383. switch(target->ID)
  384. {
  385. case Obj::STAR_AXIS:
  386. case Obj::SCHOLAR:
  387. case Obj::SCHOOL_OF_MAGIC:
  388. case Obj::SCHOOL_OF_WAR:
  389. case Obj::GARDEN_OF_REVELATION:
  390. case Obj::MARLETTO_TOWER:
  391. case Obj::MERCENARY_CAMP:
  392. case Obj::SHRINE_OF_MAGIC_GESTURE:
  393. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  394. case Obj::TREE_OF_KNOWLEDGE:
  395. return 1;
  396. case Obj::LEARNING_STONE:
  397. return 1.0f / std::sqrt(hero->level);
  398. case Obj::ARENA:
  399. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  400. return 2;
  401. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  402. return 8;
  403. case Obj::WITCH_HUT:
  404. return evaluateWitchHutSkillScore(dynamic_cast<const CGWitchHut *>(target), hero, role);
  405. case Obj::PANDORAS_BOX:
  406. //Can contains experience, spells, or skills (only on custom maps)
  407. return 2.5f;
  408. case Obj::HERO:
  409. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  410. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  411. : 0;
  412. default:
  413. return 0;
  414. }
  415. }
  416. const HitMapInfo & RewardEvaluator::getEnemyHeroDanger(const int3 & tile, uint8_t turn) const
  417. {
  418. auto & treatNode = ai->dangerHitMap->getTileTreat(tile);
  419. if(treatNode.maximumDanger.danger == 0)
  420. return HitMapInfo::NoTreat;
  421. if(treatNode.maximumDanger.turn <= turn)
  422. return treatNode.maximumDanger;
  423. return treatNode.fastestDanger.turn <= turn ? treatNode.fastestDanger : HitMapInfo::NoTreat;
  424. }
  425. int32_t getArmyCost(const CArmedInstance * army)
  426. {
  427. int32_t value = 0;
  428. for(auto stack : army->Slots())
  429. {
  430. value += stack.second->getCreatureID().toCreature()->getRecruitCost(EGameResID::GOLD) * stack.second->count;
  431. }
  432. return value;
  433. }
  434. /// Gets aproximated reward in gold. Daily income is multiplied by 5
  435. int32_t RewardEvaluator::getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero) const
  436. {
  437. if(!target)
  438. return 0;
  439. const int dailyIncomeMultiplier = 5;
  440. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  441. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  442. auto isGold = target->subID == GameResID(EGameResID::GOLD); // TODO: other resorces could be sold but need to evaluate market power
  443. switch(target->ID)
  444. {
  445. case Obj::RESOURCE:
  446. return isGold ? 600 : 100;
  447. case Obj::TREASURE_CHEST:
  448. return 1500;
  449. case Obj::WATER_WHEEL:
  450. return 1000;
  451. case Obj::TOWN:
  452. return dailyIncomeMultiplier * estimateTownIncome(ai->cb.get(), target, hero);
  453. case Obj::MINE:
  454. case Obj::ABANDONED_MINE:
  455. return dailyIncomeMultiplier * (isGold ? 1000 : 75);
  456. case Obj::MYSTICAL_GARDEN:
  457. case Obj::WINDMILL:
  458. return 100;
  459. case Obj::CAMPFIRE:
  460. return 800;
  461. case Obj::WAGON:
  462. return 100;
  463. case Obj::CREATURE_BANK:
  464. return getCreatureBankResources(target, hero)[EGameResID::GOLD];
  465. case Obj::CRYPT:
  466. case Obj::DERELICT_SHIP:
  467. return 3000;
  468. case Obj::DRAGON_UTOPIA:
  469. return 10000;
  470. case Obj::SEA_CHEST:
  471. return 1500;
  472. case Obj::PANDORAS_BOX:
  473. return 2500;
  474. case Obj::PRISON:
  475. //Objectively saves us 2500 to hire hero
  476. return GameConstants::HERO_GOLD_COST;
  477. case Obj::HERO:
  478. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  479. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  480. : 0;
  481. default:
  482. return 0;
  483. }
  484. }
  485. class HeroExchangeEvaluator : public IEvaluationContextBuilder
  486. {
  487. public:
  488. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  489. {
  490. if(task->goalType != Goals::HERO_EXCHANGE)
  491. return;
  492. Goals::HeroExchange & heroExchange = dynamic_cast<Goals::HeroExchange &>(*task);
  493. uint64_t armyStrength = heroExchange.getReinforcementArmyStrength();
  494. evaluationContext.strategicalValue += 0.5f * armyStrength / heroExchange.hero.get()->getArmyStrength();
  495. }
  496. };
  497. class ArmyUpgradeEvaluator : public IEvaluationContextBuilder
  498. {
  499. public:
  500. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  501. {
  502. if(task->goalType != Goals::ARMY_UPGRADE)
  503. return;
  504. Goals::ArmyUpgrade & armyUpgrade = dynamic_cast<Goals::ArmyUpgrade &>(*task);
  505. uint64_t upgradeValue = armyUpgrade.getUpgradeValue();
  506. evaluationContext.armyReward += upgradeValue;
  507. evaluationContext.strategicalValue += upgradeValue / (float)armyUpgrade.hero->getArmyStrength();
  508. }
  509. };
  510. void addTileDanger(EvaluationContext & evaluationContext, const int3 & tile, uint8_t turn, uint64_t ourStrength)
  511. {
  512. HitMapInfo enemyDanger = evaluationContext.evaluator.getEnemyHeroDanger(tile, turn);
  513. if(enemyDanger.danger)
  514. {
  515. auto dangerRatio = enemyDanger.danger / (double)ourStrength;
  516. auto enemyHero = evaluationContext.evaluator.ai->cb->getObj(enemyDanger.hero.hid, false);
  517. bool isAI = enemyHero && isAnotherAi(enemyHero, *evaluationContext.evaluator.ai->cb);
  518. if(isAI)
  519. {
  520. dangerRatio *= 1.5; // lets make AI bit more afraid of other AI.
  521. }
  522. vstd::amax(evaluationContext.enemyHeroDangerRatio, dangerRatio);
  523. }
  524. }
  525. class DefendTownEvaluator : public IEvaluationContextBuilder
  526. {
  527. private:
  528. uint64_t townArmyIncome(const CGTownInstance * town) const
  529. {
  530. uint64_t result = 0;
  531. for(auto creatureInfo : town->creatures)
  532. {
  533. if(creatureInfo.second.empty())
  534. continue;
  535. auto creature = creatureInfo.second.back().toCreature();
  536. result += creature->getAIValue() * town->getGrowthInfo(creature->getLevel() - 1).totalGrowth();
  537. }
  538. return result;
  539. }
  540. public:
  541. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  542. {
  543. if(task->goalType != Goals::DEFEND_TOWN)
  544. return;
  545. Goals::DefendTown & defendTown = dynamic_cast<Goals::DefendTown &>(*task);
  546. const CGTownInstance * town = defendTown.town;
  547. auto & treat = defendTown.getTreat();
  548. auto armyIncome = townArmyIncome(town);
  549. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  550. auto strategicalValue = std::sqrt(armyIncome / 20000.0f) + dailyIncome / 3000.0f;
  551. if(evaluationContext.evaluator.ai->buildAnalyzer->getDevelopmentInfo().size() == 1)
  552. strategicalValue = 1;
  553. float multiplier = 1;
  554. if(treat.turn < defendTown.getTurn())
  555. multiplier /= 1 + (defendTown.getTurn() - treat.turn);
  556. evaluationContext.armyReward += armyIncome * multiplier;
  557. evaluationContext.goldReward += dailyIncome * 5 * multiplier;
  558. evaluationContext.strategicalValue += strategicalValue * multiplier;
  559. vstd::amax(evaluationContext.danger, defendTown.getTreat().danger);
  560. addTileDanger(evaluationContext, town->visitablePos(), defendTown.getTurn(), defendTown.getDefenceStrength());
  561. }
  562. };
  563. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  564. {
  565. private:
  566. const Nullkiller * ai;
  567. public:
  568. ExecuteHeroChainEvaluationContextBuilder(const Nullkiller * ai) : ai(ai) {}
  569. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  570. {
  571. if(task->goalType != Goals::EXECUTE_HERO_CHAIN)
  572. return;
  573. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  574. const AIPath & path = chain.getPath();
  575. vstd::amax(evaluationContext.danger, path.getTotalDanger());
  576. evaluationContext.movementCost += path.movementCost();
  577. evaluationContext.closestWayRatio = chain.closestWayRatio;
  578. std::map<const CGHeroInstance *, float> costsPerHero;
  579. for(auto & node : path.nodes)
  580. {
  581. vstd::amax(costsPerHero[node.targetHero], node.cost);
  582. }
  583. for(auto pair : costsPerHero)
  584. {
  585. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(pair.first);
  586. evaluationContext.movementCostByRole[role] += pair.second;
  587. }
  588. auto heroPtr = task->hero;
  589. auto hero = heroPtr.get(ai->cb.get());
  590. bool checkGold = evaluationContext.danger == 0;
  591. auto army = path.heroArmy;
  592. const CGObjectInstance * target = ai->cb->getObj((ObjectInstanceID)task->objid, false);
  593. if (target && ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner) == PlayerRelations::ENEMIES)
  594. {
  595. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero);
  596. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold);
  597. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, evaluationContext.heroRole);
  598. evaluationContext.strategicalValue += evaluationContext.evaluator.getStrategicalValue(target);
  599. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army);
  600. }
  601. vstd::amax(evaluationContext.armyLossPersentage, path.getTotalArmyLoss() / (double)path.getHeroStrength());
  602. evaluationContext.heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(heroPtr);
  603. addTileDanger(evaluationContext, path.targetTile(), path.turn(), path.getHeroStrength());
  604. vstd::amax(evaluationContext.turn, path.turn());
  605. }
  606. };
  607. class ClusterEvaluationContextBuilder : public IEvaluationContextBuilder
  608. {
  609. public:
  610. ClusterEvaluationContextBuilder(const Nullkiller * ai) {}
  611. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  612. {
  613. if(task->goalType != Goals::UNLOCK_CLUSTER)
  614. return;
  615. Goals::UnlockCluster & clusterGoal = dynamic_cast<Goals::UnlockCluster &>(*task);
  616. std::shared_ptr<ObjectCluster> cluster = clusterGoal.getCluster();
  617. auto hero = clusterGoal.hero.get();
  618. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(clusterGoal.hero);
  619. std::vector<std::pair<const CGObjectInstance *, ClusterObjectInfo>> objects(cluster->objects.begin(), cluster->objects.end());
  620. std::sort(objects.begin(), objects.end(), [](std::pair<const CGObjectInstance *, ClusterObjectInfo> o1, std::pair<const CGObjectInstance *, ClusterObjectInfo> o2) -> bool
  621. {
  622. return o1.second.priority > o2.second.priority;
  623. });
  624. int boost = 1;
  625. for(auto objInfo : objects)
  626. {
  627. auto target = objInfo.first;
  628. bool checkGold = objInfo.second.danger == 0;
  629. auto army = hero;
  630. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero) / boost;
  631. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold) / boost;
  632. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, role) / boost;
  633. evaluationContext.strategicalValue += evaluationContext.evaluator.getStrategicalValue(target) / boost;
  634. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army) / boost;
  635. evaluationContext.movementCostByRole[role] += objInfo.second.movementCost / boost;
  636. evaluationContext.movementCost += objInfo.second.movementCost / boost;
  637. vstd::amax(evaluationContext.turn, objInfo.second.turn / boost);
  638. boost <<= 1;
  639. if(boost > 8)
  640. break;
  641. }
  642. }
  643. };
  644. class ExchangeSwapTownHeroesContextBuilder : public IEvaluationContextBuilder
  645. {
  646. public:
  647. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  648. {
  649. if(task->goalType != Goals::EXCHANGE_SWAP_TOWN_HEROES)
  650. return;
  651. Goals::ExchangeSwapTownHeroes & swapCommand = dynamic_cast<Goals::ExchangeSwapTownHeroes &>(*task);
  652. const CGHeroInstance * garrisonHero = swapCommand.getGarrisonHero();
  653. if(garrisonHero && swapCommand.getLockingReason() == HeroLockedReason::DEFENCE)
  654. {
  655. auto defenderRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(garrisonHero);
  656. auto mpLeft = garrisonHero->movement / (float)garrisonHero->maxMovePoints(true);
  657. evaluationContext.movementCost += mpLeft;
  658. evaluationContext.movementCostByRole[defenderRole] += mpLeft;
  659. evaluationContext.heroRole = defenderRole;
  660. }
  661. }
  662. };
  663. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  664. {
  665. public:
  666. virtual void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  667. {
  668. if(task->goalType != Goals::BUILD_STRUCTURE)
  669. return;
  670. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  671. auto & bi = buildThis.buildingInfo;
  672. evaluationContext.goldReward += 7 * bi.dailyIncome[EGameResID::GOLD] / 2; // 7 day income but half we already have
  673. evaluationContext.heroRole = HeroRole::MAIN;
  674. evaluationContext.movementCostByRole[evaluationContext.heroRole] += bi.prerequisitesCount;
  675. evaluationContext.goldCost += bi.buildCostWithPrerequisits[EGameResID::GOLD];
  676. if(bi.creatureID != CreatureID::NONE)
  677. {
  678. evaluationContext.strategicalValue += buildThis.townInfo.armyStrength / 50000.0;
  679. if(bi.baseCreatureID == bi.creatureID)
  680. {
  681. evaluationContext.strategicalValue += (0.5f + 0.1f * bi.creatureLevel) / (float)bi.prerequisitesCount;
  682. evaluationContext.armyReward += bi.armyStrength;
  683. }
  684. else
  685. {
  686. auto potentialUpgradeValue = evaluationContext.evaluator.getUpgradeArmyReward(buildThis.town, bi);
  687. evaluationContext.strategicalValue += potentialUpgradeValue / 10000.0f / (float)bi.prerequisitesCount;
  688. evaluationContext.armyReward += potentialUpgradeValue / (float)bi.prerequisitesCount;
  689. }
  690. }
  691. else if(bi.id == BuildingID::CITADEL || bi.id == BuildingID::CASTLE)
  692. {
  693. evaluationContext.strategicalValue += buildThis.town->creatures.size() * 0.2f;
  694. evaluationContext.armyReward += buildThis.townInfo.armyStrength / 2;
  695. }
  696. else
  697. {
  698. auto goldPreasure = evaluationContext.evaluator.ai->buildAnalyzer->getGoldPreasure();
  699. evaluationContext.strategicalValue += evaluationContext.goldReward * goldPreasure / 3500.0f / bi.prerequisitesCount;
  700. }
  701. if(bi.notEnoughRes && bi.prerequisitesCount == 1)
  702. {
  703. evaluationContext.strategicalValue /= 2;
  704. }
  705. }
  706. };
  707. uint64_t RewardEvaluator::getUpgradeArmyReward(const CGTownInstance * town, const BuildingInfo & bi) const
  708. {
  709. if(ai->buildAnalyzer->hasAnyBuilding(town->subID, bi.id))
  710. return 0;
  711. auto creaturesToUpgrade = ai->armyManager->getTotalCreaturesAvailable(bi.baseCreatureID);
  712. auto upgradedPower = ai->armyManager->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  713. return upgradedPower - creaturesToUpgrade.power;
  714. }
  715. PriorityEvaluator::PriorityEvaluator(const Nullkiller * ai)
  716. :ai(ai)
  717. {
  718. initVisitTile();
  719. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>(ai));
  720. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  721. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>(ai));
  722. evaluationContextBuilders.push_back(std::make_shared<HeroExchangeEvaluator>());
  723. evaluationContextBuilders.push_back(std::make_shared<ArmyUpgradeEvaluator>());
  724. evaluationContextBuilders.push_back(std::make_shared<DefendTownEvaluator>());
  725. evaluationContextBuilders.push_back(std::make_shared<ExchangeSwapTownHeroesContextBuilder>());
  726. }
  727. EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  728. {
  729. Goals::TGoalVec parts;
  730. EvaluationContext context(ai);
  731. if(goal->goalType == Goals::COMPOSITION)
  732. {
  733. parts = goal->decompose();
  734. }
  735. else
  736. {
  737. parts.push_back(goal);
  738. }
  739. for(auto subgoal : parts)
  740. {
  741. context.goldCost += subgoal->goldCost;
  742. for(auto builder : evaluationContextBuilders)
  743. {
  744. builder->buildEvaluationContext(context, subgoal);
  745. }
  746. }
  747. return context;
  748. }
  749. float PriorityEvaluator::evaluate(Goals::TSubgoal task)
  750. {
  751. auto evaluationContext = buildEvaluationContext(task);
  752. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  753. + (evaluationContext.armyReward > 0 ? 1 : 0)
  754. + (evaluationContext.skillReward > 0 ? 1 : 0)
  755. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  756. double result = 0;
  757. try
  758. {
  759. armyLossPersentageVariable->setValue(evaluationContext.armyLossPersentage);
  760. heroRoleVariable->setValue(evaluationContext.heroRole);
  761. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  762. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  763. goldRewardVariable->setValue(evaluationContext.goldReward);
  764. armyRewardVariable->setValue(evaluationContext.armyReward);
  765. skillRewardVariable->setValue(evaluationContext.skillReward);
  766. dangerVariable->setValue(evaluationContext.danger);
  767. rewardTypeVariable->setValue(rewardType);
  768. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  769. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  770. goldPreasureVariable->setValue(ai->buildAnalyzer->getGoldPreasure());
  771. goldCostVariable->setValue(evaluationContext.goldCost / ((float)ai->getFreeResources()[EGameResID::GOLD] + (float)ai->buildAnalyzer->getDailyIncome()[EGameResID::GOLD] + 1.0f));
  772. turnVariable->setValue(evaluationContext.turn);
  773. fearVariable->setValue(evaluationContext.enemyHeroDangerRatio);
  774. engine->process();
  775. result = value->getValue();
  776. }
  777. catch(fl::Exception & fe)
  778. {
  779. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  780. }
  781. #if NKAI_TRACE_LEVEL >= 2
  782. 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",
  783. task->toString(),
  784. evaluationContext.armyLossPersentage,
  785. (int)evaluationContext.turn,
  786. evaluationContext.movementCostByRole[HeroRole::MAIN],
  787. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  788. evaluationContext.goldReward,
  789. evaluationContext.goldCost,
  790. evaluationContext.armyReward,
  791. evaluationContext.danger,
  792. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  793. evaluationContext.strategicalValue,
  794. evaluationContext.closestWayRatio,
  795. evaluationContext.enemyHeroDangerRatio,
  796. result);
  797. #endif
  798. return result;
  799. }
  800. }