CGameHandler.cpp 131 KB

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