CGameHandler.cpp 133 KB

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