CBonusSystemNode.cpp 16 KB

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