NetPacksLib.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662
  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->getPlayer(player)->resources = res;
  34. else
  35. gs->getPlayer(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->getPlayer(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->getPlayer(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->getPlayer(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->getPlayer(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->getPlayer(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->getPlayer(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->getPlayer(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)
  347. {
  348. CGHeroInstance *h = static_cast<CGHeroInstance*>(obj);
  349. PlayerState *p = gs->getPlayer(h->tempOwner);
  350. gs->map->heroesOnMap -= h;
  351. p->heroes -= h;
  352. h->detachFrom(h->whereShouldBeAttached(gs));
  353. h->tempOwner = PlayerColor::NEUTRAL; //no one owns beaten hero
  354. vstd::erase_if(h->artifactsInBackpack, [](const ArtSlotInfo& asi)
  355. {
  356. return asi.artifact->artType->id == ArtifactID::GRAIL;
  357. });
  358. if(h->visitedTown)
  359. {
  360. if(h->inTownGarrison)
  361. h->visitedTown->garrisonHero = nullptr;
  362. else
  363. h->visitedTown->visitingHero = nullptr;
  364. h->visitedTown = nullptr;
  365. }
  366. //return hero to the pool, so he may reappear in tavern
  367. gs->hpool.heroesPool[h->subID] = h;
  368. if(!vstd::contains(gs->hpool.pavailable, h->subID))
  369. gs->hpool.pavailable[h->subID] = 0xff;
  370. gs->map->objects[id.getNum()] = nullptr;
  371. //If hero on Boat is removed, the Boat disappears
  372. if(h->boat)
  373. {
  374. gs->map->instanceNames.erase(h->boat->instanceName);
  375. gs->map->objects[h->boat->id.getNum()].dellNull();
  376. h->boat = nullptr;
  377. }
  378. return;
  379. }
  380. auto quest = dynamic_cast<const IQuestObject *>(obj);
  381. if (quest)
  382. {
  383. gs->map->quests[quest->quest->qid] = nullptr;
  384. for (auto &player : gs->players)
  385. {
  386. for (auto &q : player.second.quests)
  387. {
  388. if (q.obj == obj)
  389. {
  390. q.obj = nullptr;
  391. }
  392. }
  393. }
  394. }
  395. for (TriggeredEvent & event : gs->map->triggeredEvents)
  396. {
  397. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  398. {
  399. if (cond.object == obj)
  400. {
  401. if (cond.condition == EventCondition::DESTROY || cond.condition == EventCondition::DESTROY_0)
  402. {
  403. cond.condition = EventCondition::CONST_VALUE;
  404. cond.value = 1; // destroyed object, from now on always fulfilled
  405. }
  406. else if (cond.condition == EventCondition::CONTROL || cond.condition == EventCondition::HAVE_0)
  407. {
  408. cond.condition = EventCondition::CONST_VALUE;
  409. cond.value = 0; // destroyed object, from now on can not be fulfilled
  410. }
  411. }
  412. return cond;
  413. };
  414. event.trigger = event.trigger.morph(patcher);
  415. }
  416. gs->map->instanceNames.erase(obj->instanceName);
  417. gs->map->objects[id.getNum()].dellNull();
  418. gs->map->calculateGuardingGreaturePositions();
  419. }
  420. static int getDir(int3 src, int3 dst)
  421. {
  422. int ret = -1;
  423. if(dst.x+1 == src.x && dst.y+1 == src.y) //tl
  424. {
  425. ret = 1;
  426. }
  427. else if(dst.x == src.x && dst.y+1 == src.y) //t
  428. {
  429. ret = 2;
  430. }
  431. else if(dst.x-1 == src.x && dst.y+1 == src.y) //tr
  432. {
  433. ret = 3;
  434. }
  435. else if(dst.x-1 == src.x && dst.y == src.y) //r
  436. {
  437. ret = 4;
  438. }
  439. else if(dst.x-1 == src.x && dst.y-1 == src.y) //br
  440. {
  441. ret = 5;
  442. }
  443. else if(dst.x == src.x && dst.y-1 == src.y) //b
  444. {
  445. ret = 6;
  446. }
  447. else if(dst.x+1 == src.x && dst.y-1 == src.y) //bl
  448. {
  449. ret = 7;
  450. }
  451. else if(dst.x+1 == src.x && dst.y == src.y) //l
  452. {
  453. ret = 8;
  454. }
  455. return ret;
  456. }
  457. void TryMoveHero::applyGs(CGameState *gs)
  458. {
  459. CGHeroInstance *h = gs->getHero(id);
  460. if (!h)
  461. {
  462. logGlobal->error("Attempt ot move unavailable hero %d", id.getNum());
  463. return;
  464. }
  465. h->movement = movePoints;
  466. if((result == SUCCESS || result == BLOCKING_VISIT || result == EMBARK || result == DISEMBARK) && start != end)
  467. {
  468. auto dir = getDir(start,end);
  469. if(dir > 0 && dir <= 8)
  470. h->moveDir = dir;
  471. //else don`t change move direction - hero might have traversed the subterranean gate, direction should be kept
  472. }
  473. if(result == EMBARK) //hero enters boat at destination tile
  474. {
  475. const TerrainTile &tt = gs->map->getTile(CGHeroInstance::convertPosition(end, false));
  476. assert(tt.visitableObjects.size() >= 1 && tt.visitableObjects.back()->ID == Obj::BOAT); //the only visitable object at destination is Boat
  477. CGBoat *boat = static_cast<CGBoat*>(tt.visitableObjects.back());
  478. gs->map->removeBlockVisTiles(boat); //hero blockvis mask will be used, we don't need to duplicate it with boat
  479. h->boat = boat;
  480. boat->hero = h;
  481. }
  482. else if(result == DISEMBARK) //hero leaves boat to destination tile
  483. {
  484. CGBoat *b = const_cast<CGBoat *>(h->boat);
  485. b->direction = h->moveDir;
  486. b->pos = start;
  487. b->hero = nullptr;
  488. gs->map->addBlockVisTiles(b);
  489. h->boat = nullptr;
  490. }
  491. if(start!=end && (result == SUCCESS || result == TELEPORTATION || result == EMBARK || result == DISEMBARK))
  492. {
  493. gs->map->removeBlockVisTiles(h);
  494. h->pos = end;
  495. if(CGBoat *b = const_cast<CGBoat *>(h->boat))
  496. b->pos = end;
  497. gs->map->addBlockVisTiles(h);
  498. }
  499. for(int3 t : fowRevealed)
  500. gs->getPlayerTeam(h->getOwner())->fogOfWarMap[t.x][t.y][t.z] = 1;
  501. }
  502. DLL_LINKAGE void NewStructures::applyGs(CGameState *gs)
  503. {
  504. CGTownInstance *t = gs->getTown(tid);
  505. for(const auto & id : bid)
  506. {
  507. assert(t->town->buildings.at(id) != nullptr);
  508. t->builtBuildings.insert(id);
  509. t->updateAppearance();
  510. auto currentBuilding = t->town->buildings.at(id);
  511. if(currentBuilding->overrideBids.empty())
  512. continue;
  513. for(auto overrideBid : currentBuilding->overrideBids)
  514. {
  515. t->overriddenBuildings.insert(overrideBid);
  516. t->deleteTownBonus(overrideBid);
  517. }
  518. }
  519. t->builded = builded;
  520. t->recreateBuildingsBonuses();
  521. }
  522. DLL_LINKAGE void RazeStructures::applyGs(CGameState *gs)
  523. {
  524. CGTownInstance *t = gs->getTown(tid);
  525. for(const auto & id : bid)
  526. {
  527. t->builtBuildings.erase(id);
  528. t->updateAppearance();
  529. }
  530. t->destroyed = destroyed; //yeaha
  531. t->recreateBuildingsBonuses();
  532. }
  533. DLL_LINKAGE void SetAvailableCreatures::applyGs(CGameState *gs)
  534. {
  535. CGDwelling *dw = dynamic_cast<CGDwelling*>(gs->getObjInstance(tid));
  536. assert(dw);
  537. dw->creatures = creatures;
  538. }
  539. DLL_LINKAGE void SetHeroesInTown::applyGs(CGameState *gs)
  540. {
  541. CGTownInstance *t = gs->getTown(tid);
  542. CGHeroInstance *v = gs->getHero(visiting),
  543. *g = gs->getHero(garrison);
  544. bool newVisitorComesFromGarrison = v && v == t->garrisonHero;
  545. bool newGarrisonComesFromVisiting = g && g == t->visitingHero;
  546. if(newVisitorComesFromGarrison)
  547. t->setGarrisonedHero(nullptr);
  548. if(newGarrisonComesFromVisiting)
  549. t->setVisitingHero(nullptr);
  550. if(!newGarrisonComesFromVisiting || v)
  551. t->setVisitingHero(v);
  552. if(!newVisitorComesFromGarrison || g)
  553. t->setGarrisonedHero(g);
  554. if(v)
  555. {
  556. gs->map->addBlockVisTiles(v);
  557. }
  558. if(g)
  559. {
  560. gs->map->removeBlockVisTiles(g);
  561. }
  562. }
  563. DLL_LINKAGE void HeroRecruited::applyGs(CGameState *gs)
  564. {
  565. assert(vstd::contains(gs->hpool.heroesPool, hid));
  566. CGHeroInstance *h = gs->hpool.heroesPool[hid];
  567. CGTownInstance *t = gs->getTown(tid);
  568. PlayerState *p = gs->getPlayer(player);
  569. assert(!h->boat);
  570. h->setOwner(player);
  571. h->pos = tile;
  572. bool fresh = !h->isInitialized();
  573. if(fresh)
  574. { // this is a fresh hero who hasn't appeared yet
  575. h->movement = h->maxMovePoints(true);
  576. }
  577. gs->hpool.heroesPool.erase(hid);
  578. if(h->id == ObjectInstanceID())
  579. {
  580. h->id = ObjectInstanceID((si32)gs->map->objects.size());
  581. gs->map->objects.push_back(h);
  582. }
  583. else
  584. gs->map->objects[h->id.getNum()] = h;
  585. gs->map->heroesOnMap.push_back(h);
  586. p->heroes.push_back(h);
  587. h->attachTo(p);
  588. if(fresh)
  589. {
  590. h->initObj(gs->getRandomGenerator());
  591. }
  592. gs->map->addBlockVisTiles(h);
  593. if(t)
  594. {
  595. t->setVisitingHero(h);
  596. }
  597. }
  598. DLL_LINKAGE void GiveHero::applyGs(CGameState *gs)
  599. {
  600. CGHeroInstance *h = gs->getHero(id);
  601. //bonus system
  602. h->detachFrom(&gs->globalEffects);
  603. h->attachTo(gs->getPlayer(player));
  604. h->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, h->type->heroClass->id)->getTemplates().front();
  605. gs->map->removeBlockVisTiles(h,true);
  606. h->setOwner(player);
  607. h->movement = h->maxMovePoints(true);
  608. gs->map->heroesOnMap.push_back(h);
  609. gs->getPlayer(h->getOwner())->heroes.push_back(h);
  610. gs->map->addBlockVisTiles(h);
  611. h->inTownGarrison = false;
  612. }
  613. DLL_LINKAGE void NewObject::applyGs(CGameState *gs)
  614. {
  615. ETerrainType terrainType;
  616. if(ID == Obj::BOAT && !gs->isInTheMap(pos)) //special handling for bug #3060 - pos outside map but visitablePos is not
  617. {
  618. CGObjectInstance testObject = CGObjectInstance();
  619. testObject.pos = pos;
  620. testObject.appearance = VLC->objtypeh->getHandlerFor(ID, subID)->getTemplates(ETerrainType::WATER).front();
  621. const int3 previousXAxisTile = int3(pos.x - 1, pos.y, pos.z);
  622. assert(gs->isInTheMap(previousXAxisTile) && (testObject.visitablePos() == previousXAxisTile));
  623. }
  624. else
  625. {
  626. const TerrainTile & t = gs->map->getTile(pos);
  627. terrainType = t.terType;
  628. }
  629. CGObjectInstance *o = nullptr;
  630. switch(ID)
  631. {
  632. case Obj::BOAT:
  633. o = new CGBoat();
  634. terrainType = ETerrainType::WATER; //TODO: either boat should only spawn on water, or all water objects should be handled this way
  635. break;
  636. case Obj::MONSTER: //probably more options will be needed
  637. o = new CGCreature();
  638. {
  639. //CStackInstance hlp;
  640. CGCreature *cre = static_cast<CGCreature*>(o);
  641. //cre->slots[0] = hlp;
  642. cre->notGrowingTeam = cre->neverFlees = 0;
  643. cre->character = 2;
  644. cre->gainedArtifact = ArtifactID::NONE;
  645. cre->identifier = -1;
  646. cre->addToSlot(SlotID(0), new CStackInstance(CreatureID(subID), -1)); //add placeholder stack
  647. }
  648. break;
  649. default:
  650. o = new CGObjectInstance();
  651. break;
  652. }
  653. o->ID = ID;
  654. o->subID = subID;
  655. o->pos = pos;
  656. o->appearance = VLC->objtypeh->getHandlerFor(o->ID, o->subID)->getTemplates(terrainType).front();
  657. id = o->id = ObjectInstanceID((si32)gs->map->objects.size());
  658. gs->map->objects.push_back(o);
  659. gs->map->addBlockVisTiles(o);
  660. o->initObj(gs->getRandomGenerator());
  661. gs->map->calculateGuardingGreaturePositions();
  662. logGlobal->debug("Added object id=%d; address=%x; name=%s", id, (intptr_t)o, o->getObjectName());
  663. }
  664. DLL_LINKAGE void NewArtifact::applyGs(CGameState *gs)
  665. {
  666. assert(!vstd::contains(gs->map->artInstances, art));
  667. gs->map->addNewArtifactInstance(art);
  668. assert(!art->getParentNodes().size());
  669. art->setType(art->artType);
  670. if (CCombinedArtifactInstance* cart = dynamic_cast<CCombinedArtifactInstance*>(art.get()))
  671. cart->createConstituents();
  672. }
  673. DLL_LINKAGE const CStackInstance * StackLocation::getStack()
  674. {
  675. if(!army->hasStackAtSlot(slot))
  676. {
  677. logNetwork->warn("%s don't have a stack at slot %d", army->nodeName(), slot.getNum());
  678. return nullptr;
  679. }
  680. return &army->getStack(slot);
  681. }
  682. struct ObjectRetriever : boost::static_visitor<const CArmedInstance *>
  683. {
  684. const CArmedInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  685. {
  686. return h;
  687. }
  688. const CArmedInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  689. {
  690. return s->armyObj;
  691. }
  692. };
  693. template <typename T>
  694. struct GetBase : boost::static_visitor<T*>
  695. {
  696. template <typename TArg>
  697. T * operator()(TArg &arg) const
  698. {
  699. return arg;
  700. }
  701. };
  702. DLL_LINKAGE void ArtifactLocation::removeArtifact()
  703. {
  704. CArtifactInstance *a = getArt();
  705. assert(a);
  706. a->removeFrom(*this);
  707. }
  708. DLL_LINKAGE const CArmedInstance * ArtifactLocation::relatedObj() const
  709. {
  710. return boost::apply_visitor(ObjectRetriever(), artHolder);
  711. }
  712. DLL_LINKAGE PlayerColor ArtifactLocation::owningPlayer() const
  713. {
  714. auto obj = relatedObj();
  715. return obj ? obj->tempOwner : PlayerColor::NEUTRAL;
  716. }
  717. DLL_LINKAGE CArtifactSet *ArtifactLocation::getHolderArtSet()
  718. {
  719. return boost::apply_visitor(GetBase<CArtifactSet>(), artHolder);
  720. }
  721. DLL_LINKAGE CBonusSystemNode *ArtifactLocation::getHolderNode()
  722. {
  723. return boost::apply_visitor(GetBase<CBonusSystemNode>(), artHolder);
  724. }
  725. DLL_LINKAGE const CArtifactInstance *ArtifactLocation::getArt() const
  726. {
  727. const ArtSlotInfo *s = getSlot();
  728. if(s && s->artifact)
  729. {
  730. if(!s->locked)
  731. return s->artifact;
  732. else
  733. {
  734. logNetwork->warn("ArtifactLocation::getArt: This location is locked!");
  735. return nullptr;
  736. }
  737. }
  738. return nullptr;
  739. }
  740. DLL_LINKAGE const CArtifactSet * ArtifactLocation::getHolderArtSet() const
  741. {
  742. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  743. return t->getHolderArtSet();
  744. }
  745. DLL_LINKAGE const CBonusSystemNode * ArtifactLocation::getHolderNode() const
  746. {
  747. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  748. return t->getHolderNode();
  749. }
  750. DLL_LINKAGE CArtifactInstance *ArtifactLocation::getArt()
  751. {
  752. const ArtifactLocation *t = this;
  753. return const_cast<CArtifactInstance*>(t->getArt());
  754. }
  755. DLL_LINKAGE const ArtSlotInfo *ArtifactLocation::getSlot() const
  756. {
  757. return getHolderArtSet()->getSlot(slot);
  758. }
  759. DLL_LINKAGE void ChangeStackCount::applyGs(CGameState * gs)
  760. {
  761. auto srcObj = gs->getArmyInstance(army);
  762. if(!srcObj)
  763. logNetwork->error("[CRITICAL] ChangeStackCount: invalid army object %d, possible game state corruption.", army.getNum());
  764. if(absoluteValue)
  765. srcObj->setStackCount(slot, count);
  766. else
  767. srcObj->changeStackCount(slot, count);
  768. }
  769. DLL_LINKAGE void SetStackType::applyGs(CGameState * gs)
  770. {
  771. auto srcObj = gs->getArmyInstance(army);
  772. if(!srcObj)
  773. logNetwork->error("[CRITICAL] SetStackType: invalid army object %d, possible game state corruption.", army.getNum());
  774. srcObj->setStackType(slot, type);
  775. }
  776. DLL_LINKAGE void EraseStack::applyGs(CGameState * gs)
  777. {
  778. auto srcObj = gs->getArmyInstance(army);
  779. if(!srcObj)
  780. logNetwork->error("[CRITICAL] EraseStack: invalid army object %d, possible game state corruption.", army.getNum());
  781. srcObj->eraseStack(slot);
  782. }
  783. DLL_LINKAGE void SwapStacks::applyGs(CGameState * gs)
  784. {
  785. auto srcObj = gs->getArmyInstance(srcArmy);
  786. if(!srcObj)
  787. logNetwork->error("[CRITICAL] SwapStacks: invalid army object %d, possible game state corruption.", srcArmy.getNum());
  788. auto dstObj = gs->getArmyInstance(dstArmy);
  789. if(!dstObj)
  790. logNetwork->error("[CRITICAL] SwapStacks: invalid army object %d, possible game state corruption.", dstArmy.getNum());
  791. CStackInstance * s1 = srcObj->detachStack(srcSlot);
  792. CStackInstance * s2 = dstObj->detachStack(dstSlot);
  793. srcObj->putStack(srcSlot, s2);
  794. dstObj->putStack(dstSlot, s1);
  795. }
  796. DLL_LINKAGE void InsertNewStack::applyGs(CGameState *gs)
  797. {
  798. auto s = new CStackInstance(type, count);
  799. auto obj = gs->getArmyInstance(army);
  800. if(obj)
  801. obj->putStack(slot, s);
  802. else
  803. logNetwork->error("[CRITICAL] InsertNewStack: invalid army object %d, possible game state corruption.", army.getNum());
  804. }
  805. DLL_LINKAGE void RebalanceStacks::applyGs(CGameState * gs)
  806. {
  807. auto srcObj = gs->getArmyInstance(srcArmy);
  808. if(!srcObj)
  809. logNetwork->error("[CRITICAL] RebalanceStacks: invalid army object %d, possible game state corruption.", srcArmy.getNum());
  810. auto dstObj = gs->getArmyInstance(dstArmy);
  811. if(!dstObj)
  812. logNetwork->error("[CRITICAL] RebalanceStacks: invalid army object %d, possible game state corruption.", dstArmy.getNum());
  813. StackLocation src(srcObj, srcSlot);
  814. StackLocation dst(dstObj, dstSlot);
  815. const CCreature * srcType = src.army->getCreature(src.slot);
  816. TQuantity srcCount = src.army->getStackCount(src.slot);
  817. bool stackExp = VLC->modh->modules.STACK_EXP;
  818. if(srcCount == count) //moving whole stack
  819. {
  820. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> merge
  821. {
  822. assert(c == srcType);
  823. UNUSED(c);
  824. auto alHere = ArtifactLocation (src.getStack(), ArtifactPosition::CREATURE_SLOT);
  825. auto alDest = ArtifactLocation (dst.getStack(), ArtifactPosition::CREATURE_SLOT);
  826. auto artHere = alHere.getArt();
  827. auto artDest = alDest.getArt();
  828. if (artHere)
  829. {
  830. if (alDest.getArt())
  831. {
  832. auto hero = dynamic_cast <CGHeroInstance *>(src.army.get());
  833. if (hero)
  834. {
  835. artDest->move (alDest, ArtifactLocation (hero, alDest.getArt()->firstBackpackSlot (hero)));
  836. }
  837. //else - artifact cna be lost :/
  838. else
  839. {
  840. logNetwork->warn("Artifact is present at destination slot!");
  841. }
  842. artHere->move (alHere, alDest);
  843. //TODO: choose from dialog
  844. }
  845. else //just move to the other slot before stack gets erased
  846. {
  847. artHere->move (alHere, alDest);
  848. }
  849. }
  850. if (stackExp)
  851. {
  852. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  853. src.army->eraseStack(src.slot);
  854. dst.army->changeStackCount(dst.slot, count);
  855. dst.army->setStackExp(dst.slot, totalExp /(dst.army->getStackCount(dst.slot))); //mean
  856. }
  857. else
  858. {
  859. src.army->eraseStack(src.slot);
  860. dst.army->changeStackCount(dst.slot, count);
  861. }
  862. }
  863. else //move stack to an empty slot, no exp change needed
  864. {
  865. CStackInstance *stackDetached = src.army->detachStack(src.slot);
  866. dst.army->putStack(dst.slot, stackDetached);
  867. }
  868. }
  869. else
  870. {
  871. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> rebalance
  872. {
  873. assert(c == srcType);
  874. UNUSED(c);
  875. if (stackExp)
  876. {
  877. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  878. src.army->changeStackCount(src.slot, -count);
  879. dst.army->changeStackCount(dst.slot, count);
  880. dst.army->setStackExp(dst.slot, totalExp /(src.army->getStackCount(src.slot) + dst.army->getStackCount(dst.slot))); //mean
  881. }
  882. else
  883. {
  884. src.army->changeStackCount(src.slot, -count);
  885. dst.army->changeStackCount(dst.slot, count);
  886. }
  887. }
  888. else //split stack to an empty slot
  889. {
  890. src.army->changeStackCount(src.slot, -count);
  891. dst.army->addToSlot(dst.slot, srcType->idNumber, count, false);
  892. if (stackExp)
  893. dst.army->setStackExp(dst.slot, src.army->getStackExperience(src.slot));
  894. }
  895. }
  896. CBonusSystemNode::treeHasChanged();
  897. }
  898. DLL_LINKAGE void PutArtifact::applyGs(CGameState *gs)
  899. {
  900. assert(art->canBePutAt(al));
  901. art->putAt(al);
  902. //al.hero->putArtifact(al.slot, art);
  903. }
  904. DLL_LINKAGE void EraseArtifact::applyGs(CGameState *gs)
  905. {
  906. auto slot = al.getSlot();
  907. if(slot->locked)
  908. {
  909. logGlobal->debug("Erasing locked artifact: %s", slot->artifact->artType->Name());
  910. DisassembledArtifact dis;
  911. dis.al.artHolder = al.artHolder;
  912. auto aset = al.getHolderArtSet();
  913. #ifndef NDEBUG
  914. bool found = false;
  915. #endif
  916. for(auto& p : aset->artifactsWorn)
  917. {
  918. auto art = p.second.artifact;
  919. if(art->canBeDisassembled() && art->isPart(slot->artifact))
  920. {
  921. dis.al.slot = aset->getArtPos(art);
  922. #ifndef NDEBUG
  923. found = true;
  924. #endif
  925. break;
  926. }
  927. }
  928. assert(found && "Failed to determine the assembly this locked artifact belongs to");
  929. logGlobal->debug("Found the corresponding assembly: %s", dis.al.getSlot()->artifact->artType->Name());
  930. dis.applyGs(gs);
  931. }
  932. else
  933. {
  934. logGlobal->debug("Erasing artifact %s", slot->artifact->artType->Name());
  935. }
  936. al.removeArtifact();
  937. }
  938. DLL_LINKAGE void MoveArtifact::applyGs(CGameState *gs)
  939. {
  940. CArtifactInstance *a = src.getArt();
  941. if(dst.slot < GameConstants::BACKPACK_START)
  942. assert(!dst.getArt());
  943. a->move(src, dst);
  944. //TODO what'll happen if Titan's thunder is equipped by pickin git up or the start of game?
  945. if (a->artType->id == ArtifactID::TITANS_THUNDER && dst.slot == ArtifactPosition::RIGHT_HAND) //Titan's Thunder creates new spellbook on equip
  946. {
  947. auto hPtr = boost::get<ConstTransitivePtr<CGHeroInstance> >(&dst.artHolder);
  948. if(hPtr)
  949. {
  950. CGHeroInstance *h = *hPtr;
  951. if(h && !h->hasSpellbook())
  952. gs->giveHeroArtifact(h, ArtifactID::SPELLBOOK);
  953. }
  954. }
  955. }
  956. DLL_LINKAGE void AssembledArtifact::applyGs(CGameState *gs)
  957. {
  958. CArtifactSet *artSet = al.getHolderArtSet();
  959. const CArtifactInstance *transformedArt = al.getArt();
  960. assert(transformedArt);
  961. assert(vstd::contains(transformedArt->assemblyPossibilities(artSet), builtArt));
  962. UNUSED(transformedArt);
  963. auto combinedArt = new CCombinedArtifactInstance(builtArt);
  964. gs->map->addNewArtifactInstance(combinedArt);
  965. //retrieve all constituents
  966. for(const CArtifact * constituent : *builtArt->constituents)
  967. {
  968. ArtifactPosition pos = artSet->getArtPos(constituent->id);
  969. assert(pos >= 0);
  970. CArtifactInstance *constituentInstance = artSet->getArt(pos);
  971. //move constituent from hero to be part of new, combined artifact
  972. constituentInstance->removeFrom(ArtifactLocation(al.artHolder, pos));
  973. combinedArt->addAsConstituent(constituentInstance, pos);
  974. if(!vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], al.slot) && vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], pos))
  975. al.slot = pos;
  976. }
  977. //put new combined artifacts
  978. combinedArt->putAt(al);
  979. }
  980. DLL_LINKAGE void DisassembledArtifact::applyGs(CGameState *gs)
  981. {
  982. CCombinedArtifactInstance *disassembled = dynamic_cast<CCombinedArtifactInstance*>(al.getArt());
  983. assert(disassembled);
  984. std::vector<CCombinedArtifactInstance::ConstituentInfo> constituents = disassembled->constituentsInfo;
  985. disassembled->removeFrom(al);
  986. for(CCombinedArtifactInstance::ConstituentInfo &ci : constituents)
  987. {
  988. ArtifactLocation constituentLoc = al;
  989. constituentLoc.slot = (ci.slot >= 0 ? ci.slot : al.slot); //-1 is slot of main constituent -> it'll replace combined artifact in its pos
  990. disassembled->detachFrom(ci.art);
  991. ci.art->putAt(constituentLoc);
  992. }
  993. gs->map->eraseArtifactInstance(disassembled);
  994. }
  995. DLL_LINKAGE void HeroVisit::applyGs(CGameState *gs)
  996. {
  997. }
  998. DLL_LINKAGE void SetAvailableArtifacts::applyGs(CGameState *gs)
  999. {
  1000. if(id >= 0)
  1001. {
  1002. if(CGBlackMarket *bm = dynamic_cast<CGBlackMarket*>(gs->map->objects[id].get()))
  1003. {
  1004. bm->artifacts = arts;
  1005. }
  1006. else
  1007. {
  1008. logNetwork->error("Wrong black market id!");
  1009. }
  1010. }
  1011. else
  1012. {
  1013. CGTownInstance::merchantArtifacts = arts;
  1014. }
  1015. }
  1016. DLL_LINKAGE void NewTurn::applyGs(CGameState *gs)
  1017. {
  1018. gs->day = day;
  1019. // Update bonuses before doing anything else so hero don't get more MP than needed
  1020. gs->globalEffects.removeBonusesRecursive(Bonus::OneDay); //works for children -> all game objs
  1021. gs->globalEffects.reduceBonusDurations(Bonus::NDays);
  1022. gs->globalEffects.reduceBonusDurations(Bonus::OneWeek);
  1023. //TODO not really a single root hierarchy, what about bonuses placed elsewhere? [not an issue with H3 mechanics but in the future...]
  1024. for(NewTurn::Hero h : heroes) //give mana/movement point
  1025. {
  1026. CGHeroInstance *hero = gs->getHero(h.id);
  1027. if(!hero)
  1028. {
  1029. // retreated or surrendered hero who has not been reset yet
  1030. for(auto& hp : gs->hpool.heroesPool)
  1031. {
  1032. if(hp.second->id == h.id)
  1033. {
  1034. hero = hp.second;
  1035. break;
  1036. }
  1037. }
  1038. }
  1039. if(!hero)
  1040. {
  1041. logGlobal->error("Hero %d not found in NewTurn::applyGs", h.id.getNum());
  1042. continue;
  1043. }
  1044. hero->movement = h.move;
  1045. hero->mana = h.mana;
  1046. }
  1047. for(auto i = res.cbegin(); i != res.cend(); i++)
  1048. {
  1049. assert(i->first < PlayerColor::PLAYER_LIMIT);
  1050. gs->getPlayer(i->first)->resources = i->second;
  1051. }
  1052. for(auto creatureSet : cres) //set available creatures in towns
  1053. creatureSet.second.applyGs(gs);
  1054. for(CGTownInstance* t : gs->map->towns)
  1055. t->builded = 0;
  1056. if(gs->getDate(Date::DAY_OF_WEEK) == 1)
  1057. gs->updateRumor();
  1058. //count days without town for all players, regardless of their turn order
  1059. for (auto &p : gs->players)
  1060. {
  1061. PlayerState & playerState = p.second;
  1062. if (playerState.status == EPlayerStatus::INGAME)
  1063. {
  1064. if (playerState.towns.empty())
  1065. {
  1066. if (playerState.daysWithoutCastle)
  1067. ++(*playerState.daysWithoutCastle);
  1068. else
  1069. playerState.daysWithoutCastle = boost::make_optional(0);
  1070. }
  1071. else
  1072. {
  1073. playerState.daysWithoutCastle = boost::none;
  1074. }
  1075. }
  1076. }
  1077. }
  1078. DLL_LINKAGE void SetObjectProperty::applyGs(CGameState *gs)
  1079. {
  1080. CGObjectInstance *obj = gs->getObjInstance(id);
  1081. if(!obj)
  1082. {
  1083. logNetwork->error("Wrong object ID - property cannot be set!");
  1084. return;
  1085. }
  1086. CArmedInstance *cai = dynamic_cast<CArmedInstance *>(obj);
  1087. if(what == ObjProperty::OWNER && cai)
  1088. {
  1089. if(obj->ID == Obj::TOWN)
  1090. {
  1091. CGTownInstance *t = static_cast<CGTownInstance*>(obj);
  1092. if(t->tempOwner < PlayerColor::PLAYER_LIMIT)
  1093. gs->getPlayer(t->tempOwner)->towns -= t;
  1094. if(val < PlayerColor::PLAYER_LIMIT_I)
  1095. {
  1096. PlayerState * p = gs->getPlayer(PlayerColor(val));
  1097. p->towns.push_back(t);
  1098. //reset counter before NewTurn to avoid no town message if game loaded at turn when one already captured
  1099. if(p->daysWithoutCastle)
  1100. p->daysWithoutCastle = boost::none;
  1101. }
  1102. }
  1103. CBonusSystemNode *nodeToMove = cai->whatShouldBeAttached();
  1104. nodeToMove->detachFrom(cai->whereShouldBeAttached(gs));
  1105. obj->setProperty(what,val);
  1106. nodeToMove->attachTo(cai->whereShouldBeAttached(gs));
  1107. }
  1108. else //not an armed instance
  1109. {
  1110. obj->setProperty(what,val);
  1111. }
  1112. }
  1113. DLL_LINKAGE void PrepareHeroLevelUp::applyGs(CGameState * gs)
  1114. {
  1115. auto hero = gs->getHero(heroId);
  1116. assert(hero);
  1117. auto proposedSkills = hero->getLevelUpProposedSecondarySkills();
  1118. if(skills.size() == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  1119. {
  1120. skills.push_back(*RandomGeneratorUtil::nextItem(proposedSkills, hero->skillsInfo.rand));
  1121. }
  1122. else
  1123. {
  1124. skills = proposedSkills;
  1125. }
  1126. }
  1127. DLL_LINKAGE void HeroLevelUp::applyGs(CGameState * gs)
  1128. {
  1129. auto hero = gs->getHero(heroId);
  1130. assert(hero);
  1131. hero->levelUp(skills);
  1132. }
  1133. DLL_LINKAGE void CommanderLevelUp::applyGs(CGameState * gs)
  1134. {
  1135. auto hero = gs->getHero(heroId);
  1136. assert(hero);
  1137. auto commander = hero->commander;
  1138. assert(commander);
  1139. commander->levelUp();
  1140. }
  1141. DLL_LINKAGE void BattleStart::applyGs(CGameState *gs)
  1142. {
  1143. gs->curB = info;
  1144. gs->curB->localInit();
  1145. }
  1146. DLL_LINKAGE void BattleNextRound::applyGs(CGameState *gs)
  1147. {
  1148. gs->curB->nextRound(round);
  1149. }
  1150. DLL_LINKAGE void BattleSetActiveStack::applyGs(CGameState *gs)
  1151. {
  1152. gs->curB->nextTurn(stack);
  1153. }
  1154. DLL_LINKAGE void BattleTriggerEffect::applyGs(CGameState *gs)
  1155. {
  1156. CStack * st = gs->curB->getStack(stackID);
  1157. assert(st);
  1158. switch(effect)
  1159. {
  1160. case Bonus::HP_REGENERATION:
  1161. {
  1162. int64_t toHeal = val;
  1163. st->heal(toHeal, EHealLevel::HEAL, EHealPower::PERMANENT);
  1164. break;
  1165. }
  1166. case Bonus::MANA_DRAIN:
  1167. {
  1168. CGHeroInstance * h = gs->getHero(ObjectInstanceID(additionalInfo));
  1169. st->drainedMana = true;
  1170. h->mana -= val;
  1171. vstd::amax(h->mana, 0);
  1172. break;
  1173. }
  1174. case Bonus::POISON:
  1175. {
  1176. auto b = st->getBonusLocalFirst(Selector::source(Bonus::SPELL_EFFECT, SpellID::POISON)
  1177. .And(Selector::type()(Bonus::STACK_HEALTH)));
  1178. if (b)
  1179. b->val = val;
  1180. break;
  1181. }
  1182. case Bonus::ENCHANTER:
  1183. break;
  1184. case Bonus::FEAR:
  1185. st->fear = true;
  1186. break;
  1187. default:
  1188. logNetwork->error("Unrecognized trigger effect type %d", effect);
  1189. }
  1190. }
  1191. DLL_LINKAGE void BattleUpdateGateState::applyGs(CGameState *gs)
  1192. {
  1193. if(gs->curB)
  1194. gs->curB->si.gateState = state;
  1195. }
  1196. void BattleResult::applyGs(CGameState *gs)
  1197. {
  1198. for (auto & elem : gs->curB->stacks)
  1199. delete elem;
  1200. for(int i = 0; i < 2; ++i)
  1201. {
  1202. if(auto h = gs->curB->battleGetFightingHero(i))
  1203. {
  1204. h->removeBonusesRecursive(Bonus::OneBattle); //remove any "until next battle" bonuses
  1205. if (h->commander && h->commander->alive)
  1206. {
  1207. for (auto art : h->commander->artifactsWorn) //increment bonuses for commander artifacts
  1208. {
  1209. art.second.artifact->artType->levelUpArtifact (art.second.artifact);
  1210. }
  1211. }
  1212. }
  1213. }
  1214. if(VLC->modh->modules.STACK_EXP)
  1215. {
  1216. for(int i = 0; i < 2; i++)
  1217. if(exp[i])
  1218. gs->curB->battleGetArmyObject(i)->giveStackExp(exp[i]);
  1219. CBonusSystemNode::treeHasChanged();
  1220. }
  1221. for(int i = 0; i < 2; i++)
  1222. gs->curB->battleGetArmyObject(i)->battle = nullptr;
  1223. gs->curB.dellNull();
  1224. }
  1225. DLL_LINKAGE void BattleStackMoved::applyGs(CGameState *gs)
  1226. {
  1227. applyBattle(gs->curB);
  1228. }
  1229. DLL_LINKAGE void BattleStackMoved::applyBattle(IBattleState * battleState)
  1230. {
  1231. battleState->moveUnit(stack, tilesToMove.back());
  1232. }
  1233. DLL_LINKAGE void BattleStackAttacked::applyGs(CGameState * gs)
  1234. {
  1235. applyBattle(gs->curB);
  1236. }
  1237. DLL_LINKAGE void BattleStackAttacked::applyBattle(IBattleState * battleState)
  1238. {
  1239. battleState->setUnitState(newState.id, newState.data, newState.healthDelta);
  1240. }
  1241. DLL_LINKAGE void BattleAttack::applyGs(CGameState * gs)
  1242. {
  1243. CStack * attacker = gs->curB->getStack(stackAttacking);
  1244. assert(attacker);
  1245. attackerChanges.applyGs(gs);
  1246. for(BattleStackAttacked & stackAttacked : bsa)
  1247. stackAttacked.applyGs(gs);
  1248. attacker->removeBonusesRecursive(Bonus::UntilAttack);
  1249. }
  1250. DLL_LINKAGE void StartAction::applyGs(CGameState *gs)
  1251. {
  1252. CStack *st = gs->curB->getStack(ba.stackNumber);
  1253. if(ba.actionType == EActionType::END_TACTIC_PHASE)
  1254. {
  1255. gs->curB->tacticDistance = 0;
  1256. return;
  1257. }
  1258. if(gs->curB->tacticDistance)
  1259. {
  1260. // moves in tactics phase do not affect creature status
  1261. // (tactics stack queue is managed by client)
  1262. return;
  1263. }
  1264. if(ba.actionType != EActionType::HERO_SPELL) //don't check for stack if it's custom action by hero
  1265. {
  1266. assert(st);
  1267. }
  1268. else
  1269. {
  1270. gs->curB->sides[ba.side].usedSpellsHistory.push_back(SpellID(ba.actionSubtype).toSpell());
  1271. }
  1272. switch(ba.actionType)
  1273. {
  1274. case EActionType::DEFEND:
  1275. st->waiting = false;
  1276. st->defending = true;
  1277. st->defendingAnim = true;
  1278. break;
  1279. case EActionType::WAIT:
  1280. st->defendingAnim = false;
  1281. st->waiting = true;
  1282. st->waitedThisTurn = true;
  1283. break;
  1284. case EActionType::HERO_SPELL: //no change in current stack state
  1285. break;
  1286. default: //any active stack action - attack, catapult, heal, spell...
  1287. st->waiting = false;
  1288. st->defendingAnim = false;
  1289. st->movedThisRound = true;
  1290. break;
  1291. }
  1292. }
  1293. DLL_LINKAGE void BattleSpellCast::applyGs(CGameState *gs)
  1294. {
  1295. assert(gs->curB);
  1296. if(castByHero)
  1297. {
  1298. if(side < 2)
  1299. {
  1300. gs->curB->sides[side].castSpellsCount++;
  1301. }
  1302. }
  1303. }
  1304. DLL_LINKAGE void SetStackEffect::applyGs(CGameState *gs)
  1305. {
  1306. applyBattle(gs->curB);
  1307. }
  1308. DLL_LINKAGE void SetStackEffect::applyBattle(IBattleState * battleState)
  1309. {
  1310. for(const auto & stackData : toRemove)
  1311. battleState->removeUnitBonus(stackData.first, stackData.second);
  1312. for(const auto & stackData : toUpdate)
  1313. battleState->updateUnitBonus(stackData.first, stackData.second);
  1314. for(const auto & stackData : toAdd)
  1315. battleState->addUnitBonus(stackData.first, stackData.second);
  1316. }
  1317. DLL_LINKAGE void StacksInjured::applyGs(CGameState *gs)
  1318. {
  1319. applyBattle(gs->curB);
  1320. }
  1321. DLL_LINKAGE void StacksInjured::applyBattle(IBattleState * battleState)
  1322. {
  1323. for(BattleStackAttacked stackAttacked : stacks)
  1324. stackAttacked.applyBattle(battleState);
  1325. }
  1326. DLL_LINKAGE void BattleUnitsChanged::applyGs(CGameState *gs)
  1327. {
  1328. applyBattle(gs->curB);
  1329. }
  1330. DLL_LINKAGE void BattleUnitsChanged::applyBattle(IBattleState * battleState)
  1331. {
  1332. for(auto & elem : changedStacks)
  1333. {
  1334. switch(elem.operation)
  1335. {
  1336. case BattleChanges::EOperation::RESET_STATE:
  1337. battleState->setUnitState(elem.id, elem.data, elem.healthDelta);
  1338. break;
  1339. case BattleChanges::EOperation::REMOVE:
  1340. battleState->removeUnit(elem.id);
  1341. break;
  1342. case BattleChanges::EOperation::ADD:
  1343. battleState->addUnit(elem.id, elem.data);
  1344. break;
  1345. default:
  1346. logNetwork->error("Unknown unit operation %d", (int)elem.operation);
  1347. break;
  1348. }
  1349. }
  1350. }
  1351. DLL_LINKAGE void BattleObstaclesChanged::applyGs(CGameState * gs)
  1352. {
  1353. if(gs->curB)
  1354. applyBattle(gs->curB);
  1355. }
  1356. DLL_LINKAGE void BattleObstaclesChanged::applyBattle(IBattleState * battleState)
  1357. {
  1358. for(const auto & change : changes)
  1359. {
  1360. switch(change.operation)
  1361. {
  1362. case BattleChanges::EOperation::REMOVE:
  1363. battleState->removeObstacle(change.id);
  1364. break;
  1365. case BattleChanges::EOperation::ADD:
  1366. battleState->addObstacle(change);
  1367. break;
  1368. case BattleChanges::EOperation::UPDATE:
  1369. battleState->updateObstacle(change);
  1370. break;
  1371. default:
  1372. logNetwork->error("Unknown obstacle operation %d", (int)change.operation);
  1373. break;
  1374. }
  1375. }
  1376. }
  1377. DLL_LINKAGE CatapultAttack::CatapultAttack()
  1378. {
  1379. attacker = -1;
  1380. }
  1381. DLL_LINKAGE CatapultAttack::~CatapultAttack()
  1382. {
  1383. }
  1384. DLL_LINKAGE void CatapultAttack::applyGs(CGameState * gs)
  1385. {
  1386. if(gs->curB)
  1387. applyBattle(gs->curB);
  1388. }
  1389. DLL_LINKAGE void CatapultAttack::applyBattle(IBattleState * battleState)
  1390. {
  1391. auto town = battleState->getDefendedTown();
  1392. if(!town)
  1393. return;
  1394. if(town->fortLevel() == CGTownInstance::NONE)
  1395. return;
  1396. for(const auto & part : attackedParts)
  1397. {
  1398. auto newWallState = SiegeInfo::applyDamage(EWallState::EWallState(battleState->getWallState(part.attackedPart)), part.damageDealt);
  1399. battleState->setWallState(part.attackedPart, newWallState);
  1400. }
  1401. }
  1402. DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState * gs)
  1403. {
  1404. CStack * stack = gs->curB->getStack(stackID);
  1405. switch(which)
  1406. {
  1407. case CASTS:
  1408. {
  1409. if(absolute)
  1410. logNetwork->error("Can not change casts in absolute mode");
  1411. else
  1412. stack->casts.use(-val);
  1413. break;
  1414. }
  1415. case ENCHANTER_COUNTER:
  1416. {
  1417. auto & counter = gs->curB->sides[gs->curB->whatSide(stack->owner)].enchanterCounter;
  1418. if(absolute)
  1419. counter = val;
  1420. else
  1421. counter += val;
  1422. vstd::amax(counter, 0);
  1423. break;
  1424. }
  1425. case UNBIND:
  1426. {
  1427. stack->removeBonusesRecursive(Selector::type()(Bonus::BIND_EFFECT));
  1428. break;
  1429. }
  1430. case CLONED:
  1431. {
  1432. stack->cloned = true;
  1433. break;
  1434. }
  1435. case HAS_CLONE:
  1436. {
  1437. stack->cloneID = val;
  1438. break;
  1439. }
  1440. }
  1441. }
  1442. DLL_LINKAGE void PlayerCheated::applyGs(CGameState *gs)
  1443. {
  1444. if(!player.isValidPlayer())
  1445. return;
  1446. gs->getPlayer(player)->enteredLosingCheatCode = losingCheatCode;
  1447. gs->getPlayer(player)->enteredWinningCheatCode = winningCheatCode;
  1448. }
  1449. DLL_LINKAGE void YourTurn::applyGs(CGameState *gs)
  1450. {
  1451. gs->currentPlayer = player;
  1452. auto & playerState = gs->players[player];
  1453. playerState.daysWithoutCastle = daysWithoutCastle;
  1454. }
  1455. DLL_LINKAGE Component::Component(const CStackBasicDescriptor &stack)
  1456. : id(CREATURE), subtype(stack.type->idNumber), val(stack.count), when(0)
  1457. {
  1458. }