CGameHandler.cpp 133 KB

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