CGameHandler.cpp 195 KB

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