CGameHandler.cpp 189 KB

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