2
0

NetPacksLib.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  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. }
  336. static int getDir(int3 src, int3 dst)
  337. {
  338. int ret = -1;
  339. if(dst.x+1 == src.x && dst.y+1 == src.y) //tl
  340. {
  341. ret = 1;
  342. }
  343. else if(dst.x == src.x && dst.y+1 == src.y) //t
  344. {
  345. ret = 2;
  346. }
  347. else if(dst.x-1 == src.x && dst.y+1 == src.y) //tr
  348. {
  349. ret = 3;
  350. }
  351. else if(dst.x-1 == src.x && dst.y == src.y) //r
  352. {
  353. ret = 4;
  354. }
  355. else if(dst.x-1 == src.x && dst.y-1 == src.y) //br
  356. {
  357. ret = 5;
  358. }
  359. else if(dst.x == src.x && dst.y-1 == src.y) //b
  360. {
  361. ret = 6;
  362. }
  363. else if(dst.x+1 == src.x && dst.y-1 == src.y) //bl
  364. {
  365. ret = 7;
  366. }
  367. else if(dst.x+1 == src.x && dst.y == src.y) //l
  368. {
  369. ret = 8;
  370. }
  371. return ret;
  372. }
  373. void TryMoveHero::applyGs( CGameState *gs )
  374. {
  375. CGHeroInstance *h = gs->getHero(id);
  376. h->movement = movePoints;
  377. if((result == SUCCESS || result == BLOCKING_VISIT || result == EMBARK || result == DISEMBARK) && start != end)
  378. {
  379. auto dir = getDir(start,end);
  380. if(dir > 0 && dir <= 8)
  381. h->moveDir = dir;
  382. //else dont change movedir - hero might have traversed the subterranean gate, dorectopm shpuld be kept
  383. }
  384. if(result == EMBARK) //hero enters boat at dest tile
  385. {
  386. const TerrainTile &tt = gs->map->getTile(CGHeroInstance::convertPosition(end, false));
  387. assert(tt.visitableObjects.size() >= 1 && tt.visitableObjects.back()->ID == Obj::BOAT); //the only vis obj at dest is Boat
  388. CGBoat *boat = static_cast<CGBoat*>(tt.visitableObjects.back());
  389. gs->map->removeBlockVisTiles(boat); //hero blockvis mask will be used, we don't need to duplicate it with boat
  390. h->boat = boat;
  391. boat->hero = h;
  392. }
  393. else if(result == DISEMBARK) //hero leaves boat to dest tile
  394. {
  395. CGBoat *b = const_cast<CGBoat *>(h->boat);
  396. b->direction = h->moveDir;
  397. b->pos = start;
  398. b->hero = nullptr;
  399. gs->map->addBlockVisTiles(b);
  400. h->boat = nullptr;
  401. }
  402. if(start!=end && (result == SUCCESS || result == TELEPORTATION || result == EMBARK || result == DISEMBARK))
  403. {
  404. gs->map->removeBlockVisTiles(h);
  405. h->pos = end;
  406. if(CGBoat *b = const_cast<CGBoat *>(h->boat))
  407. b->pos = end;
  408. gs->map->addBlockVisTiles(h);
  409. }
  410. for(int3 t : fowRevealed)
  411. gs->getPlayerTeam(h->getOwner())->fogOfWarMap[t.x][t.y][t.z] = 1;
  412. }
  413. DLL_LINKAGE void NewStructures::applyGs( CGameState *gs )
  414. {
  415. CGTownInstance *t = gs->getTown(tid);
  416. for(const auto & id : bid)
  417. {
  418. assert(t->town->buildings.at(id) != nullptr);
  419. t->builtBuildings.insert(id);
  420. }
  421. t->builded = builded;
  422. t->recreateBuildingsBonuses();
  423. }
  424. DLL_LINKAGE void RazeStructures::applyGs( CGameState *gs )
  425. {
  426. CGTownInstance *t = gs->getTown(tid);
  427. for(const auto & id : bid)
  428. {
  429. t->builtBuildings.erase(id);
  430. }
  431. t->destroyed = destroyed; //yeaha
  432. t->recreateBuildingsBonuses();
  433. }
  434. DLL_LINKAGE void SetAvailableCreatures::applyGs( CGameState *gs )
  435. {
  436. CGDwelling *dw = dynamic_cast<CGDwelling*>(gs->getObjInstance(tid));
  437. assert(dw);
  438. dw->creatures = creatures;
  439. }
  440. DLL_LINKAGE void SetHeroesInTown::applyGs( CGameState *gs )
  441. {
  442. CGTownInstance *t = gs->getTown(tid);
  443. CGHeroInstance *v = gs->getHero(visiting),
  444. *g = gs->getHero(garrison);
  445. bool newVisitorComesFromGarrison = v && v == t->garrisonHero;
  446. bool newGarrisonComesFromVisiting = g && g == t->visitingHero;
  447. if(newVisitorComesFromGarrison)
  448. t->setGarrisonedHero(nullptr);
  449. if(newGarrisonComesFromVisiting)
  450. t->setVisitingHero(nullptr);
  451. if(!newGarrisonComesFromVisiting || v)
  452. t->setVisitingHero(v);
  453. if(!newVisitorComesFromGarrison || g)
  454. t->setGarrisonedHero(g);
  455. if(v)
  456. {
  457. gs->map->addBlockVisTiles(v);
  458. }
  459. if(g)
  460. {
  461. gs->map->removeBlockVisTiles(g);
  462. }
  463. }
  464. DLL_LINKAGE void HeroRecruited::applyGs( CGameState *gs )
  465. {
  466. assert(vstd::contains(gs->hpool.heroesPool, hid));
  467. CGHeroInstance *h = gs->hpool.heroesPool[hid];
  468. CGTownInstance *t = gs->getTown(tid);
  469. PlayerState *p = gs->getPlayer(player);
  470. assert(!h->boat);
  471. h->setOwner(player);
  472. h->pos = tile;
  473. h->movement = h->maxMovePoints(true);
  474. gs->hpool.heroesPool.erase(hid);
  475. if(h->id == ObjectInstanceID())
  476. {
  477. h->id = ObjectInstanceID(gs->map->objects.size());
  478. gs->map->objects.push_back(h);
  479. }
  480. else
  481. gs->map->objects[h->id.getNum()] = h;
  482. gs->map->heroesOnMap.push_back(h);
  483. p->heroes.push_back(h);
  484. h->attachTo(p);
  485. h->initObj();
  486. gs->map->addBlockVisTiles(h);
  487. if(t)
  488. {
  489. t->setVisitingHero(h);
  490. }
  491. }
  492. DLL_LINKAGE void GiveHero::applyGs( CGameState *gs )
  493. {
  494. CGHeroInstance *h = gs->getHero(id);
  495. //bonus system
  496. h->detachFrom(&gs->globalEffects);
  497. h->attachTo(gs->getPlayer(player));
  498. h->appearance = VLC->dobjinfo->pickCandidates(Obj::HERO, h->type->heroClass->id).front();
  499. gs->map->removeBlockVisTiles(h,true);
  500. h->setOwner(player);
  501. h->movement = h->maxMovePoints(true);
  502. gs->map->heroesOnMap.push_back(h);
  503. gs->getPlayer(h->getOwner())->heroes.push_back(h);
  504. gs->map->addBlockVisTiles(h);
  505. h->inTownGarrison = false;
  506. }
  507. DLL_LINKAGE void NewObject::applyGs( CGameState *gs )
  508. {
  509. CGObjectInstance *o = nullptr;
  510. switch(ID)
  511. {
  512. case Obj::BOAT:
  513. o = new CGBoat();
  514. break;
  515. case Obj::MONSTER: //probably more options will be needed
  516. o = new CGCreature();
  517. {
  518. //CStackInstance hlp;
  519. CGCreature *cre = static_cast<CGCreature*>(o);
  520. //cre->slots[0] = hlp;
  521. cre->notGrowingTeam = cre->neverFlees = 0;
  522. cre->character = 2;
  523. cre->gainedArtifact = ArtifactID::NONE;
  524. cre->identifier = -1;
  525. cre->addToSlot(SlotID(0), new CStackInstance(CreatureID(subID), -1)); //add placeholder stack
  526. }
  527. break;
  528. default:
  529. o = new CGObjectInstance();
  530. break;
  531. }
  532. o->ID = ID;
  533. o->subID = subID;
  534. o->pos = pos;
  535. const TerrainTile &t = gs->map->getTile(pos);
  536. o->appearance = VLC->dobjinfo->pickCandidates(o->ID, o->subID, t.terType).front();
  537. id = o->id = ObjectInstanceID(gs->map->objects.size());
  538. o->hoverName = VLC->generaltexth->names[ID];
  539. gs->map->objects.push_back(o);
  540. gs->map->addBlockVisTiles(o);
  541. o->initObj();
  542. logGlobal->debugStream() << "added object id=" << id << "; address=" << (intptr_t)o << "; name=" << o->getHoverText();
  543. }
  544. DLL_LINKAGE void NewArtifact::applyGs( CGameState *gs )
  545. {
  546. assert(!vstd::contains(gs->map->artInstances, art));
  547. gs->map->addNewArtifactInstance(art);
  548. assert(!art->getParentNodes().size());
  549. art->setType(art->artType);
  550. if (CCombinedArtifactInstance* cart = dynamic_cast<CCombinedArtifactInstance*>(art.get()))
  551. cart->createConstituents();
  552. }
  553. DLL_LINKAGE const CStackInstance * StackLocation::getStack()
  554. {
  555. if(!army->hasStackAtSlot(slot))
  556. {
  557. logNetwork->warnStream() << "Warning: " << army->nodeName() << " don't have a stack at slot " << slot;
  558. return nullptr;
  559. }
  560. return &army->getStack(slot);
  561. }
  562. struct ObjectRetriever : boost::static_visitor<const CArmedInstance *>
  563. {
  564. const CArmedInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  565. {
  566. return h;
  567. }
  568. const CArmedInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  569. {
  570. return s->armyObj;
  571. }
  572. };
  573. template <typename T>
  574. struct GetBase : boost::static_visitor<T*>
  575. {
  576. template <typename TArg>
  577. T * operator()(TArg &arg) const
  578. {
  579. return arg;
  580. }
  581. };
  582. DLL_LINKAGE void ArtifactLocation::removeArtifact()
  583. {
  584. CArtifactInstance *a = getArt();
  585. assert(a);
  586. a->removeFrom(*this);
  587. }
  588. DLL_LINKAGE const CArmedInstance * ArtifactLocation::relatedObj() const
  589. {
  590. return boost::apply_visitor(ObjectRetriever(), artHolder);
  591. }
  592. DLL_LINKAGE PlayerColor ArtifactLocation::owningPlayer() const
  593. {
  594. auto obj = relatedObj();
  595. return obj ? obj->tempOwner : PlayerColor::NEUTRAL;
  596. }
  597. DLL_LINKAGE CArtifactSet *ArtifactLocation::getHolderArtSet()
  598. {
  599. return boost::apply_visitor(GetBase<CArtifactSet>(), artHolder);
  600. }
  601. DLL_LINKAGE CBonusSystemNode *ArtifactLocation::getHolderNode()
  602. {
  603. return boost::apply_visitor(GetBase<CBonusSystemNode>(), artHolder);
  604. }
  605. DLL_LINKAGE const CArtifactInstance *ArtifactLocation::getArt() const
  606. {
  607. const ArtSlotInfo *s = getSlot();
  608. if(s && s->artifact)
  609. {
  610. if(!s->locked)
  611. return s->artifact;
  612. else
  613. {
  614. logNetwork->warnStream() << "ArtifactLocation::getArt: That location is locked!";
  615. return nullptr;
  616. }
  617. }
  618. return nullptr;
  619. }
  620. DLL_LINKAGE const CArtifactSet * ArtifactLocation::getHolderArtSet() const
  621. {
  622. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  623. return t->getHolderArtSet();
  624. }
  625. DLL_LINKAGE const CBonusSystemNode * ArtifactLocation::getHolderNode() const
  626. {
  627. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  628. return t->getHolderNode();
  629. }
  630. DLL_LINKAGE CArtifactInstance *ArtifactLocation::getArt()
  631. {
  632. const ArtifactLocation *t = this;
  633. return const_cast<CArtifactInstance*>(t->getArt());
  634. }
  635. DLL_LINKAGE const ArtSlotInfo *ArtifactLocation::getSlot() const
  636. {
  637. return getHolderArtSet()->getSlot(slot);
  638. }
  639. DLL_LINKAGE void ChangeStackCount::applyGs( CGameState *gs )
  640. {
  641. if(absoluteValue)
  642. sl.army->setStackCount(sl.slot, count);
  643. else
  644. sl.army->changeStackCount(sl.slot, count);
  645. }
  646. DLL_LINKAGE void SetStackType::applyGs( CGameState *gs )
  647. {
  648. sl.army->setStackType(sl.slot, type);
  649. }
  650. DLL_LINKAGE void EraseStack::applyGs( CGameState *gs )
  651. {
  652. sl.army->eraseStack(sl.slot);
  653. }
  654. DLL_LINKAGE void SwapStacks::applyGs( CGameState *gs )
  655. {
  656. CStackInstance *s1 = sl1.army->detachStack(sl1.slot),
  657. *s2 = sl2.army->detachStack(sl2.slot);
  658. sl2.army->putStack(sl2.slot, s1);
  659. sl1.army->putStack(sl1.slot, s2);
  660. }
  661. DLL_LINKAGE void InsertNewStack::applyGs( CGameState *gs )
  662. {
  663. auto s = new CStackInstance(stack.type, stack.count);
  664. sl.army->putStack(sl.slot, s);
  665. }
  666. DLL_LINKAGE void RebalanceStacks::applyGs( CGameState *gs )
  667. {
  668. const CCreature *srcType = src.army->getCreature(src.slot);
  669. TQuantity srcCount = src.army->getStackCount(src.slot);
  670. bool stackExp = VLC->modh->modules.STACK_EXP;
  671. if(srcCount == count) //moving whole stack
  672. {
  673. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> merge
  674. {
  675. assert(c == srcType);
  676. UNUSED(c);
  677. auto alHere = ArtifactLocation (src.getStack(), ArtifactPosition::CREATURE_SLOT);
  678. auto alDest = ArtifactLocation (dst.getStack(), ArtifactPosition::CREATURE_SLOT);
  679. auto artHere = alHere.getArt();
  680. auto artDest = alDest.getArt();
  681. if (artHere)
  682. {
  683. if (alDest.getArt())
  684. {
  685. auto hero = dynamic_cast <CGHeroInstance *>(src.army.get());
  686. if (hero)
  687. {
  688. artDest->move (alDest, ArtifactLocation (hero, alDest.getArt()->firstBackpackSlot (hero)));
  689. }
  690. //else - artifact cna be lost :/
  691. else
  692. {
  693. logNetwork->warnStream() << "Artifact is present at destination slot!";
  694. }
  695. artHere->move (alHere, alDest);
  696. //TODO: choose from dialog
  697. }
  698. else //just move to the other slot before stack gets erased
  699. {
  700. artHere->move (alHere, alDest);
  701. }
  702. }
  703. if (stackExp)
  704. {
  705. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  706. src.army->eraseStack(src.slot);
  707. dst.army->changeStackCount(dst.slot, count);
  708. dst.army->setStackExp(dst.slot, totalExp /(dst.army->getStackCount(dst.slot))); //mean
  709. }
  710. else
  711. {
  712. src.army->eraseStack(src.slot);
  713. dst.army->changeStackCount(dst.slot, count);
  714. }
  715. }
  716. else //move stack to an empty slot, no exp change needed
  717. {
  718. CStackInstance *stackDetached = src.army->detachStack(src.slot);
  719. dst.army->putStack(dst.slot, stackDetached);
  720. }
  721. }
  722. else
  723. {
  724. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> rebalance
  725. {
  726. assert(c == srcType);
  727. UNUSED(c);
  728. if (stackExp)
  729. {
  730. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  731. src.army->changeStackCount(src.slot, -count);
  732. dst.army->changeStackCount(dst.slot, count);
  733. dst.army->setStackExp(dst.slot, totalExp /(src.army->getStackCount(src.slot) + dst.army->getStackCount(dst.slot))); //mean
  734. }
  735. else
  736. {
  737. src.army->changeStackCount(src.slot, -count);
  738. dst.army->changeStackCount(dst.slot, count);
  739. }
  740. }
  741. else //split stack to an empty slot
  742. {
  743. src.army->changeStackCount(src.slot, -count);
  744. dst.army->addToSlot(dst.slot, srcType->idNumber, count, false);
  745. if (stackExp)
  746. dst.army->setStackExp(dst.slot, src.army->getStackExperience(src.slot));
  747. }
  748. }
  749. CBonusSystemNode::treeHasChanged();
  750. }
  751. DLL_LINKAGE void PutArtifact::applyGs( CGameState *gs )
  752. {
  753. assert(art->canBePutAt(al));
  754. art->putAt(al);
  755. //al.hero->putArtifact(al.slot, art);
  756. }
  757. DLL_LINKAGE void EraseArtifact::applyGs( CGameState *gs )
  758. {
  759. al.removeArtifact();
  760. }
  761. DLL_LINKAGE void MoveArtifact::applyGs( CGameState *gs )
  762. {
  763. CArtifactInstance *a = src.getArt();
  764. if(dst.slot < GameConstants::BACKPACK_START)
  765. assert(!dst.getArt());
  766. a->move(src, dst);
  767. //TODO what'll happen if Titan's thunder is equipped by pickin git up or the start of game?
  768. if (a->artType->id == 135 && dst.slot == ArtifactPosition::RIGHT_HAND) //Titan's Thunder creates new spellbook on equip
  769. {
  770. auto hPtr = boost::get<ConstTransitivePtr<CGHeroInstance> >(&dst.artHolder);
  771. if(hPtr)
  772. {
  773. CGHeroInstance *h = *hPtr;
  774. if(h && !h->hasSpellbook())
  775. gs->giveHeroArtifact(h, ArtifactID::SPELLBOOK);
  776. }
  777. }
  778. }
  779. DLL_LINKAGE void AssembledArtifact::applyGs( CGameState *gs )
  780. {
  781. CArtifactSet *artSet = al.getHolderArtSet();
  782. const CArtifactInstance *transformedArt = al.getArt();
  783. assert(transformedArt);
  784. assert(vstd::contains(transformedArt->assemblyPossibilities(artSet), builtArt));
  785. UNUSED(transformedArt);
  786. auto combinedArt = new CCombinedArtifactInstance(builtArt);
  787. gs->map->addNewArtifactInstance(combinedArt);
  788. //retrieve all constituents
  789. for(const CArtifact * constituent : *builtArt->constituents)
  790. {
  791. ArtifactPosition pos = artSet->getArtPos(constituent->id);
  792. assert(pos >= 0);
  793. CArtifactInstance *constituentInstance = artSet->getArt(pos);
  794. //move constituent from hero to be part of new, combined artifact
  795. constituentInstance->removeFrom(ArtifactLocation(al.artHolder, pos));
  796. combinedArt->addAsConstituent(constituentInstance, pos);
  797. if(!vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], al.slot) && vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], pos))
  798. al.slot = pos;
  799. }
  800. //put new combined artifacts
  801. combinedArt->putAt(al);
  802. }
  803. DLL_LINKAGE void DisassembledArtifact::applyGs( CGameState *gs )
  804. {
  805. CCombinedArtifactInstance *disassembled = dynamic_cast<CCombinedArtifactInstance*>(al.getArt());
  806. assert(disassembled);
  807. std::vector<CCombinedArtifactInstance::ConstituentInfo> constituents = disassembled->constituentsInfo;
  808. disassembled->removeFrom(al);
  809. for(CCombinedArtifactInstance::ConstituentInfo &ci : constituents)
  810. {
  811. ArtifactLocation constituentLoc = al;
  812. constituentLoc.slot = (ci.slot >= 0 ? ci.slot : al.slot); //-1 is slot of main constituent -> it'll replace combined artifact in its pos
  813. disassembled->detachFrom(ci.art);
  814. ci.art->putAt(constituentLoc);
  815. }
  816. gs->map->eraseArtifactInstance(disassembled);
  817. }
  818. DLL_LINKAGE void HeroVisit::applyGs( CGameState *gs )
  819. {
  820. }
  821. DLL_LINKAGE void SetAvailableArtifacts::applyGs( CGameState *gs )
  822. {
  823. if(id >= 0)
  824. {
  825. if(CGBlackMarket *bm = dynamic_cast<CGBlackMarket*>(gs->map->objects[id].get()))
  826. {
  827. bm->artifacts = arts;
  828. }
  829. else
  830. {
  831. logNetwork->errorStream() << "Wrong black market id!";
  832. }
  833. }
  834. else
  835. {
  836. CGTownInstance::merchantArtifacts = arts;
  837. }
  838. }
  839. DLL_LINKAGE void NewTurn::applyGs( CGameState *gs )
  840. {
  841. gs->day = day;
  842. for(NewTurn::Hero h : heroes) //give mana/movement point
  843. {
  844. CGHeroInstance *hero = gs->getHero(h.id);
  845. hero->movement = h.move;
  846. hero->mana = h.mana;
  847. }
  848. for(auto i = res.cbegin(); i != res.cend(); i++)
  849. {
  850. assert(i->first < PlayerColor::PLAYER_LIMIT);
  851. gs->getPlayer(i->first)->resources = i->second;
  852. }
  853. for(auto creatureSet : cres) //set available creatures in towns
  854. creatureSet.second.applyGs(gs);
  855. gs->globalEffects.popBonuses(Bonus::OneDay); //works for children -> all game objs
  856. if(gs->getDate(Date::DAY_OF_WEEK) == 1) //new week
  857. gs->globalEffects.popBonuses(Bonus::OneWeek); //works for children -> all game objs
  858. //TODO not really a single root hierarchy, what about bonuses placed elsewhere? [not an issue with H3 mechanics but in the future...]
  859. for(CGTownInstance* t : gs->map->towns)
  860. t->builded = 0;
  861. }
  862. DLL_LINKAGE void SetObjectProperty::applyGs( CGameState *gs )
  863. {
  864. CGObjectInstance *obj = gs->getObjInstance(id);
  865. if(!obj)
  866. {
  867. logNetwork->errorStream() << "Wrong object ID - property cannot be set!";
  868. return;
  869. }
  870. CArmedInstance *cai = dynamic_cast<CArmedInstance *>(obj);
  871. if(what == ObjProperty::OWNER && cai)
  872. {
  873. if(obj->ID == Obj::TOWN)
  874. {
  875. CGTownInstance *t = static_cast<CGTownInstance*>(obj);
  876. if(t->tempOwner < PlayerColor::PLAYER_LIMIT)
  877. gs->getPlayer(t->tempOwner)->towns -= t;
  878. if(val < PlayerColor::PLAYER_LIMIT_I)
  879. gs->getPlayer(PlayerColor(val))->towns.push_back(t);
  880. }
  881. CBonusSystemNode *nodeToMove = cai->whatShouldBeAttached();
  882. nodeToMove->detachFrom(cai->whereShouldBeAttached(gs));
  883. obj->setProperty(what,val);
  884. nodeToMove->attachTo(cai->whereShouldBeAttached(gs));
  885. }
  886. else //not an armed instance
  887. {
  888. obj->setProperty(what,val);
  889. }
  890. }
  891. DLL_LINKAGE void SetHoverName::applyGs( CGameState *gs )
  892. {
  893. name.toString(gs->getObj(id)->hoverName);
  894. }
  895. DLL_LINKAGE void HeroLevelUp::applyGs( CGameState *gs )
  896. {
  897. CGHeroInstance* h = gs->getHero(hero->id);
  898. h->level = level;
  899. //deterministic secondary skills
  900. h->skillsInfo.magicSchoolCounter = (h->skillsInfo.magicSchoolCounter + 1) % h->maxlevelsToMagicSchool();
  901. h->skillsInfo.wisdomCounter = (h->skillsInfo.wisdomCounter + 1) % h->maxlevelsToWisdom();
  902. if (vstd::contains(skills, SecondarySkill::WISDOM))
  903. h->skillsInfo.resetWisdomCounter();
  904. SecondarySkill spellSchools[] = {
  905. SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
  906. for (auto skill : spellSchools)
  907. {
  908. if (vstd::contains(skills, skill))
  909. {
  910. h->skillsInfo.resetMagicSchoolCounter();
  911. break;
  912. }
  913. }
  914. //specialty
  915. h->Updatespecialty();
  916. }
  917. DLL_LINKAGE void CommanderLevelUp::applyGs (CGameState *gs)
  918. {
  919. CCommanderInstance * commander = gs->getHero(hero->id)->commander;
  920. assert (commander);
  921. commander->levelUp();
  922. }
  923. DLL_LINKAGE void BattleStart::applyGs( CGameState *gs )
  924. {
  925. gs->curB = info;
  926. gs->curB->localInit();
  927. }
  928. DLL_LINKAGE void BattleNextRound::applyGs( CGameState *gs )
  929. {
  930. for (int i = 0; i < 2; ++i)
  931. {
  932. gs->curB->sides[i].castSpellsCount = 0;
  933. vstd::amax(--gs->curB->sides[i].enchanterCounter, 0);
  934. }
  935. gs->curB->round = round;
  936. for(CStack *s : gs->curB->stacks)
  937. {
  938. s->state -= EBattleStackState::DEFENDING;
  939. s->state -= EBattleStackState::WAITING;
  940. s->state -= EBattleStackState::MOVED;
  941. s->state -= EBattleStackState::HAD_MORALE;
  942. s->state -= EBattleStackState::FEAR;
  943. s->state -= EBattleStackState::DRAINED_MANA;
  944. s->counterAttacks = 1 + s->valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  945. // new turn effects
  946. s->battleTurnPassed();
  947. }
  948. for(auto &obst : gs->curB->obstacles)
  949. obst->battleTurnPassed();
  950. }
  951. DLL_LINKAGE void BattleSetActiveStack::applyGs( CGameState *gs )
  952. {
  953. gs->curB->activeStack = stack;
  954. CStack *st = gs->curB->getStack(stack);
  955. //remove bonuses that last until when stack gets new turn
  956. st->getBonusList().remove_if(Bonus::UntilGetsTurn);
  957. if(vstd::contains(st->state,EBattleStackState::MOVED)) //if stack is moving second time this turn it must had a high morale bonus
  958. st->state.insert(EBattleStackState::HAD_MORALE);
  959. }
  960. DLL_LINKAGE void BattleTriggerEffect::applyGs( CGameState *gs )
  961. {
  962. CStack *st = gs->curB->getStack(stackID);
  963. switch (effect)
  964. {
  965. case Bonus::HP_REGENERATION:
  966. st->firstHPleft += val;
  967. vstd::amin (st->firstHPleft, (ui32)st->MaxHealth());
  968. break;
  969. case Bonus::MANA_DRAIN:
  970. {
  971. CGHeroInstance * h = gs->getHero(ObjectInstanceID(additionalInfo));
  972. st->state.insert (EBattleStackState::DRAINED_MANA);
  973. h->mana -= val;
  974. vstd::amax(h->mana, 0);
  975. break;
  976. }
  977. case Bonus::POISON:
  978. {
  979. Bonus * b = st->getBonusLocalFirst(Selector::source(Bonus::SPELL_EFFECT, 71)
  980. .And(Selector::type(Bonus::STACK_HEALTH)));
  981. if (b)
  982. b->val = val;
  983. break;
  984. }
  985. case Bonus::ENCHANTER:
  986. break;
  987. case Bonus::FEAR:
  988. st->state.insert(EBattleStackState::FEAR);
  989. break;
  990. default:
  991. logNetwork->warnStream() << "Unrecognized trigger effect type "<< type;
  992. }
  993. }
  994. DLL_LINKAGE void BattleObstaclePlaced::applyGs( CGameState *gs )
  995. {
  996. gs->curB->obstacles.push_back(obstacle);
  997. }
  998. void BattleResult::applyGs( CGameState *gs )
  999. {
  1000. for (CStack *s : gs->curB->stacks)
  1001. {
  1002. if (s->base && s->base->armyObj && vstd::contains(s->state, EBattleStackState::SUMMONED))
  1003. {
  1004. //stack with SUMMONED flag but coming from garrison -> most likely resurrected, needs to be removed
  1005. assert(&s->base->armyObj->getStack(s->slot) == s->base);
  1006. const_cast<CArmedInstance*>(s->base->armyObj)->eraseStack(s->slot);
  1007. }
  1008. }
  1009. for (auto & elem : gs->curB->stacks)
  1010. delete elem;
  1011. for(int i = 0; i < 2; ++i)
  1012. {
  1013. if(auto h = gs->curB->battleGetFightingHero(i))
  1014. {
  1015. h->getBonusList().remove_if(Bonus::OneBattle); //remove any "until next battle" bonuses
  1016. if (h->commander && h->commander->alive)
  1017. {
  1018. for (auto art : h->commander->artifactsWorn) //increment bonuses for commander artifacts
  1019. {
  1020. art.second.artifact->artType->levelUpArtifact (art.second.artifact);
  1021. }
  1022. }
  1023. }
  1024. }
  1025. if(VLC->modh->modules.STACK_EXP)
  1026. {
  1027. for(int i = 0; i < 2; i++)
  1028. if(exp[i])
  1029. gs->curB->battleGetArmyObject(i)->giveStackExp(exp[i]);
  1030. CBonusSystemNode::treeHasChanged();
  1031. }
  1032. for(int i = 0; i < 2; i++)
  1033. gs->curB->battleGetArmyObject(i)->battle = nullptr;
  1034. gs->curB.dellNull();
  1035. }
  1036. void BattleStackMoved::applyGs( CGameState *gs )
  1037. {
  1038. CStack *s = gs->curB->getStack(stack);
  1039. BattleHex dest = tilesToMove.back();
  1040. //if unit ended movement on quicksands that were created by enemy, that quicksand patch becomes visible for owner
  1041. for(auto &oi : gs->curB->obstacles)
  1042. {
  1043. if(oi->obstacleType == CObstacleInstance::QUICKSAND
  1044. && vstd::contains(oi->getAffectedTiles(), tilesToMove.back()))
  1045. {
  1046. SpellCreatedObstacle *sands = dynamic_cast<SpellCreatedObstacle*>(oi.get());
  1047. assert(sands);
  1048. if(sands->casterSide != !s->attackerOwned)
  1049. sands->visibleForAnotherSide = true;
  1050. }
  1051. }
  1052. s->position = dest;
  1053. }
  1054. DLL_LINKAGE void BattleStackAttacked::applyGs( CGameState *gs )
  1055. {
  1056. CStack * at = gs->curB->getStack(stackAttacked);
  1057. assert(at);
  1058. at->count = newAmount;
  1059. at->firstHPleft = newHP;
  1060. if(killed())
  1061. {
  1062. at->state -= EBattleStackState::ALIVE;
  1063. }
  1064. //life drain handling
  1065. for (auto & elem : healedStacks)
  1066. {
  1067. elem.applyGs(gs);
  1068. }
  1069. if (willRebirth())
  1070. {
  1071. at->casts--;
  1072. at->state.insert(EBattleStackState::ALIVE); //hmm?
  1073. }
  1074. if (cloneKilled())
  1075. {
  1076. //"hide" killed creatures instead so we keep info about it
  1077. at->state.insert(EBattleStackState::DEAD_CLONE);
  1078. }
  1079. }
  1080. DLL_LINKAGE void BattleAttack::applyGs( CGameState *gs )
  1081. {
  1082. CStack *attacker = gs->curB->getStack(stackAttacking);
  1083. if(counter())
  1084. attacker->counterAttacks--;
  1085. if(shot())
  1086. {
  1087. //don't remove ammo if we have a working ammo cart
  1088. bool hasAmmoCart = false;
  1089. for(const CStack * st : gs->curB->stacks)
  1090. {
  1091. if(st->owner == attacker->owner && st->getCreature()->idNumber == CreatureID::AMMO_CART && st->alive())
  1092. {
  1093. hasAmmoCart = true;
  1094. break;
  1095. }
  1096. }
  1097. if (!hasAmmoCart)
  1098. {
  1099. attacker->shots--;
  1100. }
  1101. }
  1102. for(BattleStackAttacked stackAttacked : bsa)
  1103. stackAttacked.applyGs(gs);
  1104. attacker->getBonusList().remove_if(Bonus::UntilAttack);
  1105. for(auto & elem : bsa)
  1106. {
  1107. CStack * stack = gs->curB->getStack(elem.stackAttacked, false);
  1108. if (stack) //cloned stack is already gone
  1109. stack->getBonusList().remove_if(Bonus::UntilBeingAttacked);
  1110. }
  1111. }
  1112. DLL_LINKAGE void StartAction::applyGs( CGameState *gs )
  1113. {
  1114. CStack *st = gs->curB->getStack(ba.stackNumber);
  1115. if(ba.actionType == Battle::END_TACTIC_PHASE)
  1116. {
  1117. gs->curB->tacticDistance = 0;
  1118. return;
  1119. }
  1120. if(gs->curB->tacticDistance)
  1121. {
  1122. // moves in tactics phase do not affect creature status
  1123. // (tactics stack queue is managed by client)
  1124. return;
  1125. }
  1126. if(ba.actionType != Battle::HERO_SPELL) //don't check for stack if it's custom action by hero
  1127. {
  1128. assert(st);
  1129. }
  1130. else
  1131. {
  1132. gs->curB->sides[ba.side].usedSpellsHistory.push_back(SpellID(ba.additionalInfo).toSpell());
  1133. }
  1134. switch(ba.actionType)
  1135. {
  1136. case Battle::DEFEND:
  1137. st->state.insert(EBattleStackState::DEFENDING);
  1138. break;
  1139. case Battle::WAIT:
  1140. st->state.insert(EBattleStackState::WAITING);
  1141. return;
  1142. case Battle::HERO_SPELL: //no change in current stack state
  1143. return;
  1144. default: //any active stack action - attack, catapult, heal, spell...
  1145. st->state.insert(EBattleStackState::MOVED);
  1146. break;
  1147. }
  1148. if(st)
  1149. 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)
  1150. }
  1151. DLL_LINKAGE void BattleSpellCast::applyGs( CGameState *gs )
  1152. {
  1153. assert(gs->curB);
  1154. if (castedByHero)
  1155. {
  1156. CGHeroInstance * h = gs->curB->battleGetFightingHero(side);
  1157. CGHeroInstance * enemy = gs->curB->battleGetFightingHero(!side);
  1158. h->mana -= spellCost;
  1159. vstd::amax(h->mana, 0);
  1160. if (enemy && manaGained)
  1161. enemy->mana += manaGained;
  1162. if (side < 2)
  1163. {
  1164. gs->curB->sides[side].castSpellsCount++;
  1165. }
  1166. }
  1167. //Handle spells removing effects from stacks
  1168. const CSpell *spell = SpellID(id).toSpell();
  1169. const bool removeAllSpells = id == SpellID::DISPEL;
  1170. const bool removeHelpful = id == SpellID::DISPEL_HELPFUL_SPELLS;
  1171. for(auto stackID : affectedCres)
  1172. {
  1173. if(vstd::contains(resisted, stackID))
  1174. continue;
  1175. CStack *s = gs->curB->getStack(stackID);
  1176. s->popBonuses([&](const Bonus *b) -> bool
  1177. {
  1178. //check for each bonus if it should be removed
  1179. const bool isSpellEffect = Selector::sourceType(Bonus::SPELL_EFFECT)(b);
  1180. const bool isPositiveSpell = Selector::positiveSpellEffects(b);
  1181. const int spellID = isSpellEffect ? b->sid : -1;
  1182. return (removeHelpful && isPositiveSpell)
  1183. || (removeAllSpells && isSpellEffect)
  1184. || vstd::contains(spell->counteredSpells, spellID);
  1185. });
  1186. }
  1187. }
  1188. void actualizeEffect(CStack * s, const std::vector<Bonus> & ef)
  1189. {
  1190. //actualizing features vector
  1191. for(const Bonus &fromEffect : ef)
  1192. {
  1193. for(Bonus *stackBonus : s->getBonusList()) //TODO: optimize
  1194. {
  1195. if(stackBonus->source == Bonus::SPELL_EFFECT && stackBonus->type == fromEffect.type && stackBonus->subtype == fromEffect.subtype)
  1196. {
  1197. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, fromEffect.turnsRemain);
  1198. }
  1199. }
  1200. }
  1201. }
  1202. void actualizeEffect(CStack * s, const Bonus & ef)
  1203. {
  1204. for(Bonus *stackBonus : s->getBonusList()) //TODO: optimize
  1205. {
  1206. if(stackBonus->source == Bonus::SPELL_EFFECT && stackBonus->type == ef.type && stackBonus->subtype == ef.subtype)
  1207. {
  1208. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, ef.turnsRemain);
  1209. }
  1210. }
  1211. }
  1212. DLL_LINKAGE void SetStackEffect::applyGs( CGameState *gs )
  1213. {
  1214. if (effect.empty())
  1215. {
  1216. logGlobal->errorStream() << "Trying to apply SetStackEffect with no effects";
  1217. return;
  1218. }
  1219. int spellid = effect.begin()->sid; //effects' source ID
  1220. for(ui32 id : stacks)
  1221. {
  1222. CStack *s = gs->curB->getStack(id);
  1223. if(s)
  1224. {
  1225. 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
  1226. {
  1227. for(Bonus &fromEffect : effect)
  1228. {
  1229. logBonus->traceStream() << s->nodeName() << " receives a new bonus: " << fromEffect.Description();
  1230. s->addNewBonus( new Bonus(fromEffect));
  1231. }
  1232. }
  1233. else //just actualize
  1234. {
  1235. actualizeEffect(s, effect);
  1236. }
  1237. }
  1238. else
  1239. logNetwork->errorStream() << "Cannot find stack " << id;
  1240. }
  1241. typedef std::pair<ui32, Bonus> p;
  1242. for(p para : uniqueBonuses)
  1243. {
  1244. CStack *s = gs->curB->getStack(para.first);
  1245. if (s)
  1246. {
  1247. if (!s->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellid).And(Selector::typeSubtype(para.second.type, para.second.subtype))))
  1248. s->addNewBonus(new Bonus(para.second));
  1249. else
  1250. actualizeEffect(s, effect);
  1251. }
  1252. else
  1253. logNetwork->errorStream() << "Cannot find stack " << para.first;
  1254. }
  1255. }
  1256. DLL_LINKAGE void StacksInjured::applyGs( CGameState *gs )
  1257. {
  1258. for(BattleStackAttacked stackAttacked : stacks)
  1259. stackAttacked.applyGs(gs);
  1260. }
  1261. DLL_LINKAGE void StacksHealedOrResurrected::applyGs( CGameState *gs )
  1262. {
  1263. for(auto & elem : healedStacks)
  1264. {
  1265. CStack * changedStack = gs->curB->getStack(elem.stackID, false);
  1266. //checking if we resurrect a stack that is under a living stack
  1267. auto accessibility = gs->curB->getAccesibility();
  1268. if(!changedStack->alive() && !accessibility.accessible(changedStack->position, changedStack))
  1269. {
  1270. logNetwork->errorStream() << "Cannot resurrect " << changedStack->nodeName() << " because hex " << changedStack->position << " is occupied!";
  1271. return; //position is already occupied
  1272. }
  1273. //applying changes
  1274. bool resurrected = !changedStack->alive(); //indicates if stack is resurrected or just healed
  1275. if(resurrected)
  1276. {
  1277. changedStack->state.insert(EBattleStackState::ALIVE);
  1278. }
  1279. //int missingHPfirst = changedStack->MaxHealth() - changedStack->firstHPleft;
  1280. int res = std::min( elem.healedHP / changedStack->MaxHealth() , changedStack->baseAmount - changedStack->count );
  1281. changedStack->count += res;
  1282. if(elem.lowLevelResurrection)
  1283. changedStack->resurrected += res;
  1284. changedStack->firstHPleft += elem.healedHP - res * changedStack->MaxHealth();
  1285. if(changedStack->firstHPleft > changedStack->MaxHealth())
  1286. {
  1287. changedStack->firstHPleft -= changedStack->MaxHealth();
  1288. if(changedStack->baseAmount > changedStack->count)
  1289. {
  1290. changedStack->count += 1;
  1291. }
  1292. }
  1293. vstd::amin(changedStack->firstHPleft, changedStack->MaxHealth());
  1294. //removal of negative effects
  1295. if(resurrected)
  1296. {
  1297. // for (BonusList::iterator it = changedStack->bonuses.begin(); it != changedStack->bonuses.end(); it++)
  1298. // {
  1299. // if(VLC->spellh->spells[(*it)->sid]->positiveness < 0)
  1300. // {
  1301. // changedStack->bonuses.erase(it);
  1302. // }
  1303. // }
  1304. //removing all features from negative spells
  1305. const BonusList tmpFeatures = changedStack->getBonusList();
  1306. //changedStack->bonuses.clear();
  1307. for(Bonus *b : tmpFeatures)
  1308. {
  1309. const CSpell *s = b->sourceSpell();
  1310. if(s && s->isNegative())
  1311. {
  1312. changedStack->removeBonus(b);
  1313. }
  1314. }
  1315. }
  1316. }
  1317. }
  1318. DLL_LINKAGE void ObstaclesRemoved::applyGs( CGameState *gs )
  1319. {
  1320. if(gs->curB) //if there is a battle
  1321. {
  1322. for(const si32 rem_obst :obstacles)
  1323. {
  1324. for(int i=0; i<gs->curB->obstacles.size(); ++i)
  1325. {
  1326. if(gs->curB->obstacles[i]->uniqueID == rem_obst) //remove this obstacle
  1327. {
  1328. gs->curB->obstacles.erase(gs->curB->obstacles.begin() + i);
  1329. break;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. }
  1335. DLL_LINKAGE CatapultAttack::CatapultAttack()
  1336. {
  1337. type = 3015;
  1338. }
  1339. DLL_LINKAGE CatapultAttack::~CatapultAttack()
  1340. {
  1341. }
  1342. DLL_LINKAGE void CatapultAttack::applyGs( CGameState *gs )
  1343. {
  1344. if(gs->curB && gs->curB->siege != CGTownInstance::NONE) //if there is a battle and it's a siege
  1345. {
  1346. for(const auto &it :attackedParts)
  1347. {
  1348. gs->curB->si.wallState[it.attackedPart] =
  1349. SiegeInfo::applyDamage(EWallState::EWallState(gs->curB->si.wallState[it.attackedPart]), it.damageDealt);
  1350. }
  1351. }
  1352. }
  1353. DLL_LINKAGE std::string CatapultAttack::AttackInfo::toString() const
  1354. {
  1355. return boost::str(boost::format("{AttackInfo: destinationTile '%d', attackedPart '%d', damageDealt '%d'}")
  1356. % destinationTile % static_cast<int>(attackedPart) % static_cast<int>(damageDealt));
  1357. }
  1358. DLL_LINKAGE std::ostream & operator<<(std::ostream & out, const CatapultAttack::AttackInfo & attackInfo)
  1359. {
  1360. return out << attackInfo.toString();
  1361. }
  1362. DLL_LINKAGE std::string CatapultAttack::toString() const
  1363. {
  1364. return boost::str(boost::format("{CatapultAttack: attackedParts '%s', attacker '%d'}") % attackedParts % attacker);
  1365. }
  1366. DLL_LINKAGE void BattleStacksRemoved::applyGs( CGameState *gs )
  1367. {
  1368. if(!gs->curB)
  1369. return;
  1370. for(ui32 rem_stack : stackIDs)
  1371. {
  1372. for(int b=0; b<gs->curB->stacks.size(); ++b) //find it in vector of stacks
  1373. {
  1374. if(gs->curB->stacks[b]->ID == rem_stack) //if found
  1375. {
  1376. CStack *toRemove = gs->curB->stacks[b];
  1377. gs->curB->stacks.erase(gs->curB->stacks.begin() + b); //remove
  1378. toRemove->detachFromAll();
  1379. delete toRemove;
  1380. break;
  1381. }
  1382. }
  1383. }
  1384. }
  1385. DLL_LINKAGE void BattleStackAdded::applyGs(CGameState *gs)
  1386. {
  1387. if (!BattleHex(pos).isValid())
  1388. {
  1389. logNetwork->warnStream() << "No place found for new stack!";
  1390. return;
  1391. }
  1392. CStackBasicDescriptor csbd(creID, amount);
  1393. CStack * addedStack = gs->curB->generateNewStack(csbd, attacker, SlotID(255), pos); //TODO: netpacks?
  1394. if (summoned)
  1395. addedStack->state.insert(EBattleStackState::SUMMONED);
  1396. gs->curB->localInitStack(addedStack);
  1397. gs->curB->stacks.push_back(addedStack); //the stack is not "SUMMONED", it is permanent
  1398. }
  1399. DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState *gs)
  1400. {
  1401. CStack * stack = gs->curB->getStack(stackID);
  1402. switch (which)
  1403. {
  1404. case CASTS:
  1405. {
  1406. if (absolute)
  1407. stack->casts = val;
  1408. else
  1409. stack->casts += val;
  1410. vstd::amax(stack->casts, 0);
  1411. break;
  1412. }
  1413. case ENCHANTER_COUNTER:
  1414. {
  1415. auto & counter = gs->curB->sides[gs->curB->whatSide(stack->owner)].enchanterCounter;
  1416. if (absolute)
  1417. counter = val;
  1418. else
  1419. counter += val;
  1420. vstd::amax(counter, 0);
  1421. break;
  1422. }
  1423. case UNBIND:
  1424. {
  1425. stack->popBonuses(Selector::type(Bonus::BIND_EFFECT));
  1426. break;
  1427. }
  1428. case CLONED:
  1429. {
  1430. stack->state.insert(EBattleStackState::CLONED);
  1431. break;
  1432. }
  1433. }
  1434. }
  1435. DLL_LINKAGE void YourTurn::applyGs( CGameState *gs )
  1436. {
  1437. gs->currentPlayer = player;
  1438. //count days without town
  1439. auto & playerState = gs->players[player];
  1440. if(playerState.towns.empty())
  1441. {
  1442. if(playerState.daysWithoutCastle)
  1443. ++(*playerState.daysWithoutCastle);
  1444. else playerState.daysWithoutCastle = 0;
  1445. }
  1446. else
  1447. {
  1448. playerState.daysWithoutCastle = boost::none;
  1449. }
  1450. }
  1451. DLL_LINKAGE void SetSelection::applyGs( CGameState *gs )
  1452. {
  1453. gs->getPlayer(player)->currentSelection = id;
  1454. }
  1455. DLL_LINKAGE Component::Component(const CStackBasicDescriptor &stack)
  1456. : id(CREATURE), subtype(stack.type->idNumber), val(stack.count), when(0)
  1457. {
  1458. type = 2002;
  1459. }