PriorityEvaluator.cpp 30 KB

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