StackWithBonuses.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. /*
  2. * StackWithBonuses.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 "StackWithBonuses.h"
  12. #include <vcmi/events/EventBus.h>
  13. #include "../../lib/CStack.h"
  14. #include "../../lib/ScriptHandler.h"
  15. #include "../../lib/networkPacks/PacksForClientBattle.h"
  16. #include "../../lib/networkPacks/SetStackEffect.h"
  17. #if SCRIPTING_ENABLED
  18. using scripting::Pool;
  19. #endif
  20. void actualizeEffect(TBonusListPtr target, const Bonus & ef)
  21. {
  22. for(auto & bonus : *target) //TODO: optimize
  23. {
  24. if(bonus->source == BonusSource::SPELL_EFFECT && bonus->type == ef.type && bonus->subtype == ef.subtype)
  25. {
  26. if(bonus->turnsRemain < ef.turnsRemain)
  27. {
  28. bonus.reset(new Bonus(*bonus));
  29. bonus->turnsRemain = ef.turnsRemain;
  30. }
  31. }
  32. }
  33. }
  34. StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::CUnitState * Stack)
  35. : battle::CUnitState(),
  36. origBearer(Stack->getBonusBearer()),
  37. owner(Owner),
  38. type(Stack->unitType()),
  39. baseAmount(Stack->unitBaseAmount()),
  40. id(Stack->unitId()),
  41. side(Stack->unitSide()),
  42. player(Stack->unitOwner()),
  43. slot(Stack->unitSlot()),
  44. treeVersionLocal(0)
  45. {
  46. localInit(Owner);
  47. battle::CUnitState::operator=(*Stack);
  48. }
  49. StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::Unit * Stack)
  50. : battle::CUnitState(),
  51. origBearer(Stack->getBonusBearer()),
  52. owner(Owner),
  53. type(Stack->unitType()),
  54. baseAmount(Stack->unitBaseAmount()),
  55. id(Stack->unitId()),
  56. side(Stack->unitSide()),
  57. player(Stack->unitOwner()),
  58. slot(Stack->unitSlot()),
  59. treeVersionLocal(0)
  60. {
  61. localInit(Owner);
  62. auto state = Stack->acquireState();
  63. battle::CUnitState::operator=(*state);
  64. }
  65. StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::UnitInfo & info)
  66. : battle::CUnitState(),
  67. origBearer(nullptr),
  68. owner(Owner),
  69. baseAmount(info.count),
  70. id(info.id),
  71. side(info.side),
  72. slot(SlotID::SUMMONED_SLOT_PLACEHOLDER),
  73. treeVersionLocal(0)
  74. {
  75. type = info.type.toCreature();
  76. origBearer = type;
  77. player = Owner->getSidePlayer(side);
  78. localInit(Owner);
  79. position = info.position;
  80. summoned = info.summoned;
  81. }
  82. StackWithBonuses::~StackWithBonuses() = default;
  83. StackWithBonuses & StackWithBonuses::operator=(const battle::CUnitState & other)
  84. {
  85. battle::CUnitState::operator=(other);
  86. return *this;
  87. }
  88. const CCreature * StackWithBonuses::unitType() const
  89. {
  90. return type;
  91. }
  92. int32_t StackWithBonuses::unitBaseAmount() const
  93. {
  94. return baseAmount;
  95. }
  96. uint32_t StackWithBonuses::unitId() const
  97. {
  98. return id;
  99. }
  100. ui8 StackWithBonuses::unitSide() const
  101. {
  102. return side;
  103. }
  104. PlayerColor StackWithBonuses::unitOwner() const
  105. {
  106. return player;
  107. }
  108. SlotID StackWithBonuses::unitSlot() const
  109. {
  110. return slot;
  111. }
  112. TConstBonusListPtr StackWithBonuses::getAllBonuses(const CSelector & selector, const CSelector & limit,
  113. const CBonusSystemNode * root, const std::string & cachingStr) const
  114. {
  115. auto ret = std::make_shared<BonusList>();
  116. TConstBonusListPtr originalList = origBearer->getAllBonuses(selector, limit, root, cachingStr);
  117. vstd::copy_if(*originalList, std::back_inserter(*ret), [this](const std::shared_ptr<Bonus> & b)
  118. {
  119. return !vstd::contains(bonusesToRemove, b);
  120. });
  121. for(const Bonus & bonus : bonusesToUpdate)
  122. {
  123. if(selector(&bonus) && (!limit || limit(&bonus)))
  124. {
  125. if(ret->getFirst(Selector::source(BonusSource::SPELL_EFFECT, bonus.sid).And(Selector::typeSubtype(bonus.type, bonus.subtype))))
  126. {
  127. actualizeEffect(ret, bonus);
  128. }
  129. else
  130. {
  131. auto b = std::make_shared<Bonus>(bonus);
  132. ret->push_back(b);
  133. }
  134. }
  135. }
  136. for(auto & bonus : bonusesToAdd)
  137. {
  138. auto b = std::make_shared<Bonus>(bonus);
  139. if(selector(b.get()) && (!limit || !limit(b.get())))
  140. ret->push_back(b);
  141. }
  142. //TODO limiters?
  143. return ret;
  144. }
  145. int64_t StackWithBonuses::getTreeVersion() const
  146. {
  147. auto result = owner->getTreeVersion();
  148. if(bonusesToAdd.empty() && bonusesToUpdate.empty() && bonusesToRemove.empty())
  149. return result;
  150. else
  151. return result + treeVersionLocal;
  152. }
  153. void StackWithBonuses::addUnitBonus(const std::vector<Bonus> & bonus)
  154. {
  155. vstd::concatenate(bonusesToAdd, bonus);
  156. treeVersionLocal++;
  157. }
  158. void StackWithBonuses::updateUnitBonus(const std::vector<Bonus> & bonus)
  159. {
  160. //TODO: optimize, actualize to last value
  161. vstd::concatenate(bonusesToUpdate, bonus);
  162. treeVersionLocal++;
  163. }
  164. void StackWithBonuses::removeUnitBonus(const std::vector<Bonus> & bonus)
  165. {
  166. for(auto & one : bonus)
  167. {
  168. CSelector selector([&one](const Bonus * b) -> bool
  169. {
  170. //compare everything but turnsRemain, limiter and propagator
  171. return one.duration == b->duration
  172. && one.type == b->type
  173. && one.subtype == b->subtype
  174. && one.source == b->source
  175. && one.val == b->val
  176. && one.sid == b->sid
  177. && one.valType == b->valType
  178. && one.additionalInfo == b->additionalInfo
  179. && one.effectRange == b->effectRange;
  180. });
  181. removeUnitBonus(selector);
  182. }
  183. }
  184. void StackWithBonuses::removeUnitBonus(const CSelector & selector)
  185. {
  186. TConstBonusListPtr toRemove = origBearer->getBonuses(selector);
  187. for(auto b : *toRemove)
  188. bonusesToRemove.insert(b);
  189. vstd::erase_if(bonusesToAdd, [&](const Bonus & b){return selector(&b);});
  190. vstd::erase_if(bonusesToUpdate, [&](const Bonus & b){return selector(&b);});
  191. treeVersionLocal++;
  192. }
  193. std::string StackWithBonuses::getDescription() const
  194. {
  195. std::ostringstream oss;
  196. oss << unitOwner().toString();
  197. oss << " battle stack [" << unitId() << "]: " << getCount() << " of ";
  198. if(type)
  199. oss << type->getJsonKey();
  200. else
  201. oss << "[UNDEFINED TYPE]";
  202. oss << " from slot " << slot;
  203. return oss.str();
  204. }
  205. void StackWithBonuses::spendMana(ServerCallback * server, const int spellCost) const
  206. {
  207. //TODO: evaluate cast use
  208. }
  209. HypotheticBattle::HypotheticBattle(const Environment * ENV, Subject realBattle)
  210. : BattleProxy(realBattle),
  211. env(ENV),
  212. bonusTreeVersion(1)
  213. {
  214. auto activeUnit = realBattle->battleActiveUnit();
  215. activeUnitId = activeUnit ? activeUnit->unitId() : -1;
  216. nextId = 0x00F00000;
  217. eventBus.reset(new events::EventBus());
  218. localEnvironment.reset(new HypotheticEnvironment(this, env));
  219. serverCallback.reset(new HypotheticServerCallback(this));
  220. #if SCRIPTING_ENABLED
  221. pool.reset(new scripting::PoolImpl(localEnvironment.get(), serverCallback.get()));
  222. #endif
  223. }
  224. bool HypotheticBattle::unitHasAmmoCart(const battle::Unit * unit) const
  225. {
  226. //FIXME: check ammocart alive state here
  227. return false;
  228. }
  229. PlayerColor HypotheticBattle::unitEffectiveOwner(const battle::Unit * unit) const
  230. {
  231. return battleGetOwner(unit);
  232. }
  233. std::shared_ptr<StackWithBonuses> HypotheticBattle::getForUpdate(uint32_t id)
  234. {
  235. auto iter = stackStates.find(id);
  236. if(iter == stackStates.end())
  237. {
  238. const battle::Unit * s = subject->battleGetUnitByID(id);
  239. auto ret = std::make_shared<StackWithBonuses>(this, s);
  240. stackStates[id] = ret;
  241. return ret;
  242. }
  243. else
  244. {
  245. return iter->second;
  246. }
  247. }
  248. battle::Units HypotheticBattle::getUnitsIf(const battle::UnitFilter & predicate) const
  249. {
  250. battle::Units proxyed = BattleProxy::getUnitsIf(predicate);
  251. battle::Units ret;
  252. ret.reserve(proxyed.size());
  253. for(auto unit : proxyed)
  254. {
  255. //unit was not changed, trust proxyed data
  256. if(stackStates.find(unit->unitId()) == stackStates.end())
  257. ret.push_back(unit);
  258. }
  259. for(auto id_unit : stackStates)
  260. {
  261. if(predicate(id_unit.second.get()))
  262. ret.push_back(id_unit.second.get());
  263. }
  264. return ret;
  265. }
  266. BattleID HypotheticBattle::getBattleID() const
  267. {
  268. return subject->getBattle()->getBattleID();
  269. }
  270. int32_t HypotheticBattle::getActiveStackID() const
  271. {
  272. return activeUnitId;
  273. }
  274. void HypotheticBattle::nextRound()
  275. {
  276. //TODO:HypotheticBattle::nextRound
  277. for(auto unit : battleAliveUnits())
  278. {
  279. auto forUpdate = getForUpdate(unit->unitId());
  280. //TODO: update Bonus::NTurns effects
  281. forUpdate->afterNewRound();
  282. }
  283. }
  284. void HypotheticBattle::nextTurn(uint32_t unitId)
  285. {
  286. activeUnitId = unitId;
  287. auto unit = getForUpdate(unitId);
  288. unit->removeUnitBonus(Bonus::UntilGetsTurn);
  289. unit->afterGetsTurn();
  290. }
  291. void HypotheticBattle::addUnit(uint32_t id, const JsonNode & data)
  292. {
  293. battle::UnitInfo info;
  294. info.load(id, data);
  295. auto newUnit = std::make_shared<StackWithBonuses>(this, info);
  296. stackStates[newUnit->unitId()] = newUnit;
  297. }
  298. void HypotheticBattle::moveUnit(uint32_t id, BattleHex destination)
  299. {
  300. std::shared_ptr<StackWithBonuses> changed = getForUpdate(id);
  301. changed->position = destination;
  302. }
  303. void HypotheticBattle::setUnitState(uint32_t id, const JsonNode & data, int64_t healthDelta)
  304. {
  305. std::shared_ptr<StackWithBonuses> changed = getForUpdate(id);
  306. changed->load(data);
  307. if(healthDelta < 0)
  308. {
  309. changed->removeUnitBonus(Bonus::UntilBeingAttacked);
  310. }
  311. }
  312. void HypotheticBattle::removeUnit(uint32_t id)
  313. {
  314. std::set<uint32_t> ids;
  315. ids.insert(id);
  316. while(!ids.empty())
  317. {
  318. auto toRemoveId = *ids.begin();
  319. auto toRemove = getForUpdate(toRemoveId);
  320. if(!toRemove->ghost)
  321. {
  322. toRemove->onRemoved();
  323. //TODO: emulate detachFromAll() somehow
  324. //stack may be removed instantly (not being killed first)
  325. //handle clone remove also here
  326. if(toRemove->cloneID >= 0)
  327. {
  328. ids.insert(toRemove->cloneID);
  329. toRemove->cloneID = -1;
  330. }
  331. //TODO: cleanup remaining clone links if any
  332. // for(auto s : stacks)
  333. // {
  334. // if(s->cloneID == toRemoveId)
  335. // s->cloneID = -1;
  336. // }
  337. }
  338. ids.erase(toRemoveId);
  339. }
  340. }
  341. void HypotheticBattle::updateUnit(uint32_t id, const JsonNode & data)
  342. {
  343. //TODO:
  344. }
  345. void HypotheticBattle::addUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  346. {
  347. getForUpdate(id)->addUnitBonus(bonus);
  348. bonusTreeVersion++;
  349. }
  350. void HypotheticBattle::updateUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  351. {
  352. getForUpdate(id)->updateUnitBonus(bonus);
  353. bonusTreeVersion++;
  354. }
  355. void HypotheticBattle::removeUnitBonus(uint32_t id, const std::vector<Bonus> & bonus)
  356. {
  357. getForUpdate(id)->removeUnitBonus(bonus);
  358. bonusTreeVersion++;
  359. }
  360. void HypotheticBattle::setWallState(EWallPart partOfWall, EWallState state)
  361. {
  362. //TODO:HypotheticBattle::setWallState
  363. }
  364. void HypotheticBattle::addObstacle(const ObstacleChanges & changes)
  365. {
  366. //TODO:HypotheticBattle::addObstacle
  367. }
  368. void HypotheticBattle::updateObstacle(const ObstacleChanges& changes)
  369. {
  370. //TODO:HypotheticBattle::updateObstacle
  371. }
  372. void HypotheticBattle::removeObstacle(uint32_t id)
  373. {
  374. //TODO:HypotheticBattle::removeObstacle
  375. }
  376. uint32_t HypotheticBattle::nextUnitId() const
  377. {
  378. return nextId++;
  379. }
  380. int64_t HypotheticBattle::getActualDamage(const DamageRange & damage, int32_t attackerCount, vstd::RNG & rng) const
  381. {
  382. return (damage.min + damage.max) / 2;
  383. }
  384. std::vector<SpellID> HypotheticBattle::getUsedSpells(ui8 side) const
  385. {
  386. // TODO
  387. return {};
  388. }
  389. int3 HypotheticBattle::getLocation() const
  390. {
  391. // TODO
  392. return int3(-1, -1, -1);
  393. }
  394. bool HypotheticBattle::isCreatureBank() const
  395. {
  396. // TODO
  397. return false;
  398. }
  399. int64_t HypotheticBattle::getTreeVersion() const
  400. {
  401. return getBonusBearer()->getTreeVersion() + bonusTreeVersion;
  402. }
  403. #if SCRIPTING_ENABLED
  404. Pool * HypotheticBattle::getContextPool() const
  405. {
  406. return pool.get();
  407. }
  408. #endif
  409. ServerCallback * HypotheticBattle::getServerCallback()
  410. {
  411. return serverCallback.get();
  412. }
  413. HypotheticBattle::HypotheticServerCallback::HypotheticServerCallback(HypotheticBattle * owner_)
  414. :owner(owner_)
  415. {
  416. }
  417. void HypotheticBattle::HypotheticServerCallback::complain(const std::string & problem)
  418. {
  419. logAi->error(problem);
  420. }
  421. bool HypotheticBattle::HypotheticServerCallback::describeChanges() const
  422. {
  423. return false;
  424. }
  425. vstd::RNG * HypotheticBattle::HypotheticServerCallback::getRNG()
  426. {
  427. return &rngStub;
  428. }
  429. void HypotheticBattle::HypotheticServerCallback::apply(CPackForClient * pack)
  430. {
  431. logAi->error("Package of type %s is not allowed in battle evaluation", typeid(pack).name());
  432. }
  433. void HypotheticBattle::HypotheticServerCallback::apply(BattleLogMessage * pack)
  434. {
  435. pack->applyBattle(owner);
  436. }
  437. void HypotheticBattle::HypotheticServerCallback::apply(BattleStackMoved * pack)
  438. {
  439. pack->applyBattle(owner);
  440. }
  441. void HypotheticBattle::HypotheticServerCallback::apply(BattleUnitsChanged * pack)
  442. {
  443. pack->applyBattle(owner);
  444. }
  445. void HypotheticBattle::HypotheticServerCallback::apply(SetStackEffect * pack)
  446. {
  447. pack->applyBattle(owner);
  448. }
  449. void HypotheticBattle::HypotheticServerCallback::apply(StacksInjured * pack)
  450. {
  451. pack->applyBattle(owner);
  452. }
  453. void HypotheticBattle::HypotheticServerCallback::apply(BattleObstaclesChanged * pack)
  454. {
  455. pack->applyBattle(owner);
  456. }
  457. void HypotheticBattle::HypotheticServerCallback::apply(CatapultAttack * pack)
  458. {
  459. pack->applyBattle(owner);
  460. }
  461. HypotheticBattle::HypotheticEnvironment::HypotheticEnvironment(HypotheticBattle * owner_, const Environment * upperEnvironment)
  462. : owner(owner_),
  463. env(upperEnvironment)
  464. {
  465. }
  466. const Services * HypotheticBattle::HypotheticEnvironment::services() const
  467. {
  468. return env->services();
  469. }
  470. const Environment::BattleCb * HypotheticBattle::HypotheticEnvironment::battle(const BattleID & battleID) const
  471. {
  472. assert(battleID == owner->getBattleID());
  473. return owner;
  474. }
  475. const Environment::GameCb * HypotheticBattle::HypotheticEnvironment::game() const
  476. {
  477. return env->game();
  478. }
  479. vstd::CLoggerBase * HypotheticBattle::HypotheticEnvironment::logger() const
  480. {
  481. return env->logger();
  482. }
  483. events::EventBus * HypotheticBattle::HypotheticEnvironment::eventBus() const
  484. {
  485. return owner->eventBus.get();
  486. }