CGameHandler.cpp 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254
  1. /*
  2. * CGameHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CGameHandler.h"
  12. #include "CVCMIServer.h"
  13. #include "ServerNetPackVisitors.h"
  14. #include "ServerSpellCastEnvironment.h"
  15. #include "battles/BattleProcessor.h"
  16. #include "processors/HeroPoolProcessor.h"
  17. #include "processors/PlayerMessageProcessor.h"
  18. #include "queries/QueriesProcessor.h"
  19. #include "queries/MapQueries.h"
  20. #include "../lib/ArtifactUtils.h"
  21. #include "../lib/CArtHandler.h"
  22. #include "../lib/CBuildingHandler.h"
  23. #include "../lib/CCreatureHandler.h"
  24. #include "../lib/CCreatureSet.h"
  25. #include "../lib/CGeneralTextHandler.h"
  26. #include "../lib/CHeroHandler.h"
  27. #include "../lib/CSoundBase.h"
  28. #include "../lib/CThreadHelper.h"
  29. #include "../lib/CTownHandler.h"
  30. #include "../lib/GameConstants.h"
  31. #include "../lib/UnlockGuard.h"
  32. #include "../lib/GameSettings.h"
  33. #include "../lib/ScriptHandler.h"
  34. #include "../lib/StartInfo.h"
  35. #include "../lib/TerrainHandler.h"
  36. #include "../lib/VCMIDirs.h"
  37. #include "../lib/VCMI_Lib.h"
  38. #include "../lib/int3.h"
  39. #include "../lib/filesystem/FileInfo.h"
  40. #include "../lib/filesystem/Filesystem.h"
  41. #include "../lib/gameState/CGameState.h"
  42. #include "../lib/mapping/CMap.h"
  43. #include "../lib/mapping/CMapService.h"
  44. #include "../lib/modding/ModIncompatibility.h"
  45. #include "../lib/pathfinder/CPathfinder.h"
  46. #include "../lib/pathfinder/PathfinderOptions.h"
  47. #include "../lib/pathfinder/TurnInfo.h"
  48. #include "../lib/registerTypes/RegisterTypes.h"
  49. #include "../lib/rmg/CMapGenOptions.h"
  50. #include "../lib/serializer/CTypeList.h"
  51. #include "../lib/serializer/Cast.h"
  52. #include "../lib/serializer/Connection.h"
  53. #include "../lib/serializer/JsonSerializer.h"
  54. #include "../lib/spells/CSpellHandler.h"
  55. #include "vstd/CLoggerBase.h"
  56. #include <vcmi/events/EventBus.h>
  57. #include <vcmi/events/GenericEvents.h>
  58. #include <vcmi/events/AdventureEvents.h>
  59. #define COMPLAIN_RET_IF(cond, txt) do {if (cond){complain(txt); return;}} while(0)
  60. #define COMPLAIN_RET_FALSE_IF(cond, txt) do {if (cond){complain(txt); return false;}} while(0)
  61. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  62. #define COMPLAIN_RETF(txt, FORMAT) {complain(boost::str(boost::format(txt) % FORMAT)); return false;}
  63. template <typename T> class CApplyOnGH;
  64. class CBaseForGHApply
  65. {
  66. public:
  67. virtual bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const =0;
  68. virtual ~CBaseForGHApply(){}
  69. template<typename U> static CBaseForGHApply *getApplier(const U * t=nullptr)
  70. {
  71. return new CApplyOnGH<U>();
  72. }
  73. };
  74. template <typename T> class CApplyOnGH : public CBaseForGHApply
  75. {
  76. public:
  77. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  78. {
  79. T *ptr = static_cast<T*>(pack);
  80. try
  81. {
  82. ApplyGhNetPackVisitor applier(*gh, *gs);
  83. ptr->visit(applier);
  84. return applier.getResult();
  85. }
  86. catch(ExceptionNotAllowedAction & e)
  87. {
  88. (void)e;
  89. return false;
  90. }
  91. }
  92. };
  93. template <>
  94. class CApplyOnGH<CPack> : public CBaseForGHApply
  95. {
  96. public:
  97. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  98. {
  99. logGlobal->error("Cannot apply on GH plain CPack!");
  100. assert(0);
  101. return false;
  102. }
  103. };
  104. static inline double distance(int3 a, int3 b)
  105. {
  106. return std::sqrt((double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
  107. }
  108. PlayerStatus PlayerStatuses::operator[](PlayerColor player)
  109. {
  110. boost::unique_lock<boost::mutex> l(mx);
  111. if (players.find(player) != players.end())
  112. {
  113. return players.at(player);
  114. }
  115. else
  116. {
  117. throw std::runtime_error("No such player!");
  118. }
  119. }
  120. void PlayerStatuses::addPlayer(PlayerColor player)
  121. {
  122. boost::unique_lock<boost::mutex> l(mx);
  123. players[player];
  124. }
  125. bool PlayerStatuses::checkFlag(PlayerColor player, bool PlayerStatus::*flag)
  126. {
  127. boost::unique_lock<boost::mutex> l(mx);
  128. if (players.find(player) != players.end())
  129. {
  130. return players[player].*flag;
  131. }
  132. else
  133. {
  134. throw std::runtime_error("No such player!");
  135. }
  136. }
  137. void PlayerStatuses::setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val)
  138. {
  139. boost::unique_lock<boost::mutex> l(mx);
  140. if (players.find(player) != players.end())
  141. {
  142. players[player].*flag = val;
  143. }
  144. else
  145. {
  146. throw std::runtime_error("No such player!");
  147. }
  148. cv.notify_all();
  149. }
  150. template <typename T>
  151. void callWith(std::vector<T> args, std::function<void(T)> fun, ui32 which)
  152. {
  153. fun(args[which]);
  154. }
  155. const Services * CGameHandler::services() const
  156. {
  157. return VLC;
  158. }
  159. const CGameHandler::BattleCb * CGameHandler::battle() const
  160. {
  161. return this;
  162. }
  163. const CGameHandler::GameCb * CGameHandler::game() const
  164. {
  165. return this;
  166. }
  167. vstd::CLoggerBase * CGameHandler::logger() const
  168. {
  169. return logGlobal;
  170. }
  171. events::EventBus * CGameHandler::eventBus() const
  172. {
  173. return serverEventBus.get();
  174. }
  175. CVCMIServer * CGameHandler::gameLobby() const
  176. {
  177. return lobby;
  178. }
  179. void CGameHandler::levelUpHero(const CGHeroInstance * hero, SecondarySkill skill)
  180. {
  181. changeSecSkill(hero, skill, 1, 0);
  182. expGiven(hero);
  183. }
  184. void CGameHandler::levelUpHero(const CGHeroInstance * hero)
  185. {
  186. // required exp for at least 1 lvl-up hasn't been reached
  187. if (!hero->gainsLevel())
  188. {
  189. return;
  190. }
  191. // give primary skill
  192. logGlobal->trace("%s got level %d", hero->getNameTranslated(), hero->level);
  193. auto primarySkill = hero->nextPrimarySkill(getRandomGenerator());
  194. SetPrimSkill sps;
  195. sps.id = hero->id;
  196. sps.which = primarySkill;
  197. sps.abs = false;
  198. sps.val = 1;
  199. sendAndApply(&sps);
  200. PrepareHeroLevelUp pre;
  201. pre.heroId = hero->id;
  202. sendAndApply(&pre);
  203. HeroLevelUp hlu;
  204. hlu.player = hero->tempOwner;
  205. hlu.heroId = hero->id;
  206. hlu.primskill = primarySkill;
  207. hlu.skills = pre.skills;
  208. if (hlu.skills.size() == 0)
  209. {
  210. sendAndApply(&hlu);
  211. levelUpHero(hero);
  212. }
  213. else if (hlu.skills.size() == 1)
  214. {
  215. sendAndApply(&hlu);
  216. levelUpHero(hero, pre.skills.front());
  217. }
  218. else if (hlu.skills.size() > 1)
  219. {
  220. auto levelUpQuery = std::make_shared<CHeroLevelUpDialogQuery>(this, hlu, hero);
  221. hlu.queryID = levelUpQuery->queryID;
  222. queries->addQuery(levelUpQuery);
  223. sendAndApply(&hlu);
  224. //level up will be called on query reply
  225. }
  226. }
  227. void CGameHandler::levelUpCommander (const CCommanderInstance * c, int skill)
  228. {
  229. SetCommanderProperty scp;
  230. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  231. if (hero)
  232. scp.heroid = hero->id;
  233. else
  234. {
  235. complain ("Commander is not led by hero!");
  236. return;
  237. }
  238. scp.accumulatedBonus.subtype = 0;
  239. scp.accumulatedBonus.additionalInfo = 0;
  240. scp.accumulatedBonus.duration = BonusDuration::PERMANENT;
  241. scp.accumulatedBonus.turnsRemain = 0;
  242. scp.accumulatedBonus.source = BonusSource::COMMANDER;
  243. scp.accumulatedBonus.valType = BonusValueType::BASE_NUMBER;
  244. if (skill <= ECommander::SPELL_POWER)
  245. {
  246. scp.which = SetCommanderProperty::BONUS;
  247. auto difference = [](std::vector< std::vector <ui8> > skillLevels, std::vector <ui8> secondarySkills, int skill)->int
  248. {
  249. int s = std::min (skill, (int)ECommander::SPELL_POWER); //spell power level controls also casts and resistance
  250. return skillLevels.at(skill).at(secondarySkills.at(s)) - (secondarySkills.at(s) ? skillLevels.at(skill).at(secondarySkills.at(s)-1) : 0);
  251. };
  252. switch (skill)
  253. {
  254. case ECommander::ATTACK:
  255. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  256. scp.accumulatedBonus.subtype = PrimarySkill::ATTACK;
  257. break;
  258. case ECommander::DEFENSE:
  259. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  260. scp.accumulatedBonus.subtype = PrimarySkill::DEFENSE;
  261. break;
  262. case ECommander::HEALTH:
  263. scp.accumulatedBonus.type = BonusType::STACK_HEALTH;
  264. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  265. break;
  266. case ECommander::DAMAGE:
  267. scp.accumulatedBonus.type = BonusType::CREATURE_DAMAGE;
  268. scp.accumulatedBonus.subtype = 0;
  269. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  270. break;
  271. case ECommander::SPEED:
  272. scp.accumulatedBonus.type = BonusType::STACKS_SPEED;
  273. break;
  274. case ECommander::SPELL_POWER:
  275. scp.accumulatedBonus.type = BonusType::MAGIC_RESISTANCE;
  276. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::RESISTANCE);
  277. sendAndApply (&scp); //additional pack
  278. scp.accumulatedBonus.type = BonusType::CREATURE_SPELL_POWER;
  279. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::SPELL_POWER) * 100; //like hero with spellpower = ability level
  280. sendAndApply (&scp); //additional pack
  281. scp.accumulatedBonus.type = BonusType::CASTS;
  282. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::CASTS);
  283. sendAndApply (&scp); //additional pack
  284. scp.accumulatedBonus.type = BonusType::CREATURE_ENCHANT_POWER; //send normally
  285. break;
  286. }
  287. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, skill);
  288. sendAndApply (&scp);
  289. scp.which = SetCommanderProperty::SECONDARY_SKILL;
  290. scp.additionalInfo = skill;
  291. scp.amount = c->secondarySkills.at(skill) + 1;
  292. sendAndApply (&scp);
  293. }
  294. else if (skill >= 100)
  295. {
  296. scp.which = SetCommanderProperty::SPECIAL_SKILL;
  297. scp.accumulatedBonus = *VLC->creh->skillRequirements.at(skill-100).first;
  298. scp.additionalInfo = skill; //unnormalized
  299. sendAndApply (&scp);
  300. }
  301. expGiven(hero);
  302. }
  303. void CGameHandler::levelUpCommander(const CCommanderInstance * c)
  304. {
  305. if (!c->gainsLevel())
  306. {
  307. return;
  308. }
  309. CommanderLevelUp clu;
  310. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  311. if(hero)
  312. {
  313. clu.heroId = hero->id;
  314. clu.player = hero->tempOwner;
  315. }
  316. else
  317. {
  318. complain ("Commander is not led by hero!");
  319. return;
  320. }
  321. //picking sec. skills for choice
  322. for (int i = 0; i <= ECommander::SPELL_POWER; ++i)
  323. {
  324. if (c->secondarySkills.at(i) < ECommander::MAX_SKILL_LEVEL)
  325. clu.skills.push_back(i);
  326. }
  327. int i = 100;
  328. for (auto specialSkill : VLC->creh->skillRequirements)
  329. {
  330. if (c->secondarySkills.at(specialSkill.second.first) == ECommander::MAX_SKILL_LEVEL
  331. && c->secondarySkills.at(specialSkill.second.second) == ECommander::MAX_SKILL_LEVEL
  332. && !vstd::contains (c->specialSKills, i))
  333. clu.skills.push_back (i);
  334. ++i;
  335. }
  336. int skillAmount = static_cast<int>(clu.skills.size());
  337. if (!skillAmount)
  338. {
  339. sendAndApply(&clu);
  340. levelUpCommander(c);
  341. }
  342. else if (skillAmount == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  343. {
  344. sendAndApply(&clu);
  345. levelUpCommander(c, *RandomGeneratorUtil::nextItem(clu.skills, getRandomGenerator()));
  346. }
  347. else if (skillAmount > 1) //apply and ask for secondary skill
  348. {
  349. auto commanderLevelUp = std::make_shared<CCommanderLevelUpDialogQuery>(this, clu, hero);
  350. clu.queryID = commanderLevelUp->queryID;
  351. queries->addQuery(commanderLevelUp);
  352. sendAndApply(&clu);
  353. }
  354. }
  355. void CGameHandler::expGiven(const CGHeroInstance *hero)
  356. {
  357. if (hero->gainsLevel())
  358. levelUpHero(hero);
  359. else if (hero->commander && hero->commander->gainsLevel())
  360. levelUpCommander(hero->commander);
  361. //if (hero->commander && hero->level > hero->commander->level && hero->commander->gainsLevel())
  362. // levelUpCommander(hero->commander);
  363. // else
  364. // levelUpHero(hero);
  365. }
  366. void CGameHandler::changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs)
  367. {
  368. if (which == PrimarySkill::EXPERIENCE) // Check if scenario limit reached
  369. {
  370. if (gs->map->levelLimit != 0)
  371. {
  372. TExpType expLimit = VLC->heroh->reqExp(gs->map->levelLimit);
  373. TExpType resultingExp = abs ? val : hero->exp + val;
  374. if (resultingExp > expLimit)
  375. {
  376. // set given experience to max possible, but don't decrease if hero already over top
  377. abs = true;
  378. val = std::max(expLimit, hero->exp);
  379. InfoWindow iw;
  380. iw.player = hero->tempOwner;
  381. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 1); //can gain no more XP
  382. iw.text.replaceRawString(hero->getNameTranslated());
  383. sendAndApply(&iw);
  384. }
  385. }
  386. }
  387. SetPrimSkill sps;
  388. sps.id = hero->id;
  389. sps.which = which;
  390. sps.abs = abs;
  391. sps.val = val;
  392. sendAndApply(&sps);
  393. //only for exp - hero may level up
  394. if (which == PrimarySkill::EXPERIENCE)
  395. {
  396. if (hero->commander && hero->commander->alive)
  397. {
  398. //FIXME: trim experience according to map limit?
  399. SetCommanderProperty scp;
  400. scp.heroid = hero->id;
  401. scp.which = SetCommanderProperty::EXPERIENCE;
  402. scp.amount = val;
  403. sendAndApply (&scp);
  404. CBonusSystemNode::treeHasChanged();
  405. }
  406. expGiven(hero);
  407. }
  408. }
  409. void CGameHandler::changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs)
  410. {
  411. if(!hero)
  412. {
  413. logGlobal->error("changeSecSkill provided no hero");
  414. return;
  415. }
  416. SetSecSkill sss;
  417. sss.id = hero->id;
  418. sss.which = which;
  419. sss.val = val;
  420. sss.abs = abs;
  421. sendAndApply(&sss);
  422. if (hero->visitedTown)
  423. giveSpells(hero->visitedTown, hero);
  424. }
  425. void CGameHandler::handleClientDisconnection(std::shared_ptr<CConnection> c)
  426. {
  427. if(lobby->state == EServerState::SHUTDOWN || !gs || !gs->scenarioOps)
  428. return;
  429. for(auto & playerConnections : connections)
  430. {
  431. PlayerColor playerId = playerConnections.first;
  432. auto * playerSettings = gs->scenarioOps->getPlayersSettings(playerId.getNum());
  433. if(!playerSettings)
  434. continue;
  435. auto playerConnection = vstd::find(playerConnections.second, c);
  436. if(playerConnection != playerConnections.second.end())
  437. {
  438. std::string messageText = boost::str(boost::format("%s (cid %d) was disconnected") % playerSettings->name % c->connectionID);
  439. playerMessages->broadcastMessage(playerId, messageText);
  440. }
  441. }
  442. }
  443. void CGameHandler::handleReceivedPack(CPackForServer * pack)
  444. {
  445. //prepare struct informing that action was applied
  446. auto sendPackageResponse = [&](bool succesfullyApplied)
  447. {
  448. PackageApplied applied;
  449. applied.player = pack->player;
  450. applied.result = succesfullyApplied;
  451. applied.packType = typeList.getTypeID(pack);
  452. applied.requestID = pack->requestID;
  453. pack->c->sendPack(&applied);
  454. };
  455. CBaseForGHApply * apply = applier->getApplier(typeList.getTypeID(pack)); //and appropriate applier object
  456. if(isBlockedByQueries(pack, pack->player))
  457. {
  458. sendPackageResponse(false);
  459. }
  460. else if(apply)
  461. {
  462. const bool result = apply->applyOnGH(this, this->gs, pack);
  463. if(result)
  464. logGlobal->trace("Message %s successfully applied!", typeid(*pack).name());
  465. else
  466. complain((boost::format("Got false in applying %s... that request must have been fishy!")
  467. % typeid(*pack).name()).str());
  468. sendPackageResponse(true);
  469. }
  470. else
  471. {
  472. logGlobal->error("Message cannot be applied, cannot find applier (unregistered type)!");
  473. sendPackageResponse(false);
  474. }
  475. vstd::clear_pointer(pack);
  476. }
  477. CGameHandler::CGameHandler()
  478. : turnTimerHandler(*this)
  479. {}
  480. CGameHandler::CGameHandler(CVCMIServer * lobby)
  481. : lobby(lobby)
  482. , heroPool(std::make_unique<HeroPoolProcessor>(this))
  483. , battles(std::make_unique<BattleProcessor>(this))
  484. , queries(std::make_unique<QueriesProcessor>())
  485. , playerMessages(std::make_unique<PlayerMessageProcessor>(this))
  486. , complainNoCreatures("No creatures to split")
  487. , complainNotEnoughCreatures("Cannot split that stack, not enough creatures!")
  488. , complainInvalidSlot("Invalid slot accessed!")
  489. , turnTimerHandler(*this)
  490. {
  491. QID = 1;
  492. IObjectInterface::cb = this;
  493. applier = std::make_shared<CApplier<CBaseForGHApply>>();
  494. registerTypesServerPacks(*applier);
  495. spellEnv = new ServerSpellCastEnvironment(this);
  496. }
  497. CGameHandler::~CGameHandler()
  498. {
  499. delete spellEnv;
  500. delete gs;
  501. }
  502. void CGameHandler::reinitScripting()
  503. {
  504. serverEventBus = std::make_unique<events::EventBus>();
  505. #if SCRIPTING_ENABLED
  506. serverScripts.reset(new scripting::PoolImpl(this, spellEnv));
  507. #endif
  508. }
  509. void CGameHandler::init(StartInfo *si, Load::ProgressAccumulator & progressTracking)
  510. {
  511. if (si->seedToBeUsed == 0)
  512. {
  513. si->seedToBeUsed = static_cast<ui32>(std::time(nullptr));
  514. }
  515. CMapService mapService;
  516. gs = new CGameState();
  517. gs->preInit(VLC);
  518. logGlobal->info("Gamestate created!");
  519. gs->init(&mapService, si, progressTracking);
  520. logGlobal->info("Gamestate initialized!");
  521. // reset seed, so that clients can't predict any following random values
  522. getRandomGenerator().resetSeed();
  523. for (auto & elem : gs->players)
  524. {
  525. states.addPlayer(elem.first);
  526. }
  527. reinitScripting();
  528. }
  529. static bool evntCmp(const CMapEvent &a, const CMapEvent &b)
  530. {
  531. return a.earlierThan(b);
  532. }
  533. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false, bool clear = false)
  534. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  535. const PlayerState * p = getPlayerState(town->tempOwner);
  536. if (!p)
  537. {
  538. assert(town->tempOwner == PlayerColor::NEUTRAL);
  539. return;
  540. }
  541. if (forced || town->creatures.at(GameConstants::CREATURES_PER_TOWN).second.empty())//we need to change creature
  542. {
  543. SetAvailableCreatures ssi;
  544. ssi.tid = town->id;
  545. ssi.creatures = town->creatures;
  546. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.clear();//remove old one
  547. const std::vector<ConstTransitivePtr<CGDwelling> > &dwellings = p->dwellings;
  548. if (dwellings.empty())//no dwellings - just remove
  549. {
  550. sendAndApply(&ssi);
  551. return;
  552. }
  553. auto dwelling = *RandomGeneratorUtil::nextItem(dwellings, getRandomGenerator());
  554. // for multi-creature dwellings like Golem Factory
  555. auto creatureId = RandomGeneratorUtil::nextItem(dwelling->creatures, getRandomGenerator())->second[0];
  556. if (clear)
  557. {
  558. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = std::max(1, (VLC->creh->objects.at(creatureId)->getGrowth())/2);
  559. }
  560. else
  561. {
  562. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = VLC->creh->objects.at(creatureId)->getGrowth();
  563. }
  564. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.push_back(creatureId);
  565. sendAndApply(&ssi);
  566. }
  567. }
  568. void CGameHandler::newTurn()
  569. {
  570. logGlobal->trace("Turn %d", gs->day+1);
  571. NewTurn n;
  572. n.specialWeek = NewTurn::NO_ACTION;
  573. n.creatureid = CreatureID::NONE;
  574. n.day = gs->day + 1;
  575. bool firstTurn = !getDate(Date::DAY);
  576. bool newWeek = getDate(Date::DAY_OF_WEEK) == 7; //day numbers are confusing, as day was not yet switched
  577. bool newMonth = getDate(Date::DAY_OF_MONTH) == 28;
  578. std::map<PlayerColor, si32> hadGold;//starting gold - for buildings like dwarven treasury
  579. if (firstTurn)
  580. {
  581. for (auto obj : gs->map->objects)
  582. {
  583. if (obj && obj->ID == Obj::PRISON) //give imprisoned hero 0 exp to level him up. easiest to do at this point
  584. {
  585. changePrimSkill (getHero(obj->id), PrimarySkill::EXPERIENCE, 0);
  586. }
  587. }
  588. }
  589. if (newWeek && !firstTurn)
  590. {
  591. n.specialWeek = NewTurn::NORMAL;
  592. bool deityOfFireBuilt = false;
  593. for (const CGTownInstance *t : gs->map->towns)
  594. {
  595. if (t->hasBuilt(BuildingID::GRAIL, ETownType::INFERNO))
  596. {
  597. deityOfFireBuilt = true;
  598. break;
  599. }
  600. }
  601. if (deityOfFireBuilt)
  602. {
  603. n.specialWeek = NewTurn::DEITYOFFIRE;
  604. n.creatureid = CreatureID::IMP;
  605. }
  606. else if(VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_RANDOM_SPECIAL_WEEKS))
  607. {
  608. int monthType = getRandomGenerator().nextInt(99);
  609. if (newMonth) //new month
  610. {
  611. if (monthType < 40) //double growth
  612. {
  613. n.specialWeek = NewTurn::DOUBLE_GROWTH;
  614. if (VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_ALL_FOR_DOUBLE_MONTH))
  615. {
  616. n.creatureid = VLC->creh->pickRandomMonster(getRandomGenerator());
  617. }
  618. else if (VLC->creh->doubledCreatures.size())
  619. {
  620. n.creatureid = *RandomGeneratorUtil::nextItem(VLC->creh->doubledCreatures, getRandomGenerator());
  621. }
  622. else
  623. {
  624. complain("Cannot find creature that can be spawned!");
  625. n.specialWeek = NewTurn::NORMAL;
  626. }
  627. }
  628. else if (monthType < 50)
  629. n.specialWeek = NewTurn::PLAGUE;
  630. }
  631. else //it's a week, but not full month
  632. {
  633. if (monthType < 25)
  634. {
  635. n.specialWeek = NewTurn::BONUS_GROWTH; //+5
  636. std::pair<int, CreatureID> newMonster(54, CreatureID());
  637. do
  638. {
  639. newMonster.second = VLC->creh->pickRandomMonster(getRandomGenerator());
  640. } while (VLC->creh->objects[newMonster.second] &&
  641. (*VLC->townh)[VLC->creatures()->getById(newMonster.second)->getFaction()]->town == nullptr); // find first non neutral creature
  642. n.creatureid = newMonster.second;
  643. }
  644. }
  645. }
  646. }
  647. for (auto & elem : gs->players)
  648. {
  649. if (elem.first == PlayerColor::NEUTRAL)
  650. continue;
  651. else if (elem.first >= PlayerColor::PLAYER_LIMIT)
  652. assert(0); //illegal player number!
  653. std::pair<PlayerColor, si32> playerGold(elem.first, elem.second.resources[EGameResID::GOLD]);
  654. hadGold.insert(playerGold);
  655. if (newWeek) //new heroes in tavern
  656. heroPool->onNewWeek(elem.first);
  657. n.res[elem.first] = elem.second.resources;
  658. if(!firstTurn && newWeek) //weekly crystal generation if 1 or more crystal dragons in any hero army or town garrison
  659. {
  660. bool hasCrystalGenCreature = false;
  661. for(CGHeroInstance * hero : elem.second.heroes)
  662. {
  663. for(auto stack : hero->stacks)
  664. {
  665. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  666. {
  667. hasCrystalGenCreature = true;
  668. break;
  669. }
  670. }
  671. }
  672. if(!hasCrystalGenCreature) //not found in armies, check towns
  673. {
  674. for(CGTownInstance * town : elem.second.towns)
  675. {
  676. for(auto stack : town->stacks)
  677. {
  678. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  679. {
  680. hasCrystalGenCreature = true;
  681. break;
  682. }
  683. }
  684. }
  685. }
  686. if(hasCrystalGenCreature)
  687. n.res[elem.first][EGameResID::CRYSTAL] += 3;
  688. }
  689. for (CGHeroInstance *h : (elem).second.heroes)
  690. {
  691. if (h->visitedTown)
  692. giveSpells(h->visitedTown, h);
  693. NewTurn::Hero hth;
  694. hth.id = h->id;
  695. auto ti = std::make_unique<TurnInfo>(h, 1);
  696. // TODO: this code executed when bonuses of previous day not yet updated (this happen in NewTurn::applyGs). See issue 2356
  697. hth.move = h->movementPointsLimitCached(gs->map->getTile(h->visitablePos()).terType->isLand(), ti.get());
  698. hth.mana = h->getManaNewTurn();
  699. n.heroes.insert(hth);
  700. if (!firstTurn) //not first day
  701. {
  702. for (int k = 0; k < GameConstants::RESOURCE_QUANTITY; k++)
  703. {
  704. n.res[elem.first][k] += h->valOfBonuses(BonusType::GENERATE_RESOURCE, k);
  705. }
  706. }
  707. }
  708. }
  709. for (CGTownInstance *t : gs->map->towns)
  710. {
  711. PlayerColor player = t->tempOwner;
  712. handleTownEvents(t, n);
  713. if (newWeek) //first day of week
  714. {
  715. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  716. setPortalDwelling(t, true, (n.specialWeek == NewTurn::PLAGUE ? true : false)); //set creatures for Portal of Summoning
  717. if (!firstTurn)
  718. if (t->hasBuilt(BuildingSubID::TREASURY) && player < PlayerColor::PLAYER_LIMIT)
  719. n.res[player][EGameResID::GOLD] += hadGold.at(player)/10; //give 10% of starting gold
  720. if (!vstd::contains(n.cres, t->id))
  721. {
  722. n.cres[t->id].tid = t->id;
  723. n.cres[t->id].creatures = t->creatures;
  724. }
  725. auto & sac = n.cres.at(t->id);
  726. for (int k=0; k < GameConstants::CREATURES_PER_TOWN; k++) //creature growths
  727. {
  728. if (!t->creatures.at(k).second.empty()) // there are creatures at this level
  729. {
  730. ui32 &availableCount = sac.creatures.at(k).first;
  731. const CCreature *cre = VLC->creh->objects.at(t->creatures.at(k).second.back());
  732. if (n.specialWeek == NewTurn::PLAGUE)
  733. availableCount = t->creatures.at(k).first / 2; //halve their number, no growth
  734. else
  735. {
  736. if (firstTurn) //first day of game: use only basic growths
  737. availableCount = cre->getGrowth();
  738. else
  739. availableCount += t->creatureGrowth(k);
  740. //Deity of fire week - upgrade both imps and upgrades
  741. if (n.specialWeek == NewTurn::DEITYOFFIRE && vstd::contains(t->creatures.at(k).second, n.creatureid))
  742. availableCount += 15;
  743. if (cre->getId() == n.creatureid) //bonus week, effect applies only to identical creatures
  744. {
  745. if (n.specialWeek == NewTurn::DOUBLE_GROWTH)
  746. availableCount *= 2;
  747. else if (n.specialWeek == NewTurn::BONUS_GROWTH)
  748. availableCount += 5;
  749. }
  750. }
  751. }
  752. }
  753. }
  754. if (!firstTurn && player < PlayerColor::PLAYER_LIMIT)//not the first day and town not neutral
  755. {
  756. n.res[player] = n.res[player] + t->dailyIncome();
  757. }
  758. if(t->hasBuilt(BuildingID::GRAIL)
  759. && t->town->buildings.at(BuildingID::GRAIL)->height == CBuilding::HEIGHT_SKYSHIP)
  760. {
  761. // Skyship, probably easier to handle same as Veil of darkness
  762. //do it every new day after veils apply
  763. if (player != PlayerColor::NEUTRAL) //do not reveal fow for neutral player
  764. {
  765. FoWChange fw;
  766. fw.mode = 1;
  767. fw.player = player;
  768. // find all hidden tiles
  769. const auto fow = getPlayerTeam(player)->fogOfWarMap;
  770. auto shape = fow->shape();
  771. for(size_t z = 0; z < shape[0]; z++)
  772. for(size_t x = 0; x < shape[1]; x++)
  773. for(size_t y = 0; y < shape[2]; y++)
  774. if (!(*fow)[z][x][y])
  775. fw.tiles.insert(int3(x, y, z));
  776. sendAndApply (&fw);
  777. }
  778. }
  779. if (t->hasBonusOfType (BonusType::DARKNESS))
  780. {
  781. for (auto & player : gs->players)
  782. {
  783. if (getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  784. getPlayerRelations(player.first, t->tempOwner) == PlayerRelations::ENEMIES)
  785. changeFogOfWar(t->visitablePos(), t->getBonusLocalFirst(Selector::type()(BonusType::DARKNESS))->val, player.first, true);
  786. }
  787. }
  788. }
  789. if (newMonth)
  790. {
  791. SetAvailableArtifacts saa;
  792. saa.id = -1;
  793. pickAllowedArtsSet(saa.arts, getRandomGenerator());
  794. sendAndApply(&saa);
  795. }
  796. sendAndApply(&n);
  797. if (newWeek)
  798. {
  799. //spawn wandering monsters
  800. if (newMonth && (n.specialWeek == NewTurn::DOUBLE_GROWTH || n.specialWeek == NewTurn::DEITYOFFIRE))
  801. {
  802. spawnWanderingMonsters(n.creatureid);
  803. }
  804. //new week info popup
  805. if (!firstTurn)
  806. {
  807. InfoWindow iw;
  808. switch (n.specialWeek)
  809. {
  810. case NewTurn::DOUBLE_GROWTH:
  811. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 131);
  812. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  813. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  814. break;
  815. case NewTurn::PLAGUE:
  816. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 132);
  817. break;
  818. case NewTurn::BONUS_GROWTH:
  819. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 134);
  820. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  821. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  822. break;
  823. case NewTurn::DEITYOFFIRE:
  824. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 135);
  825. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  826. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  827. iw.text.replacePositiveNumber(15); //%+d 15
  828. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 43); //%s familiar
  829. iw.text.replacePositiveNumber(15); //%+d 15
  830. break;
  831. default:
  832. if (newMonth)
  833. {
  834. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (130));
  835. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(32, 41));
  836. }
  837. else
  838. {
  839. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (133));
  840. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(43, 57));
  841. }
  842. }
  843. for (auto & elem : gs->players)
  844. {
  845. iw.player = elem.first;
  846. sendAndApply(&iw);
  847. }
  848. }
  849. }
  850. logGlobal->trace("Info about turn %d has been sent!", n.day);
  851. handleTimeEvents();
  852. //call objects
  853. for (auto & elem : gs->map->objects)
  854. {
  855. if (elem)
  856. elem->newTurn(getRandomGenerator());
  857. }
  858. synchronizeArtifactHandlerLists(); //new day events may have changed them. TODO better of managing that
  859. }
  860. void CGameHandler::run(bool resume)
  861. {
  862. LOG_TRACE_PARAMS(logGlobal, "resume=%d", resume);
  863. for (auto cc : lobby->connections)
  864. {
  865. auto players = lobby->getAllClientPlayers(cc->connectionID);
  866. std::stringstream sbuffer;
  867. sbuffer << "Connection " << cc->connectionID << " will handle " << players.size() << " player: ";
  868. for (PlayerColor color : players)
  869. {
  870. sbuffer << color << " ";
  871. {
  872. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  873. connections[color].insert(cc);
  874. }
  875. }
  876. logGlobal->info(sbuffer.str());
  877. }
  878. #if SCRIPTING_ENABLED
  879. services()->scripts()->run(serverScripts);
  880. #endif
  881. if(resume)
  882. events::GameResumed::defaultExecute(serverEventBus.get());
  883. auto playerTurnOrder = generatePlayerTurnOrder();
  884. if(!resume)
  885. for(auto & playerColor : playerTurnOrder)
  886. turnTimerHandler.onGameplayStart(gs->players[playerColor]);
  887. while(lobby->state == EServerState::GAMEPLAY)
  888. {
  889. if(!resume)
  890. {
  891. newTurn();
  892. events::TurnStarted::defaultExecute(serverEventBus.get());
  893. }
  894. std::list<PlayerColor>::iterator it;
  895. if (resume)
  896. {
  897. it = std::find(playerTurnOrder.begin(), playerTurnOrder.end(), gs->currentPlayer);
  898. }
  899. else
  900. {
  901. it = playerTurnOrder.begin();
  902. }
  903. resume = false;
  904. for (; (it != playerTurnOrder.end()) && (lobby->state == EServerState::GAMEPLAY) ; it++)
  905. {
  906. auto playerColor = *it;
  907. auto onGetTurn = [&](events::PlayerGotTurn & event)
  908. {
  909. //if player runs out of time, he shouldn't get the turn (especially AI)
  910. //pre-trigger may change anything, should check before each player
  911. //TODO: is it enough to check only one player?
  912. checkVictoryLossConditionsForAll();
  913. auto player = event.getPlayer();
  914. const PlayerState * playerState = &gs->players[player];
  915. if(playerState->status != EPlayerStatus::INGAME)
  916. {
  917. event.setPlayer(PlayerColor::CANNOT_DETERMINE);
  918. }
  919. else
  920. {
  921. states.setFlag(player, &PlayerStatus::makingTurn, true);
  922. YourTurn yt;
  923. yt.player = player;
  924. //Change local daysWithoutCastle counter for local interface message //TODO: needed?
  925. yt.daysWithoutCastle = playerState->daysWithoutCastle;
  926. applyAndSend(&yt);
  927. turnTimerHandler.onPlayerGetTurn(gs->players[player]);
  928. }
  929. };
  930. events::PlayerGotTurn::defaultExecute(serverEventBus.get(), onGetTurn, playerColor);
  931. if(playerColor != PlayerColor::CANNOT_DETERMINE)
  932. {
  933. //wait till turn is done
  934. const int waitTime = 100; //ms
  935. boost::unique_lock<boost::mutex> lock(states.mx);
  936. while(states.players.at(playerColor).makingTurn && lobby->state == EServerState::GAMEPLAY)
  937. {
  938. turnTimerHandler.onPlayerMakingTurn(gs->players[playerColor], waitTime);
  939. if(gs->curB)
  940. turnTimerHandler.onBattleLoop(waitTime);
  941. states.cv.wait_for(lock, boost::chrono::milliseconds(waitTime));
  942. }
  943. }
  944. }
  945. //additional check that game is not finished
  946. bool activePlayer = false;
  947. for (auto player : playerTurnOrder)
  948. {
  949. if (gs->players[player].status == EPlayerStatus::INGAME)
  950. activePlayer = true;
  951. }
  952. if(!activePlayer)
  953. lobby->state = EServerState::GAMEPLAY_ENDED;
  954. }
  955. }
  956. std::list<PlayerColor> CGameHandler::generatePlayerTurnOrder() const
  957. {
  958. // Generate player turn order
  959. std::list<PlayerColor> playerTurnOrder;
  960. for (const auto & player : gs->players) // add human players first
  961. {
  962. if (player.second.human)
  963. playerTurnOrder.push_back(player.first);
  964. }
  965. for (const auto & player : gs->players) // then add non-human players
  966. {
  967. if (!player.second.human)
  968. playerTurnOrder.push_back(player.first);
  969. }
  970. return playerTurnOrder;
  971. }
  972. void CGameHandler::giveSpells(const CGTownInstance *t, const CGHeroInstance *h)
  973. {
  974. if (!h->hasSpellbook())
  975. return; //hero hasn't spellbook
  976. ChangeSpells cs;
  977. cs.hid = h->id;
  978. cs.learn = true;
  979. if (t->hasBuilt(BuildingID::GRAIL, ETownType::CONFLUX) && t->hasBuilt(BuildingID::MAGES_GUILD_1))
  980. {
  981. // Aurora Borealis give spells of all levels even if only level 1 mages guild built
  982. for (int i = 0; i < h->maxSpellLevel(); i++)
  983. {
  984. std::vector<SpellID> spells;
  985. getAllowedSpells(spells, i+1);
  986. for (auto & spell : spells)
  987. cs.spells.insert(spell);
  988. }
  989. }
  990. else
  991. {
  992. for (int i = 0; i < std::min(t->mageGuildLevel(), h->maxSpellLevel()); i++)
  993. {
  994. for (int j = 0; j < t->spellsAtLevel(i+1, true) && j < t->spells.at(i).size(); j++)
  995. {
  996. if (!h->spellbookContainsSpell(t->spells.at(i).at(j)))
  997. cs.spells.insert(t->spells.at(i).at(j));
  998. }
  999. }
  1000. }
  1001. if (!cs.spells.empty())
  1002. sendAndApply(&cs);
  1003. }
  1004. bool CGameHandler::removeObject(const CGObjectInstance * obj)
  1005. {
  1006. if (!obj || !getObj(obj->id))
  1007. {
  1008. logGlobal->error("Something wrong, that object already has been removed or hasn't existed!");
  1009. return false;
  1010. }
  1011. RemoveObject ro;
  1012. ro.id = obj->id;
  1013. sendAndApply(&ro);
  1014. checkVictoryLossConditionsForAll(); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1015. return true;
  1016. }
  1017. bool CGameHandler::moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit, PlayerColor asker)
  1018. {
  1019. const CGHeroInstance *h = getHero(hid);
  1020. // not turn of that hero or player can't simply teleport hero (at least not with this function)
  1021. if (!h || (asker != PlayerColor::NEUTRAL && (teleporting || h->getOwner() != gs->currentPlayer)))
  1022. {
  1023. if(h && getStartInfo()->turnTimerInfo.isEnabled() && gs->players[h->getOwner()].turnTimer.turnTimer == 0)
  1024. return true; //timer expired, no error
  1025. logGlobal->error("Illegal call to move hero!");
  1026. return false;
  1027. }
  1028. logGlobal->trace("Player %d (%s) wants to move hero %d from %s to %s", asker, asker.getStr(), hid.getNum(), h->pos.toString(), dst.toString());
  1029. const int3 hmpos = h->convertToVisitablePos(dst);
  1030. if (!gs->map->isInTheMap(hmpos))
  1031. {
  1032. logGlobal->error("Destination tile is outside the map!");
  1033. return false;
  1034. }
  1035. const TerrainTile t = *getTile(hmpos);
  1036. const int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1037. const bool embarking = !h->boat && !t.visitableObjects.empty() && t.visitableObjects.back()->ID == Obj::BOAT;
  1038. const bool disembarking = h->boat
  1039. && t.terType->isLand()
  1040. && (dst == h->pos
  1041. || (h->boat->layer == EPathfindingLayer::SAIL && !t.blocked));
  1042. //result structure for start - movement failed, no move points used
  1043. TryMoveHero tmh;
  1044. tmh.id = hid;
  1045. tmh.start = h->pos;
  1046. tmh.end = dst;
  1047. tmh.result = TryMoveHero::FAILED;
  1048. tmh.movePoints = h->movementPointsRemaining();
  1049. //check if destination tile is available
  1050. auto pathfinderHelper = std::make_unique<CPathfinderHelper>(gs, h, PathfinderOptions());
  1051. auto ti = pathfinderHelper->getTurnInfo();
  1052. const bool canFly = pathfinderHelper->hasBonusOfType(BonusType::FLYING_MOVEMENT) || (h->boat && h->boat->layer == EPathfindingLayer::AIR);
  1053. const bool canWalkOnSea = pathfinderHelper->hasBonusOfType(BonusType::WATER_WALKING) || (h->boat && h->boat->layer == EPathfindingLayer::WATER);
  1054. const int cost = pathfinderHelper->getMovementCost(h->visitablePos(), hmpos, nullptr, nullptr, h->movementPointsRemaining());
  1055. //it's a rock or blocked and not visitable tile
  1056. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1057. if (((!t.terType->isPassable() || (t.blocked && !t.visitable && !canFly))
  1058. && complain("Cannot move hero, destination tile is blocked!"))
  1059. || ((!h->boat && !canWalkOnSea && !canFly && t.terType->isWater() && (t.visitableObjects.size() < 1 || !t.visitableObjects.back()->isCoastVisitable())) //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land) -> we test back cause boat may be on top of another object (#276)
  1060. && complain("Cannot move hero, destination tile is on water!"))
  1061. || ((h->boat && h->boat->layer == EPathfindingLayer::SAIL && t.terType->isLand() && t.blocked)
  1062. && complain("Cannot disembark hero, tile is blocked!"))
  1063. || ((distance(h->pos, dst) >= 1.5 && !teleporting)
  1064. && complain("Tiles are not neighboring!"))
  1065. || ((h->inTownGarrison)
  1066. && complain("Can not move garrisoned hero!"))
  1067. || (((int)h->movementPointsRemaining() < cost && dst != h->pos && !teleporting)
  1068. && complain("Hero doesn't have any movement points left!"))
  1069. || ((transit && !canFly && !CGTeleport::isTeleport(t.topVisitableObj()))
  1070. && complain("Hero cannot transit over this tile!"))
  1071. /*|| (states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1072. && complain("Cannot move hero during the battle"))*/)
  1073. {
  1074. //send info about movement failure
  1075. sendAndApply(&tmh);
  1076. return false;
  1077. }
  1078. //several generic blocks of code
  1079. // should be called if hero changes tile but before applying TryMoveHero package
  1080. auto leaveTile = [&]()
  1081. {
  1082. for (CGObjectInstance *obj : gs->map->getTile(int3(h->pos.x-1, h->pos.y, h->pos.z)).visitableObjects)
  1083. {
  1084. obj->onHeroLeave(h);
  1085. }
  1086. this->getTilesInRange(tmh.fowRevealed, h->getSightCenter()+(tmh.end-tmh.start), h->getSightRadius(), h->tempOwner, 1);
  1087. };
  1088. auto doMove = [&](TryMoveHero::EResult result, EGuardLook lookForGuards,
  1089. EVisitDest visitDest, ELEaveTile leavingTile) -> bool
  1090. {
  1091. LOG_TRACE_PARAMS(logGlobal, "Hero %s starts movement from %s to %s", h->getNameTranslated() % tmh.start.toString() % tmh.end.toString());
  1092. auto moveQuery = std::make_shared<CHeroMovementQuery>(this, tmh, h);
  1093. queries->addQuery(moveQuery);
  1094. if (leavingTile == LEAVING_TILE)
  1095. leaveTile();
  1096. if (isInTheMap(guardPos))
  1097. tmh.attackedFrom = std::make_optional(guardPos);
  1098. tmh.result = result;
  1099. sendAndApply(&tmh);
  1100. if (visitDest == VISIT_DEST && t.topVisitableObj() && t.topVisitableObj()->id == h->id)
  1101. { // Hero should be always able to visit any object he staying on even if there guards around
  1102. visitObjectOnTile(t, h);
  1103. }
  1104. else if (lookForGuards == CHECK_FOR_GUARDS && isInTheMap(guardPos))
  1105. {
  1106. const TerrainTile &guardTile = *gs->getTile(guardPos);
  1107. objectVisited(guardTile.visitableObjects.back(), h);
  1108. moveQuery->visitDestAfterVictory = visitDest==VISIT_DEST;
  1109. }
  1110. else if (visitDest == VISIT_DEST)
  1111. {
  1112. visitObjectOnTile(t, h);
  1113. }
  1114. for(auto topQuery = queries->topQuery(h->tempOwner); true; topQuery = queries->topQuery(h->tempOwner))
  1115. {
  1116. moveQuery = std::dynamic_pointer_cast<CHeroMovementQuery>(topQuery);
  1117. if(moveQuery
  1118. && (!transit || result == TryMoveHero::FAILED || moveQuery->tmh.stopMovement()))
  1119. queries->popIfTop(moveQuery);
  1120. else
  1121. break;
  1122. }
  1123. logGlobal->trace("Hero %s ends movement", h->getNameTranslated());
  1124. return result != TryMoveHero::FAILED;
  1125. };
  1126. //interaction with blocking object (like resources)
  1127. auto blockingVisit = [&]() -> bool
  1128. {
  1129. for (CGObjectInstance *obj : t.visitableObjects)
  1130. {
  1131. if(h->boat && !obj->isBlockedVisitable() && !h->boat->onboardVisitAllowed)
  1132. return doMove(TryMoveHero::SUCCESS, this->IGNORE_GUARDS, DONT_VISIT_DEST, REMAINING_ON_TILE);
  1133. if (obj != h && obj->isBlockedVisitable() && !obj->passableFor(h->tempOwner))
  1134. {
  1135. EVisitDest visitDest = VISIT_DEST;
  1136. if(h->boat && !h->boat->onboardVisitAllowed)
  1137. visitDest = DONT_VISIT_DEST;
  1138. return doMove(TryMoveHero::BLOCKING_VISIT, this->IGNORE_GUARDS, visitDest, REMAINING_ON_TILE);
  1139. }
  1140. }
  1141. return false;
  1142. };
  1143. if (!transit && embarking)
  1144. {
  1145. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, false, ti);
  1146. return doMove(TryMoveHero::EMBARK, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  1147. // In H3 embark ignore guards
  1148. }
  1149. if (disembarking)
  1150. {
  1151. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, true, ti);
  1152. return doMove(TryMoveHero::DISEMBARK, CHECK_FOR_GUARDS, VISIT_DEST, LEAVING_TILE);
  1153. }
  1154. if (teleporting)
  1155. {
  1156. if (blockingVisit()) // e.g. hero on the other side of teleporter
  1157. return true;
  1158. doMove(TryMoveHero::TELEPORTATION, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  1159. // visit town for town portal \ castle gates
  1160. // do not use generic visitObjectOnTile to avoid double-teleporting
  1161. // if this moveHero call was triggered by teleporter
  1162. if (!t.visitableObjects.empty())
  1163. {
  1164. if (CGTownInstance * town = dynamic_cast<CGTownInstance *>(t.visitableObjects.back()))
  1165. town->onHeroVisit(h);
  1166. }
  1167. return true;
  1168. }
  1169. //still here? it is standard movement!
  1170. {
  1171. tmh.movePoints = (int)h->movementPointsRemaining() >= cost
  1172. ? h->movementPointsRemaining() - cost
  1173. : 0;
  1174. EGuardLook lookForGuards = CHECK_FOR_GUARDS;
  1175. EVisitDest visitDest = VISIT_DEST;
  1176. if (transit)
  1177. {
  1178. if (CGTeleport::isTeleport(t.topVisitableObj()))
  1179. visitDest = DONT_VISIT_DEST;
  1180. if (canFly)
  1181. {
  1182. lookForGuards = IGNORE_GUARDS;
  1183. visitDest = DONT_VISIT_DEST;
  1184. }
  1185. }
  1186. else if (blockingVisit())
  1187. return true;
  1188. if(h->boat && !h->boat->onboardAssaultAllowed)
  1189. lookForGuards = IGNORE_GUARDS;
  1190. doMove(TryMoveHero::SUCCESS, lookForGuards, visitDest, LEAVING_TILE);
  1191. return true;
  1192. }
  1193. }
  1194. bool CGameHandler::teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker)
  1195. {
  1196. const CGHeroInstance *h = getHero(hid);
  1197. const CGTownInstance *t = getTown(dstid);
  1198. if (!h || !t || h->getOwner() != gs->currentPlayer)
  1199. COMPLAIN_RET("Invalid call to teleportHero!");
  1200. const CGTownInstance *from = h->visitedTown;
  1201. if (((h->getOwner() != t->getOwner())
  1202. && complain("Cannot teleport hero to another player"))
  1203. || (from->town->faction->getId() != t->town->faction->getId()
  1204. && complain("Source town and destination town should belong to the same faction"))
  1205. || ((!from || !from->hasBuilt(BuildingSubID::CASTLE_GATE))
  1206. && complain("Hero must be in town with Castle gate for teleporting"))
  1207. || (!t->hasBuilt(BuildingSubID::CASTLE_GATE)
  1208. && complain("Cannot teleport hero to town without Castle gate in it")))
  1209. return false;
  1210. int3 pos = h->convertFromVisitablePos(t->visitablePos());
  1211. moveHero(hid,pos,1);
  1212. return true;
  1213. }
  1214. void CGameHandler::setOwner(const CGObjectInstance * obj, const PlayerColor owner)
  1215. {
  1216. PlayerColor oldOwner = getOwner(obj->id);
  1217. SetObjectProperty sop(obj->id, ObjProperty::OWNER, owner.getNum());
  1218. sendAndApply(&sop);
  1219. std::set<PlayerColor> playerColors = {owner, oldOwner};
  1220. checkVictoryLossConditions(playerColors);
  1221. const CGTownInstance * town = dynamic_cast<const CGTownInstance *>(obj);
  1222. if (town) //town captured
  1223. {
  1224. if (owner < PlayerColor::PLAYER_LIMIT) //new owner is real player
  1225. {
  1226. if (town->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  1227. setPortalDwelling(town, true, false);
  1228. }
  1229. if (oldOwner < PlayerColor::PLAYER_LIMIT) //old owner is real player
  1230. {
  1231. if (getPlayerState(oldOwner)->towns.empty() && getPlayerState(oldOwner)->status != EPlayerStatus::LOSER) //previous player lost last last town
  1232. {
  1233. InfoWindow iw;
  1234. iw.player = oldOwner;
  1235. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1236. iw.text.replaceLocalString(EMetaText::COLOR, oldOwner.getNum());
  1237. sendAndApply(&iw);
  1238. }
  1239. }
  1240. }
  1241. const PlayerState * p = getPlayerState(owner);
  1242. if ((obj->ID == Obj::CREATURE_GENERATOR1 || obj->ID == Obj::CREATURE_GENERATOR4) && p && p->dwellings.size()==1)//first dwelling captured
  1243. {
  1244. for (const CGTownInstance * t : getPlayerState(owner)->towns)
  1245. {
  1246. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  1247. setPortalDwelling(t);//set initial creatures for all portals of summoning
  1248. }
  1249. }
  1250. }
  1251. void CGameHandler::showBlockingDialog(BlockingDialog *iw)
  1252. {
  1253. auto dialogQuery = std::make_shared<CBlockingDialogQuery>(this, *iw);
  1254. queries->addQuery(dialogQuery);
  1255. iw->queryID = dialogQuery->queryID;
  1256. sendToAllClients(iw);
  1257. }
  1258. void CGameHandler::showTeleportDialog(TeleportDialog *iw)
  1259. {
  1260. auto dialogQuery = std::make_shared<CTeleportDialogQuery>(this, *iw);
  1261. queries->addQuery(dialogQuery);
  1262. iw->queryID = dialogQuery->queryID;
  1263. sendToAllClients(iw);
  1264. }
  1265. void CGameHandler::giveResource(PlayerColor player, GameResID which, int val) //TODO: cap according to Bersy's suggestion
  1266. {
  1267. if (!val) return; //don't waste time on empty call
  1268. TResources resources;
  1269. resources[which] = val;
  1270. giveResources(player, resources);
  1271. }
  1272. void CGameHandler::giveResources(PlayerColor player, TResources resources)
  1273. {
  1274. SetResources sr;
  1275. sr.abs = false;
  1276. sr.player = player;
  1277. sr.res = resources;
  1278. sendAndApply(&sr);
  1279. }
  1280. void CGameHandler::giveCreatures(const CArmedInstance *obj, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove)
  1281. {
  1282. COMPLAIN_RET_IF(!creatures.stacksCount(), "Strange, giveCreatures called without args!");
  1283. COMPLAIN_RET_IF(obj->stacksCount(), "Cannot give creatures from not-cleared object!");
  1284. COMPLAIN_RET_IF(creatures.stacksCount() > GameConstants::ARMY_SIZE, "Too many stacks to give!");
  1285. //first we move creatures to give to make them army of object-source
  1286. for (auto & elem : creatures.Slots())
  1287. {
  1288. addToSlot(StackLocation(obj, obj->getSlotFor(elem.second->type)), elem.second->type, elem.second->count);
  1289. }
  1290. tryJoiningArmy(obj, h, remove, true);
  1291. }
  1292. void CGameHandler::takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures)
  1293. {
  1294. std::vector<CStackBasicDescriptor> cres = creatures;
  1295. if (cres.size() <= 0)
  1296. return;
  1297. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  1298. for (CStackBasicDescriptor &sbd : cres)
  1299. {
  1300. TQuantity collected = 0;
  1301. while(collected < sbd.count)
  1302. {
  1303. bool foundSth = false;
  1304. for (auto i = obj->Slots().begin(); i != obj->Slots().end(); i++)
  1305. {
  1306. if (i->second->type == sbd.type)
  1307. {
  1308. TQuantity take = std::min(sbd.count - collected, i->second->count); //collect as much cres as we can
  1309. changeStackCount(StackLocation(obj, i->first), -take, false);
  1310. collected += take;
  1311. foundSth = true;
  1312. break;
  1313. }
  1314. }
  1315. if (!foundSth) //we went through the whole loop and haven't found appropriate cres
  1316. {
  1317. complain("Unexpected failure during taking creatures!");
  1318. return;
  1319. }
  1320. }
  1321. }
  1322. }
  1323. void CGameHandler::heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  1324. {
  1325. HeroVisitCastle vc;
  1326. vc.hid = hero->id;
  1327. vc.tid = obj->id;
  1328. vc.flags |= 1;
  1329. sendAndApply(&vc);
  1330. visitCastleObjects(obj, hero);
  1331. giveSpells (obj, hero);
  1332. checkVictoryLossConditionsForPlayer(hero->tempOwner); //transported artifact?
  1333. }
  1334. void CGameHandler::visitCastleObjects(const CGTownInstance * t, const CGHeroInstance * h)
  1335. {
  1336. for (auto building : t->bonusingBuildings)
  1337. building->onHeroVisit(h);
  1338. }
  1339. void CGameHandler::stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  1340. {
  1341. HeroVisitCastle vc;
  1342. vc.hid = hero->id;
  1343. vc.tid = obj->id;
  1344. sendAndApply(&vc);
  1345. }
  1346. void CGameHandler::removeArtifact(const ArtifactLocation &al)
  1347. {
  1348. EraseArtifact ea;
  1349. ea.al = al;
  1350. sendAndApply(&ea);
  1351. }
  1352. void CGameHandler::changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells)
  1353. {
  1354. ChangeSpells cs;
  1355. cs.hid = hero->id;
  1356. cs.spells = spells;
  1357. cs.learn = give;
  1358. sendAndApply(&cs);
  1359. }
  1360. void CGameHandler::giveHeroBonus(GiveBonus * bonus)
  1361. {
  1362. sendAndApply(bonus);
  1363. }
  1364. void CGameHandler::setMovePoints(SetMovePoints * smp)
  1365. {
  1366. sendAndApply(smp);
  1367. }
  1368. void CGameHandler::setManaPoints(ObjectInstanceID hid, int val)
  1369. {
  1370. SetMana sm;
  1371. sm.hid = hid;
  1372. sm.val = val;
  1373. sm.absolute = true;
  1374. sendAndApply(&sm);
  1375. }
  1376. void CGameHandler::giveHero(ObjectInstanceID id, PlayerColor player, ObjectInstanceID boatId)
  1377. {
  1378. GiveHero gh;
  1379. gh.id = id;
  1380. gh.player = player;
  1381. gh.boatId = boatId;
  1382. sendAndApply(&gh);
  1383. //Reveal fow around new hero, especially released from Prison
  1384. auto h = getHero(id);
  1385. changeFogOfWar(h->pos, h->getSightRadius(), player, false);
  1386. }
  1387. void CGameHandler::changeObjPos(ObjectInstanceID objid, int3 newPos)
  1388. {
  1389. ChangeObjPos cop;
  1390. cop.objid = objid;
  1391. cop.nPos = newPos;
  1392. sendAndApply(&cop);
  1393. }
  1394. void CGameHandler::useScholarSkill(ObjectInstanceID fromHero, ObjectInstanceID toHero)
  1395. {
  1396. const CGHeroInstance * h1 = getHero(fromHero);
  1397. const CGHeroInstance * h2 = getHero(toHero);
  1398. int h1_scholarSpellLevel = h1->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  1399. int h2_scholarSpellLevel = h2->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  1400. if (h1_scholarSpellLevel < h2_scholarSpellLevel)
  1401. {
  1402. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  1403. std::swap(fromHero, toHero);
  1404. }
  1405. int ScholarSpellLevel = std::max(h1_scholarSpellLevel, h2_scholarSpellLevel);//heroes can trade up to this level
  1406. if (!ScholarSpellLevel || !h1->hasSpellbook() || !h2->hasSpellbook())
  1407. return;//no scholar skill or no spellbook
  1408. int h1Lvl = std::min(ScholarSpellLevel, h1->maxSpellLevel()),
  1409. h2Lvl = std::min(ScholarSpellLevel, h2->maxSpellLevel());//heroes can receive this levels
  1410. ChangeSpells cs1;
  1411. cs1.learn = true;
  1412. cs1.hid = toHero;//giving spells to first hero
  1413. for (auto it : h1->getSpellsInSpellbook())
  1414. if (h2Lvl >= it.toSpell()->level && !h2->spellbookContainsSpell(it))//hero can learn it and don't have it yet
  1415. cs1.spells.insert(it);//spell to learn
  1416. ChangeSpells cs2;
  1417. cs2.learn = true;
  1418. cs2.hid = fromHero;
  1419. for (auto it : h2->getSpellsInSpellbook())
  1420. if (h1Lvl >= it.toSpell()->level && !h1->spellbookContainsSpell(it))
  1421. cs2.spells.insert(it);
  1422. if (!cs1.spells.empty() || !cs2.spells.empty())//create a message
  1423. {
  1424. int ScholarSkillLevel = std::max(h1->getSecSkillLevel(SecondarySkill::SCHOLAR),
  1425. h2->getSecSkillLevel(SecondarySkill::SCHOLAR));
  1426. InfoWindow iw;
  1427. iw.player = h1->tempOwner;
  1428. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, 18, ScholarSkillLevel, 0);
  1429. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  1430. iw.text.replaceRawString(h1->getNameTranslated());
  1431. if (!cs2.spells.empty())//if found new spell - apply
  1432. {
  1433. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 140);//learns
  1434. int size = static_cast<int>(cs2.spells.size());
  1435. for (auto it : cs2.spells)
  1436. {
  1437. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  1438. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  1439. switch (size--)
  1440. {
  1441. case 2:
  1442. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  1443. case 1:
  1444. break;
  1445. default:
  1446. iw.text.appendRawString(", ");
  1447. }
  1448. }
  1449. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 142);//from %s
  1450. iw.text.replaceRawString(h2->getNameTranslated());
  1451. sendAndApply(&cs2);
  1452. }
  1453. if (!cs1.spells.empty() && !cs2.spells.empty())
  1454. {
  1455. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);//and
  1456. }
  1457. if (!cs1.spells.empty())
  1458. {
  1459. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 147);//teaches
  1460. int size = static_cast<int>(cs1.spells.size());
  1461. for (auto it : cs1.spells)
  1462. {
  1463. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  1464. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  1465. switch (size--)
  1466. {
  1467. case 2:
  1468. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  1469. case 1:
  1470. break;
  1471. default:
  1472. iw.text.appendRawString(", ");
  1473. }
  1474. }
  1475. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 148);//from %s
  1476. iw.text.replaceRawString(h2->getNameTranslated());
  1477. sendAndApply(&cs1);
  1478. }
  1479. sendAndApply(&iw);
  1480. }
  1481. }
  1482. void CGameHandler::heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  1483. {
  1484. auto h1 = getHero(hero1), h2 = getHero(hero2);
  1485. if (getPlayerRelations(h1->getOwner(), h2->getOwner()))
  1486. {
  1487. auto exchange = std::make_shared<CGarrisonDialogQuery>(this, h1, h2);
  1488. ExchangeDialog hex;
  1489. hex.queryID = exchange->queryID;
  1490. hex.player = h1->getOwner();
  1491. hex.hero1 = hero1;
  1492. hex.hero2 = hero2;
  1493. sendAndApply(&hex);
  1494. useScholarSkill(hero1,hero2);
  1495. queries->addQuery(exchange);
  1496. }
  1497. }
  1498. void CGameHandler::sendToAllClients(CPackForClient * pack)
  1499. {
  1500. logNetwork->trace("\tSending to all clients: %s", typeid(*pack).name());
  1501. for (auto c : lobby->connections)
  1502. {
  1503. if(!c->isOpen())
  1504. continue;
  1505. c->sendPack(pack);
  1506. }
  1507. }
  1508. void CGameHandler::sendAndApply(CPackForClient * pack)
  1509. {
  1510. sendToAllClients(pack);
  1511. gs->apply(pack);
  1512. logNetwork->trace("\tApplied on gs: %s", typeid(*pack).name());
  1513. }
  1514. void CGameHandler::applyAndSend(CPackForClient * pack)
  1515. {
  1516. gs->apply(pack);
  1517. sendToAllClients(pack);
  1518. }
  1519. void CGameHandler::sendAndApply(CGarrisonOperationPack * pack)
  1520. {
  1521. sendAndApply(static_cast<CPackForClient *>(pack));
  1522. checkVictoryLossConditionsForAll();
  1523. }
  1524. void CGameHandler::sendAndApply(SetResources * pack)
  1525. {
  1526. sendAndApply(static_cast<CPackForClient *>(pack));
  1527. checkVictoryLossConditionsForPlayer(pack->player);
  1528. }
  1529. void CGameHandler::sendAndApply(NewStructures * pack)
  1530. {
  1531. sendAndApply(static_cast<CPackForClient *>(pack));
  1532. checkVictoryLossConditionsForPlayer(getTown(pack->tid)->tempOwner);
  1533. }
  1534. bool CGameHandler::isPlayerOwns(CPackForServer * pack, ObjectInstanceID id)
  1535. {
  1536. return getPlayerAt(pack->c) == getOwner(id);
  1537. }
  1538. void CGameHandler::throwNotAllowedAction(CPackForServer * pack)
  1539. {
  1540. if(pack->c)
  1541. playerMessages->sendSystemMessage(pack->c, "You are not allowed to perform this action!");
  1542. logNetwork->error("Player is not allowed to perform this action!");
  1543. throw ExceptionNotAllowedAction();
  1544. }
  1545. void CGameHandler::wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer)
  1546. {
  1547. std::ostringstream oss;
  1548. oss << "You were identified as player " << getPlayerAt(pack->c) << " while expecting " << expectedplayer;
  1549. logNetwork->error(oss.str());
  1550. if(pack->c)
  1551. playerMessages->sendSystemMessage(pack->c, oss.str());
  1552. }
  1553. void CGameHandler::throwOnWrongOwner(CPackForServer * pack, ObjectInstanceID id)
  1554. {
  1555. if(!isPlayerOwns(pack, id))
  1556. {
  1557. wrongPlayerMessage(pack, getOwner(id));
  1558. throwNotAllowedAction(pack);
  1559. }
  1560. }
  1561. void CGameHandler::throwOnWrongPlayer(CPackForServer * pack, PlayerColor player)
  1562. {
  1563. if(!hasPlayerAt(player, pack->c) && player != getPlayerAt(pack->c))
  1564. {
  1565. wrongPlayerMessage(pack, player);
  1566. throwNotAllowedAction(pack);
  1567. }
  1568. }
  1569. void CGameHandler::throwAndComplain(CPackForServer * pack, std::string txt)
  1570. {
  1571. complain(txt);
  1572. throwNotAllowedAction(pack);
  1573. }
  1574. void CGameHandler::save(const std::string & filename)
  1575. {
  1576. logGlobal->info("Saving to %s", filename);
  1577. const auto stem = FileInfo::GetPathStem(filename);
  1578. const auto savefname = stem.to_string() + ".vsgm1";
  1579. CResourceHandler::get("local")->createResource(savefname);
  1580. try
  1581. {
  1582. {
  1583. CSaveFile save(*CResourceHandler::get("local")->getResourceName(ResourceID(stem.to_string(), EResType::SAVEGAME)));
  1584. saveCommonState(save);
  1585. logGlobal->info("Saving server state");
  1586. save << *this;
  1587. }
  1588. logGlobal->info("Game has been successfully saved!");
  1589. }
  1590. catch(std::exception &e)
  1591. {
  1592. logGlobal->error("Failed to save game: %s", e.what());
  1593. }
  1594. }
  1595. bool CGameHandler::load(const std::string & filename)
  1596. {
  1597. logGlobal->info("Loading from %s", filename);
  1598. const auto stem = FileInfo::GetPathStem(filename);
  1599. reinitScripting();
  1600. try
  1601. {
  1602. {
  1603. CLoadFile lf(*CResourceHandler::get()->getResourceName(ResourceID(stem.to_string(), EResType::SAVEGAME)), MINIMAL_SERIALIZATION_VERSION);
  1604. loadCommonState(lf);
  1605. logGlobal->info("Loading server state");
  1606. lf >> *this;
  1607. }
  1608. logGlobal->info("Game has been successfully loaded!");
  1609. }
  1610. catch(const ModIncompatibility & e)
  1611. {
  1612. logGlobal->error("Failed to load game: %s", e.what());
  1613. auto errorMsg = VLC->generaltexth->translate("vcmi.server.errors.modsIncompatibility") + '\n';
  1614. errorMsg += e.what();
  1615. lobby->announceMessage(errorMsg);
  1616. return false;
  1617. }
  1618. catch(const std::exception & e)
  1619. {
  1620. logGlobal->error("Failed to load game: %s", e.what());
  1621. return false;
  1622. }
  1623. gs->preInit(VLC);
  1624. gs->updateOnLoad(lobby->si.get());
  1625. return true;
  1626. }
  1627. bool CGameHandler::bulkSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner, si32 howMany)
  1628. {
  1629. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1630. return false;
  1631. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  1632. const CCreatureSet & creatureSet = *army;
  1633. if((!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1634. || (howMany < 1 && complain("Invalid split parameter!")))
  1635. {
  1636. return false;
  1637. }
  1638. auto actualAmount = army->getStackCount(slotSrc);
  1639. if(actualAmount <= howMany && complain(complainNotEnoughCreatures)) // '<=' because it's not intended just for moving a stack
  1640. return false;
  1641. auto freeSlots = creatureSet.getFreeSlots();
  1642. if(freeSlots.empty() && complain("No empty stacks"))
  1643. return false;
  1644. BulkRebalanceStacks bulkRS;
  1645. for(auto slot : freeSlots)
  1646. {
  1647. RebalanceStacks rs;
  1648. rs.srcArmy = army->id;
  1649. rs.dstArmy = army->id;
  1650. rs.srcSlot = slotSrc;
  1651. rs.dstSlot = slot;
  1652. rs.count = howMany;
  1653. bulkRS.moves.push_back(rs);
  1654. actualAmount -= howMany;
  1655. if(actualAmount <= howMany)
  1656. break;
  1657. }
  1658. sendAndApply(&bulkRS);
  1659. return true;
  1660. }
  1661. bool CGameHandler::bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner)
  1662. {
  1663. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1664. return false;
  1665. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  1666. const CCreatureSet & creatureSet = *army;
  1667. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1668. return false;
  1669. auto actualAmount = creatureSet.getStackCount(slotSrc);
  1670. if(actualAmount < 1 && complain(complainNoCreatures))
  1671. return false;
  1672. auto currentCreature = creatureSet.getCreature(slotSrc);
  1673. if(!currentCreature && complain(complainNoCreatures))
  1674. return false;
  1675. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, slotSrc);
  1676. if(!creatureSlots.size())
  1677. return false;
  1678. BulkRebalanceStacks bulkRS;
  1679. for(auto slot : creatureSlots)
  1680. {
  1681. RebalanceStacks rs;
  1682. rs.srcArmy = army->id;
  1683. rs.dstArmy = army->id;
  1684. rs.srcSlot = slot;
  1685. rs.dstSlot = slotSrc;
  1686. rs.count = creatureSet.getStackCount(slot);
  1687. bulkRS.moves.push_back(rs);
  1688. }
  1689. sendAndApply(&bulkRS);
  1690. return true;
  1691. }
  1692. bool CGameHandler::bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot)
  1693. {
  1694. if(!srcSlot.validSlot() && complain(complainInvalidSlot))
  1695. return false;
  1696. const CArmedInstance * armySrc = static_cast<const CArmedInstance*>(getObjInstance(srcArmy));
  1697. const CCreatureSet & setSrc = *armySrc;
  1698. if(!vstd::contains(setSrc.stacks, srcSlot) && complain(complainNoCreatures))
  1699. return false;
  1700. const CArmedInstance * armyDest = static_cast<const CArmedInstance*>(getObjInstance(destArmy));
  1701. const CCreatureSet & setDest = *armyDest;
  1702. auto freeSlots = setDest.getFreeSlotsQueue();
  1703. typedef std::map<SlotID, std::pair<SlotID, TQuantity>> TRebalanceMap;
  1704. TRebalanceMap moves;
  1705. auto srcQueue = setSrc.getCreatureQueue(srcSlot); // Exclude srcSlot, it should be moved last
  1706. auto slotsLeft = setSrc.stacksCount();
  1707. auto destMap = setDest.getCreatureMap();
  1708. TMapCreatureSlot::key_compare keyComp = destMap.key_comp();
  1709. while(!srcQueue.empty())
  1710. {
  1711. auto pair = srcQueue.top();
  1712. srcQueue.pop();
  1713. auto currCreature = pair.first;
  1714. auto currSlot = pair.second;
  1715. const auto quantity = setSrc.getStackCount(currSlot);
  1716. TMapCreatureSlot::iterator lb = destMap.lower_bound(currCreature);
  1717. const bool alreadyExists = (lb != destMap.end() && !(keyComp(currCreature, lb->first)));
  1718. if(!alreadyExists)
  1719. {
  1720. if(freeSlots.empty())
  1721. continue;
  1722. auto currFreeSlot = freeSlots.front();
  1723. freeSlots.pop();
  1724. destMap.insert(lb, TMapCreatureSlot::value_type(currCreature, currFreeSlot));
  1725. }
  1726. moves.insert(std::make_pair(currSlot, std::make_pair(destMap[currCreature], quantity)));
  1727. slotsLeft--;
  1728. }
  1729. if(slotsLeft == 1)
  1730. {
  1731. auto lastCreature = setSrc.getCreature(srcSlot);
  1732. auto slotToMove = SlotID();
  1733. // Try to find a slot for last creature
  1734. if(destMap.find(lastCreature) == destMap.end())
  1735. {
  1736. if(!freeSlots.empty())
  1737. slotToMove = freeSlots.front();
  1738. }
  1739. else
  1740. {
  1741. slotToMove = destMap[lastCreature];
  1742. }
  1743. if(slotToMove != SlotID())
  1744. {
  1745. const bool needsLastStack = armySrc->needsLastStack();
  1746. const auto quantity = setSrc.getStackCount(srcSlot) - (needsLastStack ? 1 : 0);
  1747. moves.insert(std::make_pair(srcSlot, std::make_pair(slotToMove, quantity)));
  1748. }
  1749. }
  1750. BulkRebalanceStacks bulkRS;
  1751. for(auto & move : moves)
  1752. {
  1753. RebalanceStacks rs;
  1754. rs.srcArmy = armySrc->id;
  1755. rs.dstArmy = armyDest->id;
  1756. rs.srcSlot = move.first;
  1757. rs.dstSlot = move.second.first;
  1758. rs.count = move.second.second;
  1759. bulkRS.moves.push_back(rs);
  1760. }
  1761. sendAndApply(&bulkRS);
  1762. return true;
  1763. }
  1764. bool CGameHandler::bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner)
  1765. {
  1766. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1767. return false;
  1768. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  1769. const CCreatureSet & creatureSet = *army;
  1770. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1771. return false;
  1772. auto actualAmount = creatureSet.getStackCount(slotSrc);
  1773. if(actualAmount <= 1 && complain(complainNoCreatures))
  1774. return false;
  1775. auto freeSlot = creatureSet.getFreeSlot();
  1776. auto currentCreature = creatureSet.getCreature(slotSrc);
  1777. if(freeSlot == SlotID() && creatureSet.isCreatureBalanced(currentCreature))
  1778. return true;
  1779. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, SlotID(-1), 1); // Ignore slots where's only 1 creature, don't ignore slotSrc
  1780. TQuantity totalCreatures = 0;
  1781. for(auto slot : creatureSlots)
  1782. totalCreatures += creatureSet.getStackCount(slot);
  1783. if(totalCreatures <= 1 && complain("Total creatures number is invalid"))
  1784. return false;
  1785. if(freeSlot != SlotID())
  1786. creatureSlots.push_back(freeSlot);
  1787. if(creatureSlots.empty() && complain("No available slots for smart rebalancing"))
  1788. return false;
  1789. const auto totalCreatureSlots = creatureSlots.size();
  1790. const auto rem = totalCreatures % totalCreatureSlots;
  1791. const auto quotient = totalCreatures / totalCreatureSlots;
  1792. // totalCreatures == rem * (quotient + 1) + (totalCreatureSlots - rem) * quotient;
  1793. // Proof: r(q+1)+(s-r)q = rq+r+qs-rq = r+qs = total, where total/s = q+r/s
  1794. BulkSmartRebalanceStacks bulkSRS;
  1795. if(freeSlot != SlotID())
  1796. {
  1797. RebalanceStacks rs;
  1798. rs.srcArmy = rs.dstArmy = army->id;
  1799. rs.srcSlot = slotSrc;
  1800. rs.dstSlot = freeSlot;
  1801. rs.count = 1;
  1802. bulkSRS.moves.push_back(rs);
  1803. }
  1804. auto currSlot = 0;
  1805. auto check = 0;
  1806. for(auto slot : creatureSlots)
  1807. {
  1808. ChangeStackCount csc;
  1809. csc.army = army->id;
  1810. csc.slot = slot;
  1811. csc.count = (currSlot < rem)
  1812. ? quotient + 1
  1813. : quotient;
  1814. csc.absoluteValue = true;
  1815. bulkSRS.changes.push_back(csc);
  1816. currSlot++;
  1817. check += csc.count;
  1818. }
  1819. if(check != totalCreatures)
  1820. {
  1821. complain((boost::format("Failure: totalCreatures=%d but check=%d") % totalCreatures % check).str());
  1822. return false;
  1823. }
  1824. sendAndApply(&bulkSRS);
  1825. return true;
  1826. }
  1827. bool CGameHandler::arrangeStacks(ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player)
  1828. {
  1829. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id1)),
  1830. * s2 = static_cast<const CArmedInstance *>(getObjInstance(id2));
  1831. const CCreatureSet &S1 = *s1, &S2 = *s2;
  1832. StackLocation sl1(s1, p1), sl2(s2, p2);
  1833. if (!sl1.slot.validSlot() || !sl2.slot.validSlot())
  1834. {
  1835. complain(complainInvalidSlot);
  1836. return false;
  1837. }
  1838. if (!isAllowedExchange(id1,id2))
  1839. {
  1840. complain("Cannot exchange stacks between these two objects!\n");
  1841. return false;
  1842. }
  1843. // We can always put stacks into locked garrison, but not take them out of it
  1844. auto notRemovable = [&](const CArmedInstance * army)
  1845. {
  1846. if (id1 != id2) // Stack arrangement inside locked garrison is allowed
  1847. {
  1848. auto g = dynamic_cast<const CGGarrison *>(army);
  1849. if (g && !g->removableUnits)
  1850. {
  1851. complain("Stacks in this garrison are not removable!\n");
  1852. return true;
  1853. }
  1854. }
  1855. return false;
  1856. };
  1857. if (what==1) //swap
  1858. {
  1859. if (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s1->getStackCount(p1))
  1860. || ((s2->tempOwner != player && s2->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)))
  1861. {
  1862. complain("Can't take troops from another player!");
  1863. return false;
  1864. }
  1865. if (sl1.army == sl2.army && sl1.slot == sl2.slot)
  1866. {
  1867. complain("Cannot swap stacks - slots are the same!");
  1868. return false;
  1869. }
  1870. if (!s1->slotEmpty(p1) && !s2->slotEmpty(p2))
  1871. {
  1872. if (notRemovable(sl1.army) || notRemovable(sl2.army))
  1873. return false;
  1874. }
  1875. if (s1->slotEmpty(p1) && notRemovable(sl2.army))
  1876. return false;
  1877. else if (s2->slotEmpty(p2) && notRemovable(sl1.army))
  1878. return false;
  1879. swapStacks(sl1, sl2);
  1880. }
  1881. else if (what==2)//merge
  1882. {
  1883. if ((s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot merge different creatures stacks!"))
  1884. || (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)) && complain("Can't take troops from another player!")))
  1885. return false;
  1886. if (s1->slotEmpty(p1) || s2->slotEmpty(p2))
  1887. {
  1888. complain("Cannot merge empty stack!");
  1889. return false;
  1890. }
  1891. else if (notRemovable(sl1.army))
  1892. return false;
  1893. moveStack(sl1, sl2);
  1894. }
  1895. else if (what==3) //split
  1896. {
  1897. const int countToMove = val - s2->getStackCount(p2);
  1898. const int countLeftOnSrc = s1->getStackCount(p1) - countToMove;
  1899. if ( (s1->tempOwner != player && countLeftOnSrc < s1->getStackCount(p1))
  1900. || (s2->tempOwner != player && val < s2->getStackCount(p2)))
  1901. {
  1902. complain("Can't move troops of another player!");
  1903. return false;
  1904. }
  1905. //general conditions checking
  1906. if ((!vstd::contains(S1.stacks,p1) && complain(complainNoCreatures))
  1907. || (val<1 && complain(complainNoCreatures)) )
  1908. {
  1909. return false;
  1910. }
  1911. if (vstd::contains(S2.stacks,p2)) //dest. slot not free - it must be "rebalancing"...
  1912. {
  1913. int total = s1->getStackCount(p1) + s2->getStackCount(p2);
  1914. if ((total < val && complain("Cannot split that stack, not enough creatures!"))
  1915. || (s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot rebalance different creatures stacks!"))
  1916. )
  1917. {
  1918. return false;
  1919. }
  1920. if (notRemovable(sl1.army))
  1921. {
  1922. if (s1->getStackCount(p1) > countLeftOnSrc)
  1923. return false;
  1924. }
  1925. else if (notRemovable(sl2.army))
  1926. {
  1927. if (s2->getStackCount(p1) < countLeftOnSrc)
  1928. return false;
  1929. }
  1930. moveStack(sl1, sl2, countToMove);
  1931. //S2.slots[p2]->count = val;
  1932. //S1.slots[p1]->count = total - val;
  1933. }
  1934. else //split one stack to the two
  1935. {
  1936. if (s1->getStackCount(p1) < val)//not enough creatures
  1937. {
  1938. complain(complainNotEnoughCreatures);
  1939. return false;
  1940. }
  1941. if (notRemovable(sl1.army))
  1942. return false;
  1943. moveStack(sl1, sl2, val);
  1944. }
  1945. }
  1946. return true;
  1947. }
  1948. bool CGameHandler::hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const
  1949. {
  1950. return connections.at(player).count(c);
  1951. }
  1952. PlayerColor CGameHandler::getPlayerAt(std::shared_ptr<CConnection> c) const
  1953. {
  1954. std::set<PlayerColor> all;
  1955. for (auto i=connections.cbegin(); i!=connections.cend(); i++)
  1956. if(vstd::contains(i->second, c))
  1957. all.insert(i->first);
  1958. switch(all.size())
  1959. {
  1960. case 0:
  1961. return PlayerColor::NEUTRAL;
  1962. case 1:
  1963. return *all.begin();
  1964. default:
  1965. {
  1966. //if we have more than one player at this connection, try to pick active one
  1967. if (vstd::contains(all, gs->currentPlayer))
  1968. return gs->currentPlayer;
  1969. else
  1970. return PlayerColor::CANNOT_DETERMINE; //cannot say which player is it
  1971. }
  1972. }
  1973. }
  1974. bool CGameHandler::disbandCreature(ObjectInstanceID id, SlotID pos)
  1975. {
  1976. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id));
  1977. if (!vstd::contains(s1->stacks,pos))
  1978. {
  1979. complain("Illegal call to disbandCreature - no such stack in army!");
  1980. return false;
  1981. }
  1982. eraseStack(StackLocation(s1, pos));
  1983. return true;
  1984. }
  1985. bool CGameHandler::buildStructure(ObjectInstanceID tid, BuildingID requestedID, bool force)
  1986. {
  1987. const CGTownInstance * t = getTown(tid);
  1988. if(!t)
  1989. COMPLAIN_RETF("No such town (ID=%s)!", tid);
  1990. if(!t->town->buildings.count(requestedID))
  1991. COMPLAIN_RETF("Town of faction %s does not have info about building ID=%s!", t->town->faction->getNameTranslated() % requestedID);
  1992. if(t->hasBuilt(requestedID))
  1993. COMPLAIN_RETF("Building %s is already built in %s", t->town->buildings.at(requestedID)->getNameTranslated() % t->getNameTranslated());
  1994. const CBuilding * requestedBuilding = t->town->buildings.at(requestedID);
  1995. //Vector with future list of built building and buildings in auto-mode that are not yet built.
  1996. std::vector<const CBuilding*> remainingAutoBuildings;
  1997. std::set<BuildingID> buildingsThatWillBe;
  1998. //Check validity of request
  1999. if(!force)
  2000. {
  2001. switch(requestedBuilding->mode)
  2002. {
  2003. case CBuilding::BUILD_NORMAL :
  2004. if (canBuildStructure(t, requestedID) != EBuildingState::ALLOWED)
  2005. COMPLAIN_RET("Cannot build that building!");
  2006. break;
  2007. case CBuilding::BUILD_AUTO :
  2008. case CBuilding::BUILD_SPECIAL:
  2009. COMPLAIN_RET("This building can not be constructed normally!");
  2010. case CBuilding::BUILD_GRAIL :
  2011. if(requestedBuilding->mode == CBuilding::BUILD_GRAIL) //needs grail
  2012. {
  2013. if(!t->visitingHero || !t->visitingHero->hasArt(ArtifactID::GRAIL))
  2014. COMPLAIN_RET("Cannot build this without grail!")
  2015. else
  2016. removeArtifact(ArtifactLocation(t->visitingHero, t->visitingHero->getArtPos(ArtifactID::GRAIL, false)));
  2017. }
  2018. break;
  2019. }
  2020. }
  2021. //Performs stuff that has to be done before new building is built
  2022. auto processBeforeBuiltStructure = [t, this](const BuildingID buildingID)
  2023. {
  2024. if(buildingID >= BuildingID::DWELL_FIRST) //dwelling
  2025. {
  2026. int level = (buildingID - BuildingID::DWELL_FIRST) % GameConstants::CREATURES_PER_TOWN;
  2027. int upgradeNumber = (buildingID - BuildingID::DWELL_FIRST) / GameConstants::CREATURES_PER_TOWN;
  2028. if(upgradeNumber >= t->town->creatures.at(level).size())
  2029. {
  2030. complain(boost::str(boost::format("Error ecountered when building dwelling (bid=%s):"
  2031. "no creature found (upgrade number %d, level %d!")
  2032. % buildingID % upgradeNumber % level));
  2033. return;
  2034. }
  2035. CCreature * crea = VLC->creh->objects.at(t->town->creatures.at(level).at(upgradeNumber));
  2036. SetAvailableCreatures ssi;
  2037. ssi.tid = t->id;
  2038. ssi.creatures = t->creatures;
  2039. if (ssi.creatures[level].second.empty()) // first creature in a dwelling
  2040. ssi.creatures[level].first = crea->getGrowth();
  2041. ssi.creatures[level].second.push_back(crea->getId());
  2042. sendAndApply(&ssi);
  2043. }
  2044. if(t->town->buildings.at(buildingID)->subId == BuildingSubID::PORTAL_OF_SUMMONING)
  2045. {
  2046. setPortalDwelling(t);
  2047. }
  2048. };
  2049. //Performs stuff that has to be done after new building is built
  2050. auto processAfterBuiltStructure = [t, this](const BuildingID buildingID)
  2051. {
  2052. auto isMageGuild = (buildingID <= BuildingID::MAGES_GUILD_5 && buildingID >= BuildingID::MAGES_GUILD_1);
  2053. auto isLibrary = isMageGuild ? false
  2054. : t->town->buildings.at(buildingID)->subId == BuildingSubID::EBuildingSubID::LIBRARY;
  2055. if(isMageGuild || isLibrary || (t->subID == ETownType::CONFLUX && buildingID == BuildingID::GRAIL))
  2056. {
  2057. if(t->visitingHero)
  2058. giveSpells(t,t->visitingHero);
  2059. if(t->garrisonHero)
  2060. giveSpells(t,t->garrisonHero);
  2061. }
  2062. };
  2063. //Checks if all requirements will be met with expected building list "buildingsThatWillBe"
  2064. auto areRequirementsFullfilled = [&](const BuildingID & buildID)
  2065. {
  2066. return buildingsThatWillBe.count(buildID);
  2067. };
  2068. //Init the vectors
  2069. for(auto & build : t->town->buildings)
  2070. {
  2071. if(t->hasBuilt(build.first))
  2072. {
  2073. buildingsThatWillBe.insert(build.first);
  2074. }
  2075. else
  2076. {
  2077. if(build.second->mode == CBuilding::BUILD_AUTO) //not built auto building
  2078. remainingAutoBuildings.push_back(build.second);
  2079. }
  2080. }
  2081. //Prepare structure (list of building ids will be filled later)
  2082. NewStructures ns;
  2083. ns.tid = tid;
  2084. ns.builded = force ? t->builded : (t->builded+1);
  2085. std::queue<const CBuilding*> buildingsToAdd;
  2086. buildingsToAdd.push(requestedBuilding);
  2087. while(!buildingsToAdd.empty())
  2088. {
  2089. auto b = buildingsToAdd.front();
  2090. buildingsToAdd.pop();
  2091. ns.bid.insert(b->bid);
  2092. buildingsThatWillBe.insert(b->bid);
  2093. remainingAutoBuildings -= b;
  2094. for(auto autoBuilding : remainingAutoBuildings)
  2095. {
  2096. auto actualRequirements = t->genBuildingRequirements(autoBuilding->bid);
  2097. if(actualRequirements.test(areRequirementsFullfilled))
  2098. buildingsToAdd.push(autoBuilding);
  2099. }
  2100. }
  2101. // FIXME: it's done before NewStructures applied because otherwise town window wont be properly updated on client. That should be actually fixed on client and not on server.
  2102. for(auto builtID : ns.bid)
  2103. processBeforeBuiltStructure(builtID);
  2104. //Take cost
  2105. if(!force)
  2106. giveResources(t->tempOwner, -requestedBuilding->resources);
  2107. //We know what has been built, apply changes. Do this as final step to properly update town window
  2108. sendAndApply(&ns);
  2109. //Other post-built events. To some logic like giving spells to work gamestate changes for new building must be already in place!
  2110. for(auto builtID : ns.bid)
  2111. processAfterBuiltStructure(builtID);
  2112. // now when everything is built - reveal tiles for lookout tower
  2113. FoWChange fw;
  2114. fw.player = t->tempOwner;
  2115. fw.mode = 1;
  2116. getTilesInRange(fw.tiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, 1);
  2117. sendAndApply(&fw);
  2118. if(t->visitingHero)
  2119. visitCastleObjects(t, t->visitingHero);
  2120. if(t->garrisonHero)
  2121. visitCastleObjects(t, t->garrisonHero);
  2122. checkVictoryLossConditionsForPlayer(t->tempOwner);
  2123. return true;
  2124. }
  2125. bool CGameHandler::razeStructure (ObjectInstanceID tid, BuildingID bid)
  2126. {
  2127. ///incomplete, simply erases target building
  2128. const CGTownInstance * t = getTown(tid);
  2129. if (!vstd::contains(t->builtBuildings, bid))
  2130. return false;
  2131. RazeStructures rs;
  2132. rs.tid = tid;
  2133. rs.bid.insert(bid);
  2134. rs.destroyed = t->destroyed + 1;
  2135. sendAndApply(&rs);
  2136. //TODO: Remove dwellers
  2137. // if (t->subID == 4 && bid == 17) //Veil of Darkness
  2138. // {
  2139. // RemoveBonus rb(RemoveBonus::TOWN);
  2140. // rb.whoID = t->id;
  2141. // rb.source = BonusSource::TOWN_STRUCTURE;
  2142. // rb.id = 17;
  2143. // sendAndApply(&rb);
  2144. // }
  2145. return true;
  2146. }
  2147. bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dstid, CreatureID crid, ui32 cram, si32 fromLvl)
  2148. {
  2149. const CGDwelling * dw = static_cast<const CGDwelling *>(getObj(objid));
  2150. const CArmedInstance *dst = nullptr;
  2151. const CCreature *c = VLC->creh->objects.at(crid);
  2152. const bool warMachine = c->warMachine != ArtifactID::NONE;
  2153. //TODO: test for owning
  2154. //TODO: check if dst can recruit objects (e.g. hero is actually visiting object, town and source are same, etc)
  2155. dst = dynamic_cast<const CArmedInstance*>(getObj(dstid));
  2156. assert(dw && dst);
  2157. //verify
  2158. bool found = false;
  2159. int level = 0;
  2160. for (; level < dw->creatures.size(); level++) //iterate through all levels
  2161. {
  2162. if ((fromLvl != -1) && (level !=fromLvl))
  2163. continue;
  2164. const auto &cur = dw->creatures.at(level); //current level info <amount, list of cr. ids>
  2165. int i = 0;
  2166. for (; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  2167. if (cur.second.at(i) == crid)
  2168. break;
  2169. if (i < cur.second.size())
  2170. {
  2171. found = true;
  2172. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  2173. break;
  2174. }
  2175. }
  2176. SlotID slot = dst->getSlotFor(crid);
  2177. if ((!found && complain("Cannot recruit: no such creatures!"))
  2178. || ((si32)cram > VLC->creh->objects.at(crid)->maxAmount(getPlayerState(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!"))
  2179. || (cram<=0 && complain("Cannot recruit: cram <= 0!"))
  2180. || (!slot.validSlot() && !warMachine && complain("Cannot recruit: no available slot!")))
  2181. {
  2182. return false;
  2183. }
  2184. //recruit
  2185. giveResources(dst->tempOwner, -(c->getFullRecruitCost() * cram));
  2186. SetAvailableCreatures sac;
  2187. sac.tid = objid;
  2188. sac.creatures = dw->creatures;
  2189. sac.creatures[level].first -= cram;
  2190. sendAndApply(&sac);
  2191. if (warMachine)
  2192. {
  2193. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(dst);
  2194. COMPLAIN_RET_FALSE_IF(!h, "Only hero can buy war machines");
  2195. ArtifactID artId = c->warMachine;
  2196. COMPLAIN_RET_FALSE_IF(artId == ArtifactID::CATAPULT, "Catapult cannot be recruited!");
  2197. const CArtifact * art = artId.toArtifact();
  2198. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid war machine artifact");
  2199. return giveHeroNewArtifact(h, art);
  2200. }
  2201. else
  2202. {
  2203. addToSlot(StackLocation(dst, slot), c, cram);
  2204. }
  2205. return true;
  2206. }
  2207. bool CGameHandler::upgradeCreature(ObjectInstanceID objid, SlotID pos, CreatureID upgID)
  2208. {
  2209. const CArmedInstance * obj = static_cast<const CArmedInstance *>(getObjInstance(objid));
  2210. if (!obj->hasStackAtSlot(pos))
  2211. {
  2212. COMPLAIN_RET("Cannot upgrade, no stack at slot " + std::to_string(pos));
  2213. }
  2214. UpgradeInfo ui;
  2215. fillUpgradeInfo(obj, pos, ui);
  2216. PlayerColor player = obj->tempOwner;
  2217. const PlayerState *p = getPlayerState(player);
  2218. int crQuantity = obj->stacks.at(pos)->count;
  2219. int newIDpos= vstd::find_pos(ui.newID, upgID);//get position of new id in UpgradeInfo
  2220. //check if upgrade is possible
  2221. if ((ui.oldID<0 || newIDpos == -1) && complain("That upgrade is not possible!"))
  2222. {
  2223. return false;
  2224. }
  2225. TResources totalCost = ui.cost.at(newIDpos) * crQuantity;
  2226. //check if player has enough resources
  2227. if (!p->resources.canAfford(totalCost))
  2228. COMPLAIN_RET("Cannot upgrade, not enough resources!");
  2229. //take resources
  2230. giveResources(player, -totalCost);
  2231. //upgrade creature
  2232. changeStackType(StackLocation(obj, pos), VLC->creh->objects.at(upgID));
  2233. return true;
  2234. }
  2235. bool CGameHandler::changeStackType(const StackLocation &sl, const CCreature *c)
  2236. {
  2237. if (!sl.army->hasStackAtSlot(sl.slot))
  2238. COMPLAIN_RET("Cannot find a stack to change type");
  2239. SetStackType sst;
  2240. sst.army = sl.army->id;
  2241. sst.slot = sl.slot;
  2242. sst.type = c->getId();
  2243. sendAndApply(&sst);
  2244. return true;
  2245. }
  2246. void CGameHandler::moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging)
  2247. {
  2248. assert(src->canBeMergedWith(*dst, allowMerging));
  2249. while(src->stacksCount())//while there are unmoved creatures
  2250. {
  2251. auto i = src->Slots().begin(); //iterator to stack to move
  2252. StackLocation sl(src, i->first); //location of stack to move
  2253. SlotID pos = dst->getSlotFor(i->second->type);
  2254. if (!pos.validSlot())
  2255. {
  2256. //try to merge two other stacks to make place
  2257. std::pair<SlotID, SlotID> toMerge;
  2258. if (dst->mergableStacks(toMerge, i->first) && allowMerging)
  2259. {
  2260. moveStack(StackLocation(dst, toMerge.first), StackLocation(dst, toMerge.second)); //merge toMerge.first into toMerge.second
  2261. assert(!dst->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  2262. moveStack(sl, StackLocation(dst, toMerge.first)); //move stack to freed slot
  2263. }
  2264. else
  2265. {
  2266. complain("Unexpected failure during an attempt to move army from " + src->nodeName() + " to " + dst->nodeName() + "!");
  2267. return;
  2268. }
  2269. }
  2270. else
  2271. {
  2272. moveStack(sl, StackLocation(dst, pos));
  2273. }
  2274. }
  2275. }
  2276. bool CGameHandler::swapGarrisonOnSiege(ObjectInstanceID tid)
  2277. {
  2278. const CGTownInstance * town = getTown(tid);
  2279. if(!town->garrisonHero == !town->visitingHero)
  2280. return false;
  2281. SetHeroesInTown intown;
  2282. intown.tid = tid;
  2283. if(town->garrisonHero) //garrison -> vising
  2284. {
  2285. intown.garrison = ObjectInstanceID();
  2286. intown.visiting = town->garrisonHero->id;
  2287. }
  2288. else //visiting -> garrison
  2289. {
  2290. if(town->armedGarrison())
  2291. town->mergeGarrisonOnSiege();
  2292. intown.visiting = ObjectInstanceID();
  2293. intown.garrison = town->visitingHero->id;
  2294. }
  2295. sendAndApply(&intown);
  2296. return true;
  2297. }
  2298. bool CGameHandler::garrisonSwap(ObjectInstanceID tid)
  2299. {
  2300. const CGTownInstance * town = getTown(tid);
  2301. if (!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2302. {
  2303. if (!town->visitingHero->canBeMergedWith(*town))
  2304. {
  2305. complain("Cannot make garrison swap, not enough free slots!");
  2306. return false;
  2307. }
  2308. moveArmy(town, town->visitingHero, true);
  2309. SetHeroesInTown intown;
  2310. intown.tid = tid;
  2311. intown.visiting = ObjectInstanceID();
  2312. intown.garrison = town->visitingHero->id;
  2313. sendAndApply(&intown);
  2314. return true;
  2315. }
  2316. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2317. {
  2318. //check if moving hero out of town will break 8 wandering heroes limit
  2319. if (getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2320. {
  2321. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2322. return false;
  2323. }
  2324. SetHeroesInTown intown;
  2325. intown.tid = tid;
  2326. intown.garrison = ObjectInstanceID();
  2327. intown.visiting = town->garrisonHero->id;
  2328. sendAndApply(&intown);
  2329. return true;
  2330. }
  2331. else if (!!town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2332. {
  2333. SetHeroesInTown intown;
  2334. intown.tid = tid;
  2335. intown.garrison = town->visitingHero->id;
  2336. intown.visiting = town->garrisonHero->id;
  2337. sendAndApply(&intown);
  2338. return true;
  2339. }
  2340. else
  2341. {
  2342. complain("Cannot swap garrison hero!");
  2343. return false;
  2344. }
  2345. }
  2346. // With the amount of changes done to the function, it's more like transferArtifacts.
  2347. // Function moves artifact from src to dst. If dst is not a backpack and is already occupied, old dst art goes to backpack and is replaced.
  2348. bool CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2)
  2349. {
  2350. ArtifactLocation src = al1, dst = al2;
  2351. const PlayerColor srcPlayer = src.owningPlayer(), dstPlayer = dst.owningPlayer();
  2352. const CArmedInstance *srcObj = src.relatedObj(), *dstObj = dst.relatedObj();
  2353. // Make sure exchange is even possible between the two heroes.
  2354. if(!isAllowedExchange(srcObj->id, dstObj->id))
  2355. COMPLAIN_RET("That heroes cannot make any exchange!");
  2356. const CArtifactInstance *srcArtifact = src.getArt();
  2357. const CArtifactInstance *destArtifact = dst.getArt();
  2358. const bool isDstSlotBackpack = ArtifactUtils::isSlotBackpack(dst.slot);
  2359. if(srcArtifact == nullptr)
  2360. COMPLAIN_RET("No artifact to move!");
  2361. if(destArtifact && srcPlayer != dstPlayer && !isDstSlotBackpack)
  2362. COMPLAIN_RET("Can't touch artifact on hero of another player!");
  2363. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2364. // Moving to the backpack is always allowed.
  2365. if((!srcArtifact || !isDstSlotBackpack)
  2366. && srcArtifact && !srcArtifact->canBePutAt(dst, true))
  2367. COMPLAIN_RET("Cannot move artifact!");
  2368. auto srcSlot = src.getSlot();
  2369. auto dstSlot = dst.getSlot();
  2370. if((srcSlot && srcSlot->locked) || (dstSlot && dstSlot->locked))
  2371. COMPLAIN_RET("Cannot move artifact locks.");
  2372. if(isDstSlotBackpack && srcArtifact->artType->isBig())
  2373. COMPLAIN_RET("Cannot put big artifacts in backpack!");
  2374. if(src.slot == ArtifactPosition::MACH4 || dst.slot == ArtifactPosition::MACH4)
  2375. COMPLAIN_RET("Cannot move catapult!");
  2376. if(isDstSlotBackpack)
  2377. {
  2378. if(!ArtifactUtils::isBackpackFreeSlots(dst.getHolderArtSet()))
  2379. COMPLAIN_RET("Backpack is full!");
  2380. vstd::amin(dst.slot, GameConstants::BACKPACK_START + dst.getHolderArtSet()->artifactsInBackpack.size());
  2381. }
  2382. if(!(src.slot == ArtifactPosition::TRANSITION_POS && dst.slot == ArtifactPosition::TRANSITION_POS))
  2383. {
  2384. if(src.slot == dst.slot && src.artHolder == dst.artHolder)
  2385. COMPLAIN_RET("Won't move artifact: Dest same as source!");
  2386. // Check if dst slot is occupied
  2387. if(!isDstSlotBackpack && destArtifact)
  2388. {
  2389. // Previous artifact must be removed first
  2390. moveArtifact(dst, ArtifactLocation(dst.artHolder, ArtifactPosition::TRANSITION_POS));
  2391. }
  2392. try
  2393. {
  2394. auto hero = std::get<ConstTransitivePtr<CGHeroInstance>>(dst.artHolder);
  2395. if(ArtifactUtils::checkSpellbookIsNeeded(hero, srcArtifact->artType->getId(), dst.slot))
  2396. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  2397. }
  2398. catch(const std::bad_variant_access &)
  2399. {
  2400. // object other than hero received an art - ignore
  2401. }
  2402. MoveArtifact ma(&src, &dst);
  2403. if(dst.slot == ArtifactPosition::TRANSITION_POS)
  2404. ma.askAssemble = false;
  2405. sendAndApply(&ma);
  2406. }
  2407. return true;
  2408. }
  2409. bool CGameHandler::bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap)
  2410. {
  2411. // Make sure exchange is even possible between the two heroes.
  2412. if(!isAllowedExchange(srcHero, dstHero))
  2413. COMPLAIN_RET("That heroes cannot make any exchange!");
  2414. auto psrcHero = getHero(srcHero);
  2415. auto pdstHero = getHero(dstHero);
  2416. if((!psrcHero) || (!pdstHero))
  2417. COMPLAIN_RET("bulkMoveArtifacts: wrong hero's ID");
  2418. BulkMoveArtifacts ma(static_cast<ConstTransitivePtr<CGHeroInstance>>(psrcHero),
  2419. static_cast<ConstTransitivePtr<CGHeroInstance>>(pdstHero), swap);
  2420. auto & slotsSrcDst = ma.artsPack0;
  2421. auto & slotsDstSrc = ma.artsPack1;
  2422. // Temporary fitting set for artifacts. Used to select available slots before sending data.
  2423. CArtifactFittingSet artFittingSet(pdstHero->bearerType());
  2424. auto moveArtifact = [this, &artFittingSet](const CArtifactInstance * artifact,
  2425. ArtifactPosition srcSlot, const CGHeroInstance * dstHero,
  2426. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  2427. {
  2428. assert(artifact);
  2429. auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, artifact->getTypeId());
  2430. if(dstSlot != ArtifactPosition::PRE_FIRST)
  2431. {
  2432. artFittingSet.putArtifact(dstSlot, static_cast<ConstTransitivePtr<CArtifactInstance>>(artifact));
  2433. slots.push_back(BulkMoveArtifacts::LinkedSlots(srcSlot, dstSlot));
  2434. if(ArtifactUtils::checkSpellbookIsNeeded(dstHero, artifact->getTypeId(), dstSlot))
  2435. giveHeroNewArtifact(dstHero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  2436. }
  2437. };
  2438. if(swap)
  2439. {
  2440. auto moveArtsWorn = [moveArtifact](const CGHeroInstance * srcHero, const CGHeroInstance * dstHero,
  2441. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  2442. {
  2443. for(auto & artifact : srcHero->artifactsWorn)
  2444. {
  2445. if(ArtifactUtils::isArtRemovable(artifact))
  2446. moveArtifact(artifact.second.getArt(), artifact.first, dstHero, slots);
  2447. }
  2448. };
  2449. auto moveArtsInBackpack = [](const CArtifactSet * artSet,
  2450. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  2451. {
  2452. for(auto & slotInfo : artSet->artifactsInBackpack)
  2453. {
  2454. auto slot = artSet->getArtPos(slotInfo.artifact);
  2455. slots.push_back(BulkMoveArtifacts::LinkedSlots(slot, slot));
  2456. }
  2457. };
  2458. // Move over artifacts that are worn srcHero -> dstHero
  2459. moveArtsWorn(psrcHero, pdstHero, slotsSrcDst);
  2460. artFittingSet.artifactsWorn.clear();
  2461. // Move over artifacts that are worn dstHero -> srcHero
  2462. moveArtsWorn(pdstHero, psrcHero, slotsDstSrc);
  2463. // Move over artifacts that are in backpack srcHero -> dstHero
  2464. moveArtsInBackpack(psrcHero, slotsSrcDst);
  2465. // Move over artifacts that are in backpack dstHero -> srcHero
  2466. moveArtsInBackpack(pdstHero, slotsDstSrc);
  2467. }
  2468. else
  2469. {
  2470. artFittingSet.artifactsInBackpack = pdstHero->artifactsInBackpack;
  2471. artFittingSet.artifactsWorn = pdstHero->artifactsWorn;
  2472. // Move over artifacts that are worn
  2473. for(auto & artInfo : psrcHero->artifactsWorn)
  2474. {
  2475. if(ArtifactUtils::isArtRemovable(artInfo))
  2476. {
  2477. moveArtifact(psrcHero->getArt(artInfo.first), artInfo.first, pdstHero, slotsSrcDst);
  2478. }
  2479. }
  2480. // Move over artifacts that are in backpack
  2481. for(auto & slotInfo : psrcHero->artifactsInBackpack)
  2482. {
  2483. moveArtifact(psrcHero->getArt(psrcHero->getArtPos(slotInfo.artifact)),
  2484. psrcHero->getArtPos(slotInfo.artifact), pdstHero, slotsSrcDst);
  2485. }
  2486. }
  2487. sendAndApply(&ma);
  2488. return true;
  2489. }
  2490. /**
  2491. * Assembles or disassembles a combination artifact.
  2492. * @param heroID ID of hero holding the artifact(s).
  2493. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2494. * @param assemble True for assembly operation, false for disassembly.
  2495. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2496. * artifact to assemble to. Otherwise it's not used.
  2497. */
  2498. bool CGameHandler::assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  2499. {
  2500. const CGHeroInstance * hero = getHero(heroID);
  2501. const CArtifactInstance * destArtifact = hero->getArt(artifactSlot);
  2502. if(!destArtifact)
  2503. COMPLAIN_RET("assembleArtifacts: there is no such artifact instance!");
  2504. if(assemble)
  2505. {
  2506. CArtifact * combinedArt = VLC->arth->objects[assembleTo];
  2507. if(!combinedArt->isCombined())
  2508. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to assemble is not a combined artifacts!");
  2509. if (!vstd::contains(ArtifactUtils::assemblyPossibilities(hero, destArtifact->getTypeId(),
  2510. ArtifactUtils::isSlotEquipment(artifactSlot)), combinedArt))
  2511. {
  2512. COMPLAIN_RET("assembleArtifacts: It's impossible to assemble requested artifact!");
  2513. }
  2514. if(ArtifactUtils::checkSpellbookIsNeeded(hero, assembleTo, artifactSlot))
  2515. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  2516. AssembledArtifact aa;
  2517. aa.al = ArtifactLocation(hero, artifactSlot);
  2518. aa.builtArt = combinedArt;
  2519. sendAndApply(&aa);
  2520. }
  2521. else
  2522. {
  2523. if(!destArtifact->isCombined())
  2524. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is not a combined artifact!");
  2525. if(ArtifactUtils::isSlotBackpack(artifactSlot)
  2526. && !ArtifactUtils::isBackpackFreeSlots(hero, destArtifact->artType->getConstituents().size() - 1))
  2527. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble but backpack is full!");
  2528. DisassembledArtifact da;
  2529. da.al = ArtifactLocation(hero, artifactSlot);
  2530. sendAndApply(&da);
  2531. }
  2532. return true;
  2533. }
  2534. bool CGameHandler::eraseArtifactByClient(const ArtifactLocation & al)
  2535. {
  2536. const auto * hero = getHero(al.relatedObj()->id);
  2537. if(hero == nullptr)
  2538. COMPLAIN_RET("eraseArtifactByClient: wrong hero's ID");
  2539. const auto * art = al.getArt();
  2540. if(art == nullptr)
  2541. COMPLAIN_RET("Cannot remove artifact!");
  2542. if(al.getArt()->artType->canBePutAt(hero) || al.slot != ArtifactPosition::TRANSITION_POS)
  2543. COMPLAIN_RET("Illegal artifact removal request");
  2544. removeArtifact(al);
  2545. return true;
  2546. }
  2547. bool CGameHandler::buyArtifact(ObjectInstanceID hid, ArtifactID aid)
  2548. {
  2549. const CGHeroInstance * hero = getHero(hid);
  2550. COMPLAIN_RET_FALSE_IF(nullptr == hero, "Invalid hero index");
  2551. const CGTownInstance * town = hero->visitedTown;
  2552. COMPLAIN_RET_FALSE_IF(nullptr == town, "Hero not in town");
  2553. if (aid==ArtifactID::SPELLBOOK)
  2554. {
  2555. if ((!town->hasBuilt(BuildingID::MAGES_GUILD_1) && complain("Cannot buy a spellbook, no mage guild in the town!"))
  2556. || (getResource(hero->getOwner(), EGameResID::GOLD) < GameConstants::SPELLBOOK_GOLD_COST && complain("Cannot buy a spellbook, not enough gold!"))
  2557. || (hero->getArt(ArtifactPosition::SPELLBOOK) && complain("Cannot buy a spellbook, hero already has a one!"))
  2558. )
  2559. return false;
  2560. giveResource(hero->getOwner(),EGameResID::GOLD,-GameConstants::SPELLBOOK_GOLD_COST);
  2561. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  2562. assert(hero->getArt(ArtifactPosition::SPELLBOOK));
  2563. giveSpells(town,hero);
  2564. return true;
  2565. }
  2566. else
  2567. {
  2568. const CArtifact * art = aid.toArtifact();
  2569. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid artifact index to buy");
  2570. COMPLAIN_RET_FALSE_IF(art->getWarMachine() == CreatureID::NONE, "War machine artifact required");
  2571. COMPLAIN_RET_FALSE_IF(hero->hasArt(aid),"Hero already has this machine!");
  2572. const int price = art->getPrice();
  2573. COMPLAIN_RET_FALSE_IF(getPlayerState(hero->getOwner())->resources[EGameResID::GOLD] < price, "Not enough gold!");
  2574. if ((town->hasBuilt(BuildingID::BLACKSMITH) && town->town->warMachine == aid)
  2575. || (town->hasBuilt(BuildingSubID::BALLISTA_YARD) && aid == ArtifactID::BALLISTA))
  2576. {
  2577. giveResource(hero->getOwner(),EGameResID::GOLD,-price);
  2578. return giveHeroNewArtifact(hero, art);
  2579. }
  2580. else
  2581. COMPLAIN_RET("This machine is unavailable here!");
  2582. }
  2583. }
  2584. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid)
  2585. {
  2586. if(!h)
  2587. COMPLAIN_RET("Only hero can buy artifacts!");
  2588. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_ARTIFACT), aid))
  2589. COMPLAIN_RET("That artifact is unavailable!");
  2590. int b1, b2;
  2591. m->getOffer(rid, aid, b1, b2, EMarketMode::RESOURCE_ARTIFACT);
  2592. if (getResource(h->tempOwner, rid) < b1)
  2593. COMPLAIN_RET("You can't afford to buy this artifact!");
  2594. giveResource(h->tempOwner, rid, -b1);
  2595. SetAvailableArtifacts saa;
  2596. if(dynamic_cast<const CGTownInstance *>(m))
  2597. {
  2598. saa.id = -1;
  2599. saa.arts = CGTownInstance::merchantArtifacts;
  2600. }
  2601. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m)) //black market
  2602. {
  2603. saa.id = bm->id.getNum();
  2604. saa.arts = bm->artifacts;
  2605. }
  2606. else
  2607. COMPLAIN_RET("Wrong marktet...");
  2608. bool found = false;
  2609. for (const CArtifact *&art : saa.arts)
  2610. {
  2611. if (art && art->getId() == aid)
  2612. {
  2613. art = nullptr;
  2614. found = true;
  2615. break;
  2616. }
  2617. }
  2618. if (!found)
  2619. COMPLAIN_RET("Cannot find selected artifact on the list");
  2620. sendAndApply(&saa);
  2621. giveHeroNewArtifact(h, VLC->arth->objects[aid], ArtifactPosition::FIRST_AVAILABLE);
  2622. return true;
  2623. }
  2624. bool CGameHandler::sellArtifact(const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid)
  2625. {
  2626. COMPLAIN_RET_FALSE_IF((!h), "Only hero can sell artifacts!");
  2627. const CArtifactInstance *art = h->getArtByInstanceId(aid);
  2628. COMPLAIN_RET_FALSE_IF((!art), "There is no artifact to sell!");
  2629. COMPLAIN_RET_FALSE_IF((!art->artType->isTradable()), "Cannot sell a war machine or spellbook!");
  2630. int resVal = 0, dump = 1;
  2631. m->getOffer(art->artType->getId(), rid, dump, resVal, EMarketMode::ARTIFACT_RESOURCE);
  2632. removeArtifact(ArtifactLocation(h, h->getArtPos(art)));
  2633. giveResource(h->tempOwner, rid, resVal);
  2634. return true;
  2635. }
  2636. bool CGameHandler::buySecSkill(const IMarket *m, const CGHeroInstance *h, SecondarySkill skill)
  2637. {
  2638. if (!h)
  2639. COMPLAIN_RET("You need hero to buy a skill!");
  2640. if (h->getSecSkillLevel(SecondarySkill(skill)))
  2641. COMPLAIN_RET("Hero already know this skill");
  2642. if (!h->canLearnSkill())
  2643. COMPLAIN_RET("Hero can't learn any more skills");
  2644. if (!h->canLearnSkill(skill))
  2645. COMPLAIN_RET("The hero can't learn this skill!");
  2646. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_SKILL), skill))
  2647. COMPLAIN_RET("That skill is unavailable!");
  2648. if (getResource(h->tempOwner, EGameResID::GOLD) < GameConstants::SKILL_GOLD_COST)//TODO: remove hardcoded resource\summ?
  2649. COMPLAIN_RET("You can't afford to buy this skill");
  2650. giveResource(h->tempOwner, EGameResID::GOLD, -GameConstants::SKILL_GOLD_COST);
  2651. changeSecSkill(h, skill, 1, true);
  2652. return true;
  2653. }
  2654. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2)
  2655. {
  2656. TResourceCap r1 = getPlayerState(player)->resources[id1];
  2657. vstd::amin(val, r1); //can't trade more resources than have
  2658. int b1, b2; //base quantities for trade
  2659. market->getOffer(id1, id2, b1, b2, EMarketMode::RESOURCE_RESOURCE);
  2660. int units = val / b1; //how many base quantities we trade
  2661. if (val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2662. {
  2663. COMPLAIN_RET("Invalid deal, not all offered units of resource were used.");
  2664. }
  2665. giveResource(player, GameResID(id1), - b1 * units);
  2666. giveResource(player, GameResID(id2), b2 * units);
  2667. return true;
  2668. }
  2669. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID)
  2670. {
  2671. if(!hero)
  2672. COMPLAIN_RET("Only hero can sell creatures!");
  2673. if (!vstd::contains(hero->Slots(), slot))
  2674. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  2675. const CStackInstance &s = hero->getStack(slot);
  2676. if (s.count < (TQuantity)count //can't sell more creatures than have
  2677. || (hero->stacksCount() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack
  2678. {
  2679. COMPLAIN_RET("Not enough creatures in army!");
  2680. }
  2681. int b1, b2; //base quantities for trade
  2682. market->getOffer(s.type->getId(), resourceID, b1, b2, EMarketMode::CREATURE_RESOURCE);
  2683. int units = count / b1; //how many base quantities we trade
  2684. if (count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2685. {
  2686. //TODO: complain?
  2687. assert(0);
  2688. }
  2689. changeStackCount(StackLocation(hero, slot), -(TQuantity)count);
  2690. giveResource(hero->tempOwner, resourceID, b2 * units);
  2691. return true;
  2692. }
  2693. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot)
  2694. {
  2695. const CArmedInstance *army = nullptr;
  2696. if (hero)
  2697. army = hero;
  2698. else
  2699. army = dynamic_cast<const CGTownInstance *>(market);
  2700. if (!army)
  2701. COMPLAIN_RET("Incorrect call to transform in undead!");
  2702. if (!army->hasStackAtSlot(slot))
  2703. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  2704. const CStackInstance &s = army->getStack(slot);
  2705. //resulting creature - bone dragons or skeletons
  2706. CreatureID resCreature = CreatureID::SKELETON;
  2707. if ((s.hasBonusOfType(BonusType::DRAGON_NATURE)
  2708. && !(s.hasBonusOfType(BonusType::UNDEAD)))
  2709. || (s.getCreatureID() == CreatureID::HYDRA)
  2710. || (s.getCreatureID() == CreatureID::CHAOS_HYDRA))
  2711. resCreature = CreatureID::BONE_DRAGON;
  2712. changeStackType(StackLocation(army, slot), resCreature.toCreature());
  2713. return true;
  2714. }
  2715. bool CGameHandler::sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2)
  2716. {
  2717. const PlayerState *p2 = getPlayerState(r2, false);
  2718. if (!p2 || p2->status != EPlayerStatus::INGAME)
  2719. {
  2720. complain("Dest player must be in game!");
  2721. return false;
  2722. }
  2723. TResourceCap curRes1 = getPlayerState(player)->resources[r1];
  2724. vstd::amin(val, curRes1);
  2725. giveResource(player, r1, -(int)val);
  2726. giveResource(r2, r1, val);
  2727. return true;
  2728. }
  2729. bool CGameHandler::setFormation(ObjectInstanceID hid, ui8 formation)
  2730. {
  2731. const CGHeroInstance *h = getHero(hid);
  2732. if (!h)
  2733. {
  2734. logGlobal->error("Hero doesn't exist!");
  2735. return false;
  2736. }
  2737. ChangeFormation cf;
  2738. cf.hid = hid;
  2739. cf.formation = formation;
  2740. sendAndApply(&cf);
  2741. return true;
  2742. }
  2743. bool CGameHandler::queryReply(QueryID qid, const JsonNode & answer, PlayerColor player)
  2744. {
  2745. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2746. logGlobal->trace("Player %s attempts answering query %d with answer:", player, qid);
  2747. logGlobal->trace(answer.toJson());
  2748. auto topQuery = queries->topQuery(player);
  2749. COMPLAIN_RET_FALSE_IF(!topQuery, "This player doesn't have any queries!");
  2750. if(topQuery->queryID != qid)
  2751. {
  2752. auto currentQuery = queries->getQuery(qid);
  2753. if(currentQuery != nullptr && currentQuery->endsByPlayerAnswer())
  2754. currentQuery->setReply(answer);
  2755. COMPLAIN_RET("This player top query has different ID!"); //topQuery->queryID != qid
  2756. }
  2757. COMPLAIN_RET_FALSE_IF(!topQuery->endsByPlayerAnswer(), "This query cannot be ended by player's answer!");
  2758. topQuery->setReply(answer);
  2759. queries->popQuery(topQuery);
  2760. return true;
  2761. }
  2762. void CGameHandler::handleTimeEvents()
  2763. {
  2764. gs->map->events.sort(evntCmp);
  2765. while(gs->map->events.size() && gs->map->events.front().firstOccurence+1 == gs->day)
  2766. {
  2767. CMapEvent ev = gs->map->events.front();
  2768. for (int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
  2769. {
  2770. auto color = PlayerColor(player);
  2771. const PlayerState * pinfo = getPlayerState(color, false); //do not output error if player does not exist
  2772. if (pinfo //player exists
  2773. && (ev.players & 1<<player) //event is enabled to this player
  2774. && ((ev.computerAffected && !pinfo->human)
  2775. || (ev.humanAffected && pinfo->human)
  2776. )
  2777. )
  2778. {
  2779. //give resources
  2780. giveResources(color, ev.resources);
  2781. //prepare dialog
  2782. InfoWindow iw;
  2783. iw.player = color;
  2784. iw.text.appendRawString(ev.message);
  2785. for (int i=0; i<ev.resources.size(); i++)
  2786. {
  2787. if (ev.resources[i]) //if resource is changed, we add it to the dialog
  2788. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,ev.resources[i],0);
  2789. }
  2790. sendAndApply(&iw); //show dialog
  2791. }
  2792. } //PLAYERS LOOP
  2793. if (ev.nextOccurence)
  2794. {
  2795. gs->map->events.pop_front();
  2796. ev.firstOccurence += ev.nextOccurence;
  2797. auto it = gs->map->events.begin();
  2798. while(it != gs->map->events.end() && it->earlierThanOrEqual(ev))
  2799. it++;
  2800. gs->map->events.insert(it, ev);
  2801. }
  2802. else
  2803. {
  2804. gs->map->events.pop_front();
  2805. }
  2806. }
  2807. //TODO send only if changed
  2808. UpdateMapEvents ume;
  2809. ume.events = gs->map->events;
  2810. sendAndApply(&ume);
  2811. }
  2812. void CGameHandler::handleTownEvents(CGTownInstance * town, NewTurn &n)
  2813. {
  2814. town->events.sort(evntCmp);
  2815. while(town->events.size() && town->events.front().firstOccurence == gs->day)
  2816. {
  2817. PlayerColor player = town->tempOwner;
  2818. CCastleEvent ev = town->events.front();
  2819. const PlayerState * pinfo = getPlayerState(player, false);
  2820. if (pinfo //player exists
  2821. && (ev.players & 1<<player.getNum()) //event is enabled to this player
  2822. && ((ev.computerAffected && !pinfo->human)
  2823. || (ev.humanAffected && pinfo->human)))
  2824. {
  2825. // dialog
  2826. InfoWindow iw;
  2827. iw.player = player;
  2828. iw.text.appendRawString(ev.message);
  2829. if (ev.resources.nonZero())
  2830. {
  2831. TResources was = n.res[player];
  2832. n.res[player] += ev.resources;
  2833. n.res[player].amax(0);
  2834. for (int i=0; i<ev.resources.size(); i++)
  2835. if (ev.resources[i] && pinfo->resources[i] != n.res.at(player)[i]) //if resource had changed, we add it to the dialog
  2836. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,n.res.at(player)[i]-was[i],0);
  2837. }
  2838. for (auto & i : ev.buildings)
  2839. {
  2840. if (!town->hasBuilt(i))
  2841. {
  2842. buildStructure(town->id, i, true);
  2843. iw.components.emplace_back(Component::EComponentType::BUILDING, town->subID, i, 0);
  2844. }
  2845. }
  2846. if (!ev.creatures.empty() && !vstd::contains(n.cres, town->id))
  2847. {
  2848. n.cres[town->id].tid = town->id;
  2849. n.cres[town->id].creatures = town->creatures;
  2850. }
  2851. auto & sac = n.cres[town->id];
  2852. for (si32 i=0;i<ev.creatures.size();i++) //creature growths
  2853. {
  2854. if (!town->creatures.at(i).second.empty() && ev.creatures.at(i) > 0)//there is dwelling
  2855. {
  2856. sac.creatures[i].first += ev.creatures.at(i);
  2857. iw.components.emplace_back(Component::EComponentType::CREATURE,
  2858. town->creatures.at(i).second.back(), ev.creatures.at(i), 0);
  2859. }
  2860. }
  2861. sendAndApply(&iw); //show dialog
  2862. }
  2863. if (ev.nextOccurence)
  2864. {
  2865. town->events.pop_front();
  2866. ev.firstOccurence += ev.nextOccurence;
  2867. auto it = town->events.begin();
  2868. while(it != town->events.end() && it->earlierThanOrEqual(ev))
  2869. it++;
  2870. town->events.insert(it, ev);
  2871. }
  2872. else
  2873. {
  2874. town->events.pop_front();
  2875. }
  2876. }
  2877. //TODO send only if changed
  2878. UpdateCastleEvents uce;
  2879. uce.town = town->id;
  2880. uce.events = town->events;
  2881. sendAndApply(&uce);
  2882. }
  2883. bool CGameHandler::complain(const std::string &problem)
  2884. {
  2885. playerMessages->broadcastSystemMessage("Server encountered a problem: " + problem);
  2886. logGlobal->error(problem);
  2887. return true;
  2888. }
  2889. void CGameHandler::showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits)
  2890. {
  2891. //PlayerColor player = getOwner(hid);
  2892. auto upperArmy = dynamic_cast<const CArmedInstance*>(getObj(upobj));
  2893. auto lowerArmy = dynamic_cast<const CArmedInstance*>(getObj(hid));
  2894. assert(lowerArmy);
  2895. assert(upperArmy);
  2896. auto garrisonQuery = std::make_shared<CGarrisonDialogQuery>(this, upperArmy, lowerArmy);
  2897. queries->addQuery(garrisonQuery);
  2898. GarrisonDialog gd;
  2899. gd.hid = hid;
  2900. gd.objid = upobj;
  2901. gd.removableUnits = removableUnits;
  2902. gd.queryID = garrisonQuery->queryID;
  2903. sendAndApply(&gd);
  2904. }
  2905. void CGameHandler::showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId)
  2906. {
  2907. OpenWindow ow;
  2908. ow.window = EOpenWindowMode::THIEVES_GUILD;
  2909. ow.id1 = player.getNum();
  2910. ow.id2 = requestingObjId.getNum();
  2911. sendAndApply(&ow);
  2912. }
  2913. bool CGameHandler::isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2)
  2914. {
  2915. if (id1 == id2)
  2916. return true;
  2917. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  2918. if (!o1 || !o2)
  2919. return true; //arranging stacks within an object should be always allowed
  2920. if (o1 && o2)
  2921. {
  2922. if (o1->ID == Obj::TOWN)
  2923. {
  2924. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  2925. if (t->visitingHero == o2 || t->garrisonHero == o2)
  2926. return true;
  2927. }
  2928. if (o2->ID == Obj::TOWN)
  2929. {
  2930. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  2931. if (t->visitingHero == o1 || t->garrisonHero == o1)
  2932. return true;
  2933. }
  2934. if (o1->ID == Obj::HERO && o2->ID == Obj::HERO)
  2935. {
  2936. const CGHeroInstance *h1 = static_cast<const CGHeroInstance*>(o1);
  2937. const CGHeroInstance *h2 = static_cast<const CGHeroInstance*>(o2);
  2938. // two heroes in same town (garrisoned and visiting)
  2939. if (h1->visitedTown != nullptr && h2->visitedTown != nullptr && h1->visitedTown == h2->visitedTown)
  2940. return true;
  2941. }
  2942. //Ongoing garrison exchange - usually picking from top garison (from o1 to o2), but who knows
  2943. auto dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries->topQuery(o1->tempOwner));
  2944. if (!dialog)
  2945. {
  2946. dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries->topQuery(o2->tempOwner));
  2947. }
  2948. if (dialog)
  2949. {
  2950. auto topArmy = dialog->exchangingArmies.at(0);
  2951. auto bottomArmy = dialog->exchangingArmies.at(1);
  2952. if ((topArmy == o1 && bottomArmy == o2) || (bottomArmy == o1 && topArmy == o2))
  2953. return true;
  2954. }
  2955. }
  2956. return false;
  2957. }
  2958. void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInstance * h)
  2959. {
  2960. using events::ObjectVisitStarted;
  2961. logGlobal->debug("%s visits %s (%d:%d)", h->nodeName(), obj->getObjectName(), obj->ID, obj->subID);
  2962. std::shared_ptr<CObjectVisitQuery> visitQuery;
  2963. auto startVisit = [&](ObjectVisitStarted & event)
  2964. {
  2965. auto visitedObject = obj;
  2966. if(obj->ID == Obj::HERO)
  2967. {
  2968. auto visitedHero = static_cast<const CGHeroInstance *>(obj);
  2969. const auto visitedTown = visitedHero->visitedTown;
  2970. if(visitedTown)
  2971. {
  2972. const bool isEnemy = visitedHero->getOwner() != h->getOwner();
  2973. if(isEnemy && !visitedTown->isBattleOutsideTown(visitedHero))
  2974. visitedObject = visitedTown;
  2975. }
  2976. }
  2977. visitQuery = std::make_shared<CObjectVisitQuery>(this, visitedObject, h, visitedObject->visitablePos());
  2978. queries->addQuery(visitQuery); //TODO real visit pos
  2979. HeroVisit hv;
  2980. hv.objId = obj->id;
  2981. hv.heroId = h->id;
  2982. hv.player = h->tempOwner;
  2983. hv.starting = true;
  2984. sendAndApply(&hv);
  2985. obj->onHeroVisit(h);
  2986. };
  2987. ObjectVisitStarted::defaultExecute(serverEventBus.get(), startVisit, h->tempOwner, h->id, obj->id);
  2988. if(visitQuery)
  2989. queries->popIfTop(visitQuery); //visit ends here if no queries were created
  2990. }
  2991. void CGameHandler::objectVisitEnded(const CObjectVisitQuery & query)
  2992. {
  2993. using events::ObjectVisitEnded;
  2994. logGlobal->debug("%s visit ends.\n", query.visitingHero->nodeName());
  2995. auto endVisit = [&](ObjectVisitEnded & event)
  2996. {
  2997. HeroVisit hv;
  2998. hv.player = event.getPlayer();
  2999. hv.heroId = event.getHero();
  3000. hv.starting = false;
  3001. sendAndApply(&hv);
  3002. };
  3003. //TODO: ObjectVisitEnded should also have id of visited object,
  3004. //but this requires object being deleted only by `removeAfterVisit()` but not `removeObject()`
  3005. ObjectVisitEnded::defaultExecute(serverEventBus.get(), endVisit, query.players.front(), query.visitingHero->id);
  3006. }
  3007. bool CGameHandler::buildBoat(ObjectInstanceID objid, PlayerColor playerID)
  3008. {
  3009. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  3010. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  3011. {
  3012. complain("Cannot build boat in this shipyard!");
  3013. return false;
  3014. }
  3015. TResources boatCost;
  3016. obj->getBoatCost(boatCost);
  3017. TResources aviable = getPlayerState(playerID)->resources;
  3018. if (!aviable.canAfford(boatCost))
  3019. {
  3020. complain("Not enough resources to build a boat!");
  3021. return false;
  3022. }
  3023. int3 tile = obj->bestLocation();
  3024. if (!gs->map->isInTheMap(tile))
  3025. {
  3026. complain("Cannot find appropriate tile for a boat!");
  3027. return false;
  3028. }
  3029. giveResources(playerID, -boatCost);
  3030. createObject(tile, Obj::BOAT, obj->getBoatType().getNum());
  3031. return true;
  3032. }
  3033. void CGameHandler::checkVictoryLossConditions(const std::set<PlayerColor> & playerColors)
  3034. {
  3035. for (auto playerColor : playerColors)
  3036. {
  3037. if (getPlayerState(playerColor, false))
  3038. checkVictoryLossConditionsForPlayer(playerColor);
  3039. }
  3040. }
  3041. void CGameHandler::checkVictoryLossConditionsForAll()
  3042. {
  3043. std::set<PlayerColor> playerColors;
  3044. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  3045. {
  3046. playerColors.insert(PlayerColor(i));
  3047. }
  3048. checkVictoryLossConditions(playerColors);
  3049. }
  3050. void CGameHandler::checkVictoryLossConditionsForPlayer(PlayerColor player)
  3051. {
  3052. const PlayerState * p = getPlayerState(player);
  3053. if(!p || p->status != EPlayerStatus::INGAME) return;
  3054. auto victoryLossCheckResult = gs->checkForVictoryAndLoss(player);
  3055. if (victoryLossCheckResult.victory() || victoryLossCheckResult.loss())
  3056. {
  3057. InfoWindow iw;
  3058. getVictoryLossMessage(player, victoryLossCheckResult, iw);
  3059. sendAndApply(&iw);
  3060. PlayerEndsGame peg;
  3061. peg.player = player;
  3062. peg.victoryLossCheckResult = victoryLossCheckResult;
  3063. sendAndApply(&peg);
  3064. if (victoryLossCheckResult.victory())
  3065. {
  3066. //one player won -> all enemies lost
  3067. for (auto i = gs->players.cbegin(); i!=gs->players.cend(); i++)
  3068. {
  3069. if (i->first != player && getPlayerState(i->first)->status == EPlayerStatus::INGAME)
  3070. {
  3071. peg.player = i->first;
  3072. peg.victoryLossCheckResult = getPlayerRelations(player, i->first) == PlayerRelations::ALLIES ?
  3073. victoryLossCheckResult : victoryLossCheckResult.invert(); // ally of winner
  3074. InfoWindow iw;
  3075. getVictoryLossMessage(player, peg.victoryLossCheckResult, iw);
  3076. iw.player = i->first;
  3077. sendAndApply(&iw);
  3078. sendAndApply(&peg);
  3079. }
  3080. }
  3081. if(p->human)
  3082. {
  3083. lobby->state = EServerState::GAMEPLAY_ENDED;
  3084. }
  3085. }
  3086. else
  3087. {
  3088. //copy heroes vector to avoid iterator invalidation as removal change PlayerState
  3089. auto hlp = p->heroes;
  3090. for (auto h : hlp) //eliminate heroes
  3091. {
  3092. if (h.get())
  3093. removeObject(h);
  3094. }
  3095. //player lost -> all his objects become unflagged (neutral)
  3096. for (auto obj : gs->map->objects) //unflag objs
  3097. {
  3098. if (obj.get() && obj->tempOwner == player)
  3099. setOwner(obj, PlayerColor::NEUTRAL);
  3100. }
  3101. //eliminating one player may cause victory of another:
  3102. std::set<PlayerColor> playerColors;
  3103. //do not copy player state (CBonusSystemNode) by value
  3104. for (auto &p : gs->players) //players may have different colors, iterate over players and not integers
  3105. {
  3106. if (p.first != player)
  3107. playerColors.insert(p.first);
  3108. }
  3109. //notify all players
  3110. for (auto pc : playerColors)
  3111. {
  3112. if (getPlayerState(pc)->status == EPlayerStatus::INGAME)
  3113. {
  3114. InfoWindow iw;
  3115. getVictoryLossMessage(player, victoryLossCheckResult.invert(), iw);
  3116. iw.player = pc;
  3117. sendAndApply(&iw);
  3118. }
  3119. }
  3120. checkVictoryLossConditions(playerColors);
  3121. }
  3122. auto playerInfo = getPlayerState(gs->currentPlayer, false);
  3123. // If we are called before the actual game start, there might be no current player
  3124. if (playerInfo && playerInfo->status != EPlayerStatus::INGAME)
  3125. {
  3126. // If player making turn has lost his turn must be over as well
  3127. states.setFlag(gs->currentPlayer, &PlayerStatus::makingTurn, false);
  3128. }
  3129. }
  3130. }
  3131. void CGameHandler::getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const
  3132. {
  3133. out.player = player;
  3134. out.text = victoryLossCheckResult.messageToSelf;
  3135. out.text.replaceLocalString(EMetaText::COLOR, player.getNum());
  3136. out.components.emplace_back(Component::EComponentType::FLAG, player.getNum(), 0, 0);
  3137. }
  3138. bool CGameHandler::dig(const CGHeroInstance *h)
  3139. {
  3140. if (h->diggingStatus() != EDiggingStatus::CAN_DIG) //checks for terrain and movement
  3141. COMPLAIN_RETF("Hero cannot dig (error code %d)!", h->diggingStatus());
  3142. createObject(h->visitablePos(), Obj::HOLE, 0 );
  3143. //take MPs
  3144. SetMovePoints smp;
  3145. smp.hid = h->id;
  3146. smp.val = 0;
  3147. sendAndApply(&smp);
  3148. InfoWindow iw;
  3149. iw.type = EInfoWindowMode::AUTO;
  3150. iw.player = h->tempOwner;
  3151. if (gs->map->grailPos == h->visitablePos())
  3152. {
  3153. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  3154. iw.text.appendLocalString(EMetaText::ART_NAMES, ArtifactID::GRAIL);
  3155. iw.soundID = soundBase::ULTIMATEARTIFACT;
  3156. giveHeroNewArtifact(h, VLC->arth->objects[ArtifactID::GRAIL], ArtifactPosition::FIRST_AVAILABLE); //give grail
  3157. sendAndApply(&iw);
  3158. iw.soundID = soundBase::invalid;
  3159. iw.components.emplace_back(Component::EComponentType::ARTIFACT, ArtifactID::GRAIL, 0, 0);
  3160. iw.text.clear();
  3161. iw.text.appendLocalString(EMetaText::ART_DESCR, ArtifactID::GRAIL);
  3162. sendAndApply(&iw);
  3163. }
  3164. else
  3165. {
  3166. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  3167. iw.soundID = soundBase::Dig;
  3168. sendAndApply(&iw);
  3169. }
  3170. return true;
  3171. }
  3172. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  3173. {
  3174. if (!t.visitableObjects.empty())
  3175. {
  3176. //to prevent self-visiting heroes on space press
  3177. if (t.visitableObjects.back() != h)
  3178. objectVisited(t.visitableObjects.back(), h);
  3179. else if (t.visitableObjects.size() > 1)
  3180. objectVisited(*(t.visitableObjects.end()-2),h);
  3181. }
  3182. }
  3183. bool CGameHandler::sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count)
  3184. {
  3185. if (!hero)
  3186. COMPLAIN_RET("You need hero to sacrifice creature!");
  3187. int expSum = 0;
  3188. auto finish = [this, &hero, &expSum]()
  3189. {
  3190. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  3191. };
  3192. for(int i = 0; i < slot.size(); ++i)
  3193. {
  3194. int oldCount = hero->getStackCount(slot[i]);
  3195. if(oldCount < (int)count[i])
  3196. {
  3197. finish();
  3198. COMPLAIN_RET("Not enough creatures to sacrifice!")
  3199. }
  3200. else if(oldCount == count[i] && hero->stacksCount() == 1 && hero->needsLastStack())
  3201. {
  3202. finish();
  3203. COMPLAIN_RET("Cannot sacrifice last creature!");
  3204. }
  3205. int crid = hero->getStack(slot[i]).type->getId();
  3206. changeStackCount(StackLocation(hero, slot[i]), -(TQuantity)count[i]);
  3207. int dump, exp;
  3208. market->getOffer(crid, 0, dump, exp, EMarketMode::CREATURE_EXP);
  3209. exp *= count[i];
  3210. expSum += exp;
  3211. }
  3212. finish();
  3213. return true;
  3214. }
  3215. bool CGameHandler::sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactPosition> & slot)
  3216. {
  3217. if (!hero)
  3218. COMPLAIN_RET("You need hero to sacrifice artifact!");
  3219. int expSum = 0;
  3220. auto finish = [this, &hero, &expSum]()
  3221. {
  3222. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  3223. };
  3224. for(int i = 0; i < slot.size(); ++i)
  3225. {
  3226. ArtifactLocation al(hero, slot[i]);
  3227. const CArtifactInstance * a = al.getArt();
  3228. if(!a)
  3229. {
  3230. finish();
  3231. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  3232. }
  3233. const CArtifactInstance * art = hero->getArt(slot[i]);
  3234. if(!art)
  3235. {
  3236. finish();
  3237. COMPLAIN_RET("No artifact at position to sacrifice!");
  3238. }
  3239. si32 typId = art->artType->getId();
  3240. int dmp, expToGive;
  3241. m->getOffer(typId, 0, dmp, expToGive, EMarketMode::ARTIFACT_EXP);
  3242. expSum += expToGive;
  3243. removeArtifact(al);
  3244. }
  3245. finish();
  3246. return true;
  3247. }
  3248. bool CGameHandler::insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count)
  3249. {
  3250. if (sl.army->hasStackAtSlot(sl.slot))
  3251. COMPLAIN_RET("Slot is already taken!");
  3252. if (!sl.slot.validSlot())
  3253. COMPLAIN_RET("Cannot insert stack to that slot!");
  3254. InsertNewStack ins;
  3255. ins.army = sl.army->id;
  3256. ins.slot = sl.slot;
  3257. ins.type = c->getId();
  3258. ins.count = count;
  3259. sendAndApply(&ins);
  3260. return true;
  3261. }
  3262. bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval)
  3263. {
  3264. if (!sl.army->hasStackAtSlot(sl.slot))
  3265. COMPLAIN_RET("Cannot find a stack to erase");
  3266. if (sl.army->stacksCount() == 1 //from the last stack
  3267. && sl.army->needsLastStack() //that must be left
  3268. && !forceRemoval) //ignore above conditions if we are forcing removal
  3269. {
  3270. COMPLAIN_RET("Cannot erase the last stack!");
  3271. }
  3272. EraseStack es;
  3273. es.army = sl.army->id;
  3274. es.slot = sl.slot;
  3275. sendAndApply(&es);
  3276. return true;
  3277. }
  3278. bool CGameHandler::changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue)
  3279. {
  3280. TQuantity currentCount = sl.army->getStackCount(sl.slot);
  3281. if ((absoluteValue && count < 0)
  3282. || (!absoluteValue && -count > currentCount))
  3283. {
  3284. COMPLAIN_RET("Cannot take more stacks than present!");
  3285. }
  3286. if ((currentCount == -count && !absoluteValue)
  3287. || (!count && absoluteValue))
  3288. {
  3289. eraseStack(sl);
  3290. }
  3291. else
  3292. {
  3293. ChangeStackCount csc;
  3294. csc.army = sl.army->id;
  3295. csc.slot = sl.slot;
  3296. csc.count = count;
  3297. csc.absoluteValue = absoluteValue;
  3298. sendAndApply(&csc);
  3299. }
  3300. return true;
  3301. }
  3302. bool CGameHandler::addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count)
  3303. {
  3304. const CCreature *slotC = sl.army->getCreature(sl.slot);
  3305. if (!slotC) //slot is empty
  3306. insertNewStack(sl, c, count);
  3307. else if (c == slotC)
  3308. changeStackCount(sl, count);
  3309. else
  3310. {
  3311. COMPLAIN_RET("Cannot add " + c->getNamePluralTranslated() + " to slot " + boost::lexical_cast<std::string>(sl.slot) + "!");
  3312. }
  3313. return true;
  3314. }
  3315. void CGameHandler::tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging)
  3316. {
  3317. if (removeObjWhenFinished)
  3318. removeAfterVisit(src);
  3319. if (!src->canBeMergedWith(*dst, allowMerging))
  3320. {
  3321. if (allowMerging) //do that, add all matching creatures.
  3322. {
  3323. bool cont = true;
  3324. while (cont)
  3325. {
  3326. for (auto i = src->stacks.begin(); i != src->stacks.end(); i++)//while there are unmoved creatures
  3327. {
  3328. SlotID pos = dst->getSlotFor(i->second->type);
  3329. if (pos.validSlot())
  3330. {
  3331. moveStack(StackLocation(src, i->first), StackLocation(dst, pos));
  3332. cont = true;
  3333. break; //or iterator crashes
  3334. }
  3335. cont = false;
  3336. }
  3337. }
  3338. }
  3339. showGarrisonDialog(src->id, dst->id, true); //show garrison window and optionally remove ourselves from map when player ends
  3340. }
  3341. else //merge
  3342. {
  3343. moveArmy(src, dst, allowMerging);
  3344. }
  3345. }
  3346. bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count)
  3347. {
  3348. if (!src.army->hasStackAtSlot(src.slot))
  3349. COMPLAIN_RET("No stack to move!");
  3350. if (dst.army->hasStackAtSlot(dst.slot) && dst.army->getCreature(dst.slot) != src.army->getCreature(src.slot))
  3351. COMPLAIN_RET("Cannot move: stack of different type at destination pos!");
  3352. if (!dst.slot.validSlot())
  3353. COMPLAIN_RET("Cannot move stack to that slot!");
  3354. if (count == -1)
  3355. {
  3356. count = src.army->getStackCount(src.slot);
  3357. }
  3358. if (src.army != dst.army //moving away
  3359. && count == src.army->getStackCount(src.slot) //all creatures
  3360. && src.army->stacksCount() == 1 //from the last stack
  3361. && src.army->needsLastStack()) //that must be left
  3362. {
  3363. COMPLAIN_RET("Cannot move away the last creature!");
  3364. }
  3365. RebalanceStacks rs;
  3366. rs.srcArmy = src.army->id;
  3367. rs.dstArmy = dst.army->id;
  3368. rs.srcSlot = src.slot;
  3369. rs.dstSlot = dst.slot;
  3370. rs.count = count;
  3371. sendAndApply(&rs);
  3372. return true;
  3373. }
  3374. void CGameHandler::castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos)
  3375. {
  3376. const CSpell * s = spellID.toSpell();
  3377. if(!s)
  3378. return;
  3379. AdventureSpellCastParameters p;
  3380. p.caster = caster;
  3381. p.pos = pos;
  3382. s->adventureCast(spellEnv, p);
  3383. }
  3384. bool CGameHandler::swapStacks(const StackLocation & sl1, const StackLocation & sl2)
  3385. {
  3386. if(!sl1.army->hasStackAtSlot(sl1.slot))
  3387. {
  3388. return moveStack(sl2, sl1);
  3389. }
  3390. else if(!sl2.army->hasStackAtSlot(sl2.slot))
  3391. {
  3392. return moveStack(sl1, sl2);
  3393. }
  3394. else
  3395. {
  3396. SwapStacks ss;
  3397. ss.srcArmy = sl1.army->id;
  3398. ss.dstArmy = sl2.army->id;
  3399. ss.srcSlot = sl1.slot;
  3400. ss.dstSlot = sl2.slot;
  3401. sendAndApply(&ss);
  3402. return true;
  3403. }
  3404. }
  3405. bool CGameHandler::giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos)
  3406. {
  3407. assert(a->artType);
  3408. ArtifactLocation al(h, ArtifactPosition::PRE_FIRST);
  3409. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  3410. {
  3411. al.slot = ArtifactUtils::getArtAnyPosition(h, a->getTypeId());
  3412. }
  3413. else if(ArtifactUtils::isSlotBackpack(pos))
  3414. {
  3415. al.slot = ArtifactUtils::getArtBackpackPosition(h, a->getTypeId());
  3416. }
  3417. else
  3418. {
  3419. al.slot = pos;
  3420. }
  3421. if(a->canBePutAt(al))
  3422. putArtifact(al, a);
  3423. else
  3424. return false;
  3425. return true;
  3426. }
  3427. void CGameHandler::putArtifact(const ArtifactLocation &al, const CArtifactInstance *a)
  3428. {
  3429. PutArtifact pa;
  3430. pa.art = a;
  3431. pa.al = al;
  3432. sendAndApply(&pa);
  3433. }
  3434. bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos)
  3435. {
  3436. assert(artType);
  3437. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  3438. {
  3439. if(!artType->canBePutAt(h, ArtifactUtils::getArtAnyPosition(h, artType->getId())))
  3440. COMPLAIN_RET("Cannot put artifact in that slot!");
  3441. }
  3442. else if(ArtifactUtils::isSlotBackpack(pos))
  3443. {
  3444. if(!artType->canBePutAt(h, ArtifactUtils::getArtBackpackPosition(h, artType->getId())))
  3445. COMPLAIN_RET("Cannot put artifact in that slot!");
  3446. }
  3447. else
  3448. {
  3449. COMPLAIN_RET_FALSE_IF(!artType->canBePutAt(h, pos, false), "Cannot put artifact in that slot!");
  3450. }
  3451. auto * newArtInst = new CArtifactInstance();
  3452. newArtInst->artType = artType; // *NOT* via settype -> all bonus-related stuff must be done by NewArtifact apply
  3453. NewArtifact na;
  3454. na.art = newArtInst;
  3455. sendAndApply(&na); // -> updates newArtInst!!!
  3456. if(giveHeroArtifact(h, newArtInst, pos))
  3457. return true;
  3458. else
  3459. return false;
  3460. }
  3461. void CGameHandler::spawnWanderingMonsters(CreatureID creatureID)
  3462. {
  3463. std::vector<int3>::iterator tile;
  3464. std::vector<int3> tiles;
  3465. getFreeTiles(tiles);
  3466. ui32 amount = (ui32)tiles.size() / 200; //Chance is 0.5% for each tile
  3467. RandomGeneratorUtil::randomShuffle(tiles, getRandomGenerator());
  3468. logGlobal->trace("Spawning wandering monsters. Found %d free tiles. Creature type: %d", tiles.size(), creatureID.num);
  3469. const CCreature *cre = VLC->creh->objects.at(creatureID);
  3470. for (int i = 0; i < (int)amount; ++i)
  3471. {
  3472. tile = tiles.begin();
  3473. logGlobal->trace("\tSpawning monster at %s", tile->toString());
  3474. {
  3475. auto count = cre->getRandomAmount(std::rand);
  3476. createObject(*tile, Obj::MONSTER, creatureID);
  3477. auto monsterId = getTopObj(*tile)->id;
  3478. setObjProperty(monsterId, ObjProperty::MONSTER_COUNT, count);
  3479. setObjProperty(monsterId, ObjProperty::MONSTER_POWER, (si64)1000*count);
  3480. }
  3481. tiles.erase(tile); //not use it again
  3482. }
  3483. }
  3484. void CGameHandler::synchronizeArtifactHandlerLists()
  3485. {
  3486. UpdateArtHandlerLists uahl;
  3487. uahl.treasures = VLC->arth->treasures;
  3488. uahl.minors = VLC->arth->minors;
  3489. uahl.majors = VLC->arth->majors;
  3490. uahl.relics = VLC->arth->relics;
  3491. sendAndApply(&uahl);
  3492. }
  3493. bool CGameHandler::isValidObject(const CGObjectInstance *obj) const
  3494. {
  3495. return vstd::contains(gs->map->objects, obj);
  3496. }
  3497. bool CGameHandler::isBlockedByQueries(const CPack *pack, PlayerColor player)
  3498. {
  3499. if (!strcmp(typeid(*pack).name(), typeid(PlayerMessage).name()))
  3500. return false;
  3501. auto query = queries->topQuery(player);
  3502. if (query && query->blocksPack(pack))
  3503. {
  3504. complain(boost::str(boost::format(
  3505. "\r\n| Player \"%s\" has to answer queries before attempting any further actions.\r\n| Top Query: \"%s\"\r\n")
  3506. % boost::to_upper_copy<std::string>(player.getStr())
  3507. % query->toString()
  3508. ));
  3509. return true;
  3510. }
  3511. return false;
  3512. }
  3513. void CGameHandler::removeAfterVisit(const CGObjectInstance *object)
  3514. {
  3515. //If the object is being visited, there must be a matching query
  3516. for (const auto &query : queries->allQueries())
  3517. {
  3518. if (auto someVistQuery = std::dynamic_pointer_cast<CObjectVisitQuery>(query))
  3519. {
  3520. if (someVistQuery->visitedObject == object)
  3521. {
  3522. someVistQuery->removeObjectAfterVisit = true;
  3523. return;
  3524. }
  3525. }
  3526. }
  3527. //If we haven't returned so far, there is no query and no visit, call was wrong
  3528. assert("This function needs to be called during the object visit!");
  3529. }
  3530. void CGameHandler::changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide)
  3531. {
  3532. std::unordered_set<int3> tiles;
  3533. getTilesInRange(tiles, center, radius, player, hide? -1 : 1);
  3534. if (hide)
  3535. {
  3536. std::unordered_set<int3> observedTiles; //do not hide tiles observed by heroes. May lead to disastrous AI problems
  3537. auto p = getPlayerState(player);
  3538. for (auto h : p->heroes)
  3539. {
  3540. getTilesInRange(observedTiles, h->getSightCenter(), h->getSightRadius(), h->tempOwner, -1);
  3541. }
  3542. for (auto t : p->towns)
  3543. {
  3544. getTilesInRange(observedTiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, -1);
  3545. }
  3546. for (auto tile : observedTiles)
  3547. vstd::erase_if_present (tiles, tile);
  3548. }
  3549. changeFogOfWar(tiles, player, hide);
  3550. }
  3551. void CGameHandler::changeFogOfWar(std::unordered_set<int3> &tiles, PlayerColor player, bool hide)
  3552. {
  3553. FoWChange fow;
  3554. fow.tiles = tiles;
  3555. fow.player = player;
  3556. fow.mode = hide? 0 : 1;
  3557. sendAndApply(&fow);
  3558. }
  3559. bool CGameHandler::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero)
  3560. {
  3561. if (auto topQuery = queries->topQuery(hero->getOwner()))
  3562. if (auto visit = std::dynamic_pointer_cast<const CObjectVisitQuery>(topQuery))
  3563. return !(visit->visitedObject == obj && visit->visitingHero == hero);
  3564. return true;
  3565. }
  3566. void CGameHandler::setObjProperty(ObjectInstanceID objid, int prop, si64 val)
  3567. {
  3568. SetObjectProperty sob;
  3569. sob.id = objid;
  3570. sob.what = prop;
  3571. sob.val = static_cast<ui32>(val);
  3572. sendAndApply(&sob);
  3573. }
  3574. void CGameHandler::showInfoDialog(InfoWindow * iw)
  3575. {
  3576. sendAndApply(iw);
  3577. }
  3578. void CGameHandler::showInfoDialog(const std::string & msg, PlayerColor player)
  3579. {
  3580. InfoWindow iw;
  3581. iw.player = player;
  3582. iw.text.appendRawString(msg);
  3583. showInfoDialog(&iw);
  3584. }
  3585. CRandomGenerator & CGameHandler::getRandomGenerator()
  3586. {
  3587. return CRandomGenerator::getDefault();
  3588. }
  3589. #if SCRIPTING_ENABLED
  3590. scripting::Pool * CGameHandler::getGlobalContextPool() const
  3591. {
  3592. return serverScripts.get();
  3593. }
  3594. scripting::Pool * CGameHandler::getContextPool() const
  3595. {
  3596. return serverScripts.get();
  3597. }
  3598. #endif
  3599. void CGameHandler::createObject(const int3 & visitablePosition, Obj type, int32_t subtype)
  3600. {
  3601. NewObject no;
  3602. no.ID = type;
  3603. no.subID= subtype;
  3604. no.targetPos = visitablePosition;
  3605. sendAndApply(&no);
  3606. }
  3607. void CGameHandler::deserializationFix()
  3608. {
  3609. //FIXME: pointer to GameHandler itself can't be deserialized at the moment since GameHandler is top-level entity in serialization
  3610. // restore any places that requires such pointer manually
  3611. heroPool->gameHandler = this;
  3612. battles->setGameHandler(this);
  3613. playerMessages->gameHandler = this;
  3614. }
  3615. void CGameHandler::startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, const CGTownInstance *town)
  3616. {
  3617. battles->startBattlePrimary(army1, army2, tile, hero1, hero2, creatureBank, town);
  3618. }
  3619. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank )
  3620. {
  3621. battles->startBattleI(army1, army2, tile, creatureBank);
  3622. }
  3623. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank )
  3624. {
  3625. battles->startBattleI(army1, army2, creatureBank);
  3626. }