CBonusSystemNode.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. /*
  2. * CBonusSystemNode.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 "CBonusSystemNode.h"
  12. #include "Limiters.h"
  13. #include "Updaters.h"
  14. #include "Propagators.h"
  15. VCMI_LIB_NAMESPACE_BEGIN
  16. std::atomic<int64_t> CBonusSystemNode::treeChanged(1);
  17. constexpr bool CBonusSystemNode::cachingEnabled = true;
  18. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector)
  19. {
  20. auto ret = bonuses.getFirst(selector);
  21. if(ret)
  22. return ret;
  23. TNodes lparents;
  24. getParents(lparents);
  25. for(CBonusSystemNode *pname : lparents)
  26. {
  27. ret = pname->getBonusLocalFirst(selector);
  28. if (ret)
  29. return ret;
  30. }
  31. return nullptr;
  32. }
  33. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector) const
  34. {
  35. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  36. }
  37. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  38. {
  39. for(const auto * elem : parents)
  40. out.insert(elem);
  41. }
  42. void CBonusSystemNode::getParents(TNodes &out)
  43. {
  44. for (auto * elem : parents)
  45. {
  46. out.insert(elem);
  47. }
  48. }
  49. void CBonusSystemNode::getAllParents(TCNodes & out) const //retrieves list of parent nodes (nodes to inherit bonuses from)
  50. {
  51. for(auto * parent : parents)
  52. {
  53. out.insert(parent);
  54. parent->getAllParents(out);
  55. }
  56. }
  57. void CBonusSystemNode::getAllBonusesRec(BonusList &out, const CSelector & selector) const
  58. {
  59. //out has been reserved sufficient capacity at getAllBonuses() call
  60. BonusList beforeUpdate;
  61. TCNodes lparents;
  62. getAllParents(lparents);
  63. if(!lparents.empty())
  64. {
  65. //estimate on how many bonuses are missing yet - must be positive
  66. beforeUpdate.reserve(std::max(out.capacity() - out.size(), bonuses.size()));
  67. }
  68. else
  69. {
  70. beforeUpdate.reserve(bonuses.size()); //at most all local bonuses
  71. }
  72. for(const auto * parent : lparents)
  73. {
  74. parent->getAllBonusesRec(beforeUpdate, selector);
  75. }
  76. bonuses.getAllBonuses(beforeUpdate);
  77. for(const auto & b : beforeUpdate)
  78. {
  79. //We should not run updaters on non-selected bonuses
  80. auto updated = selector(b.get()) && b->updater
  81. ? getUpdatedBonus(b, b->updater)
  82. : b;
  83. //do not add bonus with updater
  84. bool bonusExists = false;
  85. for(const auto & bonus : out)
  86. {
  87. if (bonus == updated)
  88. bonusExists = true;
  89. if (bonus->updater && bonus->updater == updated->updater)
  90. bonusExists = true;
  91. }
  92. if (!bonusExists)
  93. out.push_back(updated);
  94. }
  95. }
  96. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  97. {
  98. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  99. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  100. {
  101. // Exclusive access for one thread
  102. boost::lock_guard<boost::mutex> lock(sync);
  103. // If the bonus system tree changes(state of a single node or the relations to each other) then
  104. // cache all bonus objects. Selector objects doesn't matter.
  105. if (cachedLast != treeChanged)
  106. {
  107. BonusList allBonuses;
  108. allBonuses.reserve(cachedBonuses.capacity()); //we assume we'll get about the same number of bonuses
  109. cachedBonuses.clear();
  110. cachedRequests.clear();
  111. getAllBonusesRec(allBonuses, Selector::all);
  112. limitBonuses(allBonuses, cachedBonuses);
  113. cachedBonuses.stackBonuses();
  114. cachedLast = treeChanged;
  115. }
  116. // If a bonus system request comes with a caching string then look up in the map if there are any
  117. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  118. if(!cachingStr.empty())
  119. {
  120. auto it = cachedRequests.find(cachingStr);
  121. if(it != cachedRequests.end())
  122. {
  123. //Cached list contains bonuses for our query with applied limiters
  124. return it->second;
  125. }
  126. }
  127. //We still don't have the bonuses (didn't returned them from cache)
  128. //Perform bonus selection
  129. auto ret = std::make_shared<BonusList>();
  130. cachedBonuses.getBonuses(*ret, selector, limit);
  131. // Save the results in the cache
  132. if(!cachingStr.empty())
  133. cachedRequests[cachingStr] = ret;
  134. return ret;
  135. }
  136. else
  137. {
  138. return getAllBonusesWithoutCaching(selector, limit, root);
  139. }
  140. }
  141. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  142. {
  143. auto ret = std::make_shared<BonusList>();
  144. // Get bonus results without caching enabled.
  145. BonusList beforeLimiting;
  146. BonusList afterLimiting;
  147. getAllBonusesRec(beforeLimiting, selector);
  148. if(!root || root == this)
  149. {
  150. limitBonuses(beforeLimiting, afterLimiting);
  151. }
  152. else if(root)
  153. {
  154. //We want to limit our query against an external node. We get all its bonuses,
  155. // add the ones we're considering and see if they're cut out by limiters
  156. BonusList rootBonuses;
  157. BonusList limitedRootBonuses;
  158. getAllBonusesRec(rootBonuses, selector);
  159. for(const auto & b : beforeLimiting)
  160. rootBonuses.push_back(b);
  161. root->limitBonuses(rootBonuses, limitedRootBonuses);
  162. for(const auto & b : beforeLimiting)
  163. if(vstd::contains(limitedRootBonuses, b))
  164. afterLimiting.push_back(b);
  165. }
  166. afterLimiting.getBonuses(*ret, selector, limit);
  167. ret->stackBonuses();
  168. return ret;
  169. }
  170. std::shared_ptr<Bonus> CBonusSystemNode::getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr & updater) const
  171. {
  172. assert(updater);
  173. return updater->createUpdatedBonus(b, * this);
  174. }
  175. CBonusSystemNode::CBonusSystemNode(bool isHypotetic):
  176. bonuses(true),
  177. exportedBonuses(true),
  178. nodeType(UNKNOWN),
  179. cachedLast(0),
  180. isHypotheticNode(isHypotetic)
  181. {
  182. }
  183. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType):
  184. bonuses(true),
  185. exportedBonuses(true),
  186. nodeType(NodeType),
  187. cachedLast(0),
  188. isHypotheticNode(false)
  189. {
  190. }
  191. CBonusSystemNode::~CBonusSystemNode()
  192. {
  193. detachFromAll();
  194. if(!children.empty())
  195. {
  196. while(!children.empty())
  197. children.front()->detachFrom(*this);
  198. }
  199. }
  200. void CBonusSystemNode::attachTo(CBonusSystemNode & parent)
  201. {
  202. assert(!vstd::contains(parents, &parent));
  203. parents.push_back(&parent);
  204. if(!isHypothetic())
  205. {
  206. if(parent.actsAsBonusSourceOnly())
  207. parent.newRedDescendant(*this);
  208. else
  209. newRedDescendant(parent);
  210. parent.newChildAttached(*this);
  211. }
  212. CBonusSystemNode::treeHasChanged();
  213. }
  214. void CBonusSystemNode::detachFrom(CBonusSystemNode & parent)
  215. {
  216. assert(vstd::contains(parents, &parent));
  217. if(!isHypothetic())
  218. {
  219. if(parent.actsAsBonusSourceOnly())
  220. parent.removedRedDescendant(*this);
  221. else
  222. removedRedDescendant(parent);
  223. }
  224. if (vstd::contains(parents, &parent))
  225. {
  226. parents -= &parent;
  227. }
  228. else
  229. {
  230. logBonus->error("Error on Detach. Node %s (nodeType=%d) has not parent %s (nodeType=%d)"
  231. , nodeShortInfo(), nodeType, parent.nodeShortInfo(), parent.nodeType);
  232. }
  233. if(!isHypothetic())
  234. {
  235. parent.childDetached(*this);
  236. }
  237. CBonusSystemNode::treeHasChanged();
  238. }
  239. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  240. {
  241. removeBonuses(s);
  242. for(CBonusSystemNode * child : children)
  243. child->removeBonusesRecursive(s);
  244. }
  245. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  246. {
  247. BonusList bl;
  248. exportedBonuses.getBonuses(bl, s, Selector::all);
  249. for(const auto & b : bl)
  250. {
  251. b->turnsRemain--;
  252. if(b->turnsRemain <= 0)
  253. removeBonus(b);
  254. }
  255. for(CBonusSystemNode *child : children)
  256. child->reduceBonusDurations(s);
  257. }
  258. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  259. {
  260. //turnsRemain shouldn't be zero for following durations
  261. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  262. {
  263. assert(b->turnsRemain);
  264. }
  265. assert(!vstd::contains(exportedBonuses, b));
  266. exportedBonuses.push_back(b);
  267. exportBonus(b);
  268. CBonusSystemNode::treeHasChanged();
  269. }
  270. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  271. {
  272. auto bonus = exportedBonuses.getFirst(Selector::typeSubtypeValueType(b->type, b->subtype, b->valType)); //only local bonuses are interesting
  273. if(bonus)
  274. bonus->val += b->val;
  275. else
  276. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  277. }
  278. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  279. {
  280. exportedBonuses -= b;
  281. if(b->propagator)
  282. unpropagateBonus(b);
  283. else
  284. bonuses -= b;
  285. CBonusSystemNode::treeHasChanged();
  286. }
  287. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  288. {
  289. BonusList toRemove;
  290. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  291. for(const auto & bonus : toRemove)
  292. removeBonus(bonus);
  293. }
  294. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  295. {
  296. switch(nodeType)
  297. {
  298. case CREATURE:
  299. case ARTIFACT:
  300. case ARTIFACT_INSTANCE:
  301. return true;
  302. default:
  303. return false;
  304. }
  305. }
  306. void CBonusSystemNode::propagateBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & source)
  307. {
  308. if(b->propagator->shouldBeAttached(this))
  309. {
  310. auto propagated = b->propagationUpdater
  311. ? source.getUpdatedBonus(b, b->propagationUpdater)
  312. : b;
  313. bonuses.push_back(propagated);
  314. logBonus->trace("#$# %s #propagated to# %s", propagated->Description(), nodeName());
  315. }
  316. TNodes lchildren;
  317. getRedChildren(lchildren);
  318. for(CBonusSystemNode *pname : lchildren)
  319. pname->propagateBonus(b, source);
  320. }
  321. void CBonusSystemNode::unpropagateBonus(const std::shared_ptr<Bonus> & b)
  322. {
  323. if(b->propagator->shouldBeAttached(this))
  324. {
  325. bonuses -= b;
  326. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  327. }
  328. TNodes lchildren;
  329. getRedChildren(lchildren);
  330. for(CBonusSystemNode *pname : lchildren)
  331. pname->unpropagateBonus(b);
  332. }
  333. void CBonusSystemNode::newChildAttached(CBonusSystemNode & child)
  334. {
  335. assert(!vstd::contains(children, &child));
  336. children.push_back(&child);
  337. }
  338. void CBonusSystemNode::childDetached(CBonusSystemNode & child)
  339. {
  340. if(vstd::contains(children, &child))
  341. children -= &child;
  342. else
  343. {
  344. logBonus->error("Error on Detach. Node %s (nodeType=%d) is not a child of %s (nodeType=%d)"
  345. , child.nodeShortInfo(), child.nodeType, nodeShortInfo(), nodeType);
  346. }
  347. }
  348. void CBonusSystemNode::detachFromAll()
  349. {
  350. while(!parents.empty())
  351. detachFrom(*parents.front());
  352. }
  353. bool CBonusSystemNode::isIndependentNode() const
  354. {
  355. return parents.empty() && children.empty();
  356. }
  357. std::string CBonusSystemNode::nodeName() const
  358. {
  359. return std::string("Bonus system node of type ") + typeid(*this).name();
  360. }
  361. std::string CBonusSystemNode::nodeShortInfo() const
  362. {
  363. std::ostringstream str;
  364. str << "'" << typeid(* this).name() << "'";
  365. return str.str();
  366. }
  367. void CBonusSystemNode::deserializationFix()
  368. {
  369. exportBonuses();
  370. }
  371. void CBonusSystemNode::getRedParents(TCNodes & out) const
  372. {
  373. TCNodes lparents;
  374. getParents(lparents);
  375. for(const CBonusSystemNode *pname : lparents)
  376. {
  377. if(pname->actsAsBonusSourceOnly())
  378. {
  379. out.insert(pname);
  380. }
  381. }
  382. if(!actsAsBonusSourceOnly())
  383. {
  384. for(CBonusSystemNode *child : children)
  385. {
  386. out.insert(child);
  387. }
  388. }
  389. }
  390. void CBonusSystemNode::getRedChildren(TNodes &out)
  391. {
  392. TNodes lparents;
  393. getParents(lparents);
  394. for(CBonusSystemNode *pname : lparents)
  395. {
  396. if(!pname->actsAsBonusSourceOnly())
  397. {
  398. out.insert(pname);
  399. }
  400. }
  401. if(actsAsBonusSourceOnly())
  402. {
  403. for(CBonusSystemNode *child : children)
  404. {
  405. out.insert(child);
  406. }
  407. }
  408. }
  409. void CBonusSystemNode::newRedDescendant(CBonusSystemNode & descendant)
  410. {
  411. for(const auto & b : exportedBonuses)
  412. {
  413. if(b->propagator)
  414. descendant.propagateBonus(b, *this);
  415. }
  416. TCNodes redParents;
  417. getRedAncestors(redParents); //get all red parents recursively
  418. for(auto * parent : redParents)
  419. {
  420. for(const auto & b : parent->exportedBonuses)
  421. {
  422. if(b->propagator)
  423. descendant.propagateBonus(b, *this);
  424. }
  425. }
  426. }
  427. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode & descendant)
  428. {
  429. for(const auto & b : exportedBonuses)
  430. if(b->propagator)
  431. descendant.unpropagateBonus(b);
  432. TCNodes redParents;
  433. getRedAncestors(redParents); //get all red parents recursively
  434. for(auto * parent : redParents)
  435. {
  436. for(const auto & b : parent->exportedBonuses)
  437. if(b->propagator)
  438. descendant.unpropagateBonus(b);
  439. }
  440. }
  441. void CBonusSystemNode::getRedAncestors(TCNodes &out) const
  442. {
  443. getRedParents(out);
  444. TCNodes redParents;
  445. getRedParents(redParents);
  446. for(const CBonusSystemNode * parent : redParents)
  447. parent->getRedAncestors(out);
  448. }
  449. void CBonusSystemNode::exportBonus(const std::shared_ptr<Bonus> & b)
  450. {
  451. if(b->propagator)
  452. propagateBonus(b, *this);
  453. else
  454. bonuses.push_back(b);
  455. CBonusSystemNode::treeHasChanged();
  456. }
  457. void CBonusSystemNode::exportBonuses()
  458. {
  459. for(const auto & b : exportedBonuses)
  460. exportBonus(b);
  461. }
  462. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  463. {
  464. return nodeType;
  465. }
  466. const TNodesVector& CBonusSystemNode::getParentNodes() const
  467. {
  468. return parents;
  469. }
  470. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  471. {
  472. nodeType = type;
  473. }
  474. BonusList & CBonusSystemNode::getExportedBonusList()
  475. {
  476. return exportedBonuses;
  477. }
  478. const BonusList & CBonusSystemNode::getExportedBonusList() const
  479. {
  480. return exportedBonuses;
  481. }
  482. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  483. {
  484. assert(&allBonuses != &out); //todo should it work in-place?
  485. BonusList undecided = allBonuses;
  486. BonusList & accepted = out;
  487. while(true)
  488. {
  489. int undecidedCount = static_cast<int>(undecided.size());
  490. for(int i = 0; i < undecided.size(); i++)
  491. {
  492. auto b = undecided[i];
  493. BonusLimitationContext context = {*b, *this, out, undecided};
  494. auto decision = b->limiter ? b->limiter->limit(context) : ILimiter::EDecision::ACCEPT; //bonuses without limiters will be accepted by default
  495. if(decision == ILimiter::EDecision::DISCARD)
  496. {
  497. undecided.erase(i);
  498. i--; continue;
  499. }
  500. else if(decision == ILimiter::EDecision::ACCEPT)
  501. {
  502. accepted.push_back(b);
  503. undecided.erase(i);
  504. i--; continue;
  505. }
  506. else
  507. assert(decision == ILimiter::EDecision::NOT_SURE);
  508. }
  509. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  510. return;
  511. }
  512. }
  513. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  514. {
  515. auto ret = std::make_shared<BonusList>();
  516. limitBonuses(allBonuses, *ret);
  517. return ret;
  518. }
  519. void CBonusSystemNode::treeHasChanged()
  520. {
  521. treeChanged++;
  522. }
  523. int64_t CBonusSystemNode::getTreeVersion() const
  524. {
  525. return treeChanged;
  526. }
  527. VCMI_LIB_NAMESPACE_END