CGameHandler.cpp 199 KB

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