CGameHandler.cpp 191 KB

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