CGameHandler.cpp 191 KB

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