NetPacksLib.cpp 41 KB

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