CGameHandler.cpp 172 KB

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