PriorityEvaluator.cpp 29 KB

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