NetPacksLib.cpp 44 KB

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