NetPacksLib.cpp 44 KB

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