NetPacksLib.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  1. #include "StdInc.h"
  2. #include "NetPacks.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "mapObjects/CObjectClassesHandler.h"
  5. #include "CArtHandler.h"
  6. #include "CHeroHandler.h"
  7. #include "mapObjects/CObjectHandler.h"
  8. #include "CModHandler.h"
  9. #include "VCMI_Lib.h"
  10. #include "mapping/CMap.h"
  11. #include "spells/CSpellHandler.h"
  12. #include "CCreatureHandler.h"
  13. #include "CGameState.h"
  14. #include "BattleState.h"
  15. #include "CTownHandler.h"
  16. #include "mapping/CMapInfo.h"
  17. #include "StartInfo.h"
  18. #include "CPlayerState.h"
  19. /*
  20. * NetPacksLib.cpp, part of VCMI engine
  21. *
  22. * Authors: listed in file AUTHORS in main folder
  23. *
  24. * License: GNU General Public License v2.0 or later
  25. * Full text of license available in license.txt file, in main folder
  26. *
  27. */
  28. #undef min
  29. #undef max
  30. std::ostream & operator<<(std::ostream & out, const CPack * pack)
  31. {
  32. return out << pack->toString();
  33. }
  34. DLL_LINKAGE void SetResource::applyGs( CGameState *gs )
  35. {
  36. assert(player < PlayerColor::PLAYER_LIMIT);
  37. vstd::amax(val, 0); //new value must be >= 0
  38. gs->getPlayer(player)->resources[resid] = val;
  39. }
  40. DLL_LINKAGE void SetResources::applyGs( CGameState *gs )
  41. {
  42. assert(player < PlayerColor::PLAYER_LIMIT);
  43. gs->getPlayer(player)->resources = res;
  44. }
  45. DLL_LINKAGE void SetPrimSkill::applyGs( CGameState *gs )
  46. {
  47. CGHeroInstance * hero = gs->getHero(id);
  48. assert(hero);
  49. hero->setPrimarySkill(which, val, abs);
  50. }
  51. DLL_LINKAGE void SetSecSkill::applyGs( CGameState *gs )
  52. {
  53. CGHeroInstance *hero = gs->getHero(id);
  54. hero->setSecSkillLevel(which, val, abs);
  55. }
  56. DLL_LINKAGE SelectMap::SelectMap(const CMapInfo &src)
  57. {
  58. mapInfo = &src;
  59. free = false;
  60. }
  61. DLL_LINKAGE SelectMap::SelectMap()
  62. {
  63. mapInfo = nullptr;
  64. free = true;
  65. }
  66. DLL_LINKAGE SelectMap::~SelectMap()
  67. {
  68. if(free)
  69. delete mapInfo;
  70. }
  71. DLL_LINKAGE UpdateStartOptions::UpdateStartOptions(StartInfo &src)
  72. {
  73. options = &src;
  74. free = false;
  75. }
  76. DLL_LINKAGE UpdateStartOptions::UpdateStartOptions()
  77. {
  78. options = nullptr;
  79. free = true;
  80. }
  81. DLL_LINKAGE UpdateStartOptions::~UpdateStartOptions()
  82. {
  83. if(free)
  84. delete options;
  85. }
  86. DLL_LINKAGE void SetCommanderProperty::applyGs(CGameState *gs)
  87. {
  88. CCommanderInstance * commander = gs->getHero(heroid)->commander;
  89. assert (commander);
  90. switch (which)
  91. {
  92. case BONUS:
  93. commander->accumulateBonus (accumulatedBonus);
  94. break;
  95. case SPECIAL_SKILL:
  96. commander->accumulateBonus (accumulatedBonus);
  97. commander->specialSKills.insert (additionalInfo);
  98. break;
  99. case SECONDARY_SKILL:
  100. commander->secondarySkills[additionalInfo] = amount;
  101. break;
  102. case ALIVE:
  103. if (amount)
  104. commander->setAlive(true);
  105. else
  106. commander->setAlive(false);
  107. break;
  108. case EXPERIENCE:
  109. commander->giveStackExp (amount); //TODO: allow setting exp for stacks via netpacks
  110. break;
  111. }
  112. }
  113. DLL_LINKAGE void AddQuest::applyGs(CGameState *gs)
  114. {
  115. assert (vstd::contains(gs->players, player));
  116. auto vec = &gs->players[player].quests;
  117. if (!vstd::contains(*vec, quest))
  118. vec->push_back (quest);
  119. else
  120. logNetwork->warnStream() << "Warning! Attempt to add duplicated quest";
  121. }
  122. DLL_LINKAGE void UpdateArtHandlerLists::applyGs(CGameState *gs)
  123. {
  124. VLC->arth->minors = minors;
  125. VLC->arth->majors = majors;
  126. VLC->arth->treasures = treasures;
  127. VLC->arth->relics = relics;
  128. }
  129. DLL_LINKAGE void UpdateMapEvents::applyGs(CGameState *gs)
  130. {
  131. gs->map->events = events;
  132. }
  133. DLL_LINKAGE void UpdateCastleEvents::applyGs(CGameState *gs)
  134. {
  135. auto t = gs->getTown(town);
  136. t->events = events;
  137. }
  138. DLL_LINKAGE void HeroVisitCastle::applyGs( CGameState *gs )
  139. {
  140. CGHeroInstance *h = gs->getHero(hid);
  141. CGTownInstance *t = gs->getTown(tid);
  142. assert(h);
  143. assert(t);
  144. if(start())
  145. t->setVisitingHero(h);
  146. else
  147. t->setVisitingHero(nullptr);
  148. }
  149. DLL_LINKAGE void ChangeSpells::applyGs( CGameState *gs )
  150. {
  151. CGHeroInstance *hero = gs->getHero(hid);
  152. if(learn)
  153. for(auto sid : spells)
  154. hero->spells.insert(sid);
  155. else
  156. for(auto sid : spells)
  157. hero->spells.erase(sid);
  158. }
  159. DLL_LINKAGE void SetMana::applyGs( CGameState *gs )
  160. {
  161. CGHeroInstance * hero = gs->getHero(hid);
  162. assert(hero);
  163. if(absolute)
  164. hero->mana = val;
  165. else
  166. hero->mana += val;
  167. vstd::amax(hero->mana, 0); //not less than 0
  168. }
  169. DLL_LINKAGE void SetMovePoints::applyGs( CGameState *gs )
  170. {
  171. CGHeroInstance *hero = gs->getHero(hid);
  172. hero->movement = val;
  173. }
  174. DLL_LINKAGE void FoWChange::applyGs( CGameState *gs )
  175. {
  176. TeamState * team = gs->getPlayerTeam(player);
  177. for(int3 t : tiles)
  178. team->fogOfWarMap[t.x][t.y][t.z] = mode;
  179. if (mode == 0) //do not hide too much
  180. {
  181. std::unordered_set<int3, ShashInt3> tilesRevealed;
  182. for (auto & elem : gs->map->objects)
  183. {
  184. const CGObjectInstance *o = elem;
  185. if (o)
  186. {
  187. switch(o->ID)
  188. {
  189. case Obj::HERO:
  190. case Obj::MINE:
  191. case Obj::TOWN:
  192. case Obj::ABANDONED_MINE:
  193. if(vstd::contains(team->players, o->tempOwner)) //check owned observators
  194. gs->getTilesInRange(tilesRevealed, o->getSightCenter(), o->getSightRadious(), o->tempOwner, 1);
  195. break;
  196. }
  197. }
  198. }
  199. for(int3 t : tilesRevealed) //probably not the most optimal solution ever
  200. team->fogOfWarMap[t.x][t.y][t.z] = 1;
  201. }
  202. }
  203. DLL_LINKAGE void SetAvailableHeroes::applyGs( CGameState *gs )
  204. {
  205. PlayerState *p = gs->getPlayer(player);
  206. p->availableHeroes.clear();
  207. for (int i = 0; i < GameConstants::AVAILABLE_HEROES_PER_PLAYER; i++)
  208. {
  209. CGHeroInstance *h = (hid[i]>=0 ? gs->hpool.heroesPool[hid[i]].get() : nullptr);
  210. if(h && army[i])
  211. h->setToArmy(army[i]);
  212. p->availableHeroes.push_back(h);
  213. }
  214. }
  215. DLL_LINKAGE void GiveBonus::applyGs( CGameState *gs )
  216. {
  217. CBonusSystemNode *cbsn = nullptr;
  218. switch(who)
  219. {
  220. case HERO:
  221. cbsn = gs->getHero(ObjectInstanceID(id));
  222. break;
  223. case PLAYER:
  224. cbsn = gs->getPlayer(PlayerColor(id));
  225. break;
  226. case TOWN:
  227. cbsn = gs->getTown(ObjectInstanceID(id));
  228. break;
  229. }
  230. assert(cbsn);
  231. if(Bonus::OneWeek(&bonus))
  232. bonus.turnsRemain = 8 - gs->getDate(Date::DAY_OF_WEEK); // set correct number of days before adding bonus
  233. auto b = new Bonus(bonus);
  234. cbsn->addNewBonus(b);
  235. std::string &descr = b->description;
  236. if(!bdescr.message.size()
  237. && bonus.source == Bonus::OBJECT
  238. && (bonus.type == Bonus::LUCK || bonus.type == Bonus::MORALE))
  239. {
  240. descr = VLC->generaltexth->arraytxt[bonus.val > 0 ? 110 : 109]; //+/-%d Temporary until next battle"
  241. }
  242. else
  243. {
  244. bdescr.toString(descr);
  245. }
  246. // Some of(?) versions of H3 use %s here instead of %d. Try to replace both of them
  247. boost::replace_first(descr,"%d",boost::lexical_cast<std::string>(std::abs(bonus.val)));
  248. boost::replace_first(descr,"%s",boost::lexical_cast<std::string>(std::abs(bonus.val)));
  249. }
  250. DLL_LINKAGE void ChangeObjPos::applyGs( CGameState *gs )
  251. {
  252. CGObjectInstance *obj = gs->getObjInstance(objid);
  253. if(!obj)
  254. {
  255. logNetwork->errorStream() << "Wrong ChangeObjPos: object " << objid.getNum() << " doesn't exist!";
  256. return;
  257. }
  258. gs->map->removeBlockVisTiles(obj);
  259. obj->pos = nPos;
  260. gs->map->addBlockVisTiles(obj);
  261. }
  262. DLL_LINKAGE void ChangeObjectVisitors::applyGs( CGameState *gs )
  263. {
  264. switch (mode) {
  265. case VISITOR_ADD:
  266. gs->getHero(hero)->visitedObjects.insert(object);
  267. gs->getPlayer(gs->getHero(hero)->tempOwner)->visitedObjects.insert(object);
  268. break;
  269. case VISITOR_CLEAR:
  270. for (CGHeroInstance * hero : gs->map->allHeroes)
  271. hero->visitedObjects.erase(object); // remove visit info from all heroes, including those that are not present on map
  272. break;
  273. case VISITOR_REMOVE:
  274. gs->getHero(hero)->visitedObjects.erase(object);
  275. break;
  276. }
  277. }
  278. DLL_LINKAGE void PlayerEndsGame::applyGs( CGameState *gs )
  279. {
  280. PlayerState *p = gs->getPlayer(player);
  281. if(victoryLossCheckResult.victory()) p->status = EPlayerStatus::WINNER;
  282. else p->status = EPlayerStatus::LOSER;
  283. }
  284. DLL_LINKAGE void RemoveBonus::applyGs( CGameState *gs )
  285. {
  286. CBonusSystemNode *node;
  287. if (who == HERO)
  288. node = gs->getHero(ObjectInstanceID(whoID));
  289. else
  290. node = gs->getPlayer(PlayerColor(whoID));
  291. BonusList &bonuses = node->getExportedBonusList();
  292. for (int i = 0; i < bonuses.size(); i++)
  293. {
  294. Bonus *b = bonuses[i];
  295. if(b->source == source && b->sid == id)
  296. {
  297. bonus = *b; //backup bonus (to show to interfaces later)
  298. node->removeBonus(b);
  299. break;
  300. }
  301. }
  302. }
  303. DLL_LINKAGE void RemoveObject::applyGs( CGameState *gs )
  304. {
  305. CGObjectInstance *obj = gs->getObjInstance(id);
  306. logGlobal->debugStream() << "removing object id=" << id << "; address=" << (intptr_t)obj << "; name=" << obj->getObjectName();
  307. //unblock tiles
  308. gs->map->removeBlockVisTiles(obj);
  309. if(obj->ID==Obj::HERO)
  310. {
  311. CGHeroInstance *h = static_cast<CGHeroInstance*>(obj);
  312. PlayerState *p = gs->getPlayer(h->tempOwner);
  313. gs->map->heroesOnMap -= h;
  314. p->heroes -= h;
  315. h->detachFrom(h->whereShouldBeAttached(gs));
  316. h->tempOwner = PlayerColor::NEUTRAL; //no one owns beaten hero
  317. vstd::erase_if(h->artifactsInBackpack, [](const ArtSlotInfo& asi)
  318. {
  319. return asi.artifact->artType->id == ArtifactID::GRAIL;
  320. });
  321. if(h->visitedTown)
  322. {
  323. if(h->inTownGarrison)
  324. h->visitedTown->garrisonHero = nullptr;
  325. else
  326. h->visitedTown->visitingHero = nullptr;
  327. h->visitedTown = nullptr;
  328. }
  329. //return hero to the pool, so he may reappear in tavern
  330. gs->hpool.heroesPool[h->subID] = h;
  331. if(!vstd::contains(gs->hpool.pavailable, h->subID))
  332. gs->hpool.pavailable[h->subID] = 0xff;
  333. gs->map->objects[id.getNum()] = nullptr;
  334. //If hero on Boat is removed, the Boat disappears
  335. if(h->boat)
  336. {
  337. gs->map->objects[h->boat->id.getNum()].dellNull();
  338. h->boat = nullptr;
  339. }
  340. return;
  341. }
  342. auto quest = dynamic_cast<const IQuestObject *>(obj);
  343. if (quest)
  344. {
  345. gs->map->quests[quest->quest->qid] = nullptr;
  346. for (auto &player : gs->players)
  347. {
  348. for (auto &q : player.second.quests)
  349. {
  350. if (q.obj == obj)
  351. {
  352. q.obj = nullptr;
  353. }
  354. }
  355. }
  356. }
  357. for (TriggeredEvent & event : gs->map->triggeredEvents)
  358. {
  359. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  360. {
  361. if (cond.object == obj)
  362. {
  363. if (cond.condition == EventCondition::DESTROY)
  364. {
  365. cond.condition = EventCondition::CONST_VALUE;
  366. cond.value = 1; // destroyed object, from now on always fulfilled
  367. }
  368. if (cond.condition == EventCondition::CONTROL)
  369. {
  370. cond.condition = EventCondition::CONST_VALUE;
  371. cond.value = 0; // destroyed object, from now on can not be fulfilled
  372. }
  373. }
  374. return cond;
  375. };
  376. event.trigger = event.trigger.morph(patcher);
  377. }
  378. gs->map->objects[id.getNum()].dellNull();
  379. gs->map->calculateGuardingGreaturePositions();
  380. }
  381. static int getDir(int3 src, int3 dst)
  382. {
  383. int ret = -1;
  384. if(dst.x+1 == src.x && dst.y+1 == src.y) //tl
  385. {
  386. ret = 1;
  387. }
  388. else if(dst.x == src.x && dst.y+1 == src.y) //t
  389. {
  390. ret = 2;
  391. }
  392. else if(dst.x-1 == src.x && dst.y+1 == src.y) //tr
  393. {
  394. ret = 3;
  395. }
  396. else if(dst.x-1 == src.x && dst.y == src.y) //r
  397. {
  398. ret = 4;
  399. }
  400. else if(dst.x-1 == src.x && dst.y-1 == src.y) //br
  401. {
  402. ret = 5;
  403. }
  404. else if(dst.x == src.x && dst.y-1 == src.y) //b
  405. {
  406. ret = 6;
  407. }
  408. else if(dst.x+1 == src.x && dst.y-1 == src.y) //bl
  409. {
  410. ret = 7;
  411. }
  412. else if(dst.x+1 == src.x && dst.y == src.y) //l
  413. {
  414. ret = 8;
  415. }
  416. return ret;
  417. }
  418. void TryMoveHero::applyGs( CGameState *gs )
  419. {
  420. CGHeroInstance *h = gs->getHero(id);
  421. if (!h)
  422. {
  423. logGlobal->errorStream() << "Attempt ot move unavailable hero " << id;
  424. return;
  425. }
  426. h->movement = movePoints;
  427. if((result == SUCCESS || result == BLOCKING_VISIT || result == EMBARK || result == DISEMBARK) && start != end)
  428. {
  429. auto dir = getDir(start,end);
  430. if(dir > 0 && dir <= 8)
  431. h->moveDir = dir;
  432. //else don`t change move direction - hero might have traversed the subterranean gate, direction should be kept
  433. }
  434. if(result == EMBARK) //hero enters boat at destination tile
  435. {
  436. const TerrainTile &tt = gs->map->getTile(CGHeroInstance::convertPosition(end, false));
  437. assert(tt.visitableObjects.size() >= 1 && tt.visitableObjects.back()->ID == Obj::BOAT); //the only visitable object at destination is Boat
  438. CGBoat *boat = static_cast<CGBoat*>(tt.visitableObjects.back());
  439. gs->map->removeBlockVisTiles(boat); //hero blockvis mask will be used, we don't need to duplicate it with boat
  440. h->boat = boat;
  441. boat->hero = h;
  442. }
  443. else if(result == DISEMBARK) //hero leaves boat to destination tile
  444. {
  445. CGBoat *b = const_cast<CGBoat *>(h->boat);
  446. b->direction = h->moveDir;
  447. b->pos = start;
  448. b->hero = nullptr;
  449. gs->map->addBlockVisTiles(b);
  450. h->boat = nullptr;
  451. }
  452. if(start!=end && (result == SUCCESS || result == TELEPORTATION || result == EMBARK || result == DISEMBARK))
  453. {
  454. gs->map->removeBlockVisTiles(h);
  455. h->pos = end;
  456. if(CGBoat *b = const_cast<CGBoat *>(h->boat))
  457. b->pos = end;
  458. gs->map->addBlockVisTiles(h);
  459. }
  460. for(int3 t : fowRevealed)
  461. gs->getPlayerTeam(h->getOwner())->fogOfWarMap[t.x][t.y][t.z] = 1;
  462. }
  463. DLL_LINKAGE void NewStructures::applyGs( CGameState *gs )
  464. {
  465. CGTownInstance *t = gs->getTown(tid);
  466. for(const auto & id : bid)
  467. {
  468. assert(t->town->buildings.at(id) != nullptr);
  469. t->builtBuildings.insert(id);
  470. }
  471. t->builded = builded;
  472. t->recreateBuildingsBonuses();
  473. }
  474. DLL_LINKAGE void RazeStructures::applyGs( CGameState *gs )
  475. {
  476. CGTownInstance *t = gs->getTown(tid);
  477. for(const auto & id : bid)
  478. {
  479. t->builtBuildings.erase(id);
  480. }
  481. t->destroyed = destroyed; //yeaha
  482. t->recreateBuildingsBonuses();
  483. }
  484. DLL_LINKAGE void SetAvailableCreatures::applyGs( CGameState *gs )
  485. {
  486. CGDwelling *dw = dynamic_cast<CGDwelling*>(gs->getObjInstance(tid));
  487. assert(dw);
  488. dw->creatures = creatures;
  489. }
  490. DLL_LINKAGE void SetHeroesInTown::applyGs( CGameState *gs )
  491. {
  492. CGTownInstance *t = gs->getTown(tid);
  493. CGHeroInstance *v = gs->getHero(visiting),
  494. *g = gs->getHero(garrison);
  495. bool newVisitorComesFromGarrison = v && v == t->garrisonHero;
  496. bool newGarrisonComesFromVisiting = g && g == t->visitingHero;
  497. if(newVisitorComesFromGarrison)
  498. t->setGarrisonedHero(nullptr);
  499. if(newGarrisonComesFromVisiting)
  500. t->setVisitingHero(nullptr);
  501. if(!newGarrisonComesFromVisiting || v)
  502. t->setVisitingHero(v);
  503. if(!newVisitorComesFromGarrison || g)
  504. t->setGarrisonedHero(g);
  505. if(v)
  506. {
  507. gs->map->addBlockVisTiles(v);
  508. }
  509. if(g)
  510. {
  511. gs->map->removeBlockVisTiles(g);
  512. }
  513. }
  514. DLL_LINKAGE void HeroRecruited::applyGs( CGameState *gs )
  515. {
  516. assert(vstd::contains(gs->hpool.heroesPool, hid));
  517. CGHeroInstance *h = gs->hpool.heroesPool[hid];
  518. CGTownInstance *t = gs->getTown(tid);
  519. PlayerState *p = gs->getPlayer(player);
  520. assert(!h->boat);
  521. h->setOwner(player);
  522. h->pos = tile;
  523. bool fresh = !h->isInitialized();
  524. if(fresh)
  525. { // this is a fresh hero who hasn't appeared yet
  526. h->movement = h->maxMovePoints(true);
  527. }
  528. gs->hpool.heroesPool.erase(hid);
  529. if(h->id == ObjectInstanceID())
  530. {
  531. h->id = ObjectInstanceID(gs->map->objects.size());
  532. gs->map->objects.push_back(h);
  533. }
  534. else
  535. gs->map->objects[h->id.getNum()] = h;
  536. gs->map->heroesOnMap.push_back(h);
  537. p->heroes.push_back(h);
  538. h->attachTo(p);
  539. if(fresh)
  540. {
  541. h->initObj();
  542. }
  543. gs->map->addBlockVisTiles(h);
  544. if(t)
  545. {
  546. t->setVisitingHero(h);
  547. }
  548. }
  549. DLL_LINKAGE void GiveHero::applyGs( CGameState *gs )
  550. {
  551. CGHeroInstance *h = gs->getHero(id);
  552. //bonus system
  553. h->detachFrom(&gs->globalEffects);
  554. h->attachTo(gs->getPlayer(player));
  555. h->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, h->type->heroClass->id)->getTemplates().front();
  556. gs->map->removeBlockVisTiles(h,true);
  557. h->setOwner(player);
  558. h->movement = h->maxMovePoints(true);
  559. gs->map->heroesOnMap.push_back(h);
  560. gs->getPlayer(h->getOwner())->heroes.push_back(h);
  561. gs->map->addBlockVisTiles(h);
  562. h->inTownGarrison = false;
  563. }
  564. DLL_LINKAGE void NewObject::applyGs( CGameState *gs )
  565. {
  566. const TerrainTile &t = gs->map->getTile(pos);
  567. ETerrainType terrainType = t.terType;
  568. CGObjectInstance *o = nullptr;
  569. switch(ID)
  570. {
  571. case Obj::BOAT:
  572. o = new CGBoat();
  573. terrainType = ETerrainType::WATER; //TODO: either boat should only spawn on water, or all water objects should be handled this way
  574. break;
  575. case Obj::MONSTER: //probably more options will be needed
  576. o = new CGCreature();
  577. {
  578. //CStackInstance hlp;
  579. CGCreature *cre = static_cast<CGCreature*>(o);
  580. //cre->slots[0] = hlp;
  581. cre->notGrowingTeam = cre->neverFlees = 0;
  582. cre->character = 2;
  583. cre->gainedArtifact = ArtifactID::NONE;
  584. cre->identifier = -1;
  585. cre->addToSlot(SlotID(0), new CStackInstance(CreatureID(subID), -1)); //add placeholder stack
  586. }
  587. break;
  588. default:
  589. o = new CGObjectInstance();
  590. break;
  591. }
  592. o->ID = ID;
  593. o->subID = subID;
  594. o->pos = pos;
  595. o->appearance = VLC->objtypeh->getHandlerFor(o->ID, o->subID)->getTemplates(terrainType).front();
  596. id = o->id = ObjectInstanceID(gs->map->objects.size());
  597. gs->map->objects.push_back(o);
  598. gs->map->addBlockVisTiles(o);
  599. o->initObj();
  600. gs->map->calculateGuardingGreaturePositions();
  601. logGlobal->debugStream() << "added object id=" << id << "; address=" << (intptr_t)o << "; name=" << o->getObjectName();
  602. }
  603. DLL_LINKAGE void NewArtifact::applyGs( CGameState *gs )
  604. {
  605. assert(!vstd::contains(gs->map->artInstances, art));
  606. gs->map->addNewArtifactInstance(art);
  607. assert(!art->getParentNodes().size());
  608. art->setType(art->artType);
  609. if (CCombinedArtifactInstance* cart = dynamic_cast<CCombinedArtifactInstance*>(art.get()))
  610. cart->createConstituents();
  611. }
  612. DLL_LINKAGE const CStackInstance * StackLocation::getStack()
  613. {
  614. if(!army->hasStackAtSlot(slot))
  615. {
  616. logNetwork->warnStream() << "Warning: " << army->nodeName() << " don't have a stack at slot " << slot;
  617. return nullptr;
  618. }
  619. return &army->getStack(slot);
  620. }
  621. struct ObjectRetriever : boost::static_visitor<const CArmedInstance *>
  622. {
  623. const CArmedInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  624. {
  625. return h;
  626. }
  627. const CArmedInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  628. {
  629. return s->armyObj;
  630. }
  631. };
  632. template <typename T>
  633. struct GetBase : boost::static_visitor<T*>
  634. {
  635. template <typename TArg>
  636. T * operator()(TArg &arg) const
  637. {
  638. return arg;
  639. }
  640. };
  641. DLL_LINKAGE void ArtifactLocation::removeArtifact()
  642. {
  643. CArtifactInstance *a = getArt();
  644. assert(a);
  645. a->removeFrom(*this);
  646. }
  647. DLL_LINKAGE const CArmedInstance * ArtifactLocation::relatedObj() const
  648. {
  649. return boost::apply_visitor(ObjectRetriever(), artHolder);
  650. }
  651. DLL_LINKAGE PlayerColor ArtifactLocation::owningPlayer() const
  652. {
  653. auto obj = relatedObj();
  654. return obj ? obj->tempOwner : PlayerColor::NEUTRAL;
  655. }
  656. DLL_LINKAGE CArtifactSet *ArtifactLocation::getHolderArtSet()
  657. {
  658. return boost::apply_visitor(GetBase<CArtifactSet>(), artHolder);
  659. }
  660. DLL_LINKAGE CBonusSystemNode *ArtifactLocation::getHolderNode()
  661. {
  662. return boost::apply_visitor(GetBase<CBonusSystemNode>(), artHolder);
  663. }
  664. DLL_LINKAGE const CArtifactInstance *ArtifactLocation::getArt() const
  665. {
  666. const ArtSlotInfo *s = getSlot();
  667. if(s && s->artifact)
  668. {
  669. if(!s->locked)
  670. return s->artifact;
  671. else
  672. {
  673. logNetwork->warnStream() << "ArtifactLocation::getArt: This location is locked!";
  674. return nullptr;
  675. }
  676. }
  677. return nullptr;
  678. }
  679. DLL_LINKAGE const CArtifactSet * ArtifactLocation::getHolderArtSet() const
  680. {
  681. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  682. return t->getHolderArtSet();
  683. }
  684. DLL_LINKAGE const CBonusSystemNode * ArtifactLocation::getHolderNode() const
  685. {
  686. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  687. return t->getHolderNode();
  688. }
  689. DLL_LINKAGE CArtifactInstance *ArtifactLocation::getArt()
  690. {
  691. const ArtifactLocation *t = this;
  692. return const_cast<CArtifactInstance*>(t->getArt());
  693. }
  694. DLL_LINKAGE const ArtSlotInfo *ArtifactLocation::getSlot() const
  695. {
  696. return getHolderArtSet()->getSlot(slot);
  697. }
  698. DLL_LINKAGE void ChangeStackCount::applyGs( CGameState *gs )
  699. {
  700. if(absoluteValue)
  701. sl.army->setStackCount(sl.slot, count);
  702. else
  703. sl.army->changeStackCount(sl.slot, count);
  704. }
  705. DLL_LINKAGE void SetStackType::applyGs( CGameState *gs )
  706. {
  707. sl.army->setStackType(sl.slot, type);
  708. }
  709. DLL_LINKAGE void EraseStack::applyGs( CGameState *gs )
  710. {
  711. sl.army->eraseStack(sl.slot);
  712. }
  713. DLL_LINKAGE void SwapStacks::applyGs( CGameState *gs )
  714. {
  715. CStackInstance *s1 = sl1.army->detachStack(sl1.slot),
  716. *s2 = sl2.army->detachStack(sl2.slot);
  717. sl2.army->putStack(sl2.slot, s1);
  718. sl1.army->putStack(sl1.slot, s2);
  719. }
  720. DLL_LINKAGE void InsertNewStack::applyGs( CGameState *gs )
  721. {
  722. auto s = new CStackInstance(stack.type, stack.count);
  723. sl.army->putStack(sl.slot, s);
  724. }
  725. DLL_LINKAGE void RebalanceStacks::applyGs( CGameState *gs )
  726. {
  727. const CCreature *srcType = src.army->getCreature(src.slot);
  728. TQuantity srcCount = src.army->getStackCount(src.slot);
  729. bool stackExp = VLC->modh->modules.STACK_EXP;
  730. if(srcCount == count) //moving whole stack
  731. {
  732. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> merge
  733. {
  734. assert(c == srcType);
  735. UNUSED(c);
  736. auto alHere = ArtifactLocation (src.getStack(), ArtifactPosition::CREATURE_SLOT);
  737. auto alDest = ArtifactLocation (dst.getStack(), ArtifactPosition::CREATURE_SLOT);
  738. auto artHere = alHere.getArt();
  739. auto artDest = alDest.getArt();
  740. if (artHere)
  741. {
  742. if (alDest.getArt())
  743. {
  744. auto hero = dynamic_cast <CGHeroInstance *>(src.army.get());
  745. if (hero)
  746. {
  747. artDest->move (alDest, ArtifactLocation (hero, alDest.getArt()->firstBackpackSlot (hero)));
  748. }
  749. //else - artifact cna be lost :/
  750. else
  751. {
  752. logNetwork->warnStream() << "Artifact is present at destination slot!";
  753. }
  754. artHere->move (alHere, alDest);
  755. //TODO: choose from dialog
  756. }
  757. else //just move to the other slot before stack gets erased
  758. {
  759. artHere->move (alHere, alDest);
  760. }
  761. }
  762. if (stackExp)
  763. {
  764. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  765. src.army->eraseStack(src.slot);
  766. dst.army->changeStackCount(dst.slot, count);
  767. dst.army->setStackExp(dst.slot, totalExp /(dst.army->getStackCount(dst.slot))); //mean
  768. }
  769. else
  770. {
  771. src.army->eraseStack(src.slot);
  772. dst.army->changeStackCount(dst.slot, count);
  773. }
  774. }
  775. else //move stack to an empty slot, no exp change needed
  776. {
  777. CStackInstance *stackDetached = src.army->detachStack(src.slot);
  778. dst.army->putStack(dst.slot, stackDetached);
  779. }
  780. }
  781. else
  782. {
  783. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> rebalance
  784. {
  785. assert(c == srcType);
  786. UNUSED(c);
  787. if (stackExp)
  788. {
  789. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  790. src.army->changeStackCount(src.slot, -count);
  791. dst.army->changeStackCount(dst.slot, count);
  792. dst.army->setStackExp(dst.slot, totalExp /(src.army->getStackCount(src.slot) + dst.army->getStackCount(dst.slot))); //mean
  793. }
  794. else
  795. {
  796. src.army->changeStackCount(src.slot, -count);
  797. dst.army->changeStackCount(dst.slot, count);
  798. }
  799. }
  800. else //split stack to an empty slot
  801. {
  802. src.army->changeStackCount(src.slot, -count);
  803. dst.army->addToSlot(dst.slot, srcType->idNumber, count, false);
  804. if (stackExp)
  805. dst.army->setStackExp(dst.slot, src.army->getStackExperience(src.slot));
  806. }
  807. }
  808. CBonusSystemNode::treeHasChanged();
  809. }
  810. DLL_LINKAGE void PutArtifact::applyGs( CGameState *gs )
  811. {
  812. assert(art->canBePutAt(al));
  813. art->putAt(al);
  814. //al.hero->putArtifact(al.slot, art);
  815. }
  816. DLL_LINKAGE void EraseArtifact::applyGs( CGameState *gs )
  817. {
  818. auto slot = al.getSlot();
  819. if(slot->locked)
  820. {
  821. logGlobal->debugStream() << "Erasing locked artifact: " << slot->artifact->artType->Name();
  822. DisassembledArtifact dis;
  823. dis.al.artHolder = al.artHolder;
  824. auto aset = al.getHolderArtSet();
  825. bool found = false;
  826. for(auto& p : aset->artifactsWorn)
  827. {
  828. auto art = p.second.artifact;
  829. if(art->canBeDisassembled() && art->isPart(slot->artifact))
  830. {
  831. dis.al.slot = aset->getArtPos(art);
  832. found = true;
  833. break;
  834. }
  835. }
  836. assert(found && "Failed to determine the assembly this locked artifact belongs to");
  837. logGlobal->debugStream() << "Found the corresponding assembly: " << dis.al.getSlot()->artifact->artType->Name();
  838. dis.applyGs(gs);
  839. }
  840. else
  841. {
  842. logGlobal->debugStream() << "Erasing artifact " << slot->artifact->artType->Name();
  843. }
  844. al.removeArtifact();
  845. }
  846. DLL_LINKAGE void MoveArtifact::applyGs( CGameState *gs )
  847. {
  848. CArtifactInstance *a = src.getArt();
  849. if(dst.slot < GameConstants::BACKPACK_START)
  850. assert(!dst.getArt());
  851. a->move(src, dst);
  852. //TODO what'll happen if Titan's thunder is equipped by pickin git up or the start of game?
  853. if (a->artType->id == ArtifactID::TITANS_THUNDER && dst.slot == ArtifactPosition::RIGHT_HAND) //Titan's Thunder creates new spellbook on equip
  854. {
  855. auto hPtr = boost::get<ConstTransitivePtr<CGHeroInstance> >(&dst.artHolder);
  856. if(hPtr)
  857. {
  858. CGHeroInstance *h = *hPtr;
  859. if(h && !h->hasSpellbook())
  860. gs->giveHeroArtifact(h, ArtifactID::SPELLBOOK);
  861. }
  862. }
  863. }
  864. DLL_LINKAGE void AssembledArtifact::applyGs( CGameState *gs )
  865. {
  866. CArtifactSet *artSet = al.getHolderArtSet();
  867. const CArtifactInstance *transformedArt = al.getArt();
  868. assert(transformedArt);
  869. assert(vstd::contains(transformedArt->assemblyPossibilities(artSet), builtArt));
  870. UNUSED(transformedArt);
  871. auto combinedArt = new CCombinedArtifactInstance(builtArt);
  872. gs->map->addNewArtifactInstance(combinedArt);
  873. //retrieve all constituents
  874. for(const CArtifact * constituent : *builtArt->constituents)
  875. {
  876. ArtifactPosition pos = artSet->getArtPos(constituent->id);
  877. assert(pos >= 0);
  878. CArtifactInstance *constituentInstance = artSet->getArt(pos);
  879. //move constituent from hero to be part of new, combined artifact
  880. constituentInstance->removeFrom(ArtifactLocation(al.artHolder, pos));
  881. combinedArt->addAsConstituent(constituentInstance, pos);
  882. if(!vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], al.slot) && vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], pos))
  883. al.slot = pos;
  884. }
  885. //put new combined artifacts
  886. combinedArt->putAt(al);
  887. }
  888. DLL_LINKAGE void DisassembledArtifact::applyGs( CGameState *gs )
  889. {
  890. CCombinedArtifactInstance *disassembled = dynamic_cast<CCombinedArtifactInstance*>(al.getArt());
  891. assert(disassembled);
  892. std::vector<CCombinedArtifactInstance::ConstituentInfo> constituents = disassembled->constituentsInfo;
  893. disassembled->removeFrom(al);
  894. for(CCombinedArtifactInstance::ConstituentInfo &ci : constituents)
  895. {
  896. ArtifactLocation constituentLoc = al;
  897. constituentLoc.slot = (ci.slot >= 0 ? ci.slot : al.slot); //-1 is slot of main constituent -> it'll replace combined artifact in its pos
  898. disassembled->detachFrom(ci.art);
  899. ci.art->putAt(constituentLoc);
  900. }
  901. gs->map->eraseArtifactInstance(disassembled);
  902. }
  903. DLL_LINKAGE void HeroVisit::applyGs( CGameState *gs )
  904. {
  905. }
  906. DLL_LINKAGE void SetAvailableArtifacts::applyGs( CGameState *gs )
  907. {
  908. if(id >= 0)
  909. {
  910. if(CGBlackMarket *bm = dynamic_cast<CGBlackMarket*>(gs->map->objects[id].get()))
  911. {
  912. bm->artifacts = arts;
  913. }
  914. else
  915. {
  916. logNetwork->errorStream() << "Wrong black market id!";
  917. }
  918. }
  919. else
  920. {
  921. CGTownInstance::merchantArtifacts = arts;
  922. }
  923. }
  924. DLL_LINKAGE void NewTurn::applyGs( CGameState *gs )
  925. {
  926. gs->day = day;
  927. // Update bonuses before doing anything else so hero don't get more MP than needed
  928. gs->globalEffects.popBonuses(Bonus::OneDay); //works for children -> all game objs
  929. gs->globalEffects.updateBonuses(Bonus::NDays);
  930. gs->globalEffects.updateBonuses(Bonus::OneWeek);
  931. //TODO not really a single root hierarchy, what about bonuses placed elsewhere? [not an issue with H3 mechanics but in the future...]
  932. for(NewTurn::Hero h : heroes) //give mana/movement point
  933. {
  934. CGHeroInstance *hero = gs->getHero(h.id);
  935. hero->movement = h.move;
  936. hero->mana = h.mana;
  937. }
  938. for(auto i = res.cbegin(); i != res.cend(); i++)
  939. {
  940. assert(i->first < PlayerColor::PLAYER_LIMIT);
  941. gs->getPlayer(i->first)->resources = i->second;
  942. }
  943. for(auto creatureSet : cres) //set available creatures in towns
  944. creatureSet.second.applyGs(gs);
  945. for(CGTownInstance* t : gs->map->towns)
  946. t->builded = 0;
  947. if(gs->getDate(Date::DAY_OF_WEEK) == 1)
  948. gs->updateRumor();
  949. }
  950. DLL_LINKAGE void SetObjectProperty::applyGs( CGameState *gs )
  951. {
  952. CGObjectInstance *obj = gs->getObjInstance(id);
  953. if(!obj)
  954. {
  955. logNetwork->errorStream() << "Wrong object ID - property cannot be set!";
  956. return;
  957. }
  958. CArmedInstance *cai = dynamic_cast<CArmedInstance *>(obj);
  959. if(what == ObjProperty::OWNER && cai)
  960. {
  961. if(obj->ID == Obj::TOWN)
  962. {
  963. CGTownInstance *t = static_cast<CGTownInstance*>(obj);
  964. if(t->tempOwner < PlayerColor::PLAYER_LIMIT)
  965. gs->getPlayer(t->tempOwner)->towns -= t;
  966. if(val < PlayerColor::PLAYER_LIMIT_I)
  967. gs->getPlayer(PlayerColor(val))->towns.push_back(t);
  968. }
  969. CBonusSystemNode *nodeToMove = cai->whatShouldBeAttached();
  970. nodeToMove->detachFrom(cai->whereShouldBeAttached(gs));
  971. obj->setProperty(what,val);
  972. nodeToMove->attachTo(cai->whereShouldBeAttached(gs));
  973. }
  974. else //not an armed instance
  975. {
  976. obj->setProperty(what,val);
  977. }
  978. }
  979. DLL_LINKAGE void HeroLevelUp::applyGs( CGameState *gs )
  980. {
  981. CGHeroInstance * h = gs->getHero(hero->id);
  982. h->levelUp(skills);
  983. }
  984. DLL_LINKAGE void CommanderLevelUp::applyGs (CGameState *gs)
  985. {
  986. CCommanderInstance * commander = gs->getHero(hero->id)->commander;
  987. assert (commander);
  988. commander->levelUp();
  989. }
  990. DLL_LINKAGE void BattleStart::applyGs( CGameState *gs )
  991. {
  992. gs->curB = info;
  993. gs->curB->localInit();
  994. }
  995. DLL_LINKAGE void BattleNextRound::applyGs( CGameState *gs )
  996. {
  997. for (int i = 0; i < 2; ++i)
  998. {
  999. gs->curB->sides[i].castSpellsCount = 0;
  1000. vstd::amax(--gs->curB->sides[i].enchanterCounter, 0);
  1001. }
  1002. gs->curB->round = round;
  1003. for(CStack *s : gs->curB->stacks)
  1004. {
  1005. s->state -= EBattleStackState::DEFENDING;
  1006. s->state -= EBattleStackState::WAITING;
  1007. s->state -= EBattleStackState::MOVED;
  1008. s->state -= EBattleStackState::HAD_MORALE;
  1009. s->state -= EBattleStackState::FEAR;
  1010. s->state -= EBattleStackState::DRAINED_MANA;
  1011. s->counterAttacksPerformed = 0;
  1012. s->counterAttacksTotalCache = 0;
  1013. // new turn effects
  1014. s->battleTurnPassed();
  1015. }
  1016. for(auto &obst : gs->curB->obstacles)
  1017. obst->battleTurnPassed();
  1018. }
  1019. DLL_LINKAGE void BattleSetActiveStack::applyGs( CGameState *gs )
  1020. {
  1021. gs->curB->activeStack = stack;
  1022. CStack *st = gs->curB->getStack(stack);
  1023. //remove bonuses that last until when stack gets new turn
  1024. st->popBonuses(Bonus::UntilGetsTurn);
  1025. if(vstd::contains(st->state,EBattleStackState::MOVED)) //if stack is moving second time this turn it must had a high morale bonus
  1026. st->state.insert(EBattleStackState::HAD_MORALE);
  1027. }
  1028. DLL_LINKAGE void BattleTriggerEffect::applyGs( CGameState *gs )
  1029. {
  1030. CStack *st = gs->curB->getStack(stackID);
  1031. switch (effect)
  1032. {
  1033. case Bonus::HP_REGENERATION:
  1034. st->firstHPleft += val;
  1035. vstd::amin (st->firstHPleft, (ui32)st->MaxHealth());
  1036. break;
  1037. case Bonus::MANA_DRAIN:
  1038. {
  1039. CGHeroInstance * h = gs->getHero(ObjectInstanceID(additionalInfo));
  1040. st->state.insert (EBattleStackState::DRAINED_MANA);
  1041. h->mana -= val;
  1042. vstd::amax(h->mana, 0);
  1043. break;
  1044. }
  1045. case Bonus::POISON:
  1046. {
  1047. Bonus * b = st->getBonusLocalFirst(Selector::source(Bonus::SPELL_EFFECT, SpellID::POISON)
  1048. .And(Selector::type(Bonus::STACK_HEALTH)));
  1049. if (b)
  1050. b->val = val;
  1051. break;
  1052. }
  1053. case Bonus::ENCHANTER:
  1054. break;
  1055. case Bonus::FEAR:
  1056. st->state.insert(EBattleStackState::FEAR);
  1057. break;
  1058. default:
  1059. logNetwork->warnStream() << "Unrecognized trigger effect type "<< type;
  1060. }
  1061. }
  1062. DLL_LINKAGE void BattleObstaclePlaced::applyGs( CGameState *gs )
  1063. {
  1064. gs->curB->obstacles.push_back(obstacle);
  1065. }
  1066. DLL_LINKAGE void BattleUpdateGateState::applyGs(CGameState *gs)
  1067. {
  1068. if(gs->curB)
  1069. gs->curB->si.gateState = state;
  1070. }
  1071. void BattleResult::applyGs( CGameState *gs )
  1072. {
  1073. for (CStack *s : gs->curB->stacks)
  1074. {
  1075. if (s->base && s->base->armyObj && vstd::contains(s->state, EBattleStackState::SUMMONED))
  1076. {
  1077. //stack with SUMMONED flag but coming from garrison -> most likely resurrected, needs to be removed
  1078. assert(&s->base->armyObj->getStack(s->slot) == s->base);
  1079. const_cast<CArmedInstance*>(s->base->armyObj)->eraseStack(s->slot);
  1080. }
  1081. }
  1082. for (auto & elem : gs->curB->stacks)
  1083. delete elem;
  1084. for(int i = 0; i < 2; ++i)
  1085. {
  1086. if(auto h = gs->curB->battleGetFightingHero(i))
  1087. {
  1088. h->popBonuses(Bonus::OneBattle); //remove any "until next battle" bonuses
  1089. if (h->commander && h->commander->alive)
  1090. {
  1091. for (auto art : h->commander->artifactsWorn) //increment bonuses for commander artifacts
  1092. {
  1093. art.second.artifact->artType->levelUpArtifact (art.second.artifact);
  1094. }
  1095. }
  1096. }
  1097. }
  1098. if(VLC->modh->modules.STACK_EXP)
  1099. {
  1100. for(int i = 0; i < 2; i++)
  1101. if(exp[i])
  1102. gs->curB->battleGetArmyObject(i)->giveStackExp(exp[i]);
  1103. CBonusSystemNode::treeHasChanged();
  1104. }
  1105. for(int i = 0; i < 2; i++)
  1106. gs->curB->battleGetArmyObject(i)->battle = nullptr;
  1107. gs->curB.dellNull();
  1108. }
  1109. void BattleStackMoved::applyGs( CGameState *gs )
  1110. {
  1111. CStack *s = gs->curB->getStack(stack);
  1112. assert(s);
  1113. BattleHex dest = tilesToMove.back();
  1114. //if unit ended movement on quicksands that were created by enemy, that quicksand patch becomes visible for owner
  1115. for(auto &oi : gs->curB->obstacles)
  1116. {
  1117. if(oi->obstacleType == CObstacleInstance::QUICKSAND
  1118. && vstd::contains(oi->getAffectedTiles(), tilesToMove.back()))
  1119. {
  1120. SpellCreatedObstacle *sands = dynamic_cast<SpellCreatedObstacle*>(oi.get());
  1121. assert(sands);
  1122. if(sands->casterSide != !s->attackerOwned)
  1123. sands->visibleForAnotherSide = true;
  1124. }
  1125. }
  1126. s->position = dest;
  1127. }
  1128. DLL_LINKAGE void BattleStackAttacked::applyGs( CGameState *gs )
  1129. {
  1130. CStack * at = gs->curB->getStack(stackAttacked);
  1131. assert(at);
  1132. at->count = newAmount;
  1133. at->firstHPleft = newHP;
  1134. if(killed())
  1135. {
  1136. at->state -= EBattleStackState::ALIVE;
  1137. }
  1138. //life drain handling
  1139. for (auto & elem : healedStacks)
  1140. {
  1141. elem.applyGs(gs);
  1142. }
  1143. if (willRebirth())
  1144. {
  1145. at->casts--;
  1146. at->state.insert(EBattleStackState::ALIVE); //hmm?
  1147. }
  1148. if (cloneKilled())
  1149. {
  1150. //"hide" killed creatures instead so we keep info about it
  1151. at->state.insert(EBattleStackState::DEAD_CLONE);
  1152. for(CStack * s : gs->curB->stacks)
  1153. {
  1154. if(s->cloneID == at->ID)
  1155. s->cloneID = -1;
  1156. }
  1157. }
  1158. }
  1159. DLL_LINKAGE void BattleAttack::applyGs( CGameState *gs )
  1160. {
  1161. CStack *attacker = gs->curB->getStack(stackAttacking);
  1162. if(counter())
  1163. attacker->counterAttacksPerformed++;
  1164. if(shot())
  1165. {
  1166. //don't remove ammo if we have a working ammo cart
  1167. bool hasAmmoCart = false;
  1168. for(const CStack * st : gs->curB->stacks)
  1169. {
  1170. if(st->owner == attacker->owner && st->getCreature()->idNumber == CreatureID::AMMO_CART && st->alive())
  1171. {
  1172. hasAmmoCart = true;
  1173. break;
  1174. }
  1175. }
  1176. if (!hasAmmoCart)
  1177. {
  1178. attacker->shots--;
  1179. }
  1180. }
  1181. for(BattleStackAttacked stackAttacked : bsa)
  1182. stackAttacked.applyGs(gs);
  1183. attacker->popBonuses(Bonus::UntilAttack);
  1184. for(auto & elem : bsa)
  1185. {
  1186. CStack * stack = gs->curB->getStack(elem.stackAttacked, false);
  1187. if (stack) //cloned stack is already gone
  1188. stack->popBonuses(Bonus::UntilBeingAttacked);
  1189. }
  1190. }
  1191. DLL_LINKAGE void StartAction::applyGs( CGameState *gs )
  1192. {
  1193. CStack *st = gs->curB->getStack(ba.stackNumber);
  1194. if(ba.actionType == Battle::END_TACTIC_PHASE)
  1195. {
  1196. gs->curB->tacticDistance = 0;
  1197. return;
  1198. }
  1199. if(gs->curB->tacticDistance)
  1200. {
  1201. // moves in tactics phase do not affect creature status
  1202. // (tactics stack queue is managed by client)
  1203. return;
  1204. }
  1205. if(ba.actionType != Battle::HERO_SPELL) //don't check for stack if it's custom action by hero
  1206. {
  1207. assert(st);
  1208. }
  1209. else
  1210. {
  1211. gs->curB->sides[ba.side].usedSpellsHistory.push_back(SpellID(ba.additionalInfo).toSpell());
  1212. }
  1213. switch(ba.actionType)
  1214. {
  1215. case Battle::DEFEND:
  1216. st->state -= EBattleStackState::DEFENDING_ANIM;
  1217. st->state.insert(EBattleStackState::DEFENDING);
  1218. st->state.insert(EBattleStackState::DEFENDING_ANIM);
  1219. break;
  1220. case Battle::WAIT:
  1221. st->state -= EBattleStackState::DEFENDING_ANIM;
  1222. st->state.insert(EBattleStackState::WAITING);
  1223. return;
  1224. case Battle::HERO_SPELL: //no change in current stack state
  1225. return;
  1226. default: //any active stack action - attack, catapult, heal, spell...
  1227. st->state -= EBattleStackState::DEFENDING_ANIM;
  1228. st->state.insert(EBattleStackState::MOVED);
  1229. break;
  1230. }
  1231. if(st)
  1232. st->state -= EBattleStackState::WAITING; //if stack was waiting it has made move, so it won't be "waiting" anymore (if the action was WAIT, then we have returned)
  1233. }
  1234. DLL_LINKAGE void BattleSpellCast::applyGs( CGameState *gs )
  1235. {
  1236. assert(gs->curB);
  1237. const CSpell * spell = SpellID(id).toSpell();
  1238. spell->applyBattle(gs->curB, this);
  1239. }
  1240. void actualizeEffect(CStack * s, const Bonus & ef)
  1241. {
  1242. for(Bonus *stackBonus : s->getBonusList()) //TODO: optimize
  1243. {
  1244. if(stackBonus->source == Bonus::SPELL_EFFECT && stackBonus->type == ef.type && stackBonus->subtype == ef.subtype)
  1245. {
  1246. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, ef.turnsRemain);
  1247. }
  1248. }
  1249. CBonusSystemNode::treeHasChanged();
  1250. }
  1251. void actualizeEffect(CStack * s, const std::vector<Bonus> & ef)
  1252. {
  1253. //actualizing features vector
  1254. for(const Bonus &fromEffect : ef)
  1255. {
  1256. actualizeEffect(s, fromEffect);
  1257. }
  1258. }
  1259. DLL_LINKAGE void SetStackEffect::applyGs( CGameState *gs )
  1260. {
  1261. if (effect.empty())
  1262. {
  1263. logGlobal->errorStream() << "Trying to apply SetStackEffect with no effects";
  1264. return;
  1265. }
  1266. int spellid = effect.begin()->sid; //effects' source ID
  1267. for(ui32 id : stacks)
  1268. {
  1269. CStack *s = gs->curB->getStack(id);
  1270. if(s)
  1271. {
  1272. if(spellid == SpellID::DISRUPTING_RAY || spellid == SpellID::ACID_BREATH_DEFENSE || !s->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellid)))//disrupting ray or acid breath or not on the list - just add
  1273. {
  1274. for(Bonus &fromEffect : effect)
  1275. {
  1276. logBonus->traceStream() << s->nodeName() << " receives a new bonus: " << fromEffect.Description();
  1277. s->addNewBonus( new Bonus(fromEffect));
  1278. }
  1279. }
  1280. else //just actualize
  1281. {
  1282. actualizeEffect(s, effect);
  1283. }
  1284. }
  1285. else
  1286. logNetwork->errorStream() << "Cannot find stack " << id;
  1287. }
  1288. typedef std::pair<ui32, Bonus> p;
  1289. for(p para : uniqueBonuses)
  1290. {
  1291. CStack *s = gs->curB->getStack(para.first);
  1292. if (s)
  1293. {
  1294. if (!s->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellid).And(Selector::typeSubtype(para.second.type, para.second.subtype))))
  1295. s->addNewBonus(new Bonus(para.second));
  1296. else
  1297. actualizeEffect(s, effect);
  1298. }
  1299. else
  1300. logNetwork->errorStream() << "Cannot find stack " << para.first;
  1301. }
  1302. }
  1303. DLL_LINKAGE void StacksInjured::applyGs( CGameState *gs )
  1304. {
  1305. for(BattleStackAttacked stackAttacked : stacks)
  1306. stackAttacked.applyGs(gs);
  1307. }
  1308. DLL_LINKAGE void StacksHealedOrResurrected::applyGs( CGameState *gs )
  1309. {
  1310. for(auto & elem : healedStacks)
  1311. {
  1312. CStack * changedStack = gs->curB->getStack(elem.stackID, false);
  1313. //checking if we resurrect a stack that is under a living stack
  1314. auto accessibility = gs->curB->getAccesibility();
  1315. if(!changedStack->alive() && !accessibility.accessible(changedStack->position, changedStack))
  1316. {
  1317. logNetwork->errorStream() << "Cannot resurrect " << changedStack->nodeName() << " because hex " << changedStack->position << " is occupied!";
  1318. return; //position is already occupied
  1319. }
  1320. //applying changes
  1321. bool resurrected = !changedStack->alive(); //indicates if stack is resurrected or just healed
  1322. if(resurrected)
  1323. {
  1324. changedStack->state.insert(EBattleStackState::ALIVE);
  1325. }
  1326. //int missingHPfirst = changedStack->MaxHealth() - changedStack->firstHPleft;
  1327. int res = std::min( elem.healedHP / changedStack->MaxHealth() , changedStack->baseAmount - changedStack->count );
  1328. changedStack->count += res;
  1329. if(elem.lowLevelResurrection)
  1330. changedStack->resurrected += res;
  1331. changedStack->firstHPleft += elem.healedHP - res * changedStack->MaxHealth();
  1332. if(changedStack->firstHPleft > changedStack->MaxHealth())
  1333. {
  1334. changedStack->firstHPleft -= changedStack->MaxHealth();
  1335. if(changedStack->baseAmount > changedStack->count)
  1336. {
  1337. changedStack->count += 1;
  1338. }
  1339. }
  1340. vstd::amin(changedStack->firstHPleft, changedStack->MaxHealth());
  1341. if(resurrected)
  1342. {
  1343. //removing all effects from negative spells
  1344. auto selector = [](const Bonus * b)
  1345. {
  1346. const CSpell *s = b->sourceSpell();
  1347. //Special case: DISRUPTING_RAY is "immune" to dispell
  1348. //Other even PERMANENT effects can be removed
  1349. return (s != nullptr) && s->isNegative() && (s->id != SpellID::DISRUPTING_RAY);
  1350. };
  1351. changedStack->popBonuses(selector);
  1352. }
  1353. }
  1354. }
  1355. DLL_LINKAGE void ObstaclesRemoved::applyGs( CGameState *gs )
  1356. {
  1357. if(gs->curB) //if there is a battle
  1358. {
  1359. for(const si32 rem_obst :obstacles)
  1360. {
  1361. for(int i=0; i<gs->curB->obstacles.size(); ++i)
  1362. {
  1363. if(gs->curB->obstacles[i]->uniqueID == rem_obst) //remove this obstacle
  1364. {
  1365. gs->curB->obstacles.erase(gs->curB->obstacles.begin() + i);
  1366. break;
  1367. }
  1368. }
  1369. }
  1370. }
  1371. }
  1372. DLL_LINKAGE CatapultAttack::CatapultAttack()
  1373. {
  1374. type = 3015;
  1375. }
  1376. DLL_LINKAGE CatapultAttack::~CatapultAttack()
  1377. {
  1378. }
  1379. DLL_LINKAGE void CatapultAttack::applyGs( CGameState *gs )
  1380. {
  1381. if(gs->curB && gs->curB->town && gs->curB->town->fortLevel() != CGTownInstance::NONE) //if there is a battle and it's a siege
  1382. {
  1383. for(const auto &it :attackedParts)
  1384. {
  1385. gs->curB->si.wallState[it.attackedPart] =
  1386. SiegeInfo::applyDamage(EWallState::EWallState(gs->curB->si.wallState[it.attackedPart]), it.damageDealt);
  1387. }
  1388. }
  1389. }
  1390. DLL_LINKAGE std::string CatapultAttack::AttackInfo::toString() const
  1391. {
  1392. return boost::str(boost::format("{AttackInfo: destinationTile '%d', attackedPart '%d', damageDealt '%d'}")
  1393. % destinationTile % static_cast<int>(attackedPart) % static_cast<int>(damageDealt));
  1394. }
  1395. DLL_LINKAGE std::ostream & operator<<(std::ostream & out, const CatapultAttack::AttackInfo & attackInfo)
  1396. {
  1397. return out << attackInfo.toString();
  1398. }
  1399. DLL_LINKAGE std::string CatapultAttack::toString() const
  1400. {
  1401. return boost::str(boost::format("{CatapultAttack: attackedParts '%s', attacker '%d'}") % attackedParts % attacker);
  1402. }
  1403. DLL_LINKAGE void BattleStacksRemoved::applyGs( CGameState *gs )
  1404. {
  1405. if(!gs->curB)
  1406. return;
  1407. for(ui32 rem_stack : stackIDs)
  1408. {
  1409. for(int b=0; b<gs->curB->stacks.size(); ++b) //find it in vector of stacks
  1410. {
  1411. if(gs->curB->stacks[b]->ID == rem_stack) //if found
  1412. {
  1413. CStack *toRemove = gs->curB->stacks[b];
  1414. gs->curB->stacks.erase(gs->curB->stacks.begin() + b); //remove
  1415. toRemove->detachFromAll();
  1416. delete toRemove;
  1417. break;
  1418. }
  1419. }
  1420. }
  1421. }
  1422. DLL_LINKAGE void BattleStackAdded::applyGs(CGameState *gs)
  1423. {
  1424. newStackID = 0;
  1425. if (!BattleHex(pos).isValid())
  1426. {
  1427. logNetwork->warnStream() << "No place found for new stack!";
  1428. return;
  1429. }
  1430. CStackBasicDescriptor csbd(creID, amount);
  1431. CStack * addedStack = gs->curB->generateNewStack(csbd, attacker, SlotID(255), pos); //TODO: netpacks?
  1432. if (summoned)
  1433. addedStack->state.insert(EBattleStackState::SUMMONED);
  1434. gs->curB->localInitStack(addedStack);
  1435. gs->curB->stacks.push_back(addedStack); //the stack is not "SUMMONED", it is permanent
  1436. newStackID = addedStack->ID;
  1437. }
  1438. DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState *gs)
  1439. {
  1440. CStack * stack = gs->curB->getStack(stackID);
  1441. switch (which)
  1442. {
  1443. case CASTS:
  1444. {
  1445. if (absolute)
  1446. stack->casts = val;
  1447. else
  1448. stack->casts += val;
  1449. vstd::amax(stack->casts, 0);
  1450. break;
  1451. }
  1452. case ENCHANTER_COUNTER:
  1453. {
  1454. auto & counter = gs->curB->sides[gs->curB->whatSide(stack->owner)].enchanterCounter;
  1455. if (absolute)
  1456. counter = val;
  1457. else
  1458. counter += val;
  1459. vstd::amax(counter, 0);
  1460. break;
  1461. }
  1462. case UNBIND:
  1463. {
  1464. stack->popBonuses(Selector::type(Bonus::BIND_EFFECT));
  1465. break;
  1466. }
  1467. case CLONED:
  1468. {
  1469. stack->state.insert(EBattleStackState::CLONED);
  1470. break;
  1471. }
  1472. case HAS_CLONE:
  1473. {
  1474. stack->cloneID = val;
  1475. break;
  1476. }
  1477. }
  1478. }
  1479. DLL_LINKAGE void YourTurn::applyGs( CGameState *gs )
  1480. {
  1481. gs->currentPlayer = player;
  1482. auto & playerState = gs->players[player];
  1483. playerState.daysWithoutCastle = daysWithoutCastle;
  1484. }
  1485. DLL_LINKAGE Component::Component(const CStackBasicDescriptor &stack)
  1486. : id(CREATURE), subtype(stack.type->idNumber), val(stack.count), when(0)
  1487. {
  1488. type = 2002;
  1489. }