CGameHandler.cpp 135 KB

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