CGameHandler.cpp 221 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399
  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 "../lib/filesystem/Filesystem.h"
  12. #include "../lib/filesystem/FileInfo.h"
  13. #include "../lib/int3.h"
  14. #include "../lib/mapping/CCampaignHandler.h"
  15. #include "../lib/ArtifactUtils.h"
  16. #include "../lib/StartInfo.h"
  17. #include "../lib/CModHandler.h"
  18. #include "../lib/CArtHandler.h"
  19. #include "../lib/CBuildingHandler.h"
  20. #include "../lib/CHeroHandler.h"
  21. #include "../lib/pathfinder/CPathfinder.h"
  22. #include "../lib/pathfinder/PathfinderOptions.h"
  23. #include "../lib/pathfinder/TurnInfo.h"
  24. #include "../lib/spells/AbilityCaster.h"
  25. #include "../lib/spells/BonusCaster.h"
  26. #include "../lib/spells/CSpellHandler.h"
  27. #include "../lib/spells/ISpellMechanics.h"
  28. #include "../lib/spells/ObstacleCasterProxy.h"
  29. #include "../lib/spells/Problem.h"
  30. #include "../lib/CGeneralTextHandler.h"
  31. #include "../lib/CTownHandler.h"
  32. #include "../lib/CCreatureHandler.h"
  33. #include "../lib/CGameState.h"
  34. #include "../lib/CStack.h"
  35. #include "../lib/GameSettings.h"
  36. #include "../lib/battle/BattleInfo.h"
  37. #include "../lib/CondSh.h"
  38. #include "ServerNetPackVisitors.h"
  39. #include "../lib/VCMI_Lib.h"
  40. #include "../lib/mapping/CMap.h"
  41. #include "../lib/mapping/CMapService.h"
  42. #include "../lib/rmg/CMapGenOptions.h"
  43. #include "../lib/VCMIDirs.h"
  44. #include "../lib/ScopeGuard.h"
  45. #include "../lib/CSoundBase.h"
  46. #include "../lib/TerrainHandler.h"
  47. #include "CGameHandler.h"
  48. #include "ServerSpellCastEnvironment.h"
  49. #include "CVCMIServer.h"
  50. #include "../lib/CCreatureSet.h"
  51. #include "../lib/CThreadHelper.h"
  52. #include "../lib/GameConstants.h"
  53. #include "../lib/registerTypes/RegisterTypes.h"
  54. #include "../lib/serializer/CTypeList.h"
  55. #include "../lib/serializer/Connection.h"
  56. #include "../lib/serializer/Cast.h"
  57. #include "../lib/serializer/JsonSerializer.h"
  58. #include "../lib/ScriptHandler.h"
  59. #include "vstd/CLoggerBase.h"
  60. #include <memory>
  61. #include <vcmi/events/EventBus.h>
  62. #include <vcmi/events/GenericEvents.h>
  63. #include <vcmi/events/AdventureEvents.h>
  64. #ifndef _MSC_VER
  65. #include <boost/thread/xtime.hpp>
  66. #endif
  67. #define COMPLAIN_RET_IF(cond, txt) do {if (cond){complain(txt); return;}} while(0)
  68. #define COMPLAIN_RET_FALSE_IF(cond, txt) do {if (cond){complain(txt); return false;}} while(0)
  69. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  70. #define COMPLAIN_RETF(txt, FORMAT) {complain(boost::str(boost::format(txt) % FORMAT)); return false;}
  71. CondSh<bool> battleMadeAction(false);
  72. CondSh<BattleResult *> battleResult(nullptr);
  73. template <typename T> class CApplyOnGH;
  74. class CBaseForGHApply
  75. {
  76. public:
  77. virtual bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const =0;
  78. virtual ~CBaseForGHApply(){}
  79. template<typename U> static CBaseForGHApply *getApplier(const U * t=nullptr)
  80. {
  81. return new CApplyOnGH<U>();
  82. }
  83. };
  84. template <typename T> class CApplyOnGH : public CBaseForGHApply
  85. {
  86. public:
  87. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  88. {
  89. T *ptr = static_cast<T*>(pack);
  90. try
  91. {
  92. ApplyGhNetPackVisitor applier(*gh, *gs);
  93. ptr->visit(applier);
  94. return applier.getResult();
  95. }
  96. catch(ExceptionNotAllowedAction & e)
  97. {
  98. (void)e;
  99. return false;
  100. }
  101. catch(...)
  102. {
  103. throw;
  104. }
  105. }
  106. };
  107. template <>
  108. class CApplyOnGH<CPack> : public CBaseForGHApply
  109. {
  110. public:
  111. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  112. {
  113. logGlobal->error("Cannot apply on GH plain CPack!");
  114. assert(0);
  115. return false;
  116. }
  117. };
  118. static inline double distance(int3 a, int3 b)
  119. {
  120. return std::sqrt((double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
  121. }
  122. static void giveExp(BattleResult &r)
  123. {
  124. if (r.winner > 1)
  125. {
  126. // draw
  127. return;
  128. }
  129. r.exp[0] = 0;
  130. r.exp[1] = 0;
  131. for (auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  132. {
  133. r.exp[r.winner] += VLC->creh->objects.at(i->first)->valOfBonuses(BonusType::STACK_HEALTH) * i->second;
  134. }
  135. }
  136. static void summonGuardiansHelper(std::vector<BattleHex> & output, const BattleHex & targetPosition, ui8 side, bool targetIsTwoHex) //return hexes for summoning two hex monsters in output, target = unit to guard
  137. {
  138. int x = targetPosition.getX();
  139. int y = targetPosition.getY();
  140. const bool targetIsAttacker = side == BattleSide::ATTACKER;
  141. if (targetIsAttacker) //handle front guardians, TODO: should we handle situation when units start battle near opposite side of the battlefield? Cannot happen in normal H3...
  142. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  143. else
  144. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  145. //guardian spawn locations for four default position cases for attacker and defender, non-default starting location for att and def is handled in first two if's
  146. if (targetIsAttacker && ((y % 2 == 0) || (x > 1)))
  147. {
  148. if (targetIsTwoHex && (y % 2 == 1) && (x == 2)) //handle exceptional case
  149. {
  150. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  151. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  152. }
  153. else
  154. { //add back-side guardians for two-hex target, side guardians for one-hex
  155. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_LEFT : BattleHex::EDir::TOP_RIGHT, false), output);
  156. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_LEFT : BattleHex::EDir::BOTTOM_RIGHT, false), output);
  157. if (!targetIsTwoHex && x > 2) //back guard for one-hex
  158. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false), output);
  159. else if (targetIsTwoHex)//front-side guardians for two-hex target
  160. {
  161. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  162. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  163. if (x > 3) //back guard for two-hex
  164. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  165. }
  166. }
  167. }
  168. else if (!targetIsAttacker && ((y % 2 == 1) || (x < GameConstants::BFIELD_WIDTH - 2)))
  169. {
  170. if (targetIsTwoHex && (y % 2 == 0) && (x == GameConstants::BFIELD_WIDTH - 3)) //handle exceptional case... equivalent for above for defender side
  171. {
  172. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  173. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  174. }
  175. else
  176. {
  177. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_RIGHT : BattleHex::EDir::TOP_LEFT, false), output);
  178. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_RIGHT : BattleHex::EDir::BOTTOM_LEFT, false), output);
  179. if (!targetIsTwoHex && x < GameConstants::BFIELD_WIDTH - 3)
  180. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  181. else if (targetIsTwoHex)
  182. {
  183. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  184. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  185. if (x < GameConstants::BFIELD_WIDTH - 4)
  186. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  187. }
  188. }
  189. }
  190. else if (!targetIsAttacker && y % 2 == 0)
  191. {
  192. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  193. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  194. }
  195. else if (targetIsAttacker && y % 2 == 1)
  196. {
  197. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  198. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  199. }
  200. }
  201. PlayerStatus PlayerStatuses::operator[](PlayerColor player)
  202. {
  203. boost::unique_lock<boost::mutex> l(mx);
  204. if (players.find(player) != players.end())
  205. {
  206. return players.at(player);
  207. }
  208. else
  209. {
  210. throw std::runtime_error("No such player!");
  211. }
  212. }
  213. void PlayerStatuses::addPlayer(PlayerColor player)
  214. {
  215. boost::unique_lock<boost::mutex> l(mx);
  216. players[player];
  217. }
  218. bool PlayerStatuses::checkFlag(PlayerColor player, bool PlayerStatus::*flag)
  219. {
  220. boost::unique_lock<boost::mutex> l(mx);
  221. if (players.find(player) != players.end())
  222. {
  223. return players[player].*flag;
  224. }
  225. else
  226. {
  227. throw std::runtime_error("No such player!");
  228. }
  229. }
  230. void PlayerStatuses::setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val)
  231. {
  232. boost::unique_lock<boost::mutex> l(mx);
  233. if (players.find(player) != players.end())
  234. {
  235. players[player].*flag = val;
  236. }
  237. else
  238. {
  239. throw std::runtime_error("No such player!");
  240. }
  241. cv.notify_all();
  242. }
  243. template <typename T>
  244. void callWith(std::vector<T> args, std::function<void(T)> fun, ui32 which)
  245. {
  246. fun(args[which]);
  247. }
  248. const Services * CGameHandler::services() const
  249. {
  250. return VLC;
  251. }
  252. const CGameHandler::BattleCb * CGameHandler::battle() const
  253. {
  254. return this;
  255. }
  256. const CGameHandler::GameCb * CGameHandler::game() const
  257. {
  258. return this;
  259. }
  260. vstd::CLoggerBase * CGameHandler::logger() const
  261. {
  262. return logGlobal;
  263. }
  264. events::EventBus * CGameHandler::eventBus() const
  265. {
  266. return serverEventBus.get();
  267. }
  268. void CGameHandler::levelUpHero(const CGHeroInstance * hero, SecondarySkill skill)
  269. {
  270. changeSecSkill(hero, skill, 1, 0);
  271. expGiven(hero);
  272. }
  273. void CGameHandler::levelUpHero(const CGHeroInstance * hero)
  274. {
  275. // required exp for at least 1 lvl-up hasn't been reached
  276. if (!hero->gainsLevel())
  277. {
  278. return;
  279. }
  280. // give primary skill
  281. logGlobal->trace("%s got level %d", hero->getNameTranslated(), hero->level);
  282. auto primarySkill = hero->nextPrimarySkill(getRandomGenerator());
  283. SetPrimSkill sps;
  284. sps.id = hero->id;
  285. sps.which = primarySkill;
  286. sps.abs = false;
  287. sps.val = 1;
  288. sendAndApply(&sps);
  289. PrepareHeroLevelUp pre;
  290. pre.heroId = hero->id;
  291. sendAndApply(&pre);
  292. HeroLevelUp hlu;
  293. hlu.player = hero->tempOwner;
  294. hlu.heroId = hero->id;
  295. hlu.primskill = primarySkill;
  296. hlu.skills = pre.skills;
  297. if (hlu.skills.size() == 0)
  298. {
  299. sendAndApply(&hlu);
  300. levelUpHero(hero);
  301. }
  302. else if (hlu.skills.size() == 1)
  303. {
  304. sendAndApply(&hlu);
  305. levelUpHero(hero, pre.skills.front());
  306. }
  307. else if (hlu.skills.size() > 1)
  308. {
  309. auto levelUpQuery = std::make_shared<CHeroLevelUpDialogQuery>(this, hlu, hero);
  310. hlu.queryID = levelUpQuery->queryID;
  311. queries.addQuery(levelUpQuery);
  312. sendAndApply(&hlu);
  313. //level up will be called on query reply
  314. }
  315. }
  316. void CGameHandler::levelUpCommander (const CCommanderInstance * c, int skill)
  317. {
  318. SetCommanderProperty scp;
  319. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  320. if (hero)
  321. scp.heroid = hero->id;
  322. else
  323. {
  324. complain ("Commander is not led by hero!");
  325. return;
  326. }
  327. scp.accumulatedBonus.subtype = 0;
  328. scp.accumulatedBonus.additionalInfo = 0;
  329. scp.accumulatedBonus.duration = BonusDuration::PERMANENT;
  330. scp.accumulatedBonus.turnsRemain = 0;
  331. scp.accumulatedBonus.source = BonusSource::COMMANDER;
  332. scp.accumulatedBonus.valType = BonusValueType::BASE_NUMBER;
  333. if (skill <= ECommander::SPELL_POWER)
  334. {
  335. scp.which = SetCommanderProperty::BONUS;
  336. auto difference = [](std::vector< std::vector <ui8> > skillLevels, std::vector <ui8> secondarySkills, int skill)->int
  337. {
  338. int s = std::min (skill, (int)ECommander::SPELL_POWER); //spell power level controls also casts and resistance
  339. return skillLevels.at(skill).at(secondarySkills.at(s)) - (secondarySkills.at(s) ? skillLevels.at(skill).at(secondarySkills.at(s)-1) : 0);
  340. };
  341. switch (skill)
  342. {
  343. case ECommander::ATTACK:
  344. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  345. scp.accumulatedBonus.subtype = PrimarySkill::ATTACK;
  346. break;
  347. case ECommander::DEFENSE:
  348. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  349. scp.accumulatedBonus.subtype = PrimarySkill::DEFENSE;
  350. break;
  351. case ECommander::HEALTH:
  352. scp.accumulatedBonus.type = BonusType::STACK_HEALTH;
  353. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  354. break;
  355. case ECommander::DAMAGE:
  356. scp.accumulatedBonus.type = BonusType::CREATURE_DAMAGE;
  357. scp.accumulatedBonus.subtype = 0;
  358. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  359. break;
  360. case ECommander::SPEED:
  361. scp.accumulatedBonus.type = BonusType::STACKS_SPEED;
  362. break;
  363. case ECommander::SPELL_POWER:
  364. scp.accumulatedBonus.type = BonusType::MAGIC_RESISTANCE;
  365. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::RESISTANCE);
  366. sendAndApply (&scp); //additional pack
  367. scp.accumulatedBonus.type = BonusType::CREATURE_SPELL_POWER;
  368. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::SPELL_POWER) * 100; //like hero with spellpower = ability level
  369. sendAndApply (&scp); //additional pack
  370. scp.accumulatedBonus.type = BonusType::CASTS;
  371. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::CASTS);
  372. sendAndApply (&scp); //additional pack
  373. scp.accumulatedBonus.type = BonusType::CREATURE_ENCHANT_POWER; //send normally
  374. break;
  375. }
  376. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, skill);
  377. sendAndApply (&scp);
  378. scp.which = SetCommanderProperty::SECONDARY_SKILL;
  379. scp.additionalInfo = skill;
  380. scp.amount = c->secondarySkills.at(skill) + 1;
  381. sendAndApply (&scp);
  382. }
  383. else if (skill >= 100)
  384. {
  385. scp.which = SetCommanderProperty::SPECIAL_SKILL;
  386. scp.accumulatedBonus = *VLC->creh->skillRequirements.at(skill-100).first;
  387. scp.additionalInfo = skill; //unnormalized
  388. sendAndApply (&scp);
  389. }
  390. expGiven(hero);
  391. }
  392. void CGameHandler::levelUpCommander(const CCommanderInstance * c)
  393. {
  394. if (!c->gainsLevel())
  395. {
  396. return;
  397. }
  398. CommanderLevelUp clu;
  399. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  400. if(hero)
  401. {
  402. clu.heroId = hero->id;
  403. clu.player = hero->tempOwner;
  404. }
  405. else
  406. {
  407. complain ("Commander is not led by hero!");
  408. return;
  409. }
  410. //picking sec. skills for choice
  411. for (int i = 0; i <= ECommander::SPELL_POWER; ++i)
  412. {
  413. if (c->secondarySkills.at(i) < ECommander::MAX_SKILL_LEVEL)
  414. clu.skills.push_back(i);
  415. }
  416. int i = 100;
  417. for (auto specialSkill : VLC->creh->skillRequirements)
  418. {
  419. if (c->secondarySkills.at(specialSkill.second.first) == ECommander::MAX_SKILL_LEVEL
  420. && c->secondarySkills.at(specialSkill.second.second) == ECommander::MAX_SKILL_LEVEL
  421. && !vstd::contains (c->specialSKills, i))
  422. clu.skills.push_back (i);
  423. ++i;
  424. }
  425. int skillAmount = static_cast<int>(clu.skills.size());
  426. if (!skillAmount)
  427. {
  428. sendAndApply(&clu);
  429. levelUpCommander(c);
  430. }
  431. else if (skillAmount == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  432. {
  433. sendAndApply(&clu);
  434. levelUpCommander(c, *RandomGeneratorUtil::nextItem(clu.skills, getRandomGenerator()));
  435. }
  436. else if (skillAmount > 1) //apply and ask for secondary skill
  437. {
  438. auto commanderLevelUp = std::make_shared<CCommanderLevelUpDialogQuery>(this, clu, hero);
  439. clu.queryID = commanderLevelUp->queryID;
  440. queries.addQuery(commanderLevelUp);
  441. sendAndApply(&clu);
  442. }
  443. }
  444. void CGameHandler::expGiven(const CGHeroInstance *hero)
  445. {
  446. if (hero->gainsLevel())
  447. levelUpHero(hero);
  448. else if (hero->commander && hero->commander->gainsLevel())
  449. levelUpCommander(hero->commander);
  450. //if (hero->commander && hero->level > hero->commander->level && hero->commander->gainsLevel())
  451. // levelUpCommander(hero->commander);
  452. // else
  453. // levelUpHero(hero);
  454. }
  455. void CGameHandler::changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs)
  456. {
  457. if (which == PrimarySkill::EXPERIENCE) // Check if scenario limit reached
  458. {
  459. if (gs->map->levelLimit != 0)
  460. {
  461. TExpType expLimit = VLC->heroh->reqExp(gs->map->levelLimit);
  462. TExpType resultingExp = abs ? val : hero->exp + val;
  463. if (resultingExp > expLimit)
  464. {
  465. // set given experience to max possible, but don't decrease if hero already over top
  466. abs = true;
  467. val = std::max(expLimit, hero->exp);
  468. InfoWindow iw;
  469. iw.player = hero->tempOwner;
  470. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 1); //can gain no more XP
  471. iw.text.replaceRawString(hero->getNameTranslated());
  472. sendAndApply(&iw);
  473. }
  474. }
  475. }
  476. SetPrimSkill sps;
  477. sps.id = hero->id;
  478. sps.which = which;
  479. sps.abs = abs;
  480. sps.val = val;
  481. sendAndApply(&sps);
  482. //only for exp - hero may level up
  483. if (which == PrimarySkill::EXPERIENCE)
  484. {
  485. if (hero->commander && hero->commander->alive)
  486. {
  487. //FIXME: trim experience according to map limit?
  488. SetCommanderProperty scp;
  489. scp.heroid = hero->id;
  490. scp.which = SetCommanderProperty::EXPERIENCE;
  491. scp.amount = val;
  492. sendAndApply (&scp);
  493. CBonusSystemNode::treeHasChanged();
  494. }
  495. expGiven(hero);
  496. }
  497. }
  498. void CGameHandler::changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs)
  499. {
  500. if(!hero)
  501. {
  502. logGlobal->error("changeSecSkill provided no hero");
  503. return;
  504. }
  505. SetSecSkill sss;
  506. sss.id = hero->id;
  507. sss.which = which;
  508. sss.val = val;
  509. sss.abs = abs;
  510. sendAndApply(&sss);
  511. if (hero->visitedTown)
  512. giveSpells(hero->visitedTown, hero);
  513. }
  514. void CGameHandler::endBattle(int3 tile, const CGHeroInstance * heroAttacker, const CGHeroInstance * heroDefender)
  515. {
  516. LOG_TRACE(logGlobal);
  517. //Fill BattleResult structure with exp info
  518. giveExp(*battleResult.data);
  519. if (battleResult.get()->result == BattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  520. {
  521. if(heroAttacker)
  522. battleResult.data->exp[1] += 500;
  523. if(heroDefender)
  524. battleResult.data->exp[0] += 500;
  525. }
  526. if(heroAttacker)
  527. battleResult.data->exp[0] = heroAttacker->calculateXp(battleResult.data->exp[0]);//scholar skill
  528. if(heroDefender)
  529. battleResult.data->exp[1] = heroDefender->calculateXp(battleResult.data->exp[1]);
  530. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(gs->curB->sides[0].color));
  531. if (!battleQuery)
  532. {
  533. logGlobal->error("Cannot find battle query!");
  534. complain("Player " + boost::lexical_cast<std::string>(gs->curB->sides[0].color) + " has no battle query at the top!");
  535. return;
  536. }
  537. battleQuery->result = std::make_optional(*battleResult.data);
  538. //Check how many battle queries were created (number of players blocked by battle)
  539. const int queriedPlayers = battleQuery ? (int)boost::count(queries.allQueries(), battleQuery) : 0;
  540. finishingBattle = std::make_unique<FinishingBattleHelper>(battleQuery, queriedPlayers);
  541. auto battleDialogQuery = std::make_shared<CBattleDialogQuery>(this, gs->curB);
  542. battleResult.data->queryID = battleDialogQuery->queryID;
  543. queries.addQuery(battleDialogQuery);
  544. //set same battle result for all queries
  545. for(auto q : queries.allQueries())
  546. {
  547. auto otherBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(q);
  548. if(otherBattleQuery)
  549. otherBattleQuery->result = battleQuery->result;
  550. }
  551. sendAndApply(battleResult.data); //after this point casualties objects are destroyed
  552. }
  553. void CGameHandler::endBattleConfirm(const BattleInfo * battleInfo)
  554. {
  555. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(battleInfo->sides.at(0).color));
  556. if(!battleQuery)
  557. {
  558. logGlobal->trace("No battle query, battle end was confirmed by another player");
  559. return;
  560. }
  561. const CArmedInstance *bEndArmy1 = battleInfo->sides.at(0).armyObject;
  562. const CArmedInstance *bEndArmy2 = battleInfo->sides.at(1).armyObject;
  563. const BattleResult::EResult result = battleResult.get()->result;
  564. CasualtiesAfterBattle cab1(bEndArmy1, battleInfo), cab2(bEndArmy2, battleInfo); //calculate casualties before deleting battle
  565. ChangeSpells cs; //for Eagle Eye
  566. if(!finishingBattle->isDraw() && finishingBattle->winnerHero)
  567. {
  568. if (int eagleEyeLevel = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT, -1))
  569. {
  570. double eagleEyeChance = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE, 0);
  571. for(auto & spellId : battleInfo->sides.at(!battleResult.data->winner).usedSpellsHistory)
  572. {
  573. auto spell = spellId.toSpell(VLC->spells());
  574. if(spell && spell->getLevel() <= eagleEyeLevel && !finishingBattle->winnerHero->spellbookContainsSpell(spell->getId()) && getRandomGenerator().nextInt(99) < eagleEyeChance)
  575. cs.spells.insert(spell->getId());
  576. }
  577. }
  578. }
  579. std::vector<const CArtifactInstance *> arts; //display them in window
  580. if(result == BattleResult::NORMAL && !finishingBattle->isDraw() && finishingBattle->winnerHero)
  581. {
  582. auto sendMoveArtifact = [&](const CArtifactInstance *art, MoveArtifact *ma)
  583. {
  584. const auto slot = ArtifactUtils::getArtAnyPosition(finishingBattle->winnerHero, art->getTypeId());
  585. if(slot != ArtifactPosition::PRE_FIRST)
  586. {
  587. arts.push_back(art);
  588. ma->dst = ArtifactLocation(finishingBattle->winnerHero, slot);
  589. if(ArtifactUtils::isSlotBackpack(slot))
  590. ma->askAssemble = false;
  591. sendAndApply(ma);
  592. }
  593. };
  594. if (finishingBattle->loserHero)
  595. {
  596. //TODO: wrap it into a function, somehow (std::variant -_-)
  597. auto artifactsWorn = finishingBattle->loserHero->artifactsWorn;
  598. for (auto artSlot : artifactsWorn)
  599. {
  600. MoveArtifact ma;
  601. ma.src = ArtifactLocation(finishingBattle->loserHero, artSlot.first);
  602. const CArtifactInstance * art = ma.src.getArt();
  603. if (art && !art->artType->isBig() &&
  604. art->artType->getId() != ArtifactID::SPELLBOOK)
  605. // don't move war machines or locked arts (spellbook)
  606. {
  607. sendMoveArtifact(art, &ma);
  608. }
  609. }
  610. for(int slotNumber = finishingBattle->loserHero->artifactsInBackpack.size() - 1; slotNumber >= 0; slotNumber--)
  611. {
  612. //we assume that no big artifacts can be found
  613. MoveArtifact ma;
  614. ma.src = ArtifactLocation(finishingBattle->loserHero,
  615. ArtifactPosition(GameConstants::BACKPACK_START + slotNumber)); //backpack automatically shifts arts to beginning
  616. const CArtifactInstance * art = ma.src.getArt();
  617. if (art->artType->getId() != ArtifactID::GRAIL) //grail may not be won
  618. {
  619. sendMoveArtifact(art, &ma);
  620. }
  621. }
  622. if (finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero?
  623. {
  624. artifactsWorn = finishingBattle->loserHero->commander->artifactsWorn;
  625. for (auto artSlot : artifactsWorn)
  626. {
  627. MoveArtifact ma;
  628. ma.src = ArtifactLocation(finishingBattle->loserHero->commander.get(), artSlot.first);
  629. const CArtifactInstance * art = ma.src.getArt();
  630. if (art && !art->artType->isBig())
  631. {
  632. sendMoveArtifact(art, &ma);
  633. }
  634. }
  635. }
  636. }
  637. for (auto armySlot : battleInfo->sides.at(!battleResult.data->winner).armyObject->stacks)
  638. {
  639. auto artifactsWorn = armySlot.second->artifactsWorn;
  640. for (auto artSlot : artifactsWorn)
  641. {
  642. MoveArtifact ma;
  643. ma.src = ArtifactLocation(armySlot.second, artSlot.first);
  644. const CArtifactInstance * art = ma.src.getArt();
  645. if (art && !art->artType->isBig())
  646. {
  647. sendMoveArtifact(art, &ma);
  648. }
  649. }
  650. }
  651. }
  652. if (arts.size()) //display loot
  653. {
  654. InfoWindow iw;
  655. iw.player = finishingBattle->winnerHero->tempOwner;
  656. iw.text.appendLocalString (EMetaText::GENERAL_TXT, 30); //You have captured enemy artifact
  657. for (auto art : arts) //TODO; separate function to display loot for various ojects?
  658. {
  659. iw.components.emplace_back(
  660. Component::EComponentType::ARTIFACT, art->artType->getId(),
  661. art->artType->getId() == ArtifactID::SPELL_SCROLL? art->getScrollSpellID() : 0, 0);
  662. if (iw.components.size() >= 14)
  663. {
  664. sendAndApply(&iw);
  665. iw.components.clear();
  666. }
  667. }
  668. if (iw.components.size())
  669. {
  670. sendAndApply(&iw);
  671. }
  672. }
  673. //Eagle Eye secondary skill handling
  674. if (!cs.spells.empty())
  675. {
  676. cs.learn = 1;
  677. cs.hid = finishingBattle->winnerHero->id;
  678. InfoWindow iw;
  679. iw.player = finishingBattle->winnerHero->tempOwner;
  680. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
  681. iw.text.replaceRawString(finishingBattle->winnerHero->getNameTranslated());
  682. std::ostringstream names;
  683. for (int i = 0; i < cs.spells.size(); i++)
  684. {
  685. names << "%s";
  686. if (i < cs.spells.size() - 2)
  687. names << ", ";
  688. else if (i < cs.spells.size() - 1)
  689. names << "%s";
  690. }
  691. names << ".";
  692. iw.text.replaceRawString(names.str());
  693. auto it = cs.spells.begin();
  694. for (int i = 0; i < cs.spells.size(); i++, it++)
  695. {
  696. iw.text.replaceLocalString(EMetaText::SPELL_NAME, it->toEnum());
  697. if (i == cs.spells.size() - 2) //we just added pre-last name
  698. iw.text.replaceLocalString(EMetaText::GENERAL_TXT, 141); // " and "
  699. iw.components.emplace_back(Component::EComponentType::SPELL, *it, 0, 0);
  700. }
  701. sendAndApply(&iw);
  702. sendAndApply(&cs);
  703. }
  704. cab1.updateArmy(this);
  705. cab2.updateArmy(this); //take casualties after battle is deleted
  706. if(finishingBattle->loserHero) //remove beaten hero
  707. {
  708. RemoveObject ro(finishingBattle->loserHero->id);
  709. sendAndApply(&ro);
  710. }
  711. if(finishingBattle->isDraw() && finishingBattle->winnerHero) //for draw case both heroes should be removed
  712. {
  713. RemoveObject ro(finishingBattle->winnerHero->id);
  714. sendAndApply(&ro);
  715. }
  716. if(battleResult.data->winner == BattleSide::DEFENDER
  717. && finishingBattle->winnerHero
  718. && finishingBattle->winnerHero->visitedTown
  719. && !finishingBattle->winnerHero->inTownGarrison
  720. && finishingBattle->winnerHero->visitedTown->garrisonHero == finishingBattle->winnerHero)
  721. {
  722. swapGarrisonOnSiege(finishingBattle->winnerHero->visitedTown->id); //return defending visitor from garrison to its rightful place
  723. }
  724. //give exp
  725. if(!finishingBattle->isDraw() && battleResult.data->exp[finishingBattle->winnerSide] && finishingBattle->winnerHero)
  726. changePrimSkill(finishingBattle->winnerHero, PrimarySkill::EXPERIENCE, battleResult.data->exp[finishingBattle->winnerSide]);
  727. BattleResultAccepted raccepted;
  728. raccepted.army1 = const_cast<CArmedInstance*>(bEndArmy1);
  729. raccepted.army2 = const_cast<CArmedInstance*>(bEndArmy2);
  730. raccepted.hero1 = const_cast<CGHeroInstance*>(battleInfo->sides.at(0).hero);
  731. raccepted.hero2 = const_cast<CGHeroInstance*>(battleInfo->sides.at(1).hero);
  732. raccepted.exp[0] = battleResult.data->exp[0];
  733. raccepted.exp[1] = battleResult.data->exp[1];
  734. sendAndApply(&raccepted);
  735. queries.popIfTop(battleQuery);
  736. //--> continuation (battleAfterLevelUp) occurs after level-up queries are handled or on removing query
  737. }
  738. void CGameHandler::battleAfterLevelUp(const BattleResult &result)
  739. {
  740. LOG_TRACE(logGlobal);
  741. if(!finishingBattle)
  742. return;
  743. finishingBattle->remainingBattleQueriesCount--;
  744. logGlobal->trace("Decremented queries count to %d", finishingBattle->remainingBattleQueriesCount);
  745. if (finishingBattle->remainingBattleQueriesCount > 0)
  746. //Battle results will be handled when all battle queries are closed
  747. return;
  748. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  749. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  750. // Still, it looks like a hole.
  751. // Necromancy if applicable.
  752. const CStackBasicDescriptor raisedStack = finishingBattle->winnerHero ? finishingBattle->winnerHero->calculateNecromancy(*battleResult.data) : CStackBasicDescriptor();
  753. // Give raised units to winner and show dialog, if any were raised,
  754. // units will be given after casualties are taken
  755. const SlotID necroSlot = raisedStack.type ? finishingBattle->winnerHero->getSlotFor(raisedStack.type) : SlotID();
  756. if (necroSlot != SlotID())
  757. {
  758. finishingBattle->winnerHero->showNecromancyDialog(raisedStack, getRandomGenerator());
  759. addToSlot(StackLocation(finishingBattle->winnerHero, necroSlot), raisedStack.type, raisedStack.count);
  760. }
  761. BattleResultsApplied resultsApplied;
  762. resultsApplied.player1 = finishingBattle->victor;
  763. resultsApplied.player2 = finishingBattle->loser;
  764. sendAndApply(&resultsApplied);
  765. setBattle(nullptr);
  766. if (visitObjectAfterVictory && result.winner==0 && !finishingBattle->winnerHero->stacks.empty())
  767. {
  768. logGlobal->trace("post-victory visit");
  769. visitObjectOnTile(*getTile(finishingBattle->winnerHero->visitablePos()), finishingBattle->winnerHero);
  770. }
  771. visitObjectAfterVictory = false;
  772. //handle victory/loss of engaged players
  773. std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
  774. checkVictoryLossConditions(playerColors);
  775. if (result.result == BattleResult::SURRENDER || result.result == BattleResult::ESCAPE) //loser has escaped or surrendered
  776. {
  777. SetAvailableHeroes sah;
  778. sah.player = finishingBattle->loser;
  779. sah.hid[0] = finishingBattle->loserHero->subID;
  780. if (result.result == BattleResult::ESCAPE) //retreat
  781. {
  782. sah.army[0].clear();
  783. sah.army[0].setCreature(SlotID(0), finishingBattle->loserHero->type->initialArmy.at(0).creature, 1);
  784. }
  785. if (const CGHeroInstance *another = getPlayerState(finishingBattle->loser)->availableHeroes.at(0))
  786. sah.hid[1] = another->subID;
  787. else
  788. sah.hid[1] = -1;
  789. sendAndApply(&sah);
  790. }
  791. if (result.winner != 2 && finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()
  792. && (!finishingBattle->winnerHero->commander || !finishingBattle->winnerHero->commander->alive))
  793. {
  794. RemoveObject ro(finishingBattle->winnerHero->id);
  795. sendAndApply(&ro);
  796. if (VLC->settings()->getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  797. {
  798. SetAvailableHeroes sah;
  799. sah.player = finishingBattle->victor;
  800. sah.hid[0] = finishingBattle->winnerHero->subID;
  801. sah.army[0].clear();
  802. sah.army[0].setCreature(SlotID(0), finishingBattle->winnerHero->type->initialArmy.at(0).creature, 1);
  803. if (const CGHeroInstance *another = getPlayerState(finishingBattle->victor)->availableHeroes.at(0))
  804. sah.hid[1] = another->subID;
  805. else
  806. sah.hid[1] = -1;
  807. sendAndApply(&sah);
  808. }
  809. }
  810. finishingBattle.reset();
  811. }
  812. void CGameHandler::makeAttack(const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter)
  813. {
  814. if(first && !counter)
  815. handleAttackBeforeCasting(ranged, attacker, defender);
  816. FireShieldInfo fireShield;
  817. BattleAttack bat;
  818. BattleLogMessage blm;
  819. bat.stackAttacking = attacker->unitId();
  820. bat.tile = targetHex;
  821. std::shared_ptr<battle::CUnitState> attackerState = attacker->acquireState();
  822. if(ranged)
  823. bat.flags |= BattleAttack::SHOT;
  824. if(counter)
  825. bat.flags |= BattleAttack::COUNTER;
  826. const int attackerLuck = attacker->luckVal();
  827. if(attackerLuck > 0)
  828. {
  829. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_LUCK_DICE);
  830. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, attackerLuck);
  831. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  832. bat.flags |= BattleAttack::LUCKY;
  833. }
  834. if(attackerLuck < 0)
  835. {
  836. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_LUCK_DICE);
  837. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, -attackerLuck);
  838. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  839. bat.flags |= BattleAttack::UNLUCKY;
  840. }
  841. if (getRandomGenerator().nextInt(99) < attacker->valOfBonuses(BonusType::DOUBLE_DAMAGE_CHANCE))
  842. {
  843. bat.flags |= BattleAttack::DEATH_BLOW;
  844. }
  845. const auto * owner = gs->curB->getHero(attacker->unitOwner());
  846. if(owner)
  847. {
  848. int chance = owner->valOfBonuses(BonusType::BONUS_DAMAGE_CHANCE, attacker->creatureIndex());
  849. if (chance > getRandomGenerator().nextInt(99))
  850. bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
  851. }
  852. int64_t drainedLife = 0;
  853. // only primary target
  854. if(defender->alive())
  855. drainedLife += applyBattleEffects(bat, attackerState, fireShield, defender, distance, false);
  856. //multiple-hex normal attack
  857. std::set<const CStack*> attackedCreatures = gs->curB->getAttackedCreatures(attacker, targetHex, bat.shot()); //creatures other than primary target
  858. for(const CStack * stack : attackedCreatures)
  859. {
  860. if(stack != defender && stack->alive()) //do not hit same stack twice
  861. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  862. }
  863. std::shared_ptr<const Bonus> bonus = attacker->getBonusLocalFirst(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  864. if(bonus && ranged) //TODO: make it work in melee?
  865. {
  866. //this is need for displaying hit animation
  867. bat.flags |= BattleAttack::SPELL_LIKE;
  868. bat.spellID = SpellID(bonus->subtype);
  869. //TODO: should spell override creature`s projectile?
  870. auto spell = bat.spellID.toSpell();
  871. battle::Target target;
  872. target.emplace_back(defender, targetHex);
  873. spells::BattleCast event(gs->curB, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  874. event.setSpellLevel(bonus->val);
  875. auto attackedCreatures = spell->battleMechanics(&event)->getAffectedStacks(target);
  876. //TODO: get exact attacked hex for defender
  877. for(const CStack * stack : attackedCreatures)
  878. {
  879. if(stack != defender && stack->alive()) //do not hit same stack twice
  880. {
  881. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  882. }
  883. }
  884. //now add effect info for all attacked stacks
  885. for (BattleStackAttacked & bsa : bat.bsa)
  886. {
  887. if (bsa.attackerID == attacker->unitId()) //this is our attack and not f.e. fire shield
  888. {
  889. //this is need for displaying affect animation
  890. bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
  891. bsa.spellID = SpellID(bonus->subtype);
  892. }
  893. }
  894. }
  895. attackerState->afterAttack(ranged, counter);
  896. {
  897. UnitChanges info(attackerState->unitId(), UnitChanges::EOperation::RESET_STATE);
  898. attackerState->save(info.data);
  899. bat.attackerChanges.changedStacks.push_back(info);
  900. }
  901. if (drainedLife > 0)
  902. bat.flags |= BattleAttack::LIFE_DRAIN;
  903. sendAndApply(&bat);
  904. {
  905. const bool multipleTargets = bat.bsa.size() > 1;
  906. int64_t totalDamage = 0;
  907. int32_t totalKills = 0;
  908. for(const BattleStackAttacked & bsa : bat.bsa)
  909. {
  910. totalDamage += bsa.damageAmount;
  911. totalKills += bsa.killedAmount;
  912. }
  913. {
  914. MetaString text;
  915. attacker->addText(text, EMetaText::GENERAL_TXT, 376);
  916. attacker->addNameReplacement(text);
  917. text.replaceNumber(totalDamage);
  918. blm.lines.push_back(text);
  919. }
  920. addGenericKilledLog(blm, defender, totalKills, multipleTargets);
  921. }
  922. // drain life effect (as well as log entry) must be applied after the attack
  923. if(drainedLife > 0)
  924. {
  925. MetaString text;
  926. attackerState->addText(text, EMetaText::GENERAL_TXT, 361);
  927. attackerState->addNameReplacement(text, false);
  928. text.replaceNumber(drainedLife);
  929. defender->addNameReplacement(text, true);
  930. blm.lines.push_back(std::move(text));
  931. }
  932. if(!fireShield.empty())
  933. {
  934. //todo: this should be "virtual" spell instead, we only need fire spell school bonus here
  935. const CSpell * fireShieldSpell = SpellID(SpellID::FIRE_SHIELD).toSpell();
  936. int64_t totalDamage = 0;
  937. for(const auto & item : fireShield)
  938. {
  939. const CStack * actor = item.first;
  940. int64_t rawDamage = item.second;
  941. const CGHeroInstance * actorOwner = gs->curB->getHero(actor->unitOwner());
  942. if(actorOwner)
  943. {
  944. rawDamage = fireShieldSpell->adjustRawDamage(actorOwner, attacker, rawDamage);
  945. }
  946. else
  947. {
  948. rawDamage = fireShieldSpell->adjustRawDamage(actor, attacker, rawDamage);
  949. }
  950. totalDamage+=rawDamage;
  951. //FIXME: add custom effect on actor
  952. }
  953. if (totalDamage > 0)
  954. {
  955. BattleStackAttacked bsa;
  956. bsa.flags |= BattleStackAttacked::FIRE_SHIELD;
  957. bsa.stackAttacked = attacker->unitId(); //invert
  958. bsa.attackerID = defender->unitId();
  959. bsa.damageAmount = totalDamage;
  960. attacker->prepareAttacked(bsa, getRandomGenerator());
  961. StacksInjured pack;
  962. pack.stacks.push_back(bsa);
  963. sendAndApply(&pack);
  964. // TODO: this is already implemented in Damage::describeEffect()
  965. {
  966. MetaString text;
  967. text.appendLocalString(EMetaText::GENERAL_TXT, 376);
  968. text.replaceLocalString(EMetaText::SPELL_NAME, SpellID::FIRE_SHIELD);
  969. text.replaceNumber(totalDamage);
  970. blm.lines.push_back(std::move(text));
  971. }
  972. addGenericKilledLog(blm, attacker, bsa.killedAmount, false);
  973. }
  974. }
  975. sendAndApply(&blm);
  976. handleAfterAttackCasting(ranged, attacker, defender);
  977. }
  978. int64_t CGameHandler::applyBattleEffects(BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, int distance, bool secondary)
  979. {
  980. BattleStackAttacked bsa;
  981. if(secondary)
  982. bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
  983. bsa.attackerID = attackerState->unitId();
  984. bsa.stackAttacked = def->unitId();
  985. {
  986. BattleAttackInfo bai(attackerState.get(), def, distance, bat.shot());
  987. bai.deathBlow = bat.deathBlow();
  988. bai.doubleDamage = bat.ballistaDoubleDmg();
  989. bai.luckyStrike = bat.lucky();
  990. bai.unluckyStrike = bat.unlucky();
  991. auto range = gs->curB->calculateDmgRange(bai);
  992. bsa.damageAmount = gs->curB->getActualDamage(range.damage, attackerState->getCount(), getRandomGenerator());
  993. CStack::prepareAttacked(bsa, getRandomGenerator(), bai.defender->acquireState()); //calculate casualties
  994. }
  995. int64_t drainedLife = 0;
  996. //life drain handling
  997. if(attackerState->hasBonusOfType(BonusType::LIFE_DRAIN) && def->isLiving())
  998. {
  999. int64_t toHeal = bsa.damageAmount * attackerState->valOfBonuses(BonusType::LIFE_DRAIN) / 100;
  1000. attackerState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  1001. drainedLife += toHeal;
  1002. }
  1003. //soul steal handling
  1004. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL) && def->isLiving())
  1005. {
  1006. //we can have two bonuses - one with subtype 0 and another with subtype 1
  1007. //try to use permanent first, use only one of two
  1008. for(si32 subtype = 1; subtype >= 0; subtype--)
  1009. {
  1010. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL, subtype))
  1011. {
  1012. int64_t toHeal = bsa.killedAmount * attackerState->valOfBonuses(BonusType::SOUL_STEAL, subtype) * attackerState->getMaxHealth();
  1013. attackerState->heal(toHeal, EHealLevel::OVERHEAL, ((subtype == 0) ? EHealPower::ONE_BATTLE : EHealPower::PERMANENT));
  1014. drainedLife += toHeal;
  1015. break;
  1016. }
  1017. }
  1018. }
  1019. bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
  1020. //fire shield handling
  1021. if(!bat.shot() &&
  1022. !def->isClone() &&
  1023. def->hasBonusOfType(BonusType::FIRE_SHIELD) &&
  1024. !attackerState->hasBonusOfType(BonusType::FIRE_IMMUNITY) &&
  1025. CStack::isMeleeAttackPossible(attackerState.get(), def) // attacked needs to be adjacent to defender for fire shield to trigger (e.g. Dragon Breath attack)
  1026. )
  1027. {
  1028. //TODO: use damage with bonus but without penalties
  1029. auto fireShieldDamage = (std::min<int64_t>(def->getAvailableHealth(), bsa.damageAmount) * def->valOfBonuses(BonusType::FIRE_SHIELD)) / 100;
  1030. fireShield.push_back(std::make_pair(def, fireShieldDamage));
  1031. }
  1032. return drainedLife;
  1033. }
  1034. void CGameHandler::sendGenericKilledLog(const CStack * defender, int32_t killed, bool multiple)
  1035. {
  1036. if(killed > 0)
  1037. {
  1038. BattleLogMessage blm;
  1039. addGenericKilledLog(blm, defender, killed, multiple);
  1040. sendAndApply(&blm);
  1041. }
  1042. }
  1043. void CGameHandler::addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple)
  1044. {
  1045. if(killed > 0)
  1046. {
  1047. const int32_t txtIndex = (killed > 1) ? 379 : 378;
  1048. std::string formatString = VLC->generaltexth->allTexts[txtIndex];
  1049. // these default h3 texts have unnecessary new lines, so get rid of them before displaying (and trim just in case, trimming newlines does not works for some reason)
  1050. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\n'), formatString.end());
  1051. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\r'), formatString.end());
  1052. boost::algorithm::trim(formatString);
  1053. boost::format txt(formatString);
  1054. if(killed > 1)
  1055. {
  1056. txt % killed % (multiple ? VLC->generaltexth->allTexts[43] : defender->unitType()->getNamePluralTranslated()); // creatures perish
  1057. }
  1058. else //killed == 1
  1059. {
  1060. txt % (multiple ? VLC->generaltexth->allTexts[42] : defender->unitType()->getNameSingularTranslated()); // creature perishes
  1061. }
  1062. MetaString line;
  1063. line.appendRawString(txt.str());
  1064. blm.lines.push_back(std::move(line));
  1065. }
  1066. }
  1067. void CGameHandler::handleClientDisconnection(std::shared_ptr<CConnection> c)
  1068. {
  1069. if(lobby->state == EServerState::SHUTDOWN || !gs || !gs->scenarioOps)
  1070. return;
  1071. for(auto & playerConnections : connections)
  1072. {
  1073. PlayerColor playerId = playerConnections.first;
  1074. auto * playerSettings = gs->scenarioOps->getPlayersSettings(playerId.getNum());
  1075. if(!playerSettings)
  1076. continue;
  1077. auto playerConnection = vstd::find(playerConnections.second, c);
  1078. if(playerConnection != playerConnections.second.end())
  1079. {
  1080. std::string messageText = boost::str(boost::format("%s (cid %d) was disconnected") % playerSettings->name % c->connectionID);
  1081. playerMessage(playerId, messageText, ObjectInstanceID{});
  1082. }
  1083. }
  1084. }
  1085. void CGameHandler::handleReceivedPack(CPackForServer * pack)
  1086. {
  1087. //prepare struct informing that action was applied
  1088. auto sendPackageResponse = [&](bool succesfullyApplied)
  1089. {
  1090. PackageApplied applied;
  1091. applied.player = pack->player;
  1092. applied.result = succesfullyApplied;
  1093. applied.packType = typeList.getTypeID(pack);
  1094. applied.requestID = pack->requestID;
  1095. pack->c->sendPack(&applied);
  1096. };
  1097. CBaseForGHApply * apply = applier->getApplier(typeList.getTypeID(pack)); //and appropriate applier object
  1098. if(isBlockedByQueries(pack, pack->player))
  1099. {
  1100. sendPackageResponse(false);
  1101. }
  1102. else if(apply)
  1103. {
  1104. const bool result = apply->applyOnGH(this, this->gs, pack);
  1105. if(result)
  1106. logGlobal->trace("Message %s successfully applied!", typeid(*pack).name());
  1107. else
  1108. complain((boost::format("Got false in applying %s... that request must have been fishy!")
  1109. % typeid(*pack).name()).str());
  1110. sendPackageResponse(true);
  1111. }
  1112. else
  1113. {
  1114. logGlobal->error("Message cannot be applied, cannot find applier (unregistered type)!");
  1115. sendPackageResponse(false);
  1116. }
  1117. vstd::clear_pointer(pack);
  1118. }
  1119. int CGameHandler::moveStack(int stack, BattleHex dest)
  1120. {
  1121. int ret = 0;
  1122. const CStack *curStack = gs->curB->battleGetStackByID(stack),
  1123. *stackAtEnd = gs->curB->battleGetStackByPos(dest);
  1124. assert(curStack);
  1125. assert(dest < GameConstants::BFIELD_SIZE);
  1126. if (gs->curB->tacticDistance)
  1127. {
  1128. assert(gs->curB->isInTacticRange(dest));
  1129. }
  1130. auto start = curStack->getPosition();
  1131. if (start == dest)
  1132. return 0;
  1133. //initing necessary tables
  1134. auto accessibility = getAccesibility(curStack);
  1135. std::set<BattleHex> passed;
  1136. //Ignore obstacles on starting position
  1137. passed.insert(curStack->getPosition());
  1138. if(curStack->doubleWide())
  1139. passed.insert(curStack->occupiedHex());
  1140. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  1141. if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
  1142. {
  1143. BattleHex shifted = dest.cloneInDirection(curStack->destShiftDir(), false);
  1144. if(accessibility.accessible(shifted, curStack))
  1145. dest = shifted;
  1146. }
  1147. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
  1148. {
  1149. complain("Given destination is not accessible!");
  1150. return 0;
  1151. }
  1152. bool canUseGate = false;
  1153. auto dbState = gs->curB->si.gateState;
  1154. if(battleGetSiegeLevel() > 0 && curStack->unitSide() == BattleSide::DEFENDER &&
  1155. dbState != EGateState::DESTROYED &&
  1156. dbState != EGateState::BLOCKED)
  1157. {
  1158. canUseGate = true;
  1159. }
  1160. std::pair< std::vector<BattleHex>, int > path = gs->curB->getPath(start, dest, curStack);
  1161. ret = path.second;
  1162. int creSpeed = curStack->speed(0, true);
  1163. if (gs->curB->tacticDistance > 0 && creSpeed > 0)
  1164. creSpeed = GameConstants::BFIELD_SIZE;
  1165. bool hasWideMoat = vstd::contains_if(battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  1166. {
  1167. return obst->obstacleType == CObstacleInstance::MOAT;
  1168. });
  1169. auto isGateDrawbridgeHex = [&](BattleHex hex) -> bool
  1170. {
  1171. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  1172. return true;
  1173. if (hex == ESiegeHex::GATE_OUTER)
  1174. return true;
  1175. if (hex == ESiegeHex::GATE_INNER)
  1176. return true;
  1177. return false;
  1178. };
  1179. auto occupyGateDrawbridgeHex = [&](BattleHex hex) -> bool
  1180. {
  1181. if (isGateDrawbridgeHex(hex))
  1182. return true;
  1183. if (curStack->doubleWide())
  1184. {
  1185. BattleHex otherHex = curStack->occupiedHex(hex);
  1186. if (otherHex.isValid() && isGateDrawbridgeHex(otherHex))
  1187. return true;
  1188. }
  1189. return false;
  1190. };
  1191. if (curStack->hasBonusOfType(BonusType::FLYING))
  1192. {
  1193. if (path.second <= creSpeed && path.first.size() > 0)
  1194. {
  1195. if (canUseGate && dbState != EGateState::OPENED &&
  1196. occupyGateDrawbridgeHex(dest))
  1197. {
  1198. BattleUpdateGateState db;
  1199. db.state = EGateState::OPENED;
  1200. sendAndApply(&db);
  1201. }
  1202. //inform clients about move
  1203. BattleStackMoved sm;
  1204. sm.stack = curStack->unitId();
  1205. std::vector<BattleHex> tiles;
  1206. tiles.push_back(path.first[0]);
  1207. sm.tilesToMove = tiles;
  1208. sm.distance = path.second;
  1209. sm.teleporting = false;
  1210. sendAndApply(&sm);
  1211. }
  1212. }
  1213. else //for non-flying creatures
  1214. {
  1215. std::vector<BattleHex> tiles;
  1216. const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0);
  1217. int v = (int)path.first.size()-1;
  1218. path.first.push_back(start);
  1219. // check if gate need to be open or closed at some point
  1220. BattleHex openGateAtHex, gateMayCloseAtHex;
  1221. if (canUseGate)
  1222. {
  1223. for (int i = (int)path.first.size()-1; i >= 0; i--)
  1224. {
  1225. auto needOpenGates = [&](BattleHex hex) -> bool
  1226. {
  1227. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  1228. return true;
  1229. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] == ESiegeHex::GATE_OUTER)
  1230. return true;
  1231. else if (hex == ESiegeHex::GATE_OUTER || hex == ESiegeHex::GATE_INNER)
  1232. return true;
  1233. return false;
  1234. };
  1235. auto hex = path.first[i];
  1236. if (!openGateAtHex.isValid() && dbState != EGateState::OPENED)
  1237. {
  1238. if (needOpenGates(hex))
  1239. openGateAtHex = path.first[i+1];
  1240. //TODO we need find batter way to handle double-wide stacks
  1241. //currently if only second occupied stack part is standing on gate / bridge hex then stack will start to wait for bridge to lower before it's needed. Though this is just a visual bug.
  1242. if (curStack->doubleWide())
  1243. {
  1244. BattleHex otherHex = curStack->occupiedHex(hex);
  1245. if (otherHex.isValid() && needOpenGates(otherHex))
  1246. openGateAtHex = path.first[i+2];
  1247. }
  1248. //gate may be opened and then closed during stack movement, but not other way around
  1249. if (openGateAtHex.isValid())
  1250. dbState = EGateState::OPENED;
  1251. }
  1252. if (!gateMayCloseAtHex.isValid() && dbState != EGateState::CLOSED)
  1253. {
  1254. if (hex == ESiegeHex::GATE_INNER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  1255. {
  1256. gateMayCloseAtHex = path.first[i-1];
  1257. }
  1258. if (hasWideMoat)
  1259. {
  1260. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  1261. {
  1262. gateMayCloseAtHex = path.first[i-1];
  1263. }
  1264. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 &&
  1265. path.first[i-1] != ESiegeHex::GATE_INNER &&
  1266. path.first[i-1] != ESiegeHex::GATE_BRIDGE)
  1267. {
  1268. gateMayCloseAtHex = path.first[i-1];
  1269. }
  1270. }
  1271. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_INNER)
  1272. {
  1273. gateMayCloseAtHex = path.first[i-1];
  1274. }
  1275. }
  1276. }
  1277. }
  1278. bool stackIsMoving = true;
  1279. while(stackIsMoving)
  1280. {
  1281. if (v<tilesToMove)
  1282. {
  1283. logGlobal->error("Movement terminated abnormally");
  1284. break;
  1285. }
  1286. bool gateStateChanging = false;
  1287. //special handling for opening gate on from starting hex
  1288. if (openGateAtHex.isValid() && openGateAtHex == start)
  1289. gateStateChanging = true;
  1290. else
  1291. {
  1292. for (bool obstacleHit = false; (!obstacleHit) && (!gateStateChanging) && (v >= tilesToMove); --v)
  1293. {
  1294. BattleHex hex = path.first[v];
  1295. tiles.push_back(hex);
  1296. if ((openGateAtHex.isValid() && openGateAtHex == hex) ||
  1297. (gateMayCloseAtHex.isValid() && gateMayCloseAtHex == hex))
  1298. {
  1299. gateStateChanging = true;
  1300. }
  1301. //if we walked onto something, finalize this portion of stack movement check into obstacle
  1302. if(!battleGetAllObstaclesOnPos(hex, false).empty())
  1303. obstacleHit = true;
  1304. if (curStack->doubleWide())
  1305. {
  1306. BattleHex otherHex = curStack->occupiedHex(hex);
  1307. //two hex creature hit obstacle by backside
  1308. auto obstacle2 = battleGetAllObstaclesOnPos(otherHex, false);
  1309. if(otherHex.isValid() && !obstacle2.empty())
  1310. obstacleHit = true;
  1311. }
  1312. if(!obstacleHit)
  1313. passed.insert(hex);
  1314. }
  1315. }
  1316. if (!tiles.empty())
  1317. {
  1318. //commit movement
  1319. BattleStackMoved sm;
  1320. sm.stack = curStack->unitId();
  1321. sm.distance = path.second;
  1322. sm.teleporting = false;
  1323. sm.tilesToMove = tiles;
  1324. sendAndApply(&sm);
  1325. tiles.clear();
  1326. }
  1327. //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end
  1328. if (curStack->getPosition() != dest)
  1329. {
  1330. if(stackIsMoving && start != curStack->getPosition())
  1331. {
  1332. stackIsMoving = handleObstacleTriggersForUnit(*spellEnv, *curStack, passed);
  1333. passed.insert(curStack->getPosition());
  1334. if(curStack->doubleWide())
  1335. passed.insert(curStack->occupiedHex());
  1336. }
  1337. if (gateStateChanging)
  1338. {
  1339. if (curStack->getPosition() == openGateAtHex)
  1340. {
  1341. openGateAtHex = BattleHex();
  1342. //only open gate if stack is still alive
  1343. if (curStack->alive())
  1344. {
  1345. BattleUpdateGateState db;
  1346. db.state = EGateState::OPENED;
  1347. sendAndApply(&db);
  1348. }
  1349. }
  1350. else if (curStack->getPosition() == gateMayCloseAtHex)
  1351. {
  1352. gateMayCloseAtHex = BattleHex();
  1353. updateGateState();
  1354. }
  1355. }
  1356. }
  1357. else
  1358. //movement finished normally: we reached destination
  1359. stackIsMoving = false;
  1360. }
  1361. }
  1362. //handle last hex separately for deviation
  1363. if (VLC->settings()->getBoolean(EGameSettings::COMBAT_ONE_HEX_TRIGGERS_OBSTACLES))
  1364. {
  1365. if (dest == battle::Unit::occupiedHex(start, curStack->doubleWide(), curStack->unitSide())
  1366. || start == battle::Unit::occupiedHex(dest, curStack->doubleWide(), curStack->unitSide()))
  1367. passed.clear(); //Just empty passed, obstacles will handled automatically
  1368. }
  1369. //handling obstacle on the final field (separate, because it affects both flying and walking stacks)
  1370. handleObstacleTriggersForUnit(*spellEnv, *curStack, passed);
  1371. return ret;
  1372. }
  1373. CGameHandler::CGameHandler(CVCMIServer * lobby)
  1374. : lobby(lobby)
  1375. , complainNoCreatures("No creatures to split")
  1376. , complainNotEnoughCreatures("Cannot split that stack, not enough creatures!")
  1377. , complainInvalidSlot("Invalid slot accessed!")
  1378. {
  1379. QID = 1;
  1380. IObjectInterface::cb = this;
  1381. applier = std::make_shared<CApplier<CBaseForGHApply>>();
  1382. registerTypesServerPacks(*applier);
  1383. visitObjectAfterVictory = false;
  1384. spellEnv = new ServerSpellCastEnvironment(this);
  1385. }
  1386. CGameHandler::~CGameHandler()
  1387. {
  1388. if (battleThread)
  1389. {
  1390. //Setting battleMadeAction is needed because battleThread waits for the action to continue the main loop
  1391. battleMadeAction.setn(true);
  1392. battleThread->join();
  1393. }
  1394. delete spellEnv;
  1395. delete gs;
  1396. }
  1397. void CGameHandler::reinitScripting()
  1398. {
  1399. serverEventBus = std::make_unique<events::EventBus>();
  1400. #if SCRIPTING_ENABLED
  1401. serverScripts.reset(new scripting::PoolImpl(this, spellEnv));
  1402. #endif
  1403. }
  1404. void CGameHandler::init(StartInfo *si)
  1405. {
  1406. if (si->seedToBeUsed == 0)
  1407. {
  1408. si->seedToBeUsed = static_cast<ui32>(std::time(nullptr));
  1409. }
  1410. CMapService mapService;
  1411. gs = new CGameState();
  1412. gs->preInit(VLC);
  1413. logGlobal->info("Gamestate created!");
  1414. gs->init(&mapService, si);
  1415. logGlobal->info("Gamestate initialized!");
  1416. // reset seed, so that clients can't predict any following random values
  1417. getRandomGenerator().resetSeed();
  1418. for (auto & elem : gs->players)
  1419. {
  1420. states.addPlayer(elem.first);
  1421. }
  1422. reinitScripting();
  1423. }
  1424. static bool evntCmp(const CMapEvent &a, const CMapEvent &b)
  1425. {
  1426. return a.earlierThan(b);
  1427. }
  1428. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false, bool clear = false)
  1429. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  1430. const PlayerState * p = getPlayerState(town->tempOwner);
  1431. if (!p)
  1432. {
  1433. assert(town->tempOwner == PlayerColor::NEUTRAL);
  1434. return;
  1435. }
  1436. if (forced || town->creatures.at(GameConstants::CREATURES_PER_TOWN).second.empty())//we need to change creature
  1437. {
  1438. SetAvailableCreatures ssi;
  1439. ssi.tid = town->id;
  1440. ssi.creatures = town->creatures;
  1441. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.clear();//remove old one
  1442. const std::vector<ConstTransitivePtr<CGDwelling> > &dwellings = p->dwellings;
  1443. if (dwellings.empty())//no dwellings - just remove
  1444. {
  1445. sendAndApply(&ssi);
  1446. return;
  1447. }
  1448. auto dwelling = *RandomGeneratorUtil::nextItem(dwellings, getRandomGenerator());
  1449. // for multi-creature dwellings like Golem Factory
  1450. auto creatureId = RandomGeneratorUtil::nextItem(dwelling->creatures, getRandomGenerator())->second[0];
  1451. if (clear)
  1452. {
  1453. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = std::max(1, (VLC->creh->objects.at(creatureId)->getGrowth())/2);
  1454. }
  1455. else
  1456. {
  1457. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = VLC->creh->objects.at(creatureId)->getGrowth();
  1458. }
  1459. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.push_back(creatureId);
  1460. sendAndApply(&ssi);
  1461. }
  1462. }
  1463. void CGameHandler::newTurn()
  1464. {
  1465. logGlobal->trace("Turn %d", gs->day+1);
  1466. NewTurn n;
  1467. n.specialWeek = NewTurn::NO_ACTION;
  1468. n.creatureid = CreatureID::NONE;
  1469. n.day = gs->day + 1;
  1470. bool firstTurn = !getDate(Date::DAY);
  1471. bool newWeek = getDate(Date::DAY_OF_WEEK) == 7; //day numbers are confusing, as day was not yet switched
  1472. bool newMonth = getDate(Date::DAY_OF_MONTH) == 28;
  1473. std::map<PlayerColor, si32> hadGold;//starting gold - for buildings like dwarven treasury
  1474. if (firstTurn)
  1475. {
  1476. for (auto obj : gs->map->objects)
  1477. {
  1478. if (obj && obj->ID == Obj::PRISON) //give imprisoned hero 0 exp to level him up. easiest to do at this point
  1479. {
  1480. changePrimSkill (getHero(obj->id), PrimarySkill::EXPERIENCE, 0);
  1481. }
  1482. }
  1483. }
  1484. if (newWeek && !firstTurn)
  1485. {
  1486. n.specialWeek = NewTurn::NORMAL;
  1487. bool deityOfFireBuilt = false;
  1488. for (const CGTownInstance *t : gs->map->towns)
  1489. {
  1490. if (t->hasBuilt(BuildingID::GRAIL, ETownType::INFERNO))
  1491. {
  1492. deityOfFireBuilt = true;
  1493. break;
  1494. }
  1495. }
  1496. if (deityOfFireBuilt)
  1497. {
  1498. n.specialWeek = NewTurn::DEITYOFFIRE;
  1499. n.creatureid = CreatureID::IMP;
  1500. }
  1501. else if(VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_RANDOM_SPECIAL_WEEKS))
  1502. {
  1503. int monthType = getRandomGenerator().nextInt(99);
  1504. if (newMonth) //new month
  1505. {
  1506. if (monthType < 40) //double growth
  1507. {
  1508. n.specialWeek = NewTurn::DOUBLE_GROWTH;
  1509. if (VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_ALL_FOR_DOUBLE_MONTH))
  1510. {
  1511. n.creatureid = VLC->creh->pickRandomMonster(getRandomGenerator());
  1512. }
  1513. else if (VLC->creh->doubledCreatures.size())
  1514. {
  1515. n.creatureid = *RandomGeneratorUtil::nextItem(VLC->creh->doubledCreatures, getRandomGenerator());
  1516. }
  1517. else
  1518. {
  1519. complain("Cannot find creature that can be spawned!");
  1520. n.specialWeek = NewTurn::NORMAL;
  1521. }
  1522. }
  1523. else if (monthType < 50)
  1524. n.specialWeek = NewTurn::PLAGUE;
  1525. }
  1526. else //it's a week, but not full month
  1527. {
  1528. if (monthType < 25)
  1529. {
  1530. n.specialWeek = NewTurn::BONUS_GROWTH; //+5
  1531. std::pair<int, CreatureID> newMonster(54, CreatureID());
  1532. do
  1533. {
  1534. newMonster.second = VLC->creh->pickRandomMonster(getRandomGenerator());
  1535. } while (VLC->creh->objects[newMonster.second] &&
  1536. (*VLC->townh)[VLC->creatures()->getById(newMonster.second)->getFaction()]->town == nullptr); // find first non neutral creature
  1537. n.creatureid = newMonster.second;
  1538. }
  1539. }
  1540. }
  1541. }
  1542. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = gs->hpool.heroesPool;
  1543. for (auto& hp : pool)
  1544. {
  1545. auto hero = hp.second;
  1546. if (hero->isInitialized() && hero->stacks.size())
  1547. {
  1548. // reset retreated or surrendered heroes
  1549. auto maxmove = hero->movementPointsLimit(true);
  1550. // if movement is greater than maxmove, we should decrease it
  1551. if (hero->movementPointsRemaining() != maxmove || hero->mana < hero->manaLimit())
  1552. {
  1553. NewTurn::Hero hth;
  1554. hth.id = hero->id;
  1555. hth.move = maxmove;
  1556. hth.mana = hero->getManaNewTurn();
  1557. n.heroes.insert(hth);
  1558. }
  1559. }
  1560. }
  1561. for (auto & elem : gs->players)
  1562. {
  1563. if (elem.first == PlayerColor::NEUTRAL)
  1564. continue;
  1565. else if (elem.first >= PlayerColor::PLAYER_LIMIT)
  1566. assert(0); //illegal player number!
  1567. std::pair<PlayerColor, si32> playerGold(elem.first, elem.second.resources[EGameResID::GOLD]);
  1568. hadGold.insert(playerGold);
  1569. if (newWeek) //new heroes in tavern
  1570. {
  1571. SetAvailableHeroes sah;
  1572. sah.player = elem.first;
  1573. //pick heroes and their armies
  1574. CHeroClass *banned = nullptr;
  1575. for (int j = 0; j < GameConstants::AVAILABLE_HEROES_PER_PLAYER; j++)
  1576. {
  1577. //first hero - native if possible, second hero -> any other class
  1578. if (CGHeroInstance *h = gs->hpool.pickHeroFor(j == 0, elem.first, getNativeTown(elem.first), pool, getRandomGenerator(), banned))
  1579. {
  1580. sah.hid[j] = h->subID;
  1581. h->initArmy(getRandomGenerator(), &sah.army[j]);
  1582. banned = h->type->heroClass;
  1583. }
  1584. else
  1585. {
  1586. sah.hid[j] = -1;
  1587. }
  1588. }
  1589. sendAndApply(&sah);
  1590. }
  1591. n.res[elem.first] = elem.second.resources;
  1592. if(!firstTurn && newWeek) //weekly crystal generation if 1 or more crystal dragons in any hero army or town garrison
  1593. {
  1594. bool hasCrystalGenCreature = false;
  1595. for(CGHeroInstance * hero : elem.second.heroes)
  1596. {
  1597. for(auto stack : hero->stacks)
  1598. {
  1599. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  1600. {
  1601. hasCrystalGenCreature = true;
  1602. break;
  1603. }
  1604. }
  1605. }
  1606. if(!hasCrystalGenCreature) //not found in armies, check towns
  1607. {
  1608. for(CGTownInstance * town : elem.second.towns)
  1609. {
  1610. for(auto stack : town->stacks)
  1611. {
  1612. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  1613. {
  1614. hasCrystalGenCreature = true;
  1615. break;
  1616. }
  1617. }
  1618. }
  1619. }
  1620. if(hasCrystalGenCreature)
  1621. n.res[elem.first][EGameResID::CRYSTAL] += 3;
  1622. }
  1623. for (CGHeroInstance *h : (elem).second.heroes)
  1624. {
  1625. if (h->visitedTown)
  1626. giveSpells(h->visitedTown, h);
  1627. NewTurn::Hero hth;
  1628. hth.id = h->id;
  1629. auto ti = std::make_unique<TurnInfo>(h, 1);
  1630. // TODO: this code executed when bonuses of previous day not yet updated (this happen in NewTurn::applyGs). See issue 2356
  1631. hth.move = h->movementPointsLimitCached(gs->map->getTile(h->visitablePos()).terType->isLand(), ti.get());
  1632. hth.mana = h->getManaNewTurn();
  1633. n.heroes.insert(hth);
  1634. if (!firstTurn) //not first day
  1635. {
  1636. for (int k = 0; k < GameConstants::RESOURCE_QUANTITY; k++)
  1637. {
  1638. n.res[elem.first][k] += h->valOfBonuses(BonusType::GENERATE_RESOURCE, k);
  1639. }
  1640. }
  1641. }
  1642. }
  1643. for (CGTownInstance *t : gs->map->towns)
  1644. {
  1645. PlayerColor player = t->tempOwner;
  1646. handleTownEvents(t, n);
  1647. if (newWeek) //first day of week
  1648. {
  1649. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  1650. setPortalDwelling(t, true, (n.specialWeek == NewTurn::PLAGUE ? true : false)); //set creatures for Portal of Summoning
  1651. if (!firstTurn)
  1652. if (t->hasBuilt(BuildingSubID::TREASURY) && player < PlayerColor::PLAYER_LIMIT)
  1653. n.res[player][EGameResID::GOLD] += hadGold.at(player)/10; //give 10% of starting gold
  1654. if (!vstd::contains(n.cres, t->id))
  1655. {
  1656. n.cres[t->id].tid = t->id;
  1657. n.cres[t->id].creatures = t->creatures;
  1658. }
  1659. auto & sac = n.cres.at(t->id);
  1660. for (int k=0; k < GameConstants::CREATURES_PER_TOWN; k++) //creature growths
  1661. {
  1662. if (!t->creatures.at(k).second.empty()) // there are creatures at this level
  1663. {
  1664. ui32 &availableCount = sac.creatures.at(k).first;
  1665. const CCreature *cre = VLC->creh->objects.at(t->creatures.at(k).second.back());
  1666. if (n.specialWeek == NewTurn::PLAGUE)
  1667. availableCount = t->creatures.at(k).first / 2; //halve their number, no growth
  1668. else
  1669. {
  1670. if (firstTurn) //first day of game: use only basic growths
  1671. availableCount = cre->getGrowth();
  1672. else
  1673. availableCount += t->creatureGrowth(k);
  1674. //Deity of fire week - upgrade both imps and upgrades
  1675. if (n.specialWeek == NewTurn::DEITYOFFIRE && vstd::contains(t->creatures.at(k).second, n.creatureid))
  1676. availableCount += 15;
  1677. if (cre->getId() == n.creatureid) //bonus week, effect applies only to identical creatures
  1678. {
  1679. if (n.specialWeek == NewTurn::DOUBLE_GROWTH)
  1680. availableCount *= 2;
  1681. else if (n.specialWeek == NewTurn::BONUS_GROWTH)
  1682. availableCount += 5;
  1683. }
  1684. }
  1685. }
  1686. }
  1687. }
  1688. if (!firstTurn && player < PlayerColor::PLAYER_LIMIT)//not the first day and town not neutral
  1689. {
  1690. n.res[player] = n.res[player] + t->dailyIncome();
  1691. }
  1692. if(t->hasBuilt(BuildingID::GRAIL)
  1693. && t->town->buildings.at(BuildingID::GRAIL)->height == CBuilding::HEIGHT_SKYSHIP)
  1694. {
  1695. // Skyship, probably easier to handle same as Veil of darkness
  1696. //do it every new day after veils apply
  1697. if (player != PlayerColor::NEUTRAL) //do not reveal fow for neutral player
  1698. {
  1699. FoWChange fw;
  1700. fw.mode = 1;
  1701. fw.player = player;
  1702. // find all hidden tiles
  1703. const auto fow = getPlayerTeam(player)->fogOfWarMap;
  1704. auto shape = fow->shape();
  1705. for(size_t z = 0; z < shape[0]; z++)
  1706. for(size_t x = 0; x < shape[1]; x++)
  1707. for(size_t y = 0; y < shape[2]; y++)
  1708. if (!(*fow)[z][x][y])
  1709. fw.tiles.insert(int3(x, y, z));
  1710. sendAndApply (&fw);
  1711. }
  1712. }
  1713. if (t->hasBonusOfType (BonusType::DARKNESS))
  1714. {
  1715. for (auto & player : gs->players)
  1716. {
  1717. if (getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  1718. getPlayerRelations(player.first, t->tempOwner) == PlayerRelations::ENEMIES)
  1719. changeFogOfWar(t->visitablePos(), t->getBonusLocalFirst(Selector::type()(BonusType::DARKNESS))->val, player.first, true);
  1720. }
  1721. }
  1722. }
  1723. if (newMonth)
  1724. {
  1725. SetAvailableArtifacts saa;
  1726. saa.id = -1;
  1727. pickAllowedArtsSet(saa.arts, getRandomGenerator());
  1728. sendAndApply(&saa);
  1729. }
  1730. sendAndApply(&n);
  1731. if (newWeek)
  1732. {
  1733. //spawn wandering monsters
  1734. if (newMonth && (n.specialWeek == NewTurn::DOUBLE_GROWTH || n.specialWeek == NewTurn::DEITYOFFIRE))
  1735. {
  1736. spawnWanderingMonsters(n.creatureid);
  1737. }
  1738. //new week info popup
  1739. if (!firstTurn)
  1740. {
  1741. InfoWindow iw;
  1742. switch (n.specialWeek)
  1743. {
  1744. case NewTurn::DOUBLE_GROWTH:
  1745. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 131);
  1746. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1747. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1748. break;
  1749. case NewTurn::PLAGUE:
  1750. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 132);
  1751. break;
  1752. case NewTurn::BONUS_GROWTH:
  1753. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 134);
  1754. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1755. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1756. break;
  1757. case NewTurn::DEITYOFFIRE:
  1758. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 135);
  1759. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  1760. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  1761. iw.text.replacePositiveNumber(15); //%+d 15
  1762. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 43); //%s familiar
  1763. iw.text.replacePositiveNumber(15); //%+d 15
  1764. break;
  1765. default:
  1766. if (newMonth)
  1767. {
  1768. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (130));
  1769. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(32, 41));
  1770. }
  1771. else
  1772. {
  1773. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (133));
  1774. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(43, 57));
  1775. }
  1776. }
  1777. for (auto & elem : gs->players)
  1778. {
  1779. iw.player = elem.first;
  1780. sendAndApply(&iw);
  1781. }
  1782. }
  1783. }
  1784. logGlobal->trace("Info about turn %d has been sent!", n.day);
  1785. handleTimeEvents();
  1786. //call objects
  1787. for (auto & elem : gs->map->objects)
  1788. {
  1789. if (elem)
  1790. elem->newTurn(getRandomGenerator());
  1791. }
  1792. synchronizeArtifactHandlerLists(); //new day events may have changed them. TODO better of managing that
  1793. }
  1794. void CGameHandler::run(bool resume)
  1795. {
  1796. LOG_TRACE_PARAMS(logGlobal, "resume=%d", resume);
  1797. using namespace boost::posix_time;
  1798. for (auto cc : lobby->connections)
  1799. {
  1800. auto players = lobby->getAllClientPlayers(cc->connectionID);
  1801. std::stringstream sbuffer;
  1802. sbuffer << "Connection " << cc->connectionID << " will handle " << players.size() << " player: ";
  1803. for (PlayerColor color : players)
  1804. {
  1805. sbuffer << color << " ";
  1806. {
  1807. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1808. connections[color].insert(cc);
  1809. }
  1810. }
  1811. logGlobal->info(sbuffer.str());
  1812. }
  1813. #if SCRIPTING_ENABLED
  1814. services()->scripts()->run(serverScripts);
  1815. #endif
  1816. if(resume)
  1817. events::GameResumed::defaultExecute(serverEventBus.get());
  1818. auto playerTurnOrder = generatePlayerTurnOrder();
  1819. while(lobby->state == EServerState::GAMEPLAY)
  1820. {
  1821. if(!resume)
  1822. {
  1823. newTurn();
  1824. events::TurnStarted::defaultExecute(serverEventBus.get());
  1825. }
  1826. std::list<PlayerColor>::iterator it;
  1827. if (resume)
  1828. {
  1829. it = std::find(playerTurnOrder.begin(), playerTurnOrder.end(), gs->currentPlayer);
  1830. }
  1831. else
  1832. {
  1833. it = playerTurnOrder.begin();
  1834. }
  1835. resume = false;
  1836. for (; (it != playerTurnOrder.end()) && (lobby->state == EServerState::GAMEPLAY) ; it++)
  1837. {
  1838. auto playerColor = *it;
  1839. auto onGetTurn = [&](events::PlayerGotTurn & event)
  1840. {
  1841. //if player runs out of time, he shouldn't get the turn (especially AI)
  1842. //pre-trigger may change anything, should check before each player
  1843. //TODO: is it enough to check only one player?
  1844. checkVictoryLossConditionsForAll();
  1845. auto player = event.getPlayer();
  1846. const PlayerState * playerState = &gs->players[player];
  1847. if(playerState->status != EPlayerStatus::INGAME)
  1848. {
  1849. event.setPlayer(PlayerColor::CANNOT_DETERMINE);
  1850. }
  1851. else
  1852. {
  1853. states.setFlag(player, &PlayerStatus::makingTurn, true);
  1854. YourTurn yt;
  1855. yt.player = player;
  1856. //Change local daysWithoutCastle counter for local interface message //TODO: needed?
  1857. yt.daysWithoutCastle = playerState->daysWithoutCastle;
  1858. applyAndSend(&yt);
  1859. }
  1860. };
  1861. events::PlayerGotTurn::defaultExecute(serverEventBus.get(), onGetTurn, playerColor);
  1862. if(playerColor != PlayerColor::CANNOT_DETERMINE)
  1863. {
  1864. //wait till turn is done
  1865. boost::unique_lock<boost::mutex> lock(states.mx);
  1866. while(states.players.at(playerColor).makingTurn && lobby->state == EServerState::GAMEPLAY)
  1867. {
  1868. static time_duration p = milliseconds(100);
  1869. states.cv.timed_wait(lock, p);
  1870. }
  1871. }
  1872. }
  1873. //additional check that game is not finished
  1874. bool activePlayer = false;
  1875. for (auto player : playerTurnOrder)
  1876. {
  1877. if (gs->players[player].status == EPlayerStatus::INGAME)
  1878. activePlayer = true;
  1879. }
  1880. if(!activePlayer)
  1881. lobby->state = EServerState::GAMEPLAY_ENDED;
  1882. }
  1883. }
  1884. std::list<PlayerColor> CGameHandler::generatePlayerTurnOrder() const
  1885. {
  1886. // Generate player turn order
  1887. std::list<PlayerColor> playerTurnOrder;
  1888. for (const auto & player : gs->players) // add human players first
  1889. {
  1890. if (player.second.human)
  1891. playerTurnOrder.push_back(player.first);
  1892. }
  1893. for (const auto & player : gs->players) // then add non-human players
  1894. {
  1895. if (!player.second.human)
  1896. playerTurnOrder.push_back(player.first);
  1897. }
  1898. return playerTurnOrder;
  1899. }
  1900. void CGameHandler::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town)
  1901. {
  1902. battleResult.set(nullptr);
  1903. const auto & t = *getTile(tile);
  1904. TerrainId terrain = t.terType->getId();
  1905. if (gs->map->isCoastalTile(tile)) //coastal tile is always ground
  1906. terrain = ETerrainId::SAND;
  1907. BattleField terType = gs->battleGetBattlefieldType(tile, getRandomGenerator());
  1908. if (heroes[0] && heroes[0]->boat && heroes[1] && heroes[1]->boat)
  1909. terType = BattleField::fromString("ship_to_ship");
  1910. //send info about battles
  1911. BattleStart bs;
  1912. bs.info = BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  1913. sendAndApply(&bs);
  1914. }
  1915. void CGameHandler::checkBattleStateChanges()
  1916. {
  1917. //check if drawbridge state need to be changes
  1918. if (battleGetSiegeLevel() > 0)
  1919. updateGateState();
  1920. //check if battle ended
  1921. if (auto result = battleIsFinished())
  1922. {
  1923. setBattleResult(BattleResult::NORMAL, *result);
  1924. }
  1925. }
  1926. void CGameHandler::giveSpells(const CGTownInstance *t, const CGHeroInstance *h)
  1927. {
  1928. if (!h->hasSpellbook())
  1929. return; //hero hasn't spellbook
  1930. ChangeSpells cs;
  1931. cs.hid = h->id;
  1932. cs.learn = true;
  1933. if (t->hasBuilt(BuildingID::GRAIL, ETownType::CONFLUX) && t->hasBuilt(BuildingID::MAGES_GUILD_1))
  1934. {
  1935. // Aurora Borealis give spells of all levels even if only level 1 mages guild built
  1936. for (int i = 0; i < h->maxSpellLevel(); i++)
  1937. {
  1938. std::vector<SpellID> spells;
  1939. getAllowedSpells(spells, i+1);
  1940. for (auto & spell : spells)
  1941. cs.spells.insert(spell);
  1942. }
  1943. }
  1944. else
  1945. {
  1946. for (int i = 0; i < std::min(t->mageGuildLevel(), h->maxSpellLevel()); i++)
  1947. {
  1948. for (int j = 0; j < t->spellsAtLevel(i+1, true) && j < t->spells.at(i).size(); j++)
  1949. {
  1950. if (!h->spellbookContainsSpell(t->spells.at(i).at(j)))
  1951. cs.spells.insert(t->spells.at(i).at(j));
  1952. }
  1953. }
  1954. }
  1955. if (!cs.spells.empty())
  1956. sendAndApply(&cs);
  1957. }
  1958. bool CGameHandler::removeObject(const CGObjectInstance * obj)
  1959. {
  1960. if (!obj || !getObj(obj->id))
  1961. {
  1962. logGlobal->error("Something wrong, that object already has been removed or hasn't existed!");
  1963. return false;
  1964. }
  1965. RemoveObject ro;
  1966. ro.id = obj->id;
  1967. sendAndApply(&ro);
  1968. checkVictoryLossConditionsForAll(); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1969. return true;
  1970. }
  1971. bool CGameHandler::moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit, PlayerColor asker)
  1972. {
  1973. const CGHeroInstance *h = getHero(hid);
  1974. // not turn of that hero or player can't simply teleport hero (at least not with this function)
  1975. if (!h || (asker != PlayerColor::NEUTRAL && (teleporting || h->getOwner() != gs->currentPlayer)))
  1976. {
  1977. logGlobal->error("Illegal call to move hero!");
  1978. return false;
  1979. }
  1980. logGlobal->trace("Player %d (%s) wants to move hero %d from %s to %s", asker, asker.getStr(), hid.getNum(), h->pos.toString(), dst.toString());
  1981. const int3 hmpos = h->convertToVisitablePos(dst);
  1982. if (!gs->map->isInTheMap(hmpos))
  1983. {
  1984. logGlobal->error("Destination tile is outside the map!");
  1985. return false;
  1986. }
  1987. const TerrainTile t = *getTile(hmpos);
  1988. const int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1989. const bool embarking = !h->boat && !t.visitableObjects.empty() && t.visitableObjects.back()->ID == Obj::BOAT;
  1990. const bool disembarking = h->boat
  1991. && t.terType->isLand()
  1992. && (dst == h->pos
  1993. || (h->boat->layer == EPathfindingLayer::SAIL && !t.blocked));
  1994. //result structure for start - movement failed, no move points used
  1995. TryMoveHero tmh;
  1996. tmh.id = hid;
  1997. tmh.start = h->pos;
  1998. tmh.end = dst;
  1999. tmh.result = TryMoveHero::FAILED;
  2000. tmh.movePoints = h->movementPointsRemaining();
  2001. //check if destination tile is available
  2002. auto pathfinderHelper = std::make_unique<CPathfinderHelper>(gs, h, PathfinderOptions());
  2003. auto ti = pathfinderHelper->getTurnInfo();
  2004. const bool canFly = pathfinderHelper->hasBonusOfType(BonusType::FLYING_MOVEMENT) || (h->boat && h->boat->layer == EPathfindingLayer::AIR);
  2005. const bool canWalkOnSea = pathfinderHelper->hasBonusOfType(BonusType::WATER_WALKING) || (h->boat && h->boat->layer == EPathfindingLayer::WATER);
  2006. const int cost = pathfinderHelper->getMovementCost(h->visitablePos(), hmpos, nullptr, nullptr, h->movementPointsRemaining());
  2007. //it's a rock or blocked and not visitable tile
  2008. //OR hero is on land and dest is water and (there is not present only one object - boat)
  2009. if (((!t.terType->isPassable() || (t.blocked && !t.visitable && !canFly))
  2010. && complain("Cannot move hero, destination tile is blocked!"))
  2011. || ((!h->boat && !canWalkOnSea && !canFly && t.terType->isWater() && (t.visitableObjects.size() < 1 || !t.visitableObjects.back()->isCoastVisitable())) //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)
  2012. && complain("Cannot move hero, destination tile is on water!"))
  2013. || ((h->boat && h->boat->layer == EPathfindingLayer::SAIL && t.terType->isLand() && t.blocked)
  2014. && complain("Cannot disembark hero, tile is blocked!"))
  2015. || ((distance(h->pos, dst) >= 1.5 && !teleporting)
  2016. && complain("Tiles are not neighboring!"))
  2017. || ((h->inTownGarrison)
  2018. && complain("Can not move garrisoned hero!"))
  2019. || (((int)h->movementPointsRemaining() < cost && dst != h->pos && !teleporting)
  2020. && complain("Hero doesn't have any movement points left!"))
  2021. || ((transit && !canFly && !CGTeleport::isTeleport(t.topVisitableObj()))
  2022. && complain("Hero cannot transit over this tile!"))
  2023. /*|| (states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  2024. && complain("Cannot move hero during the battle"))*/)
  2025. {
  2026. //send info about movement failure
  2027. sendAndApply(&tmh);
  2028. return false;
  2029. }
  2030. //several generic blocks of code
  2031. // should be called if hero changes tile but before applying TryMoveHero package
  2032. auto leaveTile = [&]()
  2033. {
  2034. for (CGObjectInstance *obj : gs->map->getTile(int3(h->pos.x-1, h->pos.y, h->pos.z)).visitableObjects)
  2035. {
  2036. obj->onHeroLeave(h);
  2037. }
  2038. this->getTilesInRange(tmh.fowRevealed, h->getSightCenter()+(tmh.end-tmh.start), h->getSightRadius(), h->tempOwner, 1);
  2039. };
  2040. auto doMove = [&](TryMoveHero::EResult result, EGuardLook lookForGuards,
  2041. EVisitDest visitDest, ELEaveTile leavingTile) -> bool
  2042. {
  2043. LOG_TRACE_PARAMS(logGlobal, "Hero %s starts movement from %s to %s", h->getNameTranslated() % tmh.start.toString() % tmh.end.toString());
  2044. auto moveQuery = std::make_shared<CHeroMovementQuery>(this, tmh, h);
  2045. queries.addQuery(moveQuery);
  2046. if (leavingTile == LEAVING_TILE)
  2047. leaveTile();
  2048. if (isInTheMap(guardPos))
  2049. tmh.attackedFrom = std::make_optional(guardPos);
  2050. tmh.result = result;
  2051. sendAndApply(&tmh);
  2052. if (visitDest == VISIT_DEST && t.topVisitableObj() && t.topVisitableObj()->id == h->id)
  2053. { // Hero should be always able to visit any object he staying on even if there guards around
  2054. visitObjectOnTile(t, h);
  2055. }
  2056. else if (lookForGuards == CHECK_FOR_GUARDS && isInTheMap(guardPos))
  2057. {
  2058. const TerrainTile &guardTile = *gs->getTile(guardPos);
  2059. objectVisited(guardTile.visitableObjects.back(), h);
  2060. moveQuery->visitDestAfterVictory = visitDest==VISIT_DEST;
  2061. }
  2062. else if (visitDest == VISIT_DEST)
  2063. {
  2064. visitObjectOnTile(t, h);
  2065. }
  2066. queries.popIfTop(moveQuery);
  2067. logGlobal->trace("Hero %s ends movement", h->getNameTranslated());
  2068. return result != TryMoveHero::FAILED;
  2069. };
  2070. //interaction with blocking object (like resources)
  2071. auto blockingVisit = [&]() -> bool
  2072. {
  2073. for (CGObjectInstance *obj : t.visitableObjects)
  2074. {
  2075. if(h->boat && !obj->isBlockedVisitable() && !h->boat->onboardVisitAllowed)
  2076. return doMove(TryMoveHero::SUCCESS, this->IGNORE_GUARDS, DONT_VISIT_DEST, REMAINING_ON_TILE);
  2077. if (obj != h && obj->isBlockedVisitable() && !obj->passableFor(h->tempOwner))
  2078. {
  2079. EVisitDest visitDest = VISIT_DEST;
  2080. if(h->boat && !h->boat->onboardVisitAllowed)
  2081. visitDest = DONT_VISIT_DEST;
  2082. return doMove(TryMoveHero::BLOCKING_VISIT, this->IGNORE_GUARDS, visitDest, REMAINING_ON_TILE);
  2083. }
  2084. }
  2085. return false;
  2086. };
  2087. if (!transit && embarking)
  2088. {
  2089. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, false, ti);
  2090. return doMove(TryMoveHero::EMBARK, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  2091. // In H3 embark ignore guards
  2092. }
  2093. if (disembarking)
  2094. {
  2095. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, true, ti);
  2096. return doMove(TryMoveHero::DISEMBARK, CHECK_FOR_GUARDS, VISIT_DEST, LEAVING_TILE);
  2097. }
  2098. if (teleporting)
  2099. {
  2100. if (blockingVisit()) // e.g. hero on the other side of teleporter
  2101. return true;
  2102. doMove(TryMoveHero::TELEPORTATION, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  2103. // visit town for town portal \ castle gates
  2104. // do not use generic visitObjectOnTile to avoid double-teleporting
  2105. // if this moveHero call was triggered by teleporter
  2106. if (!t.visitableObjects.empty())
  2107. {
  2108. if (CGTownInstance * town = dynamic_cast<CGTownInstance *>(t.visitableObjects.back()))
  2109. town->onHeroVisit(h);
  2110. }
  2111. return true;
  2112. }
  2113. //still here? it is standard movement!
  2114. {
  2115. tmh.movePoints = (int)h->movementPointsRemaining() >= cost
  2116. ? h->movementPointsRemaining() - cost
  2117. : 0;
  2118. EGuardLook lookForGuards = CHECK_FOR_GUARDS;
  2119. EVisitDest visitDest = VISIT_DEST;
  2120. if (transit)
  2121. {
  2122. if (CGTeleport::isTeleport(t.topVisitableObj()))
  2123. visitDest = DONT_VISIT_DEST;
  2124. if (canFly)
  2125. {
  2126. lookForGuards = IGNORE_GUARDS;
  2127. visitDest = DONT_VISIT_DEST;
  2128. }
  2129. }
  2130. else if (blockingVisit())
  2131. return true;
  2132. if(h->boat && !h->boat->onboardAssaultAllowed)
  2133. lookForGuards = IGNORE_GUARDS;
  2134. doMove(TryMoveHero::SUCCESS, lookForGuards, visitDest, LEAVING_TILE);
  2135. return true;
  2136. }
  2137. }
  2138. bool CGameHandler::teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker)
  2139. {
  2140. const CGHeroInstance *h = getHero(hid);
  2141. const CGTownInstance *t = getTown(dstid);
  2142. if (!h || !t || h->getOwner() != gs->currentPlayer)
  2143. COMPLAIN_RET("Invalid call to teleportHero!");
  2144. const CGTownInstance *from = h->visitedTown;
  2145. if (((h->getOwner() != t->getOwner())
  2146. && complain("Cannot teleport hero to another player"))
  2147. || (from->town->faction->getId() != t->town->faction->getId()
  2148. && complain("Source town and destination town should belong to the same faction"))
  2149. || ((!from || !from->hasBuilt(BuildingSubID::CASTLE_GATE))
  2150. && complain("Hero must be in town with Castle gate for teleporting"))
  2151. || (!t->hasBuilt(BuildingSubID::CASTLE_GATE)
  2152. && complain("Cannot teleport hero to town without Castle gate in it")))
  2153. return false;
  2154. int3 pos = h->convertFromVisitablePos(t->visitablePos());
  2155. moveHero(hid,pos,1);
  2156. return true;
  2157. }
  2158. void CGameHandler::setOwner(const CGObjectInstance * obj, const PlayerColor owner)
  2159. {
  2160. PlayerColor oldOwner = getOwner(obj->id);
  2161. SetObjectProperty sop(obj->id, ObjProperty::OWNER, owner.getNum());
  2162. sendAndApply(&sop);
  2163. std::set<PlayerColor> playerColors = {owner, oldOwner};
  2164. checkVictoryLossConditions(playerColors);
  2165. const CGTownInstance * town = dynamic_cast<const CGTownInstance *>(obj);
  2166. if (town) //town captured
  2167. {
  2168. if (owner < PlayerColor::PLAYER_LIMIT) //new owner is real player
  2169. {
  2170. if (town->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  2171. setPortalDwelling(town, true, false);
  2172. }
  2173. if (oldOwner < PlayerColor::PLAYER_LIMIT) //old owner is real player
  2174. {
  2175. if (getPlayerState(oldOwner)->towns.empty() && getPlayerState(oldOwner)->status != EPlayerStatus::LOSER) //previous player lost last last town
  2176. {
  2177. InfoWindow iw;
  2178. iw.player = oldOwner;
  2179. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  2180. iw.text.replaceLocalString(EMetaText::COLOR, oldOwner.getNum());
  2181. sendAndApply(&iw);
  2182. }
  2183. }
  2184. }
  2185. const PlayerState * p = getPlayerState(owner);
  2186. if ((obj->ID == Obj::CREATURE_GENERATOR1 || obj->ID == Obj::CREATURE_GENERATOR4) && p && p->dwellings.size()==1)//first dwelling captured
  2187. {
  2188. for (const CGTownInstance * t : getPlayerState(owner)->towns)
  2189. {
  2190. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  2191. setPortalDwelling(t);//set initial creatures for all portals of summoning
  2192. }
  2193. }
  2194. }
  2195. void CGameHandler::showBlockingDialog(BlockingDialog *iw)
  2196. {
  2197. auto dialogQuery = std::make_shared<CBlockingDialogQuery>(this, *iw);
  2198. queries.addQuery(dialogQuery);
  2199. iw->queryID = dialogQuery->queryID;
  2200. sendToAllClients(iw);
  2201. }
  2202. void CGameHandler::showTeleportDialog(TeleportDialog *iw)
  2203. {
  2204. auto dialogQuery = std::make_shared<CTeleportDialogQuery>(this, *iw);
  2205. queries.addQuery(dialogQuery);
  2206. iw->queryID = dialogQuery->queryID;
  2207. sendToAllClients(iw);
  2208. }
  2209. void CGameHandler::giveResource(PlayerColor player, GameResID which, int val) //TODO: cap according to Bersy's suggestion
  2210. {
  2211. if (!val) return; //don't waste time on empty call
  2212. TResources resources;
  2213. resources[which] = val;
  2214. giveResources(player, resources);
  2215. }
  2216. void CGameHandler::giveResources(PlayerColor player, TResources resources)
  2217. {
  2218. SetResources sr;
  2219. sr.abs = false;
  2220. sr.player = player;
  2221. sr.res = resources;
  2222. sendAndApply(&sr);
  2223. }
  2224. void CGameHandler::giveCreatures(const CArmedInstance *obj, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove)
  2225. {
  2226. COMPLAIN_RET_IF(!creatures.stacksCount(), "Strange, giveCreatures called without args!");
  2227. COMPLAIN_RET_IF(obj->stacksCount(), "Cannot give creatures from not-cleared object!");
  2228. COMPLAIN_RET_IF(creatures.stacksCount() > GameConstants::ARMY_SIZE, "Too many stacks to give!");
  2229. //first we move creatures to give to make them army of object-source
  2230. for (auto & elem : creatures.Slots())
  2231. {
  2232. addToSlot(StackLocation(obj, obj->getSlotFor(elem.second->type)), elem.second->type, elem.second->count);
  2233. }
  2234. tryJoiningArmy(obj, h, remove, true);
  2235. }
  2236. void CGameHandler::takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures)
  2237. {
  2238. std::vector<CStackBasicDescriptor> cres = creatures;
  2239. if (cres.size() <= 0)
  2240. return;
  2241. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  2242. for (CStackBasicDescriptor &sbd : cres)
  2243. {
  2244. TQuantity collected = 0;
  2245. while(collected < sbd.count)
  2246. {
  2247. bool foundSth = false;
  2248. for (auto i = obj->Slots().begin(); i != obj->Slots().end(); i++)
  2249. {
  2250. if (i->second->type == sbd.type)
  2251. {
  2252. TQuantity take = std::min(sbd.count - collected, i->second->count); //collect as much cres as we can
  2253. changeStackCount(StackLocation(obj, i->first), -take, false);
  2254. collected += take;
  2255. foundSth = true;
  2256. break;
  2257. }
  2258. }
  2259. if (!foundSth) //we went through the whole loop and haven't found appropriate cres
  2260. {
  2261. complain("Unexpected failure during taking creatures!");
  2262. return;
  2263. }
  2264. }
  2265. }
  2266. }
  2267. void CGameHandler::heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  2268. {
  2269. HeroVisitCastle vc;
  2270. vc.hid = hero->id;
  2271. vc.tid = obj->id;
  2272. vc.flags |= 1;
  2273. sendAndApply(&vc);
  2274. visitCastleObjects(obj, hero);
  2275. giveSpells (obj, hero);
  2276. checkVictoryLossConditionsForPlayer(hero->tempOwner); //transported artifact?
  2277. }
  2278. void CGameHandler::visitCastleObjects(const CGTownInstance * t, const CGHeroInstance * h)
  2279. {
  2280. for (auto building : t->bonusingBuildings)
  2281. building->onHeroVisit(h);
  2282. }
  2283. void CGameHandler::stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  2284. {
  2285. HeroVisitCastle vc;
  2286. vc.hid = hero->id;
  2287. vc.tid = obj->id;
  2288. sendAndApply(&vc);
  2289. }
  2290. void CGameHandler::removeArtifact(const ArtifactLocation &al)
  2291. {
  2292. EraseArtifact ea;
  2293. ea.al = al;
  2294. sendAndApply(&ea);
  2295. }
  2296. void CGameHandler::startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile,
  2297. const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank,
  2298. const CGTownInstance *town) //use hero=nullptr for no hero
  2299. {
  2300. if(gs->curB)
  2301. gs->curB.dellNull();
  2302. engageIntoBattle(army1->tempOwner);
  2303. engageIntoBattle(army2->tempOwner);
  2304. static const CArmedInstance *armies[2];
  2305. armies[0] = army1;
  2306. armies[1] = army2;
  2307. static const CGHeroInstance*heroes[2];
  2308. heroes[0] = hero1;
  2309. heroes[1] = hero2;
  2310. setupBattle(tile, armies, heroes, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  2311. //existing battle query for retying auto-combat
  2312. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(gs->curB->sides[0].color));
  2313. if(battleQuery)
  2314. {
  2315. for(int i : {0, 1})
  2316. {
  2317. if(heroes[i])
  2318. {
  2319. SetMana restoreInitialMana;
  2320. restoreInitialMana.val = battleQuery->initialHeroMana[i];
  2321. restoreInitialMana.hid = heroes[i]->id;
  2322. sendAndApply(&restoreInitialMana);
  2323. }
  2324. }
  2325. battleQuery->bi = gs->curB;
  2326. battleQuery->result = std::nullopt;
  2327. battleQuery->belligerents[0] = gs->curB->sides[0].armyObject;
  2328. battleQuery->belligerents[1] = gs->curB->sides[1].armyObject;
  2329. }
  2330. battleQuery = std::make_shared<CBattleQuery>(this, gs->curB);
  2331. for(int i : {0, 1})
  2332. {
  2333. if(heroes[i])
  2334. {
  2335. battleQuery->initialHeroMana[i] = heroes[i]->mana;
  2336. }
  2337. }
  2338. queries.addQuery(battleQuery);
  2339. this->battleThread = std::make_unique<boost::thread>(boost::thread(&CGameHandler::runBattle, this));
  2340. }
  2341. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank)
  2342. {
  2343. startBattlePrimary(army1, army2, tile,
  2344. army1->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army1) : nullptr,
  2345. army2->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army2) : nullptr,
  2346. creatureBank);
  2347. }
  2348. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank)
  2349. {
  2350. startBattleI(army1, army2, army2->visitablePos(), creatureBank);
  2351. }
  2352. void CGameHandler::changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells)
  2353. {
  2354. ChangeSpells cs;
  2355. cs.hid = hero->id;
  2356. cs.spells = spells;
  2357. cs.learn = give;
  2358. sendAndApply(&cs);
  2359. }
  2360. void CGameHandler::sendMessageTo(std::shared_ptr<CConnection> c, const std::string &message)
  2361. {
  2362. SystemMessage sm;
  2363. sm.text = message;
  2364. boost::unique_lock<boost::mutex> lock(*c->mutexWrite);
  2365. *(c.get()) << &sm;
  2366. }
  2367. void CGameHandler::giveHeroBonus(GiveBonus * bonus)
  2368. {
  2369. sendAndApply(bonus);
  2370. }
  2371. void CGameHandler::setMovePoints(SetMovePoints * smp)
  2372. {
  2373. sendAndApply(smp);
  2374. }
  2375. void CGameHandler::setManaPoints(ObjectInstanceID hid, int val)
  2376. {
  2377. SetMana sm;
  2378. sm.hid = hid;
  2379. sm.val = val;
  2380. sm.absolute = true;
  2381. sendAndApply(&sm);
  2382. }
  2383. void CGameHandler::giveHero(ObjectInstanceID id, PlayerColor player, ObjectInstanceID boatId)
  2384. {
  2385. GiveHero gh;
  2386. gh.id = id;
  2387. gh.player = player;
  2388. gh.boatId = boatId;
  2389. sendAndApply(&gh);
  2390. //Reveal fow around new hero, especially released from Prison
  2391. auto h = getHero(id);
  2392. changeFogOfWar(h->pos, h->getSightRadius(), player, false);
  2393. }
  2394. void CGameHandler::changeObjPos(ObjectInstanceID objid, int3 newPos)
  2395. {
  2396. ChangeObjPos cop;
  2397. cop.objid = objid;
  2398. cop.nPos = newPos;
  2399. sendAndApply(&cop);
  2400. }
  2401. void CGameHandler::useScholarSkill(ObjectInstanceID fromHero, ObjectInstanceID toHero)
  2402. {
  2403. const CGHeroInstance * h1 = getHero(fromHero);
  2404. const CGHeroInstance * h2 = getHero(toHero);
  2405. int h1_scholarSpellLevel = h1->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  2406. int h2_scholarSpellLevel = h2->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  2407. if (h1_scholarSpellLevel < h2_scholarSpellLevel)
  2408. {
  2409. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  2410. std::swap(fromHero, toHero);
  2411. }
  2412. int ScholarSpellLevel = std::max(h1_scholarSpellLevel, h2_scholarSpellLevel);//heroes can trade up to this level
  2413. if (!ScholarSpellLevel || !h1->hasSpellbook() || !h2->hasSpellbook())
  2414. return;//no scholar skill or no spellbook
  2415. int h1Lvl = std::min(ScholarSpellLevel, h1->maxSpellLevel()),
  2416. h2Lvl = std::min(ScholarSpellLevel, h2->maxSpellLevel());//heroes can receive this levels
  2417. ChangeSpells cs1;
  2418. cs1.learn = true;
  2419. cs1.hid = toHero;//giving spells to first hero
  2420. for (auto it : h1->getSpellsInSpellbook())
  2421. if (h2Lvl >= it.toSpell()->level && !h2->spellbookContainsSpell(it))//hero can learn it and don't have it yet
  2422. cs1.spells.insert(it);//spell to learn
  2423. ChangeSpells cs2;
  2424. cs2.learn = true;
  2425. cs2.hid = fromHero;
  2426. for (auto it : h2->getSpellsInSpellbook())
  2427. if (h1Lvl >= it.toSpell()->level && !h1->spellbookContainsSpell(it))
  2428. cs2.spells.insert(it);
  2429. if (!cs1.spells.empty() || !cs2.spells.empty())//create a message
  2430. {
  2431. int ScholarSkillLevel = std::max(h1->getSecSkillLevel(SecondarySkill::SCHOLAR),
  2432. h2->getSecSkillLevel(SecondarySkill::SCHOLAR));
  2433. InfoWindow iw;
  2434. iw.player = h1->tempOwner;
  2435. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, 18, ScholarSkillLevel, 0);
  2436. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  2437. iw.text.replaceRawString(h1->getNameTranslated());
  2438. if (!cs2.spells.empty())//if found new spell - apply
  2439. {
  2440. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 140);//learns
  2441. int size = static_cast<int>(cs2.spells.size());
  2442. for (auto it : cs2.spells)
  2443. {
  2444. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  2445. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  2446. switch (size--)
  2447. {
  2448. case 2:
  2449. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  2450. case 1:
  2451. break;
  2452. default:
  2453. iw.text.appendRawString(", ");
  2454. }
  2455. }
  2456. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 142);//from %s
  2457. iw.text.replaceRawString(h2->getNameTranslated());
  2458. sendAndApply(&cs2);
  2459. }
  2460. if (!cs1.spells.empty() && !cs2.spells.empty())
  2461. {
  2462. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);//and
  2463. }
  2464. if (!cs1.spells.empty())
  2465. {
  2466. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 147);//teaches
  2467. int size = static_cast<int>(cs1.spells.size());
  2468. for (auto it : cs1.spells)
  2469. {
  2470. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  2471. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  2472. switch (size--)
  2473. {
  2474. case 2:
  2475. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  2476. case 1:
  2477. break;
  2478. default:
  2479. iw.text.appendRawString(", ");
  2480. }
  2481. }
  2482. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 148);//from %s
  2483. iw.text.replaceRawString(h2->getNameTranslated());
  2484. sendAndApply(&cs1);
  2485. }
  2486. sendAndApply(&iw);
  2487. }
  2488. }
  2489. void CGameHandler::heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  2490. {
  2491. auto h1 = getHero(hero1), h2 = getHero(hero2);
  2492. if (getPlayerRelations(h1->getOwner(), h2->getOwner()))
  2493. {
  2494. auto exchange = std::make_shared<CGarrisonDialogQuery>(this, h1, h2);
  2495. ExchangeDialog hex;
  2496. hex.queryID = exchange->queryID;
  2497. hex.player = h1->getOwner();
  2498. hex.hero1 = hero1;
  2499. hex.hero2 = hero2;
  2500. sendAndApply(&hex);
  2501. useScholarSkill(hero1,hero2);
  2502. queries.addQuery(exchange);
  2503. }
  2504. }
  2505. void CGameHandler::sendToAllClients(CPackForClient * pack)
  2506. {
  2507. logNetwork->trace("\tSending to all clients: %s", typeid(*pack).name());
  2508. for (auto c : lobby->connections)
  2509. {
  2510. if(!c->isOpen())
  2511. continue;
  2512. c->sendPack(pack);
  2513. }
  2514. }
  2515. void CGameHandler::sendAndApply(CPackForClient * pack)
  2516. {
  2517. sendToAllClients(pack);
  2518. gs->apply(pack);
  2519. logNetwork->trace("\tApplied on gs: %s", typeid(*pack).name());
  2520. }
  2521. void CGameHandler::applyAndSend(CPackForClient * pack)
  2522. {
  2523. gs->apply(pack);
  2524. sendToAllClients(pack);
  2525. }
  2526. void CGameHandler::sendAndApply(CGarrisonOperationPack * pack)
  2527. {
  2528. sendAndApply(static_cast<CPackForClient *>(pack));
  2529. checkVictoryLossConditionsForAll();
  2530. }
  2531. void CGameHandler::sendAndApply(SetResources * pack)
  2532. {
  2533. sendAndApply(static_cast<CPackForClient *>(pack));
  2534. checkVictoryLossConditionsForPlayer(pack->player);
  2535. }
  2536. void CGameHandler::sendAndApply(NewStructures * pack)
  2537. {
  2538. sendAndApply(static_cast<CPackForClient *>(pack));
  2539. checkVictoryLossConditionsForPlayer(getTown(pack->tid)->tempOwner);
  2540. }
  2541. bool CGameHandler::isPlayerOwns(CPackForServer * pack, ObjectInstanceID id)
  2542. {
  2543. return getPlayerAt(pack->c) == getOwner(id);
  2544. }
  2545. void CGameHandler::throwNotAllowedAction(CPackForServer * pack)
  2546. {
  2547. if(pack->c)
  2548. {
  2549. SystemMessage temp_message("You are not allowed to perform this action!");
  2550. pack->c->sendPack(&temp_message);
  2551. }
  2552. logNetwork->error("Player is not allowed to perform this action!");
  2553. throw ExceptionNotAllowedAction();
  2554. }
  2555. void CGameHandler::wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer)
  2556. {
  2557. std::ostringstream oss;
  2558. oss << "You were identified as player " << getPlayerAt(pack->c) << " while expecting " << expectedplayer;
  2559. logNetwork->error(oss.str());
  2560. if(pack->c)
  2561. {
  2562. SystemMessage temp_message(oss.str());
  2563. pack->c->sendPack(&temp_message);
  2564. }
  2565. }
  2566. void CGameHandler::throwOnWrongOwner(CPackForServer * pack, ObjectInstanceID id)
  2567. {
  2568. if(!isPlayerOwns(pack, id))
  2569. {
  2570. wrongPlayerMessage(pack, getOwner(id));
  2571. throwNotAllowedAction(pack);
  2572. }
  2573. }
  2574. void CGameHandler::throwOnWrongPlayer(CPackForServer * pack, PlayerColor player)
  2575. {
  2576. if(!hasPlayerAt(player, pack->c) && player != getPlayerAt(pack->c))
  2577. {
  2578. wrongPlayerMessage(pack, player);
  2579. throwNotAllowedAction(pack);
  2580. }
  2581. }
  2582. void CGameHandler::throwAndComplain(CPackForServer * pack, std::string txt)
  2583. {
  2584. complain(txt);
  2585. throwNotAllowedAction(pack);
  2586. }
  2587. void CGameHandler::save(const std::string & filename)
  2588. {
  2589. logGlobal->info("Saving to %s", filename);
  2590. const auto stem = FileInfo::GetPathStem(filename);
  2591. const auto savefname = stem.to_string() + ".vsgm1";
  2592. CResourceHandler::get("local")->createResource(savefname);
  2593. {
  2594. logGlobal->info("Ordering clients to serialize...");
  2595. SaveGameClient sg(savefname);
  2596. sendToAllClients(&sg);
  2597. }
  2598. try
  2599. {
  2600. {
  2601. CSaveFile save(*CResourceHandler::get("local")->getResourceName(ResourceID(stem.to_string(), EResType::SERVER_SAVEGAME)));
  2602. saveCommonState(save);
  2603. logGlobal->info("Saving server state");
  2604. save << *this;
  2605. }
  2606. logGlobal->info("Game has been successfully saved!");
  2607. }
  2608. catch(std::exception &e)
  2609. {
  2610. logGlobal->error("Failed to save game: %s", e.what());
  2611. }
  2612. }
  2613. bool CGameHandler::load(const std::string & filename)
  2614. {
  2615. logGlobal->info("Loading from %s", filename);
  2616. const auto stem = FileInfo::GetPathStem(filename);
  2617. reinitScripting();
  2618. try
  2619. {
  2620. {
  2621. CLoadFile lf(*CResourceHandler::get("local")->getResourceName(ResourceID(stem.to_string(), EResType::SERVER_SAVEGAME)), MINIMAL_SERIALIZATION_VERSION);
  2622. loadCommonState(lf);
  2623. logGlobal->info("Loading server state");
  2624. lf >> *this;
  2625. }
  2626. logGlobal->info("Game has been successfully loaded!");
  2627. }
  2628. catch(const CModHandler::Incompatibility & e)
  2629. {
  2630. logGlobal->error("Failed to load game: %s", e.what());
  2631. auto errorMsg = VLC->generaltexth->translate("vcmi.server.errors.modsIncompatibility") + '\n';
  2632. errorMsg += e.what();
  2633. lobby->announceMessage(errorMsg);
  2634. return false;
  2635. }
  2636. catch(const std::exception & e)
  2637. {
  2638. logGlobal->error("Failed to load game: %s", e.what());
  2639. return false;
  2640. }
  2641. gs->preInit(VLC);
  2642. gs->updateOnLoad(lobby->si.get());
  2643. return true;
  2644. }
  2645. bool CGameHandler::bulkSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner, si32 howMany)
  2646. {
  2647. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  2648. return false;
  2649. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  2650. const CCreatureSet & creatureSet = *army;
  2651. if((!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  2652. || (howMany < 1 && complain("Invalid split parameter!")))
  2653. {
  2654. return false;
  2655. }
  2656. auto actualAmount = army->getStackCount(slotSrc);
  2657. if(actualAmount <= howMany && complain(complainNotEnoughCreatures)) // '<=' because it's not intended just for moving a stack
  2658. return false;
  2659. auto freeSlots = creatureSet.getFreeSlots();
  2660. if(freeSlots.empty() && complain("No empty stacks"))
  2661. return false;
  2662. BulkRebalanceStacks bulkRS;
  2663. for(auto slot : freeSlots)
  2664. {
  2665. RebalanceStacks rs;
  2666. rs.srcArmy = army->id;
  2667. rs.dstArmy = army->id;
  2668. rs.srcSlot = slotSrc;
  2669. rs.dstSlot = slot;
  2670. rs.count = howMany;
  2671. bulkRS.moves.push_back(rs);
  2672. actualAmount -= howMany;
  2673. if(actualAmount <= howMany)
  2674. break;
  2675. }
  2676. sendAndApply(&bulkRS);
  2677. return true;
  2678. }
  2679. bool CGameHandler::bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner)
  2680. {
  2681. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  2682. return false;
  2683. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  2684. const CCreatureSet & creatureSet = *army;
  2685. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  2686. return false;
  2687. auto actualAmount = creatureSet.getStackCount(slotSrc);
  2688. if(actualAmount < 1 && complain(complainNoCreatures))
  2689. return false;
  2690. auto currentCreature = creatureSet.getCreature(slotSrc);
  2691. if(!currentCreature && complain(complainNoCreatures))
  2692. return false;
  2693. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, slotSrc);
  2694. if(!creatureSlots.size())
  2695. return false;
  2696. BulkRebalanceStacks bulkRS;
  2697. for(auto slot : creatureSlots)
  2698. {
  2699. RebalanceStacks rs;
  2700. rs.srcArmy = army->id;
  2701. rs.dstArmy = army->id;
  2702. rs.srcSlot = slot;
  2703. rs.dstSlot = slotSrc;
  2704. rs.count = creatureSet.getStackCount(slot);
  2705. bulkRS.moves.push_back(rs);
  2706. }
  2707. sendAndApply(&bulkRS);
  2708. return true;
  2709. }
  2710. bool CGameHandler::bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot)
  2711. {
  2712. if(!srcSlot.validSlot() && complain(complainInvalidSlot))
  2713. return false;
  2714. const CArmedInstance * armySrc = static_cast<const CArmedInstance*>(getObjInstance(srcArmy));
  2715. const CCreatureSet & setSrc = *armySrc;
  2716. if(!vstd::contains(setSrc.stacks, srcSlot) && complain(complainNoCreatures))
  2717. return false;
  2718. const CArmedInstance * armyDest = static_cast<const CArmedInstance*>(getObjInstance(destArmy));
  2719. const CCreatureSet & setDest = *armyDest;
  2720. auto freeSlots = setDest.getFreeSlotsQueue();
  2721. typedef std::map<SlotID, std::pair<SlotID, TQuantity>> TRebalanceMap;
  2722. TRebalanceMap moves;
  2723. auto srcQueue = setSrc.getCreatureQueue(srcSlot); // Exclude srcSlot, it should be moved last
  2724. auto slotsLeft = setSrc.stacksCount();
  2725. auto destMap = setDest.getCreatureMap();
  2726. TMapCreatureSlot::key_compare keyComp = destMap.key_comp();
  2727. while(!srcQueue.empty())
  2728. {
  2729. auto pair = srcQueue.top();
  2730. srcQueue.pop();
  2731. auto currCreature = pair.first;
  2732. auto currSlot = pair.second;
  2733. const auto quantity = setSrc.getStackCount(currSlot);
  2734. TMapCreatureSlot::iterator lb = destMap.lower_bound(currCreature);
  2735. const bool alreadyExists = (lb != destMap.end() && !(keyComp(currCreature, lb->first)));
  2736. if(!alreadyExists)
  2737. {
  2738. if(freeSlots.empty())
  2739. continue;
  2740. auto currFreeSlot = freeSlots.front();
  2741. freeSlots.pop();
  2742. destMap.insert(lb, TMapCreatureSlot::value_type(currCreature, currFreeSlot));
  2743. }
  2744. moves.insert(std::make_pair(currSlot, std::make_pair(destMap[currCreature], quantity)));
  2745. slotsLeft--;
  2746. }
  2747. if(slotsLeft == 1)
  2748. {
  2749. auto lastCreature = setSrc.getCreature(srcSlot);
  2750. auto slotToMove = SlotID();
  2751. // Try to find a slot for last creature
  2752. if(destMap.find(lastCreature) == destMap.end())
  2753. {
  2754. if(!freeSlots.empty())
  2755. slotToMove = freeSlots.front();
  2756. }
  2757. else
  2758. {
  2759. slotToMove = destMap[lastCreature];
  2760. }
  2761. if(slotToMove != SlotID())
  2762. {
  2763. const bool needsLastStack = armySrc->needsLastStack();
  2764. const auto quantity = setSrc.getStackCount(srcSlot) - (needsLastStack ? 1 : 0);
  2765. moves.insert(std::make_pair(srcSlot, std::make_pair(slotToMove, quantity)));
  2766. }
  2767. }
  2768. BulkRebalanceStacks bulkRS;
  2769. for(auto & move : moves)
  2770. {
  2771. RebalanceStacks rs;
  2772. rs.srcArmy = armySrc->id;
  2773. rs.dstArmy = armyDest->id;
  2774. rs.srcSlot = move.first;
  2775. rs.dstSlot = move.second.first;
  2776. rs.count = move.second.second;
  2777. bulkRS.moves.push_back(rs);
  2778. }
  2779. sendAndApply(&bulkRS);
  2780. return true;
  2781. }
  2782. bool CGameHandler::bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner)
  2783. {
  2784. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  2785. return false;
  2786. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  2787. const CCreatureSet & creatureSet = *army;
  2788. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  2789. return false;
  2790. auto actualAmount = creatureSet.getStackCount(slotSrc);
  2791. if(actualAmount <= 1 && complain(complainNoCreatures))
  2792. return false;
  2793. auto freeSlot = creatureSet.getFreeSlot();
  2794. auto currentCreature = creatureSet.getCreature(slotSrc);
  2795. if(freeSlot == SlotID() && creatureSet.isCreatureBalanced(currentCreature))
  2796. return true;
  2797. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, SlotID(-1), 1); // Ignore slots where's only 1 creature, don't ignore slotSrc
  2798. TQuantity totalCreatures = 0;
  2799. for(auto slot : creatureSlots)
  2800. totalCreatures += creatureSet.getStackCount(slot);
  2801. if(totalCreatures <= 1 && complain("Total creatures number is invalid"))
  2802. return false;
  2803. if(freeSlot != SlotID())
  2804. creatureSlots.push_back(freeSlot);
  2805. if(creatureSlots.empty() && complain("No available slots for smart rebalancing"))
  2806. return false;
  2807. const auto totalCreatureSlots = creatureSlots.size();
  2808. const auto rem = totalCreatures % totalCreatureSlots;
  2809. const auto quotient = totalCreatures / totalCreatureSlots;
  2810. // totalCreatures == rem * (quotient + 1) + (totalCreatureSlots - rem) * quotient;
  2811. // Proof: r(q+1)+(s-r)q = rq+r+qs-rq = r+qs = total, where total/s = q+r/s
  2812. BulkSmartRebalanceStacks bulkSRS;
  2813. if(freeSlot != SlotID())
  2814. {
  2815. RebalanceStacks rs;
  2816. rs.srcArmy = rs.dstArmy = army->id;
  2817. rs.srcSlot = slotSrc;
  2818. rs.dstSlot = freeSlot;
  2819. rs.count = 1;
  2820. bulkSRS.moves.push_back(rs);
  2821. }
  2822. auto currSlot = 0;
  2823. auto check = 0;
  2824. for(auto slot : creatureSlots)
  2825. {
  2826. ChangeStackCount csc;
  2827. csc.army = army->id;
  2828. csc.slot = slot;
  2829. csc.count = (currSlot < rem)
  2830. ? quotient + 1
  2831. : quotient;
  2832. csc.absoluteValue = true;
  2833. bulkSRS.changes.push_back(csc);
  2834. currSlot++;
  2835. check += csc.count;
  2836. }
  2837. if(check != totalCreatures)
  2838. {
  2839. complain((boost::format("Failure: totalCreatures=%d but check=%d") % totalCreatures % check).str());
  2840. return false;
  2841. }
  2842. sendAndApply(&bulkSRS);
  2843. return true;
  2844. }
  2845. bool CGameHandler::arrangeStacks(ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player)
  2846. {
  2847. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id1)),
  2848. * s2 = static_cast<const CArmedInstance *>(getObjInstance(id2));
  2849. const CCreatureSet &S1 = *s1, &S2 = *s2;
  2850. StackLocation sl1(s1, p1), sl2(s2, p2);
  2851. if (!sl1.slot.validSlot() || !sl2.slot.validSlot())
  2852. {
  2853. complain(complainInvalidSlot);
  2854. return false;
  2855. }
  2856. if (!isAllowedExchange(id1,id2))
  2857. {
  2858. complain("Cannot exchange stacks between these two objects!\n");
  2859. return false;
  2860. }
  2861. // We can always put stacks into locked garrison, but not take them out of it
  2862. auto notRemovable = [&](const CArmedInstance * army)
  2863. {
  2864. if (id1 != id2) // Stack arrangement inside locked garrison is allowed
  2865. {
  2866. auto g = dynamic_cast<const CGGarrison *>(army);
  2867. if (g && !g->removableUnits)
  2868. {
  2869. complain("Stacks in this garrison are not removable!\n");
  2870. return true;
  2871. }
  2872. }
  2873. return false;
  2874. };
  2875. if (what==1) //swap
  2876. {
  2877. if (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s1->getStackCount(p1))
  2878. || ((s2->tempOwner != player && s2->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)))
  2879. {
  2880. complain("Can't take troops from another player!");
  2881. return false;
  2882. }
  2883. if (sl1.army == sl2.army && sl1.slot == sl2.slot)
  2884. {
  2885. complain("Cannot swap stacks - slots are the same!");
  2886. return false;
  2887. }
  2888. if (!s1->slotEmpty(p1) && !s2->slotEmpty(p2))
  2889. {
  2890. if (notRemovable(sl1.army) || notRemovable(sl2.army))
  2891. return false;
  2892. }
  2893. if (s1->slotEmpty(p1) && notRemovable(sl2.army))
  2894. return false;
  2895. else if (s2->slotEmpty(p2) && notRemovable(sl1.army))
  2896. return false;
  2897. swapStacks(sl1, sl2);
  2898. }
  2899. else if (what==2)//merge
  2900. {
  2901. if ((s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot merge different creatures stacks!"))
  2902. || (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)) && complain("Can't take troops from another player!")))
  2903. return false;
  2904. if (s1->slotEmpty(p1) || s2->slotEmpty(p2))
  2905. {
  2906. complain("Cannot merge empty stack!");
  2907. return false;
  2908. }
  2909. else if (notRemovable(sl1.army))
  2910. return false;
  2911. moveStack(sl1, sl2);
  2912. }
  2913. else if (what==3) //split
  2914. {
  2915. const int countToMove = val - s2->getStackCount(p2);
  2916. const int countLeftOnSrc = s1->getStackCount(p1) - countToMove;
  2917. if ( (s1->tempOwner != player && countLeftOnSrc < s1->getStackCount(p1))
  2918. || (s2->tempOwner != player && val < s2->getStackCount(p2)))
  2919. {
  2920. complain("Can't move troops of another player!");
  2921. return false;
  2922. }
  2923. //general conditions checking
  2924. if ((!vstd::contains(S1.stacks,p1) && complain(complainNoCreatures))
  2925. || (val<1 && complain(complainNoCreatures)) )
  2926. {
  2927. return false;
  2928. }
  2929. if (vstd::contains(S2.stacks,p2)) //dest. slot not free - it must be "rebalancing"...
  2930. {
  2931. int total = s1->getStackCount(p1) + s2->getStackCount(p2);
  2932. if ((total < val && complain("Cannot split that stack, not enough creatures!"))
  2933. || (s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot rebalance different creatures stacks!"))
  2934. )
  2935. {
  2936. return false;
  2937. }
  2938. if (notRemovable(sl1.army))
  2939. {
  2940. if (s1->getStackCount(p1) > countLeftOnSrc)
  2941. return false;
  2942. }
  2943. else if (notRemovable(sl2.army))
  2944. {
  2945. if (s2->getStackCount(p1) < countLeftOnSrc)
  2946. return false;
  2947. }
  2948. moveStack(sl1, sl2, countToMove);
  2949. //S2.slots[p2]->count = val;
  2950. //S1.slots[p1]->count = total - val;
  2951. }
  2952. else //split one stack to the two
  2953. {
  2954. if (s1->getStackCount(p1) < val)//not enough creatures
  2955. {
  2956. complain(complainNotEnoughCreatures);
  2957. return false;
  2958. }
  2959. if (notRemovable(sl1.army))
  2960. return false;
  2961. moveStack(sl1, sl2, val);
  2962. }
  2963. }
  2964. return true;
  2965. }
  2966. bool CGameHandler::hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const
  2967. {
  2968. return connections.at(player).count(c);
  2969. }
  2970. PlayerColor CGameHandler::getPlayerAt(std::shared_ptr<CConnection> c) const
  2971. {
  2972. std::set<PlayerColor> all;
  2973. for (auto i=connections.cbegin(); i!=connections.cend(); i++)
  2974. if(vstd::contains(i->second, c))
  2975. all.insert(i->first);
  2976. switch(all.size())
  2977. {
  2978. case 0:
  2979. return PlayerColor::NEUTRAL;
  2980. case 1:
  2981. return *all.begin();
  2982. default:
  2983. {
  2984. //if we have more than one player at this connection, try to pick active one
  2985. if (vstd::contains(all, gs->currentPlayer))
  2986. return gs->currentPlayer;
  2987. else
  2988. return PlayerColor::CANNOT_DETERMINE; //cannot say which player is it
  2989. }
  2990. }
  2991. }
  2992. bool CGameHandler::disbandCreature(ObjectInstanceID id, SlotID pos)
  2993. {
  2994. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id));
  2995. if (!vstd::contains(s1->stacks,pos))
  2996. {
  2997. complain("Illegal call to disbandCreature - no such stack in army!");
  2998. return false;
  2999. }
  3000. eraseStack(StackLocation(s1, pos));
  3001. return true;
  3002. }
  3003. bool CGameHandler::buildStructure(ObjectInstanceID tid, BuildingID requestedID, bool force)
  3004. {
  3005. const CGTownInstance * t = getTown(tid);
  3006. if(!t)
  3007. COMPLAIN_RETF("No such town (ID=%s)!", tid);
  3008. if(!t->town->buildings.count(requestedID))
  3009. COMPLAIN_RETF("Town of faction %s does not have info about building ID=%s!", t->town->faction->getNameTranslated() % requestedID);
  3010. if(t->hasBuilt(requestedID))
  3011. COMPLAIN_RETF("Building %s is already built in %s", t->town->buildings.at(requestedID)->getNameTranslated() % t->getNameTranslated());
  3012. const CBuilding * requestedBuilding = t->town->buildings.at(requestedID);
  3013. //Vector with future list of built building and buildings in auto-mode that are not yet built.
  3014. std::vector<const CBuilding*> remainingAutoBuildings;
  3015. std::set<BuildingID> buildingsThatWillBe;
  3016. //Check validity of request
  3017. if(!force)
  3018. {
  3019. switch(requestedBuilding->mode)
  3020. {
  3021. case CBuilding::BUILD_NORMAL :
  3022. if (canBuildStructure(t, requestedID) != EBuildingState::ALLOWED)
  3023. COMPLAIN_RET("Cannot build that building!");
  3024. break;
  3025. case CBuilding::BUILD_AUTO :
  3026. case CBuilding::BUILD_SPECIAL:
  3027. COMPLAIN_RET("This building can not be constructed normally!");
  3028. case CBuilding::BUILD_GRAIL :
  3029. if(requestedBuilding->mode == CBuilding::BUILD_GRAIL) //needs grail
  3030. {
  3031. if(!t->visitingHero || !t->visitingHero->hasArt(ArtifactID::GRAIL))
  3032. COMPLAIN_RET("Cannot build this without grail!")
  3033. else
  3034. removeArtifact(ArtifactLocation(t->visitingHero, t->visitingHero->getArtPos(ArtifactID::GRAIL, false)));
  3035. }
  3036. break;
  3037. }
  3038. }
  3039. //Performs stuff that has to be done before new building is built
  3040. auto processBeforeBuiltStructure = [t, this](const BuildingID buildingID)
  3041. {
  3042. if(buildingID >= BuildingID::DWELL_FIRST) //dwelling
  3043. {
  3044. int level = (buildingID - BuildingID::DWELL_FIRST) % GameConstants::CREATURES_PER_TOWN;
  3045. int upgradeNumber = (buildingID - BuildingID::DWELL_FIRST) / GameConstants::CREATURES_PER_TOWN;
  3046. if(upgradeNumber >= t->town->creatures.at(level).size())
  3047. {
  3048. complain(boost::str(boost::format("Error ecountered when building dwelling (bid=%s):"
  3049. "no creature found (upgrade number %d, level %d!")
  3050. % buildingID % upgradeNumber % level));
  3051. return;
  3052. }
  3053. CCreature * crea = VLC->creh->objects.at(t->town->creatures.at(level).at(upgradeNumber));
  3054. SetAvailableCreatures ssi;
  3055. ssi.tid = t->id;
  3056. ssi.creatures = t->creatures;
  3057. if (ssi.creatures[level].second.empty()) // first creature in a dwelling
  3058. ssi.creatures[level].first = crea->getGrowth();
  3059. ssi.creatures[level].second.push_back(crea->getId());
  3060. sendAndApply(&ssi);
  3061. }
  3062. if(t->town->buildings.at(buildingID)->subId == BuildingSubID::PORTAL_OF_SUMMONING)
  3063. {
  3064. setPortalDwelling(t);
  3065. }
  3066. };
  3067. //Performs stuff that has to be done after new building is built
  3068. auto processAfterBuiltStructure = [t, this](const BuildingID buildingID)
  3069. {
  3070. auto isMageGuild = (buildingID <= BuildingID::MAGES_GUILD_5 && buildingID >= BuildingID::MAGES_GUILD_1);
  3071. auto isLibrary = isMageGuild ? false
  3072. : t->town->buildings.at(buildingID)->subId == BuildingSubID::EBuildingSubID::LIBRARY;
  3073. if(isMageGuild || isLibrary || (t->subID == ETownType::CONFLUX && buildingID == BuildingID::GRAIL))
  3074. {
  3075. if(t->visitingHero)
  3076. giveSpells(t,t->visitingHero);
  3077. if(t->garrisonHero)
  3078. giveSpells(t,t->garrisonHero);
  3079. }
  3080. };
  3081. //Checks if all requirements will be met with expected building list "buildingsThatWillBe"
  3082. auto areRequirementsFullfilled = [&](const BuildingID & buildID)
  3083. {
  3084. return buildingsThatWillBe.count(buildID);
  3085. };
  3086. //Init the vectors
  3087. for(auto & build : t->town->buildings)
  3088. {
  3089. if(t->hasBuilt(build.first))
  3090. {
  3091. buildingsThatWillBe.insert(build.first);
  3092. }
  3093. else
  3094. {
  3095. if(build.second->mode == CBuilding::BUILD_AUTO) //not built auto building
  3096. remainingAutoBuildings.push_back(build.second);
  3097. }
  3098. }
  3099. //Prepare structure (list of building ids will be filled later)
  3100. NewStructures ns;
  3101. ns.tid = tid;
  3102. ns.builded = force ? t->builded : (t->builded+1);
  3103. std::queue<const CBuilding*> buildingsToAdd;
  3104. buildingsToAdd.push(requestedBuilding);
  3105. while(!buildingsToAdd.empty())
  3106. {
  3107. auto b = buildingsToAdd.front();
  3108. buildingsToAdd.pop();
  3109. ns.bid.insert(b->bid);
  3110. buildingsThatWillBe.insert(b->bid);
  3111. remainingAutoBuildings -= b;
  3112. for(auto autoBuilding : remainingAutoBuildings)
  3113. {
  3114. auto actualRequirements = t->genBuildingRequirements(autoBuilding->bid);
  3115. if(actualRequirements.test(areRequirementsFullfilled))
  3116. buildingsToAdd.push(autoBuilding);
  3117. }
  3118. }
  3119. // 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.
  3120. for(auto builtID : ns.bid)
  3121. processBeforeBuiltStructure(builtID);
  3122. //Take cost
  3123. if(!force)
  3124. giveResources(t->tempOwner, -requestedBuilding->resources);
  3125. //We know what has been built, apply changes. Do this as final step to properly update town window
  3126. sendAndApply(&ns);
  3127. //Other post-built events. To some logic like giving spells to work gamestate changes for new building must be already in place!
  3128. for(auto builtID : ns.bid)
  3129. processAfterBuiltStructure(builtID);
  3130. // now when everything is built - reveal tiles for lookout tower
  3131. FoWChange fw;
  3132. fw.player = t->tempOwner;
  3133. fw.mode = 1;
  3134. getTilesInRange(fw.tiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, 1);
  3135. sendAndApply(&fw);
  3136. if(t->visitingHero)
  3137. objectVisited(t, t->visitingHero);
  3138. if(t->garrisonHero)
  3139. visitCastleObjects(t, t->garrisonHero);
  3140. checkVictoryLossConditionsForPlayer(t->tempOwner);
  3141. return true;
  3142. }
  3143. bool CGameHandler::razeStructure (ObjectInstanceID tid, BuildingID bid)
  3144. {
  3145. ///incomplete, simply erases target building
  3146. const CGTownInstance * t = getTown(tid);
  3147. if (!vstd::contains(t->builtBuildings, bid))
  3148. return false;
  3149. RazeStructures rs;
  3150. rs.tid = tid;
  3151. rs.bid.insert(bid);
  3152. rs.destroyed = t->destroyed + 1;
  3153. sendAndApply(&rs);
  3154. //TODO: Remove dwellers
  3155. // if (t->subID == 4 && bid == 17) //Veil of Darkness
  3156. // {
  3157. // RemoveBonus rb(RemoveBonus::TOWN);
  3158. // rb.whoID = t->id;
  3159. // rb.source = BonusSource::TOWN_STRUCTURE;
  3160. // rb.id = 17;
  3161. // sendAndApply(&rb);
  3162. // }
  3163. return true;
  3164. }
  3165. void CGameHandler::sendMessageToAll(const std::string &message)
  3166. {
  3167. SystemMessage sm;
  3168. sm.text = message;
  3169. sendToAllClients(&sm);
  3170. }
  3171. bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dstid, CreatureID crid, ui32 cram, si32 fromLvl)
  3172. {
  3173. const CGDwelling * dw = static_cast<const CGDwelling *>(getObj(objid));
  3174. const CArmedInstance *dst = nullptr;
  3175. const CCreature *c = VLC->creh->objects.at(crid);
  3176. const bool warMachine = c->warMachine != ArtifactID::NONE;
  3177. //TODO: test for owning
  3178. //TODO: check if dst can recruit objects (e.g. hero is actually visiting object, town and source are same, etc)
  3179. dst = dynamic_cast<const CArmedInstance*>(getObj(dstid));
  3180. assert(dw && dst);
  3181. //verify
  3182. bool found = false;
  3183. int level = 0;
  3184. for (; level < dw->creatures.size(); level++) //iterate through all levels
  3185. {
  3186. if ((fromLvl != -1) && (level !=fromLvl))
  3187. continue;
  3188. const auto &cur = dw->creatures.at(level); //current level info <amount, list of cr. ids>
  3189. int i = 0;
  3190. for (; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  3191. if (cur.second.at(i) == crid)
  3192. break;
  3193. if (i < cur.second.size())
  3194. {
  3195. found = true;
  3196. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  3197. break;
  3198. }
  3199. }
  3200. SlotID slot = dst->getSlotFor(crid);
  3201. if ((!found && complain("Cannot recruit: no such creatures!"))
  3202. || ((si32)cram > VLC->creh->objects.at(crid)->maxAmount(getPlayerState(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!"))
  3203. || (cram<=0 && complain("Cannot recruit: cram <= 0!"))
  3204. || (!slot.validSlot() && !warMachine && complain("Cannot recruit: no available slot!")))
  3205. {
  3206. return false;
  3207. }
  3208. //recruit
  3209. giveResources(dst->tempOwner, -(c->getFullRecruitCost() * cram));
  3210. SetAvailableCreatures sac;
  3211. sac.tid = objid;
  3212. sac.creatures = dw->creatures;
  3213. sac.creatures[level].first -= cram;
  3214. sendAndApply(&sac);
  3215. if (warMachine)
  3216. {
  3217. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(dst);
  3218. COMPLAIN_RET_FALSE_IF(!h, "Only hero can buy war machines");
  3219. ArtifactID artId = c->warMachine;
  3220. COMPLAIN_RET_FALSE_IF(artId == ArtifactID::CATAPULT, "Catapult cannot be recruited!");
  3221. const CArtifact * art = artId.toArtifact();
  3222. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid war machine artifact");
  3223. return giveHeroNewArtifact(h, art);
  3224. }
  3225. else
  3226. {
  3227. addToSlot(StackLocation(dst, slot), c, cram);
  3228. }
  3229. return true;
  3230. }
  3231. bool CGameHandler::upgradeCreature(ObjectInstanceID objid, SlotID pos, CreatureID upgID)
  3232. {
  3233. const CArmedInstance * obj = static_cast<const CArmedInstance *>(getObjInstance(objid));
  3234. if (!obj->hasStackAtSlot(pos))
  3235. {
  3236. COMPLAIN_RET("Cannot upgrade, no stack at slot " + boost::to_string(pos));
  3237. }
  3238. UpgradeInfo ui;
  3239. fillUpgradeInfo(obj, pos, ui);
  3240. PlayerColor player = obj->tempOwner;
  3241. const PlayerState *p = getPlayerState(player);
  3242. int crQuantity = obj->stacks.at(pos)->count;
  3243. int newIDpos= vstd::find_pos(ui.newID, upgID);//get position of new id in UpgradeInfo
  3244. //check if upgrade is possible
  3245. if ((ui.oldID<0 || newIDpos == -1) && complain("That upgrade is not possible!"))
  3246. {
  3247. return false;
  3248. }
  3249. TResources totalCost = ui.cost.at(newIDpos) * crQuantity;
  3250. //check if player has enough resources
  3251. if (!p->resources.canAfford(totalCost))
  3252. COMPLAIN_RET("Cannot upgrade, not enough resources!");
  3253. //take resources
  3254. giveResources(player, -totalCost);
  3255. //upgrade creature
  3256. changeStackType(StackLocation(obj, pos), VLC->creh->objects.at(upgID));
  3257. return true;
  3258. }
  3259. bool CGameHandler::changeStackType(const StackLocation &sl, const CCreature *c)
  3260. {
  3261. if (!sl.army->hasStackAtSlot(sl.slot))
  3262. COMPLAIN_RET("Cannot find a stack to change type");
  3263. SetStackType sst;
  3264. sst.army = sl.army->id;
  3265. sst.slot = sl.slot;
  3266. sst.type = c->getId();
  3267. sendAndApply(&sst);
  3268. return true;
  3269. }
  3270. void CGameHandler::moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging)
  3271. {
  3272. assert(src->canBeMergedWith(*dst, allowMerging));
  3273. while(src->stacksCount())//while there are unmoved creatures
  3274. {
  3275. auto i = src->Slots().begin(); //iterator to stack to move
  3276. StackLocation sl(src, i->first); //location of stack to move
  3277. SlotID pos = dst->getSlotFor(i->second->type);
  3278. if (!pos.validSlot())
  3279. {
  3280. //try to merge two other stacks to make place
  3281. std::pair<SlotID, SlotID> toMerge;
  3282. if (dst->mergableStacks(toMerge, i->first) && allowMerging)
  3283. {
  3284. moveStack(StackLocation(dst, toMerge.first), StackLocation(dst, toMerge.second)); //merge toMerge.first into toMerge.second
  3285. assert(!dst->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  3286. moveStack(sl, StackLocation(dst, toMerge.first)); //move stack to freed slot
  3287. }
  3288. else
  3289. {
  3290. complain("Unexpected failure during an attempt to move army from " + src->nodeName() + " to " + dst->nodeName() + "!");
  3291. return;
  3292. }
  3293. }
  3294. else
  3295. {
  3296. moveStack(sl, StackLocation(dst, pos));
  3297. }
  3298. }
  3299. }
  3300. bool CGameHandler::swapGarrisonOnSiege(ObjectInstanceID tid)
  3301. {
  3302. const CGTownInstance * town = getTown(tid);
  3303. if(!town->garrisonHero == !town->visitingHero)
  3304. return false;
  3305. SetHeroesInTown intown;
  3306. intown.tid = tid;
  3307. if(town->garrisonHero) //garrison -> vising
  3308. {
  3309. intown.garrison = ObjectInstanceID();
  3310. intown.visiting = town->garrisonHero->id;
  3311. }
  3312. else //visiting -> garrison
  3313. {
  3314. if(town->armedGarrison())
  3315. town->mergeGarrisonOnSiege();
  3316. intown.visiting = ObjectInstanceID();
  3317. intown.garrison = town->visitingHero->id;
  3318. }
  3319. sendAndApply(&intown);
  3320. return true;
  3321. }
  3322. bool CGameHandler::garrisonSwap(ObjectInstanceID tid)
  3323. {
  3324. const CGTownInstance * town = getTown(tid);
  3325. if (!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  3326. {
  3327. if (!town->visitingHero->canBeMergedWith(*town))
  3328. {
  3329. complain("Cannot make garrison swap, not enough free slots!");
  3330. return false;
  3331. }
  3332. moveArmy(town, town->visitingHero, true);
  3333. SetHeroesInTown intown;
  3334. intown.tid = tid;
  3335. intown.visiting = ObjectInstanceID();
  3336. intown.garrison = town->visitingHero->id;
  3337. sendAndApply(&intown);
  3338. return true;
  3339. }
  3340. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  3341. {
  3342. //check if moving hero out of town will break 8 wandering heroes limit
  3343. if (getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  3344. {
  3345. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  3346. return false;
  3347. }
  3348. SetHeroesInTown intown;
  3349. intown.tid = tid;
  3350. intown.garrison = ObjectInstanceID();
  3351. intown.visiting = town->garrisonHero->id;
  3352. sendAndApply(&intown);
  3353. return true;
  3354. }
  3355. else if (!!town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  3356. {
  3357. SetHeroesInTown intown;
  3358. intown.tid = tid;
  3359. intown.garrison = town->visitingHero->id;
  3360. intown.visiting = town->garrisonHero->id;
  3361. sendAndApply(&intown);
  3362. return true;
  3363. }
  3364. else
  3365. {
  3366. complain("Cannot swap garrison hero!");
  3367. return false;
  3368. }
  3369. }
  3370. // With the amount of changes done to the function, it's more like transferArtifacts.
  3371. // 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.
  3372. bool CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2)
  3373. {
  3374. ArtifactLocation src = al1, dst = al2;
  3375. const PlayerColor srcPlayer = src.owningPlayer(), dstPlayer = dst.owningPlayer();
  3376. const CArmedInstance *srcObj = src.relatedObj(), *dstObj = dst.relatedObj();
  3377. // Make sure exchange is even possible between the two heroes.
  3378. if(!isAllowedExchange(srcObj->id, dstObj->id))
  3379. COMPLAIN_RET("That heroes cannot make any exchange!");
  3380. const CArtifactInstance *srcArtifact = src.getArt();
  3381. const CArtifactInstance *destArtifact = dst.getArt();
  3382. const bool isDstSlotBackpack = ArtifactUtils::isSlotBackpack(dst.slot);
  3383. if(srcArtifact == nullptr)
  3384. COMPLAIN_RET("No artifact to move!");
  3385. if(destArtifact && srcPlayer != dstPlayer && !isDstSlotBackpack)
  3386. COMPLAIN_RET("Can't touch artifact on hero of another player!");
  3387. // Check if src/dest slots are appropriate for the artifacts exchanged.
  3388. // Moving to the backpack is always allowed.
  3389. if((!srcArtifact || !isDstSlotBackpack)
  3390. && srcArtifact && !srcArtifact->canBePutAt(dst, true))
  3391. COMPLAIN_RET("Cannot move artifact!");
  3392. auto srcSlot = src.getSlot();
  3393. auto dstSlot = dst.getSlot();
  3394. if((srcSlot && srcSlot->locked) || (dstSlot && dstSlot->locked))
  3395. COMPLAIN_RET("Cannot move artifact locks.");
  3396. if(isDstSlotBackpack && srcArtifact->artType->isBig())
  3397. COMPLAIN_RET("Cannot put big artifacts in backpack!");
  3398. if(src.slot == ArtifactPosition::MACH4 || dst.slot == ArtifactPosition::MACH4)
  3399. COMPLAIN_RET("Cannot move catapult!");
  3400. if(isDstSlotBackpack)
  3401. {
  3402. if(!ArtifactUtils::isBackpackFreeSlots(dst.getHolderArtSet()))
  3403. COMPLAIN_RET("Backpack is full!");
  3404. vstd::amin(dst.slot, GameConstants::BACKPACK_START + dst.getHolderArtSet()->artifactsInBackpack.size());
  3405. }
  3406. if(!(src.slot == ArtifactPosition::TRANSITION_POS && dst.slot == ArtifactPosition::TRANSITION_POS))
  3407. {
  3408. if(src.slot == dst.slot && src.artHolder == dst.artHolder)
  3409. COMPLAIN_RET("Won't move artifact: Dest same as source!");
  3410. // Check if dst slot is occupied
  3411. if(!isDstSlotBackpack && destArtifact)
  3412. {
  3413. // Previous artifact must be removed first
  3414. moveArtifact(dst, ArtifactLocation(dst.artHolder, ArtifactPosition::TRANSITION_POS));
  3415. }
  3416. try
  3417. {
  3418. auto hero = std::get<ConstTransitivePtr<CGHeroInstance>>(dst.artHolder);
  3419. if(ArtifactUtils::checkSpellbookIsNeeded(hero, srcArtifact->artType->getId(), dst.slot))
  3420. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3421. }
  3422. catch(const std::bad_variant_access &)
  3423. {
  3424. // object other than hero received an art - ignore
  3425. }
  3426. MoveArtifact ma(&src, &dst);
  3427. if(dst.slot == ArtifactPosition::TRANSITION_POS)
  3428. ma.askAssemble = false;
  3429. sendAndApply(&ma);
  3430. }
  3431. return true;
  3432. }
  3433. bool CGameHandler::bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap)
  3434. {
  3435. // Make sure exchange is even possible between the two heroes.
  3436. if(!isAllowedExchange(srcHero, dstHero))
  3437. COMPLAIN_RET("That heroes cannot make any exchange!");
  3438. auto psrcHero = getHero(srcHero);
  3439. auto pdstHero = getHero(dstHero);
  3440. if((!psrcHero) || (!pdstHero))
  3441. COMPLAIN_RET("bulkMoveArtifacts: wrong hero's ID");
  3442. BulkMoveArtifacts ma(static_cast<ConstTransitivePtr<CGHeroInstance>>(psrcHero),
  3443. static_cast<ConstTransitivePtr<CGHeroInstance>>(pdstHero), swap);
  3444. auto & slotsSrcDst = ma.artsPack0;
  3445. auto & slotsDstSrc = ma.artsPack1;
  3446. // Temporary fitting set for artifacts. Used to select available slots before sending data.
  3447. CArtifactFittingSet artFittingSet(pdstHero->bearerType());
  3448. auto moveArtifact = [this, &artFittingSet](const CArtifactInstance * artifact,
  3449. ArtifactPosition srcSlot, const CGHeroInstance * dstHero,
  3450. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  3451. {
  3452. assert(artifact);
  3453. auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, artifact->getTypeId());
  3454. if(dstSlot != ArtifactPosition::PRE_FIRST)
  3455. {
  3456. artFittingSet.putArtifact(dstSlot, static_cast<ConstTransitivePtr<CArtifactInstance>>(artifact));
  3457. slots.push_back(BulkMoveArtifacts::LinkedSlots(srcSlot, dstSlot));
  3458. if(ArtifactUtils::checkSpellbookIsNeeded(dstHero, artifact->getTypeId(), dstSlot))
  3459. giveHeroNewArtifact(dstHero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3460. }
  3461. };
  3462. if(swap)
  3463. {
  3464. auto moveArtsWorn = [moveArtifact](const CGHeroInstance * srcHero, const CGHeroInstance * dstHero,
  3465. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  3466. {
  3467. for(auto & artifact : srcHero->artifactsWorn)
  3468. {
  3469. if(ArtifactUtils::isArtRemovable(artifact))
  3470. moveArtifact(artifact.second.getArt(), artifact.first, dstHero, slots);
  3471. }
  3472. };
  3473. auto moveArtsInBackpack = [](const CArtifactSet * artSet,
  3474. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  3475. {
  3476. for(auto & slotInfo : artSet->artifactsInBackpack)
  3477. {
  3478. auto slot = artSet->getArtPos(slotInfo.artifact);
  3479. slots.push_back(BulkMoveArtifacts::LinkedSlots(slot, slot));
  3480. }
  3481. };
  3482. // Move over artifacts that are worn srcHero -> dstHero
  3483. moveArtsWorn(psrcHero, pdstHero, slotsSrcDst);
  3484. artFittingSet.artifactsWorn.clear();
  3485. // Move over artifacts that are worn dstHero -> srcHero
  3486. moveArtsWorn(pdstHero, psrcHero, slotsDstSrc);
  3487. // Move over artifacts that are in backpack srcHero -> dstHero
  3488. moveArtsInBackpack(psrcHero, slotsSrcDst);
  3489. // Move over artifacts that are in backpack dstHero -> srcHero
  3490. moveArtsInBackpack(pdstHero, slotsDstSrc);
  3491. }
  3492. else
  3493. {
  3494. artFittingSet.artifactsInBackpack = pdstHero->artifactsInBackpack;
  3495. artFittingSet.artifactsWorn = pdstHero->artifactsWorn;
  3496. // Move over artifacts that are worn
  3497. for(auto & artInfo : psrcHero->artifactsWorn)
  3498. {
  3499. if(ArtifactUtils::isArtRemovable(artInfo))
  3500. {
  3501. moveArtifact(psrcHero->getArt(artInfo.first), artInfo.first, pdstHero, slotsSrcDst);
  3502. }
  3503. }
  3504. // Move over artifacts that are in backpack
  3505. for(auto & slotInfo : psrcHero->artifactsInBackpack)
  3506. {
  3507. moveArtifact(psrcHero->getArt(psrcHero->getArtPos(slotInfo.artifact)),
  3508. psrcHero->getArtPos(slotInfo.artifact), pdstHero, slotsSrcDst);
  3509. }
  3510. }
  3511. sendAndApply(&ma);
  3512. return true;
  3513. }
  3514. /**
  3515. * Assembles or disassembles a combination artifact.
  3516. * @param heroID ID of hero holding the artifact(s).
  3517. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  3518. * @param assemble True for assembly operation, false for disassembly.
  3519. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  3520. * artifact to assemble to. Otherwise it's not used.
  3521. */
  3522. bool CGameHandler::assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  3523. {
  3524. const CGHeroInstance * hero = getHero(heroID);
  3525. const CArtifactInstance * destArtifact = hero->getArt(artifactSlot);
  3526. if(!destArtifact)
  3527. COMPLAIN_RET("assembleArtifacts: there is no such artifact instance!");
  3528. if(assemble)
  3529. {
  3530. CArtifact * combinedArt = VLC->arth->objects[assembleTo];
  3531. if(!combinedArt->constituents)
  3532. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to assemble is not a combined artifacts!");
  3533. if (!vstd::contains(ArtifactUtils::assemblyPossibilities(hero, destArtifact->getTypeId(),
  3534. ArtifactUtils::isSlotEquipment(artifactSlot)), combinedArt))
  3535. {
  3536. COMPLAIN_RET("assembleArtifacts: It's impossible to assemble requested artifact!");
  3537. }
  3538. if(ArtifactUtils::checkSpellbookIsNeeded(hero, assembleTo, artifactSlot))
  3539. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3540. AssembledArtifact aa;
  3541. aa.al = ArtifactLocation(hero, artifactSlot);
  3542. aa.builtArt = combinedArt;
  3543. sendAndApply(&aa);
  3544. }
  3545. else
  3546. {
  3547. if(!destArtifact->canBeDisassembled())
  3548. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is not a combined artifact!");
  3549. if(ArtifactUtils::isSlotBackpack(artifactSlot)
  3550. && !ArtifactUtils::isBackpackFreeSlots(hero, destArtifact->artType->constituents->size() - 1))
  3551. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble but backpack is full!");
  3552. DisassembledArtifact da;
  3553. da.al = ArtifactLocation(hero, artifactSlot);
  3554. sendAndApply(&da);
  3555. }
  3556. return true;
  3557. }
  3558. bool CGameHandler::eraseArtifactByClient(const ArtifactLocation & al)
  3559. {
  3560. const auto * hero = getHero(al.relatedObj()->id);
  3561. if(hero == nullptr)
  3562. COMPLAIN_RET("eraseArtifactByClient: wrong hero's ID");
  3563. const auto * art = al.getArt();
  3564. if(art == nullptr)
  3565. COMPLAIN_RET("Cannot remove artifact!");
  3566. if(al.getArt()->artType->canBePutAt(hero) || al.slot != ArtifactPosition::TRANSITION_POS)
  3567. COMPLAIN_RET("Illegal artifact removal request");
  3568. removeArtifact(al);
  3569. return true;
  3570. }
  3571. bool CGameHandler::buyArtifact(ObjectInstanceID hid, ArtifactID aid)
  3572. {
  3573. const CGHeroInstance * hero = getHero(hid);
  3574. COMPLAIN_RET_FALSE_IF(nullptr == hero, "Invalid hero index");
  3575. const CGTownInstance * town = hero->visitedTown;
  3576. COMPLAIN_RET_FALSE_IF(nullptr == town, "Hero not in town");
  3577. if (aid==ArtifactID::SPELLBOOK)
  3578. {
  3579. if ((!town->hasBuilt(BuildingID::MAGES_GUILD_1) && complain("Cannot buy a spellbook, no mage guild in the town!"))
  3580. || (getResource(hero->getOwner(), EGameResID::GOLD) < GameConstants::SPELLBOOK_GOLD_COST && complain("Cannot buy a spellbook, not enough gold!"))
  3581. || (hero->getArt(ArtifactPosition::SPELLBOOK) && complain("Cannot buy a spellbook, hero already has a one!"))
  3582. )
  3583. return false;
  3584. giveResource(hero->getOwner(),EGameResID::GOLD,-GameConstants::SPELLBOOK_GOLD_COST);
  3585. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3586. assert(hero->getArt(ArtifactPosition::SPELLBOOK));
  3587. giveSpells(town,hero);
  3588. return true;
  3589. }
  3590. else
  3591. {
  3592. const CArtifact * art = aid.toArtifact();
  3593. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid artifact index to buy");
  3594. COMPLAIN_RET_FALSE_IF(art->warMachine == CreatureID::NONE, "War machine artifact required");
  3595. COMPLAIN_RET_FALSE_IF(hero->hasArt(aid),"Hero already has this machine!");
  3596. const int price = art->price;
  3597. COMPLAIN_RET_FALSE_IF(getPlayerState(hero->getOwner())->resources[EGameResID::GOLD] < price, "Not enough gold!");
  3598. if ((town->hasBuilt(BuildingID::BLACKSMITH) && town->town->warMachine == aid)
  3599. || (town->hasBuilt(BuildingSubID::BALLISTA_YARD) && aid == ArtifactID::BALLISTA))
  3600. {
  3601. giveResource(hero->getOwner(),EGameResID::GOLD,-price);
  3602. return giveHeroNewArtifact(hero, art);
  3603. }
  3604. else
  3605. COMPLAIN_RET("This machine is unavailable here!");
  3606. }
  3607. }
  3608. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid)
  3609. {
  3610. if(!h)
  3611. COMPLAIN_RET("Only hero can buy artifacts!");
  3612. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_ARTIFACT), aid))
  3613. COMPLAIN_RET("That artifact is unavailable!");
  3614. int b1, b2;
  3615. m->getOffer(rid, aid, b1, b2, EMarketMode::RESOURCE_ARTIFACT);
  3616. if (getResource(h->tempOwner, rid) < b1)
  3617. COMPLAIN_RET("You can't afford to buy this artifact!");
  3618. giveResource(h->tempOwner, rid, -b1);
  3619. SetAvailableArtifacts saa;
  3620. if(dynamic_cast<const CGTownInstance *>(m))
  3621. {
  3622. saa.id = -1;
  3623. saa.arts = CGTownInstance::merchantArtifacts;
  3624. }
  3625. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m)) //black market
  3626. {
  3627. saa.id = bm->id.getNum();
  3628. saa.arts = bm->artifacts;
  3629. }
  3630. else
  3631. COMPLAIN_RET("Wrong marktet...");
  3632. bool found = false;
  3633. for (const CArtifact *&art : saa.arts)
  3634. {
  3635. if (art && art->getId() == aid)
  3636. {
  3637. art = nullptr;
  3638. found = true;
  3639. break;
  3640. }
  3641. }
  3642. if (!found)
  3643. COMPLAIN_RET("Cannot find selected artifact on the list");
  3644. sendAndApply(&saa);
  3645. giveHeroNewArtifact(h, VLC->arth->objects[aid], ArtifactPosition::FIRST_AVAILABLE);
  3646. return true;
  3647. }
  3648. bool CGameHandler::sellArtifact(const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid)
  3649. {
  3650. COMPLAIN_RET_FALSE_IF((!h), "Only hero can sell artifacts!");
  3651. const CArtifactInstance *art = h->getArtByInstanceId(aid);
  3652. COMPLAIN_RET_FALSE_IF((!art), "There is no artifact to sell!");
  3653. COMPLAIN_RET_FALSE_IF((!art->artType->isTradable()), "Cannot sell a war machine or spellbook!");
  3654. int resVal = 0, dump = 1;
  3655. m->getOffer(art->artType->getId(), rid, dump, resVal, EMarketMode::ARTIFACT_RESOURCE);
  3656. removeArtifact(ArtifactLocation(h, h->getArtPos(art)));
  3657. giveResource(h->tempOwner, rid, resVal);
  3658. return true;
  3659. }
  3660. bool CGameHandler::buySecSkill(const IMarket *m, const CGHeroInstance *h, SecondarySkill skill)
  3661. {
  3662. if (!h)
  3663. COMPLAIN_RET("You need hero to buy a skill!");
  3664. if (h->getSecSkillLevel(SecondarySkill(skill)))
  3665. COMPLAIN_RET("Hero already know this skill");
  3666. if (!h->canLearnSkill())
  3667. COMPLAIN_RET("Hero can't learn any more skills");
  3668. if (!h->canLearnSkill(skill))
  3669. COMPLAIN_RET("The hero can't learn this skill!");
  3670. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_SKILL), skill))
  3671. COMPLAIN_RET("That skill is unavailable!");
  3672. if (getResource(h->tempOwner, EGameResID::GOLD) < GameConstants::SKILL_GOLD_COST)//TODO: remove hardcoded resource\summ?
  3673. COMPLAIN_RET("You can't afford to buy this skill");
  3674. giveResource(h->tempOwner, EGameResID::GOLD, -GameConstants::SKILL_GOLD_COST);
  3675. changeSecSkill(h, skill, 1, true);
  3676. return true;
  3677. }
  3678. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2)
  3679. {
  3680. TResourceCap r1 = getPlayerState(player)->resources[id1];
  3681. vstd::amin(val, r1); //can't trade more resources than have
  3682. int b1, b2; //base quantities for trade
  3683. market->getOffer(id1, id2, b1, b2, EMarketMode::RESOURCE_RESOURCE);
  3684. int units = val / b1; //how many base quantities we trade
  3685. if (val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  3686. {
  3687. COMPLAIN_RET("Invalid deal, not all offered units of resource were used.");
  3688. }
  3689. giveResource(player, GameResID(id1), - b1 * units);
  3690. giveResource(player, GameResID(id2), b2 * units);
  3691. return true;
  3692. }
  3693. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID)
  3694. {
  3695. if(!hero)
  3696. COMPLAIN_RET("Only hero can sell creatures!");
  3697. if (!vstd::contains(hero->Slots(), slot))
  3698. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  3699. const CStackInstance &s = hero->getStack(slot);
  3700. if (s.count < (TQuantity)count //can't sell more creatures than have
  3701. || (hero->stacksCount() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack
  3702. {
  3703. COMPLAIN_RET("Not enough creatures in army!");
  3704. }
  3705. int b1, b2; //base quantities for trade
  3706. market->getOffer(s.type->getId(), resourceID, b1, b2, EMarketMode::CREATURE_RESOURCE);
  3707. int units = count / b1; //how many base quantities we trade
  3708. if (count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  3709. {
  3710. //TODO: complain?
  3711. assert(0);
  3712. }
  3713. changeStackCount(StackLocation(hero, slot), -(TQuantity)count);
  3714. giveResource(hero->tempOwner, resourceID, b2 * units);
  3715. return true;
  3716. }
  3717. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot)
  3718. {
  3719. const CArmedInstance *army = nullptr;
  3720. if (hero)
  3721. army = hero;
  3722. else
  3723. army = dynamic_cast<const CGTownInstance *>(market);
  3724. if (!army)
  3725. COMPLAIN_RET("Incorrect call to transform in undead!");
  3726. if (!army->hasStackAtSlot(slot))
  3727. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  3728. const CStackInstance &s = army->getStack(slot);
  3729. //resulting creature - bone dragons or skeletons
  3730. CreatureID resCreature = CreatureID::SKELETON;
  3731. if ((s.hasBonusOfType(BonusType::DRAGON_NATURE)
  3732. && !(s.hasBonusOfType(BonusType::UNDEAD)))
  3733. || (s.getCreatureID() == CreatureID::HYDRA)
  3734. || (s.getCreatureID() == CreatureID::CHAOS_HYDRA))
  3735. resCreature = CreatureID::BONE_DRAGON;
  3736. changeStackType(StackLocation(army, slot), resCreature.toCreature());
  3737. return true;
  3738. }
  3739. bool CGameHandler::sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2)
  3740. {
  3741. const PlayerState *p2 = getPlayerState(r2, false);
  3742. if (!p2 || p2->status != EPlayerStatus::INGAME)
  3743. {
  3744. complain("Dest player must be in game!");
  3745. return false;
  3746. }
  3747. TResourceCap curRes1 = getPlayerState(player)->resources[r1];
  3748. vstd::amin(val, curRes1);
  3749. giveResource(player, r1, -(int)val);
  3750. giveResource(r2, r1, val);
  3751. return true;
  3752. }
  3753. bool CGameHandler::setFormation(ObjectInstanceID hid, ui8 formation)
  3754. {
  3755. const CGHeroInstance *h = getHero(hid);
  3756. if (!h)
  3757. {
  3758. logGlobal->error("Hero doesn't exist!");
  3759. return false;
  3760. }
  3761. ChangeFormation cf;
  3762. cf.hid = hid;
  3763. cf.formation = formation;
  3764. sendAndApply(&cf);
  3765. return true;
  3766. }
  3767. bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, PlayerColor player)
  3768. {
  3769. const PlayerState * p = getPlayerState(player);
  3770. const CGTownInstance * t = getTown(obj->id);
  3771. //common preconditions
  3772. // if ((p->resources.at(EGameResID::GOLD)<GOLD_NEEDED && complain("Not enough gold for buying hero!"))
  3773. // || (getHeroCount(player, false) >= GameConstants::MAX_HEROES_PER_PLAYER && complain("Cannot hire hero, only 8 wandering heroes are allowed!")))
  3774. if ((p->resources[EGameResID::GOLD] < GameConstants::HERO_GOLD_COST && complain("Not enough gold for buying hero!"))
  3775. || ((getHeroCount(player, false) >= VLC->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP) && complain("Cannot hire hero, too many wandering heroes already!")))
  3776. || ((getHeroCount(player, true) >= VLC->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_TOTAL_CAP) && complain("Cannot hire hero, too many heroes garrizoned and wandering already!"))))
  3777. {
  3778. return false;
  3779. }
  3780. if (t) //tavern in town
  3781. {
  3782. if ((!t->hasBuilt(BuildingID::TAVERN) && complain("No tavern!"))
  3783. || (t->visitingHero && complain("There is visiting hero - no place!")))
  3784. {
  3785. return false;
  3786. }
  3787. }
  3788. else if (obj->ID == Obj::TAVERN)
  3789. {
  3790. if (getTile(obj->visitablePos())->visitableObjects.back() != obj && complain("Tavern entry must be unoccupied!"))
  3791. {
  3792. return false;
  3793. }
  3794. }
  3795. const CGHeroInstance *nh = p->availableHeroes.at(hid);
  3796. if (!nh)
  3797. {
  3798. complain ("Hero is not available for hiring!");
  3799. return false;
  3800. }
  3801. HeroRecruited hr;
  3802. hr.tid = obj->id;
  3803. hr.hid = nh->subID;
  3804. hr.player = player;
  3805. hr.tile = nh->convertFromVisitablePos(obj->visitablePos());
  3806. if (getTile(hr.tile)->isWater())
  3807. {
  3808. //Create a new boat for hero
  3809. createObject(obj->visitablePos(), Obj::BOAT, nh->getBoatType().getNum());
  3810. hr.boatId = getTopObj(hr.tile)->id;
  3811. }
  3812. sendAndApply(&hr);
  3813. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = gs->unusedHeroesFromPool();
  3814. const CGHeroInstance *theOtherHero = p->availableHeroes.at(!hid);
  3815. const CGHeroInstance *newHero = nullptr;
  3816. if (theOtherHero) //on XXL maps all heroes can be imprisoned :(
  3817. {
  3818. newHero = gs->hpool.pickHeroFor(false, player, getNativeTown(player), pool, getRandomGenerator(), theOtherHero->type->heroClass);
  3819. }
  3820. SetAvailableHeroes sah;
  3821. sah.player = player;
  3822. if (newHero)
  3823. {
  3824. sah.hid[hid] = newHero->subID;
  3825. sah.army[hid].clear();
  3826. sah.army[hid].setCreature(SlotID(0), newHero->type->initialArmy[0].creature, 1);
  3827. }
  3828. else
  3829. {
  3830. sah.hid[hid] = -1;
  3831. }
  3832. sah.hid[!hid] = theOtherHero ? theOtherHero->subID : -1;
  3833. sendAndApply(&sah);
  3834. giveResource(player, EGameResID::GOLD, -GameConstants::HERO_GOLD_COST);
  3835. if(t)
  3836. {
  3837. objectVisited(t, nh);
  3838. }
  3839. return true;
  3840. }
  3841. bool CGameHandler::queryReply(QueryID qid, const JsonNode & answer, PlayerColor player)
  3842. {
  3843. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3844. logGlobal->trace("Player %s attempts answering query %d with answer:", player, qid);
  3845. logGlobal->trace(answer.toJson());
  3846. auto topQuery = queries.topQuery(player);
  3847. COMPLAIN_RET_FALSE_IF(!topQuery, "This player doesn't have any queries!");
  3848. if(topQuery->queryID != qid)
  3849. {
  3850. auto currentQuery = queries.getQuery(qid);
  3851. if(currentQuery != nullptr && currentQuery->endsByPlayerAnswer())
  3852. currentQuery->setReply(answer);
  3853. COMPLAIN_RET("This player top query has different ID!"); //topQuery->queryID != qid
  3854. }
  3855. COMPLAIN_RET_FALSE_IF(!topQuery->endsByPlayerAnswer(), "This query cannot be ended by player's answer!");
  3856. topQuery->setReply(answer);
  3857. queries.popQuery(topQuery);
  3858. return true;
  3859. }
  3860. static EndAction end_action;
  3861. void CGameHandler::updateGateState()
  3862. {
  3863. // GATE_BRIDGE - leftmost tile, located over moat
  3864. // GATE_OUTER - central tile, mostly covered by gate image
  3865. // GATE_INNER - rightmost tile, inside the walls
  3866. // GATE_OUTER or GATE_INNER:
  3867. // - if defender moves unit on these tiles, bridge will open
  3868. // - if there is a creature (dead or alive) on these tiles, bridge will always remain open
  3869. // - blocked to attacker if bridge is closed
  3870. // GATE_BRIDGE
  3871. // - if there is a unit or corpse here, bridge can't open (and can't close in fortress)
  3872. // - if Force Field is cast here, bridge can't open (but can close, in any town)
  3873. // - deals moat damage to attacker if bridge is closed (fortress only)
  3874. bool hasForceFieldOnBridge = !battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), true).empty();
  3875. bool hasStackAtGateInner = gs->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_INNER), false) != nullptr;
  3876. bool hasStackAtGateOuter = gs->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_OUTER), false) != nullptr;
  3877. bool hasStackAtGateBridge = gs->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_BRIDGE), false) != nullptr;
  3878. bool hasWideMoat = vstd::contains_if(battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  3879. {
  3880. return obst->obstacleType == CObstacleInstance::MOAT;
  3881. });
  3882. BattleUpdateGateState db;
  3883. db.state = gs->curB->si.gateState;
  3884. if (gs->curB->si.wallState[EWallPart::GATE] == EWallState::DESTROYED)
  3885. {
  3886. db.state = EGateState::DESTROYED;
  3887. }
  3888. else if (db.state == EGateState::OPENED)
  3889. {
  3890. bool hasStackOnLongBridge = hasStackAtGateBridge && hasWideMoat;
  3891. bool gateCanClose = !hasStackAtGateInner && !hasStackAtGateOuter && !hasStackOnLongBridge;
  3892. if (gateCanClose)
  3893. db.state = EGateState::CLOSED;
  3894. else
  3895. db.state = EGateState::OPENED;
  3896. }
  3897. else // CLOSED or BLOCKED
  3898. {
  3899. bool gateBlocked = hasForceFieldOnBridge || hasStackAtGateBridge;
  3900. if (gateBlocked)
  3901. db.state = EGateState::BLOCKED;
  3902. else
  3903. db.state = EGateState::CLOSED;
  3904. }
  3905. if (db.state != gs->curB->si.gateState)
  3906. sendAndApply(&db);
  3907. }
  3908. bool CGameHandler::makeBattleAction(BattleAction &ba)
  3909. {
  3910. bool ok = true;
  3911. battle::Target target = ba.getTarget(gs->curB);
  3912. const CStack * stack = battleGetStackByID(ba.stackNumber); //may be nullptr if action is not about stack
  3913. const bool isAboutActiveStack = stack && (ba.stackNumber == gs->curB->getActiveStackID());
  3914. logGlobal->trace("Making action: %s", ba.toString());
  3915. switch(ba.actionType)
  3916. {
  3917. case EActionType::WALK: //walk
  3918. case EActionType::DEFEND: //defend
  3919. case EActionType::WAIT: //wait
  3920. case EActionType::WALK_AND_ATTACK: //walk or attack
  3921. case EActionType::SHOOT: //shoot
  3922. case EActionType::CATAPULT: //catapult
  3923. case EActionType::STACK_HEAL: //healing with First Aid Tent
  3924. case EActionType::MONSTER_SPELL:
  3925. if (!stack)
  3926. {
  3927. complain("No such stack!");
  3928. return false;
  3929. }
  3930. if (!stack->alive())
  3931. {
  3932. complain("This stack is dead: " + stack->nodeName());
  3933. return false;
  3934. }
  3935. if (battleTacticDist())
  3936. {
  3937. if (stack && stack->unitSide() != battleGetTacticsSide())
  3938. {
  3939. complain("This is not a stack of side that has tactics!");
  3940. return false;
  3941. }
  3942. }
  3943. else if (!isAboutActiveStack)
  3944. {
  3945. complain("Action has to be about active stack!");
  3946. return false;
  3947. }
  3948. }
  3949. auto wrapAction = [this](BattleAction &ba)
  3950. {
  3951. StartAction startAction(ba);
  3952. sendAndApply(&startAction);
  3953. return vstd::makeScopeGuard([&]()
  3954. {
  3955. sendAndApply(&end_action);
  3956. });
  3957. };
  3958. switch(ba.actionType)
  3959. {
  3960. case EActionType::END_TACTIC_PHASE: //wait
  3961. case EActionType::BAD_MORALE:
  3962. case EActionType::NO_ACTION:
  3963. {
  3964. auto wrapper = wrapAction(ba);
  3965. break;
  3966. }
  3967. case EActionType::WALK:
  3968. {
  3969. auto wrapper = wrapAction(ba);
  3970. if(target.size() < 1)
  3971. {
  3972. complain("Destination required for move action.");
  3973. ok = false;
  3974. break;
  3975. }
  3976. int walkedTiles = moveStack(ba.stackNumber, target.at(0).hexValue); //move
  3977. if (!walkedTiles)
  3978. complain("Stack failed movement!");
  3979. break;
  3980. }
  3981. case EActionType::DEFEND:
  3982. {
  3983. //defensive stance, TODO: filter out spell boosts from bonus (stone skin etc.)
  3984. SetStackEffect sse;
  3985. Bonus defenseBonusToAdd(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 20, -1, PrimarySkill::DEFENSE, BonusValueType::PERCENT_TO_ALL);
  3986. Bonus bonus2(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, stack->valOfBonuses(BonusType::DEFENSIVE_STANCE),
  3987. -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  3988. Bonus alternativeWeakCreatureBonus(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 1, -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  3989. BonusList defence = *stack->getBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, PrimarySkill::DEFENSE));
  3990. int oldDefenceValue = defence.totalValue();
  3991. defence.push_back(std::make_shared<Bonus>(defenseBonusToAdd));
  3992. defence.push_back(std::make_shared<Bonus>(bonus2));
  3993. int difference = defence.totalValue() - oldDefenceValue;
  3994. std::vector<Bonus> buffer;
  3995. if(difference == 0) //give replacement bonus for creatures not reaching 5 defense points (20% of def becomes 0)
  3996. {
  3997. difference = 1;
  3998. buffer.push_back(alternativeWeakCreatureBonus);
  3999. }
  4000. else
  4001. {
  4002. buffer.push_back(defenseBonusToAdd);
  4003. }
  4004. buffer.push_back(bonus2);
  4005. sse.toUpdate.push_back(std::make_pair(ba.stackNumber, buffer));
  4006. sendAndApply(&sse);
  4007. BattleLogMessage message;
  4008. MetaString text;
  4009. stack->addText(text, EMetaText::GENERAL_TXT, 120);
  4010. stack->addNameReplacement(text);
  4011. text.replaceNumber(difference);
  4012. message.lines.push_back(text);
  4013. sendAndApply(&message);
  4014. //don't break - we share code with next case
  4015. }
  4016. [[fallthrough]];
  4017. case EActionType::WAIT:
  4018. {
  4019. auto wrapper = wrapAction(ba);
  4020. break;
  4021. }
  4022. case EActionType::RETREAT: //retreat/flee
  4023. {
  4024. if (!gs->curB->battleCanFlee(gs->curB->sides.at(ba.side).color))
  4025. complain("Cannot retreat!");
  4026. else
  4027. setBattleResult(BattleResult::ESCAPE, !ba.side); //surrendering side loses
  4028. break;
  4029. }
  4030. case EActionType::SURRENDER:
  4031. {
  4032. PlayerColor player = gs->curB->sides.at(ba.side).color;
  4033. int cost = gs->curB->battleGetSurrenderCost(player);
  4034. if (cost < 0)
  4035. complain("Cannot surrender!");
  4036. else if (getResource(player, EGameResID::GOLD) < cost)
  4037. complain("Not enough gold to surrender!");
  4038. else
  4039. {
  4040. giveResource(player, EGameResID::GOLD, -cost);
  4041. setBattleResult(BattleResult::SURRENDER, !ba.side); //surrendering side loses
  4042. }
  4043. break;
  4044. }
  4045. case EActionType::WALK_AND_ATTACK: //walk or attack
  4046. {
  4047. auto wrapper = wrapAction(ba);
  4048. if(!stack)
  4049. {
  4050. complain("No attacker");
  4051. ok = false;
  4052. break;
  4053. }
  4054. if(target.size() < 2)
  4055. {
  4056. complain("Two destinations required for attack action.");
  4057. ok = false;
  4058. break;
  4059. }
  4060. BattleHex attackPos = target.at(0).hexValue;
  4061. BattleHex destinationTile = target.at(1).hexValue;
  4062. const CStack * destinationStack = gs->curB->battleGetStackByPos(destinationTile, true);
  4063. if(!destinationStack)
  4064. {
  4065. complain("Invalid target to attack");
  4066. ok = false;
  4067. break;
  4068. }
  4069. BattleHex startingPos = stack->getPosition();
  4070. int distance = moveStack(ba.stackNumber, attackPos);
  4071. logGlobal->trace("%s will attack %s", stack->nodeName(), destinationStack->nodeName());
  4072. if(stack->getPosition() != attackPos
  4073. && !(stack->doubleWide() && (stack->getPosition() == attackPos.cloneInDirection(stack->destShiftDir(), false)))
  4074. )
  4075. {
  4076. // we were not able to reach destination tile, nor occupy specified hex
  4077. // abort attack attempt, but treat this case as legal - we may have stepped onto a quicksands/mine
  4078. break;
  4079. }
  4080. if(destinationStack && stack->unitId() == destinationStack->unitId()) //we should just move, it will be handled by following check
  4081. {
  4082. destinationStack = nullptr;
  4083. }
  4084. if(!destinationStack)
  4085. {
  4086. complain("Unit can not attack itself");
  4087. ok = false;
  4088. break;
  4089. }
  4090. if(!CStack::isMeleeAttackPossible(stack, destinationStack))
  4091. {
  4092. complain("Attack cannot be performed!");
  4093. ok = false;
  4094. break;
  4095. }
  4096. //attack
  4097. int totalAttacks = stack->totalAttacks.getMeleeValue();
  4098. //TODO: move to CUnitState
  4099. const auto * attackingHero = gs->curB->battleGetFightingHero(ba.side);
  4100. if(attackingHero)
  4101. {
  4102. totalAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, stack->creatureIndex());
  4103. }
  4104. const bool firstStrike = destinationStack->hasBonusOfType(BonusType::FIRST_STRIKE);
  4105. const bool retaliation = destinationStack->ableToRetaliate();
  4106. for (int i = 0; i < totalAttacks; ++i)
  4107. {
  4108. //first strike
  4109. if(i == 0 && firstStrike && retaliation)
  4110. {
  4111. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, false, true);
  4112. }
  4113. //move can cause death, eg. by walking into the moat, first strike can cause death or paralysis/petrification
  4114. if(stack->alive() && !stack->hasBonusOfType(BonusType::NOT_ACTIVE) && destinationStack->alive())
  4115. {
  4116. makeAttack(stack, destinationStack, (i ? 0 : distance), destinationTile, i==0, false, false);//no distance travelled on second attack
  4117. }
  4118. //counterattack
  4119. //we check retaliation twice, so if it unblocked during attack it will work only on next attack
  4120. if(stack->alive()
  4121. && !stack->hasBonusOfType(BonusType::BLOCKS_RETALIATION)
  4122. && (i == 0 && !firstStrike)
  4123. && retaliation && destinationStack->ableToRetaliate())
  4124. {
  4125. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, false, true);
  4126. }
  4127. }
  4128. //return
  4129. if(stack->hasBonusOfType(BonusType::RETURN_AFTER_STRIKE)
  4130. && target.size() == 3
  4131. && startingPos != stack->getPosition()
  4132. && startingPos == target.at(2).hexValue
  4133. && stack->alive())
  4134. {
  4135. moveStack(ba.stackNumber, startingPos);
  4136. //NOTE: curStack->unitId() == ba.stackNumber (rev 1431)
  4137. }
  4138. break;
  4139. }
  4140. case EActionType::SHOOT:
  4141. {
  4142. if(target.size() < 1)
  4143. {
  4144. complain("Destination required for shot action.");
  4145. ok = false;
  4146. break;
  4147. }
  4148. auto destination = target.at(0).hexValue;
  4149. const CStack * destinationStack = gs->curB->battleGetStackByPos(destination);
  4150. if (!gs->curB->battleCanShoot(stack, destination))
  4151. {
  4152. complain("Cannot shoot!");
  4153. break;
  4154. }
  4155. if (!destinationStack)
  4156. {
  4157. complain("No target to shoot!");
  4158. break;
  4159. }
  4160. auto wrapper = wrapAction(ba);
  4161. makeAttack(stack, destinationStack, 0, destination, true, true, false);
  4162. //ranged counterattack
  4163. if (destinationStack->hasBonusOfType(BonusType::RANGED_RETALIATION)
  4164. && !stack->hasBonusOfType(BonusType::BLOCKS_RANGED_RETALIATION)
  4165. && destinationStack->ableToRetaliate()
  4166. && gs->curB->battleCanShoot(destinationStack, stack->getPosition())
  4167. && stack->alive()) //attacker may have died (fire shield)
  4168. {
  4169. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, true, true);
  4170. }
  4171. //allow more than one additional attack
  4172. int totalRangedAttacks = stack->totalAttacks.getRangedValue();
  4173. //TODO: move to CUnitState
  4174. const auto * attackingHero = gs->curB->battleGetFightingHero(ba.side);
  4175. if(attackingHero)
  4176. {
  4177. totalRangedAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, stack->creatureIndex());
  4178. }
  4179. for(int i = 1; i < totalRangedAttacks; ++i)
  4180. {
  4181. if(
  4182. stack->alive()
  4183. && destinationStack->alive()
  4184. && stack->shots.canUse()
  4185. )
  4186. {
  4187. makeAttack(stack, destinationStack, 0, destination, false, true, false);
  4188. }
  4189. }
  4190. break;
  4191. }
  4192. case EActionType::CATAPULT:
  4193. {
  4194. auto wrapper = wrapAction(ba);
  4195. const CStack * shooter = gs->curB->battleGetStackByID(ba.stackNumber);
  4196. std::shared_ptr<const Bonus> catapultAbility = stack->getBonusLocalFirst(Selector::type()(BonusType::CATAPULT));
  4197. if(!catapultAbility || catapultAbility->subtype < 0)
  4198. {
  4199. complain("We do not know how to shoot :P");
  4200. }
  4201. else
  4202. {
  4203. const CSpell * spell = SpellID(catapultAbility->subtype).toSpell();
  4204. spells::BattleCast parameters(gs->curB, shooter, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can shot infinitely by catapult
  4205. auto shotLevel = stack->valOfBonuses(Selector::typeSubtype(BonusType::CATAPULT_EXTRA_SHOTS, catapultAbility->subtype));
  4206. parameters.setSpellLevel(shotLevel);
  4207. parameters.cast(spellEnv, target);
  4208. }
  4209. //finish by scope guard
  4210. break;
  4211. }
  4212. case EActionType::STACK_HEAL: //healing with First Aid Tent
  4213. {
  4214. auto wrapper = wrapAction(ba);
  4215. const CStack * healer = gs->curB->battleGetStackByID(ba.stackNumber);
  4216. if(target.size() < 1)
  4217. {
  4218. complain("Destination required for heal action.");
  4219. ok = false;
  4220. break;
  4221. }
  4222. const battle::Unit * destStack = nullptr;
  4223. std::shared_ptr<const Bonus> healerAbility = stack->getBonusLocalFirst(Selector::type()(BonusType::HEALER));
  4224. if(target.at(0).unitValue)
  4225. destStack = target.at(0).unitValue;
  4226. else
  4227. destStack = gs->curB->battleGetUnitByPos(target.at(0).hexValue);
  4228. if(healer == nullptr || destStack == nullptr || !healerAbility || healerAbility->subtype < 0)
  4229. {
  4230. complain("There is either no healer, no destination, or healer cannot heal :P");
  4231. }
  4232. else
  4233. {
  4234. const CSpell * spell = SpellID(healerAbility->subtype).toSpell();
  4235. spells::BattleCast parameters(gs->curB, healer, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can heal infinitely by first aid tent
  4236. auto dest = battle::Destination(destStack, target.at(0).hexValue);
  4237. parameters.setSpellLevel(0);
  4238. parameters.cast(spellEnv, {dest});
  4239. }
  4240. break;
  4241. }
  4242. case EActionType::MONSTER_SPELL:
  4243. {
  4244. auto wrapper = wrapAction(ba);
  4245. const CStack * stack = gs->curB->battleGetStackByID(ba.stackNumber);
  4246. SpellID spellID = SpellID(ba.actionSubtype);
  4247. std::shared_ptr<const Bonus> randSpellcaster = stack->getBonus(Selector::type()(BonusType::RANDOM_SPELLCASTER));
  4248. std::shared_ptr<const Bonus> spellcaster = stack->getBonus(Selector::typeSubtype(BonusType::SPELLCASTER, spellID));
  4249. //TODO special bonus for genies ability
  4250. if (randSpellcaster && battleGetRandomStackSpell(getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_AIMED) < 0)
  4251. spellID = battleGetRandomStackSpell(getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_GENIE);
  4252. if (spellID < 0)
  4253. complain("That stack can't cast spells!");
  4254. else
  4255. {
  4256. const CSpell * spell = SpellID(spellID).toSpell();
  4257. spells::BattleCast parameters(gs->curB, stack, spells::Mode::CREATURE_ACTIVE, spell);
  4258. int32_t spellLvl = 0;
  4259. if(spellcaster)
  4260. vstd::amax(spellLvl, spellcaster->val);
  4261. if(randSpellcaster)
  4262. vstd::amax(spellLvl, randSpellcaster->val);
  4263. parameters.setSpellLevel(spellLvl);
  4264. parameters.cast(spellEnv, target);
  4265. }
  4266. break;
  4267. }
  4268. }
  4269. if(ba.actionType == EActionType::WAIT || ba.actionType == EActionType::DEFEND
  4270. || ba.actionType == EActionType::SHOOT || ba.actionType == EActionType::MONSTER_SPELL)
  4271. handleObstacleTriggersForUnit(*spellEnv, *stack);
  4272. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  4273. battleMadeAction.setn(true);
  4274. return ok;
  4275. }
  4276. void CGameHandler::playerMessage(PlayerColor player, const std::string &message, ObjectInstanceID currObj)
  4277. {
  4278. bool cheated = false;
  4279. if(!getPlayerSettings(player)->isControlledByAI())
  4280. {
  4281. PlayerMessageClient temp_message(player, message);
  4282. sendAndApply(&temp_message);
  4283. }
  4284. std::vector<std::string> words;
  4285. boost::split(words, message, boost::is_any_of(" "));
  4286. bool isHost = false;
  4287. for(auto & c : connections[player])
  4288. if(lobby->isClientHost(c->connectionID))
  4289. isHost = true;
  4290. if(isHost && words.size() >= 2 && words[0] == "game")
  4291. {
  4292. if(words[1] == "exit" || words[1] == "quit" || words[1] == "end")
  4293. {
  4294. SystemMessage temp_message("game was terminated");
  4295. sendAndApply(&temp_message);
  4296. lobby->state = EServerState::SHUTDOWN;
  4297. return;
  4298. }
  4299. if(words.size() == 3 && words[1] == "save")
  4300. {
  4301. save("Saves/" + words[2]);
  4302. SystemMessage temp_message("game saved as " + words[2]);
  4303. sendAndApply(&temp_message);
  4304. return;
  4305. }
  4306. if(words.size() == 3 && words[1] == "kick")
  4307. {
  4308. auto playername = words[2];
  4309. PlayerColor playerToKick(PlayerColor::CANNOT_DETERMINE);
  4310. if(std::all_of(playername.begin(), playername.end(), ::isdigit))
  4311. playerToKick = PlayerColor(std::stoi(playername));
  4312. else
  4313. {
  4314. for(auto & c : connections)
  4315. {
  4316. if(c.first.getStr(false) == playername)
  4317. playerToKick = c.first;
  4318. }
  4319. }
  4320. if(playerToKick != PlayerColor::CANNOT_DETERMINE)
  4321. {
  4322. PlayerCheated pc;
  4323. pc.player = playerToKick;
  4324. pc.losingCheatCode = true;
  4325. sendAndApply(&pc);
  4326. checkVictoryLossConditionsForPlayer(playerToKick);
  4327. }
  4328. return;
  4329. }
  4330. }
  4331. int obj = 0;
  4332. if (words.size() == 2 && words[0] != "vcmiexp" && words[0] != "vcmiolorin")
  4333. {
  4334. obj = std::atoi(words[1].c_str());
  4335. if (obj)
  4336. currObj = ObjectInstanceID(obj);
  4337. }
  4338. const CGHeroInstance * hero = getHero(currObj);
  4339. const CGTownInstance * town = getTown(currObj);
  4340. if (!town && hero)
  4341. town = hero->visitedTown;
  4342. if(words.size() > 1 && (words[0] == "vcmiarmy" || words[0] == "vcminissi" || words[0] == "vcmiexp" || words[0] == "vcmiolorin"))
  4343. {
  4344. std::string cheatCodeWithOneParameter = std::string(words[0]) + " " + words[1];
  4345. handleCheatCode(cheatCodeWithOneParameter, player, hero, town, cheated);
  4346. }
  4347. else if (words.size() == 1 || obj)
  4348. {
  4349. handleCheatCode(words[0], player, hero, town, cheated);
  4350. }
  4351. else
  4352. {
  4353. for (const auto & i : gs->players)
  4354. {
  4355. if (i.first == PlayerColor::NEUTRAL)
  4356. continue;
  4357. if (words[1] == "ai")
  4358. {
  4359. if (i.second.human)
  4360. continue;
  4361. }
  4362. else if (words[1] != "all" && words[1] != i.first.getStr())
  4363. continue;
  4364. if (words[0] == "vcmiformenos" || words[0] == "vcmieagles" || words[0] == "vcmiungoliant"
  4365. || words[0] == "vcmiresources" || words[0] == "vcmimap" || words[0] == "vcmihidemap")
  4366. {
  4367. handleCheatCode(words[0], i.first, nullptr, nullptr, cheated);
  4368. }
  4369. else if (words[0] == "vcmiarmenelos" || words[0] == "vcmibuild")
  4370. {
  4371. for (const auto & t : i.second.towns)
  4372. {
  4373. handleCheatCode(words[0], i.first, nullptr, t, cheated);
  4374. }
  4375. }
  4376. else
  4377. {
  4378. for (const auto & h : i.second.heroes)
  4379. {
  4380. handleCheatCode(words[0], i.first, h, nullptr, cheated);
  4381. }
  4382. }
  4383. }
  4384. }
  4385. if (cheated)
  4386. {
  4387. if(!getPlayerSettings(player)->isControlledByAI())
  4388. {
  4389. SystemMessage temp_message(VLC->generaltexth->allTexts[260]);
  4390. sendAndApply(&temp_message);
  4391. }
  4392. if(!player.isSpectator())
  4393. checkVictoryLossConditionsForPlayer(player);//Player enter win code or got required art\creature
  4394. }
  4395. }
  4396. bool CGameHandler::makeCustomAction(BattleAction & ba)
  4397. {
  4398. switch(ba.actionType)
  4399. {
  4400. case EActionType::HERO_SPELL:
  4401. {
  4402. COMPLAIN_RET_FALSE_IF(ba.side > 1, "Side must be 0 or 1!");
  4403. const CGHeroInstance *h = gs->curB->battleGetFightingHero(ba.side);
  4404. COMPLAIN_RET_FALSE_IF((!h), "Wrong caster!");
  4405. const CSpell * s = SpellID(ba.actionSubtype).toSpell();
  4406. if (!s)
  4407. {
  4408. logGlobal->error("Wrong spell id (%d)!", ba.actionSubtype);
  4409. return false;
  4410. }
  4411. spells::BattleCast parameters(gs->curB, h, spells::Mode::HERO, s);
  4412. spells::detail::ProblemImpl problem;
  4413. auto m = s->battleMechanics(&parameters);
  4414. if(!m->canBeCast(problem))//todo: should we check aimed cast?
  4415. {
  4416. logGlobal->warn("Spell cannot be cast!");
  4417. std::vector<std::string> texts;
  4418. problem.getAll(texts);
  4419. for(auto s : texts)
  4420. logGlobal->warn(s);
  4421. return false;
  4422. }
  4423. StartAction start_action(ba);
  4424. sendAndApply(&start_action); //start spell casting
  4425. parameters.cast(spellEnv, ba.getTarget(gs->curB));
  4426. sendAndApply(&end_action);
  4427. if (!gs->curB->battleGetStackByID(gs->curB->activeStack))
  4428. {
  4429. battleMadeAction.setn(true);
  4430. }
  4431. checkBattleStateChanges();
  4432. if (battleResult.get())
  4433. {
  4434. battleMadeAction.setn(true);
  4435. //battle will be ended by startBattle function
  4436. //endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  4437. }
  4438. return true;
  4439. }
  4440. }
  4441. return false;
  4442. }
  4443. void CGameHandler::stackEnchantedTrigger(const CStack * st)
  4444. {
  4445. auto bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTED)));
  4446. for(auto b : bl)
  4447. {
  4448. const CSpell * sp = SpellID(b->subtype).toSpell();
  4449. if(!sp)
  4450. continue;
  4451. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  4452. const int32_t level = ((val > 3) ? (val - 3) : val);
  4453. spells::BattleCast battleCast(gs->curB, st, spells::Mode::PASSIVE, sp);
  4454. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  4455. battleCast.setEffectDuration(50);
  4456. battleCast.setSpellLevel(level);
  4457. spells::Target target;
  4458. if(val > 3)
  4459. {
  4460. for(auto s : gs->curB->battleGetAllStacks())
  4461. if(battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  4462. target.emplace_back(s);
  4463. }
  4464. else
  4465. {
  4466. target.emplace_back(st);
  4467. }
  4468. battleCast.applyEffects(spellEnv, target, false, true);
  4469. }
  4470. }
  4471. void CGameHandler::stackTurnTrigger(const CStack *st)
  4472. {
  4473. BattleTriggerEffect bte;
  4474. bte.stackID = st->unitId();
  4475. bte.effect = -1;
  4476. bte.val = 0;
  4477. bte.additionalInfo = 0;
  4478. if (st->alive())
  4479. {
  4480. //unbind
  4481. if (st->hasBonus(Selector::type()(BonusType::BIND_EFFECT)))
  4482. {
  4483. bool unbind = true;
  4484. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::BIND_EFFECT)));
  4485. auto adjacent = gs->curB->battleAdjacentUnits(st);
  4486. for (auto b : bl)
  4487. {
  4488. if(b->additionalInfo != CAddInfo::NONE)
  4489. {
  4490. const CStack * stack = gs->curB->battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  4491. if(stack)
  4492. {
  4493. if(vstd::contains(adjacent, stack)) //binding stack is still present
  4494. unbind = false;
  4495. }
  4496. }
  4497. else
  4498. {
  4499. unbind = false;
  4500. }
  4501. }
  4502. if (unbind)
  4503. {
  4504. BattleSetStackProperty ssp;
  4505. ssp.which = BattleSetStackProperty::UNBIND;
  4506. ssp.stackID = st->unitId();
  4507. sendAndApply(&ssp);
  4508. }
  4509. }
  4510. if (st->hasBonusOfType(BonusType::POISON))
  4511. {
  4512. std::shared_ptr<const Bonus> b = st->getBonusLocalFirst(Selector::source(BonusSource::SPELL_EFFECT, SpellID::POISON).And(Selector::type()(BonusType::STACK_HEALTH)));
  4513. if (b) //TODO: what if not?...
  4514. {
  4515. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  4516. if (bte.val < b->val) //(negative) poison effect increases - update it
  4517. {
  4518. bte.effect = vstd::to_underlying(BonusType::POISON);
  4519. sendAndApply(&bte);
  4520. }
  4521. }
  4522. }
  4523. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  4524. {
  4525. const PlayerColor opponent = gs->curB->otherPlayer(gs->curB->battleGetOwner(st));
  4526. const CGHeroInstance * opponentHero = gs->curB->getHero(opponent);
  4527. if(opponentHero)
  4528. {
  4529. ui32 manaDrained = st->valOfBonuses(BonusType::MANA_DRAIN);
  4530. vstd::amin(manaDrained, opponentHero->mana);
  4531. if(manaDrained)
  4532. {
  4533. bte.effect = vstd::to_underlying(BonusType::MANA_DRAIN);
  4534. bte.val = manaDrained;
  4535. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  4536. sendAndApply(&bte);
  4537. }
  4538. }
  4539. }
  4540. if (st->isLiving() && !st->hasBonusOfType(BonusType::FEARLESS))
  4541. {
  4542. bool fearsomeCreature = false;
  4543. for (CStack * stack : gs->curB->stacks)
  4544. {
  4545. if (battleMatchOwner(st, stack) && stack->alive() && stack->hasBonusOfType(BonusType::FEAR))
  4546. {
  4547. fearsomeCreature = true;
  4548. break;
  4549. }
  4550. }
  4551. if (fearsomeCreature)
  4552. {
  4553. if (getRandomGenerator().nextInt(99) < 10) //fixed 10%
  4554. {
  4555. bte.effect = vstd::to_underlying(BonusType::FEAR);
  4556. sendAndApply(&bte);
  4557. }
  4558. }
  4559. }
  4560. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTER)));
  4561. int side = gs->curB->whatSide(st->unitOwner());
  4562. if(st->canCast() && gs->curB->battleGetEnchanterCounter(side) == 0)
  4563. {
  4564. bool cast = false;
  4565. while(!bl.empty() && !cast)
  4566. {
  4567. auto bonus = *RandomGeneratorUtil::nextItem(bl, getRandomGenerator());
  4568. auto spellID = SpellID(bonus->subtype);
  4569. const CSpell * spell = SpellID(spellID).toSpell();
  4570. bl.remove_if([&bonus](const Bonus * b)
  4571. {
  4572. return b == bonus.get();
  4573. });
  4574. spells::BattleCast parameters(gs->curB, st, spells::Mode::ENCHANTER, spell);
  4575. parameters.setSpellLevel(bonus->val);
  4576. parameters.massive = true;
  4577. parameters.smart = true;
  4578. //todo: recheck effect level
  4579. if(parameters.castIfPossible(spellEnv, spells::Target(1, spells::Destination())))
  4580. {
  4581. cast = true;
  4582. int cooldown = bonus->additionalInfo[0];
  4583. BattleSetStackProperty ssp;
  4584. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  4585. ssp.absolute = false;
  4586. ssp.val = cooldown;
  4587. ssp.stackID = st->unitId();
  4588. sendAndApply(&ssp);
  4589. }
  4590. }
  4591. }
  4592. }
  4593. }
  4594. void CGameHandler::handleTimeEvents()
  4595. {
  4596. gs->map->events.sort(evntCmp);
  4597. while(gs->map->events.size() && gs->map->events.front().firstOccurence+1 == gs->day)
  4598. {
  4599. CMapEvent ev = gs->map->events.front();
  4600. for (int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
  4601. {
  4602. auto color = PlayerColor(player);
  4603. const PlayerState * pinfo = getPlayerState(color, false); //do not output error if player does not exist
  4604. if (pinfo //player exists
  4605. && (ev.players & 1<<player) //event is enabled to this player
  4606. && ((ev.computerAffected && !pinfo->human)
  4607. || (ev.humanAffected && pinfo->human)
  4608. )
  4609. )
  4610. {
  4611. //give resources
  4612. giveResources(color, ev.resources);
  4613. //prepare dialog
  4614. InfoWindow iw;
  4615. iw.player = color;
  4616. iw.text.appendRawString(ev.message);
  4617. for (int i=0; i<ev.resources.size(); i++)
  4618. {
  4619. if (ev.resources[i]) //if resource is changed, we add it to the dialog
  4620. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,ev.resources[i],0);
  4621. }
  4622. sendAndApply(&iw); //show dialog
  4623. }
  4624. } //PLAYERS LOOP
  4625. if (ev.nextOccurence)
  4626. {
  4627. gs->map->events.pop_front();
  4628. ev.firstOccurence += ev.nextOccurence;
  4629. auto it = gs->map->events.begin();
  4630. while(it != gs->map->events.end() && it->earlierThanOrEqual(ev))
  4631. it++;
  4632. gs->map->events.insert(it, ev);
  4633. }
  4634. else
  4635. {
  4636. gs->map->events.pop_front();
  4637. }
  4638. }
  4639. //TODO send only if changed
  4640. UpdateMapEvents ume;
  4641. ume.events = gs->map->events;
  4642. sendAndApply(&ume);
  4643. }
  4644. void CGameHandler::handleTownEvents(CGTownInstance * town, NewTurn &n)
  4645. {
  4646. town->events.sort(evntCmp);
  4647. while(town->events.size() && town->events.front().firstOccurence == gs->day)
  4648. {
  4649. PlayerColor player = town->tempOwner;
  4650. CCastleEvent ev = town->events.front();
  4651. const PlayerState * pinfo = getPlayerState(player, false);
  4652. if (pinfo //player exists
  4653. && (ev.players & 1<<player.getNum()) //event is enabled to this player
  4654. && ((ev.computerAffected && !pinfo->human)
  4655. || (ev.humanAffected && pinfo->human)))
  4656. {
  4657. // dialog
  4658. InfoWindow iw;
  4659. iw.player = player;
  4660. iw.text.appendRawString(ev.message);
  4661. if (ev.resources.nonZero())
  4662. {
  4663. TResources was = n.res[player];
  4664. n.res[player] += ev.resources;
  4665. n.res[player].amax(0);
  4666. for (int i=0; i<ev.resources.size(); i++)
  4667. if (ev.resources[i] && pinfo->resources[i] != n.res.at(player)[i]) //if resource had changed, we add it to the dialog
  4668. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,n.res.at(player)[i]-was[i],0);
  4669. }
  4670. for (auto & i : ev.buildings)
  4671. {
  4672. if (!town->hasBuilt(i))
  4673. {
  4674. buildStructure(town->id, i, true);
  4675. iw.components.emplace_back(Component::EComponentType::BUILDING, town->subID, i, 0);
  4676. }
  4677. }
  4678. if (!ev.creatures.empty() && !vstd::contains(n.cres, town->id))
  4679. {
  4680. n.cres[town->id].tid = town->id;
  4681. n.cres[town->id].creatures = town->creatures;
  4682. }
  4683. auto & sac = n.cres[town->id];
  4684. for (si32 i=0;i<ev.creatures.size();i++) //creature growths
  4685. {
  4686. if (!town->creatures.at(i).second.empty() && ev.creatures.at(i) > 0)//there is dwelling
  4687. {
  4688. sac.creatures[i].first += ev.creatures.at(i);
  4689. iw.components.emplace_back(Component::EComponentType::CREATURE,
  4690. town->creatures.at(i).second.back(), ev.creatures.at(i), 0);
  4691. }
  4692. }
  4693. sendAndApply(&iw); //show dialog
  4694. }
  4695. if (ev.nextOccurence)
  4696. {
  4697. town->events.pop_front();
  4698. ev.firstOccurence += ev.nextOccurence;
  4699. auto it = town->events.begin();
  4700. while(it != town->events.end() && it->earlierThanOrEqual(ev))
  4701. it++;
  4702. town->events.insert(it, ev);
  4703. }
  4704. else
  4705. {
  4706. town->events.pop_front();
  4707. }
  4708. }
  4709. //TODO send only if changed
  4710. UpdateCastleEvents uce;
  4711. uce.town = town->id;
  4712. uce.events = town->events;
  4713. sendAndApply(&uce);
  4714. }
  4715. bool CGameHandler::complain(const std::string &problem)
  4716. {
  4717. sendMessageToAll("Server encountered a problem: " + problem);
  4718. logGlobal->error(problem);
  4719. return true;
  4720. }
  4721. void CGameHandler::showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits)
  4722. {
  4723. //PlayerColor player = getOwner(hid);
  4724. auto upperArmy = dynamic_cast<const CArmedInstance*>(getObj(upobj));
  4725. auto lowerArmy = dynamic_cast<const CArmedInstance*>(getObj(hid));
  4726. assert(lowerArmy);
  4727. assert(upperArmy);
  4728. auto garrisonQuery = std::make_shared<CGarrisonDialogQuery>(this, upperArmy, lowerArmy);
  4729. queries.addQuery(garrisonQuery);
  4730. GarrisonDialog gd;
  4731. gd.hid = hid;
  4732. gd.objid = upobj;
  4733. gd.removableUnits = removableUnits;
  4734. gd.queryID = garrisonQuery->queryID;
  4735. sendAndApply(&gd);
  4736. }
  4737. void CGameHandler::showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId)
  4738. {
  4739. OpenWindow ow;
  4740. ow.window = EOpenWindowMode::THIEVES_GUILD;
  4741. ow.id1 = player.getNum();
  4742. ow.id2 = requestingObjId.getNum();
  4743. sendAndApply(&ow);
  4744. }
  4745. bool CGameHandler::isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2)
  4746. {
  4747. if (id1 == id2)
  4748. return true;
  4749. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  4750. if (!o1 || !o2)
  4751. return true; //arranging stacks within an object should be always allowed
  4752. if (o1 && o2)
  4753. {
  4754. if (o1->ID == Obj::TOWN)
  4755. {
  4756. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  4757. if (t->visitingHero == o2 || t->garrisonHero == o2)
  4758. return true;
  4759. }
  4760. if (o2->ID == Obj::TOWN)
  4761. {
  4762. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  4763. if (t->visitingHero == o1 || t->garrisonHero == o1)
  4764. return true;
  4765. }
  4766. if (o1->ID == Obj::HERO && o2->ID == Obj::HERO)
  4767. {
  4768. const CGHeroInstance *h1 = static_cast<const CGHeroInstance*>(o1);
  4769. const CGHeroInstance *h2 = static_cast<const CGHeroInstance*>(o2);
  4770. // two heroes in same town (garrisoned and visiting)
  4771. if (h1->visitedTown != nullptr && h2->visitedTown != nullptr && h1->visitedTown == h2->visitedTown)
  4772. return true;
  4773. }
  4774. //Ongoing garrison exchange - usually picking from top garison (from o1 to o2), but who knows
  4775. auto dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries.topQuery(o1->tempOwner));
  4776. if (!dialog)
  4777. {
  4778. dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries.topQuery(o2->tempOwner));
  4779. }
  4780. if (dialog)
  4781. {
  4782. auto topArmy = dialog->exchangingArmies.at(0);
  4783. auto bottomArmy = dialog->exchangingArmies.at(1);
  4784. if ((topArmy == o1 && bottomArmy == o2) || (bottomArmy == o1 && topArmy == o2))
  4785. return true;
  4786. }
  4787. }
  4788. return false;
  4789. }
  4790. void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInstance * h)
  4791. {
  4792. using events::ObjectVisitStarted;
  4793. logGlobal->debug("%s visits %s (%d:%d)", h->nodeName(), obj->getObjectName(), obj->ID, obj->subID);
  4794. std::shared_ptr<CObjectVisitQuery> visitQuery;
  4795. auto startVisit = [&](ObjectVisitStarted & event)
  4796. {
  4797. auto visitedObject = obj;
  4798. if(obj->ID == Obj::HERO)
  4799. {
  4800. auto visitedHero = static_cast<const CGHeroInstance *>(obj);
  4801. const auto visitedTown = visitedHero->visitedTown;
  4802. if(visitedTown)
  4803. {
  4804. const bool isEnemy = visitedHero->getOwner() != h->getOwner();
  4805. if(isEnemy && !visitedTown->isBattleOutsideTown(visitedHero))
  4806. visitedObject = visitedTown;
  4807. }
  4808. }
  4809. visitQuery = std::make_shared<CObjectVisitQuery>(this, visitedObject, h, visitedObject->visitablePos());
  4810. queries.addQuery(visitQuery); //TODO real visit pos
  4811. HeroVisit hv;
  4812. hv.objId = obj->id;
  4813. hv.heroId = h->id;
  4814. hv.player = h->tempOwner;
  4815. hv.starting = true;
  4816. sendAndApply(&hv);
  4817. obj->onHeroVisit(h);
  4818. };
  4819. ObjectVisitStarted::defaultExecute(serverEventBus.get(), startVisit, h->tempOwner, h->id, obj->id);
  4820. if(visitQuery)
  4821. queries.popIfTop(visitQuery); //visit ends here if no queries were created
  4822. }
  4823. void CGameHandler::objectVisitEnded(const CObjectVisitQuery & query)
  4824. {
  4825. using events::ObjectVisitEnded;
  4826. logGlobal->debug("%s visit ends.\n", query.visitingHero->nodeName());
  4827. auto endVisit = [&](ObjectVisitEnded & event)
  4828. {
  4829. HeroVisit hv;
  4830. hv.player = event.getPlayer();
  4831. hv.heroId = event.getHero();
  4832. hv.starting = false;
  4833. sendAndApply(&hv);
  4834. };
  4835. //TODO: ObjectVisitEnded should also have id of visited object,
  4836. //but this requires object being deleted only by `removeAfterVisit()` but not `removeObject()`
  4837. ObjectVisitEnded::defaultExecute(serverEventBus.get(), endVisit, query.players.front(), query.visitingHero->id);
  4838. }
  4839. bool CGameHandler::buildBoat(ObjectInstanceID objid, PlayerColor playerID)
  4840. {
  4841. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  4842. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  4843. {
  4844. complain("Cannot build boat in this shipyard!");
  4845. return false;
  4846. }
  4847. TResources boatCost;
  4848. obj->getBoatCost(boatCost);
  4849. TResources aviable = getPlayerState(playerID)->resources;
  4850. if (!aviable.canAfford(boatCost))
  4851. {
  4852. complain("Not enough resources to build a boat!");
  4853. return false;
  4854. }
  4855. int3 tile = obj->bestLocation();
  4856. if (!gs->map->isInTheMap(tile))
  4857. {
  4858. complain("Cannot find appropriate tile for a boat!");
  4859. return false;
  4860. }
  4861. giveResources(playerID, -boatCost);
  4862. createObject(tile, Obj::BOAT, obj->getBoatType().getNum());
  4863. return true;
  4864. }
  4865. void CGameHandler::engageIntoBattle(PlayerColor player)
  4866. {
  4867. //notify interfaces
  4868. PlayerBlocked pb;
  4869. pb.player = player;
  4870. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  4871. pb.startOrEnd = PlayerBlocked::BLOCKADE_STARTED;
  4872. sendAndApply(&pb);
  4873. }
  4874. void CGameHandler::checkVictoryLossConditions(const std::set<PlayerColor> & playerColors)
  4875. {
  4876. for (auto playerColor : playerColors)
  4877. {
  4878. if (getPlayerState(playerColor, false))
  4879. checkVictoryLossConditionsForPlayer(playerColor);
  4880. }
  4881. }
  4882. void CGameHandler::checkVictoryLossConditionsForAll()
  4883. {
  4884. std::set<PlayerColor> playerColors;
  4885. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  4886. {
  4887. playerColors.insert(PlayerColor(i));
  4888. }
  4889. checkVictoryLossConditions(playerColors);
  4890. }
  4891. void CGameHandler::checkVictoryLossConditionsForPlayer(PlayerColor player)
  4892. {
  4893. const PlayerState * p = getPlayerState(player);
  4894. if(!p || p->status != EPlayerStatus::INGAME) return;
  4895. auto victoryLossCheckResult = gs->checkForVictoryAndLoss(player);
  4896. if (victoryLossCheckResult.victory() || victoryLossCheckResult.loss())
  4897. {
  4898. InfoWindow iw;
  4899. getVictoryLossMessage(player, victoryLossCheckResult, iw);
  4900. sendAndApply(&iw);
  4901. PlayerEndsGame peg;
  4902. peg.player = player;
  4903. peg.victoryLossCheckResult = victoryLossCheckResult;
  4904. sendAndApply(&peg);
  4905. if (victoryLossCheckResult.victory())
  4906. {
  4907. //one player won -> all enemies lost
  4908. for (auto i = gs->players.cbegin(); i!=gs->players.cend(); i++)
  4909. {
  4910. if (i->first != player && getPlayerState(i->first)->status == EPlayerStatus::INGAME)
  4911. {
  4912. peg.player = i->first;
  4913. peg.victoryLossCheckResult = getPlayerRelations(player, i->first) == PlayerRelations::ALLIES ?
  4914. victoryLossCheckResult : victoryLossCheckResult.invert(); // ally of winner
  4915. InfoWindow iw;
  4916. getVictoryLossMessage(player, peg.victoryLossCheckResult, iw);
  4917. iw.player = i->first;
  4918. sendAndApply(&iw);
  4919. sendAndApply(&peg);
  4920. }
  4921. }
  4922. if(p->human)
  4923. {
  4924. lobby->state = EServerState::GAMEPLAY_ENDED;
  4925. }
  4926. }
  4927. else
  4928. {
  4929. //copy heroes vector to avoid iterator invalidation as removal change PlayerState
  4930. auto hlp = p->heroes;
  4931. for (auto h : hlp) //eliminate heroes
  4932. {
  4933. if (h.get())
  4934. removeObject(h);
  4935. }
  4936. //player lost -> all his objects become unflagged (neutral)
  4937. for (auto obj : gs->map->objects) //unflag objs
  4938. {
  4939. if (obj.get() && obj->tempOwner == player)
  4940. setOwner(obj, PlayerColor::NEUTRAL);
  4941. }
  4942. //eliminating one player may cause victory of another:
  4943. std::set<PlayerColor> playerColors;
  4944. //do not copy player state (CBonusSystemNode) by value
  4945. for (auto &p : gs->players) //players may have different colors, iterate over players and not integers
  4946. {
  4947. if (p.first != player)
  4948. playerColors.insert(p.first);
  4949. }
  4950. //notify all players
  4951. for (auto pc : playerColors)
  4952. {
  4953. if (getPlayerState(pc)->status == EPlayerStatus::INGAME)
  4954. {
  4955. InfoWindow iw;
  4956. getVictoryLossMessage(player, victoryLossCheckResult.invert(), iw);
  4957. iw.player = pc;
  4958. sendAndApply(&iw);
  4959. }
  4960. }
  4961. checkVictoryLossConditions(playerColors);
  4962. }
  4963. auto playerInfo = getPlayerState(gs->currentPlayer, false);
  4964. // If we are called before the actual game start, there might be no current player
  4965. if (playerInfo && playerInfo->status != EPlayerStatus::INGAME)
  4966. {
  4967. // If player making turn has lost his turn must be over as well
  4968. states.setFlag(gs->currentPlayer, &PlayerStatus::makingTurn, false);
  4969. }
  4970. }
  4971. }
  4972. void CGameHandler::getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const
  4973. {
  4974. out.player = player;
  4975. out.text = victoryLossCheckResult.messageToSelf;
  4976. out.text.replaceLocalString(EMetaText::COLOR, player.getNum());
  4977. out.components.emplace_back(Component::EComponentType::FLAG, player.getNum(), 0, 0);
  4978. }
  4979. bool CGameHandler::dig(const CGHeroInstance *h)
  4980. {
  4981. if (h->diggingStatus() != EDiggingStatus::CAN_DIG) //checks for terrain and movement
  4982. COMPLAIN_RETF("Hero cannot dig (error code %d)!", h->diggingStatus());
  4983. createObject(h->visitablePos(), Obj::HOLE, 0 );
  4984. //take MPs
  4985. SetMovePoints smp;
  4986. smp.hid = h->id;
  4987. smp.val = 0;
  4988. sendAndApply(&smp);
  4989. InfoWindow iw;
  4990. iw.type = EInfoWindowMode::AUTO;
  4991. iw.player = h->tempOwner;
  4992. if (gs->map->grailPos == h->visitablePos())
  4993. {
  4994. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  4995. iw.text.appendLocalString(EMetaText::ART_NAMES, ArtifactID::GRAIL);
  4996. iw.soundID = soundBase::ULTIMATEARTIFACT;
  4997. giveHeroNewArtifact(h, VLC->arth->objects[ArtifactID::GRAIL], ArtifactPosition::FIRST_AVAILABLE); //give grail
  4998. sendAndApply(&iw);
  4999. iw.soundID = soundBase::invalid;
  5000. iw.components.emplace_back(Component::EComponentType::ARTIFACT, ArtifactID::GRAIL, 0, 0);
  5001. iw.text.clear();
  5002. iw.text.appendLocalString(EMetaText::ART_DESCR, ArtifactID::GRAIL);
  5003. sendAndApply(&iw);
  5004. }
  5005. else
  5006. {
  5007. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  5008. iw.soundID = soundBase::Dig;
  5009. sendAndApply(&iw);
  5010. }
  5011. return true;
  5012. }
  5013. void CGameHandler::attackCasting(bool ranged, BonusType attackMode, const battle::Unit * attacker, const battle::Unit * defender)
  5014. {
  5015. if(attacker->hasBonusOfType(attackMode))
  5016. {
  5017. std::set<SpellID> spellsToCast;
  5018. TConstBonusListPtr spells = attacker->getBonuses(Selector::type()(attackMode));
  5019. for(const auto & sf : *spells)
  5020. {
  5021. spellsToCast.insert(SpellID(sf->subtype));
  5022. }
  5023. for(SpellID spellID : spellsToCast)
  5024. {
  5025. bool castMe = false;
  5026. if(!defender->alive())
  5027. {
  5028. logGlobal->debug("attackCasting: all attacked creatures have been killed");
  5029. return;
  5030. }
  5031. int32_t spellLevel = 0;
  5032. TConstBonusListPtr spellsByType = attacker->getBonuses(Selector::typeSubtype(attackMode, spellID));
  5033. for(const auto & sf : *spellsByType)
  5034. {
  5035. int meleeRanged;
  5036. if(sf->additionalInfo.size() < 2)
  5037. {
  5038. // legacy format
  5039. vstd::amax(spellLevel, sf->additionalInfo[0] % 1000);
  5040. meleeRanged = sf->additionalInfo[0] / 1000;
  5041. }
  5042. else
  5043. {
  5044. vstd::amax(spellLevel, sf->additionalInfo[0]);
  5045. meleeRanged = sf->additionalInfo[1];
  5046. }
  5047. if (meleeRanged == 0 || (meleeRanged == 1 && ranged) || (meleeRanged == 2 && !ranged))
  5048. castMe = true;
  5049. }
  5050. int chance = attacker->valOfBonuses((Selector::typeSubtype(attackMode, spellID)));
  5051. vstd::amin(chance, 100);
  5052. const CSpell * spell = SpellID(spellID).toSpell();
  5053. spells::AbilityCaster caster(attacker, spellLevel);
  5054. spells::Target target;
  5055. target.emplace_back(defender);
  5056. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  5057. auto m = spell->battleMechanics(&parameters);
  5058. spells::detail::ProblemImpl ignored;
  5059. if(!m->canBeCastAt(target, ignored))
  5060. continue;
  5061. //check if spell should be cast (probability handling)
  5062. if(getRandomGenerator().nextInt(99) >= chance)
  5063. continue;
  5064. //casting
  5065. if(castMe)
  5066. {
  5067. parameters.cast(spellEnv, target);
  5068. }
  5069. }
  5070. }
  5071. }
  5072. void CGameHandler::handleAttackBeforeCasting(bool ranged, const CStack * attacker, const CStack * defender)
  5073. {
  5074. attackCasting(ranged, BonusType::SPELL_BEFORE_ATTACK, attacker, defender); //no death stare / acid breath needed?
  5075. }
  5076. void CGameHandler::handleAfterAttackCasting(bool ranged, const CStack * attacker, const CStack * defender)
  5077. {
  5078. if(!attacker->alive() || !defender->alive()) // can be already dead
  5079. return;
  5080. attackCasting(ranged, BonusType::SPELL_AFTER_ATTACK, attacker, defender);
  5081. if(!defender->alive())
  5082. {
  5083. //don't try death stare or acid breath on dead stack (crash!)
  5084. return;
  5085. }
  5086. if(attacker->hasBonusOfType(BonusType::DEATH_STARE))
  5087. {
  5088. // mechanics of Death Stare as in H3:
  5089. // each gorgon have 10% chance to kill (counted separately in H3) -> binomial distribution
  5090. //original formula x = min(x, (gorgons_count + 9)/10);
  5091. double chanceToKill = attacker->valOfBonuses(BonusType::DEATH_STARE, 0) / 100.0f;
  5092. vstd::amin(chanceToKill, 1); //cap at 100%
  5093. std::binomial_distribution<> distribution(attacker->getCount(), chanceToKill);
  5094. int staredCreatures = distribution(getRandomGenerator().getStdGenerator());
  5095. double cap = 1 / std::max(chanceToKill, (double)(0.01));//don't divide by 0
  5096. int maxToKill = static_cast<int>((attacker->getCount() + cap - 1) / cap); //not much more than chance * count
  5097. vstd::amin(staredCreatures, maxToKill);
  5098. staredCreatures += (attacker->level() * attacker->valOfBonuses(BonusType::DEATH_STARE, 1)) / defender->level();
  5099. if(staredCreatures)
  5100. {
  5101. //TODO: death stare was not originally available for multiple-hex attacks, but...
  5102. const CSpell * spell = SpellID(SpellID::DEATH_STARE).toSpell();
  5103. spells::AbilityCaster caster(attacker, 0);
  5104. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  5105. spells::Target target;
  5106. target.emplace_back(defender);
  5107. parameters.setEffectValue(staredCreatures);
  5108. parameters.cast(spellEnv, target);
  5109. }
  5110. }
  5111. if(!defender->alive())
  5112. return;
  5113. int64_t acidDamage = 0;
  5114. TConstBonusListPtr acidBreath = attacker->getBonuses(Selector::type()(BonusType::ACID_BREATH));
  5115. for(const auto & b : *acidBreath)
  5116. {
  5117. if(b->additionalInfo[0] > getRandomGenerator().nextInt(99))
  5118. acidDamage += b->val;
  5119. }
  5120. if(acidDamage > 0)
  5121. {
  5122. const CSpell * spell = SpellID(SpellID::ACID_BREATH_DAMAGE).toSpell();
  5123. spells::AbilityCaster caster(attacker, 0);
  5124. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  5125. spells::Target target;
  5126. target.emplace_back(defender);
  5127. parameters.setEffectValue(acidDamage * attacker->getCount());
  5128. parameters.cast(spellEnv, target);
  5129. }
  5130. if(!defender->alive())
  5131. return;
  5132. if(attacker->hasBonusOfType(BonusType::TRANSMUTATION) && defender->isLiving()) //transmutation mechanics, similar to WoG werewolf ability
  5133. {
  5134. double chanceToTrigger = attacker->valOfBonuses(BonusType::TRANSMUTATION) / 100.0f;
  5135. vstd::amin(chanceToTrigger, 1); //cap at 100%
  5136. if(getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  5137. return;
  5138. int bonusAdditionalInfo = attacker->getBonus(Selector::type()(BonusType::TRANSMUTATION))->additionalInfo[0];
  5139. if(defender->unitType()->getId() == bonusAdditionalInfo ||
  5140. (bonusAdditionalInfo == CAddInfo::NONE && defender->unitType()->getId() == attacker->unitType()->getId()))
  5141. return;
  5142. battle::UnitInfo resurrectInfo;
  5143. resurrectInfo.id = gs->curB->battleNextUnitId();
  5144. resurrectInfo.summoned = false;
  5145. resurrectInfo.position = defender->getPosition();
  5146. resurrectInfo.side = defender->unitSide();
  5147. if(bonusAdditionalInfo != CAddInfo::NONE)
  5148. resurrectInfo.type = CreatureID(bonusAdditionalInfo);
  5149. else
  5150. resurrectInfo.type = attacker->creatureId();
  5151. if(attacker->hasBonusOfType((BonusType::TRANSMUTATION), 0))
  5152. resurrectInfo.count = std::max((defender->getCount() * defender->getMaxHealth()) / resurrectInfo.type.toCreature()->getMaxHealth(), 1u);
  5153. else if (attacker->hasBonusOfType((BonusType::TRANSMUTATION), 1))
  5154. resurrectInfo.count = defender->getCount();
  5155. else
  5156. return; //wrong subtype
  5157. BattleUnitsChanged addUnits;
  5158. addUnits.changedStacks.emplace_back(resurrectInfo.id, UnitChanges::EOperation::ADD);
  5159. resurrectInfo.save(addUnits.changedStacks.back().data);
  5160. BattleUnitsChanged removeUnits;
  5161. removeUnits.changedStacks.emplace_back(defender->unitId(), UnitChanges::EOperation::REMOVE);
  5162. sendAndApply(&removeUnits);
  5163. sendAndApply(&addUnits);
  5164. }
  5165. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0) || attacker->hasBonusOfType(BonusType::DESTRUCTION, 1))
  5166. {
  5167. double chanceToTrigger = 0;
  5168. int amountToDie = 0;
  5169. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0)) //killing by percentage
  5170. {
  5171. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 0) / 100.0f;
  5172. int percentageToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(0)))->additionalInfo[0];
  5173. amountToDie = static_cast<int>(defender->getCount() * percentageToDie * 0.01f);
  5174. }
  5175. else if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 1)) //killing by count
  5176. {
  5177. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 1) / 100.0f;
  5178. amountToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(1)))->additionalInfo[0];
  5179. }
  5180. vstd::amin(chanceToTrigger, 1); //cap trigger chance at 100%
  5181. if(getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  5182. return;
  5183. BattleStackAttacked bsa;
  5184. bsa.attackerID = -1;
  5185. bsa.stackAttacked = defender->unitId();
  5186. bsa.damageAmount = amountToDie * defender->getMaxHealth();
  5187. bsa.flags = BattleStackAttacked::SPELL_EFFECT;
  5188. bsa.spellID = SpellID::SLAYER;
  5189. defender->prepareAttacked(bsa, getRandomGenerator());
  5190. StacksInjured si;
  5191. si.stacks.push_back(bsa);
  5192. sendAndApply(&si);
  5193. sendGenericKilledLog(defender, bsa.killedAmount, false);
  5194. }
  5195. }
  5196. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  5197. {
  5198. if (!t.visitableObjects.empty())
  5199. {
  5200. //to prevent self-visiting heroes on space press
  5201. if (t.visitableObjects.back() != h)
  5202. objectVisited(t.visitableObjects.back(), h);
  5203. else if (t.visitableObjects.size() > 1)
  5204. objectVisited(*(t.visitableObjects.end()-2),h);
  5205. }
  5206. }
  5207. bool CGameHandler::sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count)
  5208. {
  5209. if (!hero)
  5210. COMPLAIN_RET("You need hero to sacrifice creature!");
  5211. int expSum = 0;
  5212. auto finish = [this, &hero, &expSum]()
  5213. {
  5214. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  5215. };
  5216. for(int i = 0; i < slot.size(); ++i)
  5217. {
  5218. int oldCount = hero->getStackCount(slot[i]);
  5219. if(oldCount < (int)count[i])
  5220. {
  5221. finish();
  5222. COMPLAIN_RET("Not enough creatures to sacrifice!")
  5223. }
  5224. else if(oldCount == count[i] && hero->stacksCount() == 1 && hero->needsLastStack())
  5225. {
  5226. finish();
  5227. COMPLAIN_RET("Cannot sacrifice last creature!");
  5228. }
  5229. int crid = hero->getStack(slot[i]).type->getId();
  5230. changeStackCount(StackLocation(hero, slot[i]), -(TQuantity)count[i]);
  5231. int dump, exp;
  5232. market->getOffer(crid, 0, dump, exp, EMarketMode::CREATURE_EXP);
  5233. exp *= count[i];
  5234. expSum += exp;
  5235. }
  5236. finish();
  5237. return true;
  5238. }
  5239. bool CGameHandler::sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactPosition> & slot)
  5240. {
  5241. if (!hero)
  5242. COMPLAIN_RET("You need hero to sacrifice artifact!");
  5243. int expSum = 0;
  5244. auto finish = [this, &hero, &expSum]()
  5245. {
  5246. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  5247. };
  5248. for(int i = 0; i < slot.size(); ++i)
  5249. {
  5250. ArtifactLocation al(hero, slot[i]);
  5251. const CArtifactInstance * a = al.getArt();
  5252. if(!a)
  5253. {
  5254. finish();
  5255. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  5256. }
  5257. const CArtifactInstance * art = hero->getArt(slot[i]);
  5258. if(!art)
  5259. {
  5260. finish();
  5261. COMPLAIN_RET("No artifact at position to sacrifice!");
  5262. }
  5263. si32 typId = art->artType->getId();
  5264. int dmp, expToGive;
  5265. m->getOffer(typId, 0, dmp, expToGive, EMarketMode::ARTIFACT_EXP);
  5266. expSum += expToGive;
  5267. removeArtifact(al);
  5268. }
  5269. finish();
  5270. return true;
  5271. }
  5272. void CGameHandler::makeStackDoNothing(const CStack * next)
  5273. {
  5274. BattleAction doNothing;
  5275. doNothing.actionType = EActionType::NO_ACTION;
  5276. doNothing.side = next->unitSide();
  5277. doNothing.stackNumber = next->unitId();
  5278. makeAutomaticAction(next, doNothing);
  5279. }
  5280. bool CGameHandler::insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count)
  5281. {
  5282. if (sl.army->hasStackAtSlot(sl.slot))
  5283. COMPLAIN_RET("Slot is already taken!");
  5284. if (!sl.slot.validSlot())
  5285. COMPLAIN_RET("Cannot insert stack to that slot!");
  5286. InsertNewStack ins;
  5287. ins.army = sl.army->id;
  5288. ins.slot = sl.slot;
  5289. ins.type = c->getId();
  5290. ins.count = count;
  5291. sendAndApply(&ins);
  5292. return true;
  5293. }
  5294. bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval)
  5295. {
  5296. if (!sl.army->hasStackAtSlot(sl.slot))
  5297. COMPLAIN_RET("Cannot find a stack to erase");
  5298. if (sl.army->stacksCount() == 1 //from the last stack
  5299. && sl.army->needsLastStack() //that must be left
  5300. && !forceRemoval) //ignore above conditions if we are forcing removal
  5301. {
  5302. COMPLAIN_RET("Cannot erase the last stack!");
  5303. }
  5304. EraseStack es;
  5305. es.army = sl.army->id;
  5306. es.slot = sl.slot;
  5307. sendAndApply(&es);
  5308. return true;
  5309. }
  5310. bool CGameHandler::changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue)
  5311. {
  5312. TQuantity currentCount = sl.army->getStackCount(sl.slot);
  5313. if ((absoluteValue && count < 0)
  5314. || (!absoluteValue && -count > currentCount))
  5315. {
  5316. COMPLAIN_RET("Cannot take more stacks than present!");
  5317. }
  5318. if ((currentCount == -count && !absoluteValue)
  5319. || (!count && absoluteValue))
  5320. {
  5321. eraseStack(sl);
  5322. }
  5323. else
  5324. {
  5325. ChangeStackCount csc;
  5326. csc.army = sl.army->id;
  5327. csc.slot = sl.slot;
  5328. csc.count = count;
  5329. csc.absoluteValue = absoluteValue;
  5330. sendAndApply(&csc);
  5331. }
  5332. return true;
  5333. }
  5334. bool CGameHandler::addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count)
  5335. {
  5336. const CCreature *slotC = sl.army->getCreature(sl.slot);
  5337. if (!slotC) //slot is empty
  5338. insertNewStack(sl, c, count);
  5339. else if (c == slotC)
  5340. changeStackCount(sl, count);
  5341. else
  5342. {
  5343. COMPLAIN_RET("Cannot add " + c->getNamePluralTranslated() + " to slot " + boost::lexical_cast<std::string>(sl.slot) + "!");
  5344. }
  5345. return true;
  5346. }
  5347. void CGameHandler::tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging)
  5348. {
  5349. if (removeObjWhenFinished)
  5350. removeAfterVisit(src);
  5351. if (!src->canBeMergedWith(*dst, allowMerging))
  5352. {
  5353. if (allowMerging) //do that, add all matching creatures.
  5354. {
  5355. bool cont = true;
  5356. while (cont)
  5357. {
  5358. for (auto i = src->stacks.begin(); i != src->stacks.end(); i++)//while there are unmoved creatures
  5359. {
  5360. SlotID pos = dst->getSlotFor(i->second->type);
  5361. if (pos.validSlot())
  5362. {
  5363. moveStack(StackLocation(src, i->first), StackLocation(dst, pos));
  5364. cont = true;
  5365. break; //or iterator crashes
  5366. }
  5367. cont = false;
  5368. }
  5369. }
  5370. }
  5371. showGarrisonDialog(src->id, dst->id, true); //show garrison window and optionally remove ourselves from map when player ends
  5372. }
  5373. else //merge
  5374. {
  5375. moveArmy(src, dst, allowMerging);
  5376. }
  5377. }
  5378. bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count)
  5379. {
  5380. if (!src.army->hasStackAtSlot(src.slot))
  5381. COMPLAIN_RET("No stack to move!");
  5382. if (dst.army->hasStackAtSlot(dst.slot) && dst.army->getCreature(dst.slot) != src.army->getCreature(src.slot))
  5383. COMPLAIN_RET("Cannot move: stack of different type at destination pos!");
  5384. if (!dst.slot.validSlot())
  5385. COMPLAIN_RET("Cannot move stack to that slot!");
  5386. if (count == -1)
  5387. {
  5388. count = src.army->getStackCount(src.slot);
  5389. }
  5390. if (src.army != dst.army //moving away
  5391. && count == src.army->getStackCount(src.slot) //all creatures
  5392. && src.army->stacksCount() == 1 //from the last stack
  5393. && src.army->needsLastStack()) //that must be left
  5394. {
  5395. COMPLAIN_RET("Cannot move away the last creature!");
  5396. }
  5397. RebalanceStacks rs;
  5398. rs.srcArmy = src.army->id;
  5399. rs.dstArmy = dst.army->id;
  5400. rs.srcSlot = src.slot;
  5401. rs.dstSlot = dst.slot;
  5402. rs.count = count;
  5403. sendAndApply(&rs);
  5404. return true;
  5405. }
  5406. void CGameHandler::castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos)
  5407. {
  5408. const CSpell * s = spellID.toSpell();
  5409. if(!s)
  5410. return;
  5411. AdventureSpellCastParameters p;
  5412. p.caster = caster;
  5413. p.pos = pos;
  5414. s->adventureCast(spellEnv, p);
  5415. }
  5416. bool CGameHandler::swapStacks(const StackLocation & sl1, const StackLocation & sl2)
  5417. {
  5418. if(!sl1.army->hasStackAtSlot(sl1.slot))
  5419. {
  5420. return moveStack(sl2, sl1);
  5421. }
  5422. else if(!sl2.army->hasStackAtSlot(sl2.slot))
  5423. {
  5424. return moveStack(sl1, sl2);
  5425. }
  5426. else
  5427. {
  5428. SwapStacks ss;
  5429. ss.srcArmy = sl1.army->id;
  5430. ss.dstArmy = sl2.army->id;
  5431. ss.srcSlot = sl1.slot;
  5432. ss.dstSlot = sl2.slot;
  5433. sendAndApply(&ss);
  5434. return true;
  5435. }
  5436. }
  5437. void CGameHandler::runBattle()
  5438. {
  5439. setBattle(gs->curB);
  5440. assert(gs->curB);
  5441. //TODO: pre-tactic stuff, call scripts etc.
  5442. //Moat should be initialized here, because only here we can use spellcasting
  5443. if (gs->curB->town && gs->curB->town->fortLevel() >= CGTownInstance::CITADEL)
  5444. {
  5445. const auto * h = gs->curB->battleGetFightingHero(BattleSide::DEFENDER);
  5446. const auto * actualCaster = h ? static_cast<const spells::Caster*>(h) : nullptr;
  5447. auto moatCaster = spells::SilentCaster(gs->curB->getSidePlayer(BattleSide::DEFENDER), actualCaster);
  5448. auto cast = spells::BattleCast(gs->curB, &moatCaster, spells::Mode::PASSIVE, gs->curB->town->town->moatAbility.toSpell());
  5449. auto target = spells::Target();
  5450. cast.cast(spellEnv, target);
  5451. }
  5452. //tactic round
  5453. {
  5454. while ((lobby->state != EServerState::SHUTDOWN) && gs->curB->tacticDistance && !battleResult.get())
  5455. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  5456. }
  5457. //initial stacks appearance triggers, e.g. built-in bonus spells
  5458. auto initialStacks = gs->curB->stacks; //use temporary variable to outclude summoned stacks added to gs->curB->stacks from processing
  5459. for (CStack * stack : initialStacks)
  5460. {
  5461. if (stack->hasBonusOfType(BonusType::SUMMON_GUARDIANS))
  5462. {
  5463. std::shared_ptr<const Bonus> summonInfo = stack->getBonus(Selector::type()(BonusType::SUMMON_GUARDIANS));
  5464. auto accessibility = getAccesibility();
  5465. CreatureID creatureData = CreatureID(summonInfo->subtype);
  5466. std::vector<BattleHex> targetHexes;
  5467. const bool targetIsBig = stack->unitType()->isDoubleWide(); //target = creature to guard
  5468. const bool guardianIsBig = creatureData.toCreature()->isDoubleWide();
  5469. /*Chosen idea for two hex units was to cover all possible surrounding hexes of target unit with as small number of stacks as possible.
  5470. For one-hex targets there are four guardians - front, back and one per side (up + down).
  5471. Two-hex targets are wider and the difference is there are two guardians per side to cover 3 hexes + extra hex in the front
  5472. Additionally, there are special cases for starting positions etc., where guardians would be outside of battlefield if spawned normally*/
  5473. if (!guardianIsBig)
  5474. targetHexes = stack->getSurroundingHexes();
  5475. else
  5476. summonGuardiansHelper(targetHexes, stack->getPosition(), stack->unitSide(), targetIsBig);
  5477. for(auto hex : targetHexes)
  5478. {
  5479. if(accessibility.accessible(hex, guardianIsBig, stack->unitSide())) //without this multiple creatures can occupy one hex
  5480. {
  5481. battle::UnitInfo info;
  5482. info.id = gs->curB->battleNextUnitId();
  5483. info.count = std::max(1, (int)(stack->getCount() * 0.01 * summonInfo->val));
  5484. info.type = creatureData;
  5485. info.side = stack->unitSide();
  5486. info.position = hex;
  5487. info.summoned = true;
  5488. BattleUnitsChanged pack;
  5489. pack.changedStacks.emplace_back(info.id, UnitChanges::EOperation::ADD);
  5490. info.save(pack.changedStacks.back().data);
  5491. sendAndApply(&pack);
  5492. }
  5493. }
  5494. }
  5495. stackEnchantedTrigger(stack);
  5496. }
  5497. //spells opening battle
  5498. for (int i = 0; i < 2; ++i)
  5499. {
  5500. auto h = gs->curB->battleGetFightingHero(i);
  5501. if (h)
  5502. {
  5503. TConstBonusListPtr bl = h->getBonuses(Selector::type()(BonusType::OPENING_BATTLE_SPELL));
  5504. for (auto b : *bl)
  5505. {
  5506. spells::BonusCaster caster(h, b);
  5507. const CSpell * spell = SpellID(b->subtype).toSpell();
  5508. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  5509. parameters.setSpellLevel(3);
  5510. parameters.setEffectDuration(b->val);
  5511. parameters.massive = true;
  5512. parameters.castIfPossible(spellEnv, spells::Target());
  5513. }
  5514. }
  5515. }
  5516. // it is possible that due to opening spells one side was eliminated -> check for end of battle
  5517. checkBattleStateChanges();
  5518. bool firstRound = true;//FIXME: why first round is -1?
  5519. //main loop
  5520. while ((lobby->state != EServerState::SHUTDOWN) && !battleResult.get()) //till the end of the battle ;]
  5521. {
  5522. BattleNextRound bnr;
  5523. bnr.round = gs->curB->round + 1;
  5524. logGlobal->debug("Round %d", bnr.round);
  5525. sendAndApply(&bnr);
  5526. auto obstacles = gs->curB->obstacles; //we copy container, because we're going to modify it
  5527. for (auto &obstPtr : obstacles)
  5528. {
  5529. if (const SpellCreatedObstacle *sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get()))
  5530. if (sco->turnsRemaining == 0)
  5531. removeObstacle(*obstPtr);
  5532. }
  5533. const BattleInfo & curB = *gs->curB;
  5534. for(auto stack : curB.stacks)
  5535. {
  5536. if(stack->alive() && !firstRound)
  5537. stackEnchantedTrigger(stack);
  5538. }
  5539. //stack loop
  5540. auto getNextStack = [this]() -> const CStack *
  5541. {
  5542. if(battleResult.get())
  5543. return nullptr;
  5544. std::vector<battle::Units> q;
  5545. gs->curB->battleGetTurnOrder(q, 1, 0, -1); //todo: get rid of "turn -1"
  5546. if(!q.empty())
  5547. {
  5548. if(!q.front().empty())
  5549. {
  5550. auto next = q.front().front();
  5551. const auto stack = dynamic_cast<const CStack *>(next);
  5552. // regeneration takes place before everything else but only during first turn attempt in each round
  5553. // also works under blind and similar effects
  5554. if(stack && stack->alive() && !stack->waiting)
  5555. {
  5556. BattleTriggerEffect bte;
  5557. bte.stackID = stack->unitId();
  5558. bte.effect = vstd::to_underlying(BonusType::HP_REGENERATION);
  5559. const int32_t lostHealth = stack->getMaxHealth() - stack->getFirstHPleft();
  5560. if(stack->hasBonusOfType(BonusType::HP_REGENERATION))
  5561. bte.val = std::min(lostHealth, stack->valOfBonuses(BonusType::HP_REGENERATION));
  5562. if(bte.val) // anything to heal
  5563. sendAndApply(&bte);
  5564. }
  5565. if(next->willMove())
  5566. return stack;
  5567. }
  5568. }
  5569. return nullptr;
  5570. };
  5571. const CStack * next = nullptr;
  5572. while((lobby->state != EServerState::SHUTDOWN) && (next = getNextStack()))
  5573. {
  5574. BattleUnitsChanged removeGhosts;
  5575. for(auto stack : curB.stacks)
  5576. {
  5577. if(stack->ghostPending)
  5578. removeGhosts.changedStacks.emplace_back(stack->unitId(), UnitChanges::EOperation::REMOVE);
  5579. }
  5580. if(!removeGhosts.changedStacks.empty())
  5581. sendAndApply(&removeGhosts);
  5582. // check for bad morale => freeze
  5583. int nextStackMorale = next->moraleVal();
  5584. if(!next->hadMorale && !next->waited() && nextStackMorale < 0)
  5585. {
  5586. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_MORALE_DICE);
  5587. size_t diceIndex = std::min<size_t>(diceSize.size()-1, -nextStackMorale);
  5588. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  5589. {
  5590. //unit loses its turn - empty freeze action
  5591. BattleAction ba;
  5592. ba.actionType = EActionType::BAD_MORALE;
  5593. ba.side = next->unitSide();
  5594. ba.stackNumber = next->unitId();
  5595. makeAutomaticAction(next, ba);
  5596. continue;
  5597. }
  5598. }
  5599. if (next->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE)) //while in berserk
  5600. {
  5601. logGlobal->trace("Handle Berserk effect");
  5602. std::pair<const battle::Unit *, BattleHex> attackInfo = curB.getNearestStack(next);
  5603. if (attackInfo.first != nullptr)
  5604. {
  5605. BattleAction attack;
  5606. attack.actionType = EActionType::WALK_AND_ATTACK;
  5607. attack.side = next->unitSide();
  5608. attack.stackNumber = next->unitId();
  5609. attack.aimToHex(attackInfo.second);
  5610. attack.aimToUnit(attackInfo.first);
  5611. makeAutomaticAction(next, attack);
  5612. logGlobal->trace("Attacked nearest target %s", attackInfo.first->getDescription());
  5613. }
  5614. else
  5615. {
  5616. makeStackDoNothing(next);
  5617. logGlobal->trace("No target found");
  5618. }
  5619. continue;
  5620. }
  5621. const CGHeroInstance * curOwner = battleGetOwnerHero(next);
  5622. const int stackCreatureId = next->unitType()->getId();
  5623. if ((stackCreatureId == CreatureID::ARROW_TOWERS || stackCreatureId == CreatureID::BALLISTA)
  5624. && (!curOwner || getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, stackCreatureId)))
  5625. {
  5626. BattleAction attack;
  5627. attack.actionType = EActionType::SHOOT;
  5628. attack.side = next->unitSide();
  5629. attack.stackNumber = next->unitId();
  5630. //TODO: select target by priority
  5631. const battle::Unit * target = nullptr;
  5632. for(auto & elem : gs->curB->stacks)
  5633. {
  5634. if(elem->unitType()->getId() != CreatureID::CATAPULT
  5635. && elem->unitOwner() != next->unitOwner()
  5636. && elem->isValidTarget()
  5637. && gs->curB->battleCanShoot(next, elem->getPosition()))
  5638. {
  5639. target = elem;
  5640. break;
  5641. }
  5642. }
  5643. if(target == nullptr)
  5644. {
  5645. makeStackDoNothing(next);
  5646. }
  5647. else
  5648. {
  5649. attack.aimToUnit(target);
  5650. makeAutomaticAction(next, attack);
  5651. }
  5652. continue;
  5653. }
  5654. if (next->unitType()->getId() == CreatureID::CATAPULT)
  5655. {
  5656. const auto & attackableBattleHexes = curB.getAttackableBattleHexes();
  5657. if (attackableBattleHexes.empty())
  5658. {
  5659. makeStackDoNothing(next);
  5660. continue;
  5661. }
  5662. if (!curOwner || getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::CATAPULT))
  5663. {
  5664. BattleAction attack;
  5665. attack.actionType = EActionType::CATAPULT;
  5666. attack.side = next->unitSide();
  5667. attack.stackNumber = next->unitId();
  5668. makeAutomaticAction(next, attack);
  5669. continue;
  5670. }
  5671. }
  5672. if (next->unitType()->getId() == CreatureID::FIRST_AID_TENT)
  5673. {
  5674. TStacks possibleStacks = battleGetStacksIf([=](const CStack * s)
  5675. {
  5676. return s->unitOwner() == next->unitOwner() && s->canBeHealed();
  5677. });
  5678. if (!possibleStacks.size())
  5679. {
  5680. makeStackDoNothing(next);
  5681. continue;
  5682. }
  5683. if (!curOwner || getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::FIRST_AID_TENT))
  5684. {
  5685. RandomGeneratorUtil::randomShuffle(possibleStacks, getRandomGenerator());
  5686. const CStack * toBeHealed = possibleStacks.front();
  5687. BattleAction heal;
  5688. heal.actionType = EActionType::STACK_HEAL;
  5689. heal.aimToUnit(toBeHealed);
  5690. heal.side = next->unitSide();
  5691. heal.stackNumber = next->unitId();
  5692. makeAutomaticAction(next, heal);
  5693. continue;
  5694. }
  5695. }
  5696. int numberOfAsks = 1;
  5697. bool breakOuter = false;
  5698. do
  5699. {//ask interface and wait for answer
  5700. if (!battleResult.get())
  5701. {
  5702. stackTurnTrigger(next); //various effects
  5703. if(next->fear)
  5704. {
  5705. makeStackDoNothing(next); //end immediately if stack was affected by fear
  5706. }
  5707. else
  5708. {
  5709. logGlobal->trace("Activating %s", next->nodeName());
  5710. auto nextId = next->unitId();
  5711. BattleSetActiveStack sas;
  5712. sas.stack = nextId;
  5713. sendAndApply(&sas);
  5714. auto actionWasMade = [&]() -> bool
  5715. {
  5716. if (battleMadeAction.data)//active stack has made its action
  5717. return true;
  5718. if (battleResult.get())// battle is finished
  5719. return true;
  5720. if (next == nullptr)//active stack was been removed
  5721. return true;
  5722. return !next->alive();//active stack is dead
  5723. };
  5724. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  5725. battleMadeAction.data = false;
  5726. while ((lobby->state != EServerState::SHUTDOWN) && !actionWasMade())
  5727. {
  5728. battleMadeAction.cond.wait(lock);
  5729. if (battleGetStackByID(nextId, false) != next)
  5730. next = nullptr; //it may be removed, while we wait
  5731. }
  5732. }
  5733. }
  5734. if (battleResult.get()) //don't touch it, battle could be finished while waiting got action
  5735. {
  5736. breakOuter = true;
  5737. break;
  5738. }
  5739. //we're after action, all results applied
  5740. checkBattleStateChanges(); //check if this action ended the battle
  5741. if(next != nullptr)
  5742. {
  5743. //check for good morale
  5744. nextStackMorale = next->moraleVal();
  5745. if( !battleResult.get()
  5746. && !next->hadMorale
  5747. && !next->defending
  5748. && !next->waited()
  5749. && !next->fear
  5750. && next->alive()
  5751. && nextStackMorale > 0)
  5752. {
  5753. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_MORALE_DICE);
  5754. size_t diceIndex = std::min<size_t>(diceSize.size()-1, nextStackMorale);
  5755. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  5756. {
  5757. BattleTriggerEffect bte;
  5758. bte.stackID = next->unitId();
  5759. bte.effect = vstd::to_underlying(BonusType::MORALE);
  5760. bte.val = 1;
  5761. bte.additionalInfo = 0;
  5762. sendAndApply(&bte); //play animation
  5763. ++numberOfAsks; //move this stack once more
  5764. }
  5765. }
  5766. }
  5767. --numberOfAsks;
  5768. } while (numberOfAsks > 0);
  5769. if (breakOuter)
  5770. {
  5771. break;
  5772. }
  5773. }
  5774. firstRound = false;
  5775. }
  5776. if (lobby->state != EServerState::SHUTDOWN)
  5777. endBattle(gs->curB->tile, gs->curB->battleGetFightingHero(0), gs->curB->battleGetFightingHero(1));
  5778. }
  5779. bool CGameHandler::makeAutomaticAction(const CStack *stack, BattleAction &ba)
  5780. {
  5781. BattleSetActiveStack bsa;
  5782. bsa.stack = stack->unitId();
  5783. bsa.askPlayerInterface = false;
  5784. sendAndApply(&bsa);
  5785. bool ret = makeBattleAction(ba);
  5786. checkBattleStateChanges();
  5787. return ret;
  5788. }
  5789. bool CGameHandler::giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos)
  5790. {
  5791. assert(a->artType);
  5792. ArtifactLocation al(h, ArtifactPosition::PRE_FIRST);
  5793. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  5794. {
  5795. al.slot = ArtifactUtils::getArtAnyPosition(h, a->getTypeId());
  5796. }
  5797. else if(ArtifactUtils::isSlotBackpack(pos))
  5798. {
  5799. al.slot = ArtifactUtils::getArtBackpackPosition(h, a->getTypeId());
  5800. }
  5801. else
  5802. {
  5803. al.slot = pos;
  5804. }
  5805. if(a->canBePutAt(al))
  5806. putArtifact(al, a);
  5807. else
  5808. return false;
  5809. return true;
  5810. }
  5811. void CGameHandler::putArtifact(const ArtifactLocation &al, const CArtifactInstance *a)
  5812. {
  5813. PutArtifact pa;
  5814. pa.art = a;
  5815. pa.al = al;
  5816. sendAndApply(&pa);
  5817. }
  5818. bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos)
  5819. {
  5820. assert(artType);
  5821. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  5822. {
  5823. if(!artType->canBePutAt(h, ArtifactUtils::getArtAnyPosition(h, artType->getId())))
  5824. COMPLAIN_RET("Cannot put artifact in that slot!");
  5825. }
  5826. else if(ArtifactUtils::isSlotBackpack(pos))
  5827. {
  5828. if(!artType->canBePutAt(h, ArtifactUtils::getArtBackpackPosition(h, artType->getId())))
  5829. COMPLAIN_RET("Cannot put artifact in that slot!");
  5830. }
  5831. else
  5832. {
  5833. COMPLAIN_RET_FALSE_IF(!artType->canBePutAt(h, pos, false), "Cannot put artifact in that slot!");
  5834. }
  5835. CArtifactInstance * newArtInst = nullptr;
  5836. if(artType->canBeDisassembled())
  5837. newArtInst = new CCombinedArtifactInstance();
  5838. else
  5839. newArtInst = new CArtifactInstance();
  5840. newArtInst->artType = artType; // *NOT* via settype -> all bonus-related stuff must be done by NewArtifact apply
  5841. NewArtifact na;
  5842. na.art = newArtInst;
  5843. sendAndApply(&na); // -> updates a!!!, will create a on other machines
  5844. if(giveHeroArtifact(h, newArtInst, pos))
  5845. return true;
  5846. else
  5847. return false;
  5848. }
  5849. void CGameHandler::setBattleResult(BattleResult::EResult resultType, int victoriusSide)
  5850. {
  5851. boost::unique_lock<boost::mutex> guard(battleResult.mx);
  5852. if (battleResult.data)
  5853. {
  5854. complain((boost::format("The battle result has been already set (to %d, asked to %d)")
  5855. % battleResult.data->result % resultType).str());
  5856. return;
  5857. }
  5858. auto br = new BattleResult();
  5859. br->result = resultType;
  5860. br->winner = victoriusSide; //surrendering side loses
  5861. gs->curB->calculateCasualties(br->casualties);
  5862. battleResult.data = br;
  5863. }
  5864. void CGameHandler::spawnWanderingMonsters(CreatureID creatureID)
  5865. {
  5866. std::vector<int3>::iterator tile;
  5867. std::vector<int3> tiles;
  5868. getFreeTiles(tiles);
  5869. ui32 amount = (ui32)tiles.size() / 200; //Chance is 0.5% for each tile
  5870. RandomGeneratorUtil::randomShuffle(tiles, getRandomGenerator());
  5871. logGlobal->trace("Spawning wandering monsters. Found %d free tiles. Creature type: %d", tiles.size(), creatureID.num);
  5872. const CCreature *cre = VLC->creh->objects.at(creatureID);
  5873. for (int i = 0; i < (int)amount; ++i)
  5874. {
  5875. tile = tiles.begin();
  5876. logGlobal->trace("\tSpawning monster at %s", tile->toString());
  5877. {
  5878. auto count = cre->getRandomAmount(std::rand);
  5879. createObject(*tile, Obj::MONSTER, creatureID);
  5880. auto monsterId = getTopObj(*tile)->id;
  5881. setObjProperty(monsterId, ObjProperty::MONSTER_COUNT, count);
  5882. setObjProperty(monsterId, ObjProperty::MONSTER_POWER, (si64)1000*count);
  5883. }
  5884. tiles.erase(tile); //not use it again
  5885. }
  5886. }
  5887. void CGameHandler::handleCheatCode(std::string & cheat, PlayerColor player, const CGHeroInstance * hero, const CGTownInstance * town, bool & cheated)
  5888. {
  5889. //Make cheat case-insensitive
  5890. std::transform(cheat.begin(), cheat.end(), cheat.begin(), [](unsigned char c){ return std::tolower(c); });
  5891. if (cheat == "vcmiistari" || cheat == "vcmispells")
  5892. {
  5893. cheated = true;
  5894. if (!hero) return;
  5895. ///Give hero spellbook
  5896. if (!hero->hasSpellbook())
  5897. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  5898. ///Give all spells with bonus (to allow banned spells)
  5899. GiveBonus giveBonus(GiveBonus::ETarget::HERO);
  5900. giveBonus.id = hero->id.getNum();
  5901. giveBonus.bonus = Bonus(BonusDuration::PERMANENT, BonusType::SPELLS_OF_LEVEL, BonusSource::OTHER, 0, 0);
  5902. //start with level 0 to skip abilities
  5903. for (int level = 1; level <= GameConstants::SPELL_LEVELS; level++)
  5904. {
  5905. giveBonus.bonus.subtype = level;
  5906. sendAndApply(&giveBonus);
  5907. }
  5908. ///Give mana
  5909. SetMana sm;
  5910. sm.hid = hero->id;
  5911. sm.val = 999;
  5912. sm.absolute = true;
  5913. sendAndApply(&sm);
  5914. }
  5915. else if (cheat == "vcmiarmenelos" || cheat == "vcmibuild")
  5916. {
  5917. cheated = true;
  5918. if (!town) return;
  5919. ///Build all buildings in selected town
  5920. for (auto & build : town->town->buildings)
  5921. {
  5922. if (!town->hasBuilt(build.first)
  5923. && !build.second->getNameTranslated().empty()
  5924. && build.first != BuildingID::SHIP)
  5925. {
  5926. buildStructure(town->id, build.first, true);
  5927. }
  5928. }
  5929. }
  5930. else if (cheat == "vcmiainur" || cheat == "vcmiangband" || cheat == "vcmiglaurung" || cheat == "vcmiarchangel"
  5931. || cheat == "vcmiblackknight" || cheat == "vcmicrystal" || cheat == "vcmiazure" || cheat == "vcmifaerie")
  5932. {
  5933. cheated = true;
  5934. if (!hero) return;
  5935. ///Gives N creatures into each slot
  5936. std::map<std::string, std::pair<std::string, int>> creatures;
  5937. creatures.insert(std::make_pair("vcmiainur", std::make_pair("archangel", 5))); //5 archangels
  5938. creatures.insert(std::make_pair("vcmiangband", std::make_pair("blackKnight", 10))); //10 black knights
  5939. creatures.insert(std::make_pair("vcmiglaurung", std::make_pair("crystalDragon", 5000))); //5000 crystal dragons
  5940. creatures.insert(std::make_pair("vcmiarchangel", std::make_pair("archangel", 5))); //5 archangels
  5941. creatures.insert(std::make_pair("vcmiblackknight", std::make_pair("blackKnight", 10))); //10 black knights
  5942. creatures.insert(std::make_pair("vcmicrystal", std::make_pair("crystalDragon", 5000))); //5000 crystal dragons
  5943. creatures.insert(std::make_pair("vcmiazure", std::make_pair("azureDragon", 5000))); //5000 azure dragons
  5944. creatures.insert(std::make_pair("vcmifaerie", std::make_pair("fairieDragon", 5000))); //5000 faerie dragons
  5945. const int32_t creatureIdentifier = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "creature", creatures[cheat].first, false).value();
  5946. const CCreature * creature = VLC->creh->objects.at(creatureIdentifier);
  5947. for (int i = 0; i < GameConstants::ARMY_SIZE; i++)
  5948. if (!hero->hasStackAtSlot(SlotID(i)))
  5949. insertNewStack(StackLocation(hero, SlotID(i)), creature, creatures[cheat].second);
  5950. }
  5951. else if (boost::starts_with(cheat, "vcmiarmy") || boost::starts_with(cheat, "vcminissi"))
  5952. {
  5953. cheated = true;
  5954. if (!hero) return;
  5955. std::vector<std::string> words;
  5956. boost::split(words, cheat, boost::is_any_of(" "));
  5957. if(words.size() < 2)
  5958. return;
  5959. std::string creatureIdentifier = words[1];
  5960. std::optional<int32_t> creatureId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "creature", creatureIdentifier, false);
  5961. if(creatureId.has_value())
  5962. {
  5963. const auto * creature = CreatureID(creatureId.value()).toCreature();
  5964. for (int i = 0; i < GameConstants::ARMY_SIZE; i++)
  5965. if (!hero->hasStackAtSlot(SlotID(i)))
  5966. insertNewStack(StackLocation(hero, SlotID(i)), creature, 5 * std::pow(10, i));
  5967. }
  5968. }
  5969. else if (cheat == "vcminoldor" || cheat == "vcmimachines")
  5970. {
  5971. cheated = true;
  5972. if (!hero) return;
  5973. ///Give all war machines to hero
  5974. if (!hero->getArt(ArtifactPosition::MACH1))
  5975. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::BALLISTA], ArtifactPosition::MACH1);
  5976. if (!hero->getArt(ArtifactPosition::MACH2))
  5977. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::AMMO_CART], ArtifactPosition::MACH2);
  5978. if (!hero->getArt(ArtifactPosition::MACH3))
  5979. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::FIRST_AID_TENT], ArtifactPosition::MACH3);
  5980. }
  5981. else if (cheat == "vcmiforgeofnoldorking" || cheat == "vcmiartifacts")
  5982. {
  5983. cheated = true;
  5984. if (!hero) return;
  5985. ///Give hero all artifacts except war machines, spell scrolls and spell book
  5986. for(int g = 7; g < VLC->arth->objects.size(); ++g) //including artifacts from mods
  5987. {
  5988. if(VLC->arth->objects[g]->canBePutAt(hero))
  5989. giveHeroNewArtifact(hero, VLC->arth->objects[g], ArtifactPosition::FIRST_AVAILABLE);
  5990. }
  5991. }
  5992. else if (cheat == "vcmiglorfindel" || cheat == "vcmilevel")
  5993. {
  5994. cheated = true;
  5995. if (!hero) return;
  5996. ///selected hero gains a new level
  5997. changePrimSkill(hero, PrimarySkill::EXPERIENCE, VLC->heroh->reqExp(hero->level + 1) - VLC->heroh->reqExp(hero->level));
  5998. }
  5999. else if (boost::starts_with(cheat, "vcmiexp") || boost::starts_with(cheat, "vcmiolorin"))
  6000. {
  6001. cheated = true;
  6002. if (!hero) return;
  6003. std::vector<std::string> words;
  6004. boost::split(words, cheat, boost::is_any_of(" "));
  6005. if(words.size() < 2)
  6006. return;
  6007. std::string expAmount = words[1];
  6008. long expAmountProcessed = 0;
  6009. try
  6010. {
  6011. expAmountProcessed = std::stol(expAmount);
  6012. }
  6013. catch(std::exception&)
  6014. {
  6015. logGlobal->error("Could not parse experience amount for vcmiexp cheat");
  6016. }
  6017. if(expAmountProcessed > 1)
  6018. {
  6019. changePrimSkill(hero, PrimarySkill::EXPERIENCE, expAmountProcessed);
  6020. }
  6021. }
  6022. else if (cheat == "vcminahar" || cheat == "vcmimove")
  6023. {
  6024. cheated = true;
  6025. if (!hero) return;
  6026. ///Give 1000000 movement points to hero
  6027. SetMovePoints smp;
  6028. smp.hid = hero->id;
  6029. smp.val = 1000000;
  6030. sendAndApply(&smp);
  6031. GiveBonus gb(GiveBonus::ETarget::HERO);
  6032. gb.bonus.type = BonusType::FREE_SHIP_BOARDING;
  6033. gb.bonus.duration = BonusDuration::ONE_DAY;
  6034. gb.bonus.source = BonusSource::OTHER;
  6035. gb.id = hero->id.getNum();
  6036. giveHeroBonus(&gb);
  6037. }
  6038. else if (cheat == "vcmiformenos" || cheat == "vcmiresources")
  6039. {
  6040. cheated = true;
  6041. ///Give resources to player
  6042. TResources resources;
  6043. resources[EGameResID::GOLD] = 100000;
  6044. for (GameResID i = EGameResID::WOOD; i < EGameResID::GOLD; ++i)
  6045. resources[i] = 100;
  6046. giveResources(player, resources);
  6047. }
  6048. else if (cheat == "vcmisilmaril" || cheat == "vcmiwin")
  6049. {
  6050. cheated = true;
  6051. ///Player wins
  6052. PlayerCheated pc;
  6053. pc.player = player;
  6054. pc.winningCheatCode = true;
  6055. sendAndApply(&pc);
  6056. }
  6057. else if (cheat == "vcmimelkor" || cheat == "vcmilose")
  6058. {
  6059. cheated = true;
  6060. ///Player looses
  6061. PlayerCheated pc;
  6062. pc.player = player;
  6063. pc.losingCheatCode = true;
  6064. sendAndApply(&pc);
  6065. }
  6066. else if (cheat == "vcmieagles" || cheat == "vcmiungoliant" || cheat == "vcmimap" || cheat == "vcmihidemap")
  6067. {
  6068. cheated = true;
  6069. ///Reveal or conceal FoW
  6070. FoWChange fc;
  6071. fc.mode = ((cheat == "vcmieagles" || cheat == "vcmimap") ? 1 : 0);
  6072. fc.player = player;
  6073. const auto & fowMap = gs->getPlayerTeam(player)->fogOfWarMap;
  6074. auto hlp_tab = new int3[gs->map->width * gs->map->height * (gs->map->levels())];
  6075. int lastUnc = 0;
  6076. for(int z = 0; z < gs->map->levels(); z++)
  6077. for(int x = 0; x < gs->map->width; x++)
  6078. for(int y = 0; y < gs->map->height; y++)
  6079. if(!(*fowMap)[z][x][y] || !fc.mode)
  6080. hlp_tab[lastUnc++] = int3(x, y, z);
  6081. fc.tiles.insert(hlp_tab, hlp_tab + lastUnc);
  6082. delete [] hlp_tab;
  6083. sendAndApply(&fc);
  6084. }
  6085. }
  6086. void CGameHandler::removeObstacle(const CObstacleInstance & obstacle)
  6087. {
  6088. BattleObstaclesChanged obsRem;
  6089. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  6090. sendAndApply(&obsRem);
  6091. }
  6092. void CGameHandler::synchronizeArtifactHandlerLists()
  6093. {
  6094. UpdateArtHandlerLists uahl;
  6095. uahl.treasures = VLC->arth->treasures;
  6096. uahl.minors = VLC->arth->minors;
  6097. uahl.majors = VLC->arth->majors;
  6098. uahl.relics = VLC->arth->relics;
  6099. sendAndApply(&uahl);
  6100. }
  6101. bool CGameHandler::isValidObject(const CGObjectInstance *obj) const
  6102. {
  6103. return vstd::contains(gs->map->objects, obj);
  6104. }
  6105. bool CGameHandler::isBlockedByQueries(const CPack *pack, PlayerColor player)
  6106. {
  6107. if (!strcmp(typeid(*pack).name(), typeid(PlayerMessage).name()))
  6108. return false;
  6109. auto query = queries.topQuery(player);
  6110. if (query && query->blocksPack(pack))
  6111. {
  6112. complain(boost::str(boost::format(
  6113. "\r\n| Player \"%s\" has to answer queries before attempting any further actions.\r\n| Top Query: \"%s\"\r\n")
  6114. % boost::to_upper_copy<std::string>(player.getStr())
  6115. % query->toString()
  6116. ));
  6117. return true;
  6118. }
  6119. return false;
  6120. }
  6121. void CGameHandler::removeAfterVisit(const CGObjectInstance *object)
  6122. {
  6123. //If the object is being visited, there must be a matching query
  6124. for (const auto &query : queries.allQueries())
  6125. {
  6126. if (auto someVistQuery = std::dynamic_pointer_cast<CObjectVisitQuery>(query))
  6127. {
  6128. if (someVistQuery->visitedObject == object)
  6129. {
  6130. someVistQuery->removeObjectAfterVisit = true;
  6131. return;
  6132. }
  6133. }
  6134. }
  6135. //If we haven't returned so far, there is no query and no visit, call was wrong
  6136. assert("This function needs to be called during the object visit!");
  6137. }
  6138. void CGameHandler::changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide)
  6139. {
  6140. std::unordered_set<int3> tiles;
  6141. getTilesInRange(tiles, center, radius, player, hide? -1 : 1);
  6142. if (hide)
  6143. {
  6144. std::unordered_set<int3> observedTiles; //do not hide tiles observed by heroes. May lead to disastrous AI problems
  6145. auto p = getPlayerState(player);
  6146. for (auto h : p->heroes)
  6147. {
  6148. getTilesInRange(observedTiles, h->getSightCenter(), h->getSightRadius(), h->tempOwner, -1);
  6149. }
  6150. for (auto t : p->towns)
  6151. {
  6152. getTilesInRange(observedTiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, -1);
  6153. }
  6154. for (auto tile : observedTiles)
  6155. vstd::erase_if_present (tiles, tile);
  6156. }
  6157. changeFogOfWar(tiles, player, hide);
  6158. }
  6159. void CGameHandler::changeFogOfWar(std::unordered_set<int3> &tiles, PlayerColor player, bool hide)
  6160. {
  6161. FoWChange fow;
  6162. fow.tiles = tiles;
  6163. fow.player = player;
  6164. fow.mode = hide? 0 : 1;
  6165. sendAndApply(&fow);
  6166. }
  6167. bool CGameHandler::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero)
  6168. {
  6169. if (auto topQuery = queries.topQuery(hero->getOwner()))
  6170. if (auto visit = std::dynamic_pointer_cast<const CObjectVisitQuery>(topQuery))
  6171. return !(visit->visitedObject == obj && visit->visitingHero == hero);
  6172. return true;
  6173. }
  6174. void CGameHandler::setObjProperty(ObjectInstanceID objid, int prop, si64 val)
  6175. {
  6176. SetObjectProperty sob;
  6177. sob.id = objid;
  6178. sob.what = prop;
  6179. sob.val = static_cast<ui32>(val);
  6180. sendAndApply(&sob);
  6181. }
  6182. void CGameHandler::showInfoDialog(InfoWindow * iw)
  6183. {
  6184. sendAndApply(iw);
  6185. }
  6186. void CGameHandler::showInfoDialog(const std::string & msg, PlayerColor player)
  6187. {
  6188. InfoWindow iw;
  6189. iw.player = player;
  6190. iw.text.appendRawString(msg);
  6191. showInfoDialog(&iw);
  6192. }
  6193. CasualtiesAfterBattle::CasualtiesAfterBattle(const CArmedInstance * _army, const BattleInfo * bat):
  6194. army(_army)
  6195. {
  6196. heroWithDeadCommander = ObjectInstanceID();
  6197. PlayerColor color = army->tempOwner;
  6198. if(color == PlayerColor::UNFLAGGABLE)
  6199. color = PlayerColor::NEUTRAL;
  6200. for(CStack * st : bat->stacks)
  6201. {
  6202. if(st->summoned) //don't take into account temporary summoned stacks
  6203. continue;
  6204. if(st->unitOwner() != color) //remove only our stacks
  6205. continue;
  6206. logGlobal->debug("Calculating casualties for %s", st->nodeName());
  6207. st->health.takeResurrected();
  6208. if(st->unitSlot() == SlotID::ARROW_TOWERS_SLOT)
  6209. {
  6210. logGlobal->debug("Ignored arrow towers stack.");
  6211. }
  6212. else if(st->unitSlot() == SlotID::WAR_MACHINES_SLOT)
  6213. {
  6214. auto warMachine = st->unitType()->warMachine;
  6215. if(warMachine == ArtifactID::NONE)
  6216. {
  6217. logGlobal->error("Invalid creature in war machine virtual slot. Stack: %s", st->nodeName());
  6218. }
  6219. //catapult artifact remain even if "creature" killed in siege
  6220. else if(warMachine != ArtifactID::CATAPULT && st->getCount() <= 0)
  6221. {
  6222. logGlobal->debug("War machine has been destroyed");
  6223. auto hero = dynamic_ptr_cast<CGHeroInstance> (army);
  6224. if (hero)
  6225. removedWarMachines.push_back (ArtifactLocation(hero, hero->getArtPos(warMachine, true)));
  6226. else
  6227. logGlobal->error("War machine in army without hero");
  6228. }
  6229. }
  6230. else if(st->unitSlot() == SlotID::SUMMONED_SLOT_PLACEHOLDER)
  6231. {
  6232. if(st->alive() && st->getCount() > 0)
  6233. {
  6234. logGlobal->debug("Permanently summoned %d units.", st->getCount());
  6235. const CreatureID summonedType = st->creatureId();
  6236. summoned[summonedType] += st->getCount();
  6237. }
  6238. }
  6239. else if(st->unitSlot() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  6240. {
  6241. if (nullptr == st->base)
  6242. {
  6243. logGlobal->error("Stack with no base in commander slot. Stack: %s", st->nodeName());
  6244. }
  6245. else
  6246. {
  6247. auto c = dynamic_cast <const CCommanderInstance *>(st->base);
  6248. if(c)
  6249. {
  6250. auto h = dynamic_cast <const CGHeroInstance *>(army);
  6251. if(h && h->commander == c && (st->getCount() == 0 || !st->alive()))
  6252. {
  6253. logGlobal->debug("Commander is dead.");
  6254. heroWithDeadCommander = army->id; //TODO: unify commander handling
  6255. }
  6256. }
  6257. else
  6258. logGlobal->error("Stack with invalid instance in commander slot. Stack: %s", st->nodeName());
  6259. }
  6260. }
  6261. else if(st->base && !army->slotEmpty(st->unitSlot()))
  6262. {
  6263. logGlobal->debug("Count: %d; base count: %d", st->getCount(), army->getStackCount(st->unitSlot()));
  6264. if(st->getCount() == 0 || !st->alive())
  6265. {
  6266. logGlobal->debug("Stack has been destroyed.");
  6267. StackLocation sl(army, st->unitSlot());
  6268. newStackCounts.push_back(TStackAndItsNewCount(sl, 0));
  6269. }
  6270. else if(st->getCount() < army->getStackCount(st->unitSlot()))
  6271. {
  6272. logGlobal->debug("Stack lost %d units.", army->getStackCount(st->unitSlot()) - st->getCount());
  6273. StackLocation sl(army, st->unitSlot());
  6274. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  6275. }
  6276. else if(st->getCount() > army->getStackCount(st->unitSlot()))
  6277. {
  6278. logGlobal->debug("Stack gained %d units.", st->getCount() - army->getStackCount(st->unitSlot()));
  6279. StackLocation sl(army, st->unitSlot());
  6280. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  6281. }
  6282. }
  6283. else
  6284. {
  6285. logGlobal->warn("Unable to process stack: %s", st->nodeName());
  6286. }
  6287. }
  6288. }
  6289. void CasualtiesAfterBattle::updateArmy(CGameHandler *gh)
  6290. {
  6291. for (TStackAndItsNewCount &ncount : newStackCounts)
  6292. {
  6293. if (ncount.second > 0)
  6294. gh->changeStackCount(ncount.first, ncount.second, true);
  6295. else
  6296. gh->eraseStack(ncount.first, true);
  6297. }
  6298. for (auto summoned_iter : summoned)
  6299. {
  6300. SlotID slot = army->getSlotFor(summoned_iter.first);
  6301. if (slot.validSlot())
  6302. {
  6303. StackLocation location(army, slot);
  6304. gh->addToSlot(location, summoned_iter.first.toCreature(), summoned_iter.second);
  6305. }
  6306. else
  6307. {
  6308. //even if it will be possible to summon anything permanently it should be checked for free slot
  6309. //necromancy is handled separately
  6310. gh->complain("No free slot to put summoned creature");
  6311. }
  6312. }
  6313. for (auto al : removedWarMachines)
  6314. {
  6315. gh->removeArtifact(al);
  6316. }
  6317. if (heroWithDeadCommander != ObjectInstanceID())
  6318. {
  6319. SetCommanderProperty scp;
  6320. scp.heroid = heroWithDeadCommander;
  6321. scp.which = SetCommanderProperty::ALIVE;
  6322. scp.amount = 0;
  6323. gh->sendAndApply(&scp);
  6324. }
  6325. }
  6326. CGameHandler::FinishingBattleHelper::FinishingBattleHelper(std::shared_ptr<const CBattleQuery> Query, int RemainingBattleQueriesCount)
  6327. {
  6328. assert(Query->result);
  6329. assert(Query->bi);
  6330. auto &result = *Query->result;
  6331. auto &info = *Query->bi;
  6332. winnerHero = result.winner != 0 ? info.sides[1].hero : info.sides[0].hero;
  6333. loserHero = result.winner != 0 ? info.sides[0].hero : info.sides[1].hero;
  6334. victor = info.sides[result.winner].color;
  6335. loser = info.sides[!result.winner].color;
  6336. winnerSide = result.winner;
  6337. remainingBattleQueriesCount = RemainingBattleQueriesCount;
  6338. }
  6339. CGameHandler::FinishingBattleHelper::FinishingBattleHelper()
  6340. {
  6341. winnerHero = loserHero = nullptr;
  6342. winnerSide = 0;
  6343. remainingBattleQueriesCount = 0;
  6344. }
  6345. CRandomGenerator & CGameHandler::getRandomGenerator()
  6346. {
  6347. return CRandomGenerator::getDefault();
  6348. }
  6349. #if SCRIPTING_ENABLED
  6350. scripting::Pool * CGameHandler::getGlobalContextPool() const
  6351. {
  6352. return serverScripts.get();
  6353. }
  6354. scripting::Pool * CGameHandler::getContextPool() const
  6355. {
  6356. return serverScripts.get();
  6357. }
  6358. #endif
  6359. void CGameHandler::createObject(const int3 & visitablePosition, Obj type, int32_t subtype)
  6360. {
  6361. NewObject no;
  6362. no.ID = type;
  6363. no.subID= subtype;
  6364. no.targetPos = visitablePosition;
  6365. sendAndApply(&no);
  6366. }