CGameHandler.cpp 132 KB

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