CGameHandler.cpp 179 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115
  1. #include "StdInc.h"
  2. #include "../lib/filesystem/Filesystem.h"
  3. #include "../lib/filesystem/CFileInfo.h"
  4. #include "../lib/int3.h"
  5. #include "../lib/mapping/CCampaignHandler.h"
  6. #include "../lib/StartInfo.h"
  7. #include "../lib/CModHandler.h"
  8. #include "../lib/CArtHandler.h"
  9. #include "../lib/CBuildingHandler.h"
  10. #include "../lib/CHeroHandler.h"
  11. #include "../lib/spells/CSpellHandler.h"
  12. #include "../lib/spells/ISpellMechanics.h"
  13. #include "../lib/CGeneralTextHandler.h"
  14. #include "../lib/CTownHandler.h"
  15. #include "../lib/CCreatureHandler.h"
  16. #include "../lib/CGameState.h"
  17. #include "../lib/BattleState.h"
  18. #include "../lib/CondSh.h"
  19. #include "../lib/NetPacks.h"
  20. #include "../lib/VCMI_Lib.h"
  21. #include "../lib/mapping/CMap.h"
  22. #include "../lib/VCMIDirs.h"
  23. #include "../lib/ScopeGuard.h"
  24. #include "../lib/CSoundBase.h"
  25. #include "CGameHandler.h"
  26. #include "CVCMIServer.h"
  27. #include "../lib/CCreatureSet.h"
  28. #include "../lib/CThreadHelper.h"
  29. #include "../lib/GameConstants.h"
  30. #include "../lib/registerTypes/RegisterTypes.h"
  31. /*
  32. * CGameHandler.cpp, part of VCMI engine
  33. *
  34. * Authors: listed in file AUTHORS in main folder
  35. *
  36. * License: GNU General Public License v2.0 or later
  37. * Full text of license available in license.txt file, in main folder
  38. *
  39. */
  40. #ifndef _MSC_VER
  41. #include <boost/thread/xtime.hpp>
  42. #endif
  43. extern bool end2;
  44. #ifdef min
  45. #undef min
  46. #endif
  47. #ifdef max
  48. #undef max
  49. #endif
  50. #define COMPLAIN_RET_IF(cond, txt) do {if(cond){complain(txt); return;}} while(0)
  51. #define COMPLAIN_RET_FALSE_IF(cond, txt) do {if(cond){complain(txt); return false;}} while(0)
  52. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  53. #define COMPLAIN_RETF(txt, FORMAT) {complain(boost::str(boost::format(txt) % FORMAT)); return false;}
  54. #define NEW_ROUND BattleNextRound bnr;\
  55. bnr.round = gs->curB->round + 1;\
  56. sendAndApply(&bnr);
  57. class ServerSpellCastEnvironment: public SpellCastEnvironment
  58. {
  59. public:
  60. ServerSpellCastEnvironment(CGameHandler * gh);
  61. ~ServerSpellCastEnvironment(){};
  62. void sendAndApply(CPackForClient * info) const override;
  63. CRandomGenerator & getRandomGenerator() const override;
  64. void complain(const std::string & problem) const override;
  65. const CMap * getMap() const override;
  66. const CGameInfoCallback * getCb() const override;
  67. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, PlayerColor asker = PlayerColor::NEUTRAL) const override;
  68. private:
  69. mutable CGameHandler * gh;
  70. };
  71. CondSh<bool> battleMadeAction;
  72. CondSh<BattleResult *> battleResult(nullptr);
  73. template <typename T> class CApplyOnGH;
  74. class CBaseForGHApply
  75. {
  76. public:
  77. virtual bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack, PlayerColor player) 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, CConnection *c, void *pack, PlayerColor player) const
  88. {
  89. T *ptr = static_cast<T*>(pack);
  90. ptr->c = c;
  91. ptr->player = player;
  92. return ptr->applyGh(gh);
  93. }
  94. };
  95. template <>
  96. class CApplyOnGH<CPack> : public CBaseForGHApply
  97. {
  98. public:
  99. bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack, PlayerColor player) const
  100. {
  101. logGlobal->errorStream() << "Cannot apply on GH plain CPack!";
  102. assert(0);
  103. return false;
  104. }
  105. };
  106. static CApplier<CBaseForGHApply> *applier = nullptr;
  107. CMP_stack cmpst ;
  108. static inline double distance(int3 a, int3 b)
  109. {
  110. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  111. }
  112. static void giveExp(BattleResult &r)
  113. {
  114. if(r.winner > 1)
  115. {
  116. // draw
  117. return;
  118. }
  119. r.exp[0] = 0;
  120. r.exp[1] = 0;
  121. for(auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  122. {
  123. r.exp[r.winner] += VLC->creh->creatures.at(i->first)->valOfBonuses(Bonus::STACK_HEALTH) * i->second;
  124. }
  125. }
  126. PlayerStatus PlayerStatuses::operator[](PlayerColor player)
  127. {
  128. boost::unique_lock<boost::mutex> l(mx);
  129. if(players.find(player) != players.end())
  130. {
  131. return players.at(player);
  132. }
  133. else
  134. {
  135. throw std::runtime_error("No such player!");
  136. }
  137. }
  138. void PlayerStatuses::addPlayer(PlayerColor player)
  139. {
  140. boost::unique_lock<boost::mutex> l(mx);
  141. players[player];
  142. }
  143. bool PlayerStatuses::checkFlag(PlayerColor player, bool PlayerStatus::*flag)
  144. {
  145. boost::unique_lock<boost::mutex> l(mx);
  146. if(players.find(player) != players.end())
  147. {
  148. return players[player].*flag;
  149. }
  150. else
  151. {
  152. throw std::runtime_error("No such player!");
  153. }
  154. }
  155. void PlayerStatuses::setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val)
  156. {
  157. boost::unique_lock<boost::mutex> l(mx);
  158. if(players.find(player) != players.end())
  159. {
  160. players[player].*flag = val;
  161. }
  162. else
  163. {
  164. throw std::runtime_error("No such player!");
  165. }
  166. cv.notify_all();
  167. }
  168. template <typename T>
  169. void callWith(std::vector<T> args, std::function<void(T)> fun, ui32 which)
  170. {
  171. fun(args[which]);
  172. }
  173. void CGameHandler::levelUpHero(const CGHeroInstance * hero, SecondarySkill skill)
  174. {
  175. changeSecSkill(hero, skill, 1, 0);
  176. expGiven(hero);
  177. }
  178. void CGameHandler::levelUpHero(const CGHeroInstance * hero)
  179. {
  180. // required exp for at least 1 lvl-up hasn't been reached
  181. if(!hero->gainsLevel())
  182. {
  183. return;
  184. }
  185. // give primary skill
  186. logGlobal->traceStream() << hero->name << " got level "<< hero->level;
  187. auto primarySkill = hero->nextPrimarySkill();
  188. SetPrimSkill sps;
  189. sps.id = hero->id;
  190. sps.which = primarySkill;
  191. sps.abs = false;
  192. sps.val = 1;
  193. sendAndApply(&sps);
  194. HeroLevelUp hlu;
  195. hlu.hero = hero;
  196. hlu.primskill = primarySkill;
  197. hlu.skills = hero->getLevelUpProposedSecondarySkills();
  198. if(hlu.skills.size() == 0)
  199. {
  200. sendAndApply(&hlu);
  201. levelUpHero(hero);
  202. }
  203. else if(hlu.skills.size() == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  204. {
  205. sendAndApply(&hlu);
  206. levelUpHero(hero, *RandomGeneratorUtil::nextItem(hlu.skills, hero->skillsInfo.rand));
  207. }
  208. else if(hlu.skills.size() > 1)
  209. {
  210. auto levelUpQuery = std::make_shared<CHeroLevelUpDialogQuery>(hlu);
  211. hlu.queryID = levelUpQuery->queryID;
  212. queries.addQuery(levelUpQuery);
  213. sendAndApply(&hlu);
  214. //level up will be called on query reply
  215. }
  216. }
  217. void CGameHandler::levelUpCommander (const CCommanderInstance * c, int skill)
  218. {
  219. SetCommanderProperty scp;
  220. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  221. if (hero)
  222. scp.heroid = hero->id;
  223. else
  224. {
  225. complain ("Commander is not led by hero!");
  226. return;
  227. }
  228. scp.accumulatedBonus.subtype = 0;
  229. scp.accumulatedBonus.additionalInfo = 0;
  230. scp.accumulatedBonus.duration = Bonus::PERMANENT;
  231. scp.accumulatedBonus.turnsRemain = 0;
  232. scp.accumulatedBonus.source = Bonus::COMMANDER;
  233. scp.accumulatedBonus.valType = Bonus::BASE_NUMBER;
  234. if (skill <= ECommander::SPELL_POWER)
  235. {
  236. scp.which = SetCommanderProperty::BONUS;
  237. auto difference = [](std::vector< std::vector <ui8> > skillLevels, std::vector <ui8> secondarySkills, int skill)->int
  238. {
  239. int s = std::min (skill, (int)ECommander::SPELL_POWER); //spell power level controls also casts and resistance
  240. return skillLevels.at(skill).at(secondarySkills.at(s)) - (secondarySkills.at(s) ? skillLevels.at(skill).at(secondarySkills.at(s)-1) : 0);
  241. };
  242. switch (skill)
  243. {
  244. case ECommander::ATTACK:
  245. scp.accumulatedBonus.type = Bonus::PRIMARY_SKILL;
  246. scp.accumulatedBonus.subtype = PrimarySkill::ATTACK;
  247. break;
  248. case ECommander::DEFENSE:
  249. scp.accumulatedBonus.type = Bonus::PRIMARY_SKILL;
  250. scp.accumulatedBonus.subtype = PrimarySkill::DEFENSE;
  251. break;
  252. case ECommander::HEALTH:
  253. scp.accumulatedBonus.type = Bonus::STACK_HEALTH;
  254. scp.accumulatedBonus.valType = Bonus::PERCENT_TO_BASE;
  255. break;
  256. case ECommander::DAMAGE:
  257. scp.accumulatedBonus.type = Bonus::CREATURE_DAMAGE;
  258. scp.accumulatedBonus.subtype = 0;
  259. scp.accumulatedBonus.valType = Bonus::PERCENT_TO_BASE;
  260. break;
  261. case ECommander::SPEED:
  262. scp.accumulatedBonus.type = Bonus::STACKS_SPEED;
  263. break;
  264. case ECommander::SPELL_POWER:
  265. scp.accumulatedBonus.type = Bonus::MAGIC_RESISTANCE;
  266. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::RESISTANCE);
  267. sendAndApply (&scp); //additional pack
  268. scp.accumulatedBonus.type = Bonus::CREATURE_SPELL_POWER;
  269. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::SPELL_POWER) * 100; //like hero with spellpower = ability level
  270. sendAndApply (&scp); //additional pack
  271. scp.accumulatedBonus.type = Bonus::CASTS;
  272. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::CASTS);
  273. sendAndApply (&scp); //additional pack
  274. scp.accumulatedBonus.type = Bonus::CREATURE_ENCHANT_POWER; //send normally
  275. break;
  276. }
  277. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, skill);
  278. sendAndApply (&scp);
  279. scp.which = SetCommanderProperty::SECONDARY_SKILL;
  280. scp.additionalInfo = skill;
  281. scp.amount = c->secondarySkills.at(skill) + 1;
  282. sendAndApply (&scp);
  283. }
  284. else if (skill >= 100)
  285. {
  286. scp.which = SetCommanderProperty::SPECIAL_SKILL;
  287. scp.accumulatedBonus = *VLC->creh->skillRequirements.at(skill-100).first;
  288. scp.additionalInfo = skill; //unnormalized
  289. sendAndApply (&scp);
  290. }
  291. expGiven(hero);
  292. }
  293. void CGameHandler::levelUpCommander(const CCommanderInstance * c)
  294. {
  295. if (!c->gainsLevel())
  296. {
  297. return;
  298. }
  299. CommanderLevelUp clu;
  300. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  301. if (hero)
  302. clu.hero = hero;
  303. else
  304. {
  305. complain ("Commander is not led by hero!");
  306. return;
  307. }
  308. //picking sec. skills for choice
  309. for (int i = 0; i <= ECommander::SPELL_POWER; ++i)
  310. {
  311. if (c->secondarySkills.at(i) < ECommander::MAX_SKILL_LEVEL)
  312. clu.skills.push_back(i);
  313. }
  314. int i = 100;
  315. for (auto specialSkill : VLC->creh->skillRequirements)
  316. {
  317. if (c->secondarySkills.at(specialSkill.second.first) == ECommander::MAX_SKILL_LEVEL
  318. && c->secondarySkills.at(specialSkill.second.second) == ECommander::MAX_SKILL_LEVEL
  319. && !vstd::contains (c->specialSKills, i))
  320. clu.skills.push_back (i);
  321. ++i;
  322. }
  323. int skillAmount = clu.skills.size();
  324. if(!skillAmount)
  325. {
  326. sendAndApply(&clu);
  327. levelUpCommander(c);
  328. }
  329. else if(skillAmount == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  330. {
  331. sendAndApply(&clu);
  332. levelUpCommander(c, *RandomGeneratorUtil::nextItem(clu.skills, gs->getRandomGenerator()));
  333. }
  334. else if(skillAmount > 1) //apply and ask for secondary skill
  335. {
  336. auto commanderLevelUp = std::make_shared<CCommanderLevelUpDialogQuery>(clu);
  337. clu.queryID = commanderLevelUp->queryID;
  338. queries.addQuery(commanderLevelUp);
  339. sendAndApply(&clu);
  340. }
  341. }
  342. void CGameHandler::expGiven(const CGHeroInstance *hero)
  343. {
  344. if(hero->gainsLevel())
  345. levelUpHero(hero);
  346. else if(hero->commander && hero->commander->gainsLevel())
  347. levelUpCommander(hero->commander);
  348. //if(hero->commander && hero->level > hero->commander->level && hero->commander->gainsLevel())
  349. // levelUpCommander(hero->commander);
  350. // else
  351. // levelUpHero(hero);
  352. }
  353. void CGameHandler::changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs)
  354. {
  355. if (which == PrimarySkill::EXPERIENCE) // Check if scenario limit reached
  356. {
  357. if (gs->map->levelLimit != 0)
  358. {
  359. TExpType expLimit = VLC->heroh->reqExp(gs->map->levelLimit);
  360. TExpType resultingExp = abs ? val : hero->exp + val;
  361. if (resultingExp > expLimit)
  362. {
  363. // set given experience to max possible, but don't decrease if hero already over top
  364. abs = true;
  365. val = std::max(expLimit, hero->exp);
  366. InfoWindow iw;
  367. iw.player = hero->tempOwner;
  368. iw.text.addTxt(MetaString::GENERAL_TXT, 1); //can gain no more XP
  369. iw.text.addReplacement(hero->name);
  370. sendAndApply(&iw);
  371. }
  372. }
  373. }
  374. SetPrimSkill sps;
  375. sps.id = hero->id;
  376. sps.which = which;
  377. sps.abs = abs;
  378. sps.val = val;
  379. sendAndApply(&sps);
  380. //only for exp - hero may level up
  381. if (which == PrimarySkill::EXPERIENCE)
  382. {
  383. if(hero->commander && hero->commander->alive)
  384. {
  385. //FIXME: trim experience according to map limit?
  386. SetCommanderProperty scp;
  387. scp.heroid = hero->id;
  388. scp.which = SetCommanderProperty::EXPERIENCE;
  389. scp.amount = val;
  390. sendAndApply (&scp);
  391. CBonusSystemNode::treeHasChanged();
  392. }
  393. expGiven(hero);
  394. }
  395. }
  396. void CGameHandler::changeSecSkill( const CGHeroInstance * hero, SecondarySkill which, int val, bool abs/*=false*/ )
  397. {
  398. SetSecSkill sss;
  399. sss.id = hero->id;
  400. sss.which = which;
  401. sss.val = val;
  402. sss.abs = abs;
  403. sendAndApply(&sss);
  404. if(which == SecondarySkill::WISDOM)
  405. {
  406. if(hero && hero->visitedTown)
  407. giveSpells(hero->visitedTown, hero);
  408. }
  409. }
  410. void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  411. {
  412. LOG_TRACE(logGlobal);
  413. //Fill BattleResult structure with exp info
  414. giveExp(*battleResult.data);
  415. if (battleResult.get()->result == BattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  416. {
  417. if (hero1)
  418. battleResult.data->exp[1] += 500;
  419. if (hero2)
  420. battleResult.data->exp[0] += 500;
  421. }
  422. if (hero1)
  423. battleResult.data->exp[0] = hero1->calculateXp(battleResult.data->exp[0]);//scholar skill
  424. if (hero2)
  425. battleResult.data->exp[1] = hero2->calculateXp(battleResult.data->exp[1]);
  426. const CArmedInstance *bEndArmy1 = gs->curB->sides.at(0).armyObject;
  427. const CArmedInstance *bEndArmy2 = gs->curB->sides.at(1).armyObject;
  428. const BattleResult::EResult result = battleResult.get()->result;
  429. auto findBattleQuery = [this]() -> std::shared_ptr<CBattleQuery>
  430. {
  431. for(auto &q : queries.allQueries())
  432. {
  433. if(auto bq = std::dynamic_pointer_cast<CBattleQuery>(q))
  434. if(bq->bi == gs->curB)
  435. return bq;
  436. }
  437. return std::shared_ptr<CBattleQuery>();
  438. };
  439. auto battleQuery = findBattleQuery();
  440. if(!battleQuery)
  441. {
  442. logGlobal->errorStream() << "Cannot find battle query!";
  443. if(gs->initialOpts->mode == StartInfo::DUEL)
  444. {
  445. battleQuery = std::make_shared<CBattleQuery>(gs->curB);
  446. }
  447. }
  448. if(battleQuery != queries.topQuery(gs->curB->sides[0].color))
  449. complain("Player " + boost::lexical_cast<std::string>(gs->curB->sides[0].color) + " although in battle has no battle query at the top!");
  450. battleQuery->result = *battleResult.data;
  451. //Check how many battle queries were created (number of players blocked by battle)
  452. const int queriedPlayers = battleQuery ? boost::count(queries.allQueries(), battleQuery) : 0;
  453. finishingBattle = make_unique<FinishingBattleHelper>(battleQuery, gs->initialOpts->mode == StartInfo::DUEL, queriedPlayers);
  454. CasualtiesAfterBattle cab1(bEndArmy1, gs->curB), cab2(bEndArmy2, gs->curB); //calculate casualties before deleting battle
  455. if(finishingBattle->duel)
  456. {
  457. duelFinished();
  458. sendAndApply(battleResult.data); //after this point casualties objects are destroyed
  459. return;
  460. }
  461. ChangeSpells cs; //for Eagle Eye
  462. if(finishingBattle->winnerHero)
  463. {
  464. if(int eagleEyeLevel = finishingBattle->winnerHero->getSecSkillLevel(SecondarySkill::EAGLE_EYE))
  465. {
  466. int maxLevel = eagleEyeLevel + 1;
  467. double eagleEyeChance = finishingBattle->winnerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::EAGLE_EYE);
  468. for(const CSpell *sp : gs->curB->sides.at(!battleResult.data->winner).usedSpellsHistory)
  469. if(sp->level <= maxLevel && !vstd::contains(finishingBattle->winnerHero->spells, sp->id) && gs->getRandomGenerator().nextInt(99) < eagleEyeChance)
  470. cs.spells.insert(sp->id);
  471. }
  472. }
  473. std::vector<const CArtifactInstance *> arts; //display them in window
  474. if(result == BattleResult::NORMAL && finishingBattle->winnerHero)
  475. {
  476. auto sendMoveArtifact = [&](const CArtifactInstance *art, MoveArtifact *ma)
  477. {
  478. arts.push_back(art);
  479. ma->dst = ArtifactLocation(finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero));
  480. sendAndApply(ma);
  481. };
  482. if(finishingBattle->loserHero)
  483. {
  484. //TODO: wrap it into a function, somehow (boost::variant -_-)
  485. auto artifactsWorn = finishingBattle->loserHero->artifactsWorn;
  486. for (auto artSlot : artifactsWorn)
  487. {
  488. MoveArtifact ma;
  489. ma.src = ArtifactLocation(finishingBattle->loserHero, artSlot.first);
  490. const CArtifactInstance * art = ma.src.getArt();
  491. if(art && !art->artType->isBig() &&
  492. art->artType->id != ArtifactID::SPELLBOOK)
  493. // don't move war machines or locked arts (spellbook)
  494. {
  495. sendMoveArtifact(art, &ma);
  496. }
  497. }
  498. while(!finishingBattle->loserHero->artifactsInBackpack.empty())
  499. {
  500. //we assume that no big artifacts can be found
  501. MoveArtifact ma;
  502. ma.src = ArtifactLocation(finishingBattle->loserHero,
  503. ArtifactPosition(GameConstants::BACKPACK_START)); //backpack automatically shifts arts to beginning
  504. const CArtifactInstance * art = ma.src.getArt();
  505. if(art->artType->id != ArtifactID::GRAIL) //grail may not be won
  506. {
  507. sendMoveArtifact(art, &ma);
  508. }
  509. }
  510. if(finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero?
  511. {
  512. artifactsWorn = finishingBattle->loserHero->commander->artifactsWorn;
  513. for(auto artSlot : artifactsWorn)
  514. {
  515. MoveArtifact ma;
  516. ma.src = ArtifactLocation(finishingBattle->loserHero->commander.get(), artSlot.first);
  517. const CArtifactInstance * art = ma.src.getArt();
  518. if (art && !art->artType->isBig())
  519. {
  520. sendMoveArtifact(art, &ma);
  521. }
  522. }
  523. }
  524. }
  525. for(auto armySlot : gs->curB->battleGetArmyObject(!battleResult.data->winner)->stacks)
  526. {
  527. auto artifactsWorn = armySlot.second->artifactsWorn;
  528. for (auto artSlot : artifactsWorn)
  529. {
  530. MoveArtifact ma;
  531. ma.src = ArtifactLocation(armySlot.second, artSlot.first);
  532. const CArtifactInstance * art = ma.src.getArt();
  533. if (art && !art->artType->isBig())
  534. {
  535. sendMoveArtifact(art, &ma);
  536. }
  537. }
  538. }
  539. }
  540. sendAndApply(battleResult.data); //after this point casualties objects are destroyed
  541. if(arts.size()) //display loot
  542. {
  543. InfoWindow iw;
  544. iw.player = finishingBattle->winnerHero->tempOwner;
  545. iw.text.addTxt (MetaString::GENERAL_TXT, 30); //You have captured enemy artifact
  546. for(auto art : arts) //TODO; separate function to display loot for various ojects?
  547. {
  548. iw.components.push_back(Component(
  549. Component::ARTIFACT, art->artType->id,
  550. art->artType->id == ArtifactID::SPELL_SCROLL? art->getGivenSpellID() : 0, 0));
  551. if(iw.components.size() >= 14)
  552. {
  553. sendAndApply(&iw);
  554. iw.components.clear();
  555. }
  556. }
  557. if(iw.components.size())
  558. {
  559. sendAndApply(&iw);
  560. }
  561. }
  562. //Eagle Eye secondary skill handling
  563. if(!cs.spells.empty())
  564. {
  565. cs.learn = 1;
  566. cs.hid = finishingBattle->winnerHero->id;
  567. InfoWindow iw;
  568. iw.player = finishingBattle->winnerHero->tempOwner;
  569. iw.text.addTxt(MetaString::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
  570. iw.text.addReplacement(finishingBattle->winnerHero->name);
  571. std::ostringstream names;
  572. for(int i = 0; i < cs.spells.size(); i++)
  573. {
  574. names << "%s";
  575. if(i < cs.spells.size() - 2)
  576. names << ", ";
  577. else if(i < cs.spells.size() - 1)
  578. names << "%s";
  579. }
  580. names << ".";
  581. iw.text.addReplacement(names.str());
  582. auto it = cs.spells.begin();
  583. for(int i = 0; i < cs.spells.size(); i++, it++)
  584. {
  585. iw.text.addReplacement(MetaString::SPELL_NAME, it->toEnum());
  586. if(i == cs.spells.size() - 2) //we just added pre-last name
  587. iw.text.addReplacement(MetaString::GENERAL_TXT, 141); // " and "
  588. iw.components.push_back(Component(Component::SPELL, *it, 0, 0));
  589. }
  590. sendAndApply(&iw);
  591. sendAndApply(&cs);
  592. }
  593. cab1.takeFromArmy(this);
  594. cab2.takeFromArmy(this); //take casualties after battle is deleted
  595. //if one hero has lost we will erase him
  596. if(battleResult.data->winner!=0 && hero1)
  597. {
  598. RemoveObject ro(hero1->id);
  599. sendAndApply(&ro);
  600. }
  601. if(battleResult.data->winner!=1 && hero2)
  602. {
  603. RemoveObject ro(hero2->id);
  604. sendAndApply(&ro);
  605. }
  606. //give exp
  607. if (battleResult.data->exp[0] && hero1 && battleResult.get()->winner == 0)
  608. changePrimSkill(hero1, PrimarySkill::EXPERIENCE, battleResult.data->exp[0]);
  609. else if (battleResult.data->exp[1] && hero2 && battleResult.get()->winner == 1)
  610. changePrimSkill(hero2, PrimarySkill::EXPERIENCE, battleResult.data->exp[1]);
  611. queries.popIfTop(battleQuery);
  612. //--> continuation (battleAfterLevelUp) occurs after level-up queries are handled or on removing query (above)
  613. }
  614. void CGameHandler::battleAfterLevelUp( const BattleResult &result )
  615. {
  616. LOG_TRACE(logGlobal);
  617. finishingBattle->remainingBattleQueriesCount--;
  618. logGlobal->traceStream() << "Decremented queries count to " << finishingBattle->remainingBattleQueriesCount;
  619. if(finishingBattle->remainingBattleQueriesCount > 0)
  620. //Battle results will be handled when all battle queries are closed
  621. return;
  622. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  623. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  624. // Still, it looks like a hole.
  625. // Necromancy if applicable.
  626. const CStackBasicDescriptor raisedStack = finishingBattle->winnerHero ? finishingBattle->winnerHero->calculateNecromancy(*battleResult.data) : CStackBasicDescriptor();
  627. // Give raised units to winner and show dialog, if any were raised,
  628. // units will be given after casualties are taken
  629. const SlotID necroSlot = raisedStack.type ? finishingBattle->winnerHero->getSlotFor(raisedStack.type) : SlotID();
  630. if (necroSlot != SlotID())
  631. {
  632. finishingBattle->winnerHero->showNecromancyDialog(raisedStack);
  633. addToSlot(StackLocation(finishingBattle->winnerHero, necroSlot), raisedStack.type, raisedStack.count);
  634. }
  635. BattleResultsApplied resultsApplied;
  636. resultsApplied.player1 = finishingBattle->victor;
  637. resultsApplied.player2 = finishingBattle->loser;
  638. sendAndApply(&resultsApplied);
  639. setBattle(nullptr);
  640. if(visitObjectAfterVictory && result.winner==0 && !finishingBattle->winnerHero->stacks.empty())
  641. {
  642. logGlobal->traceStream() << "post-victory visit";
  643. visitObjectOnTile(*getTile(finishingBattle->winnerHero->getPosition()), finishingBattle->winnerHero);
  644. }
  645. visitObjectAfterVictory = false;
  646. //handle victory/loss of engaged players
  647. std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
  648. checkVictoryLossConditions(playerColors);
  649. if(result.result == BattleResult::SURRENDER || result.result == BattleResult::ESCAPE) //loser has escaped or surrendered
  650. {
  651. SetAvailableHeroes sah;
  652. sah.player = finishingBattle->loser;
  653. sah.hid[0] = finishingBattle->loserHero->subID;
  654. if(result.result == BattleResult::ESCAPE) //retreat
  655. {
  656. sah.army[0].clear();
  657. sah.army[0].setCreature(SlotID(0), finishingBattle->loserHero->type->initialArmy.at(0).creature, 1);
  658. }
  659. if(const CGHeroInstance *another = getPlayer(finishingBattle->loser)->availableHeroes.at(0))
  660. sah.hid[1] = another->subID;
  661. else
  662. sah.hid[1] = -1;
  663. sendAndApply(&sah);
  664. }
  665. if(result.winner != 2 && finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty())
  666. {
  667. RemoveObject ro(finishingBattle->winnerHero->id);
  668. sendAndApply(&ro);
  669. if (VLC->modh->settings.WINNING_HERO_WITH_NO_TROOPS_RETREATS)
  670. {
  671. SetAvailableHeroes sah;
  672. sah.player = finishingBattle->victor;
  673. sah.hid[0] = finishingBattle->winnerHero->subID;
  674. sah.army[0].clear();
  675. sah.army[0].setCreature(SlotID(0), finishingBattle->winnerHero->type->initialArmy.at(0).creature, 1);
  676. if(const CGHeroInstance *another = getPlayer(finishingBattle->victor)->availableHeroes.at(0))
  677. sah.hid[1] = another->subID;
  678. else
  679. sah.hid[1] = -1;
  680. sendAndApply(&sah);
  681. }
  682. }
  683. }
  684. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance, int targetHex)
  685. {
  686. bat.bsa.clear();
  687. bat.stackAttacking = att->ID;
  688. const int attackerLuck = att->LuckVal();
  689. auto sideHeroBlocksLuck = [](const SideInBattle &side){ return NBonus::hasOfType(side.hero, Bonus::BLOCK_LUCK); };
  690. if(!vstd::contains_if(gs->curB->sides, sideHeroBlocksLuck))
  691. {
  692. if(attackerLuck > 0 && gs->getRandomGenerator().nextInt(23) < attackerLuck)
  693. {
  694. bat.flags |= BattleAttack::LUCKY;
  695. }
  696. if (VLC->modh->settings.data["hardcodedFeatures"]["NEGATIVE_LUCK"].Bool()) // negative luck enabled
  697. {
  698. if (attackerLuck < 0 && gs->getRandomGenerator().nextInt(23) < abs(attackerLuck))
  699. {
  700. bat.flags |= BattleAttack::UNLUCKY;
  701. }
  702. }
  703. }
  704. if(gs->getRandomGenerator().nextInt(99) < att->valOfBonuses(Bonus::DOUBLE_DAMAGE_CHANCE))
  705. {
  706. bat.flags |= BattleAttack::DEATH_BLOW;
  707. }
  708. if(att->getCreature()->idNumber == CreatureID::BALLISTA)
  709. {
  710. static const int artilleryLvlToChance[] = {0, 50, 75, 100};
  711. const CGHeroInstance * owner = gs->curB->getHero(att->owner);
  712. int chance = artilleryLvlToChance[owner->getSecSkillLevel(SecondarySkill::ARTILLERY)];
  713. if(chance > gs->getRandomGenerator().nextInt(99))
  714. {
  715. bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
  716. }
  717. }
  718. // only primary target
  719. applyBattleEffects(bat, att, def, distance, false);
  720. if (!bat.shot()) //multiple-hex attack - only in meele
  721. {
  722. std::set<const CStack*> attackedCreatures = gs->curB->getAttackedCreatures(att, targetHex); //creatures other than primary target
  723. for(const CStack * stack : attackedCreatures)
  724. {
  725. if (stack != def) //do not hit same stack twice
  726. {
  727. applyBattleEffects(bat, att, stack, distance, true);
  728. }
  729. }
  730. }
  731. const Bonus * bonus = att->getBonusLocalFirst(Selector::type(Bonus::SPELL_LIKE_ATTACK));
  732. if (bonus && (bat.shot())) //TODO: make it work in melee?
  733. {
  734. //this is need for displaying hit animation
  735. bat.flags |= BattleAttack::SPELL_LIKE;
  736. bat.spellID = SpellID(bonus->subtype);
  737. //TODO: should spell override creature`s projectile?
  738. std::set<const CStack*> attackedCreatures = SpellID(bonus->subtype).toSpell()->getAffectedStacks(gs->curB, ECastingMode::SPELL_LIKE_ATTACK, att->owner, bonus->val, targetHex, att);
  739. //TODO: get exact attacked hex for defender
  740. for(const CStack * stack : attackedCreatures)
  741. {
  742. if (stack != def) //do not hit same stack twice
  743. {
  744. applyBattleEffects(bat, att, stack, distance, true);
  745. }
  746. }
  747. //now add effect info for all attacked stacks
  748. for(BattleStackAttacked & bsa : bat.bsa)
  749. {
  750. if(bsa.attackerID == att->ID) //this is our attack and not f.e. fire shield
  751. {
  752. //this is need for displaying affect animation
  753. bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
  754. bsa.spellID = SpellID(bonus->subtype);
  755. }
  756. }
  757. }
  758. }
  759. void CGameHandler::applyBattleEffects(BattleAttack &bat, const CStack *att, const CStack *def, int distance, bool secondary) //helper function for prepareAttack
  760. {
  761. BattleStackAttacked bsa;
  762. if (secondary)
  763. bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
  764. bsa.attackerID = att->ID;
  765. bsa.stackAttacked = def->ID;
  766. bsa.damageAmount = gs->curB->calculateDmg(att, def, gs->curB->battleGetOwner(att), gs->curB->battleGetOwner(def),
  767. bat.shot(), distance, bat.lucky(), bat.unlucky(), bat.deathBlow(), bat.ballistaDoubleDmg(), gs->getRandomGenerator());
  768. def->prepareAttacked(bsa, gs->getRandomGenerator()); //calculate casualties
  769. //life drain handling
  770. if (att->hasBonusOfType(Bonus::LIFE_DRAIN) && def->isLiving())
  771. {
  772. StacksHealedOrResurrected shi;
  773. shi.lifeDrain = true;
  774. shi.tentHealing = false;
  775. shi.drainedFrom = def->ID;
  776. StacksHealedOrResurrected::HealInfo hi;
  777. hi.stackID = att->ID;
  778. hi.healedHP = att->calculateHealedHealthPoints(bsa.damageAmount * att->valOfBonuses (Bonus::LIFE_DRAIN) / 100, true);
  779. hi.lowLevelResurrection = false;
  780. shi.healedStacks.push_back(hi);
  781. if (hi.healedHP > 0)
  782. {
  783. bsa.healedStacks.push_back(shi);
  784. }
  785. }
  786. bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
  787. //fire shield handling
  788. if(!bat.shot() && def->hasBonusOfType(Bonus::FIRE_SHIELD) && !att->hasBonusOfType (Bonus::FIRE_IMMUNITY))
  789. {
  790. BattleStackAttacked bsa2;
  791. bsa2.stackAttacked = att->ID; //invert
  792. bsa2.attackerID = def->ID;
  793. bsa2.flags |= BattleStackAttacked::EFFECT; //FIXME: play animation upon efreet and not attacker
  794. bsa2.effect = 11;
  795. bsa2.damageAmount = (bsa.damageAmount * def->valOfBonuses(Bonus::FIRE_SHIELD)) / 100; //TODO: scale with attack/defense
  796. att->prepareAttacked(bsa2, gameState()->getRandomGenerator());
  797. bat.bsa.push_back(bsa2);
  798. }
  799. }
  800. void CGameHandler::handleConnection(std::set<PlayerColor> players, CConnection &c)
  801. {
  802. setThreadName("CGameHandler::handleConnection");
  803. try
  804. {
  805. while(1)//server should never shut connection first //was: while(!end2)
  806. {
  807. CPack *pack = nullptr;
  808. PlayerColor player = PlayerColor::NEUTRAL;
  809. si32 requestID = -999;
  810. int packType = 0;
  811. {
  812. boost::unique_lock<boost::mutex> lock(*c.rmx);
  813. c >> player >> requestID >> pack; //get the package
  814. if(!pack)
  815. {
  816. logGlobal ->errorStream() << boost::format("Received a null package marked as request %d from player %d") % requestID % player;
  817. }
  818. packType = typeList.getTypeID(pack); //get the id of type
  819. logGlobal->traceStream() << boost::format("Received client message (request %d by player %d) of type with ID=%d (%s).\n")
  820. % requestID % player.getNum() % packType % typeid(*pack).name();
  821. }
  822. //prepare struct informing that action was applied
  823. auto sendPackageResponse = [&](bool succesfullyApplied)
  824. {
  825. PackageApplied applied;
  826. applied.player = player;
  827. applied.result = succesfullyApplied;
  828. applied.packType = packType;
  829. applied.requestID = requestID;
  830. boost::unique_lock<boost::mutex> lock(*c.wmx);
  831. c << &applied;
  832. };
  833. CBaseForGHApply *apply = applier->apps[packType]; //and appropriate applier object
  834. if(isBlockedByQueries(pack, player))
  835. {
  836. sendPackageResponse(false);
  837. }
  838. else if(apply)
  839. {
  840. const bool result = apply->applyOnGH(this,&c,pack, player);
  841. if(!result)
  842. {
  843. complain((boost::format("Got false in applying %s... that request must have been fishy!")
  844. % typeid(*pack).name()).str());
  845. }
  846. logGlobal->traceStream() << "Message successfully applied (result=" << result << ")!";
  847. sendPackageResponse(true);
  848. }
  849. else
  850. {
  851. logGlobal->errorStream() << "Message cannot be applied, cannot find applier (unregistered type)!";
  852. sendPackageResponse(false);
  853. }
  854. vstd::clear_pointer(pack);
  855. }
  856. }
  857. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  858. {
  859. assert(!c.connected); //make sure that connection has been marked as broken
  860. logGlobal->errorStream() << e.what();
  861. end2 = true;
  862. }
  863. catch(...)
  864. {
  865. end2 = true;
  866. handleException();
  867. throw;
  868. }
  869. logGlobal->errorStream() << "Ended handling connection";
  870. }
  871. int CGameHandler::moveStack(int stack, BattleHex dest)
  872. {
  873. int ret = 0;
  874. const CStack *curStack = gs->curB->battleGetStackByID(stack),
  875. *stackAtEnd = gs->curB->battleGetStackByPos(dest);
  876. assert(curStack);
  877. assert(dest < GameConstants::BFIELD_SIZE);
  878. if (gs->curB->tacticDistance)
  879. {
  880. assert(gs->curB->isInTacticRange(dest));
  881. }
  882. if(curStack->position == dest)
  883. return 0;
  884. //initing necessary tables
  885. auto accessibility = getAccesibility(curStack);
  886. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  887. if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
  888. {
  889. if(curStack->attackerOwned)
  890. {
  891. if(accessibility.accessible(dest+1, curStack))
  892. dest += BattleHex::RIGHT;
  893. }
  894. else
  895. {
  896. if(accessibility.accessible(dest-1, curStack))
  897. dest += BattleHex::LEFT;
  898. }
  899. }
  900. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
  901. {
  902. complain("Given destination is not accessible!");
  903. return 0;
  904. }
  905. std::pair< std::vector<BattleHex>, int > path = gs->curB->getPath(curStack->position, dest, curStack);
  906. ret = path.second;
  907. int creSpeed = gs->curB->tacticDistance ? GameConstants::BFIELD_SIZE : curStack->Speed();
  908. if(curStack->hasBonusOfType(Bonus::FLYING))
  909. {
  910. if(path.second <= creSpeed && path.first.size() > 0)
  911. {
  912. //inform clients about move
  913. BattleStackMoved sm;
  914. sm.stack = curStack->ID;
  915. std::vector<BattleHex> tiles;
  916. tiles.push_back(path.first[0]);
  917. sm.tilesToMove = tiles;
  918. sm.distance = path.second;
  919. sm.teleporting = false;
  920. sendAndApply(&sm);
  921. }
  922. }
  923. else //for non-flying creatures
  924. {
  925. std::shared_ptr<const CObstacleInstance> obstacle, obstacle2; //obstacle that interrupted movement
  926. std::vector<BattleHex> tiles;
  927. const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0);
  928. int v = path.first.size()-1;
  929. // check if gate need to be open or closed at some point
  930. BattleHex openGateAtHex, gateMayCloseAtHex;
  931. auto dbState = gs->curB->si.drawbridgeState;
  932. if(battleGetSiegeLevel() > 0 && dbState != EDrawbridgeState::LOWERED_BORKED &&
  933. dbState != EDrawbridgeState::RAISED_BLOCKED)
  934. {
  935. for(int i = path.first.size()-1; i >= 0; i--)
  936. {
  937. auto hex = path.first[i];
  938. if(!openGateAtHex.isValid() && dbState != EDrawbridgeState::LOWERED)
  939. {
  940. if(gs->curB->town->subID == ETownType::FORTRESS)
  941. {
  942. if(hex == BattleHex(93) &&
  943. i-1 >= 0 && path.first[i-1] == BattleHex(94))
  944. {
  945. openGateAtHex = path.first[i+1];
  946. }
  947. }
  948. if(hex == BattleHex(94) && i-1 >= 0 && path.first[i-1] == BattleHex(95))
  949. {
  950. openGateAtHex = path.first[i+1];
  951. }
  952. else if(hex == BattleHex(95) || hex == BattleHex(96))
  953. {
  954. openGateAtHex = path.first[i+1];
  955. }
  956. if(openGateAtHex.isValid())
  957. dbState = EDrawbridgeState::LOWERED;
  958. }
  959. if(!gateMayCloseAtHex.isValid() && dbState != EDrawbridgeState::RAISED)
  960. {
  961. if(hex == BattleHex(96) && i-1 >= 0 && path.first[i-1] != BattleHex(95))
  962. {
  963. gateMayCloseAtHex = path.first[i-1];
  964. }
  965. if(gs->curB->town->subID == ETownType::FORTRESS)
  966. {
  967. if(hex == BattleHex(94) && i-1 >= 0 && path.first[i-1] != BattleHex(95))
  968. {
  969. gateMayCloseAtHex = path.first[i-1];
  970. }
  971. else if(hex == BattleHex(95) && i-1 >= 0 &&
  972. path.first[i-1] != BattleHex(96) &&
  973. path.first[i-1] != BattleHex(94))
  974. {
  975. gateMayCloseAtHex = path.first[i-1];
  976. }
  977. }
  978. else if(hex == BattleHex(95) && i-1 >= 0 && path.first[i-1] != BattleHex(96))
  979. {
  980. gateMayCloseAtHex = path.first[i-1];
  981. }
  982. }
  983. }
  984. }
  985. bool stackIsMoving = true;
  986. while(stackIsMoving)
  987. {
  988. if(v<tilesToMove)
  989. {
  990. logGlobal->error("Movement terminated abnormally");
  991. break;
  992. }
  993. bool gateStateChanging = false;
  994. for(bool obstacleHit = false; (!obstacleHit) && (!gateStateChanging) && (v >= tilesToMove); --v)
  995. {
  996. BattleHex hex = path.first[v];
  997. tiles.push_back(hex);
  998. if((openGateAtHex.isValid() && openGateAtHex == hex) ||
  999. (gateMayCloseAtHex.isValid() && gateMayCloseAtHex == hex))
  1000. {
  1001. gateStateChanging = true;
  1002. }
  1003. //if we walked onto something, finalize this portion of stack movement check into obstacle
  1004. if((obstacle = battleGetObstacleOnPos(hex, false)))
  1005. obstacleHit = true;
  1006. if(curStack->doubleWide())
  1007. {
  1008. BattleHex otherHex = curStack->occupiedHex(hex);
  1009. //two hex creature hit obstacle by backside
  1010. if(otherHex.isValid() && ((obstacle2 = battleGetObstacleOnPos(otherHex, false))))
  1011. obstacleHit = true;
  1012. }
  1013. }
  1014. if(tiles.size() > 0)
  1015. {
  1016. //commit movement
  1017. BattleStackMoved sm;
  1018. sm.stack = curStack->ID;
  1019. sm.distance = path.second;
  1020. sm.teleporting = false;
  1021. sm.tilesToMove = tiles;
  1022. sendAndApply(&sm);
  1023. tiles.clear();
  1024. }
  1025. //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end
  1026. if(curStack->position != dest)
  1027. {
  1028. auto processObstacle = [&](std::shared_ptr<const CObstacleInstance> & obs)
  1029. {
  1030. if(obs)
  1031. {
  1032. handleDamageFromObstacle(*obs, curStack);
  1033. //if stack die in explosion or interrupted by obstacle, abort movement
  1034. if(obs->stopsMovement() || !curStack->alive())
  1035. stackIsMoving = false;
  1036. obs.reset();
  1037. }
  1038. };
  1039. processObstacle(obstacle);
  1040. if(curStack->alive())
  1041. processObstacle(obstacle2);
  1042. if(curStack->alive() && gateStateChanging)
  1043. {
  1044. if(curStack->position == openGateAtHex)
  1045. {
  1046. BattleDrawbridgeStateChanged db;
  1047. db.state = EDrawbridgeState::LOWERED;
  1048. sendAndApply(&db);
  1049. }
  1050. else
  1051. updateDrawbridgeState();
  1052. }
  1053. }
  1054. else
  1055. //movement finished normally: we reached destination
  1056. stackIsMoving = false;
  1057. }
  1058. }
  1059. //handling obstacle on the final field (separate, because it affects both flying and walking stacks)
  1060. if(curStack->alive())
  1061. {
  1062. if(auto theLastObstacle = battleGetObstacleOnPos(curStack->position, false))
  1063. {
  1064. handleDamageFromObstacle(*theLastObstacle, curStack);
  1065. }
  1066. }
  1067. if(curStack->alive() && curStack->doubleWide())
  1068. {
  1069. BattleHex otherHex = curStack->occupiedHex(curStack->position);
  1070. if(otherHex.isValid())
  1071. if(auto theLastObstacle = battleGetObstacleOnPos(otherHex, false))
  1072. {
  1073. //two hex creature hit obstacle by backside
  1074. handleDamageFromObstacle(*theLastObstacle, curStack);
  1075. }
  1076. }
  1077. updateDrawbridgeState();
  1078. return ret;
  1079. }
  1080. CGameHandler::CGameHandler(void)
  1081. {
  1082. QID = 1;
  1083. //gs = nullptr;
  1084. IObjectInterface::cb = this;
  1085. applier = new CApplier<CBaseForGHApply>;
  1086. registerTypesServerPacks(*applier);
  1087. visitObjectAfterVictory = false;
  1088. queries.gh = this;
  1089. spellEnv = new ServerSpellCastEnvironment(this);
  1090. }
  1091. CGameHandler::~CGameHandler(void)
  1092. {
  1093. delete spellEnv;
  1094. delete applier;
  1095. applier = nullptr;
  1096. delete gs;
  1097. }
  1098. void CGameHandler::init(StartInfo *si)
  1099. {
  1100. if(si->seedToBeUsed == 0)
  1101. {
  1102. si->seedToBeUsed = std::time(nullptr);
  1103. }
  1104. gs = new CGameState();
  1105. logGlobal->infoStream() << "Gamestate created!";
  1106. gs->init(si);
  1107. logGlobal->infoStream() << "Gamestate initialized!";
  1108. // reset seed, so that clients can't predict any following random values
  1109. gs->getRandomGenerator().resetSeed();
  1110. for(auto & elem : gs->players)
  1111. {
  1112. states.addPlayer(elem.first);
  1113. }
  1114. }
  1115. static bool evntCmp(const CMapEvent &a, const CMapEvent &b)
  1116. {
  1117. return a.earlierThan(b);
  1118. }
  1119. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false, bool clear = false)
  1120. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  1121. const PlayerState *p = gs->getPlayer(town->tempOwner);
  1122. if(!p)
  1123. {
  1124. logGlobal->warnStream() << "There is no player owner of town " << town->name << " at " << town->pos;
  1125. return;
  1126. }
  1127. if (forced || town->creatures.at(GameConstants::CREATURES_PER_TOWN).second.empty())//we need to change creature
  1128. {
  1129. SetAvailableCreatures ssi;
  1130. ssi.tid = town->id;
  1131. ssi.creatures = town->creatures;
  1132. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.clear();//remove old one
  1133. const std::vector<ConstTransitivePtr<CGDwelling> > &dwellings = p->dwellings;
  1134. if (dwellings.empty())//no dwellings - just remove
  1135. {
  1136. sendAndApply(&ssi);
  1137. return;
  1138. }
  1139. auto dwelling = *RandomGeneratorUtil::nextItem(dwellings, gs->getRandomGenerator());
  1140. // for multi-creature dwellings like Golem Factory
  1141. auto creatureId = RandomGeneratorUtil::nextItem(dwelling->creatures, gs->getRandomGenerator())->second[0];
  1142. if(clear)
  1143. {
  1144. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = std::max((ui32)1, (VLC->creh->creatures.at(creatureId)->growth)/2);
  1145. }
  1146. else
  1147. {
  1148. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = VLC->creh->creatures.at(creatureId)->growth;
  1149. }
  1150. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.push_back(creatureId);
  1151. sendAndApply(&ssi);
  1152. }
  1153. }
  1154. void CGameHandler::newTurn()
  1155. {
  1156. logGlobal->traceStream() << "Turn " << gs->day+1;
  1157. NewTurn n;
  1158. n.specialWeek = NewTurn::NO_ACTION;
  1159. n.creatureid = CreatureID::NONE;
  1160. n.day = gs->day + 1;
  1161. bool firstTurn = !getDate(Date::DAY);
  1162. bool newWeek = getDate(Date::DAY_OF_WEEK) == 7; //day numbers are confusing, as day was not yet switched
  1163. bool newMonth = getDate(Date::DAY_OF_MONTH) == 28;
  1164. std::map<PlayerColor, si32> hadGold;//starting gold - for buildings like dwarven treasury
  1165. if (firstTurn)
  1166. {
  1167. for (auto obj : gs->map->objects)
  1168. {
  1169. if (obj && obj->ID == Obj::PRISON) //give imprisoned hero 0 exp to level him up. easiest to do at this point
  1170. {
  1171. changePrimSkill (getHero(obj->id), PrimarySkill::EXPERIENCE, 0);
  1172. }
  1173. }
  1174. }
  1175. if (newWeek && !firstTurn)
  1176. {
  1177. n.specialWeek = NewTurn::NORMAL;
  1178. bool deityOfFireBuilt = false;
  1179. for(const CGTownInstance *t : gs->map->towns)
  1180. {
  1181. if(t->hasBuilt(BuildingID::GRAIL, ETownType::INFERNO))
  1182. {
  1183. deityOfFireBuilt = true;
  1184. break;
  1185. }
  1186. }
  1187. if(deityOfFireBuilt)
  1188. {
  1189. n.specialWeek = NewTurn::DEITYOFFIRE;
  1190. n.creatureid = CreatureID::IMP;
  1191. }
  1192. else
  1193. {
  1194. int monthType = gs->getRandomGenerator().nextInt(99);
  1195. if(newMonth) //new month
  1196. {
  1197. if (monthType < 40) //double growth
  1198. {
  1199. n.specialWeek = NewTurn::DOUBLE_GROWTH;
  1200. if (VLC->modh->settings.ALL_CREATURES_GET_DOUBLE_MONTHS)
  1201. {
  1202. std::pair<int, CreatureID> newMonster(54, VLC->creh->pickRandomMonster(gs->getRandomGenerator()));
  1203. n.creatureid = newMonster.second;
  1204. }
  1205. else if(VLC->creh->doubledCreatures.size())
  1206. {
  1207. const std::vector<CreatureID> doubledCreatures (VLC->creh->doubledCreatures.begin(), VLC->creh->doubledCreatures.end());
  1208. n.creatureid = *RandomGeneratorUtil::nextItem(doubledCreatures, gs->getRandomGenerator());
  1209. }
  1210. else
  1211. {
  1212. complain("Cannot find creature that can be spawned!");
  1213. n.specialWeek = NewTurn::NORMAL;
  1214. }
  1215. }
  1216. else if (monthType < 50)
  1217. n.specialWeek = NewTurn::PLAGUE;
  1218. }
  1219. else //it's a week, but not full month
  1220. {
  1221. if (monthType < 25)
  1222. {
  1223. n.specialWeek = NewTurn::BONUS_GROWTH; //+5
  1224. std::pair<int, CreatureID> newMonster(54, VLC->creh->pickRandomMonster(gs->getRandomGenerator()));
  1225. //TODO do not pick neutrals
  1226. n.creatureid = newMonster.second;
  1227. }
  1228. }
  1229. }
  1230. }
  1231. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = gs->hpool.heroesPool;
  1232. for (auto & elem : gs->players)
  1233. {
  1234. if(elem.first == PlayerColor::NEUTRAL)
  1235. continue;
  1236. else if(elem.first >= PlayerColor::PLAYER_LIMIT)
  1237. assert(0); //illegal player number!
  1238. std::pair<PlayerColor, si32> playerGold(elem.first, elem.second.resources.at(Res::GOLD));
  1239. hadGold.insert(playerGold);
  1240. if(newWeek) //new heroes in tavern
  1241. {
  1242. SetAvailableHeroes sah;
  1243. sah.player = elem.first;
  1244. //pick heroes and their armies
  1245. CHeroClass *banned = nullptr;
  1246. for (int j = 0; j < GameConstants::AVAILABLE_HEROES_PER_PLAYER; j++)
  1247. {
  1248. //first hero - native if possible, second hero -> any other class
  1249. if(CGHeroInstance *h = gs->hpool.pickHeroFor(j == 0, elem.first, getNativeTown(elem.first), pool, gs->getRandomGenerator(), banned))
  1250. {
  1251. sah.hid[j] = h->subID;
  1252. h->initArmy(&sah.army[j]);
  1253. banned = h->type->heroClass;
  1254. }
  1255. else
  1256. sah.hid[j] = -1;
  1257. }
  1258. sendAndApply(&sah);
  1259. }
  1260. n.res[elem.first] = elem.second.resources;
  1261. for(CGHeroInstance *h : (elem).second.heroes)
  1262. {
  1263. if(h->visitedTown)
  1264. giveSpells(h->visitedTown, h);
  1265. NewTurn::Hero hth;
  1266. hth.id = h->id;
  1267. // TODO: this code executed when bonuses of previous day not yet updated (this happen in NewTurn::applyGs). See issue 2356
  1268. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).terType != ETerrainType::WATER, new TurnInfo(h, 1));
  1269. if(h->visitedTown && h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1)) //if hero starts turn in town with mage guild
  1270. hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
  1271. else
  1272. hth.mana = std::max((si32)(0), std::max(h->mana, std::min((si32)(h->mana + h->manaRegain()), h->manaLimit())));
  1273. n.heroes.insert(hth);
  1274. if(!firstTurn) //not first day
  1275. {
  1276. n.res[elem.first][Res::GOLD] += h->valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ESTATES)); //estates
  1277. for (int k = 0; k < GameConstants::RESOURCE_QUANTITY; k++)
  1278. {
  1279. n.res[elem.first][k] += h->valOfBonuses(Bonus::GENERATE_RESOURCE, k);
  1280. }
  1281. }
  1282. }
  1283. }
  1284. for(CGTownInstance *t : gs->map->towns)
  1285. {
  1286. PlayerColor player = t->tempOwner;
  1287. handleTownEvents(t, n);
  1288. if(newWeek) //first day of week
  1289. {
  1290. if(t->hasBuilt(BuildingID::PORTAL_OF_SUMMON, ETownType::DUNGEON))
  1291. setPortalDwelling(t, true, (n.specialWeek == NewTurn::PLAGUE ? true : false)); //set creatures for Portal of Summoning
  1292. if(!firstTurn)
  1293. if (t->hasBuilt(BuildingID::TREASURY, ETownType::RAMPART) && player < PlayerColor::PLAYER_LIMIT)
  1294. n.res[player][Res::GOLD] += hadGold.at(player)/10; //give 10% of starting gold
  1295. if (!vstd::contains(n.cres, t->id))
  1296. {
  1297. n.cres[t->id].tid = t->id;
  1298. n.cres[t->id].creatures = t->creatures;
  1299. }
  1300. auto & sac = n.cres.at(t->id);
  1301. for (int k=0; k < GameConstants::CREATURES_PER_TOWN; k++) //creature growths
  1302. {
  1303. if (!t->creatures.at(k).second.empty()) // there are creatures at this level
  1304. {
  1305. ui32 &availableCount = sac.creatures.at(k).first;
  1306. const CCreature *cre = VLC->creh->creatures.at(t->creatures.at(k).second.back());
  1307. if (n.specialWeek == NewTurn::PLAGUE)
  1308. availableCount = t->creatures.at(k).first / 2; //halve their number, no growth
  1309. else
  1310. {
  1311. if(firstTurn) //first day of game: use only basic growths
  1312. availableCount = cre->growth;
  1313. else
  1314. availableCount += t->creatureGrowth(k);
  1315. //Deity of fire week - upgrade both imps and upgrades
  1316. if (n.specialWeek == NewTurn::DEITYOFFIRE && vstd::contains(t->creatures.at(k).second, n.creatureid))
  1317. availableCount += 15;
  1318. if( cre->idNumber == n.creatureid ) //bonus week, effect applies only to identical creatures
  1319. {
  1320. if(n.specialWeek == NewTurn::DOUBLE_GROWTH)
  1321. availableCount *= 2;
  1322. else if(n.specialWeek == NewTurn::BONUS_GROWTH)
  1323. availableCount += 5;
  1324. }
  1325. }
  1326. }
  1327. }
  1328. }
  1329. if(!firstTurn && player < PlayerColor::PLAYER_LIMIT)//not the first day and town not neutral
  1330. {
  1331. n.res[player] = n.res[player] + t->dailyIncome();
  1332. }
  1333. if(t->hasBuilt(BuildingID::GRAIL, ETownType::TOWER))
  1334. {
  1335. // Skyship, probably easier to handle same as Veil of darkness
  1336. //do it every new day after veils apply
  1337. if (player != PlayerColor::NEUTRAL) //do not reveal fow for neutral player
  1338. {
  1339. FoWChange fw;
  1340. fw.mode = 1;
  1341. fw.player = player;
  1342. // find all hidden tiles
  1343. const auto & fow = gs->getPlayerTeam(player)->fogOfWarMap;
  1344. for (size_t i=0; i<fow.size(); i++)
  1345. for (size_t j=0; j<fow.at(i).size(); j++)
  1346. for (size_t k=0; k<fow.at(i).at(j).size(); k++)
  1347. if (!fow.at(i).at(j).at(k))
  1348. fw.tiles.insert(int3(i,j,k));
  1349. sendAndApply (&fw);
  1350. }
  1351. }
  1352. if (t->hasBonusOfType (Bonus::DARKNESS))
  1353. {
  1354. for (auto & player : gameState()->players)
  1355. {
  1356. if (getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  1357. getPlayerRelations(player.first, t->tempOwner) == PlayerRelations::ENEMIES)
  1358. changeFogOfWar(t->visitablePos(), t->getBonusLocalFirst(Selector::type(Bonus::DARKNESS))->val, player.first, true);
  1359. }
  1360. }
  1361. }
  1362. if(newMonth)
  1363. {
  1364. SetAvailableArtifacts saa;
  1365. saa.id = -1;
  1366. pickAllowedArtsSet(saa.arts);
  1367. sendAndApply(&saa);
  1368. }
  1369. sendAndApply(&n);
  1370. if(newWeek)
  1371. {
  1372. //spawn wandering monsters
  1373. if (newMonth && (n.specialWeek == NewTurn::DOUBLE_GROWTH || n.specialWeek == NewTurn::DEITYOFFIRE))
  1374. {
  1375. spawnWanderingMonsters(n.creatureid);
  1376. }
  1377. //new week info popup
  1378. if(!firstTurn)
  1379. {
  1380. InfoWindow iw;
  1381. switch (n.specialWeek)
  1382. {
  1383. case NewTurn::DOUBLE_GROWTH:
  1384. iw.text.addTxt(MetaString::ARRAY_TXT, 131);
  1385. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  1386. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  1387. break;
  1388. case NewTurn::PLAGUE:
  1389. iw.text.addTxt(MetaString::ARRAY_TXT, 132);
  1390. break;
  1391. case NewTurn::BONUS_GROWTH:
  1392. iw.text.addTxt(MetaString::ARRAY_TXT, 134);
  1393. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  1394. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  1395. break;
  1396. case NewTurn::DEITYOFFIRE:
  1397. iw.text.addTxt(MetaString::ARRAY_TXT, 135);
  1398. iw.text.addReplacement(MetaString::CRE_SING_NAMES, 42); //%s imp
  1399. iw.text.addReplacement(MetaString::CRE_SING_NAMES, 42); //%s imp
  1400. iw.text.addReplacement2(15); //%+d 15
  1401. iw.text.addReplacement(MetaString::CRE_SING_NAMES, 43); //%s familiar
  1402. iw.text.addReplacement2(15); //%+d 15
  1403. break;
  1404. default:
  1405. if (newMonth)
  1406. {
  1407. iw.text.addTxt(MetaString::ARRAY_TXT, (130));
  1408. iw.text.addReplacement(MetaString::ARRAY_TXT, gs->getRandomGenerator().nextInt(32, 41));
  1409. }
  1410. else
  1411. {
  1412. iw.text.addTxt(MetaString::ARRAY_TXT, (133));
  1413. iw.text.addReplacement(MetaString::ARRAY_TXT, gs->getRandomGenerator().nextInt(43, 57));
  1414. }
  1415. }
  1416. for (auto & elem : gs->players)
  1417. {
  1418. iw.player = elem.first;
  1419. sendAndApply(&iw);
  1420. }
  1421. }
  1422. }
  1423. logGlobal->traceStream() << "Info about turn " << n.day << "has been sent!";
  1424. handleTimeEvents();
  1425. //call objects
  1426. for(auto & elem : gs->map->objects)
  1427. {
  1428. if(elem)
  1429. elem->newTurn();
  1430. }
  1431. //count days without town for all players, regardless of their turn order
  1432. for (auto &p : gs->players)
  1433. {
  1434. PlayerState & playerState = p.second;
  1435. if (playerState.status == EPlayerStatus::INGAME)
  1436. {
  1437. if (playerState.towns.empty())
  1438. {
  1439. if (playerState.daysWithoutCastle)
  1440. ++(*playerState.daysWithoutCastle);
  1441. else playerState.daysWithoutCastle = 0;
  1442. }
  1443. else
  1444. {
  1445. playerState.daysWithoutCastle = boost::none;
  1446. }
  1447. }
  1448. }
  1449. synchronizeArtifactHandlerLists(); //new day events may have changed them. TODO better of managing that
  1450. }
  1451. void CGameHandler::run(bool resume)
  1452. {
  1453. LOG_TRACE_PARAMS(logGlobal, "resume=%d", resume);
  1454. using namespace boost::posix_time;
  1455. for(CConnection *cc : conns)
  1456. {
  1457. if(!resume)
  1458. {
  1459. (*cc) << gs->initialOpts; // gs->scenarioOps
  1460. }
  1461. std::set<PlayerColor> players;
  1462. (*cc) >> players; //how many players will be handled at that client
  1463. std::stringstream sbuffer;
  1464. sbuffer << "Connection " << cc->connectionID << " will handle " << players.size() << " player: ";
  1465. for(PlayerColor color : players)
  1466. {
  1467. sbuffer << color << " ";
  1468. {
  1469. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1470. connections[color] = cc;
  1471. }
  1472. }
  1473. logGlobal->infoStream() << sbuffer.str();
  1474. cc->addStdVecItems(gs);
  1475. cc->enableStackSendingByID();
  1476. cc->disableSmartPointerSerialization();
  1477. }
  1478. for(auto & elem : conns)
  1479. {
  1480. std::set<PlayerColor> pom;
  1481. for(auto j = connections.cbegin(); j!=connections.cend();j++)
  1482. if(j->second == elem)
  1483. pom.insert(j->first);
  1484. boost::thread(std::bind(&CGameHandler::handleConnection,this,pom,std::ref(*elem)));
  1485. }
  1486. if(gs->scenarioOps->mode == StartInfo::DUEL)
  1487. {
  1488. runBattle();
  1489. end2 = true;
  1490. while(conns.size() && (*conns.begin())->isOpen())
  1491. boost::this_thread::sleep(boost::posix_time::milliseconds(5)); //give time client to close socket
  1492. return;
  1493. }
  1494. auto playerTurnOrder = generatePlayerTurnOrder();
  1495. while(!end2)
  1496. {
  1497. if(!resume) newTurn();
  1498. std::list<PlayerColor>::iterator it;
  1499. if(resume)
  1500. {
  1501. it = std::find(playerTurnOrder.begin(), playerTurnOrder.end(), gs->currentPlayer);
  1502. }
  1503. else
  1504. {
  1505. it = playerTurnOrder.begin();
  1506. }
  1507. resume = false;
  1508. for (; it != playerTurnOrder.end(); it++)
  1509. {
  1510. auto playerColor = *it;
  1511. PlayerState * playerState = &gs->players[playerColor]; //can't copy CBonusSystemNode by value
  1512. if (playerState->status == EPlayerStatus::INGAME)
  1513. {
  1514. //if player runs out of time, he shouldn't get the turn (especially AI)
  1515. checkVictoryLossConditionsForAll();
  1516. if (gs->players[playerColor].status != EPlayerStatus::INGAME)
  1517. { //player lost at the beginning of his turn
  1518. continue;
  1519. }
  1520. else //give normal turn
  1521. {
  1522. states.setFlag(playerColor, &PlayerStatus::makingTurn, true);
  1523. YourTurn yt;
  1524. yt.player = playerColor;
  1525. //Change local daysWithoutCastle counter for local interface message //TODO: needed?
  1526. yt.daysWithoutCastle = playerState->daysWithoutCastle;
  1527. applyAndSend(&yt);
  1528. //wait till turn is done
  1529. boost::unique_lock<boost::mutex> lock(states.mx);
  1530. while (states.players.at(playerColor).makingTurn && !end2)
  1531. {
  1532. static time_duration p = milliseconds(100);
  1533. states.cv.timed_wait(lock, p);
  1534. }
  1535. }
  1536. }
  1537. }
  1538. //additional check that game is not finished
  1539. bool activePlayer = false;
  1540. for(auto player : playerTurnOrder)
  1541. {
  1542. if(gs->players[player].status == EPlayerStatus::INGAME)
  1543. activePlayer = true;
  1544. }
  1545. if(!activePlayer)
  1546. end2 = true;
  1547. }
  1548. while(conns.size() && (*conns.begin())->isOpen())
  1549. boost::this_thread::sleep(boost::posix_time::milliseconds(5)); //give time client to close socket
  1550. }
  1551. std::list<PlayerColor> CGameHandler::generatePlayerTurnOrder() const
  1552. {
  1553. // Generate player turn order
  1554. std::list<PlayerColor> playerTurnOrder;
  1555. for(const auto & player : gs->players) // add human players first
  1556. {
  1557. if(player.second.human)
  1558. playerTurnOrder.push_back(player.first);
  1559. }
  1560. for(const auto & player : gs->players) // then add non-human players
  1561. {
  1562. if(!player.second.human)
  1563. playerTurnOrder.push_back(player.first);
  1564. }
  1565. return playerTurnOrder;
  1566. }
  1567. void CGameHandler::setupBattle( int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town )
  1568. {
  1569. battleResult.set(nullptr);
  1570. //send info about battles
  1571. BattleStart bs;
  1572. bs.info = gs->setupBattle(tile, armies, heroes, creatureBank, town);
  1573. sendAndApply(&bs);
  1574. }
  1575. void CGameHandler::checkForBattleEnd()
  1576. {
  1577. if(auto result = battleIsFinished())
  1578. {
  1579. setBattleResult(BattleResult::NORMAL, *result);
  1580. }
  1581. }
  1582. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1583. {
  1584. if(!h->hasSpellbook())
  1585. return; //hero hasn't spellbook
  1586. ChangeSpells cs;
  1587. cs.hid = h->id;
  1588. cs.learn = true;
  1589. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(SecondarySkill::WISDOM)+2);i++)
  1590. {
  1591. if (t->hasBuilt(BuildingID::GRAIL, ETownType::CONFLUX)) //Aurora Borealis
  1592. {
  1593. std::vector<SpellID> spells;
  1594. getAllowedSpells(spells, i);
  1595. for (auto & spell : spells)
  1596. cs.spells.insert(spell);
  1597. }
  1598. else
  1599. {
  1600. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells.at(i).size(); j++)
  1601. {
  1602. if(!vstd::contains(h->spells,t->spells.at(i).at(j)))
  1603. cs.spells.insert(t->spells.at(i).at(j));
  1604. }
  1605. }
  1606. }
  1607. if(!cs.spells.empty())
  1608. sendAndApply(&cs);
  1609. }
  1610. void CGameHandler::setBlockVis(ObjectInstanceID objid, bool bv)
  1611. {
  1612. SetObjectProperty sop(objid,2,bv);
  1613. sendAndApply(&sop);
  1614. }
  1615. bool CGameHandler::removeObject( const CGObjectInstance * obj )
  1616. {
  1617. if(!obj || !getObj(obj->id))
  1618. {
  1619. logGlobal->errorStream() << "Something wrong, that object already has been removed or hasn't existed!";
  1620. return false;
  1621. }
  1622. RemoveObject ro;
  1623. ro.id = obj->id;
  1624. sendAndApply(&ro);
  1625. checkVictoryLossConditionsForAll(); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1626. return true;
  1627. }
  1628. void CGameHandler::setAmount(ObjectInstanceID objid, ui32 val)
  1629. {
  1630. SetObjectProperty sop(objid,3,val);
  1631. sendAndApply(&sop);
  1632. }
  1633. bool CGameHandler::moveHero( ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit, PlayerColor asker /*= 255*/ )
  1634. {
  1635. const CGHeroInstance *h = getHero(hid);
  1636. if(!h || (asker != PlayerColor::NEUTRAL && (teleporting || h->getOwner() != gs->currentPlayer)) //not turn of that hero or player can't simply teleport hero (at least not with this function)
  1637. )
  1638. {
  1639. logGlobal->errorStream() << "Illegal call to move hero!";
  1640. return false;
  1641. }
  1642. logGlobal->traceStream() << "Player " << asker << " wants to move hero "<< hid.getNum() << " from "<< h->pos << " to " << dst;
  1643. const int3 hmpos = CGHeroInstance::convertPosition(dst, false);
  1644. if(!gs->map->isInTheMap(hmpos))
  1645. {
  1646. logGlobal->errorStream() << "Destination tile is outside the map!";
  1647. return false;
  1648. }
  1649. const TerrainTile t = *gs->getTile(hmpos);
  1650. const int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1651. const bool embarking = !h->boat && !t.visitableObjects.empty() && t.visitableObjects.back()->ID == Obj::BOAT;
  1652. const bool disembarking = h->boat && t.terType != ETerrainType::WATER && !t.blocked;
  1653. //result structure for start - movement failed, no move points used
  1654. TryMoveHero tmh;
  1655. tmh.id = hid;
  1656. tmh.start = h->pos;
  1657. tmh.end = dst;
  1658. tmh.result = TryMoveHero::FAILED;
  1659. tmh.movePoints = h->movement;
  1660. //check if destination tile is available
  1661. auto ti = new TurnInfo(h);
  1662. const bool canFly = ti->hasBonusOfType(Bonus::FLYING_MOVEMENT);
  1663. const bool canWalkOnSea = ti->hasBonusOfType(Bonus::WATER_WALKING);
  1664. const int cost = CPathfinderHelper::getMovementCost(h, h->getPosition(), hmpos, nullptr, nullptr, h->movement, ti);
  1665. //it's a rock or blocked and not visitable tile
  1666. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1667. if(((t.terType == ETerrainType::ROCK || (t.blocked && !t.visitable && !canFly))
  1668. && complain("Cannot move hero, destination tile is blocked!"))
  1669. || ((!h->boat && !canWalkOnSea && !canFly && t.terType == ETerrainType::WATER && (t.visitableObjects.size() < 1 || (t.visitableObjects.back()->ID != Obj::BOAT && t.visitableObjects.back()->ID != Obj::HERO))) //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)
  1670. && complain("Cannot move hero, destination tile is on water!"))
  1671. || ((h->boat && t.terType != ETerrainType::WATER && t.blocked)
  1672. && complain("Cannot disembark hero, tile is blocked!"))
  1673. || ( (distance(h->pos, dst) >= 1.5 && !teleporting)
  1674. && complain("Tiles are not neighboring!"))
  1675. || ( (h->inTownGarrison)
  1676. && complain("Can not move garrisoned hero!"))
  1677. || ((h->movement < cost && dst != h->pos && !teleporting)
  1678. && complain("Hero doesn't have any movement points left!"))
  1679. || ((transit && !canFly && !CGTeleport::isTeleport(t.topVisitableObj()))
  1680. && complain("Hero cannot transit over this tile!"))
  1681. /*|| (states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1682. && complain("Cannot move hero during the battle"))*/)
  1683. {
  1684. //send info about movement failure
  1685. sendAndApply(&tmh);
  1686. return false;
  1687. }
  1688. //several generic blocks of code
  1689. // should be called if hero changes tile but before applying TryMoveHero package
  1690. auto leaveTile = [&]()
  1691. {
  1692. for(CGObjectInstance *obj : gs->map->getTile(int3(h->pos.x-1, h->pos.y, h->pos.z)).visitableObjects)
  1693. {
  1694. obj->onHeroLeave(h);
  1695. }
  1696. this->getTilesInRange(tmh.fowRevealed, h->getSightCenter()+(tmh.end-tmh.start), h->getSightRadious(), h->tempOwner, 1);
  1697. };
  1698. auto doMove = [&](TryMoveHero::EResult result, EGuardLook lookForGuards,
  1699. EVisitDest visitDest, ELEaveTile leavingTile) -> bool
  1700. {
  1701. LOG_TRACE_PARAMS(logGlobal, "Hero %s starts movement from %s to %s", h->name % tmh.start % tmh.end);
  1702. auto moveQuery = std::make_shared<CHeroMovementQuery>(tmh, h);
  1703. queries.addQuery(moveQuery);
  1704. if(leavingTile == LEAVING_TILE)
  1705. leaveTile();
  1706. tmh.result = result;
  1707. sendAndApply(&tmh);
  1708. if (visitDest == VISIT_DEST && t.topVisitableObj() && t.topVisitableObj()->id == h->id)
  1709. { // Hero should be always able to visit any object he staying on even if there guards around
  1710. visitObjectOnTile(t, h);
  1711. }
  1712. else if(lookForGuards == CHECK_FOR_GUARDS && this->isInTheMap(guardPos))
  1713. {
  1714. tmh.attackedFrom = guardPos;
  1715. const TerrainTile &guardTile = *gs->getTile(guardPos);
  1716. objectVisited(guardTile.visitableObjects.back(), h);
  1717. moveQuery->visitDestAfterVictory = visitDest==VISIT_DEST;
  1718. }
  1719. else if(visitDest == VISIT_DEST)
  1720. {
  1721. visitObjectOnTile(t, h);
  1722. }
  1723. queries.popIfTop(moveQuery);
  1724. logGlobal->traceStream() << "Hero " << h->name << " ends movement";
  1725. return result != TryMoveHero::FAILED;
  1726. };
  1727. //interaction with blocking object (like resources)
  1728. auto blockingVisit = [&]() -> bool
  1729. {
  1730. for(CGObjectInstance *obj : t.visitableObjects)
  1731. {
  1732. if(obj != h && obj->blockVisit && !obj->passableFor(h->tempOwner))
  1733. {
  1734. return doMove(TryMoveHero::BLOCKING_VISIT, this->IGNORE_GUARDS, VISIT_DEST, REMAINING_ON_TILE);
  1735. //this-> is needed for MVS2010 to recognize scope (?)
  1736. }
  1737. }
  1738. return false;
  1739. };
  1740. if(!transit && embarking)
  1741. {
  1742. tmh.movePoints = h->movementPointsAfterEmbark(h->movement, cost, false, ti);
  1743. return doMove(TryMoveHero::EMBARK, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  1744. // In H3 embark ignore guards
  1745. }
  1746. if(disembarking)
  1747. {
  1748. tmh.movePoints = h->movementPointsAfterEmbark(h->movement, cost, true, ti);
  1749. return doMove(TryMoveHero::DISEMBARK, CHECK_FOR_GUARDS, VISIT_DEST, LEAVING_TILE);
  1750. }
  1751. if(teleporting)
  1752. {
  1753. if(blockingVisit()) // e.g. hero on the other side of teleporter
  1754. return true;
  1755. doMove(TryMoveHero::TELEPORTATION, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  1756. // visit town for town portal \ castle gates
  1757. // do not use generic visitObjectOnTile to avoid double-teleporting
  1758. // if this moveHero call was triggered by teleporter
  1759. if (!t.visitableObjects.empty())
  1760. {
  1761. if (CGTownInstance * town = dynamic_cast<CGTownInstance *>(t.visitableObjects.back()))
  1762. town->onHeroVisit(h);
  1763. }
  1764. return true;
  1765. }
  1766. //still here? it is standard movement!
  1767. {
  1768. tmh.movePoints = h->movement >= cost
  1769. ? h->movement - cost
  1770. : 0;
  1771. EGuardLook lookForGuards = CHECK_FOR_GUARDS;
  1772. EVisitDest visitDest = VISIT_DEST;
  1773. if(transit)
  1774. {
  1775. if(CGTeleport::isTeleport(t.topVisitableObj()))
  1776. visitDest = DONT_VISIT_DEST;
  1777. if(canFly)
  1778. {
  1779. lookForGuards = IGNORE_GUARDS;
  1780. visitDest = DONT_VISIT_DEST;
  1781. }
  1782. }
  1783. else if(blockingVisit())
  1784. return true;
  1785. doMove(TryMoveHero::SUCCESS, lookForGuards, visitDest, LEAVING_TILE);
  1786. return true;
  1787. }
  1788. }
  1789. bool CGameHandler::teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker/* = 255*/)
  1790. {
  1791. const CGHeroInstance *h = getHero(hid);
  1792. const CGTownInstance *t = getTown(dstid);
  1793. if ( !h || !t || h->getOwner() != gs->currentPlayer )
  1794. logGlobal->errorStream()<<"Invalid call to teleportHero!";
  1795. const CGTownInstance *from = h->visitedTown;
  1796. if(((h->getOwner() != t->getOwner())
  1797. && complain("Cannot teleport hero to another player"))
  1798. || ((!from || !from->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO))
  1799. && complain("Hero must be in town with Castle gate for teleporting"))
  1800. || (!t->hasBuilt(BuildingID::CASTLE_GATE, ETownType::INFERNO)
  1801. && complain("Cannot teleport hero to town without Castle gate in it")))
  1802. return false;
  1803. int3 pos = t->visitablePos();
  1804. pos += h->getVisitableOffset();
  1805. moveHero(hid,pos,1);
  1806. return true;
  1807. }
  1808. void CGameHandler::setOwner(const CGObjectInstance * obj, PlayerColor owner)
  1809. {
  1810. PlayerColor oldOwner = getOwner(obj->id);
  1811. SetObjectProperty sop(obj->id, 1, owner.getNum());
  1812. sendAndApply(&sop);
  1813. std::set<PlayerColor> playerColors = {owner, oldOwner};
  1814. checkVictoryLossConditions(playerColors);
  1815. if(dynamic_cast<const CGTownInstance *>(obj)) //town captured
  1816. {
  1817. if (owner < PlayerColor::PLAYER_LIMIT) //new owner is real player
  1818. {
  1819. const CGTownInstance * town = dynamic_cast<const CGTownInstance *>(obj);
  1820. if (town->hasBuilt(BuildingID::PORTAL_OF_SUMMON, ETownType::DUNGEON))
  1821. setPortalDwelling(town, true, false);
  1822. gs->getPlayer(owner)->daysWithoutCastle = boost::none; // reset counter
  1823. }
  1824. if (oldOwner < PlayerColor::PLAYER_LIMIT) //old owner is real player
  1825. {
  1826. if (gs->getPlayer(oldOwner)->towns.empty())//previous player lost last last town
  1827. {
  1828. InfoWindow iw;
  1829. iw.player = oldOwner;
  1830. iw.text.addTxt(MetaString::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.
  1831. iw.text.addReplacement(MetaString::COLOR, oldOwner.getNum());
  1832. sendAndApply(&iw);
  1833. }
  1834. }
  1835. }
  1836. const PlayerState * p = gs->getPlayer(owner);
  1837. if((obj->ID == Obj::CREATURE_GENERATOR1 || obj->ID == Obj::CREATURE_GENERATOR4 ) && p && p->dwellings.size()==1)//first dwelling captured
  1838. {
  1839. for(const CGTownInstance *t : gs->getPlayer(owner)->towns)
  1840. {
  1841. if (t->hasBuilt(BuildingID::PORTAL_OF_SUMMON, ETownType::DUNGEON))
  1842. setPortalDwelling(t);//set initial creatures for all portals of summoning
  1843. }
  1844. }
  1845. }
  1846. void CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1847. {
  1848. auto dialogQuery = std::make_shared<CBlockingDialogQuery>(*iw);
  1849. queries.addQuery(dialogQuery);
  1850. iw->queryID = dialogQuery->queryID;
  1851. sendToAllClients(iw);
  1852. }
  1853. void CGameHandler::showTeleportDialog( TeleportDialog *iw )
  1854. {
  1855. auto dialogQuery = std::make_shared<CTeleportDialogQuery>(*iw);
  1856. queries.addQuery(dialogQuery);
  1857. iw->queryID = dialogQuery->queryID;
  1858. sendToAllClients(iw);
  1859. }
  1860. void CGameHandler::giveResource(PlayerColor player, Res::ERes which, int val) //TODO: cap according to Bersy's suggestion
  1861. {
  1862. if(!val) return; //don't waste time on empty call
  1863. SetResource sr;
  1864. sr.player = player;
  1865. sr.resid = which;
  1866. sr.val = gs->players.find(player)->second.resources.at(which) + val;
  1867. sendAndApply(&sr);
  1868. }
  1869. void CGameHandler::giveResources(PlayerColor player, TResources resources)
  1870. {
  1871. for(TResources::nziterator i(resources); i.valid(); i++)
  1872. giveResource(player, i->resType, i->resVal);
  1873. }
  1874. void CGameHandler::giveCreatures(const CArmedInstance *obj, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove)
  1875. {
  1876. COMPLAIN_RET_IF(!creatures.stacksCount(), "Strange, giveCreatures called without args!");
  1877. COMPLAIN_RET_IF(obj->stacksCount(), "Cannot give creatures from not-cleared object!");
  1878. COMPLAIN_RET_IF(creatures.stacksCount() > GameConstants::ARMY_SIZE, "Too many stacks to give!");
  1879. //first we move creatures to give to make them army of object-source
  1880. for (auto & elem : creatures.Slots())
  1881. {
  1882. addToSlot(StackLocation(obj, obj->getSlotFor(elem.second->type)), elem.second->type, elem.second->count);
  1883. }
  1884. tryJoiningArmy(obj, h, remove, true);
  1885. }
  1886. void CGameHandler::takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures)
  1887. {
  1888. std::vector<CStackBasicDescriptor> cres = creatures;
  1889. if (cres.size() <= 0)
  1890. return;
  1891. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  1892. for(CStackBasicDescriptor &sbd : cres)
  1893. {
  1894. TQuantity collected = 0;
  1895. while(collected < sbd.count)
  1896. {
  1897. bool foundSth = false;
  1898. for(auto i = obj->Slots().begin(); i != obj->Slots().end(); i++)
  1899. {
  1900. if(i->second->type == sbd.type)
  1901. {
  1902. TQuantity take = std::min(sbd.count - collected, i->second->count); //collect as much cres as we can
  1903. changeStackCount(StackLocation(obj, i->first), -take, false);
  1904. collected += take;
  1905. foundSth = true;
  1906. break;
  1907. }
  1908. }
  1909. if(!foundSth) //we went through the whole loop and haven't found appropriate cres
  1910. {
  1911. complain("Unexpected failure during taking creatures!");
  1912. return;
  1913. }
  1914. }
  1915. }
  1916. }
  1917. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1918. {
  1919. sendToAllClients(comp);
  1920. }
  1921. void CGameHandler::heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  1922. {
  1923. HeroVisitCastle vc;
  1924. vc.hid = hero->id;
  1925. vc.tid = obj->id;
  1926. vc.flags |= 1;
  1927. sendAndApply(&vc);
  1928. vistiCastleObjects (obj, hero);
  1929. giveSpells (obj, hero);
  1930. checkVictoryLossConditionsForPlayer(hero->tempOwner); //transported artifact?
  1931. }
  1932. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1933. {
  1934. std::vector<CGTownBuilding*>::const_iterator i;
  1935. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1936. (*i)->onHeroVisit (h);
  1937. }
  1938. void CGameHandler::stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  1939. {
  1940. HeroVisitCastle vc;
  1941. vc.hid = hero->id;
  1942. vc.tid = obj->id;
  1943. sendAndApply(&vc);
  1944. }
  1945. void CGameHandler::removeArtifact(const ArtifactLocation &al)
  1946. {
  1947. EraseArtifact ea;
  1948. ea.al = al;
  1949. sendAndApply(&ea);
  1950. }
  1951. void CGameHandler::startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile,
  1952. const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank,
  1953. const CGTownInstance *town) //use hero=nullptr for no hero
  1954. {
  1955. engageIntoBattle(army1->tempOwner);
  1956. engageIntoBattle(army2->tempOwner);
  1957. static const CArmedInstance *armies[2];
  1958. armies[0] = army1;
  1959. armies[1] = army2;
  1960. static const CGHeroInstance*heroes[2];
  1961. heroes[0] = hero1;
  1962. heroes[1] = hero2;
  1963. setupBattle(tile, armies, heroes, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  1964. auto battleQuery = std::make_shared<CBattleQuery>(gs->curB);
  1965. queries.addQuery(battleQuery);
  1966. boost::thread(&CGameHandler::runBattle, this);
  1967. }
  1968. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank )
  1969. {
  1970. startBattlePrimary(army1, army2, tile,
  1971. army1->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army1) : nullptr,
  1972. army2->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army2) : nullptr,
  1973. creatureBank);
  1974. }
  1975. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank)
  1976. {
  1977. startBattleI(army1, army2, army2->visitablePos(), creatureBank);
  1978. }
  1979. void CGameHandler::changeSpells( const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells )
  1980. {
  1981. ChangeSpells cs;
  1982. cs.hid = hero->id;
  1983. cs.spells = spells;
  1984. cs.learn = give;
  1985. sendAndApply(&cs);
  1986. }
  1987. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1988. {
  1989. SystemMessage sm;
  1990. sm.text = message;
  1991. boost::unique_lock<boost::mutex> lock(*c.wmx);
  1992. c << &sm;
  1993. }
  1994. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1995. {
  1996. sendAndApply(bonus);
  1997. }
  1998. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1999. {
  2000. sendAndApply(smp);
  2001. }
  2002. void CGameHandler::setManaPoints( ObjectInstanceID hid, int val )
  2003. {
  2004. SetMana sm;
  2005. sm.hid = hid;
  2006. sm.val = val;
  2007. sm.absolute = true;
  2008. sendAndApply(&sm);
  2009. }
  2010. void CGameHandler::giveHero( ObjectInstanceID id, PlayerColor player )
  2011. {
  2012. GiveHero gh;
  2013. gh.id = id;
  2014. gh.player = player;
  2015. sendAndApply(&gh);
  2016. }
  2017. void CGameHandler::changeObjPos( ObjectInstanceID objid, int3 newPos, ui8 flags )
  2018. {
  2019. ChangeObjPos cop;
  2020. cop.objid = objid;
  2021. cop.nPos = newPos;
  2022. cop.flags = flags;
  2023. sendAndApply(&cop);
  2024. }
  2025. void CGameHandler::useScholarSkill(ObjectInstanceID fromHero, ObjectInstanceID toHero)
  2026. {
  2027. const CGHeroInstance * h1 = getHero(fromHero);
  2028. const CGHeroInstance * h2 = getHero(toHero);
  2029. if ( h1->getSecSkillLevel(SecondarySkill::SCHOLAR) < h2->getSecSkillLevel(SecondarySkill::SCHOLAR) )
  2030. {
  2031. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  2032. std::swap(fromHero, toHero);
  2033. }
  2034. int ScholarLevel = h1->getSecSkillLevel(SecondarySkill::SCHOLAR);//heroes can trade up to this level
  2035. if (!ScholarLevel || !h1->hasSpellbook() || !h2->hasSpellbook() )
  2036. return;//no scholar skill or no spellbook
  2037. int h1Lvl = std::min(ScholarLevel+1, h1->getSecSkillLevel(SecondarySkill::WISDOM)+2),
  2038. h2Lvl = std::min(ScholarLevel+1, h2->getSecSkillLevel(SecondarySkill::WISDOM)+2);//heroes can receive this levels
  2039. ChangeSpells cs1;
  2040. cs1.learn = true;
  2041. cs1.hid = toHero;//giving spells to first hero
  2042. for(auto it : h1->spells)
  2043. if ( h2Lvl >= it.toSpell()->level && !vstd::contains(h2->spells, it))//hero can learn it and don't have it yet
  2044. cs1.spells.insert(it);//spell to learn
  2045. ChangeSpells cs2;
  2046. cs2.learn = true;
  2047. cs2.hid = fromHero;
  2048. for(auto it : h2->spells)
  2049. if ( h1Lvl >= it.toSpell()->level && !vstd::contains(h1->spells, it))
  2050. cs2.spells.insert(it);
  2051. if (!cs1.spells.empty() || !cs2.spells.empty())//create a message
  2052. {
  2053. InfoWindow iw;
  2054. iw.player = h1->tempOwner;
  2055. iw.components.push_back(Component(Component::SEC_SKILL, 18, ScholarLevel, 0));
  2056. iw.text.addTxt(MetaString::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  2057. iw.text.addReplacement(h1->name);
  2058. if (!cs2.spells.empty())//if found new spell - apply
  2059. {
  2060. iw.text.addTxt(MetaString::GENERAL_TXT, 140);//learns
  2061. int size = cs2.spells.size();
  2062. for(auto it : cs2.spells)
  2063. {
  2064. iw.components.push_back(Component(Component::SPELL, it, 1, 0));
  2065. iw.text.addTxt(MetaString::SPELL_NAME, it.toEnum());
  2066. switch (size--)
  2067. {
  2068. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  2069. case 1: break;
  2070. default: iw.text << ", ";
  2071. }
  2072. }
  2073. iw.text.addTxt(MetaString::GENERAL_TXT, 142);//from %s
  2074. iw.text.addReplacement(h2->name);
  2075. sendAndApply(&cs2);
  2076. }
  2077. if (!cs1.spells.empty() && !cs2.spells.empty() )
  2078. {
  2079. iw.text.addTxt(MetaString::GENERAL_TXT, 141);//and
  2080. }
  2081. if (!cs1.spells.empty())
  2082. {
  2083. iw.text.addTxt(MetaString::GENERAL_TXT, 147);//teaches
  2084. int size = cs1.spells.size();
  2085. for(auto it : cs1.spells)
  2086. {
  2087. iw.components.push_back(Component(Component::SPELL, it, 1, 0));
  2088. iw.text.addTxt(MetaString::SPELL_NAME, it.toEnum());
  2089. switch (size--)
  2090. {
  2091. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  2092. case 1: break;
  2093. default: iw.text << ", ";
  2094. } }
  2095. iw.text.addTxt(MetaString::GENERAL_TXT, 148);//from %s
  2096. iw.text.addReplacement(h2->name);
  2097. sendAndApply(&cs1);
  2098. }
  2099. sendAndApply(&iw);
  2100. }
  2101. }
  2102. void CGameHandler::heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  2103. {
  2104. auto h1 = getHero(hero1), h2 = getHero(hero2);
  2105. if( gameState()->getPlayerRelations(h1->getOwner(), h2->getOwner()))
  2106. {
  2107. auto exchange = std::make_shared<CGarrisonDialogQuery>(h1, h2);
  2108. ExchangeDialog hex;
  2109. hex.queryID = exchange->queryID;
  2110. hex.heroes[0] = getHero(hero1);
  2111. hex.heroes[1] = getHero(hero2);
  2112. sendAndApply(&hex);
  2113. useScholarSkill(hero1,hero2);
  2114. queries.addQuery(exchange);
  2115. }
  2116. }
  2117. void CGameHandler::sendToAllClients( CPackForClient * info )
  2118. {
  2119. logGlobal->traceStream() << "Sending to all clients a package of type " << typeid(*info).name();
  2120. for(auto & elem : conns)
  2121. {
  2122. boost::unique_lock<boost::mutex> lock(*(elem)->wmx);
  2123. *elem << info;
  2124. }
  2125. }
  2126. void CGameHandler::sendAndApply(CPackForClient * info)
  2127. {
  2128. sendToAllClients(info);
  2129. gs->apply(info);
  2130. }
  2131. void CGameHandler::applyAndSend(CPackForClient * info)
  2132. {
  2133. gs->apply(info);
  2134. sendToAllClients(info);
  2135. }
  2136. void CGameHandler::sendAndApply(CGarrisonOperationPack * info)
  2137. {
  2138. sendAndApply(static_cast<CPackForClient*>(info));
  2139. checkVictoryLossConditionsForAll();
  2140. }
  2141. void CGameHandler::sendAndApply( SetResource * info )
  2142. {
  2143. sendAndApply(static_cast<CPackForClient*>(info));
  2144. checkVictoryLossConditionsForPlayer(info->player);
  2145. }
  2146. void CGameHandler::sendAndApply( SetResources * info )
  2147. {
  2148. sendAndApply(static_cast<CPackForClient*>(info));
  2149. checkVictoryLossConditionsForPlayer(info->player);
  2150. }
  2151. void CGameHandler::sendAndApply( NewStructures * info )
  2152. {
  2153. sendAndApply(static_cast<CPackForClient*>(info));
  2154. checkVictoryLossConditionsForPlayer(getTown(info->tid)->tempOwner);
  2155. }
  2156. void CGameHandler::save(const std::string & filename )
  2157. {
  2158. logGlobal->infoStream() << "Saving to " << filename;
  2159. CFileInfo info(filename);
  2160. //CResourceHandler::get("local")->createResource(info.getStem() + ".vlgm1");
  2161. CResourceHandler::get("local")->createResource(info.getStem() + ".vsgm1");
  2162. {
  2163. logGlobal->infoStream() << "Ordering clients to serialize...";
  2164. SaveGame sg(info.getStem() + ".vcgm1");
  2165. sendToAllClients(&sg);
  2166. }
  2167. try
  2168. {
  2169. // {
  2170. // logGlobal->infoStream() << "Serializing game info...";
  2171. // CSaveFile save(CResourceHandler::get("local")->getResourceName(ResourceID(info.getStem(), EResType::LIB_SAVEGAME)));
  2172. // // char hlp[8] = "VCMISVG";
  2173. // // save << hlp;
  2174. // saveCommonState(save);
  2175. // }
  2176. {
  2177. CSaveFile save(*CResourceHandler::get("local")->getResourceName(ResourceID(info.getStem(), EResType::SERVER_SAVEGAME)));
  2178. saveCommonState(save);
  2179. logGlobal->infoStream() << "Saving server state";
  2180. save << *this;
  2181. }
  2182. logGlobal->infoStream() << "Game has been successfully saved!";
  2183. }
  2184. catch(std::exception &e)
  2185. {
  2186. logGlobal->errorStream() << "Failed to save game: " << e.what();
  2187. }
  2188. }
  2189. void CGameHandler::close()
  2190. {
  2191. logGlobal->infoStream() << "We have been requested to close.";
  2192. if(gs->initialOpts->mode == StartInfo::DUEL)
  2193. {
  2194. exit(0);
  2195. }
  2196. //for(CConnection *cc : conns)
  2197. // if(cc && cc->socket && cc->socket->is_open())
  2198. // cc->socket->close();
  2199. //exit(0);
  2200. }
  2201. bool CGameHandler::arrangeStacks( ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player )
  2202. {
  2203. const CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->getObjInstance(id1)),
  2204. *s2 = static_cast<CArmedInstance*>(gs->getObjInstance(id2));
  2205. const CCreatureSet &S1 = *s1, &S2 = *s2;
  2206. StackLocation sl1(s1, p1), sl2(s2, p2);
  2207. if(!sl1.slot.validSlot() || !sl2.slot.validSlot())
  2208. {
  2209. complain("Invalid slot accessed!");
  2210. return false;
  2211. }
  2212. if(!isAllowedExchange(id1,id2))
  2213. {
  2214. complain("Cannot exchange stacks between these two objects!\n");
  2215. return false;
  2216. }
  2217. if(what==1) //swap
  2218. {
  2219. if ( ((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s1->getStackCount(p1))
  2220. || ((s2->tempOwner != player && s2->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)))
  2221. {
  2222. complain("Can't take troops from another player!");
  2223. return false;
  2224. }
  2225. if (sl1.army == sl2.army && sl1.slot == sl2.slot)
  2226. {
  2227. complain("Cannot swap stacks - slots are the same!");
  2228. return false;
  2229. }
  2230. swapStacks(sl1, sl2);
  2231. }
  2232. else if(what==2)//merge
  2233. {
  2234. if (( s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot merge different creatures stacks!"))
  2235. || (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)) && complain("Can't take troops from another player!")))
  2236. return false;
  2237. moveStack(sl1, sl2);
  2238. }
  2239. else if(what==3) //split
  2240. {
  2241. const int countToMove = val - s2->getStackCount(p2);
  2242. const int countLeftOnSrc = s1->getStackCount(p1) - countToMove;
  2243. if ( (s1->tempOwner != player && countLeftOnSrc < s1->getStackCount(p1) )
  2244. || (s2->tempOwner != player && val < s2->getStackCount(p2) ) )
  2245. {
  2246. complain("Can't move troops of another player!");
  2247. return false;
  2248. }
  2249. //general conditions checking
  2250. if((!vstd::contains(S1.stacks,p1) && complain("no creatures to split"))
  2251. || (val<1 && complain("no creatures to split")) )
  2252. {
  2253. return false;
  2254. }
  2255. if(vstd::contains(S2.stacks,p2)) //dest. slot not free - it must be "rebalancing"...
  2256. {
  2257. int total = s1->getStackCount(p1) + s2->getStackCount(p2);
  2258. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  2259. || (s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot rebalance different creatures stacks!"))
  2260. )
  2261. {
  2262. return false;
  2263. }
  2264. moveStack(sl1, sl2, countToMove);
  2265. //S2.slots[p2]->count = val;
  2266. //S1.slots[p1]->count = total - val;
  2267. }
  2268. else //split one stack to the two
  2269. {
  2270. if(s1->getStackCount(p1) < val)//not enough creatures
  2271. {
  2272. complain("Cannot split that stack, not enough creatures!");
  2273. return false;
  2274. }
  2275. moveStack(sl1, sl2, val);
  2276. }
  2277. }
  2278. return true;
  2279. }
  2280. PlayerColor CGameHandler::getPlayerAt( CConnection *c ) const
  2281. {
  2282. std::set<PlayerColor> all;
  2283. for(auto i=connections.cbegin(); i!=connections.cend(); i++)
  2284. if(i->second == c)
  2285. all.insert(i->first);
  2286. switch(all.size())
  2287. {
  2288. case 0:
  2289. return PlayerColor::NEUTRAL;
  2290. case 1:
  2291. return *all.begin();
  2292. default:
  2293. {
  2294. //if we have more than one player at this connection, try to pick active one
  2295. if(vstd::contains(all, gs->currentPlayer))
  2296. return gs->currentPlayer;
  2297. else
  2298. return PlayerColor::CANNOT_DETERMINE; //cannot say which player is it
  2299. }
  2300. }
  2301. }
  2302. bool CGameHandler::disbandCreature( ObjectInstanceID id, SlotID pos )
  2303. {
  2304. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->getObjInstance(id));
  2305. if(!vstd::contains(s1->stacks,pos))
  2306. {
  2307. complain("Illegal call to disbandCreature - no such stack in army!");
  2308. return false;
  2309. }
  2310. eraseStack(StackLocation(s1, pos));
  2311. return true;
  2312. }
  2313. bool CGameHandler::buildStructure( ObjectInstanceID tid, BuildingID requestedID, bool force /*=false*/ )
  2314. {
  2315. const CGTownInstance * t = getTown(tid);
  2316. if(!t)
  2317. COMPLAIN_RETF("No such town (ID=%s)!", tid);
  2318. if(!t->town->buildings.count(requestedID))
  2319. COMPLAIN_RETF("Town of faction %s does not have info about building ID=%s!", t->town->faction->name % tid);
  2320. if (t->hasBuilt(requestedID))
  2321. COMPLAIN_RETF("Building %s is already built in %s", t->town->buildings.at(requestedID)->Name() % t->name);
  2322. const CBuilding * requestedBuilding = t->town->buildings.at(requestedID);
  2323. //Vector with future list of built building and buildings in auto-mode that are not yet built.
  2324. std::vector<const CBuilding*> remainingAutoBuildings;
  2325. std::set<BuildingID> buildingsThatWillBe;
  2326. //Check validity of request
  2327. if(!force)
  2328. {
  2329. switch (requestedBuilding->mode)
  2330. {
  2331. case CBuilding::BUILD_NORMAL :
  2332. if (gs->canBuildStructure(t, requestedID) != EBuildingState::ALLOWED)
  2333. COMPLAIN_RET("Cannot build that building!");
  2334. break;
  2335. case CBuilding::BUILD_AUTO :
  2336. case CBuilding::BUILD_SPECIAL:
  2337. COMPLAIN_RET("This building can not be constructed normally!");
  2338. case CBuilding::BUILD_GRAIL :
  2339. if(requestedBuilding->mode == CBuilding::BUILD_GRAIL) //needs grail
  2340. {
  2341. if(!t->visitingHero || !t->visitingHero->hasArt(ArtifactID::GRAIL))
  2342. COMPLAIN_RET("Cannot build this without grail!")
  2343. else
  2344. removeArtifact(ArtifactLocation(t->visitingHero, t->visitingHero->getArtPos(ArtifactID::GRAIL, false)));
  2345. }
  2346. break;
  2347. }
  2348. }
  2349. //Performs stuff that has to be done after new building is built
  2350. auto processBuiltStructure = [t, this](const BuildingID buildingID)
  2351. {
  2352. if(buildingID >= BuildingID::DWELL_FIRST) //dwelling
  2353. {
  2354. int level = (buildingID - BuildingID::DWELL_FIRST) % GameConstants::CREATURES_PER_TOWN;
  2355. int upgradeNumber = (buildingID - BuildingID::DWELL_FIRST) / GameConstants::CREATURES_PER_TOWN;
  2356. if (upgradeNumber >= t->town->creatures.at(level).size())
  2357. {
  2358. complain(boost::str(boost::format("Error ecountered when building dwelling (bid=%s):"
  2359. "no creature found (upgrade number %d, level %d!")
  2360. % buildingID % upgradeNumber % level));
  2361. return;
  2362. }
  2363. CCreature * crea = VLC->creh->creatures.at(t->town->creatures.at(level).at(upgradeNumber));
  2364. SetAvailableCreatures ssi;
  2365. ssi.tid = t->id;
  2366. ssi.creatures = t->creatures;
  2367. if (ssi.creatures[level].second.empty()) // first creature in a dwelling
  2368. ssi.creatures[level].first = crea->growth;
  2369. ssi.creatures[level].second.push_back(crea->idNumber);
  2370. sendAndApply(&ssi);
  2371. }
  2372. if ( t->subID == ETownType::DUNGEON && buildingID == BuildingID::PORTAL_OF_SUMMON )
  2373. {
  2374. setPortalDwelling(t);
  2375. }
  2376. if(buildingID <= BuildingID::MAGES_GUILD_5) //it's mage guild
  2377. {
  2378. if(t->visitingHero)
  2379. giveSpells(t,t->visitingHero);
  2380. if(t->garrisonHero)
  2381. giveSpells(t,t->garrisonHero);
  2382. }
  2383. };
  2384. //Checks if all requirements will be met with expected building list "buildingsThatWillBe"
  2385. auto areRequirementsFullfilled = [&](const BuildingID & buildID)
  2386. {
  2387. return buildingsThatWillBe.count(buildID);
  2388. };
  2389. //Init the vectors
  2390. for(auto & build : t->town->buildings)
  2391. {
  2392. if(t->hasBuilt(build.first))
  2393. buildingsThatWillBe.insert(build.first);
  2394. else
  2395. {
  2396. if(build.second->mode == CBuilding::BUILD_AUTO) //not built auto building
  2397. remainingAutoBuildings.push_back(build.second);
  2398. }
  2399. }
  2400. //Prepare structure (list of building ids will be filled later)
  2401. NewStructures ns;
  2402. ns.tid = tid;
  2403. ns.builded = force ? t->builded : (t->builded+1);
  2404. std::queue<const CBuilding*> buildingsToAdd;
  2405. buildingsToAdd.push(requestedBuilding);
  2406. while(!buildingsToAdd.empty())
  2407. {
  2408. auto b = buildingsToAdd.front();
  2409. buildingsToAdd.pop();
  2410. ns.bid.insert(b->bid);
  2411. buildingsThatWillBe.insert(b->bid);
  2412. remainingAutoBuildings -= b;
  2413. for(auto autoBuilding : remainingAutoBuildings)
  2414. {
  2415. if (autoBuilding->requirements.test(areRequirementsFullfilled))
  2416. buildingsToAdd.push(autoBuilding);
  2417. }
  2418. }
  2419. //Other post-built events
  2420. for(auto builtID : ns.bid)
  2421. processBuiltStructure(builtID);
  2422. //Take cost
  2423. if (!force)
  2424. {
  2425. SetResources sr;
  2426. sr.player = t->tempOwner;
  2427. sr.res = gs->getPlayer(t->tempOwner)->resources - requestedBuilding->resources;
  2428. sendAndApply(&sr);
  2429. }
  2430. //We know what has been built, appluy changes. Do this as final step to properly update town window
  2431. sendAndApply(&ns);
  2432. // now when everything is built - reveal tiles for lookout tower
  2433. FoWChange fw;
  2434. fw.player = t->tempOwner;
  2435. fw.mode = 1;
  2436. getTilesInRange(fw.tiles, t->getSightCenter(), t->getSightRadious(), t->tempOwner, 1);
  2437. sendAndApply(&fw);
  2438. if(t->visitingHero)
  2439. vistiCastleObjects (t, t->visitingHero);
  2440. if(t->garrisonHero)
  2441. vistiCastleObjects (t, t->garrisonHero);
  2442. checkVictoryLossConditionsForPlayer(t->tempOwner);
  2443. return true;
  2444. }
  2445. bool CGameHandler::razeStructure (ObjectInstanceID tid, BuildingID bid)
  2446. {
  2447. ///incomplete, simply erases target building
  2448. const CGTownInstance * t = getTown(tid);
  2449. if (!vstd::contains(t->builtBuildings, bid))
  2450. return false;
  2451. RazeStructures rs;
  2452. rs.tid = tid;
  2453. rs.bid.insert(bid);
  2454. rs.destroyed = t->destroyed + 1;
  2455. sendAndApply(&rs);
  2456. //TODO: Remove dwellers
  2457. // if (t->subID == 4 && bid == 17) //Veil of Darkness
  2458. // {
  2459. // RemoveBonus rb(RemoveBonus::TOWN);
  2460. // rb.whoID = t->id;
  2461. // rb.source = Bonus::TOWN_STRUCTURE;
  2462. // rb.id = 17;
  2463. // sendAndApply(&rb);
  2464. // }
  2465. return true;
  2466. }
  2467. void CGameHandler::sendMessageToAll( const std::string &message )
  2468. {
  2469. SystemMessage sm;
  2470. sm.text = message;
  2471. sendToAllClients(&sm);
  2472. }
  2473. bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dstid, CreatureID crid, ui32 cram, si32 fromLvl )
  2474. {
  2475. const CGDwelling *dw = static_cast<const CGDwelling*>(gs->getObj(objid));
  2476. const CArmedInstance *dst = nullptr;
  2477. const CCreature *c = VLC->creh->creatures.at(crid);
  2478. bool warMachine = c->hasBonusOfType(Bonus::SIEGE_WEAPON);
  2479. //TODO: test for owning
  2480. //TODO: check if dst can recruit objects (e.g. hero is actually visiting object, town and source are same, etc)
  2481. dst = dynamic_cast<const CArmedInstance*>(getObj(dstid));
  2482. assert(dw && dst);
  2483. //verify
  2484. bool found = false;
  2485. int level = 0;
  2486. for(; level < dw->creatures.size(); level++) //iterate through all levels
  2487. {
  2488. if ( (fromLvl != -1) && ( level !=fromLvl ) )
  2489. continue;
  2490. const auto &cur = dw->creatures.at(level); //current level info <amount, list of cr. ids>
  2491. int i = 0;
  2492. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  2493. if(cur.second.at(i) == crid)
  2494. break;
  2495. if(i < cur.second.size())
  2496. {
  2497. found = true;
  2498. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  2499. break;
  2500. }
  2501. }
  2502. SlotID slot = dst->getSlotFor(crid);
  2503. if( (!found && complain("Cannot recruit: no such creatures!"))
  2504. || (cram > VLC->creh->creatures.at(crid)->maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!"))
  2505. || (cram<=0 && complain("Cannot recruit: cram <= 0!"))
  2506. || (!slot.validSlot() && !warMachine && complain("Cannot recruit: no available slot!")))
  2507. {
  2508. return false;
  2509. }
  2510. //recruit
  2511. SetResources sr;
  2512. sr.player = dst->tempOwner;
  2513. sr.res = gs->getPlayer(dst->tempOwner)->resources - (c->cost * cram);
  2514. SetAvailableCreatures sac;
  2515. sac.tid = objid;
  2516. sac.creatures = dw->creatures;
  2517. sac.creatures[level].first -= cram;
  2518. sendAndApply(&sr);
  2519. sendAndApply(&sac);
  2520. if(warMachine)
  2521. {
  2522. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(dst);
  2523. if(!h)
  2524. COMPLAIN_RET("Only hero can buy war machines");
  2525. switch(crid)
  2526. {
  2527. case CreatureID::BALLISTA:
  2528. giveHeroNewArtifact(h, VLC->arth->artifacts[ArtifactID::BALLISTA], ArtifactPosition::MACH1);
  2529. break;
  2530. case CreatureID::FIRST_AID_TENT:
  2531. giveHeroNewArtifact(h, VLC->arth->artifacts[ArtifactID::FIRST_AID_TENT], ArtifactPosition::MACH3);
  2532. break;
  2533. case CreatureID::AMMO_CART:
  2534. giveHeroNewArtifact(h, VLC->arth->artifacts[ArtifactID::AMMO_CART], ArtifactPosition::MACH2);
  2535. break;
  2536. default:
  2537. complain("This war machine cannot be recruited!");
  2538. return false;
  2539. }
  2540. }
  2541. else
  2542. {
  2543. addToSlot(StackLocation(dst, slot), c, cram);
  2544. }
  2545. return true;
  2546. }
  2547. bool CGameHandler::upgradeCreature( ObjectInstanceID objid, SlotID pos, CreatureID upgID )
  2548. {
  2549. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->getObjInstance(objid));
  2550. if (!obj->hasStackAtSlot(pos))
  2551. {
  2552. COMPLAIN_RET("Cannot upgrade, no stack at slot " + boost::to_string(pos));
  2553. }
  2554. UpgradeInfo ui = gs->getUpgradeInfo(obj->getStack(pos));
  2555. PlayerColor player = obj->tempOwner;
  2556. const PlayerState *p = getPlayer(player);
  2557. int crQuantity = obj->stacks.at(pos)->count;
  2558. int newIDpos= vstd::find_pos(ui.newID, upgID);//get position of new id in UpgradeInfo
  2559. //check if upgrade is possible
  2560. if( (ui.oldID<0 || newIDpos == -1 ) && complain("That upgrade is not possible!"))
  2561. {
  2562. return false;
  2563. }
  2564. TResources totalCost = ui.cost.at(newIDpos) * crQuantity;
  2565. //check if player has enough resources
  2566. if(!p->resources.canAfford(totalCost))
  2567. COMPLAIN_RET("Cannot upgrade, not enough resources!");
  2568. //take resources
  2569. SetResources sr;
  2570. sr.player = player;
  2571. sr.res = p->resources - totalCost;
  2572. sendAndApply(&sr);
  2573. //upgrade creature
  2574. changeStackType(StackLocation(obj, pos), VLC->creh->creatures.at(upgID));
  2575. return true;
  2576. }
  2577. bool CGameHandler::changeStackType(const StackLocation &sl, const CCreature *c)
  2578. {
  2579. if(!sl.army->hasStackAtSlot(sl.slot))
  2580. COMPLAIN_RET("Cannot find a stack to change type");
  2581. SetStackType sst;
  2582. sst.sl = sl;
  2583. sst.type = c;
  2584. sendAndApply(&sst);
  2585. return true;
  2586. }
  2587. void CGameHandler::moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging)
  2588. {
  2589. assert(src->canBeMergedWith(*dst, allowMerging));
  2590. while(src->stacksCount())//while there are unmoved creatures
  2591. {
  2592. auto i = src->Slots().begin(); //iterator to stack to move
  2593. StackLocation sl(src, i->first); //location of stack to move
  2594. SlotID pos = dst->getSlotFor(i->second->type);
  2595. if(!pos.validSlot())
  2596. {
  2597. //try to merge two other stacks to make place
  2598. std::pair<SlotID, SlotID> toMerge;
  2599. if(dst->mergableStacks(toMerge, i->first) && allowMerging)
  2600. {
  2601. moveStack(StackLocation(dst, toMerge.first), StackLocation(dst, toMerge.second)); //merge toMerge.first into toMerge.second
  2602. assert(!dst->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  2603. moveStack(sl, StackLocation(dst, toMerge.first)); //move stack to freed slot
  2604. }
  2605. else
  2606. {
  2607. complain("Unexpected failure during an attempt to move army from " + src->nodeName() + " to " + dst->nodeName() + "!");
  2608. return;
  2609. }
  2610. }
  2611. else
  2612. {
  2613. moveStack(sl, StackLocation(dst, pos));
  2614. }
  2615. }
  2616. }
  2617. bool CGameHandler::garrisonSwap( ObjectInstanceID tid )
  2618. {
  2619. CGTownInstance *town = gs->getTown(tid);
  2620. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2621. {
  2622. if(!town->visitingHero->canBeMergedWith(*town))
  2623. {
  2624. complain("Cannot make garrison swap, not enough free slots!");
  2625. return false;
  2626. }
  2627. moveArmy(town, town->visitingHero, true);
  2628. SetHeroesInTown intown;
  2629. intown.tid = tid;
  2630. intown.visiting = ObjectInstanceID();
  2631. intown.garrison = town->visitingHero->id;
  2632. sendAndApply(&intown);
  2633. return true;
  2634. }
  2635. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2636. {
  2637. //check if moving hero out of town will break 8 wandering heroes limit
  2638. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2639. {
  2640. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2641. return false;
  2642. }
  2643. SetHeroesInTown intown;
  2644. intown.tid = tid;
  2645. intown.garrison = ObjectInstanceID();
  2646. intown.visiting = town->garrisonHero->id;
  2647. sendAndApply(&intown);
  2648. return true;
  2649. }
  2650. else if(!!town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2651. {
  2652. SetHeroesInTown intown;
  2653. intown.tid = tid;
  2654. intown.garrison = town->visitingHero->id;
  2655. intown.visiting = town->garrisonHero->id;
  2656. sendAndApply(&intown);
  2657. return true;
  2658. }
  2659. else
  2660. {
  2661. complain("Cannot swap garrison hero!");
  2662. return false;
  2663. }
  2664. }
  2665. // With the amount of changes done to the function, it's more like transferArtifacts.
  2666. // 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.
  2667. bool CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2)
  2668. {
  2669. ArtifactLocation src = al1, dst = al2;
  2670. const PlayerColor srcPlayer = src.owningPlayer(), dstPlayer = dst.owningPlayer();
  2671. const CArmedInstance *srcObj = src.relatedObj(), *dstObj = dst.relatedObj();
  2672. // Make sure exchange is even possible between the two heroes.
  2673. if(!isAllowedExchange(srcObj->id, dstObj->id))
  2674. COMPLAIN_RET("That heroes cannot make any exchange!");
  2675. const CArtifactInstance *srcArtifact = src.getArt();
  2676. const CArtifactInstance *destArtifact = dst.getArt();
  2677. if (srcArtifact == nullptr)
  2678. COMPLAIN_RET("No artifact to move!");
  2679. if (destArtifact && srcPlayer != dstPlayer)
  2680. COMPLAIN_RET("Can't touch artifact on hero of another player!");
  2681. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2682. // Moving to the backpack is always allowed.
  2683. if ((!srcArtifact || dst.slot < GameConstants::BACKPACK_START)
  2684. && srcArtifact && !srcArtifact->canBePutAt(dst, true))
  2685. COMPLAIN_RET("Cannot move artifact!");
  2686. if ((srcArtifact && srcArtifact->artType->id == ArtifactID::ART_LOCK) || (destArtifact && destArtifact->artType->id == ArtifactID::ART_LOCK))
  2687. COMPLAIN_RET("Cannot move artifact locks.");
  2688. if (dst.slot >= GameConstants::BACKPACK_START && srcArtifact->artType->isBig())
  2689. COMPLAIN_RET("Cannot put big artifacts in backpack!");
  2690. if (src.slot == ArtifactPosition::MACH4 || dst.slot == ArtifactPosition::MACH4)
  2691. COMPLAIN_RET("Cannot move catapult!");
  2692. if(dst.slot >= GameConstants::BACKPACK_START)
  2693. vstd::amin(dst.slot, ArtifactPosition(GameConstants::BACKPACK_START + dst.getHolderArtSet()->artifactsInBackpack.size()));
  2694. if (src.slot == dst.slot && src.artHolder == dst.artHolder)
  2695. COMPLAIN_RET("Won't move artifact: Dest same as source!");
  2696. if(dst.slot < GameConstants::BACKPACK_START && destArtifact) //moving art to another slot
  2697. {
  2698. //old artifact must be removed first
  2699. moveArtifact(dst, ArtifactLocation(dst.artHolder, ArtifactPosition(
  2700. dst.getHolderArtSet()->artifactsInBackpack.size() + GameConstants::BACKPACK_START)));
  2701. }
  2702. MoveArtifact ma;
  2703. ma.src = src;
  2704. ma.dst = dst;
  2705. sendAndApply(&ma);
  2706. return true;
  2707. }
  2708. /**
  2709. * Assembles or disassembles a combination artifact.
  2710. * @param heroID ID of hero holding the artifact(s).
  2711. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2712. * @param assemble True for assembly operation, false for disassembly.
  2713. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2714. * artifact to assemble to. Otherwise it's not used.
  2715. */
  2716. bool CGameHandler::assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  2717. {
  2718. CGHeroInstance *hero = gs->getHero(heroID);
  2719. const CArtifactInstance *destArtifact = hero->getArt(artifactSlot);
  2720. if(!destArtifact)
  2721. COMPLAIN_RET("assembleArtifacts: there is no such artifact instance!");
  2722. if(assemble)
  2723. {
  2724. CArtifact *combinedArt = VLC->arth->artifacts[assembleTo];
  2725. if(!combinedArt->constituents)
  2726. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to assemble is not a combined artifacts!");
  2727. if(!vstd::contains(destArtifact->assemblyPossibilities(hero), combinedArt))
  2728. COMPLAIN_RET("assembleArtifacts: It's impossible to assemble requested artifact!");
  2729. AssembledArtifact aa;
  2730. aa.al = ArtifactLocation(hero, artifactSlot);
  2731. aa.builtArt = combinedArt;
  2732. sendAndApply(&aa);
  2733. }
  2734. else
  2735. {
  2736. if(!destArtifact->artType->constituents)
  2737. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is not a combined artifact!");
  2738. DisassembledArtifact da;
  2739. da.al = ArtifactLocation(hero, artifactSlot);
  2740. sendAndApply(&da);
  2741. }
  2742. return true;
  2743. }
  2744. bool CGameHandler::buyArtifact( ObjectInstanceID hid, ArtifactID aid )
  2745. {
  2746. CGHeroInstance *hero = gs->getHero(hid);
  2747. CGTownInstance *town = hero->visitedTown;
  2748. if(aid==ArtifactID::SPELLBOOK)
  2749. {
  2750. if((!town->hasBuilt(BuildingID::MAGES_GUILD_1) && complain("Cannot buy a spellbook, no mage guild in the town!"))
  2751. || (getResource(hero->getOwner(), Res::GOLD) < GameConstants::SPELLBOOK_GOLD_COST && complain("Cannot buy a spellbook, not enough gold!") )
  2752. || (hero->getArt(ArtifactPosition::SPELLBOOK) && complain("Cannot buy a spellbook, hero already has a one!"))
  2753. )
  2754. return false;
  2755. giveResource(hero->getOwner(),Res::GOLD,-GameConstants::SPELLBOOK_GOLD_COST);
  2756. giveHeroNewArtifact(hero, VLC->arth->artifacts[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  2757. assert(hero->getArt(ArtifactPosition::SPELLBOOK));
  2758. giveSpells(town,hero);
  2759. return true;
  2760. }
  2761. else if(aid < 7 && aid > 3) //war machine
  2762. {
  2763. int price = VLC->arth->artifacts[aid]->price;
  2764. if(( hero->getArt(ArtifactPosition(9+aid)) && complain("Hero already has this machine!"))
  2765. || (gs->getPlayer(hero->getOwner())->resources.at(Res::GOLD) < price && complain("Not enough gold!")))
  2766. {
  2767. return false;
  2768. }
  2769. if ((town->hasBuilt(BuildingID::BLACKSMITH) && town->town->warMachine == aid )
  2770. || ((town->hasBuilt(BuildingID::BALLISTA_YARD, ETownType::STRONGHOLD)) && aid == ArtifactID::BALLISTA))
  2771. {
  2772. giveResource(hero->getOwner(),Res::GOLD,-price);
  2773. giveHeroNewArtifact(hero, VLC->arth->artifacts[aid], ArtifactPosition(9+aid));
  2774. return true;
  2775. }
  2776. else
  2777. COMPLAIN_RET("This machine is unavailable here!");
  2778. }
  2779. return false;
  2780. }
  2781. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, Res::ERes rid, ArtifactID aid)
  2782. {
  2783. if(!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_ARTIFACT), aid))
  2784. COMPLAIN_RET("That artifact is unavailable!");
  2785. int b1, b2;
  2786. m->getOffer(rid, aid, b1, b2, EMarketMode::RESOURCE_ARTIFACT);
  2787. if(getResource(h->tempOwner, rid) < b1)
  2788. COMPLAIN_RET("You can't afford to buy this artifact!");
  2789. SetResource sr;
  2790. sr.player = h->tempOwner;
  2791. sr.resid = rid;
  2792. sr.val = getResource(h->tempOwner, rid) - b1;
  2793. sendAndApply(&sr);
  2794. SetAvailableArtifacts saa;
  2795. if(m->o->ID == Obj::TOWN)
  2796. {
  2797. saa.id = -1;
  2798. saa.arts = CGTownInstance::merchantArtifacts;
  2799. }
  2800. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m->o)) //black market
  2801. {
  2802. saa.id = bm->id.getNum();
  2803. saa.arts = bm->artifacts;
  2804. }
  2805. else
  2806. COMPLAIN_RET("Wrong marktet...");
  2807. bool found = false;
  2808. for(const CArtifact *&art : saa.arts)
  2809. {
  2810. if(art && art->id == aid)
  2811. {
  2812. art = nullptr;
  2813. found = true;
  2814. break;
  2815. }
  2816. }
  2817. if(!found)
  2818. COMPLAIN_RET("Cannot find selected artifact on the list");
  2819. sendAndApply(&saa);
  2820. giveHeroNewArtifact(h, VLC->arth->artifacts[aid], ArtifactPosition::FIRST_AVAILABLE);
  2821. return true;
  2822. }
  2823. bool CGameHandler::sellArtifact( const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, Res::ERes rid )
  2824. {
  2825. const CArtifactInstance *art = h->getArtByInstanceId(aid);
  2826. if(!art)
  2827. COMPLAIN_RET("There is no artifact to sell!");
  2828. if(!art->artType->isTradable())
  2829. COMPLAIN_RET("Cannot sell a war machine or spellbook!");
  2830. int resVal = 0, dump = 1;
  2831. m->getOffer(art->artType->id, rid, dump, resVal, EMarketMode::ARTIFACT_RESOURCE);
  2832. removeArtifact(ArtifactLocation(h, h->getArtPos(art)));
  2833. giveResource(h->tempOwner, rid, resVal);
  2834. return true;
  2835. }
  2836. //void CGameHandler::lootArtifacts (TArtHolder source, TArtHolder dest, std::vector<ui32> &arts)
  2837. //{
  2838. // //const CGHeroInstance * h1 = dynamic_cast<CGHeroInstance *> source;
  2839. // //auto s = boost::apply_visitor(GetArtifactSetPtr(), source);
  2840. // {
  2841. // }
  2842. //}
  2843. bool CGameHandler::buySecSkill( const IMarket *m, const CGHeroInstance *h, SecondarySkill skill)
  2844. {
  2845. if (!h)
  2846. COMPLAIN_RET("You need hero to buy a skill!");
  2847. if (h->getSecSkillLevel(SecondarySkill(skill)))
  2848. COMPLAIN_RET("Hero already know this skill");
  2849. if (!h->canLearnSkill())
  2850. COMPLAIN_RET("Hero can't learn any more skills");
  2851. if (h->type->heroClass->secSkillProbability.at(skill)==0)//can't learn this skill (like necromancy for most of non-necros)
  2852. COMPLAIN_RET("The hero can't learn this skill!");
  2853. if(!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_SKILL), skill))
  2854. COMPLAIN_RET("That skill is unavailable!");
  2855. if(getResource(h->tempOwner, Res::GOLD) < 2000)//TODO: remove hardcoded resource\summ?
  2856. COMPLAIN_RET("You can't afford to buy this skill");
  2857. SetResource sr;
  2858. sr.player = h->tempOwner;
  2859. sr.resid = Res::GOLD;
  2860. sr.val = getResource(h->tempOwner, Res::GOLD) - 2000;
  2861. sendAndApply(&sr);
  2862. changeSecSkill(h, skill, 1, true);
  2863. return true;
  2864. }
  2865. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2)
  2866. {
  2867. int r1 = gs->getPlayer(player)->resources.at(id1),
  2868. r2 = gs->getPlayer(player)->resources.at(id2);
  2869. vstd::amin(val, r1); //can't trade more resources than have
  2870. int b1, b2; //base quantities for trade
  2871. market->getOffer(id1, id2, b1, b2, EMarketMode::RESOURCE_RESOURCE);
  2872. int units = val / b1; //how many base quantities we trade
  2873. if(val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2874. {
  2875. //TODO: complain?
  2876. assert(0);
  2877. }
  2878. SetResource sr;
  2879. sr.player = player;
  2880. sr.resid = static_cast<Res::ERes>(id1);
  2881. sr.val = r1 - b1 * units;
  2882. sendAndApply(&sr);
  2883. sr.resid = static_cast<Res::ERes>(id2);
  2884. sr.val = r2 + b2 * units;
  2885. sendAndApply(&sr);
  2886. return true;
  2887. }
  2888. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, Res::ERes resourceID)
  2889. {
  2890. if(!vstd::contains(hero->Slots(), slot))
  2891. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  2892. const CStackInstance &s = hero->getStack(slot);
  2893. if( s.count < count //can't sell more creatures than have
  2894. || (hero->stacksCount() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack
  2895. {
  2896. COMPLAIN_RET("Not enough creatures in army!");
  2897. }
  2898. int b1, b2; //base quantities for trade
  2899. market->getOffer(s.type->idNumber, resourceID, b1, b2, EMarketMode::CREATURE_RESOURCE);
  2900. int units = count / b1; //how many base quantities we trade
  2901. if(count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2902. {
  2903. //TODO: complain?
  2904. assert(0);
  2905. }
  2906. changeStackCount(StackLocation(hero, slot), -count);
  2907. SetResource sr;
  2908. sr.player = hero->tempOwner;
  2909. sr.resid = resourceID;
  2910. sr.val = getResource(hero->tempOwner, resourceID) + b2 * units;
  2911. sendAndApply(&sr);
  2912. return true;
  2913. }
  2914. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot)
  2915. {
  2916. const CArmedInstance *army = nullptr;
  2917. if (hero)
  2918. army = hero;
  2919. else
  2920. army = dynamic_cast<const CGTownInstance *>(market->o);
  2921. if (!army)
  2922. COMPLAIN_RET("Incorrect call to transform in undead!");
  2923. if(!army->hasStackAtSlot(slot))
  2924. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  2925. const CStackInstance &s = army->getStack(slot);
  2926. //resulting creature - bone dragons or skeletons
  2927. CreatureID resCreature = CreatureID::SKELETON;
  2928. if(s.hasBonusOfType(Bonus::DRAGON_NATURE)
  2929. || (s.getCreatureID() == CreatureID::HYDRA)
  2930. || (s.getCreatureID() == CreatureID::CHAOS_HYDRA))
  2931. resCreature = CreatureID::BONE_DRAGON;
  2932. changeStackType(StackLocation(army, slot), resCreature.toCreature());
  2933. return true;
  2934. }
  2935. bool CGameHandler::sendResources(ui32 val, PlayerColor player, Res::ERes r1, PlayerColor r2)
  2936. {
  2937. const PlayerState *p2 = gs->getPlayer(r2, false);
  2938. if(!p2 || p2->status != EPlayerStatus::INGAME)
  2939. {
  2940. complain("Dest player must be in game!");
  2941. return false;
  2942. }
  2943. si32 curRes1 = gs->getPlayer(player)->resources.at(r1),
  2944. curRes2 = gs->getPlayer(r2)->resources.at(r1);
  2945. val = std::min(si32(val),curRes1);
  2946. SetResource sr;
  2947. sr.player = player;
  2948. sr.resid = r1;
  2949. sr.val = curRes1 - val;
  2950. sendAndApply(&sr);
  2951. sr.player = r2;
  2952. sr.val = curRes2 + val;
  2953. sendAndApply(&sr);
  2954. return true;
  2955. }
  2956. bool CGameHandler::setFormation( ObjectInstanceID hid, ui8 formation )
  2957. {
  2958. gs->getHero(hid)-> formation = formation;
  2959. return true;
  2960. }
  2961. bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, PlayerColor player)
  2962. {
  2963. const PlayerState *p = gs->getPlayer(player);
  2964. const CGTownInstance *t = gs->getTown(obj->id);
  2965. //common preconditions
  2966. // if( (p->resources.at(Res::GOLD)<GOLD_NEEDED && complain("Not enough gold for buying hero!"))
  2967. // || (getHeroCount(player, false) >= GameConstants::MAX_HEROES_PER_PLAYER && complain("Cannot hire hero, only 8 wandering heroes are allowed!")))
  2968. if((p->resources.at(Res::GOLD) < GameConstants::HERO_GOLD_COST && complain("Not enough gold for buying hero!"))
  2969. || ((!t) && (getHeroCount(player, false) >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER && complain("Cannot hire hero, too many wandering heroes already!")))
  2970. || ((t) && (getHeroCount(player, true) >= VLC->modh->settings.MAX_HEROES_AVAILABLE_PER_PLAYER && complain("Cannot hire hero, too many heroes garrizoned and wandering already!"))) )
  2971. {
  2972. return false;
  2973. }
  2974. if(t) //tavern in town
  2975. {
  2976. if((!t->hasBuilt(BuildingID::TAVERN) && complain("No tavern!"))
  2977. || (t->visitingHero && complain("There is visiting hero - no place!")))
  2978. {
  2979. return false;
  2980. }
  2981. }
  2982. else if(obj->ID == Obj::TAVERN)
  2983. {
  2984. if(getTile(obj->visitablePos())->visitableObjects.back() != obj && complain("Tavern entry must be unoccupied!"))
  2985. {
  2986. return false;
  2987. }
  2988. }
  2989. const CGHeroInstance *nh = p->availableHeroes.at(hid);
  2990. if (!nh)
  2991. {
  2992. complain ("Hero is not available for hiring!");
  2993. return false;
  2994. }
  2995. HeroRecruited hr;
  2996. hr.tid = obj->id;
  2997. hr.hid = nh->subID;
  2998. hr.player = player;
  2999. hr.tile = obj->visitablePos() + nh->getVisitableOffset();
  3000. sendAndApply(&hr);
  3001. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = gs->unusedHeroesFromPool();
  3002. const CGHeroInstance *theOtherHero = p->availableHeroes.at(!hid);
  3003. const CGHeroInstance *newHero = nullptr;
  3004. if (theOtherHero) //on XXL maps all heroes can be imprisoned :(
  3005. {
  3006. newHero = gs->hpool.pickHeroFor(false, player, getNativeTown(player), pool, gs->getRandomGenerator(), theOtherHero->type->heroClass);
  3007. }
  3008. SetAvailableHeroes sah;
  3009. sah.player = player;
  3010. if(newHero)
  3011. {
  3012. sah.hid[hid] = newHero->subID;
  3013. sah.army[hid].clear();
  3014. sah.army[hid].setCreature(SlotID(0), newHero->type->initialArmy[0].creature, 1);
  3015. }
  3016. else
  3017. {
  3018. sah.hid[hid] = -1;
  3019. }
  3020. sah.hid[!hid] = theOtherHero ? theOtherHero->subID : -1;
  3021. sendAndApply(&sah);
  3022. SetResource sr;
  3023. sr.player = player;
  3024. sr.resid = Res::GOLD;
  3025. sr.val = p->resources.at(Res::GOLD) - GameConstants::HERO_GOLD_COST;
  3026. sendAndApply(&sr);
  3027. if(t)
  3028. {
  3029. vistiCastleObjects (t, nh);
  3030. giveSpells (t,nh);
  3031. }
  3032. return true;
  3033. }
  3034. bool CGameHandler::queryReply(QueryID qid, ui32 answer, PlayerColor player)
  3035. {
  3036. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3037. logGlobal->traceStream() << boost::format("Player %s attempts answering query %d with answer %d") % player % qid % answer;
  3038. auto topQuery = queries.topQuery(player);
  3039. COMPLAIN_RET_FALSE_IF(!topQuery, "This player doesn't have any queries!");
  3040. COMPLAIN_RET_FALSE_IF(topQuery->queryID != qid, "This player top query has different ID!");
  3041. COMPLAIN_RET_FALSE_IF(!topQuery->endsByPlayerAnswer(), "This query cannot be ended by player's answer!");
  3042. if(auto dialogQuery = std::dynamic_pointer_cast<CDialogQuery>(topQuery))
  3043. dialogQuery->answer = answer;
  3044. queries.popQuery(topQuery);
  3045. return true;
  3046. }
  3047. static EndAction end_action;
  3048. void CGameHandler::updateDrawbridgeState()
  3049. {
  3050. BattleDrawbridgeStateChanged db;
  3051. db.state = gs->curB->si.drawbridgeState;
  3052. if(gs->curB->si.wallState[EWallPart::GATE] == EWallState::DESTROYED)
  3053. {
  3054. db.state = EDrawbridgeState::LOWERED_BORKED;
  3055. }
  3056. else if(db.state == EDrawbridgeState::LOWERED)
  3057. {
  3058. if((gs->curB->town->subID != ETownType::FORTRESS || !gs->curB->battleGetStackByPos(BattleHex(94), false)) &&
  3059. !gs->curB->battleGetStackByPos(BattleHex(95), false) &&
  3060. !gs->curB->battleGetStackByPos(BattleHex(96), false))
  3061. {
  3062. db.state = EDrawbridgeState::RAISED;
  3063. }
  3064. }
  3065. else if(gs->curB->battleGetStackByPos(BattleHex(94), false))
  3066. db.state = EDrawbridgeState::RAISED_BLOCKED;
  3067. else
  3068. db.state = EDrawbridgeState::RAISED;
  3069. if(db.state != gs->curB->si.drawbridgeState)
  3070. sendAndApply(&db);
  3071. }
  3072. bool CGameHandler::makeBattleAction( BattleAction &ba )
  3073. {
  3074. bool ok = true;
  3075. const CStack *stack = battleGetStackByID(ba.stackNumber); //may be nullptr if action is not about stack
  3076. const CStack *destinationStack = ba.actionType == Battle::WALK_AND_ATTACK ? gs->curB->battleGetStackByPos(ba.additionalInfo)
  3077. : ba.actionType == Battle::SHOOT ? gs->curB->battleGetStackByPos(ba.destinationTile)
  3078. : nullptr;
  3079. const bool isAboutActiveStack = stack && (stack == battleActiveStack());
  3080. logGlobal->traceStream() << boost::format(
  3081. "Making action: type=%d; side=%d; stack=%s; dst=%s; additionalInfo=%d; stackAtDst=%s")
  3082. % ba.actionType % (int)ba.side % (stack ? stack->getName() : std::string("none"))
  3083. % ba.destinationTile % ba.additionalInfo % (destinationStack ? destinationStack->getName() : std::string("none"));
  3084. switch(ba.actionType)
  3085. {
  3086. case Battle::WALK: //walk
  3087. case Battle::DEFEND: //defend
  3088. case Battle::WAIT: //wait
  3089. case Battle::WALK_AND_ATTACK: //walk or attack
  3090. case Battle::SHOOT: //shoot
  3091. case Battle::CATAPULT: //catapult
  3092. case Battle::STACK_HEAL: //healing with First Aid Tent
  3093. case Battle::DAEMON_SUMMONING:
  3094. case Battle::MONSTER_SPELL:
  3095. if(!stack)
  3096. {
  3097. complain("No such stack!");
  3098. return false;
  3099. }
  3100. if(!stack->alive())
  3101. {
  3102. complain("This stack is dead: " + stack->nodeName());
  3103. return false;
  3104. }
  3105. if(battleTacticDist())
  3106. {
  3107. if(stack && !stack->attackerOwned != battleGetTacticsSide())
  3108. {
  3109. complain("This is not a stack of side that has tactics!");
  3110. return false;
  3111. }
  3112. }
  3113. else if(!isAboutActiveStack)
  3114. {
  3115. complain("Action has to be about active stack!");
  3116. return false;
  3117. }
  3118. }
  3119. switch(ba.actionType)
  3120. {
  3121. case Battle::END_TACTIC_PHASE: //wait
  3122. case Battle::BAD_MORALE:
  3123. case Battle::NO_ACTION:
  3124. {
  3125. StartAction start_action(ba);
  3126. sendAndApply(&start_action);
  3127. sendAndApply(&end_action);
  3128. break;
  3129. }
  3130. case Battle::WALK:
  3131. {
  3132. StartAction start_action(ba);
  3133. sendAndApply(&start_action); //start movement
  3134. int walkedTiles = moveStack(ba.stackNumber,ba.destinationTile); //move
  3135. if(!walkedTiles)
  3136. complain("Stack failed movement!");
  3137. sendAndApply(&end_action);
  3138. break;
  3139. }
  3140. case Battle::DEFEND:
  3141. {
  3142. //defensive stance //TODO: remove this bonus when stack becomes active
  3143. SetStackEffect sse;
  3144. sse.effect.push_back( Bonus(Bonus::STACK_GETS_TURN, Bonus::PRIMARY_SKILL, Bonus::OTHER, 20, -1, PrimarySkill::DEFENSE, Bonus::PERCENT_TO_ALL) );
  3145. sse.effect.push_back( Bonus(Bonus::STACK_GETS_TURN, Bonus::PRIMARY_SKILL, Bonus::OTHER, gs->curB->battleGetStackByID(ba.stackNumber)->valOfBonuses(Bonus::DEFENSIVE_STANCE),
  3146. -1, PrimarySkill::DEFENSE, Bonus::ADDITIVE_VALUE));
  3147. sse.stacks.push_back(ba.stackNumber);
  3148. sendAndApply(&sse);
  3149. //don't break - we share code with next case
  3150. }
  3151. case Battle::WAIT:
  3152. {
  3153. StartAction start_action(ba);
  3154. sendAndApply(&start_action);
  3155. sendAndApply(&end_action);
  3156. break;
  3157. }
  3158. case Battle::RETREAT: //retreat/flee
  3159. {
  3160. if(!gs->curB->battleCanFlee(gs->curB->sides.at(ba.side).color))
  3161. complain("Cannot retreat!");
  3162. else
  3163. setBattleResult(BattleResult::ESCAPE, !ba.side); //surrendering side loses
  3164. break;
  3165. }
  3166. case Battle::SURRENDER:
  3167. {
  3168. PlayerColor player = gs->curB->sides.at(ba.side).color;
  3169. int cost = gs->curB->battleGetSurrenderCost(player);
  3170. if(cost < 0)
  3171. complain("Cannot surrender!");
  3172. else if(getResource(player, Res::GOLD) < cost)
  3173. complain("Not enough gold to surrender!");
  3174. else
  3175. {
  3176. giveResource(player, Res::GOLD, -cost);
  3177. setBattleResult(BattleResult::SURRENDER, !ba.side); //surrendering side loses
  3178. }
  3179. break;
  3180. }
  3181. case Battle::WALK_AND_ATTACK: //walk or attack
  3182. {
  3183. StartAction start_action(ba);
  3184. sendAndApply(&start_action); //start movement and attack
  3185. if(!stack || !destinationStack)
  3186. {
  3187. sendAndApply(&end_action);
  3188. break;
  3189. }
  3190. BattleHex startingPos = stack->position;
  3191. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  3192. logGlobal->traceStream() << stack->nodeName() << " will attack " << destinationStack->nodeName();
  3193. if(stack->position != ba.destinationTile //we wasn't able to reach destination tile
  3194. && !(stack->doubleWide()
  3195. && ( stack->position == ba.destinationTile + (stack->attackerOwned ? +1 : -1 ) )
  3196. ) //nor occupy specified hex
  3197. )
  3198. {
  3199. std::string problem = "We cannot move this stack to its destination " + stack->getCreature()->namePl;
  3200. logGlobal->warnStream() << problem;
  3201. complain(problem);
  3202. ok = false;
  3203. sendAndApply(&end_action);
  3204. break;
  3205. }
  3206. if(destinationStack && stack && stack->ID == destinationStack->ID) //we should just move, it will be handled by following check
  3207. {
  3208. destinationStack = nullptr;
  3209. }
  3210. if(!destinationStack)
  3211. {
  3212. complain(boost::str(boost::format("walk and attack error: no stack at additionalInfo tile (%d)!\n") % ba.additionalInfo));
  3213. ok = false;
  3214. sendAndApply(&end_action);
  3215. break;
  3216. }
  3217. if( !CStack::isMeleeAttackPossible(stack, destinationStack) )
  3218. {
  3219. complain("Attack cannot be performed!");
  3220. sendAndApply(&end_action);
  3221. ok = false;
  3222. break;
  3223. }
  3224. //attack
  3225. int totalAttacks = 1 + stack->getBonuses(Selector::type (Bonus::ADDITIONAL_ATTACK),
  3226. (Selector::effectRange(Bonus::NO_LIMIT).Or(Selector::effectRange(Bonus::ONLY_MELEE_FIGHT))))->totalValue(); //all unspicified attacks + melee attacks
  3227. for (int i = 0; i < totalAttacks; ++i)
  3228. {
  3229. if (stack &&
  3230. stack->alive() && //move can cause death, eg. by walking into the moat
  3231. destinationStack->alive())
  3232. {
  3233. BattleAttack bat;
  3234. prepareAttack(bat, stack, destinationStack, (i ? 0 : distance), ba.additionalInfo); //no distance travelled on second attack
  3235. //prepareAttack(bat, stack, stackAtEnd, 0, ba.additionalInfo);
  3236. handleAttackBeforeCasting(bat); //only before first attack
  3237. sendAndApply(&bat);
  3238. handleAfterAttackCasting(bat);
  3239. }
  3240. //counterattack
  3241. if (destinationStack
  3242. && !stack->hasBonusOfType(Bonus::BLOCKS_RETALIATION)
  3243. && destinationStack->ableToRetaliate()
  3244. && stack->alive()) //attacker may have died (fire shield)
  3245. {
  3246. BattleAttack bat;
  3247. prepareAttack(bat, destinationStack, stack, 0, stack->position);
  3248. bat.flags |= BattleAttack::COUNTER;
  3249. sendAndApply(&bat);
  3250. handleAfterAttackCasting(bat);
  3251. }
  3252. }
  3253. //return
  3254. if(stack->hasBonusOfType(Bonus::RETURN_AFTER_STRIKE) && startingPos != stack->position && stack->alive())
  3255. {
  3256. moveStack(ba.stackNumber, startingPos);
  3257. //NOTE: curStack->ID == ba.stackNumber (rev 1431)
  3258. }
  3259. sendAndApply(&end_action);
  3260. break;
  3261. }
  3262. case Battle::SHOOT:
  3263. {
  3264. if( !gs->curB->battleCanShoot(stack, ba.destinationTile) )
  3265. {
  3266. complain("Cannot shoot!");
  3267. break;
  3268. }
  3269. StartAction start_action(ba);
  3270. sendAndApply(&start_action); //start shooting
  3271. {
  3272. BattleAttack bat;
  3273. bat.flags |= BattleAttack::SHOT;
  3274. prepareAttack(bat, stack, destinationStack, 0, ba.destinationTile);
  3275. handleAttackBeforeCasting(bat);
  3276. sendAndApply(&bat);
  3277. handleAfterAttackCasting(bat);
  3278. }
  3279. //second shot for ballista, only if hero has advanced artillery
  3280. const CGHeroInstance * attackingHero = gs->curB->battleGetFightingHero(ba.side);
  3281. if( destinationStack->alive()
  3282. && (stack->getCreature()->idNumber == CreatureID::BALLISTA)
  3283. && (attackingHero->getSecSkillLevel(SecondarySkill::ARTILLERY) >= SecSkillLevel::ADVANCED)
  3284. )
  3285. {
  3286. BattleAttack bat2;
  3287. bat2.flags |= BattleAttack::SHOT;
  3288. prepareAttack(bat2, stack, destinationStack, 0, ba.destinationTile);
  3289. sendAndApply(&bat2);
  3290. }
  3291. //allow more than one additional attack
  3292. int additionalAttacks = stack->getBonuses(Selector::type (Bonus::ADDITIONAL_ATTACK),
  3293. (Selector::effectRange(Bonus::NO_LIMIT).Or(Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT))))->totalValue();
  3294. for (int i = 0; i < additionalAttacks; ++i)
  3295. {
  3296. if(
  3297. stack->alive()
  3298. && destinationStack->alive()
  3299. && stack->shots
  3300. )
  3301. {
  3302. BattleAttack bat;
  3303. bat.flags |= BattleAttack::SHOT;
  3304. prepareAttack(bat, stack, destinationStack, 0, ba.destinationTile);
  3305. sendAndApply(&bat);
  3306. handleAfterAttackCasting(bat);
  3307. }
  3308. }
  3309. sendAndApply(&end_action);
  3310. break;
  3311. }
  3312. case Battle::CATAPULT:
  3313. {
  3314. auto getCatapultHitChance = [&](EWallPart::EWallPart part, const CHeroHandler::SBallisticsLevelInfo & sbi) -> int
  3315. {
  3316. switch(part)
  3317. {
  3318. case EWallPart::GATE:
  3319. return sbi.gate;
  3320. case EWallPart::KEEP:
  3321. return sbi.keep;
  3322. case EWallPart::BOTTOM_TOWER:
  3323. case EWallPart::UPPER_TOWER:
  3324. return sbi.tower;
  3325. case EWallPart::BOTTOM_WALL:
  3326. case EWallPart::BELOW_GATE:
  3327. case EWallPart::OVER_GATE:
  3328. case EWallPart::UPPER_WALL:
  3329. return sbi.wall;
  3330. default:
  3331. return 0;
  3332. }
  3333. };
  3334. StartAction start_action(ba);
  3335. sendAndApply(&start_action);
  3336. auto onExit = vstd::makeScopeGuard([&]{ sendAndApply(&end_action); }); //if we started than we have to finish
  3337. const CGHeroInstance * attackingHero = gs->curB->battleGetFightingHero(ba.side);
  3338. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics.at(attackingHero->getSecSkillLevel(SecondarySkill::BALLISTICS));
  3339. auto wallPart = gs->curB->battleHexToWallPart(ba.destinationTile);
  3340. if(!gs->curB->isWallPartPotentiallyAttackable(wallPart))
  3341. {
  3342. complain("catapult tried to attack non-catapultable hex!");
  3343. break;
  3344. }
  3345. //in successive iterations damage is dealt but not yet subtracted from wall's HPs
  3346. auto &currentHP = gs->curB->si.wallState;
  3347. if (currentHP.at(wallPart) == EWallState::DESTROYED || currentHP.at(wallPart) == EWallState::NONE)
  3348. {
  3349. complain("catapult tried to attack already destroyed wall part!");
  3350. break;
  3351. }
  3352. for(int g=0; g<sbi.shots; ++g)
  3353. {
  3354. bool hitSuccessfull = false;
  3355. auto attackedPart = wallPart;
  3356. do // catapult has chance to attack desired target. Othervice - attacks randomly
  3357. {
  3358. if(currentHP.at(attackedPart) != EWallState::DESTROYED && // this part can be hit
  3359. currentHP.at(attackedPart) != EWallState::NONE &&
  3360. gs->getRandomGenerator().nextInt(99) < getCatapultHitChance(attackedPart, sbi))//hit is successful
  3361. {
  3362. hitSuccessfull = true;
  3363. }
  3364. else // select new target
  3365. {
  3366. std::vector<EWallPart::EWallPart> allowedTargets;
  3367. for (size_t i=0; i< currentHP.size(); i++)
  3368. {
  3369. if (currentHP.at(i) != EWallState::DESTROYED &&
  3370. currentHP.at(i) != EWallState::NONE)
  3371. allowedTargets.push_back(EWallPart::EWallPart(i));
  3372. }
  3373. if (allowedTargets.empty())
  3374. break;
  3375. attackedPart = *RandomGeneratorUtil::nextItem(allowedTargets, gs->getRandomGenerator());
  3376. }
  3377. }
  3378. while (!hitSuccessfull);
  3379. if (!hitSuccessfull) // break triggered - no target to shoot at
  3380. break;
  3381. CatapultAttack ca; //package for clients
  3382. CatapultAttack::AttackInfo attack;
  3383. attack.attackedPart = attackedPart;
  3384. attack.destinationTile = ba.destinationTile;
  3385. attack.damageDealt = 0;
  3386. int dmgChance[] = { sbi.noDmg, sbi.oneDmg, sbi.twoDmg }; //dmgChance[i] - chance for doing i dmg when hit is successful
  3387. int dmgRand = gs->getRandomGenerator().nextInt(99);
  3388. //accumulating dmgChance
  3389. dmgChance[1] += dmgChance[0];
  3390. dmgChance[2] += dmgChance[1];
  3391. //calculating dealt damage
  3392. for(int damage = 0; damage < ARRAY_COUNT(dmgChance); ++damage)
  3393. {
  3394. if(dmgRand <= dmgChance[damage])
  3395. {
  3396. attack.damageDealt = damage;
  3397. break;
  3398. }
  3399. }
  3400. // attacked tile may have changed - update destination
  3401. attack.destinationTile = gs->curB->wallPartToBattleHex(EWallPart::EWallPart(attack.attackedPart));
  3402. logGlobal->traceStream() << "Catapult attacks " << (int)attack.attackedPart
  3403. << " dealing " << (int)attack.damageDealt << " damage";
  3404. //removing creatures in turrets / keep if one is destroyed
  3405. if(attack.damageDealt > 0 && (attackedPart == EWallPart::KEEP ||
  3406. attackedPart == EWallPart::BOTTOM_TOWER || attackedPart == EWallPart::UPPER_TOWER))
  3407. {
  3408. int posRemove = -1;
  3409. switch(attackedPart)
  3410. {
  3411. case EWallPart::KEEP:
  3412. posRemove = -2;
  3413. break;
  3414. case EWallPart::BOTTOM_TOWER:
  3415. posRemove = -3;
  3416. break;
  3417. case EWallPart::UPPER_TOWER:
  3418. posRemove = -4;
  3419. break;
  3420. }
  3421. BattleStacksRemoved bsr;
  3422. for(auto & elem : gs->curB->stacks)
  3423. {
  3424. if(elem->position == posRemove)
  3425. {
  3426. bsr.stackIDs.insert( elem->ID );
  3427. break;
  3428. }
  3429. }
  3430. sendAndApply(&bsr);
  3431. }
  3432. ca.attacker = ba.stackNumber;
  3433. ca.attackedParts.push_back(attack);
  3434. sendAndApply(&ca);
  3435. }
  3436. //finish by scope guard
  3437. break;
  3438. }
  3439. case Battle::STACK_HEAL: //healing with First Aid Tent
  3440. {
  3441. StartAction start_action(ba);
  3442. sendAndApply(&start_action);
  3443. const CGHeroInstance * attackingHero = gs->curB->battleGetFightingHero(ba.side);
  3444. const CStack *healer = gs->curB->battleGetStackByID(ba.stackNumber),
  3445. *destStack = gs->curB->battleGetStackByPos(ba.destinationTile);
  3446. ui32 healed = 0;
  3447. if(healer == nullptr || destStack == nullptr || !healer->hasBonusOfType(Bonus::HEALER))
  3448. {
  3449. complain("There is either no healer, no destination, or healer cannot heal :P");
  3450. }
  3451. else
  3452. {
  3453. ui32 maxiumHeal = healer->count * std::max(10, attackingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::FIRST_AID));
  3454. healed = destStack->calculateHealedHealthPoints(maxiumHeal, false);
  3455. }
  3456. if(healed == 0)
  3457. {
  3458. //nothing to heal.. should we complain?
  3459. }
  3460. else
  3461. {
  3462. StacksHealedOrResurrected shr;
  3463. shr.lifeDrain = false;
  3464. shr.tentHealing = true;
  3465. shr.drainedFrom = ba.stackNumber;
  3466. StacksHealedOrResurrected::HealInfo hi;
  3467. hi.healedHP = healed;
  3468. hi.lowLevelResurrection = false;
  3469. hi.stackID = destStack->ID;
  3470. shr.healedStacks.push_back(hi);
  3471. sendAndApply(&shr);
  3472. }
  3473. sendAndApply(&end_action);
  3474. break;
  3475. }
  3476. case Battle::DAEMON_SUMMONING:
  3477. //TODO: From Strategija:
  3478. //Summon Demon is a level 2 spell.
  3479. {
  3480. StartAction start_action(ba);
  3481. sendAndApply(&start_action);
  3482. const CStack *summoner = gs->curB->battleGetStackByID(ba.stackNumber),
  3483. *destStack = gs->curB->battleGetStackByPos(ba.destinationTile, false);
  3484. BattleStackAdded bsa;
  3485. bsa.attacker = summoner->attackerOwned;
  3486. bsa.creID = CreatureID(summoner->getBonusLocalFirst(Selector::type(Bonus::DAEMON_SUMMONING))->subtype); //in case summoner can summon more than one type of monsters... scream!
  3487. ui64 risedHp = summoner->count * summoner->valOfBonuses(Bonus::DAEMON_SUMMONING, bsa.creID.toEnum());
  3488. ui64 targetHealth = destStack->getCreature()->MaxHealth() * destStack->baseAmount;
  3489. ui64 canRiseHp = std::min(targetHealth, risedHp);
  3490. ui32 canRiseAmount = canRiseHp / VLC->creh->creatures.at(bsa.creID)->MaxHealth();
  3491. bsa.amount = std::min(canRiseAmount, destStack->baseAmount);
  3492. bsa.pos = gs->curB->getAvaliableHex(bsa.creID, bsa.attacker, destStack->position);
  3493. bsa.summoned = false;
  3494. if (bsa.amount) //there's rare possibility single creature cannot rise desired type
  3495. {
  3496. BattleStacksRemoved bsr; //remove body
  3497. bsr.stackIDs.insert(destStack->ID);
  3498. sendAndApply(&bsr);
  3499. sendAndApply(&bsa);
  3500. BattleSetStackProperty ssp;
  3501. ssp.stackID = ba.stackNumber;
  3502. ssp.which = BattleSetStackProperty::CASTS; //reduce number of casts
  3503. ssp.val = -1;
  3504. ssp.absolute = false;
  3505. sendAndApply(&ssp);
  3506. }
  3507. sendAndApply(&end_action);
  3508. break;
  3509. }
  3510. case Battle::MONSTER_SPELL:
  3511. {
  3512. StartAction start_action(ba);
  3513. sendAndApply(&start_action);
  3514. const CStack * stack = gs->curB->battleGetStackByID(ba.stackNumber);
  3515. SpellID spellID = SpellID(ba.additionalInfo);
  3516. BattleHex destination(ba.destinationTile);
  3517. const Bonus *randSpellcaster = stack->getBonusLocalFirst(Selector::type(Bonus::RANDOM_SPELLCASTER));
  3518. const Bonus * spellcaster = stack->getBonusLocalFirst(Selector::typeSubtype(Bonus::SPELLCASTER, spellID));
  3519. //TODO special bonus for genies ability
  3520. if(randSpellcaster && battleGetRandomStackSpell(stack, CBattleInfoCallback::RANDOM_AIMED) < 0)
  3521. spellID = battleGetRandomStackSpell(stack, CBattleInfoCallback::RANDOM_GENIE);
  3522. if(spellID < 0)
  3523. complain("That stack can't cast spells!");
  3524. else
  3525. {
  3526. const CSpell * spell = SpellID(spellID).toSpell();
  3527. BattleSpellCastParameters parameters(gs->curB, stack, spell);
  3528. parameters.spellLvl = 0;
  3529. if (spellcaster)
  3530. vstd::amax(parameters.spellLvl, spellcaster->val);
  3531. if (randSpellcaster)
  3532. vstd::amax(parameters.spellLvl, randSpellcaster->val);
  3533. vstd::amin (parameters.spellLvl, 3);
  3534. parameters.effectLevel = parameters.spellLvl;
  3535. parameters.mode = ECastingMode::CREATURE_ACTIVE_CASTING;
  3536. parameters.aimToHex(destination);//todo: allow multiple destinations
  3537. parameters.selectedStack = nullptr;
  3538. spell->battleCast(spellEnv, parameters);
  3539. }
  3540. sendAndApply(&end_action);
  3541. break;
  3542. }
  3543. }
  3544. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  3545. battleMadeAction.setn(true);
  3546. return ok;
  3547. }
  3548. void CGameHandler::playerMessage( PlayerColor player, const std::string &message, ObjectInstanceID currObj )
  3549. {
  3550. bool cheated=true;
  3551. PlayerMessage temp_message(player, message, ObjectInstanceID(-1)); // don't inform other client on selected object
  3552. sendAndApply(&temp_message);
  3553. if(message == "vcmiistari") //give all spells and 999 mana
  3554. {
  3555. SetMana sm;
  3556. GiveBonus giveBonus(GiveBonus::HERO);
  3557. CGHeroInstance *h = gs->getHero(currObj);
  3558. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  3559. sm.hid = h->id;
  3560. giveBonus.id = h->id.getNum();
  3561. //give all spells with bonus (to allow banned spells)
  3562. giveBonus.bonus = Bonus(Bonus::PERMANENT, Bonus::SPELLS_OF_LEVEL, Bonus::OTHER, 0, 0);
  3563. //start with level 0 to skip abilities
  3564. for(int level = 1; level <= GameConstants::SPELL_LEVELS; level++)
  3565. {
  3566. giveBonus.bonus.subtype = level;
  3567. sendAndApply(&giveBonus);
  3568. }
  3569. //give mana
  3570. sm.val = 999;
  3571. sm.absolute = true;
  3572. if(!h->hasSpellbook()) //hero doesn't have spellbook
  3573. giveHeroNewArtifact(h, VLC->arth->artifacts[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK); //give spellbook
  3574. sendAndApply(&sm);
  3575. }
  3576. else if (message == "vcmiarmenelos") //build all buildings in selected town
  3577. {
  3578. CGHeroInstance *hero = gs->getHero(currObj);
  3579. CGTownInstance *town;
  3580. if (hero)
  3581. town = hero->visitedTown;
  3582. else
  3583. town = gs->getTown(currObj);
  3584. if (town)
  3585. {
  3586. for (auto & build : town->town->buildings)
  3587. {
  3588. if (!town->hasBuilt(build.first)
  3589. && !build.second->Name().empty()
  3590. && build.first != BuildingID::SHIP)
  3591. {
  3592. buildStructure(town->id, build.first, true);
  3593. }
  3594. }
  3595. }
  3596. }
  3597. else if(message == "vcmiainur") //gives 5 archangels into each slot
  3598. {
  3599. CGHeroInstance *hero = gs->getHero(currObj);
  3600. const CCreature *archangel = VLC->creh->creatures.at(13);
  3601. if(!hero) return;
  3602. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  3603. if(!hero->hasStackAtSlot(SlotID(i)))
  3604. insertNewStack(StackLocation(hero, SlotID(i)), archangel, 5);
  3605. }
  3606. else if(message == "vcmiangband") //gives 10 black knight into each slot
  3607. {
  3608. CGHeroInstance *hero = gs->getHero(currObj);
  3609. const CCreature *blackKnight = VLC->creh->creatures.at(66);
  3610. if(!hero) return;
  3611. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  3612. if(!hero->hasStackAtSlot(SlotID(i)))
  3613. insertNewStack(StackLocation(hero, SlotID(i)), blackKnight, 10);
  3614. }
  3615. else if(message == "vcmiglaurung") //gives 5000 crystal dragons into each slot
  3616. {
  3617. CGHeroInstance *hero = gs->getHero(currObj);
  3618. const CCreature *crystalDragon = VLC->creh->creatures.at(133);
  3619. if(!hero) return;
  3620. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  3621. if(!hero->hasStackAtSlot(SlotID(i)))
  3622. insertNewStack(StackLocation(hero, SlotID(i)), crystalDragon, 5000);
  3623. }
  3624. else if(message == "vcminoldor") //all war machines
  3625. {
  3626. CGHeroInstance *hero = gs->getHero(currObj);
  3627. if(!hero) return;
  3628. if(!hero->getArt(ArtifactPosition::MACH1))
  3629. giveHeroNewArtifact(hero, VLC->arth->artifacts[ArtifactID::BALLISTA], ArtifactPosition::MACH1);
  3630. if(!hero->getArt(ArtifactPosition::MACH2))
  3631. giveHeroNewArtifact(hero, VLC->arth->artifacts[ArtifactID::AMMO_CART], ArtifactPosition::MACH2);
  3632. if(!hero->getArt(ArtifactPosition::MACH3))
  3633. giveHeroNewArtifact(hero, VLC->arth->artifacts[ArtifactID::FIRST_AID_TENT], ArtifactPosition::MACH3);
  3634. }
  3635. else if (message == "vcmiforgeofnoldorking") //hero gets all artifacts except war machines, spell scrolls and spell book
  3636. {
  3637. CGHeroInstance *hero = gs->getHero(currObj);
  3638. if(!hero) return;
  3639. for (int g = 7; g < VLC->arth->artifacts.size(); ++g) //including artifacts from mods
  3640. giveHeroNewArtifact(hero, VLC->arth->artifacts[g], ArtifactPosition::PRE_FIRST);
  3641. }
  3642. else if(message == "vcmiglorfindel") //selected hero gains a new level
  3643. {
  3644. CGHeroInstance *hero = gs->getHero(currObj);
  3645. changePrimSkill(hero, PrimarySkill::EXPERIENCE, VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  3646. }
  3647. else if(message == "vcminahar") //1000000 movement points
  3648. {
  3649. CGHeroInstance *hero = gs->getHero(currObj);
  3650. if(!hero) return;
  3651. SetMovePoints smp;
  3652. smp.hid = hero->id;
  3653. smp.val = 1000000;
  3654. sendAndApply(&smp);
  3655. }
  3656. else if(message == "vcmiformenos") //give resources
  3657. {
  3658. SetResources sr;
  3659. sr.player = player;
  3660. sr.res = gs->getPlayer(player)->resources;
  3661. for(int i=0;i<Res::GOLD;i++)
  3662. sr.res[i] += 100;
  3663. sr.res[Res::GOLD] += 100000; //100k
  3664. sendAndApply(&sr);
  3665. }
  3666. else if(message == "vcmieagles") //reveal FoW
  3667. {
  3668. FoWChange fc;
  3669. fc.mode = 1;
  3670. fc.player = player;
  3671. auto hlp_tab = new int3[gs->map->width * gs->map->height * (gs->map->twoLevel ? 2 : 1)];
  3672. int lastUnc = 0;
  3673. for(int i=0;i<gs->map->width;i++)
  3674. for(int j=0;j<gs->map->height;j++)
  3675. for(int k = 0; k < (gs->map->twoLevel ? 2 : 1); k++)
  3676. if(!gs->getPlayerTeam(fc.player)->fogOfWarMap.at(i).at(j).at(k))
  3677. hlp_tab[lastUnc++] = int3(i,j,k);
  3678. fc.tiles.insert(hlp_tab, hlp_tab + lastUnc);
  3679. delete [] hlp_tab;
  3680. sendAndApply(&fc);
  3681. }
  3682. else if(message == "vcmisilmaril") //player wins
  3683. {
  3684. gs->getPlayer(player)->enteredWinningCheatCode = 1;
  3685. }
  3686. else if(message == "vcmimelkor") //player looses
  3687. {
  3688. gs->getPlayer(player)->enteredLosingCheatCode = 1;
  3689. }
  3690. else
  3691. cheated = false;
  3692. if(cheated)
  3693. {
  3694. SystemMessage temp_message(VLC->generaltexth->allTexts.at(260));
  3695. sendAndApply(&temp_message);
  3696. checkVictoryLossConditionsForPlayer(player);//Player enter win code or got required art\creature
  3697. }
  3698. }
  3699. bool CGameHandler::makeCustomAction( BattleAction &ba )
  3700. {
  3701. switch(ba.actionType)
  3702. {
  3703. case Battle::HERO_SPELL:
  3704. {
  3705. COMPLAIN_RET_FALSE_IF(ba.side > 1, "Side must be 0 or 1!");
  3706. const CGHeroInstance *h = gs->curB->battleGetFightingHero(ba.side);
  3707. if(!h)
  3708. {
  3709. logGlobal->warnStream() << "Wrong caster!";
  3710. return false;
  3711. }
  3712. if(ba.additionalInfo >= VLC->spellh->objects.size())
  3713. {
  3714. logGlobal->warnStream() << "Wrong spell id (" << ba.additionalInfo << ")!";
  3715. return false;
  3716. }
  3717. const CSpell * s = SpellID(ba.additionalInfo).toSpell();
  3718. BattleSpellCastParameters parameters(gs->curB, h, s);
  3719. parameters.aimToHex(ba.destinationTile);//todo: allow multiple destinations
  3720. parameters.mode = ECastingMode::HERO_CASTING;
  3721. parameters.selectedStack = gs->curB->battleGetStackByID(ba.selectedStack, false);
  3722. ESpellCastProblem::ESpellCastProblem escp = gs->curB->battleCanCastThisSpell(h, s, ECastingMode::HERO_CASTING);//todo: should we check aimed cast(battleCanCastThisSpellHere)?
  3723. if(escp != ESpellCastProblem::OK)
  3724. {
  3725. logGlobal->warnStream() << "Spell cannot be cast!";
  3726. logGlobal->warnStream() << "Problem : " << escp;
  3727. return false;
  3728. }
  3729. StartAction start_action(ba);
  3730. sendAndApply(&start_action); //start spell casting
  3731. s->battleCast(spellEnv, parameters);
  3732. sendAndApply(&end_action);
  3733. if( !gs->curB->battleGetStackByID(gs->curB->activeStack, true))
  3734. {
  3735. battleMadeAction.setn(true);
  3736. }
  3737. checkForBattleEnd();
  3738. if(battleResult.get())
  3739. {
  3740. battleMadeAction.setn(true);
  3741. //battle will be ended by startBattle function
  3742. //endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  3743. }
  3744. return true;
  3745. }
  3746. }
  3747. return false;
  3748. }
  3749. void CGameHandler::stackTurnTrigger(const CStack * st)
  3750. {
  3751. BattleTriggerEffect bte;
  3752. bte.stackID = st->ID;
  3753. bte.effect = -1;
  3754. bte.val = 0;
  3755. bte.additionalInfo = 0;
  3756. if (st->alive())
  3757. {
  3758. //unbind
  3759. if (st->getEffect (SpellID::BIND))
  3760. {
  3761. bool unbind = true;
  3762. BonusList bl = *(st->getBonuses(Selector::type(Bonus::BIND_EFFECT)));
  3763. std::set<const CStack*> stacks = gs->curB-> batteAdjacentCreatures(st);
  3764. for(Bonus * b : bl)
  3765. {
  3766. const CStack * stack = gs->curB->battleGetStackByID(b->additionalInfo); //binding stack must be alive and adjacent
  3767. if (stack)
  3768. {
  3769. if (vstd::contains(stacks, stack)) //binding stack is still present
  3770. {
  3771. unbind = false;
  3772. }
  3773. }
  3774. }
  3775. if (unbind)
  3776. {
  3777. BattleSetStackProperty ssp;
  3778. ssp.which = BattleSetStackProperty::UNBIND;
  3779. ssp.stackID = st->ID;
  3780. sendAndApply(&ssp);
  3781. }
  3782. }
  3783. //regeneration
  3784. if(st->hasBonusOfType(Bonus::HP_REGENERATION))
  3785. {
  3786. bte.effect = Bonus::HP_REGENERATION;
  3787. bte.val = std::min((int)(st->MaxHealth() - st->firstHPleft), st->valOfBonuses(Bonus::HP_REGENERATION));
  3788. }
  3789. if(st->hasBonusOfType(Bonus::FULL_HP_REGENERATION))
  3790. {
  3791. bte.effect = Bonus::HP_REGENERATION;
  3792. bte.val = st->MaxHealth() - st->firstHPleft;
  3793. }
  3794. if (bte.val) //anything to heal
  3795. sendAndApply(&bte);
  3796. if(st->hasBonusOfType(Bonus::POISON))
  3797. {
  3798. const Bonus * b = st->getBonusLocalFirst(Selector::source(Bonus::SPELL_EFFECT, SpellID::POISON).And(Selector::type(Bonus::STACK_HEALTH)));
  3799. if (b) //TODO: what if not?...
  3800. {
  3801. bte.val = std::max (b->val - 10, -(st->valOfBonuses(Bonus::POISON)));
  3802. if (bte.val < b->val) //(negative) poison effect increases - update it
  3803. {
  3804. bte.effect = Bonus::POISON;
  3805. sendAndApply(&bte);
  3806. }
  3807. }
  3808. }
  3809. if (st->hasBonusOfType(Bonus::MANA_DRAIN) && !vstd::contains(st->state, EBattleStackState::DRAINED_MANA))
  3810. {
  3811. const PlayerColor opponent = gs->curB->theOtherPlayer(st->owner);
  3812. const CGHeroInstance * opponentHero = gs->curB->getHero(opponent);
  3813. if (opponentHero)
  3814. {
  3815. ui32 manaDrained = st->valOfBonuses(Bonus::MANA_DRAIN);
  3816. vstd::amin(manaDrained, opponentHero->mana);
  3817. if (manaDrained)
  3818. {
  3819. bte.effect = Bonus::MANA_DRAIN;
  3820. bte.val = manaDrained;
  3821. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  3822. sendAndApply(&bte);
  3823. }
  3824. }
  3825. }
  3826. if (st->isLiving() && !st->hasBonusOfType(Bonus::FEARLESS))
  3827. {
  3828. bool fearsomeCreature = false;
  3829. for(CStack * stack : gs->curB->stacks)
  3830. {
  3831. if (stack->owner != st->owner && stack->alive() && stack->hasBonusOfType(Bonus::FEAR))
  3832. {
  3833. fearsomeCreature = true;
  3834. break;
  3835. }
  3836. }
  3837. if (fearsomeCreature)
  3838. {
  3839. if (gs->getRandomGenerator().nextInt(99) < 10) //fixed 10%
  3840. {
  3841. bte.effect = Bonus::FEAR;
  3842. sendAndApply(&bte);
  3843. }
  3844. }
  3845. }
  3846. BonusList bl = *(st->getBonuses(Selector::type(Bonus::ENCHANTER)));
  3847. int side = gs->curB->whatSide(st->owner);
  3848. if (st->casts && !gs->curB->sides.at(side).enchanterCounter)
  3849. {
  3850. bool cast = false;
  3851. while (!bl.empty() && !cast)
  3852. {
  3853. auto bonus = *RandomGeneratorUtil::nextItem(bl, gs->getRandomGenerator());
  3854. auto spellID = SpellID(bonus->subtype);
  3855. const CSpell * spell = SpellID(spellID).toSpell();
  3856. bl.remove_if([&bonus](Bonus * b){return b==bonus;});
  3857. if (gs->curB->battleCanCastThisSpell(st, spell, ECastingMode::ENCHANTER_CASTING) == ESpellCastProblem::OK)
  3858. {
  3859. BattleSpellCastParameters parameters(gs->curB, st, spell);
  3860. parameters.spellLvl = bonus->val;
  3861. parameters.effectLevel = bonus->val;//todo: recheck
  3862. parameters.aimToHex(BattleHex::INVALID);
  3863. parameters.mode = ECastingMode::ENCHANTER_CASTING;
  3864. parameters.selectedStack = nullptr;
  3865. spell->battleCast(spellEnv, parameters);
  3866. //todo: move to mechanics
  3867. BattleSetStackProperty ssp;
  3868. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  3869. ssp.absolute = false;
  3870. ssp.val = bonus->additionalInfo; //increase cooldown counter
  3871. ssp.stackID = st->ID;
  3872. sendAndApply(&ssp);
  3873. cast = true;
  3874. }
  3875. };
  3876. }
  3877. bl = *(st->getBonuses(Selector::type(Bonus::ENCHANTED)));
  3878. for (auto b : bl)
  3879. {
  3880. SetStackEffect sse;
  3881. int val = bl.valOfBonuses (Selector::typeSubtype(b->type, b->subtype));
  3882. if (val > 3)
  3883. {
  3884. for (auto s : gs->curB->battleGetAllStacks())
  3885. {
  3886. if (st->owner == s->owner && s->isValidTarget()) //all allied
  3887. sse.stacks.push_back (s->ID);
  3888. }
  3889. }
  3890. else
  3891. sse.stacks.push_back (st->ID);
  3892. Bonus pseudoBonus;
  3893. pseudoBonus.sid = b->subtype;
  3894. pseudoBonus.val = ((val > 3) ? (val - 3) : val);
  3895. pseudoBonus.turnsRemain = 50;
  3896. st->stackEffectToFeature (sse.effect, pseudoBonus);
  3897. if (sse.effect.size())
  3898. sendAndApply (&sse);
  3899. }
  3900. }
  3901. }
  3902. void CGameHandler::handleDamageFromObstacle(const CObstacleInstance &obstacle, const CStack * curStack)
  3903. {
  3904. //we want to determine following vars depending on obstacle type
  3905. int damage = -1;
  3906. int effect = -1;
  3907. bool oneTimeObstacle = false;
  3908. //helper info
  3909. const SpellCreatedObstacle *spellObstacle = dynamic_cast<const SpellCreatedObstacle*>(&obstacle); //not nice but we may need spell params
  3910. const ui8 side = !curStack->attackerOwned; //if enemy is defending (false = 0), side of enemy hero is 1 (true)
  3911. const CGHeroInstance *hero = gs->curB->battleGetFightingHero(side);//FIXME: there may be no hero - landmines in Tower
  3912. if(obstacle.obstacleType == CObstacleInstance::MOAT)
  3913. {
  3914. damage = battleGetMoatDmg();
  3915. }
  3916. else if(obstacle.obstacleType == CObstacleInstance::LAND_MINE)
  3917. {
  3918. //You don't get hit by a Mine you can see.
  3919. if(gs->curB->battleIsObstacleVisibleForSide(obstacle, (BattlePerspective::BattlePerspective)side))
  3920. return;
  3921. oneTimeObstacle = true;
  3922. effect = 82; //makes
  3923. const CSpell * sp = SpellID(SpellID::LAND_MINE).toSpell();
  3924. if(sp->isImmuneByStack(hero, curStack))
  3925. return;
  3926. damage = sp->calculateDamage(hero, curStack,
  3927. spellObstacle->spellLevel, spellObstacle->casterSpellPower);
  3928. //TODO even if obstacle wasn't created by hero (Tower "moat") it should deal dmg as if cast by hero,
  3929. //if it is bigger than default dmg. Or is it just irrelevant H3 implementation quirk
  3930. }
  3931. else if(obstacle.obstacleType == CObstacleInstance::FIRE_WALL)
  3932. {
  3933. const CSpell * sp = SpellID(SpellID::FIRE_WALL).toSpell();
  3934. if(sp->isImmuneByStack(hero, curStack))
  3935. return;
  3936. damage = sp->calculateDamage(hero, curStack,
  3937. spellObstacle->spellLevel, spellObstacle->casterSpellPower);
  3938. }
  3939. else
  3940. {
  3941. //no other obstacle does damage to stack
  3942. return;
  3943. }
  3944. BattleStackAttacked bsa;
  3945. if(effect >= 0)
  3946. {
  3947. bsa.flags |= BattleStackAttacked::EFFECT;
  3948. bsa.effect = effect; //makes POOF
  3949. }
  3950. bsa.damageAmount = damage;
  3951. bsa.stackAttacked = curStack->ID;
  3952. bsa.attackerID = -1;
  3953. curStack->prepareAttacked(bsa, gameState()->getRandomGenerator());
  3954. StacksInjured si;
  3955. si.stacks.push_back(bsa);
  3956. sendAndApply(&si);
  3957. if(oneTimeObstacle)
  3958. removeObstacle(obstacle);
  3959. }
  3960. void CGameHandler::handleTimeEvents()
  3961. {
  3962. gs->map->events.sort(evntCmp);
  3963. while(gs->map->events.size() && gs->map->events.front().firstOccurence+1 == gs->day)
  3964. {
  3965. CMapEvent ev = gs->map->events.front();
  3966. for (int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
  3967. {
  3968. auto color = PlayerColor(player);
  3969. PlayerState *pinfo = gs->getPlayer(color, false); //do not output error if player does not exist
  3970. if( pinfo //player exists
  3971. && (ev.players & 1<<player) //event is enabled to this player
  3972. && ((ev.computerAffected && !pinfo->human)
  3973. || (ev.humanAffected && pinfo->human)
  3974. )
  3975. )
  3976. {
  3977. //give resources
  3978. SetResources sr;
  3979. sr.player = color;
  3980. sr.res = pinfo->resources + ev.resources;
  3981. //prepare dialog
  3982. InfoWindow iw;
  3983. iw.player = color;
  3984. iw.text << ev.message;
  3985. for (int i=0; i<ev.resources.size(); i++)
  3986. {
  3987. if(ev.resources.at(i)) //if resource is changed, we add it to the dialog
  3988. iw.components.push_back(Component(Component::RESOURCE,i,ev.resources.at(i),0));
  3989. }
  3990. if (iw.components.size())
  3991. {
  3992. sr.res.amax(0); // If removing too much resources, adjust the amount so the total doesn't become negative.
  3993. sendAndApply(&sr); //update player resources if changed
  3994. }
  3995. sendAndApply(&iw); //show dialog
  3996. }
  3997. } //PLAYERS LOOP
  3998. if(ev.nextOccurence)
  3999. {
  4000. gs->map->events.pop_front();
  4001. ev.firstOccurence += ev.nextOccurence;
  4002. auto it = gs->map->events.begin();
  4003. while ( it !=gs->map->events.end() && it->earlierThanOrEqual(ev))
  4004. it++;
  4005. gs->map->events.insert(it, ev);
  4006. }
  4007. else
  4008. {
  4009. gs->map->events.pop_front();
  4010. }
  4011. }
  4012. //TODO send only if changed
  4013. UpdateMapEvents ume;
  4014. ume.events = gs->map->events;
  4015. sendAndApply(&ume);
  4016. }
  4017. void CGameHandler::handleTownEvents(CGTownInstance * town, NewTurn &n)
  4018. {
  4019. town->events.sort(evntCmp);
  4020. while(town->events.size() && town->events.front().firstOccurence == gs->day)
  4021. {
  4022. PlayerColor player = town->tempOwner;
  4023. CCastleEvent ev = town->events.front();
  4024. PlayerState *pinfo = gs->getPlayer(player, false);
  4025. if( pinfo //player exists
  4026. && (ev.players & 1<<player.getNum()) //event is enabled to this player
  4027. && ((ev.computerAffected && !pinfo->human)
  4028. || (ev.humanAffected && pinfo->human) ) )
  4029. {
  4030. // dialog
  4031. InfoWindow iw;
  4032. iw.player = player;
  4033. iw.text << ev.message;
  4034. if(ev.resources.nonZero())
  4035. {
  4036. TResources was = n.res[player];
  4037. n.res[player] += ev.resources;
  4038. n.res[player].amax(0);
  4039. for (int i=0; i<ev.resources.size(); i++)
  4040. if(ev.resources.at(i) && pinfo->resources.at(i) != n.res.at(player).at(i)) //if resource had changed, we add it to the dialog
  4041. iw.components.push_back(Component(Component::RESOURCE,i,n.res.at(player).at(i)-was.at(i),0));
  4042. }
  4043. for(auto & i : ev.buildings)
  4044. {
  4045. if(!town->hasBuilt(i))
  4046. {
  4047. buildStructure(town->id, i, true);
  4048. iw.components.push_back(Component(Component::BUILDING, town->subID, i, 0));
  4049. }
  4050. }
  4051. if (!ev.creatures.empty() && !vstd::contains(n.cres, town->id))
  4052. {
  4053. n.cres[town->id].tid = town->id;
  4054. n.cres[town->id].creatures = town->creatures;
  4055. }
  4056. auto & sac = n.cres[town->id];
  4057. for(si32 i=0;i<ev.creatures.size();i++) //creature growths
  4058. {
  4059. if(!town->creatures.at(i).second.empty() && ev.creatures.at(i) > 0)//there is dwelling
  4060. {
  4061. sac.creatures[i].first += ev.creatures.at(i);
  4062. iw.components.push_back(Component(Component::CREATURE,
  4063. town->creatures.at(i).second.back(), ev.creatures.at(i), 0));
  4064. }
  4065. }
  4066. sendAndApply(&iw); //show dialog
  4067. }
  4068. if(ev.nextOccurence)
  4069. {
  4070. town->events.pop_front();
  4071. ev.firstOccurence += ev.nextOccurence;
  4072. auto it = town->events.begin();
  4073. while ( it != town->events.end() && it->earlierThanOrEqual(ev))
  4074. it++;
  4075. town->events.insert(it, ev);
  4076. }
  4077. else
  4078. {
  4079. town->events.pop_front();
  4080. }
  4081. }
  4082. //TODO send only if changed
  4083. UpdateCastleEvents uce;
  4084. uce.town = town->id;
  4085. uce.events = town->events;
  4086. sendAndApply(&uce);
  4087. }
  4088. bool CGameHandler::complain( const std::string &problem )
  4089. {
  4090. sendMessageToAll("Server encountered a problem: " + problem);
  4091. logGlobal->errorStream() << problem;
  4092. return true;
  4093. }
  4094. void CGameHandler::showGarrisonDialog( ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits)
  4095. {
  4096. //PlayerColor player = getOwner(hid);
  4097. auto upperArmy = dynamic_cast<const CArmedInstance*>(getObj(upobj));
  4098. auto lowerArmy = dynamic_cast<const CArmedInstance*>(getObj(hid));
  4099. assert(lowerArmy);
  4100. assert(upperArmy);
  4101. auto garrisonQuery = std::make_shared<CGarrisonDialogQuery>(upperArmy, lowerArmy);
  4102. queries.addQuery(garrisonQuery);
  4103. GarrisonDialog gd;
  4104. gd.hid = hid;
  4105. gd.objid = upobj;
  4106. gd.removableUnits = removableUnits;
  4107. gd.queryID = garrisonQuery->queryID;
  4108. sendAndApply(&gd);
  4109. }
  4110. void CGameHandler::showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId)
  4111. {
  4112. OpenWindow ow;
  4113. ow.window = OpenWindow::THIEVES_GUILD;
  4114. ow.id1 = player.getNum();
  4115. ow.id2 = requestingObjId.getNum();
  4116. sendAndApply(&ow);
  4117. }
  4118. bool CGameHandler::isAllowedExchange( ObjectInstanceID id1, ObjectInstanceID id2 )
  4119. {
  4120. if(id1 == id2)
  4121. return true;
  4122. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  4123. if(!o1 || !o2)
  4124. return true; //arranging stacks within an object should be always allowed
  4125. if (o1 && o2)
  4126. {
  4127. if(o1->ID == Obj::TOWN)
  4128. {
  4129. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  4130. if(t->visitingHero == o2 || t->garrisonHero == o2)
  4131. return true;
  4132. }
  4133. if(o2->ID == Obj::TOWN)
  4134. {
  4135. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  4136. if(t->visitingHero == o1 || t->garrisonHero == o1)
  4137. return true;
  4138. }
  4139. if (o1->ID == Obj::HERO && o2->ID == Obj::HERO)
  4140. {
  4141. const CGHeroInstance *h1 = static_cast<const CGHeroInstance*>(o1);
  4142. const CGHeroInstance *h2 = static_cast<const CGHeroInstance*>(o2);
  4143. // two heroes in same town (garrisoned and visiting)
  4144. if (h1->visitedTown != nullptr && h2->visitedTown != nullptr && h1->visitedTown == h2->visitedTown)
  4145. return true;
  4146. }
  4147. //Ongoing garrison exchange
  4148. if(auto dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries.topQuery(o1->tempOwner)))
  4149. {
  4150. if(dialog->exchangingArmies.at(0) == o1 && dialog->exchangingArmies.at(1) == o2)
  4151. return true;
  4152. if(dialog->exchangingArmies.at(1) == o1 && dialog->exchangingArmies.at(0) == o2)
  4153. return true;
  4154. }
  4155. }
  4156. return false;
  4157. }
  4158. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  4159. {
  4160. logGlobal->debugStream() << h->nodeName() << " visits " << obj->getObjectName() << "(" << obj->ID << ":" << obj->subID << ")";
  4161. auto visitQuery = std::make_shared<CObjectVisitQuery>(obj, h, obj->visitablePos());
  4162. queries.addQuery(visitQuery); //TODO real visit pos
  4163. HeroVisit hv;
  4164. hv.obj = obj;
  4165. hv.hero = h;
  4166. hv.player = h->tempOwner;
  4167. hv.starting = true;
  4168. sendAndApply(&hv);
  4169. obj->onHeroVisit(h);
  4170. queries.popIfTop(visitQuery); //visit ends here if no queries were created
  4171. }
  4172. void CGameHandler::objectVisitEnded(const CObjectVisitQuery &query)
  4173. {
  4174. logGlobal->traceStream() << query.visitingHero->nodeName() << " visit ends.\n";
  4175. HeroVisit hv;
  4176. hv.player = query.players.front();
  4177. hv.obj = nullptr; //not necessary, moreover may have been deleted in the meantime
  4178. hv.hero = query.visitingHero;
  4179. assert(hv.hero);
  4180. hv.starting = false;
  4181. sendAndApply(&hv);
  4182. }
  4183. bool CGameHandler::buildBoat( ObjectInstanceID objid )
  4184. {
  4185. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  4186. if(obj->shipyardStatus() != IBoatGenerator::GOOD)
  4187. {
  4188. complain("Cannot build boat in this shipyard!");
  4189. return false;
  4190. }
  4191. else if(obj->o->ID == Obj::TOWN
  4192. && !static_cast<const CGTownInstance*>(obj)->hasBuilt(BuildingID::SHIPYARD))
  4193. {
  4194. complain("Cannot build boat in the town - no shipyard!");
  4195. return false;
  4196. }
  4197. const PlayerColor playerID = obj->o->tempOwner;
  4198. TResources boatCost;
  4199. obj->getBoatCost(boatCost);
  4200. TResources aviable = gs->getPlayer(playerID)->resources;
  4201. if (!aviable.canAfford(boatCost))
  4202. {
  4203. complain("Not enough resources to build a boat!");
  4204. return false;
  4205. }
  4206. int3 tile = obj->bestLocation();
  4207. if(!gs->map->isInTheMap(tile))
  4208. {
  4209. complain("Cannot find appropriate tile for a boat!");
  4210. return false;
  4211. }
  4212. //take boat cost
  4213. SetResources sr;
  4214. sr.player = playerID;
  4215. sr.res = (aviable - boatCost);
  4216. sendAndApply(&sr);
  4217. //create boat
  4218. NewObject no;
  4219. no.ID = Obj::BOAT;
  4220. no.subID = obj->getBoatType();
  4221. no.pos = tile + int3(1,0,0);
  4222. sendAndApply(&no);
  4223. return true;
  4224. }
  4225. void CGameHandler::engageIntoBattle( PlayerColor player )
  4226. {
  4227. //notify interfaces
  4228. PlayerBlocked pb;
  4229. pb.player = player;
  4230. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  4231. pb.startOrEnd = PlayerBlocked::BLOCKADE_STARTED;
  4232. sendAndApply(&pb);
  4233. }
  4234. void CGameHandler::checkVictoryLossConditions(const std::set<PlayerColor> & playerColors)
  4235. {
  4236. for(auto playerColor : playerColors)
  4237. {
  4238. if(gs->getPlayer(playerColor, false))
  4239. checkVictoryLossConditionsForPlayer(playerColor);
  4240. }
  4241. }
  4242. void CGameHandler::checkVictoryLossConditionsForAll()
  4243. {
  4244. std::set<PlayerColor> playerColors;
  4245. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  4246. {
  4247. playerColors.insert(PlayerColor(i));
  4248. }
  4249. checkVictoryLossConditions(playerColors);
  4250. }
  4251. void CGameHandler::checkVictoryLossConditionsForPlayer(PlayerColor player)
  4252. {
  4253. const PlayerState *p = gs->getPlayer(player);
  4254. if(p->status != EPlayerStatus::INGAME) return;
  4255. auto victoryLossCheckResult = gs->checkForVictoryAndLoss(player);
  4256. if(victoryLossCheckResult.victory() || victoryLossCheckResult.loss())
  4257. {
  4258. InfoWindow iw;
  4259. getVictoryLossMessage(player, victoryLossCheckResult, iw);
  4260. sendAndApply(&iw);
  4261. PlayerEndsGame peg;
  4262. peg.player = player;
  4263. peg.victoryLossCheckResult = victoryLossCheckResult;
  4264. sendAndApply(&peg);
  4265. if(victoryLossCheckResult.victory())
  4266. {
  4267. //one player won -> all enemies lost
  4268. for (auto i = gs->players.cbegin(); i!=gs->players.cend(); i++)
  4269. {
  4270. if(i->first != player && gs->getPlayer(i->first)->status == EPlayerStatus::INGAME)
  4271. {
  4272. peg.player = i->first;
  4273. peg.victoryLossCheckResult = gameState()->getPlayerRelations(player, i->first) == PlayerRelations::ALLIES ?
  4274. victoryLossCheckResult : victoryLossCheckResult.invert(); // ally of winner
  4275. InfoWindow iw;
  4276. getVictoryLossMessage(player, peg.victoryLossCheckResult, iw);
  4277. iw.player = i->first;
  4278. sendAndApply(&iw);
  4279. sendAndApply(&peg);
  4280. }
  4281. }
  4282. if(p->human)
  4283. {
  4284. end2 = true;
  4285. if(gs->scenarioOps->campState)
  4286. {
  4287. std::vector<CGHeroInstance *> crossoverHeroes;
  4288. for(CGHeroInstance * hero : gs->map->heroesOnMap)
  4289. {
  4290. if(hero->tempOwner == player)
  4291. {
  4292. // keep all heroes from the winning player
  4293. crossoverHeroes.push_back(hero);
  4294. }
  4295. else if(vstd::contains(gs->scenarioOps->campState->getCurrentScenario().keepHeroes, HeroTypeID(hero->subID)))
  4296. {
  4297. // keep hero whether lost or won (like Xeron in AB campaign)
  4298. crossoverHeroes.push_back(hero);
  4299. }
  4300. }
  4301. // keep lost heroes which are in heroes pool
  4302. for(auto & heroPair : gs->hpool.heroesPool)
  4303. {
  4304. if(vstd::contains(gs->scenarioOps->campState->getCurrentScenario().keepHeroes, HeroTypeID(heroPair.first)))
  4305. {
  4306. crossoverHeroes.push_back(heroPair.second.get());
  4307. }
  4308. }
  4309. gs->scenarioOps->campState->setCurrentMapAsConquered(crossoverHeroes);
  4310. //Request clients to change connection mode
  4311. PrepareForAdvancingCampaign pfac;
  4312. sendAndApply(&pfac);
  4313. //Change connection mode
  4314. if(getPlayer(player)->human && getStartInfo()->campState)
  4315. {
  4316. for(auto connection : conns)
  4317. connection->prepareForSendingHeroes();
  4318. }
  4319. UpdateCampaignState ucs;
  4320. ucs.camp = gs->scenarioOps->campState;
  4321. sendAndApply(&ucs);
  4322. }
  4323. }
  4324. }
  4325. else
  4326. {
  4327. //copy heroes vector to avoid iterator invalidation as removal change PlayerState
  4328. auto hlp = p->heroes;
  4329. for(auto h : hlp) //eliminate heroes
  4330. {
  4331. if(h.get())
  4332. removeObject(h);
  4333. }
  4334. //player lost -> all his objects become unflagged (neutral)
  4335. for (auto obj : gs->map->objects) //unflag objs
  4336. {
  4337. if(obj.get() && obj->tempOwner == player)
  4338. setOwner(obj, PlayerColor::NEUTRAL);
  4339. }
  4340. //eliminating one player may cause victory of another:
  4341. std::set<PlayerColor> playerColors;
  4342. //do not copy player state (CBonusSystemNode) by value
  4343. for (auto &p : gs->players) //players may have different colors, iterate over players and not integers
  4344. {
  4345. if (p.first != player)
  4346. playerColors.insert(p.first);
  4347. }
  4348. //notify all players
  4349. for (auto pc : playerColors)
  4350. {
  4351. if (gs->getPlayer(pc)->status == EPlayerStatus::INGAME)
  4352. {
  4353. InfoWindow iw;
  4354. getVictoryLossMessage(player, victoryLossCheckResult.invert(), iw);
  4355. iw.player = pc;
  4356. sendAndApply(&iw);
  4357. }
  4358. }
  4359. checkVictoryLossConditions(playerColors);
  4360. }
  4361. auto playerInfo = gs->getPlayer(gs->currentPlayer, false);
  4362. // If we are called before the actual game start, there might be no current player
  4363. if (playerInfo && playerInfo->status != EPlayerStatus::INGAME)
  4364. {
  4365. // If player making turn has lost his turn must be over as well
  4366. states.setFlag(gs->currentPlayer, &PlayerStatus::makingTurn, false);
  4367. }
  4368. }
  4369. }
  4370. void CGameHandler::getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const
  4371. {
  4372. out.player = player;
  4373. out.text.clear();
  4374. out.text << victoryLossCheckResult.messageToSelf;
  4375. // hackish, insert one player-specific string, if applicable
  4376. if (victoryLossCheckResult.messageToSelf.find("%s") != std::string::npos)
  4377. out.text.addReplacement(MetaString::COLOR, player.getNum());
  4378. out.components.push_back(Component(Component::FLAG, player.getNum(), 0, 0));
  4379. }
  4380. bool CGameHandler::dig( const CGHeroInstance *h )
  4381. {
  4382. for (auto i = gs->map->objects.cbegin(); i != gs->map->objects.cend(); i++) //unflag objs
  4383. {
  4384. if(*i && (*i)->ID == Obj::HOLE && (*i)->pos == h->getPosition())
  4385. {
  4386. complain("Cannot dig - there is already a hole under the hero!");
  4387. return false;
  4388. }
  4389. }
  4390. if(h->diggingStatus() != EDiggingStatus::CAN_DIG) //checks for terrain and movement
  4391. COMPLAIN_RETF("Hero cannot dig (error code %d)!", h->diggingStatus());
  4392. //create a hole
  4393. NewObject no;
  4394. no.ID = Obj::HOLE;
  4395. no.pos = h->getPosition();
  4396. no.subID = 0;
  4397. sendAndApply(&no);
  4398. //take MPs
  4399. SetMovePoints smp;
  4400. smp.hid = h->id;
  4401. smp.val = 0;
  4402. sendAndApply(&smp);
  4403. InfoWindow iw;
  4404. iw.player = h->tempOwner;
  4405. if(gs->map->grailPos == h->getPosition())
  4406. {
  4407. iw.text.addTxt(MetaString::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  4408. iw.text.addTxt(MetaString::ART_NAMES, ArtifactID::GRAIL);
  4409. iw.soundID = soundBase::ULTIMATEARTIFACT;
  4410. giveHeroNewArtifact(h, VLC->arth->artifacts[ArtifactID::GRAIL], ArtifactPosition::PRE_FIRST); //give grail
  4411. sendAndApply(&iw);
  4412. iw.soundID = soundBase::invalid;
  4413. iw.text.clear();
  4414. iw.text.addTxt(MetaString::ART_DESCR, ArtifactID::GRAIL);
  4415. sendAndApply(&iw);
  4416. }
  4417. else
  4418. {
  4419. iw.text.addTxt(MetaString::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  4420. iw.soundID = soundBase::Dig;
  4421. sendAndApply(&iw);
  4422. }
  4423. return true;
  4424. }
  4425. void CGameHandler::attackCasting(const BattleAttack & bat, Bonus::BonusType attackMode, const CStack * attacker)
  4426. {
  4427. if(attacker->hasBonusOfType(attackMode))
  4428. {
  4429. std::set<SpellID> spellsToCast;
  4430. TBonusListPtr spells = attacker->getBonuses(Selector::type(attackMode));
  4431. for(const Bonus *sf : *spells)
  4432. {
  4433. spellsToCast.insert (SpellID(sf->subtype));
  4434. }
  4435. for(SpellID spellID : spellsToCast)
  4436. {
  4437. const CStack * oneOfAttacked = nullptr;
  4438. for (auto & elem : bat.bsa)
  4439. {
  4440. if (elem.newAmount > 0 && !elem.isSecondary()) //apply effects only to first target stack if it's alive
  4441. {
  4442. oneOfAttacked = gs->curB->battleGetStackByID(elem.stackAttacked);
  4443. break;
  4444. }
  4445. }
  4446. bool castMe = false;
  4447. if(oneOfAttacked == nullptr) //all attacked creatures have been killed
  4448. return;
  4449. int spellLevel = 0;
  4450. TBonusListPtr spellsByType = attacker->getBonuses(Selector::typeSubtype(attackMode, spellID));
  4451. for(const Bonus *sf : *spellsByType)
  4452. {
  4453. vstd::amax(spellLevel, sf->additionalInfo % 1000); //pick highest level
  4454. int meleeRanged = sf->additionalInfo / 1000;
  4455. if (meleeRanged == 0 || (meleeRanged == 1 && bat.shot()) || (meleeRanged == 2 && !bat.shot()))
  4456. castMe = true;
  4457. }
  4458. int chance = attacker->valOfBonuses((Selector::typeSubtype(attackMode, spellID)));
  4459. vstd::amin (chance, 100);
  4460. const CSpell * spell = SpellID(spellID).toSpell();
  4461. if(gs->curB->battleCanCastThisSpellHere(attacker, spell, ECastingMode::AFTER_ATTACK_CASTING, oneOfAttacked->position) != ESpellCastProblem::OK)
  4462. continue;
  4463. //check if spell should be cast (probability handling)
  4464. if(gs->getRandomGenerator().nextInt(99) >= chance)
  4465. continue;
  4466. //casting
  4467. if (castMe) //stacks use 0 spell power. If needed, default = 3 or custom value is used
  4468. {
  4469. BattleSpellCastParameters parameters(gs->curB, attacker, spell);
  4470. parameters.spellLvl = spellLevel;
  4471. parameters.effectLevel = spellLevel;
  4472. parameters.aimToStack(oneOfAttacked);
  4473. parameters.mode = ECastingMode::AFTER_ATTACK_CASTING;
  4474. parameters.selectedStack = nullptr;
  4475. spell->battleCast(spellEnv, parameters);
  4476. }
  4477. }
  4478. }
  4479. }
  4480. void CGameHandler::handleAttackBeforeCasting (const BattleAttack & bat)
  4481. {
  4482. const CStack * attacker = gs->curB->battleGetStackByID(bat.stackAttacking);
  4483. attackCasting(bat, Bonus::SPELL_BEFORE_ATTACK, attacker); //no death stare / acid breath needed?
  4484. }
  4485. void CGameHandler::handleAfterAttackCasting( const BattleAttack & bat )
  4486. {
  4487. const CStack * attacker = gs->curB->battleGetStackByID(bat.stackAttacking);
  4488. if (!attacker) //could be already dead
  4489. return;
  4490. auto cast = [=](SpellID spellID, int power)
  4491. {
  4492. const CSpell * spell = SpellID(spellID).toSpell();
  4493. BattleSpellCastParameters parameters(gs->curB, attacker, spell);
  4494. parameters.spellLvl = 0;
  4495. parameters.effectLevel = 0;
  4496. parameters.aimToStack(gs->curB->battleGetStackByID(bat.bsa.at(0).stackAttacked));
  4497. parameters.effectPower = power;
  4498. parameters.mode = ECastingMode::AFTER_ATTACK_CASTING;
  4499. parameters.selectedStack = nullptr;
  4500. spell->battleCast(this->spellEnv, parameters);
  4501. };
  4502. attackCasting(bat, Bonus::SPELL_AFTER_ATTACK, attacker);
  4503. if(bat.bsa.at(0).newAmount <= 0)
  4504. {
  4505. //don't try death stare or acid breath on dead stack (crash!)
  4506. return;
  4507. }
  4508. if (attacker->hasBonusOfType(Bonus::DEATH_STARE) && bat.bsa.size())
  4509. {
  4510. // mechanics of Death Stare as in H3:
  4511. // each gorgon have 10% chance to kill (counted separately in H3) -> binomial distribution
  4512. //original formula x = min(x, (gorgons_count + 9)/10);
  4513. double chanceToKill = attacker->valOfBonuses(Bonus::DEATH_STARE, 0) / 100.0f;
  4514. vstd::amin(chanceToKill, 1); //cap at 100%
  4515. std::binomial_distribution<> distribution(attacker->count, chanceToKill);
  4516. std::mt19937 rng(std::time(nullptr));
  4517. int staredCreatures = distribution(rng);
  4518. double cap = 1 / std::max(chanceToKill, (double)(0.01));//don't divide by 0
  4519. int maxToKill = (attacker->count + cap - 1) / cap; //not much more than chance * count
  4520. vstd::amin(staredCreatures, maxToKill);
  4521. staredCreatures += (attacker->level() * attacker->valOfBonuses(Bonus::DEATH_STARE, 1)) / gs->curB->battleGetStackByID(bat.bsa.at(0).stackAttacked)->level();
  4522. if (staredCreatures)
  4523. {
  4524. if (bat.bsa.at(0).newAmount > 0) //TODO: death stare was not originally available for multiple-hex attacks, but...
  4525. cast(SpellID::DEATH_STARE, staredCreatures);
  4526. }
  4527. }
  4528. int acidDamage = 0;
  4529. TBonusListPtr acidBreath = attacker->getBonuses(Selector::type(Bonus::ACID_BREATH));
  4530. for(const Bonus *b : *acidBreath)
  4531. {
  4532. if (b->additionalInfo > gs->getRandomGenerator().nextInt(99))
  4533. acidDamage += b->val;
  4534. }
  4535. if (acidDamage)
  4536. {
  4537. cast(SpellID::ACID_BREATH_DAMAGE, acidDamage * attacker->count);
  4538. }
  4539. }
  4540. bool CGameHandler::castSpell(const CGHeroInstance *h, SpellID spellID, const int3 &pos)
  4541. {
  4542. const CSpell *s = spellID.toSpell();
  4543. AdventureSpellCastParameters p;
  4544. p.caster = h;
  4545. p.pos = pos;
  4546. return s->adventureCast(spellEnv, p);
  4547. }
  4548. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  4549. {
  4550. if (!t.visitableObjects.empty())
  4551. {
  4552. //to prevent self-visiting heroes on space press
  4553. if(t.visitableObjects.back() != h)
  4554. objectVisited(t.visitableObjects.back(), h);
  4555. else if(t.visitableObjects.size() > 1)
  4556. objectVisited(*(t.visitableObjects.end()-2),h);
  4557. }
  4558. }
  4559. bool CGameHandler::sacrificeCreatures(const IMarket *market, const CGHeroInstance *hero, SlotID slot, ui32 count)
  4560. {
  4561. int oldCount = hero->getStackCount(slot);
  4562. if(oldCount < count)
  4563. COMPLAIN_RET("Not enough creatures to sacrifice!")
  4564. else if(oldCount == count && hero->stacksCount() == 1 && hero->needsLastStack())
  4565. COMPLAIN_RET("Cannot sacrifice last creature!");
  4566. int crid = hero->getStack(slot).type->idNumber;
  4567. changeStackCount(StackLocation(hero, slot), -count);
  4568. int dump, exp;
  4569. market->getOffer(crid, 0, dump, exp, EMarketMode::CREATURE_EXP);
  4570. exp *= count;
  4571. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(exp));
  4572. return true;
  4573. }
  4574. bool CGameHandler::sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, ArtifactPosition slot)
  4575. {
  4576. ArtifactLocation al(hero, slot);
  4577. const CArtifactInstance *a = al.getArt();
  4578. if(!a)
  4579. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  4580. int dmp, expToGive;
  4581. m->getOffer(hero->getArtTypeId(slot), 0, dmp, expToGive, EMarketMode::ARTIFACT_EXP);
  4582. removeArtifact(al);
  4583. changePrimSkill(hero, PrimarySkill::EXPERIENCE, expToGive);
  4584. return true;
  4585. }
  4586. void CGameHandler::makeStackDoNothing(const CStack * next)
  4587. {
  4588. BattleAction doNothing;
  4589. doNothing.actionType = Battle::NO_ACTION;
  4590. doNothing.additionalInfo = 0;
  4591. doNothing.destinationTile = -1;
  4592. doNothing.side = !next->attackerOwned;
  4593. doNothing.stackNumber = next->ID;
  4594. makeAutomaticAction(next, doNothing);
  4595. }
  4596. bool CGameHandler::insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count)
  4597. {
  4598. if(sl.army->hasStackAtSlot(sl.slot))
  4599. COMPLAIN_RET("Slot is already taken!");
  4600. if(!sl.slot.validSlot())
  4601. COMPLAIN_RET("Cannot insert stack to that slot!");
  4602. InsertNewStack ins;
  4603. ins.sl = sl;
  4604. ins.stack = CStackBasicDescriptor(c, count);
  4605. sendAndApply(&ins);
  4606. return true;
  4607. }
  4608. bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval/* = false*/)
  4609. {
  4610. if(!sl.army->hasStackAtSlot(sl.slot))
  4611. COMPLAIN_RET("Cannot find a stack to erase");
  4612. if(sl.army->stacksCount() == 1 //from the last stack
  4613. && sl.army->needsLastStack() //that must be left
  4614. && !forceRemoval) //ignore above conditions if we are forcing removal
  4615. {
  4616. COMPLAIN_RET("Cannot erase the last stack!");
  4617. }
  4618. EraseStack es;
  4619. es.sl = sl;
  4620. sendAndApply(&es);
  4621. return true;
  4622. }
  4623. bool CGameHandler::changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue /*= false*/)
  4624. {
  4625. TQuantity currentCount = sl.army->getStackCount(sl.slot);
  4626. if((absoluteValue && count < 0)
  4627. || (!absoluteValue && -count > currentCount))
  4628. {
  4629. COMPLAIN_RET("Cannot take more stacks than present!");
  4630. }
  4631. if((currentCount == -count && !absoluteValue)
  4632. || (!count && absoluteValue))
  4633. {
  4634. eraseStack(sl);
  4635. }
  4636. else
  4637. {
  4638. ChangeStackCount csc;
  4639. csc.sl = sl;
  4640. csc.count = count;
  4641. csc.absoluteValue = absoluteValue;
  4642. sendAndApply(&csc);
  4643. }
  4644. return true;
  4645. }
  4646. bool CGameHandler::addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count)
  4647. {
  4648. const CCreature *slotC = sl.army->getCreature(sl.slot);
  4649. if(!slotC) //slot is empty
  4650. insertNewStack(sl, c, count);
  4651. else if(c == slotC)
  4652. changeStackCount(sl, count);
  4653. else
  4654. {
  4655. COMPLAIN_RET("Cannot add " + c->namePl + " to slot " + boost::lexical_cast<std::string>(sl.slot) + "!");
  4656. }
  4657. return true;
  4658. }
  4659. void CGameHandler::tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging)
  4660. {
  4661. if(removeObjWhenFinished)
  4662. removeAfterVisit(src);
  4663. if(!src->canBeMergedWith(*dst, allowMerging))
  4664. {
  4665. if (allowMerging) //do that, add all matching creatures.
  4666. {
  4667. bool cont = true;
  4668. while (cont)
  4669. {
  4670. for(auto i = src->stacks.begin(); i != src->stacks.end(); i++)//while there are unmoved creatures
  4671. {
  4672. SlotID pos = dst->getSlotFor(i->second->type);
  4673. if(pos.validSlot())
  4674. {
  4675. moveStack(StackLocation(src, i->first), StackLocation(dst, pos));
  4676. cont = true;
  4677. break; //or iterator crashes
  4678. }
  4679. cont = false;
  4680. }
  4681. }
  4682. }
  4683. showGarrisonDialog(src->id, dst->id, true); //show garrison window and optionally remove ourselves from map when player ends
  4684. }
  4685. else //merge
  4686. {
  4687. moveArmy(src, dst, allowMerging);
  4688. }
  4689. }
  4690. bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count)
  4691. {
  4692. if(!src.army->hasStackAtSlot(src.slot))
  4693. COMPLAIN_RET("No stack to move!");
  4694. if(dst.army->hasStackAtSlot(dst.slot) && dst.army->getCreature(dst.slot) != src.army->getCreature(src.slot))
  4695. COMPLAIN_RET("Cannot move: stack of different type at destination pos!");
  4696. if(!dst.slot.validSlot())
  4697. COMPLAIN_RET("Cannot move stack to that slot!");
  4698. if(count == -1)
  4699. {
  4700. count = src.army->getStackCount(src.slot);
  4701. }
  4702. if(src.army != dst.army //moving away
  4703. && count == src.army->getStackCount(src.slot) //all creatures
  4704. && src.army->stacksCount() == 1 //from the last stack
  4705. && src.army->needsLastStack()) //that must be left
  4706. {
  4707. COMPLAIN_RET("Cannot move away the last creature!");
  4708. }
  4709. RebalanceStacks rs;
  4710. rs.src = src;
  4711. rs.dst = dst;
  4712. rs.count = count;
  4713. sendAndApply(&rs);
  4714. return true;
  4715. }
  4716. bool CGameHandler::swapStacks(const StackLocation &sl1, const StackLocation &sl2)
  4717. {
  4718. if(!sl1.army->hasStackAtSlot(sl1.slot))
  4719. return moveStack(sl2, sl1);
  4720. else if(!sl2.army->hasStackAtSlot(sl2.slot))
  4721. return moveStack(sl1, sl2);
  4722. else
  4723. {
  4724. SwapStacks ss;
  4725. ss.sl1 = sl1;
  4726. ss.sl2 = sl2;
  4727. sendAndApply(&ss);
  4728. return true;
  4729. }
  4730. }
  4731. void CGameHandler::runBattle()
  4732. {
  4733. setBattle(gs->curB);
  4734. assert(gs->curB);
  4735. //TODO: pre-tactic stuff, call scripts etc.
  4736. //tactic round
  4737. {
  4738. while(gs->curB->tacticDistance && !battleResult.get())
  4739. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  4740. }
  4741. //spells opening battle
  4742. for(int i = 0; i < 2; ++i)
  4743. {
  4744. auto h = gs->curB->battleGetFightingHero(i);
  4745. if(h && h->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL))
  4746. {
  4747. TBonusListPtr bl = h->getBonuses(Selector::type(Bonus::OPENING_BATTLE_SPELL));
  4748. for (Bonus *b : *bl)
  4749. {
  4750. const CSpell * spell = SpellID(b->subtype).toSpell();
  4751. BattleSpellCastParameters parameters(gs->curB, h, spell);
  4752. parameters.spellLvl = 3;
  4753. parameters.effectLevel = 3;
  4754. parameters.aimToHex(BattleHex::INVALID);
  4755. parameters.mode = ECastingMode::PASSIVE_CASTING;
  4756. parameters.selectedStack = nullptr;
  4757. parameters.enchantPower = b->val;
  4758. spell->battleCast(spellEnv, parameters);
  4759. }
  4760. }
  4761. }
  4762. //main loop
  4763. while(!battleResult.get()) //till the end of the battle ;]
  4764. {
  4765. NEW_ROUND;
  4766. auto obstacles = gs->curB->obstacles; //we copy container, because we're going to modify it
  4767. for(auto &obstPtr : obstacles)
  4768. {
  4769. if(const SpellCreatedObstacle *sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get()))
  4770. if(sco->turnsRemaining == 0)
  4771. removeObstacle(*obstPtr);
  4772. }
  4773. const BattleInfo & curB = *gs->curB;
  4774. //remove clones after all mechanics and animations are handled!
  4775. std::set <const CStack*> stacksToRemove;
  4776. for (auto stack : curB.stacks)
  4777. {
  4778. if (stack->idDeadClone())
  4779. stacksToRemove.insert(stack);
  4780. }
  4781. for (auto stack : stacksToRemove)
  4782. {
  4783. BattleStacksRemoved bsr;
  4784. bsr.stackIDs.insert(stack->ID);
  4785. sendAndApply(&bsr);
  4786. }
  4787. //stack loop
  4788. const CStack *next;
  4789. while(!battleResult.get() && (next = curB.getNextStack()) && next->willMove())
  4790. {
  4791. //check for bad morale => freeze
  4792. int nextStackMorale = next->MoraleVal();
  4793. if( nextStackMorale < 0 &&
  4794. !(NBonus::hasOfType(gs->curB->battleGetFightingHero(0), Bonus::BLOCK_MORALE)
  4795. || NBonus::hasOfType(gs->curB->battleGetFightingHero(1), Bonus::BLOCK_MORALE)) //checking if gs->curB->heroes have (or don't have) morale blocking bonuses)
  4796. )
  4797. {
  4798. if(gs->getRandomGenerator().nextInt(23) < -2 * nextStackMorale)
  4799. {
  4800. //unit loses its turn - empty freeze action
  4801. BattleAction ba;
  4802. ba.actionType = Battle::BAD_MORALE;
  4803. ba.additionalInfo = 1;
  4804. ba.side = !next->attackerOwned;
  4805. ba.stackNumber = next->ID;
  4806. makeAutomaticAction(next, ba);
  4807. continue;
  4808. }
  4809. }
  4810. if(next->hasBonusOfType(Bonus::ATTACKS_NEAREST_CREATURE)) //while in berserk
  4811. { //fixme: stack should not attack itself
  4812. std::pair<const CStack *, int> attackInfo = curB.getNearestStack(next, boost::logic::indeterminate);
  4813. if(attackInfo.first != nullptr)
  4814. {
  4815. BattleAction attack;
  4816. attack.actionType = Battle::WALK_AND_ATTACK;
  4817. attack.side = !next->attackerOwned;
  4818. attack.stackNumber = next->ID;
  4819. attack.additionalInfo = attackInfo.first->position;
  4820. attack.destinationTile = attackInfo.second;
  4821. makeAutomaticAction(next, attack);
  4822. }
  4823. else
  4824. {
  4825. makeStackDoNothing(next);
  4826. }
  4827. continue;
  4828. }
  4829. const CGHeroInstance * curOwner = gs->curB->battleGetOwner(next);
  4830. if( (next->position < 0 || next->getCreature()->idNumber == CreatureID::BALLISTA) //arrow turret or ballista
  4831. && (!curOwner || curOwner->getSecSkillLevel(SecondarySkill::ARTILLERY) == 0)) //hero has no artillery
  4832. {
  4833. BattleAction attack;
  4834. attack.actionType = Battle::SHOOT;
  4835. attack.side = !next->attackerOwned;
  4836. attack.stackNumber = next->ID;
  4837. for(auto & elem : gs->curB->stacks)
  4838. {
  4839. if(elem->owner != next->owner && elem->isValidTarget())
  4840. {
  4841. attack.destinationTile = elem->position;
  4842. break;
  4843. }
  4844. }
  4845. makeAutomaticAction(next, attack);
  4846. continue;
  4847. }
  4848. if(next->getCreature()->idNumber == CreatureID::CATAPULT)
  4849. {
  4850. const auto & attackableBattleHexes = curB.getAttackableBattleHexes();
  4851. if(attackableBattleHexes.empty())
  4852. {
  4853. makeStackDoNothing(next);
  4854. continue;
  4855. }
  4856. if(!curOwner || curOwner->getSecSkillLevel(SecondarySkill::BALLISTICS) == 0)
  4857. {
  4858. BattleAction attack;
  4859. attack.destinationTile = *RandomGeneratorUtil::nextItem(attackableBattleHexes,
  4860. gs->getRandomGenerator());
  4861. attack.actionType = Battle::CATAPULT;
  4862. attack.additionalInfo = 0;
  4863. attack.side = !next->attackerOwned;
  4864. attack.stackNumber = next->ID;
  4865. makeAutomaticAction(next, attack);
  4866. continue;
  4867. }
  4868. }
  4869. if(next->getCreature()->idNumber == CreatureID::FIRST_AID_TENT)
  4870. {
  4871. TStacks possibleStacks = battleGetStacksIf([&](const CStack * s){
  4872. return s->owner == next->owner && s->canBeHealed();
  4873. });
  4874. if(!possibleStacks.size())
  4875. {
  4876. makeStackDoNothing(next);
  4877. continue;
  4878. }
  4879. if(!curOwner || curOwner->getSecSkillLevel(SecondarySkill::FIRST_AID) == 0) //no hero or hero has no first aid
  4880. {
  4881. range::random_shuffle(possibleStacks);
  4882. const CStack * toBeHealed = possibleStacks.front();
  4883. BattleAction heal;
  4884. heal.actionType = Battle::STACK_HEAL;
  4885. heal.additionalInfo = 0;
  4886. heal.destinationTile = toBeHealed->position;
  4887. heal.side = !next->attackerOwned;
  4888. heal.stackNumber = next->ID;
  4889. makeAutomaticAction(next, heal);
  4890. continue;
  4891. }
  4892. }
  4893. int numberOfAsks = 1;
  4894. bool breakOuter = false;
  4895. do
  4896. {//ask interface and wait for answer
  4897. if(!battleResult.get())
  4898. {
  4899. stackTurnTrigger(next); //various effects
  4900. if (vstd::contains(next->state, EBattleStackState::FEAR))
  4901. {
  4902. makeStackDoNothing(next); //end immediately if stack was affected by fear
  4903. }
  4904. else
  4905. {
  4906. logGlobal->traceStream() << "Activating " << next->nodeName();
  4907. auto nextId = next->ID;
  4908. BattleSetActiveStack sas;
  4909. sas.stack = nextId;
  4910. sendAndApply(&sas);
  4911. auto actionWasMade = [&]() -> bool
  4912. {
  4913. if(battleMadeAction.data)//active stack has made its action
  4914. return true;
  4915. if(battleResult.get())// battle is finished
  4916. return true;
  4917. if(next == nullptr)//active stack was been removed
  4918. return true;
  4919. return !next->alive();//active stack is dead
  4920. };
  4921. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  4922. battleMadeAction.data = false;
  4923. while(!actionWasMade())
  4924. {
  4925. battleMadeAction.cond.wait(lock);
  4926. if(battleGetStackByID(nextId, false) != next)
  4927. next = nullptr; //it may be removed, while we wait
  4928. }
  4929. }
  4930. }
  4931. if(battleResult.get()) //don't touch it, battle could be finished while waiting got action
  4932. {
  4933. breakOuter = true;
  4934. break;
  4935. }
  4936. //we're after action, all results applied
  4937. checkForBattleEnd(); //check if this action ended the battle
  4938. if(next != nullptr)
  4939. {
  4940. //check for good morale
  4941. nextStackMorale = next->MoraleVal();
  4942. if(!vstd::contains(next->state,EBattleStackState::HAD_MORALE) //only one extra move per turn possible
  4943. && !vstd::contains(next->state,EBattleStackState::DEFENDING)
  4944. && !next->waited()
  4945. && !vstd::contains(next->state, EBattleStackState::FEAR)
  4946. && next->alive()
  4947. && nextStackMorale > 0
  4948. && !(NBonus::hasOfType(gs->curB->battleGetFightingHero(0), Bonus::BLOCK_MORALE)
  4949. || NBonus::hasOfType(gs->curB->battleGetFightingHero(1), Bonus::BLOCK_MORALE)) //checking if gs->curB->heroes have (or don't have) morale blocking bonuses
  4950. )
  4951. {
  4952. if(gs->getRandomGenerator().nextInt(23) < nextStackMorale) //this stack hasn't got morale this turn
  4953. {
  4954. BattleTriggerEffect bte;
  4955. bte.stackID = next->ID;
  4956. bte.effect = Bonus::MORALE;
  4957. bte.val = 1;
  4958. bte.additionalInfo = 0;
  4959. sendAndApply(&bte); //play animation
  4960. ++numberOfAsks; //move this stack once more
  4961. }
  4962. }
  4963. }
  4964. --numberOfAsks;
  4965. } while (numberOfAsks > 0);
  4966. if (breakOuter)
  4967. {
  4968. break;
  4969. }
  4970. }
  4971. }
  4972. endBattle(gs->curB->tile, gs->curB->battleGetFightingHero(0), gs->curB->battleGetFightingHero(1));
  4973. }
  4974. bool CGameHandler::makeAutomaticAction(const CStack *stack, BattleAction &ba)
  4975. {
  4976. BattleSetActiveStack bsa;
  4977. bsa.stack = stack->ID;
  4978. bsa.askPlayerInterface = false;
  4979. sendAndApply(&bsa);
  4980. bool ret = makeBattleAction(ba);
  4981. checkForBattleEnd();
  4982. return ret;
  4983. }
  4984. void CGameHandler::giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos)
  4985. {
  4986. assert(a->artType);
  4987. ArtifactLocation al;
  4988. al.artHolder = const_cast<CGHeroInstance*>(h);
  4989. ArtifactPosition slot = ArtifactPosition::PRE_FIRST;
  4990. if(pos < 0)
  4991. {
  4992. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  4993. slot = a->firstAvailableSlot(h);
  4994. else
  4995. slot = a->firstBackpackSlot(h);
  4996. }
  4997. else
  4998. {
  4999. slot = pos;
  5000. }
  5001. al.slot = slot;
  5002. if(slot < 0 || !a->canBePutAt(al))
  5003. {
  5004. complain("Cannot put artifact in that slot!");
  5005. return;
  5006. }
  5007. putArtifact(al, a);
  5008. }
  5009. void CGameHandler::putArtifact(const ArtifactLocation &al, const CArtifactInstance *a)
  5010. {
  5011. PutArtifact pa;
  5012. pa.art = a;
  5013. pa.al = al;
  5014. sendAndApply(&pa);
  5015. }
  5016. void CGameHandler::giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos)
  5017. {
  5018. CArtifactInstance *a = nullptr;
  5019. if(!artType->constituents)
  5020. {
  5021. a = new CArtifactInstance();
  5022. }
  5023. else
  5024. {
  5025. a = new CCombinedArtifactInstance();
  5026. }
  5027. a->artType = artType; //*NOT* via settype -> all bonus-related stuff must be done by NewArtifact apply
  5028. NewArtifact na;
  5029. na.art = a;
  5030. sendAndApply(&na); // -> updates a!!!, will create a on other machines
  5031. giveHeroArtifact(h, a, pos);
  5032. }
  5033. void CGameHandler::setBattleResult(BattleResult::EResult resultType, int victoriusSide)
  5034. {
  5035. boost::unique_lock<boost::mutex> guard(battleResult.mx);
  5036. if(battleResult.data)
  5037. {
  5038. complain((boost::format("The battle result has been already set (to %d, asked to %d)")
  5039. % battleResult.data->result % resultType).str());
  5040. return;
  5041. }
  5042. auto br = new BattleResult;
  5043. br->result = resultType;
  5044. br->winner = victoriusSide; //surrendering side loses
  5045. gs->curB->calculateCasualties(br->casualties);
  5046. battleResult.data = br;
  5047. }
  5048. void CGameHandler::commitPackage( CPackForClient *pack )
  5049. {
  5050. sendAndApply(pack);
  5051. }
  5052. void CGameHandler::spawnWanderingMonsters(CreatureID creatureID)
  5053. {
  5054. std::vector<int3>::iterator tile;
  5055. std::vector<int3> tiles;
  5056. getFreeTiles(tiles);
  5057. ui32 amount = tiles.size() / 200; //Chance is 0.5% for each tile
  5058. std::random_shuffle(tiles.begin(), tiles.end());
  5059. logGlobal->traceStream() << "Spawning wandering monsters. Found " << tiles.size() << " free tiles. Creature type: " << creatureID;
  5060. const CCreature *cre = VLC->creh->creatures.at(creatureID);
  5061. for (int i = 0; i < amount; ++i)
  5062. {
  5063. tile = tiles.begin();
  5064. logGlobal->traceStream() << "\tSpawning monster at " << *tile;
  5065. putNewMonster(creatureID, cre->getRandomAmount(std::rand), *tile);
  5066. tiles.erase(tile); //not use it again
  5067. }
  5068. }
  5069. void CGameHandler::removeObstacle(const CObstacleInstance &obstacle)
  5070. {
  5071. ObstaclesRemoved obsRem;
  5072. obsRem.obstacles.insert(obstacle.uniqueID);
  5073. sendAndApply(&obsRem);
  5074. }
  5075. void CGameHandler::synchronizeArtifactHandlerLists()
  5076. {
  5077. UpdateArtHandlerLists uahl;
  5078. uahl.treasures = VLC->arth->treasures;
  5079. uahl.minors = VLC->arth->minors;
  5080. uahl.majors = VLC->arth->majors;
  5081. uahl.relics = VLC->arth->relics;
  5082. sendAndApply(&uahl);
  5083. }
  5084. bool CGameHandler::isValidObject(const CGObjectInstance *obj) const
  5085. {
  5086. return vstd::contains(gs->map->objects, obj);
  5087. }
  5088. bool CGameHandler::isBlockedByQueries(const CPack *pack, PlayerColor player)
  5089. {
  5090. if(!strcmp(typeid(*pack).name(), typeid(PlayerMessage).name()))
  5091. return false;
  5092. auto query = queries.topQuery(player);
  5093. if(query && query->blocksPack(pack))
  5094. {
  5095. complain(boost::str(boost::format("Player %s has to answer queries before attempting any further actions. Top query is %s!") % player % query->toString()));
  5096. return true;
  5097. }
  5098. return false;
  5099. }
  5100. void CGameHandler::removeAfterVisit(const CGObjectInstance *object)
  5101. {
  5102. //If the object is being visited, there must be a matching query
  5103. for(const auto &query : queries.allQueries())
  5104. {
  5105. if(auto someVistQuery = std::dynamic_pointer_cast<CObjectVisitQuery>(query))
  5106. {
  5107. if(someVistQuery->visitedObject == object)
  5108. {
  5109. someVistQuery->removeObjectAfterVisit = true;
  5110. return;
  5111. }
  5112. }
  5113. };
  5114. //If we haven't returned so far, there is no query and no visit, call was wrong
  5115. assert("This function needs to be called during the object visit!");
  5116. }
  5117. void CGameHandler::changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide)
  5118. {
  5119. std::unordered_set<int3, ShashInt3> tiles;
  5120. getTilesInRange(tiles, center, radius, player, hide? -1 : 1);
  5121. if (hide)
  5122. {
  5123. std::unordered_set<int3, ShashInt3> observedTiles; //do not hide tiles observed by heroes. May lead to disastrous AI problems
  5124. auto p = gs->getPlayer(player);
  5125. for (auto h : p->heroes)
  5126. {
  5127. getTilesInRange(observedTiles, h->getSightCenter(), h->getSightRadious(), h->tempOwner, -1);
  5128. }
  5129. for (auto t : p->towns)
  5130. {
  5131. getTilesInRange(observedTiles, t->getSightCenter(), t->getSightRadious(), t->tempOwner, -1);
  5132. }
  5133. for (auto tile : observedTiles)
  5134. vstd::erase_if_present (tiles, tile);
  5135. }
  5136. changeFogOfWar(tiles, player, hide);
  5137. }
  5138. void CGameHandler::changeFogOfWar(std::unordered_set<int3, ShashInt3> &tiles, PlayerColor player, bool hide)
  5139. {
  5140. FoWChange fow;
  5141. fow.tiles = tiles;
  5142. fow.player = player;
  5143. fow.mode = hide? 0 : 1;
  5144. sendAndApply(&fow);
  5145. }
  5146. bool CGameHandler::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero)
  5147. {
  5148. if(auto topQuery = queries.topQuery(hero->getOwner()))
  5149. if(auto visit = std::dynamic_pointer_cast<const CObjectVisitQuery>(topQuery))
  5150. return !(visit->visitedObject == obj && visit->visitingHero == hero);
  5151. return true;
  5152. }
  5153. void CGameHandler::duelFinished()
  5154. {
  5155. auto si = getStartInfo();
  5156. auto getName = [&](int i){ return si->getIthPlayersSettings(gs->curB->sides.at(i).color).name; };
  5157. int casualtiesPoints = 0;
  5158. logGlobal->debugStream() << boost::format("Winner side %d\nWinner casualties:")
  5159. % (int)battleResult.data->winner;
  5160. for(auto & elem : battleResult.data->casualties[battleResult.data->winner])
  5161. {
  5162. const CCreature *c = VLC->creh->creatures[elem.first];
  5163. logGlobal->debugStream() << boost::format("\t* %d of %s") % elem.second % c->namePl;
  5164. casualtiesPoints += c->AIValue * elem.second;
  5165. }
  5166. logGlobal->debugStream() << boost::format("Total casualties points: %d") % casualtiesPoints;
  5167. time_t timeNow;
  5168. time(&timeNow);
  5169. std::ofstream out(cmdLineOptions["resultsFile"].as<std::string>(), std::ios::app);
  5170. if(out)
  5171. {
  5172. out << boost::format("%s\t%s\t%s\t%d\t%d\t%d\t%s\n") % si->mapname % getName(0) % getName(1)
  5173. % battleResult.data->winner % battleResult.data->result % casualtiesPoints
  5174. % asctime(localtime(&timeNow));
  5175. }
  5176. else
  5177. {
  5178. logGlobal->errorStream() << "Cannot open to write " << cmdLineOptions["resultsFile"].as<std::string>();
  5179. }
  5180. CSaveFile resultFile("result.vdrst");
  5181. resultFile << *battleResult.data;
  5182. BattleResultsApplied resultsApplied;
  5183. resultsApplied.player1 = finishingBattle->victor;
  5184. resultsApplied.player2 = finishingBattle->loser;
  5185. sendAndApply(&resultsApplied);
  5186. return;
  5187. }
  5188. CasualtiesAfterBattle::CasualtiesAfterBattle(const CArmedInstance *army, BattleInfo *bat)
  5189. {
  5190. heroWithDeadCommander = ObjectInstanceID();
  5191. PlayerColor color = army->tempOwner;
  5192. if(color == PlayerColor::UNFLAGGABLE)
  5193. color = PlayerColor::NEUTRAL;
  5194. for(CStack *st : bat->stacks)
  5195. {
  5196. if(vstd::contains(st->state, EBattleStackState::SUMMONED)) //don't take into account summoned stacks
  5197. continue;
  5198. if (st->owner != color) //remove only our stacks
  5199. continue;
  5200. //FIXME: this info is also used in BattleInfo::calculateCasualties, refactor
  5201. st->count = std::max (0, st->count - st->resurrected);
  5202. if (!st->count && !st->base) //we can imagine stacks of war mahcines that are not spawned by artifacts?
  5203. {
  5204. auto warMachine = VLC->arth->creatureToMachineID(st->type->idNumber);
  5205. //catapult artifact remain even if "creature" killed in siege
  5206. if(warMachine != ArtifactID::NONE && warMachine != ArtifactID::CATAPULT)
  5207. {
  5208. auto hero = dynamic_ptr_cast<CGHeroInstance> (army);
  5209. if (hero)
  5210. removedWarMachines.push_back (ArtifactLocation(hero, hero->getArtPos(warMachine, true)));
  5211. }
  5212. }
  5213. if(!army->slotEmpty(st->slot) && st->count < army->getStackCount(st->slot))
  5214. {
  5215. StackLocation sl(army, st->slot);
  5216. if(st->alive())
  5217. newStackCounts.push_back(std::pair<StackLocation, int>(sl, st->count));
  5218. else
  5219. newStackCounts.push_back(std::pair<StackLocation, int>(sl, 0));
  5220. }
  5221. if (st->base && !st->count)
  5222. {
  5223. auto c = dynamic_cast <const CCommanderInstance *>(st->base);
  5224. if (c) //switch commander status to dead
  5225. {
  5226. auto h = dynamic_cast <const CGHeroInstance *>(army);
  5227. if (h && h->commander == c)
  5228. heroWithDeadCommander = army->id; //TODO: unify commander handling
  5229. }
  5230. }
  5231. }
  5232. }
  5233. void CasualtiesAfterBattle::takeFromArmy(CGameHandler *gh)
  5234. {
  5235. for(TStackAndItsNewCount &ncount : newStackCounts)
  5236. {
  5237. if(ncount.second > 0)
  5238. gh->changeStackCount(ncount.first, ncount.second, true);
  5239. else
  5240. gh->eraseStack(ncount.first, true);
  5241. }
  5242. for (auto al : removedWarMachines)
  5243. {
  5244. gh->removeArtifact(al);
  5245. }
  5246. if (heroWithDeadCommander != ObjectInstanceID())
  5247. {
  5248. SetCommanderProperty scp;
  5249. scp.heroid = heroWithDeadCommander;
  5250. scp.which = SetCommanderProperty::ALIVE;
  5251. scp.amount = 0;
  5252. gh->sendAndApply (&scp);
  5253. }
  5254. }
  5255. CGameHandler::FinishingBattleHelper::FinishingBattleHelper(std::shared_ptr<const CBattleQuery> Query, bool Duel, int RemainingBattleQueriesCount)
  5256. {
  5257. assert(Query->result);
  5258. assert(Query->bi);
  5259. auto &result = *Query->result;
  5260. auto &info = *Query->bi;
  5261. winnerHero = result.winner != 0 ? info.sides[1].hero : info.sides[0].hero;
  5262. loserHero = result.winner != 0 ? info.sides[0].hero : info.sides[1].hero;
  5263. victor = info.sides[result.winner].color;
  5264. loser = info.sides[!result.winner].color;
  5265. duel = Duel;
  5266. remainingBattleQueriesCount = RemainingBattleQueriesCount;
  5267. }
  5268. CGameHandler::FinishingBattleHelper::FinishingBattleHelper()
  5269. {
  5270. winnerHero = loserHero = nullptr;
  5271. }
  5272. ///ServerSpellCastEnvironment
  5273. ServerSpellCastEnvironment::ServerSpellCastEnvironment(CGameHandler * gh): gh(gh)
  5274. {
  5275. }
  5276. void ServerSpellCastEnvironment::sendAndApply(CPackForClient * info) const
  5277. {
  5278. gh->sendAndApply(info);
  5279. }
  5280. CRandomGenerator & ServerSpellCastEnvironment::getRandomGenerator() const
  5281. {
  5282. return gh->gameState()->getRandomGenerator();
  5283. }
  5284. void ServerSpellCastEnvironment::complain(const std::string& problem) const
  5285. {
  5286. gh->complain(problem);
  5287. }
  5288. const CGameInfoCallback * ServerSpellCastEnvironment::getCb() const
  5289. {
  5290. return gh;
  5291. }
  5292. const CMap * ServerSpellCastEnvironment::getMap() const
  5293. {
  5294. return gh->gameState()->map;
  5295. }
  5296. bool ServerSpellCastEnvironment::moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, PlayerColor asker) const
  5297. {
  5298. return gh->moveHero(hid, dst, teleporting, false, asker);
  5299. }