CBonusSystemNode.cpp 15 KB

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