CBonusSystemNode.cpp 14 KB

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