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