CGameHandler.cpp 137 KB

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