CGameHandler.cpp 133 KB

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