CGameHandler.cpp 128 KB

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