NetPacksLib.cpp 44 KB

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