NetPacksLib.cpp 43 KB

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