2
0

NetPacksLib.cpp 42 KB

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