NetPacksLib.cpp 48 KB

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