NetPacksLib.cpp 43 KB

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