CBonusSystemNode.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  19. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  20. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector)
  21. {
  22. auto ret = bonuses.getFirst(selector);
  23. if(ret)
  24. return ret;
  25. FOREACH_PARENT(pname)
  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(CBonusSystemNode && other) noexcept:
  192. bonuses(std::move(other.bonuses)),
  193. exportedBonuses(std::move(other.exportedBonuses)),
  194. nodeType(other.nodeType),
  195. cachedLast(0),
  196. isHypotheticNode(other.isHypotheticNode)
  197. {
  198. std::swap(parents, other.parents);
  199. std::swap(children, other.children);
  200. //fixing bonus tree without recalculation
  201. if(!isHypothetic())
  202. {
  203. for(CBonusSystemNode * n : parents)
  204. {
  205. n->children -= &other;
  206. n->children.push_back(this);
  207. }
  208. }
  209. for(CBonusSystemNode * n : children)
  210. {
  211. n->parents -= &other;
  212. n->parents.push_back(this);
  213. }
  214. //cache ignored
  215. //cachedBonuses
  216. //cachedRequests
  217. }
  218. CBonusSystemNode::~CBonusSystemNode()
  219. {
  220. detachFromAll();
  221. if(!children.empty())
  222. {
  223. while(!children.empty())
  224. children.front()->detachFrom(*this);
  225. }
  226. }
  227. void CBonusSystemNode::attachTo(CBonusSystemNode & parent)
  228. {
  229. assert(!vstd::contains(parents, &parent));
  230. parents.push_back(&parent);
  231. if(!isHypothetic())
  232. {
  233. if(parent.actsAsBonusSourceOnly())
  234. parent.newRedDescendant(*this);
  235. else
  236. newRedDescendant(parent);
  237. parent.newChildAttached(*this);
  238. }
  239. CBonusSystemNode::treeHasChanged();
  240. }
  241. void CBonusSystemNode::detachFrom(CBonusSystemNode & parent)
  242. {
  243. assert(vstd::contains(parents, &parent));
  244. if(!isHypothetic())
  245. {
  246. if(parent.actsAsBonusSourceOnly())
  247. parent.removedRedDescendant(*this);
  248. else
  249. removedRedDescendant(parent);
  250. }
  251. if (vstd::contains(parents, &parent))
  252. {
  253. parents -= &parent;
  254. }
  255. else
  256. {
  257. logBonus->error("Error on Detach. Node %s (nodeType=%d) has not parent %s (nodeType=%d)"
  258. , nodeShortInfo(), nodeType, parent.nodeShortInfo(), parent.nodeType);
  259. }
  260. if(!isHypothetic())
  261. {
  262. parent.childDetached(*this);
  263. }
  264. CBonusSystemNode::treeHasChanged();
  265. }
  266. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  267. {
  268. removeBonuses(s);
  269. for(CBonusSystemNode * child : children)
  270. child->removeBonusesRecursive(s);
  271. }
  272. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  273. {
  274. BonusList bl;
  275. exportedBonuses.getBonuses(bl, s, Selector::all);
  276. for(const auto & b : bl)
  277. {
  278. b->turnsRemain--;
  279. if(b->turnsRemain <= 0)
  280. removeBonus(b);
  281. }
  282. for(CBonusSystemNode *child : children)
  283. child->reduceBonusDurations(s);
  284. }
  285. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  286. {
  287. //turnsRemain shouldn't be zero for following durations
  288. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  289. {
  290. assert(b->turnsRemain);
  291. }
  292. assert(!vstd::contains(exportedBonuses, b));
  293. exportedBonuses.push_back(b);
  294. exportBonus(b);
  295. CBonusSystemNode::treeHasChanged();
  296. }
  297. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  298. {
  299. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  300. if(bonus)
  301. bonus->val += b->val;
  302. else
  303. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  304. }
  305. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  306. {
  307. exportedBonuses -= b;
  308. if(b->propagator)
  309. unpropagateBonus(b);
  310. else
  311. bonuses -= b;
  312. CBonusSystemNode::treeHasChanged();
  313. }
  314. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  315. {
  316. BonusList toRemove;
  317. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  318. for(const auto & bonus : toRemove)
  319. removeBonus(bonus);
  320. }
  321. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  322. {
  323. switch(nodeType)
  324. {
  325. case CREATURE:
  326. case ARTIFACT:
  327. case ARTIFACT_INSTANCE:
  328. return true;
  329. default:
  330. return false;
  331. }
  332. }
  333. void CBonusSystemNode::propagateBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & source)
  334. {
  335. if(b->propagator->shouldBeAttached(this))
  336. {
  337. auto propagated = b->propagationUpdater
  338. ? source.getUpdatedBonus(b, b->propagationUpdater)
  339. : b;
  340. bonuses.push_back(propagated);
  341. logBonus->trace("#$# %s #propagated to# %s", propagated->Description(), nodeName());
  342. }
  343. FOREACH_RED_CHILD(child)
  344. child->propagateBonus(b, source);
  345. }
  346. void CBonusSystemNode::unpropagateBonus(const std::shared_ptr<Bonus> & b)
  347. {
  348. if(b->propagator->shouldBeAttached(this))
  349. {
  350. bonuses -= b;
  351. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  352. }
  353. FOREACH_RED_CHILD(child)
  354. child->unpropagateBonus(b);
  355. }
  356. void CBonusSystemNode::newChildAttached(CBonusSystemNode & child)
  357. {
  358. assert(!vstd::contains(children, &child));
  359. children.push_back(&child);
  360. }
  361. void CBonusSystemNode::childDetached(CBonusSystemNode & child)
  362. {
  363. if(vstd::contains(children, &child))
  364. children -= &child;
  365. else
  366. {
  367. logBonus->error("Error on Detach. Node %s (nodeType=%d) is not a child of %s (nodeType=%d)"
  368. , child.nodeShortInfo(), child.nodeType, nodeShortInfo(), nodeType);
  369. }
  370. }
  371. void CBonusSystemNode::detachFromAll()
  372. {
  373. while(!parents.empty())
  374. detachFrom(*parents.front());
  375. }
  376. bool CBonusSystemNode::isIndependentNode() const
  377. {
  378. return parents.empty() && children.empty();
  379. }
  380. std::string CBonusSystemNode::nodeName() const
  381. {
  382. return std::string("Bonus system node of type ") + typeid(*this).name();
  383. }
  384. std::string CBonusSystemNode::nodeShortInfo() const
  385. {
  386. std::ostringstream str;
  387. str << "'" << typeid(* this).name() << "'";
  388. return str.str();
  389. }
  390. void CBonusSystemNode::deserializationFix()
  391. {
  392. exportBonuses();
  393. }
  394. void CBonusSystemNode::getRedParents(TNodes & out)
  395. {
  396. FOREACH_PARENT(pname)
  397. {
  398. if(pname->actsAsBonusSourceOnly())
  399. {
  400. out.insert(pname);
  401. }
  402. }
  403. if(!actsAsBonusSourceOnly())
  404. {
  405. for(CBonusSystemNode *child : children)
  406. {
  407. out.insert(child);
  408. }
  409. }
  410. }
  411. void CBonusSystemNode::getRedChildren(TNodes &out)
  412. {
  413. FOREACH_PARENT(pname)
  414. {
  415. if(!pname->actsAsBonusSourceOnly())
  416. {
  417. out.insert(pname);
  418. }
  419. }
  420. if(actsAsBonusSourceOnly())
  421. {
  422. for(CBonusSystemNode *child : children)
  423. {
  424. out.insert(child);
  425. }
  426. }
  427. }
  428. void CBonusSystemNode::newRedDescendant(CBonusSystemNode & descendant)
  429. {
  430. for(const auto & b : exportedBonuses)
  431. {
  432. if(b->propagator)
  433. descendant.propagateBonus(b, *this);
  434. }
  435. TNodes redParents;
  436. getRedAncestors(redParents); //get all red parents recursively
  437. for(auto * parent : redParents)
  438. {
  439. for(const auto & b : parent->exportedBonuses)
  440. {
  441. if(b->propagator)
  442. descendant.propagateBonus(b, *this);
  443. }
  444. }
  445. }
  446. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode & descendant)
  447. {
  448. for(const auto & b : exportedBonuses)
  449. if(b->propagator)
  450. descendant.unpropagateBonus(b);
  451. TNodes redParents;
  452. getRedAncestors(redParents); //get all red parents recursively
  453. for(auto * parent : redParents)
  454. {
  455. for(const auto & b : parent->exportedBonuses)
  456. if(b->propagator)
  457. descendant.unpropagateBonus(b);
  458. }
  459. }
  460. void CBonusSystemNode::getRedAncestors(TNodes &out)
  461. {
  462. getRedParents(out);
  463. TNodes redParents;
  464. getRedParents(redParents);
  465. for(CBonusSystemNode * parent : redParents)
  466. parent->getRedAncestors(out);
  467. }
  468. void CBonusSystemNode::exportBonus(const std::shared_ptr<Bonus> & b)
  469. {
  470. if(b->propagator)
  471. propagateBonus(b, *this);
  472. else
  473. bonuses.push_back(b);
  474. CBonusSystemNode::treeHasChanged();
  475. }
  476. void CBonusSystemNode::exportBonuses()
  477. {
  478. for(const auto & b : exportedBonuses)
  479. exportBonus(b);
  480. }
  481. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  482. {
  483. return nodeType;
  484. }
  485. const TNodesVector& CBonusSystemNode::getParentNodes() const
  486. {
  487. return parents;
  488. }
  489. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  490. {
  491. nodeType = type;
  492. }
  493. BonusList & CBonusSystemNode::getExportedBonusList()
  494. {
  495. return exportedBonuses;
  496. }
  497. const BonusList & CBonusSystemNode::getExportedBonusList() const
  498. {
  499. return exportedBonuses;
  500. }
  501. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  502. {
  503. assert(&allBonuses != &out); //todo should it work in-place?
  504. BonusList undecided = allBonuses;
  505. BonusList & accepted = out;
  506. while(true)
  507. {
  508. int undecidedCount = static_cast<int>(undecided.size());
  509. for(int i = 0; i < undecided.size(); i++)
  510. {
  511. auto b = undecided[i];
  512. BonusLimitationContext context = {*b, *this, out, undecided};
  513. auto decision = b->limiter ? b->limiter->limit(context) : ILimiter::EDecision::ACCEPT; //bonuses without limiters will be accepted by default
  514. if(decision == ILimiter::EDecision::DISCARD)
  515. {
  516. undecided.erase(i);
  517. i--; continue;
  518. }
  519. else if(decision == ILimiter::EDecision::ACCEPT)
  520. {
  521. accepted.push_back(b);
  522. undecided.erase(i);
  523. i--; continue;
  524. }
  525. else
  526. assert(decision == ILimiter::EDecision::NOT_SURE);
  527. }
  528. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  529. return;
  530. }
  531. }
  532. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  533. {
  534. auto ret = std::make_shared<BonusList>();
  535. limitBonuses(allBonuses, *ret);
  536. return ret;
  537. }
  538. void CBonusSystemNode::treeHasChanged()
  539. {
  540. treeChanged++;
  541. }
  542. int64_t CBonusSystemNode::getTreeVersion() const
  543. {
  544. return treeChanged;
  545. }
  546. VCMI_LIB_NAMESPACE_END