NetPacksLib.cpp 47 KB

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