NetPacksLib.cpp 41 KB

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