NetPacksLib.cpp 43 KB

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