BuildAnalyzer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /*
  2. * BuildAnalyzer.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 <boost/range/algorithm/sort.hpp>
  12. #include "../Engine/Nullkiller.h"
  13. #include "../../../lib/entities/building/CBuilding.h"
  14. #include "../../../lib/IGameSettings.h"
  15. #include "../AIUtility.h"
  16. namespace NK2AI
  17. {
  18. TResources BuildAnalyzer::getMissingResourcesNow(const float armyGoldRatio) const
  19. {
  20. TResources result = armyCost;
  21. result[GameResID::GOLD] *= armyGoldRatio;
  22. result += requiredResources;
  23. result -= aiNk->getFreeResources();
  24. result.positive();
  25. return result;
  26. }
  27. TResources BuildAnalyzer::getMissingResourcesInTotal(const float armyGoldRatio) const
  28. {
  29. TResources result = armyCost;
  30. result[GameResID::GOLD] *= armyGoldRatio;
  31. result += totalDevelopmentCost;
  32. result -= aiNk->getFreeResources();
  33. result.positive();
  34. return result;
  35. }
  36. TResources BuildAnalyzer::getFreeResourcesAfterMissingTotal(const float armyGoldRatio) const
  37. {
  38. TResources result = -armyCost;
  39. result[GameResID::GOLD] *= armyGoldRatio;
  40. result -= totalDevelopmentCost;
  41. result += aiNk->getFreeResources();
  42. result.positive();
  43. return result;
  44. }
  45. bool BuildAnalyzer::isGoldPressureOverMax() const
  46. {
  47. return goldPressure > aiNk->settings->getMaxGoldPressure();
  48. }
  49. void BuildAnalyzer::update()
  50. {
  51. logAi->trace("Start BuildAnalyzer::update");
  52. reset();
  53. const auto towns = aiNk->cc->getTownsInfo();
  54. float economyDevelopmentCost = 0;
  55. for(const CGTownInstance * town : towns)
  56. {
  57. if(town->built >= aiNk->cc->getSettings().getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP))
  58. continue; // Not much point in trying anything - can't built in this town anymore today
  59. #if NK2AI_TRACE_LEVEL >= 1
  60. logAi->trace("Checking town %s", town->getNameTranslated());
  61. #endif
  62. developmentInfos.push_back(TownDevelopmentInfo(town));
  63. TownDevelopmentInfo & tdi = developmentInfos.back();
  64. updateDwellings(tdi, aiNk->armyManager, aiNk->cc);
  65. updateOtherBuildings(tdi, aiNk->armyManager, aiNk->cc);
  66. requiredResources += tdi.requiredResources;
  67. totalDevelopmentCost += tdi.townDevelopmentCost;
  68. for(auto building : tdi.toBuild)
  69. {
  70. if (building.dailyIncome[EGameResID::GOLD] > 0)
  71. economyDevelopmentCost += building.buildCostWithPrerequisites[EGameResID::GOLD];
  72. }
  73. armyCost += tdi.armyCost;
  74. #if NK2AI_TRACE_LEVEL >= 1
  75. for(const auto & biToBuild : tdi.toBuild)
  76. logAi->trace("Building preferences %s", biToBuild.toString());
  77. #endif
  78. }
  79. boost::range::sort(developmentInfos, [](const TownDevelopmentInfo & tdi1, const TownDevelopmentInfo & tdi2) -> bool
  80. {
  81. auto val1 = goldApproximate(tdi1.armyCost) - goldApproximate(tdi1.townDevelopmentCost);
  82. auto val2 = goldApproximate(tdi2.armyCost) - goldApproximate(tdi2.townDevelopmentCost);
  83. return val1 > val2;
  84. });
  85. dailyIncome = calculateDailyIncome(aiNk->cc->getMyObjects(), aiNk->cc->getTownsInfo());
  86. goldPressure = calculateGoldPressure(aiNk->getLockedResources()[EGameResID::GOLD],
  87. static_cast<float>(armyCost[EGameResID::GOLD]),
  88. economyDevelopmentCost,
  89. aiNk->getFreeGold(),
  90. static_cast<float>(dailyIncome[EGameResID::GOLD]));
  91. }
  92. void BuildAnalyzer::reset()
  93. {
  94. requiredResources = TResources();
  95. totalDevelopmentCost = TResources();
  96. armyCost = TResources();
  97. developmentInfos.clear();
  98. }
  99. bool BuildAnalyzer::isBuilt(FactionID alignment, BuildingID bid) const
  100. {
  101. for(const auto & tdi : developmentInfos)
  102. {
  103. if(tdi.town->getFactionID() == alignment && tdi.town->hasBuilt(bid))
  104. return true;
  105. }
  106. return false;
  107. }
  108. void TownDevelopmentInfo::addBuildingBuilt(const BuildingInfo & bi)
  109. {
  110. armyCost += bi.armyCost;
  111. armyStrength += bi.armyStrength;
  112. built.push_back(bi);
  113. }
  114. void TownDevelopmentInfo::addBuildingToBuild(const BuildingInfo & bi)
  115. {
  116. townDevelopmentCost += bi.buildCostWithPrerequisites;
  117. townDevelopmentCost += BuildAnalyzer::goldRemove(bi.armyCost);
  118. if (bi.isBuildable)
  119. {
  120. toBuild.push_back(bi);
  121. }
  122. else if (bi.isMissingResources)
  123. {
  124. requiredResources += bi.buildCost;
  125. toBuild.push_back(bi);
  126. }
  127. }
  128. BuildingInfo::BuildingInfo() {}
  129. BuildingInfo::BuildingInfo(
  130. const CBuilding * building,
  131. const CCreature * creature,
  132. CreatureID baseCreature,
  133. const CGTownInstance * town,
  134. const std::unique_ptr<ArmyManager> & armyManager)
  135. {
  136. id = building->bid;
  137. buildCost = building->resources;
  138. buildCostWithPrerequisites = building->resources;
  139. dailyIncome = building->produce;
  140. isBuilt = town->hasBuilt(id);
  141. prerequisitesCount = 1;
  142. name = building->getNameTranslated();
  143. if(creature)
  144. {
  145. creatureGrowth = creature->getGrowth();
  146. creatureID = creature->getId();
  147. baseCreatureID = baseCreature;
  148. creatureUnitCost = creature->getFullRecruitCost();
  149. creatureLevel = creature->getLevel();
  150. if(isBuilt)
  151. {
  152. creatureGrowth = town->creatureGrowth(creatureLevel - 1);
  153. }
  154. else
  155. {
  156. if(id.isDwelling())
  157. {
  158. creatureGrowth = creature->getGrowth();
  159. if(town->hasBuilt(BuildingID::CASTLE))
  160. creatureGrowth *= 2;
  161. else if(town->hasBuilt(BuildingID::CITADEL))
  162. creatureGrowth += creatureGrowth / 2;
  163. }
  164. else
  165. {
  166. creatureGrowth = creature->getHorde();
  167. }
  168. }
  169. armyStrength = armyManager->evaluateStackPower(creature, creatureGrowth);
  170. armyCost = creatureUnitCost * creatureGrowth;
  171. }
  172. }
  173. std::string BuildingInfo::toString() const
  174. {
  175. return name + ", cost: " + buildCost.toString()
  176. + ", creature: " + std::to_string(creatureGrowth) + " x " + std::to_string(creatureLevel)
  177. + " x " + creatureUnitCost.toString()
  178. + ", daily: " + dailyIncome.toString();
  179. }
  180. float BuildAnalyzer::calculateGoldPressure(TResource lockedGold, float armyCostGold, float economyDevelopmentCost, float freeGold, float dailyIncomeGold)
  181. {
  182. auto pressure = (lockedGold + armyCostGold + economyDevelopmentCost) / (1 + 2 * freeGold + dailyIncomeGold * 7.0f);
  183. #if NK2AI_TRACE_LEVEL >= 1
  184. logAi->trace("Gold pressure: %f", pressure);
  185. #endif
  186. return pressure;
  187. }
  188. TResources BuildAnalyzer::calculateDailyIncome(const std::vector<const CGObjectInstance *> & objects, const std::vector<const CGTownInstance *> & townInfos)
  189. {
  190. auto result = TResources();
  191. for(const CGObjectInstance * obj : objects)
  192. {
  193. if(const auto * mine = dynamic_cast<const CGMine *>(obj))
  194. result += mine->dailyIncome();
  195. }
  196. for(const CGTownInstance * town : townInfos)
  197. {
  198. result += town->dailyIncome();
  199. }
  200. return result;
  201. }
  202. void BuildAnalyzer::updateDwellings(TownDevelopmentInfo & developmentInfo, std::unique_ptr<ArmyManager> & armyManager, std::shared_ptr<CCallback> & cc)
  203. {
  204. for(int level = 0; level < developmentInfo.town->getTown()->creatures.size(); level++)
  205. {
  206. #if NK2AI_TRACE_LEVEL >= 1
  207. logAi->trace("Checking dwelling level %d", level);
  208. #endif
  209. std::vector<BuildingID> dwellingsInTown;
  210. for(BuildingID buildID = BuildingID::getDwellingFromLevel(level, 0); buildID.hasValue(); BuildingID::advanceDwelling(buildID))
  211. if(developmentInfo.town->getTown()->buildings.count(buildID) != 0)
  212. dwellingsInTown.push_back(buildID);
  213. // find best, already built dwelling
  214. for (const auto & buildID : boost::adaptors::reverse(dwellingsInTown))
  215. {
  216. if (!developmentInfo.town->hasBuilt(buildID))
  217. continue;
  218. const auto & info = getBuildingOrPrerequisite(developmentInfo.town, buildID, armyManager, cc);
  219. developmentInfo.addBuildingBuilt(info);
  220. break;
  221. }
  222. // find all non-built dwellings that can be built and add them for consideration
  223. for (const auto & buildID : dwellingsInTown)
  224. {
  225. if (developmentInfo.town->hasBuilt(buildID))
  226. continue;
  227. const auto & info = getBuildingOrPrerequisite(developmentInfo.town, buildID, armyManager, cc);
  228. if (info.isBuildable || info.isMissingResources)
  229. developmentInfo.addBuildingToBuild(info);
  230. }
  231. }
  232. }
  233. void BuildAnalyzer::updateOtherBuildings(TownDevelopmentInfo & developmentInfo,
  234. std::unique_ptr<ArmyManager> & armyManager,
  235. std::shared_ptr<CCallback> & cc)
  236. {
  237. logAi->trace("Checking other buildings");
  238. std::vector<std::vector<BuildingID>> otherBuildings = {
  239. {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL},
  240. {BuildingID::MAGES_GUILD_3, BuildingID::MAGES_GUILD_5}
  241. };
  242. if(developmentInfo.built.size() >= 2 && cc->getDate(Date::DAY_OF_WEEK) > 4)
  243. {
  244. otherBuildings.push_back({BuildingID::HORDE_1});
  245. otherBuildings.push_back({BuildingID::HORDE_2});
  246. }
  247. otherBuildings.push_back({ BuildingID::CITADEL, BuildingID::CASTLE });
  248. otherBuildings.push_back({ BuildingID::RESOURCE_SILO });
  249. otherBuildings.push_back({ BuildingID::SPECIAL_1 });
  250. otherBuildings.push_back({ BuildingID::SPECIAL_2 });
  251. otherBuildings.push_back({ BuildingID::SPECIAL_3 });
  252. otherBuildings.push_back({ BuildingID::SPECIAL_4 });
  253. otherBuildings.push_back({ BuildingID::MARKETPLACE });
  254. for(auto & buildingSet : otherBuildings)
  255. {
  256. for(auto & buildingID : buildingSet)
  257. {
  258. if(!developmentInfo.town->hasBuilt(buildingID) && developmentInfo.town->getTown()->buildings.count(buildingID))
  259. {
  260. developmentInfo.addBuildingToBuild(getBuildingOrPrerequisite(developmentInfo.town, buildingID, armyManager, cc));
  261. break;
  262. }
  263. }
  264. }
  265. }
  266. BuildingInfo BuildAnalyzer::getBuildingOrPrerequisite(
  267. const CGTownInstance * town,
  268. BuildingID b,
  269. std::unique_ptr<ArmyManager> & armyManager,
  270. std::shared_ptr<CCallback> & cc,
  271. bool excludeDwellingDependencies)
  272. {
  273. // TODO: Mircea: Remove redundant variable
  274. BuildingID building = b;
  275. const auto * townInfo = town->getTown();
  276. const auto & buildPtr = townInfo->buildings.at(building);
  277. const CCreature * creature = nullptr;
  278. CreatureID baseCreatureID;
  279. int creatureLevelIndex = -1;
  280. int creatureUpgradeNo = 0;
  281. if(b.isDwelling())
  282. {
  283. creatureLevelIndex = BuildingID::getLevelIndexFromDwelling(b);
  284. creatureUpgradeNo = BuildingID::getUpgradeNoFromDwelling(b);
  285. }
  286. else if(b == BuildingID::HORDE_1 || b == BuildingID::HORDE_1_UPGR)
  287. {
  288. creatureLevelIndex = townInfo->hordeLvl.at(0);
  289. }
  290. else if(b == BuildingID::HORDE_2 || b == BuildingID::HORDE_2_UPGR)
  291. {
  292. creatureLevelIndex = townInfo->hordeLvl.at(1);
  293. }
  294. if(creatureLevelIndex >= 0)
  295. {
  296. auto creatures = townInfo->creatures.at(creatureLevelIndex);
  297. auto creatureID = creatures.size() > creatureUpgradeNo
  298. ? creatures.at(creatureUpgradeNo)
  299. : creatures.front();
  300. baseCreatureID = creatures.front();
  301. creature = creatureID.toCreature();
  302. }
  303. auto info = BuildingInfo(buildPtr.get(), creature, baseCreatureID, town, armyManager);
  304. //logAi->trace("checking %s buildInfo %s", info.name, info.toString());
  305. int highestFort = 0;
  306. for (const auto * ti : cc->getTownsInfo())
  307. {
  308. highestFort = std::max(highestFort, static_cast<int>(ti->fortLevel()));
  309. }
  310. if(!town->hasBuilt(building))
  311. {
  312. auto canBuild = cc->canBuildStructure(town, building);
  313. if(canBuild == EBuildingState::ALLOWED)
  314. {
  315. info.isBuildable = true;
  316. }
  317. else if(canBuild == EBuildingState::NO_RESOURCES)
  318. {
  319. //logAi->trace("cant build. Not enough resources. Need %s", info.buildCost.toString());
  320. info.isMissingResources = true;
  321. }
  322. else if(canBuild == EBuildingState::PREREQUIRES)
  323. {
  324. auto buildExpression = town->genBuildingRequirements(building, false);
  325. auto missingBuildings = buildExpression.getFulfillmentCandidates([&](const BuildingID & id) -> bool
  326. {
  327. return town->hasBuilt(id);
  328. });
  329. auto otherDwelling = [](const BuildingID & id) -> bool
  330. {
  331. return id.isDwelling();
  332. };
  333. if(vstd::contains_if(missingBuildings, otherDwelling))
  334. {
  335. #if NK2AI_TRACE_LEVEL >= 1
  336. logAi->trace("Can't build %d. Needs other dwelling %d", b.getNum(), missingBuildings.front().getNum());
  337. #endif
  338. }
  339. else if(missingBuildings[0] != b)
  340. {
  341. #if NK2AI_TRACE_LEVEL >= 1
  342. logAi->trace("Can't build %d. Needs %d", b.getNum(), missingBuildings[0].num);
  343. #endif
  344. BuildingInfo prerequisite = getBuildingOrPrerequisite(town, missingBuildings[0], armyManager, cc, excludeDwellingDependencies);
  345. prerequisite.buildCostWithPrerequisites += info.buildCost;
  346. prerequisite.creatureUnitCost = info.creatureUnitCost;
  347. prerequisite.creatureGrowth = info.creatureGrowth;
  348. prerequisite.creatureLevel = info.creatureLevel;
  349. prerequisite.creatureID = info.creatureID;
  350. prerequisite.baseCreatureID = info.baseCreatureID;
  351. prerequisite.prerequisitesCount++;
  352. prerequisite.armyCost = info.armyCost;
  353. prerequisite.armyStrength = info.armyStrength;
  354. bool haveSameOrBetterFort = false;
  355. if (prerequisite.id == BuildingID::FORT && highestFort >= CGTownInstance::EFortLevel::FORT)
  356. haveSameOrBetterFort = true;
  357. if (prerequisite.id == BuildingID::CITADEL && highestFort >= CGTownInstance::EFortLevel::CITADEL)
  358. haveSameOrBetterFort = true;
  359. if (prerequisite.id == BuildingID::CASTLE && highestFort >= CGTownInstance::EFortLevel::CASTLE)
  360. haveSameOrBetterFort = true;
  361. if(!haveSameOrBetterFort)
  362. prerequisite.dailyIncome = info.dailyIncome;
  363. return prerequisite;
  364. }
  365. else
  366. {
  367. #if NK2AI_TRACE_LEVEL >= 1
  368. logAi->trace("Can't build. The building requires itself as prerequisite");
  369. #endif
  370. return info;
  371. }
  372. }
  373. else
  374. {
  375. #if NK2AI_TRACE_LEVEL >= 1
  376. logAi->trace("Can't build. Reason: %d", static_cast<int>(canBuild));
  377. #endif
  378. }
  379. }
  380. else
  381. {
  382. #if NK2AI_TRACE_LEVEL >= 1
  383. logAi->trace("Dwelling %d exists", b.getNum());
  384. #endif
  385. info.isBuilt = true;
  386. }
  387. return info;
  388. }
  389. TResource BuildAnalyzer::goldApproximate(const TResources & res)
  390. {
  391. // TODO: Mircea: Would it make sense to use the marketplace rate of the player? See ResourceTrader::trade()
  392. return goldApproximate(res[EGameResID::WOOD], EGameResID::WOOD) + goldApproximate(res[EGameResID::MERCURY], EGameResID::MERCURY) +
  393. goldApproximate(res[EGameResID::ORE], EGameResID::ORE) + goldApproximate(res[EGameResID::SULFUR], EGameResID::SULFUR) +
  394. goldApproximate(res[EGameResID::CRYSTAL], EGameResID::CRYSTAL) + goldApproximate(res[EGameResID::GEMS], EGameResID::GEMS) +
  395. goldApproximate(res[EGameResID::GOLD], EGameResID::GOLD);
  396. }
  397. TResource BuildAnalyzer::goldApproximate(const TResource & res, const EGameResID resId)
  398. {
  399. // TODO: Mircea: replace with LIBRARY->objh->resVals[resId]
  400. switch(resId)
  401. {
  402. case EGameResID::WOOD:
  403. case EGameResID::ORE:
  404. return res * 75;
  405. case EGameResID::MERCURY:
  406. case EGameResID::SULFUR:
  407. case EGameResID::CRYSTAL:
  408. case EGameResID::GEMS:
  409. return res * 150;
  410. case EGameResID::GOLD:
  411. return res;
  412. default:
  413. throw std::runtime_error("Unsupported resource ID" + std::to_string(resId));
  414. }
  415. }
  416. TResources BuildAnalyzer::goldRemove(TResources other)
  417. {
  418. TResources copy;
  419. for(int i = 0; i < GameResID::COUNT; ++i)
  420. copy[i] = other[i];
  421. copy[GameResID::GOLD] = 0;
  422. return copy;
  423. }
  424. TResources BuildAnalyzer::goldOnly(TResources other)
  425. {
  426. TResources copy;
  427. copy[GameResID::GOLD] = other[GameResID::GOLD];
  428. return copy;
  429. }
  430. }