ResourceManager.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*
  2. * ResourceManager.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 "ResourceManager.h"
  12. #include "Goals/Goals.h"
  13. #include "../../CCallback.h"
  14. #include "../../lib/mapObjects/MapObjects.h"
  15. #define GOLD_RESERVE (10000); //at least we'll be able to reach capitol
  16. ResourceObjective::ResourceObjective(const TResources & Res, Goals::TSubgoal Goal)
  17. : resources(Res), goal(Goal)
  18. {
  19. }
  20. bool ResourceObjective::operator<(const ResourceObjective & ro) const
  21. {
  22. return goal->priority < ro.goal->priority;
  23. }
  24. ResourceManager::ResourceManager(CPlayerSpecificInfoCallback * CB, VCAI * AI)
  25. : ai(AI), cb(CB)
  26. {
  27. }
  28. void ResourceManager::init(CPlayerSpecificInfoCallback * CB)
  29. {
  30. cb = CB;
  31. }
  32. void ResourceManager::setAI(VCAI * AI)
  33. {
  34. ai = AI;
  35. }
  36. bool ResourceManager::canAfford(const TResources & cost) const
  37. {
  38. return freeResources().canAfford(cost);
  39. }
  40. TResources ResourceManager::estimateIncome() const
  41. {
  42. TResources ret;
  43. for (const CGTownInstance * t : cb->getTownsInfo())
  44. {
  45. ret += t->dailyIncome();
  46. }
  47. for (const CGObjectInstance * obj : ai->getFlaggedObjects())
  48. {
  49. if (obj->ID == Obj::MINE)
  50. {
  51. auto mine = dynamic_cast<const CGMine*>(obj);
  52. ret += mine->dailyIncome();
  53. }
  54. }
  55. return ret;
  56. }
  57. void ResourceManager::reserveResources(const TResources & res, Goals::TSubgoal goal)
  58. {
  59. if (!goal->invalid())
  60. tryPush(ResourceObjective(res, goal));
  61. else
  62. logAi->warn("Attempt to reserve resources for Invalid goal");
  63. }
  64. Goals::TSubgoal ResourceManager::collectResourcesForOurGoal(ResourceObjective &o) const
  65. {
  66. auto allResources = cb->getResourceAmount();
  67. auto income = estimateIncome();
  68. GameResID resourceType = EGameResID::NONE;
  69. TResource amountToCollect = 0;
  70. using resPair = std::pair<GameResID, TResource>;
  71. std::map<GameResID, TResource> missingResources;
  72. //TODO: unit test for complex resource sets
  73. //sum missing resources of given type for ALL reserved objectives
  74. for (auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  75. {
  76. //choose specific resources we need for this goal (not 0)
  77. for (auto r = ResourceSet::nziterator(o.resources); r.valid(); r++)
  78. missingResources[r->resType] += it->resources[r->resType]; //goal it costs r units of resType
  79. }
  80. for (auto it = ResourceSet::nziterator(o.resources); it.valid(); it++)
  81. {
  82. missingResources[it->resType] -= allResources[it->resType]; //missing = (what we need) - (what we have)
  83. vstd::amax(missingResources[it->resType], 0); // if we have more resources than reserved, we don't need them
  84. }
  85. vstd::erase_if(missingResources, [=](const resPair & p) -> bool
  86. {
  87. return !(p.second); //in case evaluated to 0 or less
  88. });
  89. if (missingResources.empty()) //FIXME: should be unit-tested out
  90. {
  91. logAi->error("We don't need to collect resources %s for goal %s", o.resources.toString(), o.goal->name());
  92. return o.goal;
  93. }
  94. for (const resPair p : missingResources)
  95. {
  96. if (!income[p.first]) //prioritize resources with 0 income
  97. {
  98. resourceType = p.first;
  99. amountToCollect = p.second;
  100. break;
  101. }
  102. }
  103. if (resourceType == EGameResID::NONE) //no needed resources has 0 income,
  104. {
  105. //find the one which takes longest to collect
  106. using timePair = std::pair<GameResID, float>;
  107. std::map<GameResID, float> daysToEarn;
  108. for (auto it : missingResources)
  109. daysToEarn[it.first] = (float)missingResources[it.first] / income[it.first];
  110. auto incomeComparer = [](const timePair & lhs, const timePair & rhs) -> bool
  111. {
  112. //theoretically income can be negative, but that falls into this comparison
  113. return lhs.second < rhs.second;
  114. };
  115. resourceType = boost::max_element(daysToEarn, incomeComparer)->first;
  116. amountToCollect = missingResources[resourceType];
  117. }
  118. //this is abstract goal and might take some time to complete
  119. return Goals::sptr(Goals::CollectRes(resourceType, amountToCollect).setisAbstract(true));
  120. }
  121. Goals::TSubgoal ResourceManager::whatToDo() const //suggest any goal
  122. {
  123. if (queue.size())
  124. {
  125. auto o = queue.top();
  126. auto allResources = cb->getResourceAmount(); //we don't consider savings, it's out top-priority goal
  127. if (allResources.canAfford(o.resources))
  128. return o.goal;
  129. else //we can't afford even top-priority goal, need to collect resources
  130. return collectResourcesForOurGoal(o);
  131. }
  132. else
  133. return Goals::sptr(Goals::Invalid()); //nothing else to do
  134. }
  135. Goals::TSubgoal ResourceManager::whatToDo(TResources &res, Goals::TSubgoal goal)
  136. {
  137. logAi->trace("ResourceManager: checking goal %s which requires resources %s", goal->name(), res.toString());
  138. TResources accumulatedResources;
  139. auto allResources = cb->getResourceAmount();
  140. ResourceObjective ro(res, goal);
  141. tryPush(ro);
  142. //check if we can afford all the objectives with higher priority first
  143. for (auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  144. {
  145. accumulatedResources += it->resources;
  146. logAi->trace(
  147. "ResourceManager: checking goal %s, accumulatedResources=%s, available=%s",
  148. it->goal->name(),
  149. accumulatedResources.toString(),
  150. allResources.toString());
  151. if(!accumulatedResources.canBeAfforded(allResources))
  152. {
  153. //can't afford
  154. break;
  155. }
  156. else //can afford all goals up to this point
  157. {
  158. if(it->goal == goal)
  159. {
  160. logAi->debug("ResourceManager: can afford goal %s", goal->name());
  161. return goal; //can afford immediately
  162. }
  163. }
  164. }
  165. logAi->debug("ResourceManager: can not afford goal %s", goal->name());
  166. return collectResourcesForOurGoal(ro);
  167. }
  168. bool ResourceManager::containsObjective(Goals::TSubgoal goal) const
  169. {
  170. logAi->trace("Entering ResourceManager.containsObjective goal=%s", goal->name());
  171. dumpToLog();
  172. //TODO: unit tests for once
  173. for (auto objective : queue)
  174. {
  175. if (objective.goal == goal)
  176. return true;
  177. }
  178. return false;
  179. }
  180. bool ResourceManager::notifyGoalCompleted(Goals::TSubgoal goal)
  181. {
  182. logAi->trace("Entering ResourceManager.notifyGoalCompleted goal=%s", goal->name());
  183. if (goal->invalid())
  184. logAi->warn("Attempt to complete Invalid goal");
  185. std::function<bool(const Goals::TSubgoal &)> equivalentGoalsCheck = [goal](const Goals::TSubgoal & x) -> bool
  186. {
  187. return x == goal || x->fulfillsMe(goal);
  188. };
  189. bool removedGoal = removeOutdatedObjectives(equivalentGoalsCheck);
  190. dumpToLog();
  191. return removedGoal;
  192. }
  193. bool ResourceManager::updateGoal(Goals::TSubgoal goal)
  194. {
  195. //we update priority of goal if it is easier or more difficult to complete
  196. if (goal->invalid())
  197. logAi->warn("Attempt to update Invalid goal");
  198. auto it = boost::find_if(queue, [goal](const ResourceObjective & ro) -> bool
  199. {
  200. return ro.goal == goal;
  201. });
  202. if (it != queue.end())
  203. {
  204. it->goal->setpriority(goal->priority);
  205. auto handle = queue.s_handle_from_iterator(it);
  206. queue.update(handle); //restore order
  207. return true;
  208. }
  209. else
  210. return false;
  211. }
  212. void ResourceManager::dumpToLog() const
  213. {
  214. for(auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  215. {
  216. logAi->trace("ResourceManager contains goal %s which requires resources %s", it->goal->name(), it->resources.toString());
  217. }
  218. }
  219. bool ResourceManager::tryPush(const ResourceObjective & o)
  220. {
  221. auto goal = o.goal;
  222. logAi->trace("ResourceManager: Trying to add goal %s which requires resources %s", goal->name(), o.resources.toString());
  223. dumpToLog();
  224. auto it = boost::find_if(queue, [goal](const ResourceObjective & ro) -> bool
  225. {
  226. return ro.goal == goal;
  227. });
  228. if (it != queue.end())
  229. {
  230. auto handle = queue.s_handle_from_iterator(it);
  231. vstd::amax(goal->priority, it->goal->priority); //increase priority if case
  232. //update resources with new value
  233. queue.update(handle, ResourceObjective(o.resources, goal)); //restore order
  234. return false;
  235. }
  236. else
  237. {
  238. queue.push(o); //add new objective
  239. logAi->debug("Reserved resources (%s) for %s", o.resources.toString(), goal->name());
  240. return true;
  241. }
  242. }
  243. bool ResourceManager::hasTasksLeft() const
  244. {
  245. return !queue.empty();
  246. }
  247. bool ResourceManager::removeOutdatedObjectives(std::function<bool(const Goals::TSubgoal &)> predicate)
  248. {
  249. bool removedAnything = false;
  250. while(true)
  251. { //unfortunately we can't use remove_if on heap
  252. auto it = boost::find_if(queue, [&](const ResourceObjective & ro) -> bool
  253. {
  254. return predicate(ro.goal);
  255. });
  256. if(it != queue.end()) //removed at least one
  257. {
  258. logAi->debug("Removing goal %s from ResourceManager.", it->goal->name());
  259. queue.erase(queue.s_handle_from_iterator(it));
  260. removedAnything = true;
  261. }
  262. else
  263. { //found nothing more to remove
  264. break;
  265. }
  266. }
  267. return removedAnything;
  268. }
  269. TResources ResourceManager::reservedResources() const
  270. {
  271. TResources res;
  272. for (auto it : queue) //subtract the value of reserved goals
  273. res += it.resources;
  274. return res;
  275. }
  276. TResources ResourceManager::freeResources() const
  277. {
  278. TResources myRes = cb->getResourceAmount();
  279. myRes -= reservedResources(); //subtract the value of reserved goals
  280. for (auto & val : myRes)
  281. vstd::amax(val, 0); //never negative
  282. return myRes;
  283. }
  284. TResource ResourceManager::freeGold() const
  285. {
  286. return freeResources()[EGameResID::GOLD];
  287. }
  288. TResources ResourceManager::allResources() const
  289. {
  290. return cb->getResourceAmount();
  291. }
  292. TResource ResourceManager::allGold() const
  293. {
  294. return cb->getResourceAmount()[EGameResID::GOLD];
  295. }