StackWithBonuses.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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/gameState/GameStatePackVisitor.h"
  17. #include "../../lib/networkPacks/PacksForClientBattle.h"
  18. #include "../../lib/networkPacks/SetStackEffect.h"
  19. #if SCRIPTING_ENABLED
  20. using scripting::Pool;
  21. #endif
  22. void actualizeEffect(TBonusListPtr target, const Bonus & ef)
  23. {
  24. for(auto & bonus : *target) //TODO: optimize
  25. {
  26. if(bonus->source == BonusSource::SPELL_EFFECT && bonus->type == ef.type && bonus->subtype == ef.subtype)
  27. {
  28. if(bonus->turnsRemain < ef.turnsRemain)
  29. {
  30. bonus.reset(new Bonus(*bonus));
  31. bonus->turnsRemain = ef.turnsRemain;
  32. }
  33. }
  34. }
  35. }
  36. StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::CUnitState * Stack)
  37. : battle::CUnitState(),
  38. origBearer(Stack->getBonusBearer()),
  39. owner(Owner),
  40. type(Stack->unitType()),
  41. baseAmount(Stack->unitBaseAmount()),
  42. id(Stack->unitId()),
  43. side(Stack->unitSide()),
  44. player(Stack->unitOwner()),
  45. slot(Stack->unitSlot()),
  46. treeVersionLocal(0)
  47. {
  48. localInit(Owner);
  49. battle::CUnitState::operator=(*Stack);
  50. }
  51. StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::Unit * Stack)
  52. : battle::CUnitState(),
  53. origBearer(Stack->getBonusBearer()),
  54. owner(Owner),
  55. type(Stack->unitType()),
  56. baseAmount(Stack->unitBaseAmount()),
  57. id(Stack->unitId()),
  58. side(Stack->unitSide()),
  59. player(Stack->unitOwner()),
  60. slot(Stack->unitSlot()),
  61. treeVersionLocal(0)
  62. {
  63. localInit(Owner);
  64. auto state = Stack->acquireState();
  65. battle::CUnitState::operator=(*state);
  66. }
  67. StackWithBonuses::StackWithBonuses(const HypotheticBattle * Owner, const battle::UnitInfo & info)
  68. : battle::CUnitState(),
  69. origBearer(nullptr),
  70. owner(Owner),
  71. baseAmount(info.count),
  72. id(info.id),
  73. side(info.side),
  74. slot(SlotID::SUMMONED_SLOT_PLACEHOLDER),
  75. treeVersionLocal(0)
  76. {
  77. type = info.type.toCreature();
  78. origBearer = type;
  79. player = Owner->getSidePlayer(side);
  80. localInit(Owner);
  81. position = info.position;
  82. summoned = info.summoned;
  83. }
  84. StackWithBonuses::~StackWithBonuses() = default;
  85. StackWithBonuses & StackWithBonuses::operator=(const battle::CUnitState & other)
  86. {
  87. battle::CUnitState::operator=(other);
  88. return *this;
  89. }
  90. const CCreature * StackWithBonuses::unitType() const
  91. {
  92. return type;
  93. }
  94. int32_t StackWithBonuses::unitBaseAmount() const
  95. {
  96. return baseAmount;
  97. }
  98. uint32_t StackWithBonuses::unitId() const
  99. {
  100. return id;
  101. }
  102. BattleSide StackWithBonuses::unitSide() const
  103. {
  104. return side;
  105. }
  106. PlayerColor StackWithBonuses::unitOwner() const
  107. {
  108. return player;
  109. }
  110. SlotID StackWithBonuses::unitSlot() const
  111. {
  112. return slot;
  113. }
  114. TConstBonusListPtr StackWithBonuses::getAllBonuses(const CSelector & selector, const std::string & cachingStr) const
  115. {
  116. auto ret = std::make_shared<BonusList>();
  117. TConstBonusListPtr originalList = origBearer->getAllBonuses(selector, 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))
  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()))
  141. ret->push_back(b);
  142. }
  143. //TODO limiters?
  144. return ret;
  145. }
  146. int32_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.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, BattleUnitTurnReason reason)
  285. {
  286. activeUnitId = unitId;
  287. auto unit = getForUpdate(unitId);
  288. unit->removeUnitBonus(Bonus::UntilGetsTurn);
  289. unit->afterGetsTurn(reason);
  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, const 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(BattleSide side) const
  385. {
  386. // TODO
  387. return {};
  388. }
  389. int3 HypotheticBattle::getLocation() const
  390. {
  391. // TODO
  392. return int3(-1, -1, -1);
  393. }
  394. BattleLayout HypotheticBattle::getLayout() const
  395. {
  396. return subject->getBattle()->getLayout();
  397. }
  398. int32_t HypotheticBattle::getTreeVersion() const
  399. {
  400. return getBonusBearer()->getTreeVersion() + bonusTreeVersion;
  401. }
  402. #if SCRIPTING_ENABLED
  403. Pool * HypotheticBattle::getContextPool() const
  404. {
  405. return pool.get();
  406. }
  407. #endif
  408. ServerCallback * HypotheticBattle::getServerCallback()
  409. {
  410. return serverCallback.get();
  411. }
  412. void HypotheticBattle::makeWait(const battle::Unit * activeStack)
  413. {
  414. auto unit = getForUpdate(activeStack->unitId());
  415. resetActiveUnit();
  416. unit->waiting = true;
  417. unit->waitedThisTurn = true;
  418. }
  419. HypotheticBattle::HypotheticServerCallback::HypotheticServerCallback(HypotheticBattle * owner_)
  420. :owner(owner_)
  421. {
  422. }
  423. void HypotheticBattle::HypotheticServerCallback::complain(const std::string & problem)
  424. {
  425. logAi->error(problem);
  426. }
  427. bool HypotheticBattle::HypotheticServerCallback::describeChanges() const
  428. {
  429. return false;
  430. }
  431. vstd::RNG * HypotheticBattle::HypotheticServerCallback::getRNG()
  432. {
  433. return &rngStub;
  434. }
  435. void HypotheticBattle::HypotheticServerCallback::apply(CPackForClient & pack)
  436. {
  437. logAi->error("Package of type %s is not allowed in battle evaluation", typeid(pack).name());
  438. }
  439. void HypotheticBattle::HypotheticServerCallback::apply(BattleLogMessage & pack)
  440. {
  441. BattleStatePackVisitor visitor(*owner);
  442. pack.visit(visitor);
  443. }
  444. void HypotheticBattle::HypotheticServerCallback::apply(BattleStackMoved & pack)
  445. {
  446. BattleStatePackVisitor visitor(*owner);
  447. pack.visit(visitor);
  448. }
  449. void HypotheticBattle::HypotheticServerCallback::apply(BattleUnitsChanged & pack)
  450. {
  451. BattleStatePackVisitor visitor(*owner);
  452. pack.visit(visitor);
  453. }
  454. void HypotheticBattle::HypotheticServerCallback::apply(SetStackEffect & pack)
  455. {
  456. BattleStatePackVisitor visitor(*owner);
  457. pack.visit(visitor);
  458. }
  459. void HypotheticBattle::HypotheticServerCallback::apply(StacksInjured & pack)
  460. {
  461. BattleStatePackVisitor visitor(*owner);
  462. pack.visit(visitor);
  463. }
  464. void HypotheticBattle::HypotheticServerCallback::apply(BattleObstaclesChanged & pack)
  465. {
  466. BattleStatePackVisitor visitor(*owner);
  467. pack.visit(visitor);
  468. }
  469. void HypotheticBattle::HypotheticServerCallback::apply(CatapultAttack & pack)
  470. {
  471. BattleStatePackVisitor visitor(*owner);
  472. pack.visit(visitor);
  473. }
  474. HypotheticBattle::HypotheticEnvironment::HypotheticEnvironment(HypotheticBattle * owner_, const Environment * upperEnvironment)
  475. : owner(owner_),
  476. env(upperEnvironment)
  477. {
  478. }
  479. const Services * HypotheticBattle::HypotheticEnvironment::services() const
  480. {
  481. return env->services();
  482. }
  483. const Environment::BattleCb * HypotheticBattle::HypotheticEnvironment::battle(const BattleID & battleID) const
  484. {
  485. assert(battleID == owner->getBattleID());
  486. return owner;
  487. }
  488. const Environment::GameCb * HypotheticBattle::HypotheticEnvironment::game() const
  489. {
  490. return env->game();
  491. }
  492. vstd::CLoggerBase * HypotheticBattle::HypotheticEnvironment::logger() const
  493. {
  494. return env->logger();
  495. }
  496. events::EventBus * HypotheticBattle::HypotheticEnvironment::eventBus() const
  497. {
  498. return owner->eventBus.get();
  499. }