CGameHandler.cpp 134 KB

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