CGameHandler.cpp 132 KB

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