NetPacksLib.cpp 43 KB

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