StackWithBonuses.cpp 14 KB

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