NetPacksLib.cpp 42 KB

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