CGameHandler.cpp 131 KB

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