NetPacksLib.cpp 40 KB

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