NetPacksLib.cpp 44 KB

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