PriorityEvaluator.cpp 36 KB

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