CBonusSystemNode.cpp 14 KB

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