CGameHandler.cpp 119 KB

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