BuildAnalyzer.cpp 13 KB

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