NetPacksLib.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  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->spells.insert(sid);
  125. else
  126. for(auto sid : spells)
  127. hero->spells.erase(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. const TerrainTile &t = gs->map->getTile(pos);
  597. ETerrainType terrainType = t.terType;
  598. CGObjectInstance *o = nullptr;
  599. switch(ID)
  600. {
  601. case Obj::BOAT:
  602. o = new CGBoat();
  603. terrainType = ETerrainType::WATER; //TODO: either boat should only spawn on water, or all water objects should be handled this way
  604. break;
  605. case Obj::MONSTER: //probably more options will be needed
  606. o = new CGCreature();
  607. {
  608. //CStackInstance hlp;
  609. CGCreature *cre = static_cast<CGCreature*>(o);
  610. //cre->slots[0] = hlp;
  611. cre->notGrowingTeam = cre->neverFlees = 0;
  612. cre->character = 2;
  613. cre->gainedArtifact = ArtifactID::NONE;
  614. cre->identifier = -1;
  615. cre->addToSlot(SlotID(0), new CStackInstance(CreatureID(subID), -1)); //add placeholder stack
  616. }
  617. break;
  618. default:
  619. o = new CGObjectInstance();
  620. break;
  621. }
  622. o->ID = ID;
  623. o->subID = subID;
  624. o->pos = pos;
  625. o->appearance = VLC->objtypeh->getHandlerFor(o->ID, o->subID)->getTemplates(terrainType).front();
  626. id = o->id = ObjectInstanceID(gs->map->objects.size());
  627. gs->map->objects.push_back(o);
  628. gs->map->addBlockVisTiles(o);
  629. o->initObj(gs->getRandomGenerator());
  630. gs->map->calculateGuardingGreaturePositions();
  631. logGlobal->debug("Added object id=%d; address=%x; name=%s", id, (intptr_t)o, o->getObjectName());
  632. }
  633. DLL_LINKAGE void NewArtifact::applyGs(CGameState *gs)
  634. {
  635. assert(!vstd::contains(gs->map->artInstances, art));
  636. gs->map->addNewArtifactInstance(art);
  637. assert(!art->getParentNodes().size());
  638. art->setType(art->artType);
  639. if (CCombinedArtifactInstance* cart = dynamic_cast<CCombinedArtifactInstance*>(art.get()))
  640. cart->createConstituents();
  641. }
  642. DLL_LINKAGE const CStackInstance * StackLocation::getStack()
  643. {
  644. if(!army->hasStackAtSlot(slot))
  645. {
  646. logNetwork->warn("%s don't have a stack at slot %d", army->nodeName(), slot.getNum());
  647. return nullptr;
  648. }
  649. return &army->getStack(slot);
  650. }
  651. struct ObjectRetriever : boost::static_visitor<const CArmedInstance *>
  652. {
  653. const CArmedInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  654. {
  655. return h;
  656. }
  657. const CArmedInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  658. {
  659. return s->armyObj;
  660. }
  661. };
  662. template <typename T>
  663. struct GetBase : boost::static_visitor<T*>
  664. {
  665. template <typename TArg>
  666. T * operator()(TArg &arg) const
  667. {
  668. return arg;
  669. }
  670. };
  671. DLL_LINKAGE void ArtifactLocation::removeArtifact()
  672. {
  673. CArtifactInstance *a = getArt();
  674. assert(a);
  675. a->removeFrom(*this);
  676. }
  677. DLL_LINKAGE const CArmedInstance * ArtifactLocation::relatedObj() const
  678. {
  679. return boost::apply_visitor(ObjectRetriever(), artHolder);
  680. }
  681. DLL_LINKAGE PlayerColor ArtifactLocation::owningPlayer() const
  682. {
  683. auto obj = relatedObj();
  684. return obj ? obj->tempOwner : PlayerColor::NEUTRAL;
  685. }
  686. DLL_LINKAGE CArtifactSet *ArtifactLocation::getHolderArtSet()
  687. {
  688. return boost::apply_visitor(GetBase<CArtifactSet>(), artHolder);
  689. }
  690. DLL_LINKAGE CBonusSystemNode *ArtifactLocation::getHolderNode()
  691. {
  692. return boost::apply_visitor(GetBase<CBonusSystemNode>(), artHolder);
  693. }
  694. DLL_LINKAGE const CArtifactInstance *ArtifactLocation::getArt() const
  695. {
  696. const ArtSlotInfo *s = getSlot();
  697. if(s && s->artifact)
  698. {
  699. if(!s->locked)
  700. return s->artifact;
  701. else
  702. {
  703. logNetwork->warn("ArtifactLocation::getArt: This location is locked!");
  704. return nullptr;
  705. }
  706. }
  707. return nullptr;
  708. }
  709. DLL_LINKAGE const CArtifactSet * ArtifactLocation::getHolderArtSet() const
  710. {
  711. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  712. return t->getHolderArtSet();
  713. }
  714. DLL_LINKAGE const CBonusSystemNode * ArtifactLocation::getHolderNode() const
  715. {
  716. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  717. return t->getHolderNode();
  718. }
  719. DLL_LINKAGE CArtifactInstance *ArtifactLocation::getArt()
  720. {
  721. const ArtifactLocation *t = this;
  722. return const_cast<CArtifactInstance*>(t->getArt());
  723. }
  724. DLL_LINKAGE const ArtSlotInfo *ArtifactLocation::getSlot() const
  725. {
  726. return getHolderArtSet()->getSlot(slot);
  727. }
  728. DLL_LINKAGE void ChangeStackCount::applyGs(CGameState * gs)
  729. {
  730. auto srcObj = gs->getArmyInstance(army);
  731. if(!srcObj)
  732. logNetwork->error("[CRITICAL] ChangeStackCount: invalid army object %d, possible game state corruption.", army.getNum());
  733. if(absoluteValue)
  734. srcObj->setStackCount(slot, count);
  735. else
  736. srcObj->changeStackCount(slot, count);
  737. }
  738. DLL_LINKAGE void SetStackType::applyGs(CGameState * gs)
  739. {
  740. auto srcObj = gs->getArmyInstance(army);
  741. if(!srcObj)
  742. logNetwork->error("[CRITICAL] SetStackType: invalid army object %d, possible game state corruption.", army.getNum());
  743. srcObj->setStackType(slot, type);
  744. }
  745. DLL_LINKAGE void EraseStack::applyGs(CGameState * gs)
  746. {
  747. auto srcObj = gs->getArmyInstance(army);
  748. if(!srcObj)
  749. logNetwork->error("[CRITICAL] EraseStack: invalid army object %d, possible game state corruption.", army.getNum());
  750. srcObj->eraseStack(slot);
  751. }
  752. DLL_LINKAGE void SwapStacks::applyGs(CGameState * gs)
  753. {
  754. auto srcObj = gs->getArmyInstance(srcArmy);
  755. if(!srcObj)
  756. logNetwork->error("[CRITICAL] SwapStacks: invalid army object %d, possible game state corruption.", srcArmy.getNum());
  757. auto dstObj = gs->getArmyInstance(dstArmy);
  758. if(!dstObj)
  759. logNetwork->error("[CRITICAL] SwapStacks: invalid army object %d, possible game state corruption.", dstArmy.getNum());
  760. CStackInstance * s1 = srcObj->detachStack(srcSlot);
  761. CStackInstance * s2 = dstObj->detachStack(dstSlot);
  762. srcObj->putStack(srcSlot, s2);
  763. dstObj->putStack(dstSlot, s1);
  764. }
  765. DLL_LINKAGE void InsertNewStack::applyGs(CGameState *gs)
  766. {
  767. auto s = new CStackInstance(type, count);
  768. auto obj = gs->getArmyInstance(army);
  769. if(obj)
  770. obj->putStack(slot, s);
  771. else
  772. logNetwork->error("[CRITICAL] InsertNewStack: invalid army object %d, possible game state corruption.", army.getNum());
  773. }
  774. DLL_LINKAGE void RebalanceStacks::applyGs(CGameState * gs)
  775. {
  776. auto srcObj = gs->getArmyInstance(srcArmy);
  777. if(!srcObj)
  778. logNetwork->error("[CRITICAL] RebalanceStacks: invalid army object %d, possible game state corruption.", srcArmy.getNum());
  779. auto dstObj = gs->getArmyInstance(dstArmy);
  780. if(!dstObj)
  781. logNetwork->error("[CRITICAL] RebalanceStacks: invalid army object %d, possible game state corruption.", dstArmy.getNum());
  782. StackLocation src(srcObj, srcSlot);
  783. StackLocation dst(dstObj, dstSlot);
  784. const CCreature * srcType = src.army->getCreature(src.slot);
  785. TQuantity srcCount = src.army->getStackCount(src.slot);
  786. bool stackExp = VLC->modh->modules.STACK_EXP;
  787. if(srcCount == count) //moving whole stack
  788. {
  789. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> merge
  790. {
  791. assert(c == srcType);
  792. UNUSED(c);
  793. auto alHere = ArtifactLocation (src.getStack(), ArtifactPosition::CREATURE_SLOT);
  794. auto alDest = ArtifactLocation (dst.getStack(), ArtifactPosition::CREATURE_SLOT);
  795. auto artHere = alHere.getArt();
  796. auto artDest = alDest.getArt();
  797. if (artHere)
  798. {
  799. if (alDest.getArt())
  800. {
  801. auto hero = dynamic_cast <CGHeroInstance *>(src.army.get());
  802. if (hero)
  803. {
  804. artDest->move (alDest, ArtifactLocation (hero, alDest.getArt()->firstBackpackSlot (hero)));
  805. }
  806. //else - artifact cna be lost :/
  807. else
  808. {
  809. logNetwork->warn("Artifact is present at destination slot!");
  810. }
  811. artHere->move (alHere, alDest);
  812. //TODO: choose from dialog
  813. }
  814. else //just move to the other slot before stack gets erased
  815. {
  816. artHere->move (alHere, alDest);
  817. }
  818. }
  819. if (stackExp)
  820. {
  821. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  822. src.army->eraseStack(src.slot);
  823. dst.army->changeStackCount(dst.slot, count);
  824. dst.army->setStackExp(dst.slot, totalExp /(dst.army->getStackCount(dst.slot))); //mean
  825. }
  826. else
  827. {
  828. src.army->eraseStack(src.slot);
  829. dst.army->changeStackCount(dst.slot, count);
  830. }
  831. }
  832. else //move stack to an empty slot, no exp change needed
  833. {
  834. CStackInstance *stackDetached = src.army->detachStack(src.slot);
  835. dst.army->putStack(dst.slot, stackDetached);
  836. }
  837. }
  838. else
  839. {
  840. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> rebalance
  841. {
  842. assert(c == srcType);
  843. UNUSED(c);
  844. if (stackExp)
  845. {
  846. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  847. src.army->changeStackCount(src.slot, -count);
  848. dst.army->changeStackCount(dst.slot, count);
  849. dst.army->setStackExp(dst.slot, totalExp /(src.army->getStackCount(src.slot) + dst.army->getStackCount(dst.slot))); //mean
  850. }
  851. else
  852. {
  853. src.army->changeStackCount(src.slot, -count);
  854. dst.army->changeStackCount(dst.slot, count);
  855. }
  856. }
  857. else //split stack to an empty slot
  858. {
  859. src.army->changeStackCount(src.slot, -count);
  860. dst.army->addToSlot(dst.slot, srcType->idNumber, count, false);
  861. if (stackExp)
  862. dst.army->setStackExp(dst.slot, src.army->getStackExperience(src.slot));
  863. }
  864. }
  865. CBonusSystemNode::treeHasChanged();
  866. }
  867. DLL_LINKAGE void PutArtifact::applyGs(CGameState *gs)
  868. {
  869. assert(art->canBePutAt(al));
  870. art->putAt(al);
  871. //al.hero->putArtifact(al.slot, art);
  872. }
  873. DLL_LINKAGE void EraseArtifact::applyGs(CGameState *gs)
  874. {
  875. auto slot = al.getSlot();
  876. if(slot->locked)
  877. {
  878. logGlobal->debug("Erasing locked artifact: %s", slot->artifact->artType->Name());
  879. DisassembledArtifact dis;
  880. dis.al.artHolder = al.artHolder;
  881. auto aset = al.getHolderArtSet();
  882. #ifndef NDEBUG
  883. bool found = false;
  884. #endif
  885. for(auto& p : aset->artifactsWorn)
  886. {
  887. auto art = p.second.artifact;
  888. if(art->canBeDisassembled() && art->isPart(slot->artifact))
  889. {
  890. dis.al.slot = aset->getArtPos(art);
  891. #ifndef NDEBUG
  892. found = true;
  893. #endif
  894. break;
  895. }
  896. }
  897. assert(found && "Failed to determine the assembly this locked artifact belongs to");
  898. logGlobal->debug("Found the corresponding assembly: %s", dis.al.getSlot()->artifact->artType->Name());
  899. dis.applyGs(gs);
  900. }
  901. else
  902. {
  903. logGlobal->debug("Erasing artifact %s", slot->artifact->artType->Name());
  904. }
  905. al.removeArtifact();
  906. }
  907. DLL_LINKAGE void MoveArtifact::applyGs(CGameState *gs)
  908. {
  909. CArtifactInstance *a = src.getArt();
  910. if(dst.slot < GameConstants::BACKPACK_START)
  911. assert(!dst.getArt());
  912. a->move(src, dst);
  913. //TODO what'll happen if Titan's thunder is equipped by pickin git up or the start of game?
  914. if (a->artType->id == ArtifactID::TITANS_THUNDER && dst.slot == ArtifactPosition::RIGHT_HAND) //Titan's Thunder creates new spellbook on equip
  915. {
  916. auto hPtr = boost::get<ConstTransitivePtr<CGHeroInstance> >(&dst.artHolder);
  917. if(hPtr)
  918. {
  919. CGHeroInstance *h = *hPtr;
  920. if(h && !h->hasSpellbook())
  921. gs->giveHeroArtifact(h, ArtifactID::SPELLBOOK);
  922. }
  923. }
  924. }
  925. DLL_LINKAGE void AssembledArtifact::applyGs(CGameState *gs)
  926. {
  927. CArtifactSet *artSet = al.getHolderArtSet();
  928. const CArtifactInstance *transformedArt = al.getArt();
  929. assert(transformedArt);
  930. assert(vstd::contains(transformedArt->assemblyPossibilities(artSet), builtArt));
  931. UNUSED(transformedArt);
  932. auto combinedArt = new CCombinedArtifactInstance(builtArt);
  933. gs->map->addNewArtifactInstance(combinedArt);
  934. //retrieve all constituents
  935. for(const CArtifact * constituent : *builtArt->constituents)
  936. {
  937. ArtifactPosition pos = artSet->getArtPos(constituent->id);
  938. assert(pos >= 0);
  939. CArtifactInstance *constituentInstance = artSet->getArt(pos);
  940. //move constituent from hero to be part of new, combined artifact
  941. constituentInstance->removeFrom(ArtifactLocation(al.artHolder, pos));
  942. combinedArt->addAsConstituent(constituentInstance, pos);
  943. if(!vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], al.slot) && vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], pos))
  944. al.slot = pos;
  945. }
  946. //put new combined artifacts
  947. combinedArt->putAt(al);
  948. }
  949. DLL_LINKAGE void DisassembledArtifact::applyGs(CGameState *gs)
  950. {
  951. CCombinedArtifactInstance *disassembled = dynamic_cast<CCombinedArtifactInstance*>(al.getArt());
  952. assert(disassembled);
  953. std::vector<CCombinedArtifactInstance::ConstituentInfo> constituents = disassembled->constituentsInfo;
  954. disassembled->removeFrom(al);
  955. for(CCombinedArtifactInstance::ConstituentInfo &ci : constituents)
  956. {
  957. ArtifactLocation constituentLoc = al;
  958. constituentLoc.slot = (ci.slot >= 0 ? ci.slot : al.slot); //-1 is slot of main constituent -> it'll replace combined artifact in its pos
  959. disassembled->detachFrom(ci.art);
  960. ci.art->putAt(constituentLoc);
  961. }
  962. gs->map->eraseArtifactInstance(disassembled);
  963. }
  964. DLL_LINKAGE void HeroVisit::applyGs(CGameState *gs)
  965. {
  966. }
  967. DLL_LINKAGE void SetAvailableArtifacts::applyGs(CGameState *gs)
  968. {
  969. if(id >= 0)
  970. {
  971. if(CGBlackMarket *bm = dynamic_cast<CGBlackMarket*>(gs->map->objects[id].get()))
  972. {
  973. bm->artifacts = arts;
  974. }
  975. else
  976. {
  977. logNetwork->error("Wrong black market id!");
  978. }
  979. }
  980. else
  981. {
  982. CGTownInstance::merchantArtifacts = arts;
  983. }
  984. }
  985. DLL_LINKAGE void NewTurn::applyGs(CGameState *gs)
  986. {
  987. gs->day = day;
  988. // Update bonuses before doing anything else so hero don't get more MP than needed
  989. gs->globalEffects.removeBonusesRecursive(Bonus::OneDay); //works for children -> all game objs
  990. gs->globalEffects.reduceBonusDurations(Bonus::NDays);
  991. gs->globalEffects.reduceBonusDurations(Bonus::OneWeek);
  992. //TODO not really a single root hierarchy, what about bonuses placed elsewhere? [not an issue with H3 mechanics but in the future...]
  993. for(NewTurn::Hero h : heroes) //give mana/movement point
  994. {
  995. CGHeroInstance *hero = gs->getHero(h.id);
  996. if(!hero)
  997. {
  998. // retreated or surrendered hero who has not been reset yet
  999. for(auto& hp : gs->hpool.heroesPool)
  1000. {
  1001. if(hp.second->id == h.id)
  1002. {
  1003. hero = hp.second;
  1004. break;
  1005. }
  1006. }
  1007. }
  1008. if(!hero)
  1009. {
  1010. logGlobal->error("Hero %d not found in NewTurn::applyGs", h.id.getNum());
  1011. continue;
  1012. }
  1013. hero->movement = h.move;
  1014. hero->mana = h.mana;
  1015. }
  1016. for(auto i = res.cbegin(); i != res.cend(); i++)
  1017. {
  1018. assert(i->first < PlayerColor::PLAYER_LIMIT);
  1019. gs->getPlayer(i->first)->resources = i->second;
  1020. }
  1021. for(auto creatureSet : cres) //set available creatures in towns
  1022. creatureSet.second.applyGs(gs);
  1023. for(CGTownInstance* t : gs->map->towns)
  1024. t->builded = 0;
  1025. if(gs->getDate(Date::DAY_OF_WEEK) == 1)
  1026. gs->updateRumor();
  1027. //count days without town for all players, regardless of their turn order
  1028. for (auto &p : gs->players)
  1029. {
  1030. PlayerState & playerState = p.second;
  1031. if (playerState.status == EPlayerStatus::INGAME)
  1032. {
  1033. if (playerState.towns.empty())
  1034. {
  1035. if (playerState.daysWithoutCastle)
  1036. ++(*playerState.daysWithoutCastle);
  1037. else
  1038. playerState.daysWithoutCastle = boost::make_optional(0);
  1039. }
  1040. else
  1041. {
  1042. playerState.daysWithoutCastle = boost::none;
  1043. }
  1044. }
  1045. }
  1046. }
  1047. DLL_LINKAGE void SetObjectProperty::applyGs(CGameState *gs)
  1048. {
  1049. CGObjectInstance *obj = gs->getObjInstance(id);
  1050. if(!obj)
  1051. {
  1052. logNetwork->error("Wrong object ID - property cannot be set!");
  1053. return;
  1054. }
  1055. CArmedInstance *cai = dynamic_cast<CArmedInstance *>(obj);
  1056. if(what == ObjProperty::OWNER && cai)
  1057. {
  1058. if(obj->ID == Obj::TOWN)
  1059. {
  1060. CGTownInstance *t = static_cast<CGTownInstance*>(obj);
  1061. if(t->tempOwner < PlayerColor::PLAYER_LIMIT)
  1062. gs->getPlayer(t->tempOwner)->towns -= t;
  1063. if(val < PlayerColor::PLAYER_LIMIT_I)
  1064. {
  1065. PlayerState * p = gs->getPlayer(PlayerColor(val));
  1066. p->towns.push_back(t);
  1067. //reset counter before NewTurn to avoid no town message if game loaded at turn when one already captured
  1068. if(p->daysWithoutCastle)
  1069. p->daysWithoutCastle = boost::none;
  1070. }
  1071. }
  1072. CBonusSystemNode *nodeToMove = cai->whatShouldBeAttached();
  1073. nodeToMove->detachFrom(cai->whereShouldBeAttached(gs));
  1074. obj->setProperty(what,val);
  1075. nodeToMove->attachTo(cai->whereShouldBeAttached(gs));
  1076. }
  1077. else //not an armed instance
  1078. {
  1079. obj->setProperty(what,val);
  1080. }
  1081. }
  1082. DLL_LINKAGE void PrepareHeroLevelUp::applyGs(CGameState * gs)
  1083. {
  1084. auto hero = gs->getHero(heroId);
  1085. assert(hero);
  1086. auto proposedSkills = hero->getLevelUpProposedSecondarySkills();
  1087. if(skills.size() == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  1088. {
  1089. skills.push_back(*RandomGeneratorUtil::nextItem(proposedSkills, hero->skillsInfo.rand));
  1090. }
  1091. else
  1092. {
  1093. skills = proposedSkills;
  1094. }
  1095. }
  1096. DLL_LINKAGE void HeroLevelUp::applyGs(CGameState * gs)
  1097. {
  1098. auto hero = gs->getHero(heroId);
  1099. assert(hero);
  1100. hero->levelUp(skills);
  1101. }
  1102. DLL_LINKAGE void CommanderLevelUp::applyGs(CGameState * gs)
  1103. {
  1104. auto hero = gs->getHero(heroId);
  1105. assert(hero);
  1106. auto commander = hero->commander;
  1107. assert(commander);
  1108. commander->levelUp();
  1109. }
  1110. DLL_LINKAGE void BattleStart::applyGs(CGameState *gs)
  1111. {
  1112. gs->curB = info;
  1113. gs->curB->localInit();
  1114. }
  1115. DLL_LINKAGE void BattleNextRound::applyGs(CGameState *gs)
  1116. {
  1117. gs->curB->nextRound(round);
  1118. }
  1119. DLL_LINKAGE void BattleSetActiveStack::applyGs(CGameState *gs)
  1120. {
  1121. gs->curB->nextTurn(stack);
  1122. }
  1123. DLL_LINKAGE void BattleTriggerEffect::applyGs(CGameState *gs)
  1124. {
  1125. CStack * st = gs->curB->getStack(stackID);
  1126. assert(st);
  1127. switch(effect)
  1128. {
  1129. case Bonus::HP_REGENERATION:
  1130. {
  1131. int64_t toHeal = val;
  1132. st->heal(toHeal, EHealLevel::HEAL, EHealPower::PERMANENT);
  1133. break;
  1134. }
  1135. case Bonus::MANA_DRAIN:
  1136. {
  1137. CGHeroInstance * h = gs->getHero(ObjectInstanceID(additionalInfo));
  1138. st->drainedMana = true;
  1139. h->mana -= val;
  1140. vstd::amax(h->mana, 0);
  1141. break;
  1142. }
  1143. case Bonus::POISON:
  1144. {
  1145. auto b = st->getBonusLocalFirst(Selector::source(Bonus::SPELL_EFFECT, SpellID::POISON)
  1146. .And(Selector::type(Bonus::STACK_HEALTH)));
  1147. if (b)
  1148. b->val = val;
  1149. break;
  1150. }
  1151. case Bonus::ENCHANTER:
  1152. break;
  1153. case Bonus::FEAR:
  1154. st->fear = true;
  1155. break;
  1156. default:
  1157. logNetwork->error("Unrecognized trigger effect type %d", effect);
  1158. }
  1159. }
  1160. DLL_LINKAGE void BattleUpdateGateState::applyGs(CGameState *gs)
  1161. {
  1162. if(gs->curB)
  1163. gs->curB->si.gateState = state;
  1164. }
  1165. void BattleResult::applyGs(CGameState *gs)
  1166. {
  1167. for (auto & elem : gs->curB->stacks)
  1168. delete elem;
  1169. for(int i = 0; i < 2; ++i)
  1170. {
  1171. if(auto h = gs->curB->battleGetFightingHero(i))
  1172. {
  1173. h->removeBonusesRecursive(Bonus::OneBattle); //remove any "until next battle" bonuses
  1174. if (h->commander && h->commander->alive)
  1175. {
  1176. for (auto art : h->commander->artifactsWorn) //increment bonuses for commander artifacts
  1177. {
  1178. art.second.artifact->artType->levelUpArtifact (art.second.artifact);
  1179. }
  1180. }
  1181. }
  1182. }
  1183. if(VLC->modh->modules.STACK_EXP)
  1184. {
  1185. for(int i = 0; i < 2; i++)
  1186. if(exp[i])
  1187. gs->curB->battleGetArmyObject(i)->giveStackExp(exp[i]);
  1188. CBonusSystemNode::treeHasChanged();
  1189. }
  1190. for(int i = 0; i < 2; i++)
  1191. gs->curB->battleGetArmyObject(i)->battle = nullptr;
  1192. gs->curB.dellNull();
  1193. }
  1194. DLL_LINKAGE void BattleStackMoved::applyGs(CGameState *gs)
  1195. {
  1196. applyBattle(gs->curB);
  1197. }
  1198. DLL_LINKAGE void BattleStackMoved::applyBattle(IBattleState * battleState)
  1199. {
  1200. battleState->moveUnit(stack, tilesToMove.back());
  1201. }
  1202. DLL_LINKAGE void BattleStackAttacked::applyGs(CGameState * gs)
  1203. {
  1204. applyBattle(gs->curB);
  1205. }
  1206. DLL_LINKAGE void BattleStackAttacked::applyBattle(IBattleState * battleState)
  1207. {
  1208. battleState->setUnitState(newState.id, newState.data, newState.healthDelta);
  1209. }
  1210. DLL_LINKAGE void BattleAttack::applyGs(CGameState * gs)
  1211. {
  1212. CStack * attacker = gs->curB->getStack(stackAttacking);
  1213. assert(attacker);
  1214. attackerChanges.applyGs(gs);
  1215. for(BattleStackAttacked & stackAttacked : bsa)
  1216. stackAttacked.applyGs(gs);
  1217. attacker->removeBonusesRecursive(Bonus::UntilAttack);
  1218. }
  1219. DLL_LINKAGE void StartAction::applyGs(CGameState *gs)
  1220. {
  1221. CStack *st = gs->curB->getStack(ba.stackNumber);
  1222. if(ba.actionType == EActionType::END_TACTIC_PHASE)
  1223. {
  1224. gs->curB->tacticDistance = 0;
  1225. return;
  1226. }
  1227. if(gs->curB->tacticDistance)
  1228. {
  1229. // moves in tactics phase do not affect creature status
  1230. // (tactics stack queue is managed by client)
  1231. return;
  1232. }
  1233. if(ba.actionType != EActionType::HERO_SPELL) //don't check for stack if it's custom action by hero
  1234. {
  1235. assert(st);
  1236. }
  1237. else
  1238. {
  1239. gs->curB->sides[ba.side].usedSpellsHistory.push_back(SpellID(ba.actionSubtype).toSpell());
  1240. }
  1241. switch(ba.actionType)
  1242. {
  1243. case EActionType::DEFEND:
  1244. st->waiting = false;
  1245. st->defending = true;
  1246. st->defendingAnim = true;
  1247. break;
  1248. case EActionType::WAIT:
  1249. st->defendingAnim = false;
  1250. st->waiting = true;
  1251. break;
  1252. case EActionType::HERO_SPELL: //no change in current stack state
  1253. break;
  1254. default: //any active stack action - attack, catapult, heal, spell...
  1255. st->waiting = false;
  1256. st->defendingAnim = false;
  1257. st->movedThisRound = true;
  1258. break;
  1259. }
  1260. }
  1261. DLL_LINKAGE void BattleSpellCast::applyGs(CGameState *gs)
  1262. {
  1263. assert(gs->curB);
  1264. if(castByHero)
  1265. {
  1266. if(side < 2)
  1267. {
  1268. gs->curB->sides[side].castSpellsCount++;
  1269. }
  1270. }
  1271. }
  1272. DLL_LINKAGE void SetStackEffect::applyGs(CGameState *gs)
  1273. {
  1274. applyBattle(gs->curB);
  1275. }
  1276. DLL_LINKAGE void SetStackEffect::applyBattle(IBattleState * battleState)
  1277. {
  1278. for(const auto & stackData : toRemove)
  1279. battleState->removeUnitBonus(stackData.first, stackData.second);
  1280. for(const auto & stackData : toUpdate)
  1281. battleState->updateUnitBonus(stackData.first, stackData.second);
  1282. for(const auto & stackData : toAdd)
  1283. battleState->addUnitBonus(stackData.first, stackData.second);
  1284. }
  1285. DLL_LINKAGE void StacksInjured::applyGs(CGameState *gs)
  1286. {
  1287. applyBattle(gs->curB);
  1288. }
  1289. DLL_LINKAGE void StacksInjured::applyBattle(IBattleState * battleState)
  1290. {
  1291. for(BattleStackAttacked stackAttacked : stacks)
  1292. stackAttacked.applyBattle(battleState);
  1293. }
  1294. DLL_LINKAGE void BattleUnitsChanged::applyGs(CGameState *gs)
  1295. {
  1296. applyBattle(gs->curB);
  1297. }
  1298. DLL_LINKAGE void BattleUnitsChanged::applyBattle(IBattleState * battleState)
  1299. {
  1300. for(auto & elem : changedStacks)
  1301. {
  1302. switch(elem.operation)
  1303. {
  1304. case BattleChanges::EOperation::RESET_STATE:
  1305. battleState->setUnitState(elem.id, elem.data, elem.healthDelta);
  1306. break;
  1307. case BattleChanges::EOperation::REMOVE:
  1308. battleState->removeUnit(elem.id);
  1309. break;
  1310. case BattleChanges::EOperation::ADD:
  1311. battleState->addUnit(elem.id, elem.data);
  1312. break;
  1313. default:
  1314. logNetwork->error("Unknown unit operation %d", (int)elem.operation);
  1315. break;
  1316. }
  1317. }
  1318. }
  1319. DLL_LINKAGE void BattleObstaclesChanged::applyGs(CGameState * gs)
  1320. {
  1321. if(gs->curB)
  1322. applyBattle(gs->curB);
  1323. }
  1324. DLL_LINKAGE void BattleObstaclesChanged::applyBattle(IBattleState * battleState)
  1325. {
  1326. for(const auto & change : changes)
  1327. {
  1328. switch(change.operation)
  1329. {
  1330. case BattleChanges::EOperation::REMOVE:
  1331. battleState->removeObstacle(change.id);
  1332. break;
  1333. case BattleChanges::EOperation::ADD:
  1334. battleState->addObstacle(change);
  1335. break;
  1336. default:
  1337. logNetwork->error("Unknown obstacle operation %d", (int)change.operation);
  1338. break;
  1339. }
  1340. }
  1341. }
  1342. DLL_LINKAGE CatapultAttack::CatapultAttack()
  1343. {
  1344. attacker = -1;
  1345. }
  1346. DLL_LINKAGE CatapultAttack::~CatapultAttack()
  1347. {
  1348. }
  1349. DLL_LINKAGE void CatapultAttack::applyGs(CGameState * gs)
  1350. {
  1351. if(gs->curB)
  1352. applyBattle(gs->curB);
  1353. }
  1354. DLL_LINKAGE void CatapultAttack::applyBattle(IBattleState * battleState)
  1355. {
  1356. auto town = battleState->getDefendedTown();
  1357. if(!town)
  1358. return;
  1359. if(town->fortLevel() == CGTownInstance::NONE)
  1360. return;
  1361. for(const auto & part : attackedParts)
  1362. {
  1363. auto newWallState = SiegeInfo::applyDamage(EWallState::EWallState(battleState->getWallState(part.attackedPart)), part.damageDealt);
  1364. battleState->setWallState(part.attackedPart, newWallState);
  1365. }
  1366. }
  1367. DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState * gs)
  1368. {
  1369. CStack * stack = gs->curB->getStack(stackID);
  1370. switch(which)
  1371. {
  1372. case CASTS:
  1373. {
  1374. if(absolute)
  1375. logNetwork->error("Can not change casts in absolute mode");
  1376. else
  1377. stack->casts.use(-val);
  1378. break;
  1379. }
  1380. case ENCHANTER_COUNTER:
  1381. {
  1382. auto & counter = gs->curB->sides[gs->curB->whatSide(stack->owner)].enchanterCounter;
  1383. if(absolute)
  1384. counter = val;
  1385. else
  1386. counter += val;
  1387. vstd::amax(counter, 0);
  1388. break;
  1389. }
  1390. case UNBIND:
  1391. {
  1392. stack->removeBonusesRecursive(Selector::type(Bonus::BIND_EFFECT));
  1393. break;
  1394. }
  1395. case CLONED:
  1396. {
  1397. stack->cloned = true;
  1398. break;
  1399. }
  1400. case HAS_CLONE:
  1401. {
  1402. stack->cloneID = val;
  1403. break;
  1404. }
  1405. }
  1406. }
  1407. DLL_LINKAGE void PlayerCheated::applyGs(CGameState *gs)
  1408. {
  1409. if(!player.isValidPlayer())
  1410. return;
  1411. gs->getPlayer(player)->enteredLosingCheatCode = losingCheatCode;
  1412. gs->getPlayer(player)->enteredWinningCheatCode = winningCheatCode;
  1413. }
  1414. DLL_LINKAGE void YourTurn::applyGs(CGameState *gs)
  1415. {
  1416. gs->currentPlayer = player;
  1417. auto & playerState = gs->players[player];
  1418. playerState.daysWithoutCastle = daysWithoutCastle;
  1419. }
  1420. DLL_LINKAGE Component::Component(const CStackBasicDescriptor &stack)
  1421. : id(CREATURE), subtype(stack.type->idNumber), val(stack.count), when(0)
  1422. {
  1423. }