PriorityEvaluator.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  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/mapping/CMapDefines.h"
  18. #include "../../../lib/RoadHandler.h"
  19. #include "../../../lib/CCreatureHandler.h"
  20. #include "../../../lib/VCMI_Lib.h"
  21. #include "../../../lib/StartInfo.h"
  22. #include "../../../CCallback.h"
  23. #include "../../../lib/filesystem/Filesystem.h"
  24. #include "../Goals/ExecuteHeroChain.h"
  25. #include "../Goals/BuildThis.h"
  26. #include "../Goals/StayAtTown.h"
  27. #include "../Goals/ExchangeSwapTownHeroes.h"
  28. #include "../Goals/DismissHero.h"
  29. #include "../Markers/UnlockCluster.h"
  30. #include "../Markers/HeroExchange.h"
  31. #include "../Markers/ArmyUpgrade.h"
  32. #include "../Markers/DefendTown.h"
  33. namespace NKAI
  34. {
  35. constexpr 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. conquestValue(0),
  51. evaluator(ai),
  52. enemyHeroDangerRatio(0),
  53. threat(0),
  54. armyGrowth(0),
  55. armyInvolvement(0),
  56. defenseValue(0),
  57. isDefend(false),
  58. threatTurns(INT_MAX),
  59. involvesSailing(false),
  60. isTradeBuilding(false),
  61. isExchange(false),
  62. isArmyUpgrade(false),
  63. isHero(false),
  64. isEnemy(false),
  65. explorePriority(0)
  66. {
  67. }
  68. void EvaluationContext::addNonCriticalStrategicalValue(float value)
  69. {
  70. vstd::amax(strategicalValue, std::min(value, MIN_CRITICAL_VALUE));
  71. }
  72. PriorityEvaluator::~PriorityEvaluator()
  73. {
  74. delete engine;
  75. }
  76. void PriorityEvaluator::initVisitTile()
  77. {
  78. auto file = CResourceHandler::get()->load(ResourcePath("config/ai/nkai/object-priorities.txt"))->readAll();
  79. std::string str = std::string((char *)file.first.get(), file.second);
  80. engine = fl::FllImporter().fromString(str);
  81. armyLossPersentageVariable = engine->getInputVariable("armyLoss");
  82. armyGrowthVariable = engine->getInputVariable("armyGrowth");
  83. heroRoleVariable = engine->getInputVariable("heroRole");
  84. dangerVariable = engine->getInputVariable("danger");
  85. turnVariable = engine->getInputVariable("turn");
  86. mainTurnDistanceVariable = engine->getInputVariable("mainTurnDistance");
  87. scoutTurnDistanceVariable = engine->getInputVariable("scoutTurnDistance");
  88. goldRewardVariable = engine->getInputVariable("goldReward");
  89. armyRewardVariable = engine->getInputVariable("armyReward");
  90. skillRewardVariable = engine->getInputVariable("skillReward");
  91. rewardTypeVariable = engine->getInputVariable("rewardType");
  92. closestHeroRatioVariable = engine->getInputVariable("closestHeroRatio");
  93. strategicalValueVariable = engine->getInputVariable("strategicalValue");
  94. goldPressureVariable = engine->getInputVariable("goldPressure");
  95. goldCostVariable = engine->getInputVariable("goldCost");
  96. fearVariable = engine->getInputVariable("fear");
  97. value = engine->getOutputVariable("Value");
  98. }
  99. bool isAnotherAi(const CGObjectInstance * obj, const CPlayerSpecificInfoCallback & cb)
  100. {
  101. return obj->getOwner().isValidPlayer()
  102. && cb.getStartInfo()->getIthPlayersSettings(obj->getOwner()).isControlledByAI();
  103. }
  104. int32_t estimateTownIncome(CCallback * cb, const CGObjectInstance * target, const CGHeroInstance * hero)
  105. {
  106. auto relations = cb->getPlayerRelations(hero->tempOwner, target->tempOwner);
  107. if(relations != PlayerRelations::ENEMIES)
  108. return 0; // if we already own it, no additional reward will be received by just visiting it
  109. auto booster = isAnotherAi(target, *cb) ? 1 : 2;
  110. auto town = cb->getTown(target->id);
  111. auto fortLevel = town->fortLevel();
  112. if(town->hasCapitol())
  113. return booster * 2000;
  114. // probably well developed town will have city hall
  115. if(fortLevel == CGTownInstance::CASTLE) return booster * 750;
  116. return booster * (town->hasFort() && town->tempOwner != PlayerColor::NEUTRAL ? booster * 500 : 250);
  117. }
  118. int32_t getResourcesGoldReward(const TResources & res)
  119. {
  120. int32_t result = 0;
  121. for(auto r : GameResID::ALL_RESOURCES())
  122. {
  123. if(res[r] > 0)
  124. result += r == EGameResID::GOLD ? res[r] : res[r] * 100;
  125. }
  126. return result;
  127. }
  128. uint64_t getCreatureBankArmyReward(const CGObjectInstance * target, const CGHeroInstance * hero)
  129. {
  130. auto objectInfo = target->getObjectHandler()->getObjectInfo(target->appearance);
  131. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  132. auto creatures = bankInfo->getPossibleCreaturesReward(target->cb);
  133. uint64_t result = 0;
  134. const auto& slots = hero->Slots();
  135. ui64 weakestStackPower = 0;
  136. int duplicatingSlots = getDuplicatingSlots(hero);
  137. if (slots.size() >= GameConstants::ARMY_SIZE)
  138. {
  139. //No free slot, we might discard our weakest stack
  140. weakestStackPower = std::numeric_limits<ui64>().max();
  141. for (const auto & stack : slots)
  142. {
  143. vstd::amin(weakestStackPower, stack.second->getPower());
  144. }
  145. }
  146. for (auto c : creatures)
  147. {
  148. //Only if hero has slot for this creature in the army
  149. auto ccre = dynamic_cast<const CCreature*>(c.data.getType());
  150. if (hero->getSlotFor(ccre).validSlot() || duplicatingSlots > 0)
  151. {
  152. result += (c.data.getType()->getAIValue() * c.data.count) * c.chance;
  153. }
  154. /*else
  155. {
  156. //we will need to discard the weakest stack
  157. result += (c.data.type->getAIValue() * c.data.count - weakestStackPower) * c.chance;
  158. }*/
  159. }
  160. result /= 100; //divide by total chance
  161. return result;
  162. }
  163. uint64_t getDwellingArmyValue(CCallback * cb, const CGObjectInstance * target, bool checkGold)
  164. {
  165. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  166. uint64_t score = 0;
  167. for(auto & creLevel : dwelling->creatures)
  168. {
  169. if(creLevel.first && creLevel.second.size())
  170. {
  171. auto creature = creLevel.second.back().toCreature();
  172. auto creaturesAreFree = creature->getLevel() == 1;
  173. if(!creaturesAreFree && checkGold && !cb->getResourceAmount().canAfford(creature->getFullRecruitCost() * creLevel.first))
  174. continue;
  175. score += creature->getAIValue() * creLevel.first;
  176. }
  177. }
  178. return score;
  179. }
  180. uint64_t getDwellingArmyGrowth(CCallback * cb, const CGObjectInstance * target, PlayerColor myColor)
  181. {
  182. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  183. uint64_t score = 0;
  184. if(dwelling->getOwner() == myColor)
  185. return 0;
  186. for(auto & creLevel : dwelling->creatures)
  187. {
  188. if(creLevel.second.size())
  189. {
  190. auto creature = creLevel.second.back().toCreature();
  191. score += creature->getAIValue() * creature->getGrowth();
  192. }
  193. }
  194. return score;
  195. }
  196. int getDwellingArmyCost(const CGObjectInstance * target)
  197. {
  198. auto dwelling = dynamic_cast<const CGDwelling *>(target);
  199. int cost = 0;
  200. for(auto & creLevel : dwelling->creatures)
  201. {
  202. if(creLevel.first && creLevel.second.size())
  203. {
  204. auto creature = creLevel.second.back().toCreature();
  205. auto creaturesAreFree = creature->getLevel() == 1;
  206. if(!creaturesAreFree)
  207. cost += creature->getFullRecruitCost().marketValue() * creLevel.first;
  208. }
  209. }
  210. return cost;
  211. }
  212. static uint64_t evaluateArtifactArmyValue(const CArtifact * art)
  213. {
  214. if(art->getId() == ArtifactID::SPELL_SCROLL)
  215. return 1500;
  216. auto statsValue =
  217. 10 * art->valOfBonuses(BonusType::MOVEMENT, BonusCustomSubtype::heroMovementLand)
  218. + 1200 * art->valOfBonuses(BonusType::STACKS_SPEED)
  219. + 700 * art->valOfBonuses(BonusType::MORALE)
  220. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::ATTACK))
  221. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::DEFENSE))
  222. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::KNOWLEDGE))
  223. + 700 * art->valOfBonuses(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::SPELL_POWER))
  224. + 500 * art->valOfBonuses(BonusType::LUCK);
  225. auto classValue = 0;
  226. switch(art->aClass)
  227. {
  228. case CArtifact::EartClass::ART_TREASURE:
  229. //FALL_THROUGH
  230. case CArtifact::EartClass::ART_MINOR:
  231. classValue = 1000;
  232. break;
  233. case CArtifact::EartClass::ART_MAJOR:
  234. classValue = 3000;
  235. break;
  236. case CArtifact::EartClass::ART_RELIC:
  237. case CArtifact::EartClass::ART_SPECIAL:
  238. classValue = 8000;
  239. break;
  240. }
  241. return statsValue > classValue ? statsValue : classValue;
  242. }
  243. uint64_t RewardEvaluator::getArmyReward(
  244. const CGObjectInstance * target,
  245. const CGHeroInstance * hero,
  246. const CCreatureSet * army,
  247. bool checkGold) const
  248. {
  249. const float enemyArmyEliminationRewardRatio = 0.5f;
  250. auto relations = ai->cb->getPlayerRelations(target->tempOwner, ai->playerID);
  251. if(!target)
  252. return 0;
  253. switch(target->ID)
  254. {
  255. case Obj::HILL_FORT:
  256. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeValue;
  257. case Obj::CREATURE_GENERATOR1:
  258. case Obj::CREATURE_GENERATOR2:
  259. case Obj::CREATURE_GENERATOR3:
  260. case Obj::CREATURE_GENERATOR4:
  261. return getDwellingArmyValue(ai->cb.get(), target, checkGold);
  262. case Obj::SPELL_SCROLL:
  263. //FALL_THROUGH
  264. case Obj::ARTIFACT:
  265. return evaluateArtifactArmyValue(dynamic_cast<const CGArtifact *>(target)->storedArtifact->getType());
  266. case Obj::HERO:
  267. return relations == PlayerRelations::ENEMIES
  268. ? enemyArmyEliminationRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->getArmyStrength()
  269. : 0;
  270. case Obj::PANDORAS_BOX:
  271. return 5000;
  272. case Obj::MAGIC_WELL:
  273. case Obj::MAGIC_SPRING:
  274. return getManaRecoveryArmyReward(hero);
  275. default:
  276. break;
  277. }
  278. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  279. if(rewardable)
  280. {
  281. auto totalValue = 0;
  282. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  283. {
  284. auto & info = rewardable->configuration.info[index];
  285. auto rewardValue = 0;
  286. if(!info.reward.artifacts.empty())
  287. {
  288. for(auto artID : info.reward.artifacts)
  289. {
  290. const auto * art = dynamic_cast<const CArtifact *>(VLC->artifacts()->getById(artID));
  291. rewardValue += evaluateArtifactArmyValue(art);
  292. }
  293. }
  294. if(!info.reward.creatures.empty())
  295. {
  296. for(const auto & stackInfo : info.reward.creatures)
  297. {
  298. rewardValue += stackInfo.getType()->getAIValue() * stackInfo.getCount();
  299. }
  300. }
  301. totalValue += rewardValue > 0 ? rewardValue / (info.reward.artifacts.size() + info.reward.creatures.size()) : 0;
  302. }
  303. return totalValue;
  304. }
  305. return 0;
  306. }
  307. uint64_t RewardEvaluator::getArmyGrowth(
  308. const CGObjectInstance * target,
  309. const CGHeroInstance * hero,
  310. const CCreatureSet * army) const
  311. {
  312. if(!target)
  313. return 0;
  314. auto relations = ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner);
  315. if(relations != PlayerRelations::ENEMIES)
  316. return 0;
  317. switch(target->ID)
  318. {
  319. case Obj::TOWN:
  320. {
  321. auto town = dynamic_cast<const CGTownInstance *>(target);
  322. auto fortLevel = town->fortLevel();
  323. auto neutral = !town->getOwner().isValidPlayer();
  324. auto booster = isAnotherAi(town, *ai->cb) || neutral ? 1 : 2;
  325. if(fortLevel < CGTownInstance::CITADEL)
  326. return town->hasFort() ? booster * 500 : 0;
  327. else
  328. return booster * (fortLevel == CGTownInstance::CASTLE ? 5000 : 2000);
  329. }
  330. case Obj::CREATURE_GENERATOR1:
  331. case Obj::CREATURE_GENERATOR2:
  332. case Obj::CREATURE_GENERATOR3:
  333. case Obj::CREATURE_GENERATOR4:
  334. return getDwellingArmyGrowth(ai->cb.get(), target, hero->getOwner());
  335. case Obj::ARTIFACT:
  336. // 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.
  337. return 0;
  338. default:
  339. return 0;
  340. }
  341. }
  342. int RewardEvaluator::getGoldCost(const CGObjectInstance * target, const CGHeroInstance * hero, const CCreatureSet * army) const
  343. {
  344. if(!target)
  345. return 0;
  346. if(auto * m = dynamic_cast<const IMarket *>(target))
  347. {
  348. if(m->allowsTrade(EMarketMode::RESOURCE_SKILL))
  349. return 2000;
  350. }
  351. switch(target->ID)
  352. {
  353. case Obj::HILL_FORT:
  354. return ai->armyManager->calculateCreaturesUpgrade(army, target, ai->cb->getResourceAmount()).upgradeCost[EGameResID::GOLD];
  355. case Obj::SCHOOL_OF_MAGIC:
  356. case Obj::SCHOOL_OF_WAR:
  357. return 1000;
  358. case Obj::CREATURE_GENERATOR1:
  359. case Obj::CREATURE_GENERATOR2:
  360. case Obj::CREATURE_GENERATOR3:
  361. case Obj::CREATURE_GENERATOR4:
  362. return getDwellingArmyCost(target);
  363. default:
  364. return 0;
  365. }
  366. }
  367. float RewardEvaluator::getEnemyHeroStrategicalValue(const CGHeroInstance * enemy) const
  368. {
  369. auto objectsUnderTreat = ai->dangerHitMap->getOneTurnAccessibleObjects(enemy);
  370. float objectValue = 0;
  371. for(auto obj : objectsUnderTreat)
  372. {
  373. vstd::amax(objectValue, getStrategicalValue(obj));
  374. }
  375. /*
  376. 1. If an enemy hero can attack nearby object, it's not useful to capture the object on our own.
  377. Killing the hero is almost as important (0.9) as capturing the object itself.
  378. 2. The formula quickly approaches 1.0 as hero level increases,
  379. but higher level always means higher value and the minimal value for level 1 hero is 0.5
  380. */
  381. return std::min(1.5f, objectValue * 0.9f + (1.5f - (1.5f / (1 + enemy->level))));
  382. }
  383. float RewardEvaluator::getResourceRequirementStrength(int resType) const
  384. {
  385. TResources requiredResources = ai->buildAnalyzer->getResourcesRequiredNow();
  386. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  387. if(requiredResources[resType] == 0)
  388. return 0;
  389. if(dailyIncome[resType] == 0)
  390. return 1.0f;
  391. float ratio = (float)requiredResources[resType] / dailyIncome[resType] / 2;
  392. return std::min(ratio, 1.0f);
  393. }
  394. float RewardEvaluator::getTotalResourceRequirementStrength(int resType) const
  395. {
  396. TResources requiredResources = ai->buildAnalyzer->getTotalResourcesRequired();
  397. TResources dailyIncome = ai->buildAnalyzer->getDailyIncome();
  398. if(requiredResources[resType] == 0)
  399. return 0;
  400. float ratio = dailyIncome[resType] == 0
  401. ? (float)requiredResources[resType] / 10.0f
  402. : (float)requiredResources[resType] / dailyIncome[resType] / 20.0f;
  403. return std::min(ratio, 2.0f);
  404. }
  405. uint64_t RewardEvaluator::townArmyGrowth(const CGTownInstance * town) const
  406. {
  407. uint64_t result = 0;
  408. for(auto creatureInfo : town->creatures)
  409. {
  410. if(creatureInfo.second.empty())
  411. continue;
  412. auto creature = creatureInfo.second.back().toCreature();
  413. result += creature->getAIValue() * town->getGrowthInfo(creature->getLevel() - 1).totalGrowth();
  414. }
  415. return result;
  416. }
  417. float RewardEvaluator::getManaRecoveryArmyReward(const CGHeroInstance * hero) const
  418. {
  419. return ai->heroManager->getMagicStrength(hero) * 10000 * (1.0f - std::sqrt(static_cast<float>(hero->mana) / hero->manaLimit()));
  420. }
  421. float RewardEvaluator::getResourceRequirementStrength(const TResources & res) const
  422. {
  423. float sum = 0.0f;
  424. for(TResources::nziterator it(res); it.valid(); it++)
  425. {
  426. //Evaluate resources used for construction. Gold is evaluated separately.
  427. if(it->resType != EGameResID::GOLD)
  428. {
  429. sum += 0.1f * it->resVal * getResourceRequirementStrength(it->resType)
  430. + 0.05f * it->resVal * getTotalResourceRequirementStrength(it->resType);
  431. }
  432. }
  433. return sum;
  434. }
  435. float RewardEvaluator::getStrategicalValue(const CGObjectInstance * target, const CGHeroInstance * hero) const
  436. {
  437. if(!target)
  438. return 0;
  439. switch(target->ID)
  440. {
  441. case Obj::MINE:
  442. {
  443. auto mine = dynamic_cast<const CGMine *>(target);
  444. return mine->producedResource == EGameResID::GOLD
  445. ? 0.5f
  446. : 0.4f * getTotalResourceRequirementStrength(mine->producedResource) + 0.1f * getResourceRequirementStrength(mine->producedResource);
  447. }
  448. case Obj::RESOURCE:
  449. {
  450. auto resource = dynamic_cast<const CGResource *>(target);
  451. TResources res;
  452. res[resource->resourceID()] = resource->amount;
  453. return getResourceRequirementStrength(res);
  454. }
  455. case Obj::TOWN:
  456. {
  457. if(ai->buildAnalyzer->getDevelopmentInfo().empty())
  458. return 10.0f;
  459. auto town = dynamic_cast<const CGTownInstance *>(target);
  460. if(town->getOwner() == ai->playerID)
  461. {
  462. auto armyIncome = townArmyGrowth(town);
  463. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  464. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  465. }
  466. auto fortLevel = town->fortLevel();
  467. auto booster = isAnotherAi(town, *ai->cb) ? 0.4f : 1.0f;
  468. if(town->hasCapitol())
  469. return booster * 1.5;
  470. if(fortLevel < CGTownInstance::CITADEL)
  471. return booster * (town->hasFort() ? 1.0 : 0.8);
  472. else
  473. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  474. }
  475. case Obj::HERO:
  476. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  477. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance *>(target))
  478. : 0;
  479. case Obj::KEYMASTER:
  480. return 0.6f;
  481. default:
  482. break;
  483. }
  484. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  485. if(rewardable && hero)
  486. {
  487. auto resourceReward = 0.0f;
  488. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  489. {
  490. resourceReward += getResourceRequirementStrength(rewardable->configuration.info[index].reward.resources);
  491. }
  492. return resourceReward;
  493. }
  494. return 0;
  495. }
  496. float RewardEvaluator::getConquestValue(const CGObjectInstance* target) const
  497. {
  498. if (!target)
  499. return 0;
  500. if (target->getOwner() == ai->playerID)
  501. return 0;
  502. switch (target->ID)
  503. {
  504. case Obj::TOWN:
  505. {
  506. if (ai->buildAnalyzer->getDevelopmentInfo().empty())
  507. return 10.0f;
  508. auto town = dynamic_cast<const CGTownInstance*>(target);
  509. if (town->getOwner() == ai->playerID)
  510. {
  511. auto armyIncome = townArmyGrowth(town);
  512. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  513. return std::min(1.0f, std::sqrt(armyIncome / 40000.0f)) + std::min(0.3f, dailyIncome / 10000.0f);
  514. }
  515. auto fortLevel = town->fortLevel();
  516. auto booster = 1.0f;
  517. if (town->hasCapitol())
  518. return booster * 1.5;
  519. if (fortLevel < CGTownInstance::CITADEL)
  520. return booster * (town->hasFort() ? 1.0 : 0.8);
  521. else
  522. return booster * (fortLevel == CGTownInstance::CASTLE ? 1.4 : 1.2);
  523. }
  524. case Obj::HERO:
  525. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  526. ? getEnemyHeroStrategicalValue(dynamic_cast<const CGHeroInstance*>(target))
  527. : 0;
  528. case Obj::KEYMASTER:
  529. return 0.6f;
  530. default:
  531. return 0;
  532. }
  533. }
  534. float RewardEvaluator::evaluateWitchHutSkillScore(const CGObjectInstance * hut, const CGHeroInstance * hero, HeroRole role) const
  535. {
  536. auto rewardable = dynamic_cast<const CRewardableObject *>(hut);
  537. assert(rewardable);
  538. auto skill = SecondarySkill(*rewardable->configuration.getVariable("secondarySkill", "gainedSkill"));
  539. if(!hut->wasVisited(hero->tempOwner))
  540. return role == HeroRole::SCOUT ? 2 : 0;
  541. if(hero->getSecSkillLevel(skill) != MasteryLevel::NONE
  542. || hero->secSkills.size() >= GameConstants::SKILL_PER_HERO)
  543. return 0;
  544. auto score = ai->heroManager->evaluateSecSkill(skill, hero);
  545. return score >= 2 ? (role == HeroRole::MAIN ? 10 : 4) : score;
  546. }
  547. float RewardEvaluator::getSkillReward(const CGObjectInstance * target, const CGHeroInstance * hero, HeroRole role) const
  548. {
  549. const float enemyHeroEliminationSkillRewardRatio = 0.5f;
  550. if(!target)
  551. return 0;
  552. switch(target->ID)
  553. {
  554. case Obj::STAR_AXIS:
  555. case Obj::SCHOLAR:
  556. case Obj::SCHOOL_OF_MAGIC:
  557. case Obj::SCHOOL_OF_WAR:
  558. case Obj::GARDEN_OF_REVELATION:
  559. case Obj::MARLETTO_TOWER:
  560. case Obj::MERCENARY_CAMP:
  561. case Obj::TREE_OF_KNOWLEDGE:
  562. return 1;
  563. case Obj::LEARNING_STONE:
  564. return 1.0f / std::sqrt(hero->level);
  565. case Obj::ARENA:
  566. return 2;
  567. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  568. return 0.25f;
  569. case Obj::SHRINE_OF_MAGIC_GESTURE:
  570. return 1.0f;
  571. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  572. return 2.0f;
  573. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  574. return 8;
  575. case Obj::WITCH_HUT:
  576. return evaluateWitchHutSkillScore(target, hero, role);
  577. case Obj::PANDORAS_BOX:
  578. //Can contains experience, spells, or skills (only on custom maps)
  579. return 2.5f;
  580. case Obj::HERO:
  581. return ai->cb->getPlayerRelations(target->tempOwner, ai->playerID) == PlayerRelations::ENEMIES
  582. ? enemyHeroEliminationSkillRewardRatio * dynamic_cast<const CGHeroInstance *>(target)->level
  583. : 0;
  584. default:
  585. break;
  586. }
  587. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  588. if(rewardable)
  589. {
  590. auto totalValue = 0.0f;
  591. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  592. {
  593. auto & info = rewardable->configuration.info[index];
  594. auto rewardValue = 0.0f;
  595. if(!info.reward.spells.empty())
  596. {
  597. for(auto spellID : info.reward.spells)
  598. {
  599. const spells::Spell * spell = VLC->spells()->getById(spellID);
  600. if(hero->canLearnSpell(spell) && !hero->spellbookContainsSpell(spellID))
  601. {
  602. rewardValue += std::sqrt(spell->getLevel()) / 4.0f;
  603. }
  604. }
  605. totalValue += rewardValue / info.reward.spells.size();
  606. }
  607. if(!info.reward.primary.empty())
  608. {
  609. for(auto value : info.reward.primary)
  610. {
  611. totalValue += value;
  612. }
  613. }
  614. }
  615. return totalValue;
  616. }
  617. return 0;
  618. }
  619. const HitMapInfo & RewardEvaluator::getEnemyHeroDanger(const int3 & tile, uint8_t turn) const
  620. {
  621. auto & treatNode = ai->dangerHitMap->getTileThreat(tile);
  622. if(treatNode.maximumDanger.danger == 0)
  623. return HitMapInfo::NoThreat;
  624. if(treatNode.maximumDanger.turn <= turn)
  625. return treatNode.maximumDanger;
  626. return treatNode.fastestDanger.turn <= turn ? treatNode.fastestDanger : HitMapInfo::NoThreat;
  627. }
  628. int32_t getArmyCost(const CArmedInstance * army)
  629. {
  630. int32_t value = 0;
  631. for(auto stack : army->Slots())
  632. {
  633. value += stack.second->getCreatureID().toCreature()->getFullRecruitCost().marketValue() * stack.second->count;
  634. }
  635. return value;
  636. }
  637. int32_t RewardEvaluator::getGoldReward(const CGObjectInstance * target, const CGHeroInstance * hero) const
  638. {
  639. if(!target)
  640. return 0;
  641. auto relations = ai->cb->getPlayerRelations(target->tempOwner, hero->tempOwner);
  642. const int dailyIncomeMultiplier = 5;
  643. const float enemyArmyEliminationGoldRewardRatio = 0.2f;
  644. const int32_t heroEliminationBonus = GameConstants::HERO_GOLD_COST / 2;
  645. switch(target->ID)
  646. {
  647. case Obj::RESOURCE:
  648. {
  649. auto * res = dynamic_cast<const CGResource*>(target);
  650. return res && res->resourceID() == GameResID::GOLD ? 600 : 100;
  651. }
  652. case Obj::TREASURE_CHEST:
  653. return 1500;
  654. case Obj::WATER_WHEEL:
  655. return 1000;
  656. case Obj::TOWN:
  657. return dailyIncomeMultiplier * estimateTownIncome(ai->cb.get(), target, hero);
  658. case Obj::MINE:
  659. case Obj::ABANDONED_MINE:
  660. {
  661. auto * mine = dynamic_cast<const CGMine*>(target);
  662. return dailyIncomeMultiplier * (mine->producedResource == GameResID::GOLD ? 1000 : 75);
  663. }
  664. case Obj::PANDORAS_BOX:
  665. return 2500;
  666. case Obj::PRISON:
  667. //Objectively saves us 2500 to hire hero
  668. return GameConstants::HERO_GOLD_COST;
  669. case Obj::HERO:
  670. return relations == PlayerRelations::ENEMIES
  671. ? heroEliminationBonus + enemyArmyEliminationGoldRewardRatio * getArmyCost(dynamic_cast<const CGHeroInstance *>(target))
  672. : 0;
  673. default:
  674. break;
  675. }
  676. auto rewardable = dynamic_cast<const Rewardable::Interface *>(target);
  677. if(rewardable)
  678. {
  679. auto goldReward = 0;
  680. for(int index : rewardable->getAvailableRewards(hero, Rewardable::EEventType::EVENT_FIRST_VISIT))
  681. {
  682. auto & info = rewardable->configuration.info[index];
  683. goldReward += getResourcesGoldReward(info.reward.resources);
  684. }
  685. return goldReward;
  686. }
  687. return 0;
  688. }
  689. class HeroExchangeEvaluator : public IEvaluationContextBuilder
  690. {
  691. public:
  692. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  693. {
  694. if(task->goalType != Goals::HERO_EXCHANGE)
  695. return;
  696. Goals::HeroExchange & heroExchange = dynamic_cast<Goals::HeroExchange &>(*task);
  697. uint64_t armyStrength = heroExchange.getReinforcementArmyStrength(evaluationContext.evaluator.ai);
  698. evaluationContext.addNonCriticalStrategicalValue(2.0f * armyStrength / (float)heroExchange.hero->getArmyStrength());
  699. evaluationContext.conquestValue += 2.0f * armyStrength / (float)heroExchange.hero->getArmyStrength();
  700. evaluationContext.heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(heroExchange.hero);
  701. evaluationContext.isExchange = true;
  702. }
  703. };
  704. class ArmyUpgradeEvaluator : public IEvaluationContextBuilder
  705. {
  706. public:
  707. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  708. {
  709. if(task->goalType != Goals::ARMY_UPGRADE)
  710. return;
  711. Goals::ArmyUpgrade & armyUpgrade = dynamic_cast<Goals::ArmyUpgrade &>(*task);
  712. uint64_t upgradeValue = armyUpgrade.getUpgradeValue();
  713. evaluationContext.armyReward += upgradeValue;
  714. evaluationContext.addNonCriticalStrategicalValue(upgradeValue / (float)armyUpgrade.hero->getArmyStrength());
  715. evaluationContext.isArmyUpgrade = true;
  716. }
  717. };
  718. class ExplorePointEvaluator : public IEvaluationContextBuilder
  719. {
  720. public:
  721. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  722. {
  723. if(task->goalType != Goals::EXPLORATION_POINT)
  724. return;
  725. int tilesDiscovered = task->value;
  726. evaluationContext.addNonCriticalStrategicalValue(0.03f * tilesDiscovered);
  727. for (auto obj : evaluationContext.evaluator.ai->cb->getVisitableObjs(task->tile))
  728. {
  729. switch (obj->ID.num)
  730. {
  731. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  732. case Obj::MONOLITH_TWO_WAY:
  733. case Obj::SUBTERRANEAN_GATE:
  734. evaluationContext.explorePriority = 1;
  735. break;
  736. case Obj::REDWOOD_OBSERVATORY:
  737. case Obj::PILLAR_OF_FIRE:
  738. evaluationContext.explorePriority = 2;
  739. break;
  740. }
  741. }
  742. if(evaluationContext.evaluator.ai->cb->getTile(task->tile)->roadType != RoadId::NO_ROAD)
  743. evaluationContext.explorePriority = 1;
  744. if (evaluationContext.explorePriority == 0)
  745. evaluationContext.explorePriority = 3;
  746. }
  747. };
  748. class StayAtTownManaRecoveryEvaluator : public IEvaluationContextBuilder
  749. {
  750. public:
  751. void buildEvaluationContext(EvaluationContext& evaluationContext, Goals::TSubgoal task) const override
  752. {
  753. if (task->goalType != Goals::STAY_AT_TOWN)
  754. return;
  755. Goals::StayAtTown& stayAtTown = dynamic_cast<Goals::StayAtTown&>(*task);
  756. evaluationContext.armyReward += evaluationContext.evaluator.getManaRecoveryArmyReward(stayAtTown.getHero());
  757. if (evaluationContext.armyReward == 0)
  758. evaluationContext.isDefend = true;
  759. else
  760. {
  761. evaluationContext.movementCost += stayAtTown.getMovementWasted();
  762. evaluationContext.movementCostByRole[evaluationContext.heroRole] += stayAtTown.getMovementWasted();
  763. }
  764. }
  765. };
  766. void addTileDanger(EvaluationContext & evaluationContext, const int3 & tile, uint8_t turn, uint64_t ourStrength)
  767. {
  768. HitMapInfo enemyDanger = evaluationContext.evaluator.getEnemyHeroDanger(tile, turn);
  769. if(enemyDanger.danger)
  770. {
  771. auto dangerRatio = enemyDanger.danger / (double)ourStrength;
  772. vstd::amax(evaluationContext.enemyHeroDangerRatio, dangerRatio);
  773. vstd::amax(evaluationContext.threat, enemyDanger.threat);
  774. }
  775. }
  776. class DefendTownEvaluator : public IEvaluationContextBuilder
  777. {
  778. public:
  779. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  780. {
  781. if(task->goalType != Goals::DEFEND_TOWN)
  782. return;
  783. Goals::DefendTown & defendTown = dynamic_cast<Goals::DefendTown &>(*task);
  784. const CGTownInstance * town = defendTown.town;
  785. auto & treat = defendTown.getTreat();
  786. auto strategicalValue = evaluationContext.evaluator.getStrategicalValue(town);
  787. float multiplier = 1;
  788. if(treat.turn < defendTown.getTurn())
  789. multiplier /= 1 + (defendTown.getTurn() - treat.turn);
  790. multiplier /= 1.0f + treat.turn / 5.0f;
  791. if(defendTown.getTurn() > 0 && defendTown.isCounterAttack())
  792. {
  793. auto ourSpeed = defendTown.hero->movementPointsLimit(true);
  794. auto enemySpeed = treat.hero.get(evaluationContext.evaluator.ai->cb.get())->movementPointsLimit(true);
  795. if(enemySpeed > ourSpeed) multiplier *= 0.7f;
  796. }
  797. auto dailyIncome = town->dailyIncome()[EGameResID::GOLD];
  798. auto armyGrowth = evaluationContext.evaluator.townArmyGrowth(town);
  799. evaluationContext.armyGrowth += armyGrowth * multiplier;
  800. evaluationContext.goldReward += dailyIncome * 5 * multiplier;
  801. if(evaluationContext.evaluator.ai->buildAnalyzer->getDevelopmentInfo().size() == 1)
  802. vstd::amax(evaluationContext.strategicalValue, 2.5f * multiplier * strategicalValue);
  803. else
  804. evaluationContext.addNonCriticalStrategicalValue(1.7f * multiplier * strategicalValue);
  805. evaluationContext.defenseValue = town->fortLevel();
  806. evaluationContext.isDefend = true;
  807. evaluationContext.threatTurns = treat.turn;
  808. vstd::amax(evaluationContext.danger, defendTown.getTreat().danger);
  809. addTileDanger(evaluationContext, town->visitablePos(), defendTown.getTurn(), defendTown.getDefenceStrength());
  810. }
  811. };
  812. class ExecuteHeroChainEvaluationContextBuilder : public IEvaluationContextBuilder
  813. {
  814. private:
  815. const Nullkiller * ai;
  816. public:
  817. ExecuteHeroChainEvaluationContextBuilder(const Nullkiller * ai) : ai(ai) {}
  818. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  819. {
  820. if(task->goalType != Goals::EXECUTE_HERO_CHAIN)
  821. return;
  822. Goals::ExecuteHeroChain & chain = dynamic_cast<Goals::ExecuteHeroChain &>(*task);
  823. const AIPath & path = chain.getPath();
  824. if (vstd::isAlmostZero(path.movementCost()))
  825. return;
  826. vstd::amax(evaluationContext.danger, path.getTotalDanger());
  827. evaluationContext.movementCost += path.movementCost();
  828. evaluationContext.closestWayRatio = chain.closestWayRatio;
  829. std::map<const CGHeroInstance *, float> costsPerHero;
  830. for(auto & node : path.nodes)
  831. {
  832. vstd::amax(costsPerHero[node.targetHero], node.cost);
  833. if (node.layer == EPathfindingLayer::SAIL)
  834. evaluationContext.involvesSailing = true;
  835. }
  836. float highestCostForSingleHero = 0;
  837. for(auto pair : costsPerHero)
  838. {
  839. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(pair.first);
  840. evaluationContext.movementCostByRole[role] += pair.second;
  841. if (pair.second > highestCostForSingleHero)
  842. highestCostForSingleHero = pair.second;
  843. }
  844. if (highestCostForSingleHero > 1 && costsPerHero.size() > 1)
  845. {
  846. //Chains that involve more than 1 hero doing something for more than a turn are too expensive in my book. They often involved heroes doing nothing just standing there waiting to fulfill their part of the chain.
  847. return;
  848. }
  849. evaluationContext.movementCost *= costsPerHero.size(); //further deincentivise chaining as it often involves bringing back the army afterwards
  850. auto hero = task->hero;
  851. bool checkGold = evaluationContext.danger == 0;
  852. auto army = path.heroArmy;
  853. const CGObjectInstance * target = ai->cb->getObj((ObjectInstanceID)task->objid, false);
  854. auto heroRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(hero);
  855. if(heroRole == HeroRole::MAIN)
  856. evaluationContext.heroRole = heroRole;
  857. if (target)
  858. {
  859. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero);
  860. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold);
  861. evaluationContext.armyGrowth += evaluationContext.evaluator.getArmyGrowth(target, hero, army);
  862. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, heroRole);
  863. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target));
  864. evaluationContext.conquestValue += evaluationContext.evaluator.getConquestValue(target);
  865. if (target->ID == Obj::HERO)
  866. evaluationContext.isHero = true;
  867. if (target->getOwner().isValidPlayer() && ai->cb->getPlayerRelations(ai->playerID, target->getOwner()) == PlayerRelations::ENEMIES)
  868. evaluationContext.isEnemy = true;
  869. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army);
  870. if(evaluationContext.danger > 0)
  871. evaluationContext.skillReward += (float)evaluationContext.danger / (float)hero->getArmyStrength();
  872. }
  873. evaluationContext.armyInvolvement += army->getArmyCost();
  874. vstd::amax(evaluationContext.armyLossPersentage, (float)path.getTotalArmyLoss() / (float)army->getArmyStrength());
  875. addTileDanger(evaluationContext, path.targetTile(), path.turn(), path.getHeroStrength());
  876. vstd::amax(evaluationContext.turn, path.turn());
  877. }
  878. };
  879. class ClusterEvaluationContextBuilder : public IEvaluationContextBuilder
  880. {
  881. public:
  882. ClusterEvaluationContextBuilder(const Nullkiller * ai) {}
  883. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  884. {
  885. if(task->goalType != Goals::UNLOCK_CLUSTER)
  886. return;
  887. Goals::UnlockCluster & clusterGoal = dynamic_cast<Goals::UnlockCluster &>(*task);
  888. std::shared_ptr<ObjectCluster> cluster = clusterGoal.getCluster();
  889. auto hero = clusterGoal.hero;
  890. auto role = evaluationContext.evaluator.ai->heroManager->getHeroRole(hero);
  891. std::vector<std::pair<ObjectInstanceID, ClusterObjectInfo>> objects(cluster->objects.begin(), cluster->objects.end());
  892. std::sort(objects.begin(), objects.end(), [](std::pair<ObjectInstanceID, ClusterObjectInfo> o1, std::pair<ObjectInstanceID, ClusterObjectInfo> o2) -> bool
  893. {
  894. return o1.second.priority > o2.second.priority;
  895. });
  896. int boost = 1;
  897. for(auto & objInfo : objects)
  898. {
  899. auto target = evaluationContext.evaluator.ai->cb->getObj(objInfo.first);
  900. bool checkGold = objInfo.second.danger == 0;
  901. auto army = hero;
  902. evaluationContext.goldReward += evaluationContext.evaluator.getGoldReward(target, hero) / boost;
  903. evaluationContext.armyReward += evaluationContext.evaluator.getArmyReward(target, hero, army, checkGold) / boost;
  904. evaluationContext.skillReward += evaluationContext.evaluator.getSkillReward(target, hero, role) / boost;
  905. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.evaluator.getStrategicalValue(target) / boost);
  906. evaluationContext.conquestValue += evaluationContext.evaluator.getConquestValue(target);
  907. evaluationContext.goldCost += evaluationContext.evaluator.getGoldCost(target, hero, army) / boost;
  908. evaluationContext.movementCostByRole[role] += objInfo.second.movementCost / boost;
  909. evaluationContext.movementCost += objInfo.second.movementCost / boost;
  910. vstd::amax(evaluationContext.turn, objInfo.second.turn / boost);
  911. boost <<= 1;
  912. if(boost > 8)
  913. break;
  914. }
  915. }
  916. };
  917. class ExchangeSwapTownHeroesContextBuilder : public IEvaluationContextBuilder
  918. {
  919. public:
  920. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  921. {
  922. if(task->goalType != Goals::EXCHANGE_SWAP_TOWN_HEROES)
  923. return;
  924. Goals::ExchangeSwapTownHeroes & swapCommand = dynamic_cast<Goals::ExchangeSwapTownHeroes &>(*task);
  925. const CGHeroInstance * garrisonHero = swapCommand.getGarrisonHero();
  926. logAi->trace("buildEvaluationContext ExchangeSwapTownHeroesContextBuilder %s affected objects: %d", swapCommand.toString(), swapCommand.getAffectedObjects().size());
  927. for (auto obj : swapCommand.getAffectedObjects())
  928. {
  929. logAi->trace("affected object: %s", evaluationContext.evaluator.ai->cb->getObj(obj)->getObjectName());
  930. }
  931. if (garrisonHero)
  932. logAi->debug("with %s and %d", garrisonHero->getNameTranslated(), int(swapCommand.getLockingReason()));
  933. if(garrisonHero && swapCommand.getLockingReason() == HeroLockedReason::DEFENCE)
  934. {
  935. auto defenderRole = evaluationContext.evaluator.ai->heroManager->getHeroRole(garrisonHero);
  936. auto mpLeft = garrisonHero->movementPointsRemaining() / (float)garrisonHero->movementPointsLimit(true);
  937. evaluationContext.movementCost += mpLeft;
  938. evaluationContext.movementCostByRole[defenderRole] += mpLeft;
  939. evaluationContext.heroRole = defenderRole;
  940. evaluationContext.isDefend = true;
  941. evaluationContext.armyInvolvement = garrisonHero->getArmyStrength();
  942. logAi->debug("evaluationContext.isDefend: %d", evaluationContext.isDefend);
  943. }
  944. }
  945. };
  946. class DismissHeroContextBuilder : public IEvaluationContextBuilder
  947. {
  948. private:
  949. const Nullkiller * ai;
  950. public:
  951. DismissHeroContextBuilder(const Nullkiller * ai) : ai(ai) {}
  952. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  953. {
  954. if(task->goalType != Goals::DISMISS_HERO)
  955. return;
  956. Goals::DismissHero & dismissCommand = dynamic_cast<Goals::DismissHero &>(*task);
  957. const CGHeroInstance * dismissedHero = dismissCommand.getHero();
  958. auto role = ai->heroManager->getHeroRole(dismissedHero);
  959. auto mpLeft = dismissedHero->movementPointsRemaining();
  960. evaluationContext.movementCost += mpLeft;
  961. evaluationContext.movementCostByRole[role] += mpLeft;
  962. evaluationContext.goldCost += GameConstants::HERO_GOLD_COST + getArmyCost(dismissedHero);
  963. }
  964. };
  965. class BuildThisEvaluationContextBuilder : public IEvaluationContextBuilder
  966. {
  967. public:
  968. void buildEvaluationContext(EvaluationContext & evaluationContext, Goals::TSubgoal task) const override
  969. {
  970. if(task->goalType != Goals::BUILD_STRUCTURE)
  971. return;
  972. Goals::BuildThis & buildThis = dynamic_cast<Goals::BuildThis &>(*task);
  973. auto & bi = buildThis.buildingInfo;
  974. evaluationContext.goldReward += 7 * bi.dailyIncome[EGameResID::GOLD] / 2; // 7 day income but half we already have
  975. evaluationContext.heroRole = HeroRole::MAIN;
  976. evaluationContext.movementCostByRole[evaluationContext.heroRole] += bi.prerequisitesCount;
  977. int32_t cost = bi.buildCost[EGameResID::GOLD];
  978. evaluationContext.goldCost += cost;
  979. evaluationContext.closestWayRatio = 1;
  980. evaluationContext.buildingCost += bi.buildCostWithPrerequisites;
  981. if (bi.id == BuildingID::MARKETPLACE || bi.dailyIncome[EGameResID::WOOD] > 0)
  982. evaluationContext.isTradeBuilding = true;
  983. logAi->trace("Building costs for %s : %s MarketValue: %d",bi.toString(), evaluationContext.buildingCost.toString(), evaluationContext.buildingCost.marketValue());
  984. if(bi.creatureID != CreatureID::NONE)
  985. {
  986. evaluationContext.addNonCriticalStrategicalValue(buildThis.townInfo.armyStrength / 50000.0);
  987. if(bi.baseCreatureID == bi.creatureID)
  988. {
  989. evaluationContext.addNonCriticalStrategicalValue((0.5f + 0.1f * bi.creatureLevel) / (float)bi.prerequisitesCount);
  990. evaluationContext.armyReward += bi.armyStrength;
  991. }
  992. else
  993. {
  994. auto potentialUpgradeValue = evaluationContext.evaluator.getUpgradeArmyReward(buildThis.town, bi);
  995. evaluationContext.addNonCriticalStrategicalValue(potentialUpgradeValue / 10000.0f / (float)bi.prerequisitesCount);
  996. evaluationContext.armyReward += potentialUpgradeValue / (float)bi.prerequisitesCount;
  997. }
  998. }
  999. else if(bi.id == BuildingID::CITADEL || bi.id == BuildingID::CASTLE)
  1000. {
  1001. evaluationContext.addNonCriticalStrategicalValue(buildThis.town->creatures.size() * 0.2f);
  1002. evaluationContext.armyReward += buildThis.townInfo.armyStrength / 2;
  1003. }
  1004. else if(bi.id >= BuildingID::MAGES_GUILD_1 && bi.id <= BuildingID::MAGES_GUILD_5)
  1005. {
  1006. evaluationContext.skillReward += 2 * (bi.id - BuildingID::MAGES_GUILD_1);
  1007. for (auto hero : evaluationContext.evaluator.ai->cb->getHeroesInfo())
  1008. {
  1009. evaluationContext.armyInvolvement += hero->getArmyCost();
  1010. }
  1011. }
  1012. int sameTownBonus = 0;
  1013. for (auto town : evaluationContext.evaluator.ai->cb->getTownsInfo())
  1014. {
  1015. if (buildThis.town->getFaction() == town->getFaction())
  1016. sameTownBonus += town->getTownLevel();
  1017. }
  1018. evaluationContext.armyReward *= sameTownBonus;
  1019. if(evaluationContext.goldReward)
  1020. {
  1021. auto goldPressure = evaluationContext.evaluator.ai->buildAnalyzer->getGoldPressure();
  1022. evaluationContext.addNonCriticalStrategicalValue(evaluationContext.goldReward * goldPressure / 3500.0f / bi.prerequisitesCount);
  1023. }
  1024. if(bi.notEnoughRes && bi.prerequisitesCount == 1)
  1025. {
  1026. evaluationContext.strategicalValue /= 3;
  1027. evaluationContext.movementCostByRole[evaluationContext.heroRole] += 5;
  1028. evaluationContext.turn += 5;
  1029. }
  1030. }
  1031. };
  1032. uint64_t RewardEvaluator::getUpgradeArmyReward(const CGTownInstance * town, const BuildingInfo & bi) const
  1033. {
  1034. if(ai->buildAnalyzer->hasAnyBuilding(town->getFactionID(), bi.id))
  1035. return 0;
  1036. auto creaturesToUpgrade = ai->armyManager->getTotalCreaturesAvailable(bi.baseCreatureID);
  1037. auto upgradedPower = ai->armyManager->evaluateStackPower(bi.creatureID.toCreature(), creaturesToUpgrade.count);
  1038. return upgradedPower - creaturesToUpgrade.power;
  1039. }
  1040. PriorityEvaluator::PriorityEvaluator(const Nullkiller * ai)
  1041. :ai(ai)
  1042. {
  1043. initVisitTile();
  1044. evaluationContextBuilders.push_back(std::make_shared<ExecuteHeroChainEvaluationContextBuilder>(ai));
  1045. evaluationContextBuilders.push_back(std::make_shared<BuildThisEvaluationContextBuilder>());
  1046. evaluationContextBuilders.push_back(std::make_shared<ClusterEvaluationContextBuilder>(ai));
  1047. evaluationContextBuilders.push_back(std::make_shared<HeroExchangeEvaluator>());
  1048. evaluationContextBuilders.push_back(std::make_shared<ArmyUpgradeEvaluator>());
  1049. evaluationContextBuilders.push_back(std::make_shared<DefendTownEvaluator>());
  1050. evaluationContextBuilders.push_back(std::make_shared<ExchangeSwapTownHeroesContextBuilder>());
  1051. evaluationContextBuilders.push_back(std::make_shared<DismissHeroContextBuilder>(ai));
  1052. evaluationContextBuilders.push_back(std::make_shared<StayAtTownManaRecoveryEvaluator>());
  1053. evaluationContextBuilders.push_back(std::make_shared<ExplorePointEvaluator>());
  1054. }
  1055. EvaluationContext PriorityEvaluator::buildEvaluationContext(Goals::TSubgoal goal) const
  1056. {
  1057. Goals::TGoalVec parts;
  1058. EvaluationContext context(ai);
  1059. if(goal->goalType == Goals::COMPOSITION)
  1060. {
  1061. parts = goal->decompose(ai);
  1062. }
  1063. else
  1064. {
  1065. parts.push_back(goal);
  1066. }
  1067. for(auto subgoal : parts)
  1068. {
  1069. context.goldCost += subgoal->goldCost;
  1070. context.buildingCost += subgoal->buildingCost;
  1071. for(auto builder : evaluationContextBuilders)
  1072. {
  1073. builder->buildEvaluationContext(context, subgoal);
  1074. }
  1075. }
  1076. return context;
  1077. }
  1078. float PriorityEvaluator::evaluate(Goals::TSubgoal task, int priorityTier)
  1079. {
  1080. auto evaluationContext = buildEvaluationContext(task);
  1081. int rewardType = (evaluationContext.goldReward > 0 ? 1 : 0)
  1082. + (evaluationContext.armyReward > 0 ? 1 : 0)
  1083. + (evaluationContext.skillReward > 0 ? 1 : 0)
  1084. + (evaluationContext.strategicalValue > 0 ? 1 : 0);
  1085. float goldRewardPerTurn = evaluationContext.goldReward / std::log2f(2 + evaluationContext.movementCost * 10);
  1086. double result = 0;
  1087. if (ai->settings->isUseFuzzy())
  1088. {
  1089. float fuzzyResult = 0;
  1090. try
  1091. {
  1092. armyLossPersentageVariable->setValue(evaluationContext.armyLossPersentage);
  1093. heroRoleVariable->setValue(evaluationContext.heroRole);
  1094. mainTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::MAIN]);
  1095. scoutTurnDistanceVariable->setValue(evaluationContext.movementCostByRole[HeroRole::SCOUT]);
  1096. goldRewardVariable->setValue(goldRewardPerTurn);
  1097. armyRewardVariable->setValue(evaluationContext.armyReward);
  1098. armyGrowthVariable->setValue(evaluationContext.armyGrowth);
  1099. skillRewardVariable->setValue(evaluationContext.skillReward);
  1100. dangerVariable->setValue(evaluationContext.danger);
  1101. rewardTypeVariable->setValue(rewardType);
  1102. closestHeroRatioVariable->setValue(evaluationContext.closestWayRatio);
  1103. strategicalValueVariable->setValue(evaluationContext.strategicalValue);
  1104. goldPressureVariable->setValue(ai->buildAnalyzer->getGoldPressure());
  1105. goldCostVariable->setValue(evaluationContext.goldCost / ((float)ai->getFreeResources()[EGameResID::GOLD] + (float)ai->buildAnalyzer->getDailyIncome()[EGameResID::GOLD] + 1.0f));
  1106. turnVariable->setValue(evaluationContext.turn);
  1107. fearVariable->setValue(evaluationContext.enemyHeroDangerRatio);
  1108. engine->process();
  1109. fuzzyResult = value->getValue();
  1110. }
  1111. catch (fl::Exception& fe)
  1112. {
  1113. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  1114. }
  1115. result = fuzzyResult;
  1116. }
  1117. else
  1118. {
  1119. float score = 0;
  1120. const bool amIInDanger = ai->cb->getTownsInfo().empty() || (evaluationContext.isDefend && evaluationContext.threatTurns == 0);
  1121. const float maxWillingToLose = amIInDanger ? 1 : ai->settings->getMaxArmyLossTarget();
  1122. bool arriveNextWeek = false;
  1123. if (ai->cb->getDate(Date::DAY_OF_WEEK) + evaluationContext.turn > 7 && priorityTier < PriorityTier::FAR_KILL)
  1124. arriveNextWeek = true;
  1125. #if NKAI_TRACE_LEVEL >= 2
  1126. logAi->trace("BEFORE: priorityTier %d, Evaluated %s, loss: %f, turn: %d, turns main: %f, scout: %f, army-involvement: %f, gold: %f, cost: %d, army gain: %f, army growth: %f skill: %f danger: %d, threatTurns: %d, threat: %d, role: %s, strategical value: %f, conquest value: %f cwr: %f, fear: %f, explorePriority: %d isDefend: %d isEnemy: %d arriveNextWeek: %d",
  1127. priorityTier,
  1128. task->toString(),
  1129. evaluationContext.armyLossPersentage,
  1130. (int)evaluationContext.turn,
  1131. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1132. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1133. evaluationContext.armyInvolvement,
  1134. goldRewardPerTurn,
  1135. evaluationContext.goldCost,
  1136. evaluationContext.armyReward,
  1137. evaluationContext.armyGrowth,
  1138. evaluationContext.skillReward,
  1139. evaluationContext.danger,
  1140. evaluationContext.threatTurns,
  1141. evaluationContext.threat,
  1142. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1143. evaluationContext.strategicalValue,
  1144. evaluationContext.conquestValue,
  1145. evaluationContext.closestWayRatio,
  1146. evaluationContext.enemyHeroDangerRatio,
  1147. evaluationContext.explorePriority,
  1148. evaluationContext.isDefend,
  1149. evaluationContext.isEnemy,
  1150. arriveNextWeek);
  1151. #endif
  1152. switch (priorityTier)
  1153. {
  1154. case PriorityTier::INSTAKILL: //Take towns / kill heroes in immediate reach
  1155. {
  1156. if (evaluationContext.turn > 0)
  1157. return 0;
  1158. if(evaluationContext.conquestValue > 0)
  1159. score = evaluationContext.armyInvolvement;
  1160. if (vstd::isAlmostZero(score) || (evaluationContext.enemyHeroDangerRatio > 1 && (evaluationContext.turn > 0 || evaluationContext.isExchange) && !ai->cb->getTownsInfo().empty()))
  1161. return 0;
  1162. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1163. return 0;
  1164. if (evaluationContext.movementCost > 0)
  1165. score /= evaluationContext.movementCost;
  1166. break;
  1167. }
  1168. case PriorityTier::INSTADEFEND: //Defend immediately threatened towns
  1169. {
  1170. if (evaluationContext.isDefend && evaluationContext.threatTurns == 0 && evaluationContext.turn == 0)
  1171. score = evaluationContext.armyInvolvement;
  1172. if (evaluationContext.isEnemy && maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1173. return 0;
  1174. break;
  1175. }
  1176. case PriorityTier::KILL: //Take towns / kill heroes that are further away
  1177. //FALL_THROUGH
  1178. case PriorityTier::FAR_KILL:
  1179. {
  1180. if (evaluationContext.turn > 0 && evaluationContext.isHero)
  1181. return 0;
  1182. if (arriveNextWeek && evaluationContext.isEnemy)
  1183. return 0;
  1184. if (evaluationContext.conquestValue > 0)
  1185. score = evaluationContext.armyInvolvement;
  1186. if (vstd::isAlmostZero(score) || (evaluationContext.enemyHeroDangerRatio > 1 && (evaluationContext.turn > 0 || evaluationContext.isExchange) && !ai->cb->getTownsInfo().empty()))
  1187. return 0;
  1188. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1189. return 0;
  1190. score *= evaluationContext.closestWayRatio;
  1191. if (evaluationContext.movementCost > 0)
  1192. score /= evaluationContext.movementCost;
  1193. break;
  1194. }
  1195. case PriorityTier::UPGRADE:
  1196. {
  1197. if (!evaluationContext.isArmyUpgrade)
  1198. return 0;
  1199. if (evaluationContext.enemyHeroDangerRatio > 1)
  1200. return 0;
  1201. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1202. return 0;
  1203. if (vstd::isAlmostZero(evaluationContext.armyLossPersentage) && evaluationContext.closestWayRatio < 1.0)
  1204. return 0;
  1205. score = 1000;
  1206. if (evaluationContext.movementCost > 0)
  1207. score /= evaluationContext.movementCost;
  1208. break;
  1209. }
  1210. case PriorityTier::HIGH_PRIO_EXPLORE:
  1211. {
  1212. if (evaluationContext.enemyHeroDangerRatio > 1)
  1213. return 0;
  1214. if (evaluationContext.explorePriority != 1)
  1215. return 0;
  1216. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1217. return 0;
  1218. if (vstd::isAlmostZero(evaluationContext.armyLossPersentage) && evaluationContext.closestWayRatio < 1.0)
  1219. return 0;
  1220. score = 1000;
  1221. if (evaluationContext.movementCost > 0)
  1222. score /= evaluationContext.movementCost;
  1223. break;
  1224. }
  1225. case PriorityTier::HUNTER_GATHER: //Collect guarded stuff
  1226. //FALL_THROUGH
  1227. case PriorityTier::FAR_HUNTER_GATHER:
  1228. {
  1229. if (evaluationContext.enemyHeroDangerRatio > 1 && !evaluationContext.isDefend)
  1230. return 0;
  1231. if (evaluationContext.buildingCost.marketValue() > 0)
  1232. return 0;
  1233. if (evaluationContext.isDefend && (evaluationContext.enemyHeroDangerRatio < 1 || evaluationContext.threatTurns > 0 || evaluationContext.turn > 0))
  1234. return 0;
  1235. if (evaluationContext.explorePriority == 3)
  1236. return 0;
  1237. if (evaluationContext.isArmyUpgrade)
  1238. return 0;
  1239. if ((evaluationContext.enemyHeroDangerRatio > 0 && arriveNextWeek) || evaluationContext.enemyHeroDangerRatio > 1)
  1240. return 0;
  1241. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1242. return 0;
  1243. if (vstd::isAlmostZero(evaluationContext.armyLossPersentage) && evaluationContext.closestWayRatio < 1.0)
  1244. return 0;
  1245. score += evaluationContext.strategicalValue * 1000;
  1246. score += evaluationContext.goldReward;
  1247. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossPersentage) * 0.05;
  1248. score += evaluationContext.armyReward;
  1249. score += evaluationContext.armyGrowth;
  1250. score -= evaluationContext.goldCost;
  1251. score -= evaluationContext.armyInvolvement * evaluationContext.armyLossPersentage;
  1252. if (score > 0)
  1253. {
  1254. score = 1000;
  1255. if (evaluationContext.movementCost > 0)
  1256. score /= evaluationContext.movementCost;
  1257. }
  1258. break;
  1259. }
  1260. case PriorityTier::LOW_PRIO_EXPLORE:
  1261. {
  1262. if (evaluationContext.enemyHeroDangerRatio > 1)
  1263. return 0;
  1264. if (evaluationContext.explorePriority != 3)
  1265. return 0;
  1266. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1267. return 0;
  1268. if (evaluationContext.closestWayRatio < 1.0)
  1269. return 0;
  1270. score = 1000;
  1271. if (evaluationContext.movementCost > 0)
  1272. score /= evaluationContext.movementCost;
  1273. break;
  1274. }
  1275. case PriorityTier::DEFEND: //Defend whatever if nothing else is to do
  1276. {
  1277. if (evaluationContext.enemyHeroDangerRatio > 1 && evaluationContext.isExchange)
  1278. return 0;
  1279. if (evaluationContext.isDefend || evaluationContext.isArmyUpgrade)
  1280. score = evaluationContext.armyInvolvement;
  1281. score /= (evaluationContext.turn + 1);
  1282. break;
  1283. }
  1284. case PriorityTier::BUILDINGS: //For buildings and buying army
  1285. {
  1286. if (maxWillingToLose - evaluationContext.armyLossPersentage < 0)
  1287. return 0;
  1288. //If we already have locked resources, we don't look at other buildings
  1289. if (ai->getLockedResources().marketValue() > 0)
  1290. return 0;
  1291. score += evaluationContext.conquestValue * 1000;
  1292. score += evaluationContext.strategicalValue * 1000;
  1293. score += evaluationContext.goldReward;
  1294. score += evaluationContext.skillReward * evaluationContext.armyInvolvement * (1 - evaluationContext.armyLossPersentage) * 0.05;
  1295. score += evaluationContext.armyReward;
  1296. score += evaluationContext.armyGrowth;
  1297. if (evaluationContext.buildingCost.marketValue() > 0)
  1298. {
  1299. if (!evaluationContext.isTradeBuilding && ai->getFreeResources()[EGameResID::WOOD] - evaluationContext.buildingCost[EGameResID::WOOD] < 5 && ai->buildAnalyzer->getDailyIncome()[EGameResID::WOOD] < 1)
  1300. {
  1301. logAi->trace("Should make sure to build market-place instead of %s", task->toString());
  1302. for (auto town : ai->cb->getTownsInfo())
  1303. {
  1304. if (!town->hasBuiltSomeTradeBuilding())
  1305. return 0;
  1306. }
  1307. }
  1308. score += 1000;
  1309. auto resourcesAvailable = evaluationContext.evaluator.ai->getFreeResources();
  1310. auto income = ai->buildAnalyzer->getDailyIncome();
  1311. if(ai->buildAnalyzer->isGoldPressureHigh())
  1312. score /= evaluationContext.buildingCost.marketValue();
  1313. if (!resourcesAvailable.canAfford(evaluationContext.buildingCost))
  1314. {
  1315. TResources needed = evaluationContext.buildingCost - resourcesAvailable;
  1316. needed.positive();
  1317. int turnsTo = needed.maxPurchasableCount(income);
  1318. if (turnsTo == INT_MAX)
  1319. return 0;
  1320. else
  1321. score /= turnsTo;
  1322. }
  1323. }
  1324. else
  1325. {
  1326. if (evaluationContext.enemyHeroDangerRatio > 1 && !evaluationContext.isDefend && vstd::isAlmostZero(evaluationContext.conquestValue))
  1327. return 0;
  1328. }
  1329. break;
  1330. }
  1331. }
  1332. result = score;
  1333. //TODO: Figure out the root cause for why evaluationContext.closestWayRatio has become -nan(ind).
  1334. if (std::isnan(result))
  1335. return 0;
  1336. }
  1337. #if NKAI_TRACE_LEVEL >= 2
  1338. logAi->trace("priorityTier %d, Evaluated %s, loss: %f, turn: %d, turns main: %f, scout: %f, army-involvement: %f, gold: %f, cost: %d, army gain: %f, army growth: %f skill: %f danger: %d, threatTurns: %d, threat: %d, role: %s, strategical value: %f, conquest value: %f cwr: %f, fear: %f, result %f",
  1339. priorityTier,
  1340. task->toString(),
  1341. evaluationContext.armyLossPersentage,
  1342. (int)evaluationContext.turn,
  1343. evaluationContext.movementCostByRole[HeroRole::MAIN],
  1344. evaluationContext.movementCostByRole[HeroRole::SCOUT],
  1345. evaluationContext.armyInvolvement,
  1346. goldRewardPerTurn,
  1347. evaluationContext.goldCost,
  1348. evaluationContext.armyReward,
  1349. evaluationContext.armyGrowth,
  1350. evaluationContext.skillReward,
  1351. evaluationContext.danger,
  1352. evaluationContext.threatTurns,
  1353. evaluationContext.threat,
  1354. evaluationContext.heroRole == HeroRole::MAIN ? "main" : "scout",
  1355. evaluationContext.strategicalValue,
  1356. evaluationContext.conquestValue,
  1357. evaluationContext.closestWayRatio,
  1358. evaluationContext.enemyHeroDangerRatio,
  1359. result);
  1360. #endif
  1361. return result;
  1362. }
  1363. }