ResourceManager.cpp 8.7 KB

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