CGameHandler.cpp 191 KB

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