CGameHandler.cpp 135 KB

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