NetPacksLib.cpp 43 KB

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