ResourceManager.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. switch (obj->subID)
  52. {
  53. case Res::WOOD:
  54. case Res::ORE:
  55. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  56. break;
  57. case Res::GOLD:
  58. case 7: //abandoned mine -> also gold
  59. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  60. break;
  61. default:
  62. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  63. break;
  64. }
  65. }
  66. }
  67. return ret;
  68. }
  69. void ResourceManager::reserveResoures(const TResources & res, Goals::TSubgoal goal)
  70. {
  71. if (!goal->invalid())
  72. tryPush(ResourceObjective(res, goal));
  73. else
  74. logAi->warn("Attempt to reserve resources for Invalid goal");
  75. }
  76. Goals::TSubgoal ResourceManager::collectResourcesForOurGoal(ResourceObjective &o) const
  77. {
  78. auto allResources = cb->getResourceAmount();
  79. auto income = estimateIncome();
  80. Res::ERes resourceType = Res::INVALID;
  81. TResource amountToCollect = 0;
  82. typedef std::pair<Res::ERes, TResource> resPair;
  83. std::map<Res::ERes, TResource> missingResources;
  84. //TODO: unit test for complex resource sets
  85. //sum missing resources of given type for ALL reserved objectives
  86. for (auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  87. {
  88. //choose specific resources we need for this goal (not 0)
  89. for (auto r = Res::ResourceSet::nziterator(o.resources); r.valid(); r++)
  90. missingResources[r->resType] += it->resources[r->resType]; //goal it costs r units of resType
  91. }
  92. for (auto it = Res::ResourceSet::nziterator(o.resources); it.valid(); it++)
  93. {
  94. missingResources[it->resType] -= allResources[it->resType]; //missing = (what we need) - (what we have)
  95. vstd::amax(missingResources[it->resType], 0); // if we have more resources than reserved, we don't need them
  96. }
  97. vstd::erase_if(missingResources, [=](const resPair & p) -> bool
  98. {
  99. return !(p.second); //in case evaluated to 0 or less
  100. });
  101. if (missingResources.empty()) //FIXME: should be unit-tested out
  102. {
  103. logAi->error("We don't need to collect resources %s for goal %s", o.resources.toString(), o.goal->name());
  104. return o.goal;
  105. }
  106. float goalPriority = 10; //arbitrary, will be divided
  107. for (const resPair & p : missingResources)
  108. {
  109. if (!income[p.first]) //prioritize resources with 0 income
  110. {
  111. resourceType = p.first;
  112. amountToCollect = p.second;
  113. goalPriority /= amountToCollect; //need more resources -> lower priority
  114. break;
  115. }
  116. }
  117. if (resourceType == Res::INVALID) //no needed resources has 0 income,
  118. {
  119. //find the one which takes longest to collect
  120. typedef std::pair<Res::ERes, float> timePair;
  121. std::map<Res::ERes, float> daysToEarn;
  122. for (auto it : missingResources)
  123. daysToEarn[it.first] = (float)missingResources[it.first] / income[it.first];
  124. auto incomeComparer = [&income](const timePair & lhs, const timePair & rhs) -> bool
  125. {
  126. //theoretically income can be negative, but that falls into this comparison
  127. return lhs.second < rhs.second;
  128. };
  129. resourceType = boost::max_element(daysToEarn, incomeComparer)->first;
  130. amountToCollect = missingResources[resourceType];
  131. goalPriority /= daysToEarn[resourceType]; //more days - lower priority
  132. }
  133. if (resourceType == Res::GOLD)
  134. goalPriority *= 1000;
  135. //this is abstract goal and might take soem time to complete
  136. return Goals::sptr(Goals::CollectRes(resourceType, amountToCollect).setisAbstract(true));
  137. }
  138. Goals::TSubgoal ResourceManager::whatToDo() const //suggest any goal
  139. {
  140. if (queue.size())
  141. {
  142. auto o = queue.top();
  143. auto allResources = cb->getResourceAmount(); //we don't consider savings, it's out top-priority goal
  144. if (allResources.canAfford(o.resources))
  145. return o.goal;
  146. else //we can't afford even top-priority goal, need to collect resources
  147. return collectResourcesForOurGoal(o);
  148. }
  149. else
  150. return Goals::sptr(Goals::Invalid()); //nothing else to do
  151. }
  152. Goals::TSubgoal ResourceManager::whatToDo(TResources &res, Goals::TSubgoal goal)
  153. {
  154. logAi->trace("ResourceManager: checking goal %s which requires resources %s", goal->name(), res.toString());
  155. TResources accumulatedResources;
  156. auto allResources = cb->getResourceAmount();
  157. ResourceObjective ro(res, goal);
  158. tryPush(ro);
  159. //check if we can afford all the objectives with higher priority first
  160. for (auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  161. {
  162. accumulatedResources += it->resources;
  163. logAi->trace(
  164. "ResourceManager: checking goal %s, accumulatedResources=%s, available=%s",
  165. it->goal->name(),
  166. accumulatedResources.toString(),
  167. allResources.toString());
  168. if(!accumulatedResources.canBeAfforded(allResources))
  169. {
  170. //can't afford
  171. break;
  172. }
  173. else //can afford all goals up to this point
  174. {
  175. if(it->goal == goal)
  176. {
  177. logAi->debug("ResourceManager: can afford goal %s", goal->name());
  178. return goal; //can afford immediately
  179. }
  180. }
  181. }
  182. logAi->debug("ResourceManager: can not afford goal %s", goal->name());
  183. return collectResourcesForOurGoal(ro);
  184. }
  185. bool ResourceManager::containsObjective(Goals::TSubgoal goal) const
  186. {
  187. logAi->trace("Entering ResourceManager.containsObjective goal=%s", goal->name());
  188. dumpToLog();
  189. //TODO: unit tests for once
  190. for (auto objective : queue)
  191. {
  192. if (objective.goal == goal)
  193. return true;
  194. }
  195. return false;
  196. }
  197. bool ResourceManager::notifyGoalCompleted(Goals::TSubgoal goal)
  198. {
  199. logAi->trace("Entering ResourceManager.notifyGoalCompleted goal=%s", goal->name());
  200. if (goal->invalid())
  201. logAi->warn("Attempt to complete Invalid goal");
  202. std::function<bool(const Goals::TSubgoal &)> equivalentGoalsCheck = [goal](const Goals::TSubgoal & x) -> bool
  203. {
  204. return x == goal || x->fulfillsMe(goal);
  205. };
  206. bool removedGoal = removeOutdatedObjectives(equivalentGoalsCheck);
  207. dumpToLog();
  208. return removedGoal;
  209. }
  210. bool ResourceManager::updateGoal(Goals::TSubgoal goal)
  211. {
  212. //we update priority of goal if it is easier or more difficult to complete
  213. if (goal->invalid())
  214. logAi->warn("Attempt to update Invalid goal");
  215. auto it = boost::find_if(queue, [goal](const ResourceObjective & ro) -> bool
  216. {
  217. return ro.goal == goal;
  218. });
  219. if (it != queue.end())
  220. {
  221. it->goal->setpriority(goal->priority);
  222. auto handle = queue.s_handle_from_iterator(it);
  223. queue.update(handle); //restore order
  224. return true;
  225. }
  226. else
  227. return false;
  228. }
  229. void ResourceManager::dumpToLog() const
  230. {
  231. for(auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  232. {
  233. logAi->trace("ResourceManager contains goal %s which requires resources %s", it->goal->name(), it->resources.toString());
  234. }
  235. }
  236. bool ResourceManager::tryPush(const ResourceObjective & o)
  237. {
  238. auto goal = o.goal;
  239. logAi->trace("ResourceManager: Trying to add goal %s which requires resources %s", goal->name(), o.resources.toString());
  240. dumpToLog();
  241. auto it = boost::find_if(queue, [goal](const ResourceObjective & ro) -> bool
  242. {
  243. return ro.goal == goal;
  244. });
  245. if (it != queue.end())
  246. {
  247. auto handle = queue.s_handle_from_iterator(it);
  248. vstd::amax(goal->priority, it->goal->priority); //increase priority if case
  249. //update resources with new value
  250. queue.update(handle, ResourceObjective(o.resources, goal)); //restore order
  251. return false;
  252. }
  253. else
  254. {
  255. queue.push(o); //add new objective
  256. logAi->debug("Reserved resources (%s) for %s", o.resources.toString(), goal->name());
  257. return true;
  258. }
  259. }
  260. bool ResourceManager::hasTasksLeft() const
  261. {
  262. return !queue.empty();
  263. }
  264. bool ResourceManager::removeOutdatedObjectives(std::function<bool(const Goals::TSubgoal &)> predicate)
  265. {
  266. bool removedAnything = false;
  267. while(true)
  268. { //unfortunately we can't use remove_if on heap
  269. auto it = boost::find_if(queue, [&](const ResourceObjective & ro) -> bool
  270. {
  271. return predicate(ro.goal);
  272. });
  273. if(it != queue.end()) //removed at least one
  274. {
  275. logAi->debug("Removing goal %s from ResourceManager.", it->goal->name());
  276. queue.erase(queue.s_handle_from_iterator(it));
  277. removedAnything = true;
  278. }
  279. else
  280. { //found nothing more to remove
  281. break;
  282. }
  283. }
  284. return removedAnything;
  285. }
  286. TResources ResourceManager::reservedResources() const
  287. {
  288. TResources res;
  289. for (auto it : queue) //substract the value of reserved goals
  290. res += it.resources;
  291. return res;
  292. }
  293. TResources ResourceManager::freeResources() const
  294. {
  295. TResources myRes = cb->getResourceAmount();
  296. myRes -= reservedResources(); //substract the value of reserved goals
  297. for (auto & val : myRes)
  298. vstd::amax(val, 0); //never negative
  299. return myRes;
  300. }
  301. TResource ResourceManager::freeGold() const
  302. {
  303. return freeResources()[Res::GOLD];
  304. }
  305. TResources ResourceManager::allResources() const
  306. {
  307. return cb->getResourceAmount();
  308. }
  309. TResource ResourceManager::allGold() const
  310. {
  311. return cb->getResourceAmount()[Res::GOLD];
  312. }