NetPacksLib.cpp 43 KB

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