CGameHandler.cpp 131 KB

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