CGameHandler.cpp 153 KB

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