CGameHandler.cpp 131 KB

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