CGameHandler.cpp 147 KB

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