CGameHandler.cpp 149 KB

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