CGameHandler.cpp 185 KB

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