CGameHandler.cpp 177 KB

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