CGameHandler.cpp 188 KB

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