CGameHandler.cpp 128 KB

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