CGameHandler.cpp 127 KB

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