StackWithBonuses.cpp 13 KB

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