NetPacksLib.cpp 44 KB

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