CGameHandler.cpp 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814
  1. #include "../StartInfo.h"
  2. #include "../hch/CArtHandler.h"
  3. #include "../hch/CBuildingHandler.h"
  4. #include "../hch/CDefObjInfoHandler.h"
  5. #include "../hch/CHeroHandler.h"
  6. #include "../hch/CObjectHandler.h"
  7. #include "../hch/CSpellHandler.h"
  8. #include "../hch/CGeneralTextHandler.h"
  9. #include "../hch/CTownHandler.h"
  10. #include "../lib/CGameState.h"
  11. #include "../lib/CondSh.h"
  12. #include "../lib/NetPacks.h"
  13. #include "../lib/VCMI_Lib.h"
  14. #include "../lib/map.h"
  15. #include "../lib/VCMIDirs.h"
  16. #include "CGameHandler.h"
  17. #include <boost/bind.hpp>
  18. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  19. #include <boost/foreach.hpp>
  20. #include <boost/thread.hpp>
  21. #include <boost/thread/shared_mutex.hpp>
  22. #include <boost/assign/list_of.hpp>
  23. #include <fstream>
  24. #include <boost/system/system_error.hpp>
  25. /*
  26. * CGameHandler.cpp, part of VCMI engine
  27. *
  28. * Authors: listed in file AUTHORS in main folder
  29. *
  30. * License: GNU General Public License v2.0 or later
  31. * Full text of license available in license.txt file, in main folder
  32. *
  33. */
  34. #undef DLL_EXPORT
  35. #define DLL_EXPORT
  36. #include "../lib/RegisterTypes.cpp"
  37. #ifndef _MSC_VER
  38. #include <boost/thread/xtime.hpp>
  39. #endif
  40. extern bool end2;
  41. #ifdef min
  42. #undef min
  43. #endif
  44. #ifdef max
  45. #undef max
  46. #endif
  47. #define NEW_ROUND BattleNextRound bnr;\
  48. bnr.round = gs->curB->round + 1;\
  49. sendAndApply(&bnr);
  50. CondSh<bool> battleMadeAction;
  51. CondSh<BattleResult *> battleResult(NULL);
  52. class CBaseForGHApply
  53. {
  54. public:
  55. virtual bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  56. };
  57. template <typename T> class CApplyOnGH : public CBaseForGHApply
  58. {
  59. public:
  60. bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  61. {
  62. T *ptr = static_cast<T*>(pack);
  63. ptr->c = c;
  64. return ptr->applyGh(gh);
  65. }
  66. };
  67. class CGHApplier
  68. {
  69. public:
  70. std::map<ui16,CBaseForGHApply*> apps;
  71. CGHApplier()
  72. {
  73. registerTypes3(*this);
  74. }
  75. template<typename T> void registerType(const T * t=NULL)
  76. {
  77. ui16 ID = typeList.registerType(t);
  78. apps[ID] = new CApplyOnGH<T>;
  79. }
  80. } *applier = NULL;
  81. CMP_stack cmpst ;
  82. static inline double distance(int3 a, int3 b)
  83. {
  84. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  85. }
  86. static void giveExp(BattleResult &r)
  87. {
  88. r.exp[0] = 0;
  89. r.exp[1] = 0;
  90. for(std::map<ui32,si32>::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  91. {
  92. r.exp[r.winner] += VLC->creh->creatures[i->first].hitPoints * i->second;
  93. }
  94. }
  95. PlayerStatus PlayerStatuses::operator[](ui8 player)
  96. {
  97. boost::unique_lock<boost::mutex> l(mx);
  98. if(players.find(player) != players.end())
  99. {
  100. return players[player];
  101. }
  102. else
  103. {
  104. throw std::string("No such player!");
  105. }
  106. }
  107. void PlayerStatuses::addPlayer(ui8 player)
  108. {
  109. boost::unique_lock<boost::mutex> l(mx);
  110. players[player];
  111. }
  112. bool PlayerStatuses::hasQueries(ui8 player)
  113. {
  114. boost::unique_lock<boost::mutex> l(mx);
  115. if(players.find(player) != players.end())
  116. {
  117. return players[player].queries.size();
  118. }
  119. else
  120. {
  121. throw std::string("No such player!");
  122. }
  123. }
  124. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  125. {
  126. boost::unique_lock<boost::mutex> l(mx);
  127. if(players.find(player) != players.end())
  128. {
  129. return players[player].*flag;
  130. }
  131. else
  132. {
  133. throw std::string("No such player!");
  134. }
  135. }
  136. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  137. {
  138. boost::unique_lock<boost::mutex> l(mx);
  139. if(players.find(player) != players.end())
  140. {
  141. players[player].*flag = val;
  142. }
  143. else
  144. {
  145. throw std::string("No such player!");
  146. }
  147. cv.notify_all();
  148. }
  149. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  150. {
  151. boost::unique_lock<boost::mutex> l(mx);
  152. if(players.find(player) != players.end())
  153. {
  154. players[player].queries.insert(id);
  155. }
  156. else
  157. {
  158. throw std::string("No such player!");
  159. }
  160. cv.notify_all();
  161. }
  162. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  163. {
  164. boost::unique_lock<boost::mutex> l(mx);
  165. if(players.find(player) != players.end())
  166. {
  167. players[player].queries.erase(id);
  168. }
  169. else
  170. {
  171. throw std::string("No such player!");
  172. }
  173. cv.notify_all();
  174. }
  175. template <typename T>
  176. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  177. {
  178. fun(args[which]);
  179. }
  180. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  181. {
  182. SetSecSkill sss;
  183. sss.id = ID;
  184. sss.which = which;
  185. sss.val = val;
  186. sss.abs = abs;
  187. sendAndApply(&sss);
  188. if(which == 7) //Wisdom
  189. {
  190. const CGHeroInstance *h = getHero(ID);
  191. if(h && h->visitedTown)
  192. giveSpells(h->visitedTown, h);
  193. }
  194. }
  195. void CGameHandler::changePrimSkill(int ID, int which, si64 val, bool abs)
  196. {
  197. SetPrimSkill sps;
  198. sps.id = ID;
  199. sps.which = which;
  200. sps.abs = abs;
  201. sps.val = val;
  202. sendAndApply(&sps);
  203. if(which==4) //only for exp - hero may level up
  204. {
  205. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  206. while (hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  207. {
  208. //give prim skill
  209. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  210. int r = rand()%100, pom=0, x=0;
  211. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  212. for(;x<PRIMARY_SKILLS;x++)
  213. {
  214. pom += hero->type->heroClass->primChance[x].*g;
  215. if(r<pom)
  216. break;
  217. }
  218. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  219. SetPrimSkill sps;
  220. sps.id = ID;
  221. sps.which = x;
  222. sps.abs = false;
  223. sps.val = 1;
  224. sendAndApply(&sps);
  225. HeroLevelUp hlu;
  226. hlu.heroid = ID;
  227. hlu.primskill = x;
  228. hlu.level = hero->level+1;
  229. //picking sec. skills for choice
  230. std::set<int> basicAndAdv, expert, none;
  231. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  232. for(unsigned i=0;i<hero->secSkills.size();i++)
  233. {
  234. if(hero->secSkills[i].second < 3)
  235. basicAndAdv.insert(hero->secSkills[i].first);
  236. else
  237. expert.insert(hero->secSkills[i].first);
  238. none.erase(hero->secSkills[i].first);
  239. }
  240. //first offered skill
  241. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  242. {
  243. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  244. none.erase(hlu.skills.back());
  245. }
  246. else if(basicAndAdv.size())
  247. {
  248. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  249. hlu.skills.push_back(s);
  250. basicAndAdv.erase(s);
  251. }
  252. //second offered skill
  253. if(basicAndAdv.size())
  254. {
  255. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  256. }
  257. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  258. {
  259. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  260. }
  261. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  262. {
  263. boost::function<void(ui32)> callback = boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::changeSecSkill,this,ID,_1,1,0)),_1));
  264. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  265. }
  266. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  267. {
  268. sendAndApply(&hlu);
  269. changeSecSkill(ID,hlu.skills.back(),1,false);
  270. }
  271. else //apply and send info
  272. {
  273. sendAndApply(&hlu);
  274. }
  275. }
  276. }
  277. }
  278. static CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  279. {
  280. if(color == 254)
  281. color = 255;
  282. CCreatureSet ret(set);
  283. for(int i=0; i<bat->stacks.size();i++)
  284. {
  285. if(bat->stacks[i]->hasFeatureOfType(StackFeature::SUMMONED)) //don't take into account sumoned stacks
  286. continue;
  287. CStack *st = bat->stacks[i];
  288. if(st->owner==color && vstd::contains(set.slots,st->slot) && st->amount < set.slots.find(st->slot)->second.second)
  289. {
  290. if(st->alive())
  291. ret.slots[st->slot].second = st->amount;
  292. else
  293. ret.slots.erase(st->slot);
  294. }
  295. }
  296. return ret;
  297. }
  298. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town)
  299. {
  300. battleEndCallback = new boost::function<void(BattleResult*)>(cb);
  301. bEndArmy1 = army1;
  302. bEndArmy2 = army2;
  303. {
  304. BattleInfo *curB = new BattleInfo;
  305. curB->side1 = army1->tempOwner;
  306. curB->side2 = army2->tempOwner;
  307. if(curB->side2 == 254)
  308. curB->side2 = 255;
  309. setupBattle(curB, tile, army1->army, army2->army, hero1, hero2, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  310. }
  311. NEW_ROUND;
  312. //TODO: pre-tactic stuff, call scripts etc.
  313. //tactic round
  314. {
  315. NEW_ROUND;
  316. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  317. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  318. {
  319. //TODO: tactic round (round -1)
  320. }
  321. }
  322. //main loop
  323. while(!battleResult.get()) //till the end of the battle ;]
  324. {
  325. NEW_ROUND;
  326. std::vector<CStack*> & stacks = (gs->curB->stacks);
  327. const BattleInfo & curB = *gs->curB;
  328. //stack loop
  329. const CStack *next;
  330. while(!battleResult.get() && (next = curB.getNextStack()) && next->willMove())
  331. {
  332. //check for bad morale => freeze
  333. if(next->Morale() < 0 &&
  334. !((hero1->hasBonusOfType(HeroBonus::BLOCK_MORALE)) || (hero2->hasBonusOfType(HeroBonus::BLOCK_MORALE))) //checking if heroes have (or don't have) morale blocking bonuses)
  335. )
  336. {
  337. if( rand()%24 < (-next->Morale())*2 )
  338. {
  339. //unit loses its turn - empty freeze action
  340. BattleAction ba;
  341. ba.actionType = 11;
  342. ba.additionalInfo = 1;
  343. ba.side = !next->attackerOwned;
  344. ba.stackNumber = next->ID;
  345. sendAndApply(&StartAction(ba));
  346. sendAndApply(&EndAction());
  347. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  348. continue;
  349. }
  350. }
  351. if(next->hasFeatureOfType(StackFeature::ATTACKS_NEAREST_CREATURE)) //while in berserk
  352. {
  353. std::pair<const CStack *, int> attackInfo = curB.getNearestStack(next, boost::logic::indeterminate);
  354. if(attackInfo.first != NULL)
  355. {
  356. BattleAction attack;
  357. attack.actionType = 6;
  358. attack.side = !next->attackerOwned;
  359. attack.stackNumber = next->ID;
  360. attack.additionalInfo = attackInfo.first->position;
  361. attack.destinationTile = attackInfo.second;
  362. makeBattleAction(attack);
  363. checkForBattleEnd(stacks);
  364. }
  365. continue;
  366. }
  367. const CGHeroInstance * curOwner = gs->battleGetOwner(next->ID);
  368. if(next->position < 0 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //arrow turret, hero has no ballistics
  369. {
  370. BattleAction attack;
  371. attack.actionType = 7;
  372. attack.side = !next->attackerOwned;
  373. attack.stackNumber = next->ID;
  374. for(int g=0; g<gs->curB->stacks.size(); ++g)
  375. {
  376. if(gs->curB->stacks[g]->attackerOwned && gs->curB->stacks[g]->alive())
  377. {
  378. attack.destinationTile = gs->curB->stacks[g]->position;
  379. break;
  380. }
  381. }
  382. makeBattleAction(attack);
  383. checkForBattleEnd(stacks);
  384. continue;
  385. }
  386. if(next->creature->idNumber == 145 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //catapult, hero has no ballistics
  387. {
  388. BattleAction attack;
  389. static const int wallHexes[] = {50, 183, 182, 130, 62, 29, 12, 95};
  390. attack.destinationTile = wallHexes[ rand()%ARRAY_COUNT(wallHexes) ];
  391. attack.actionType = 9;
  392. attack.additionalInfo = 0;
  393. attack.side = !next->attackerOwned;
  394. attack.stackNumber = next->ID;
  395. makeBattleAction(attack);
  396. continue;
  397. }
  398. askInterfaceForMove:
  399. //ask interface and wait for answer
  400. if(!battleResult.get())
  401. {
  402. BattleSetActiveStack sas;
  403. sas.stack = next->ID;
  404. sendAndApply(&sas);
  405. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  406. while(next->alive() && (!battleMadeAction.data && !battleResult.get())) //active stack hasn't made its action and battle is still going
  407. battleMadeAction.cond.wait(lock);
  408. battleMadeAction.data = false;
  409. }
  410. else
  411. {
  412. break;
  413. }
  414. //we're after action, all results applied
  415. checkForBattleEnd(stacks); //check if this action ended the battle
  416. //check for good morale
  417. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  418. && !vstd::contains(next->state,DEFENDING)
  419. && !vstd::contains(next->state,WAITING)
  420. && next->alive()
  421. && next->Morale() > 0
  422. && !((hero1->hasBonusOfType(HeroBonus::BLOCK_MORALE)) || (hero2->hasBonusOfType(HeroBonus::BLOCK_MORALE)) ) //checking if heroes have (or don't have) morale blocking bonuses
  423. )
  424. if(rand()%24 < next->Morale()) //this stack hasn't got morale this turn
  425. goto askInterfaceForMove; //move this stack once more
  426. }
  427. }
  428. endBattle(tile, hero1, hero2);
  429. }
  430. void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  431. {
  432. BattleResultsApplied resultsApplied;
  433. resultsApplied.player1 = bEndArmy1->tempOwner;
  434. resultsApplied.player2 = bEndArmy2->tempOwner;
  435. //unblock engaged players
  436. if(bEndArmy1->tempOwner<PLAYER_LIMIT)
  437. states.setFlag(bEndArmy1->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  438. if(bEndArmy2 && bEndArmy2->tempOwner<PLAYER_LIMIT)
  439. states.setFlag(bEndArmy2->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  440. //casualties among heroes armies
  441. SetGarrisons sg;
  442. sg.garrs[bEndArmy1->id] = takeCasualties(bEndArmy1->tempOwner, bEndArmy1->army, gs->curB);
  443. sg.garrs[bEndArmy2->id] = takeCasualties(bEndArmy2->tempOwner, bEndArmy2->army, gs->curB);
  444. sendAndApply(&sg);
  445. ui8 sides[2];
  446. sides[0] = gs->curB->side1;
  447. sides[1] = gs->curB->side2;
  448. //end battle, remove all info, free memory
  449. giveExp(*battleResult.data);
  450. sendAndApply(battleResult.data);
  451. //if one hero has lost we will erase him
  452. if(battleResult.data->winner!=0 && hero1)
  453. {
  454. RemoveObject ro(hero1->id);
  455. sendAndApply(&ro);
  456. }
  457. if(battleResult.data->winner!=1 && hero2)
  458. {
  459. RemoveObject ro(hero2->id);
  460. sendAndApply(&ro);
  461. }
  462. //give exp
  463. if(battleResult.data->exp[0] && hero1)
  464. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  465. if(battleResult.data->exp[1] && hero2)
  466. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  467. if(battleEndCallback && *battleEndCallback)
  468. {
  469. (*battleEndCallback)(battleResult.data);
  470. delete battleEndCallback;
  471. battleEndCallback = 0;
  472. }
  473. sendAndApply(&resultsApplied);
  474. // Necromancy if applicable.
  475. const CGHeroInstance *winnerHero = battleResult.data->winner != 0 ? hero2 : hero1;
  476. if (winnerHero)
  477. {
  478. std::pair<ui32, si32> raisedStack = winnerHero->calculateNecromancy(*battleResult.data);
  479. // Give raised units to winner and show dialog, if any were raised.
  480. if (raisedStack.first != -1)
  481. {
  482. int slot = winnerHero->army.getSlotFor(raisedStack.first);
  483. if (slot != -1)
  484. {
  485. SetGarrisons sg;
  486. sg.garrs[winnerHero->id] = winnerHero->army;
  487. if (vstd::contains(winnerHero->army.slots, slot)) // Add to existing stack.
  488. sg.garrs[winnerHero->id].slots[slot].second += raisedStack.second;
  489. else // Create a new stack.
  490. sg.garrs[winnerHero->id].slots[slot] = raisedStack;
  491. winnerHero->showNecromancyDialog(raisedStack);
  492. sendAndApply(&sg);
  493. }
  494. }
  495. }
  496. winLoseHandle(1<<sides[0] | 1<<sides[1]); //handle victory/loss of engaged players
  497. delete battleResult.data;
  498. }
  499. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, const CStack *def)
  500. {
  501. bsa.killedAmount = bsa.damageAmount / def->MaxHealth();
  502. unsigned damageFirst = bsa.damageAmount % def->MaxHealth();
  503. if( def->firstHPleft <= damageFirst )
  504. {
  505. bsa.killedAmount++;
  506. bsa.newHP = def->firstHPleft + def->MaxHealth() - damageFirst;
  507. }
  508. else
  509. {
  510. bsa.newHP = def->firstHPleft - damageFirst;
  511. }
  512. if(def->amount <= bsa.killedAmount) //stack killed
  513. {
  514. bsa.newAmount = 0;
  515. bsa.flags |= 1;
  516. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  517. }
  518. else
  519. {
  520. bsa.newAmount = def->amount - bsa.killedAmount;
  521. }
  522. }
  523. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance)
  524. {
  525. bat.bsa.clear();
  526. bat.stackAttacking = att->ID;
  527. std::set<BattleStackAttacked>::iterator i = bat.bsa.insert(BattleStackAttacked()).first;
  528. #ifdef __GNUC__
  529. BattleStackAttacked *bsa = (BattleStackAttacked *)&*i;
  530. #else
  531. BattleStackAttacked *bsa = &*i;
  532. #endif
  533. bsa->stackAttacked = def->ID;
  534. bsa->attackerID = att->ID;
  535. bsa->damageAmount = BattleInfo::calculateDmg(att, def, gs->battleGetOwner(att->ID), gs->battleGetOwner(def->ID), bat.shot(), distance);//counting dealt damage
  536. if(att->Luck() > 0 && rand()%24 < att->Luck())
  537. {
  538. bsa->damageAmount *= 2;
  539. bat.flags |= 4;
  540. }
  541. prepareAttacked(*bsa, def);
  542. }
  543. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  544. {
  545. srand(time(NULL));
  546. CPack *pack = NULL;
  547. try
  548. {
  549. while(1)//server should never shut connection first //was: while(!end2)
  550. {
  551. {
  552. boost::unique_lock<boost::mutex> lock(*c.rmx);
  553. c >> pack; //get the package
  554. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  555. }
  556. int packType = typeList.getTypeID(pack); //get the id of type
  557. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  558. if(apply)
  559. {
  560. bool result = apply->applyOnGH(this,&c,pack);
  561. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  562. //send confirmation that we've applied the package
  563. if(pack->type != 6000) //WORKAROUND - not confirm query replies TODO: reconsider
  564. {
  565. PackageApplied applied;
  566. applied.result = result;
  567. applied.packType = packType;
  568. {
  569. boost::unique_lock<boost::mutex> lock(*c.wmx);
  570. c << &applied;
  571. }
  572. }
  573. }
  574. else
  575. {
  576. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  577. }
  578. delete pack;
  579. pack = NULL;
  580. }
  581. }
  582. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  583. {
  584. assert(!c.connected); //make sure that connection has been marked as broken
  585. tlog1 << e.what() << std::endl;
  586. end2 = true;
  587. }
  588. HANDLE_EXCEPTION(end2 = true);
  589. tlog1 << "Ended handling connection\n";
  590. }
  591. int CGameHandler::moveStack(int stack, int dest)
  592. {
  593. int ret = 0;
  594. CStack *curStack = gs->curB->getStack(stack),
  595. *stackAtEnd = gs->curB->getStackT(dest);
  596. assert(curStack);
  597. assert(dest < BFIELD_SIZE);
  598. //initing necessary tables
  599. bool accessibility[BFIELD_SIZE];
  600. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  601. for(int b=0; b<BFIELD_SIZE; ++b)
  602. {
  603. accessibility[b] = false;
  604. }
  605. for(int g=0; g<accessible.size(); ++g)
  606. {
  607. accessibility[accessible[g]] = true;
  608. }
  609. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  610. if(!stackAtEnd && curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !accessibility[dest])
  611. {
  612. if(curStack->attackerOwned)
  613. {
  614. if(accessibility[dest+1])
  615. dest+=1;
  616. }
  617. else
  618. {
  619. if(accessibility[dest-1])
  620. dest-=1;
  621. }
  622. }
  623. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  624. return 0;
  625. bool accessibilityWithOccupyable[BFIELD_SIZE];
  626. std::vector<int> accOc = gs->curB->getAccessibility(curStack->ID, true);
  627. for(int b=0; b<BFIELD_SIZE; ++b)
  628. {
  629. accessibilityWithOccupyable[b] = false;
  630. }
  631. for(int g=0; g<accOc.size(); ++g)
  632. {
  633. accessibilityWithOccupyable[accOc[g]] = true;
  634. }
  635. //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
  636. // return false;
  637. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibilityWithOccupyable, curStack->hasFeatureOfType(StackFeature::FLYING), curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE), curStack->attackerOwned);
  638. ret = path.second;
  639. if(curStack->hasFeatureOfType(StackFeature::FLYING))
  640. {
  641. if(path.second <= curStack->Speed() && path.first.size() > 0)
  642. {
  643. //inform clients about move
  644. BattleStackMoved sm;
  645. sm.stack = curStack->ID;
  646. sm.tile = path.first[0];
  647. sm.distance = path.second;
  648. sm.ending = true;
  649. sendAndApply(&sm);
  650. }
  651. }
  652. else //for non-flying creatures
  653. {
  654. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  655. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  656. {
  657. //inform clients about move
  658. BattleStackMoved sm;
  659. sm.stack = curStack->ID;
  660. sm.tile = path.first[v];
  661. sm.distance = path.second;
  662. sm.ending = v==tilesToMove;
  663. sendAndApply(&sm);
  664. }
  665. }
  666. return ret;
  667. }
  668. CGameHandler::CGameHandler(void)
  669. {
  670. QID = 1;
  671. gs = NULL;
  672. IObjectInterface::cb = this;
  673. applier = new CGHApplier;
  674. }
  675. CGameHandler::~CGameHandler(void)
  676. {
  677. delete applier;
  678. applier = NULL;
  679. delete gs;
  680. }
  681. void CGameHandler::init(StartInfo *si, int Seed)
  682. {
  683. Mapa *map = new Mapa(si->mapname);
  684. tlog0 << "Map loaded!" << std::endl;
  685. gs = new CGameState();
  686. tlog0 << "Gamestate created!" << std::endl;
  687. gs->init(si,map,Seed);
  688. tlog0 << "Gamestate initialized!" << std::endl;
  689. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  690. states.addPlayer(i->first);
  691. }
  692. static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  693. {
  694. return *a < *b;
  695. }
  696. void CGameHandler::newTurn()
  697. {
  698. tlog5 << "Turn " << gs->day+1 << std::endl;
  699. NewTurn n;
  700. n.day = gs->day + 1;
  701. n.resetBuilded = true;
  702. std::map<ui8, si32> hadGold;//starting gold - for buildings like dwarven treasury
  703. srand(time(NULL));
  704. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  705. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  706. {
  707. if(i->first == 255) continue;
  708. else if(i->first > PLAYER_LIMIT) assert(0); //illegal player number!
  709. std::pair<ui8,si32> playerGold(i->first,i->second.resources[6]);
  710. hadGold.insert(playerGold);
  711. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  712. {
  713. SetAvailableHeroes sah;
  714. sah.player = i->first;
  715. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  716. if(h)
  717. sah.hid1 = h->subID;
  718. else
  719. sah.hid1 = -1;
  720. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  721. if(h)
  722. sah.hid2 = h->subID;
  723. else
  724. sah.hid2 = -1;
  725. sendAndApply(&sah);
  726. }
  727. if(i->first>=PLAYER_LIMIT) continue;
  728. n.res[i->first] = i->second.resources;
  729. // SetResources r;
  730. // r.player = i->first;
  731. // for(int j=0;j<RESOURCE_QUANTITY;j++)
  732. // r.res[j] = i->second.resources[j];
  733. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  734. {
  735. if(h->visitedTown)
  736. giveSpells(h->visitedTown, h);
  737. NewTurn::Hero hth;
  738. hth.id = h->id;
  739. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != TerrainTile::water);
  740. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  741. hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
  742. else
  743. hth.mana = std::max(si32(0), std::max(h->mana, std::min(h->mana + h->manaRegain(), h->manaLimit())) );
  744. n.heroes.insert(hth);
  745. if(gs->day) //not first day
  746. {
  747. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  748. {
  749. case 1: //basic
  750. n.res[i->first][6] += 125;
  751. break;
  752. case 2: //advanced
  753. n.res[i->first][6] += 250;
  754. break;
  755. case 3: //expert
  756. n.res[i->first][6] += 500;
  757. break;
  758. }
  759. for(std::list<HeroBonus>::iterator j = h->bonuses.begin(); j != h->bonuses.end(); j++)
  760. if(j->type == HeroBonus::GENERATE_RESOURCE)
  761. n.res[i->first][j->subtype] += j->val;
  762. //TODO player bonuses
  763. }
  764. }
  765. //n.res.push_back(r);
  766. }
  767. for(std::vector<CGTownInstance *>::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  768. {
  769. ui8 player = (*j)->tempOwner;
  770. if(gs->getDate(1)==7) //first day of week
  771. {
  772. if ( (**j).subID == 1 && gs->getDate(0) && player < PLAYER_LIMIT
  773. && vstd::contains((**j).builtBuildings,22) )//dwarven treasury
  774. n.res[player][6] += hadGold[player]/10; //give 10% of starting gold
  775. SetAvailableCreatures sac;
  776. sac.tid = (**j).id;
  777. sac.creatures = (**j).creatures;
  778. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  779. {
  780. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  781. {
  782. sac.creatures[k].first += (**j).creatureGrowth(k);
  783. if(!gs->getDate(0)) //first day of game: use only basic growths
  784. amin(sac.creatures[k].first, VLC->creh->creatures[(*j)->town->basicCreatures[k]].growth);
  785. }
  786. }
  787. n.cres.push_back(sac);
  788. }
  789. if(gs->day && player < PLAYER_LIMIT)//not the first day and town not neutral
  790. {
  791. ////SetResources r;
  792. //r.player = (**j).tempOwner;
  793. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  794. {
  795. if((**j).town->primaryRes == 127) //we'll give wood and ore
  796. {
  797. n.res[player][0] += 1;
  798. n.res[player][2] += 1;
  799. }
  800. else
  801. {
  802. n.res[player][(**j).town->primaryRes] += 1;
  803. }
  804. }
  805. n.res[player][6] += (**j).dailyIncome();
  806. }
  807. }
  808. sendAndApply(&n);
  809. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  810. handleTimeEvents();
  811. //call objects
  812. for(size_t i = 0; i<gs->map->objects.size(); i++)
  813. if(gs->map->objects[i])
  814. gs->map->objects[i]->newTurn();
  815. winLoseHandle(0xff);
  816. //warn players without town
  817. if(gs->day)
  818. {
  819. for (std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  820. {
  821. if(i->second.status || i->second.towns.size() || i->second.color >= PLAYER_LIMIT)
  822. continue;
  823. InfoWindow iw;
  824. iw.player = i->first;
  825. iw.components.push_back(Component(Component::FLAG,i->first,0,0));
  826. if(!i->second.daysWithoutCastle)
  827. {
  828. 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.
  829. iw.text.addReplacement(MetaString::COLOR, i->first);
  830. }
  831. else if(i->second.daysWithoutCastle == 6)
  832. {
  833. 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.
  834. iw.text.addReplacement(MetaString::COLOR, i->first);
  835. }
  836. else
  837. {
  838. 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.
  839. iw.text.addReplacement(MetaString::COLOR, i->first);
  840. iw.text.addReplacement(7 - i->second.daysWithoutCastle);
  841. }
  842. sendAndApply(&iw);
  843. }
  844. }
  845. }
  846. void CGameHandler::run(bool resume)
  847. {
  848. BOOST_FOREACH(CConnection *cc, conns)
  849. {//init conn.
  850. ui8 quantity, pom;
  851. //ui32 seed;
  852. if(!resume)
  853. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  854. (*cc) >> quantity; //how many players will be handled at that client
  855. for(int i=0;i<quantity;i++)
  856. {
  857. (*cc) >> pom; //read player color
  858. {
  859. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  860. connections[pom] = cc;
  861. }
  862. }
  863. }
  864. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  865. {
  866. std::set<int> pom;
  867. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  868. if(j->second == *i)
  869. pom.insert(j->first);
  870. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  871. }
  872. while (!end2)
  873. {
  874. if(!resume)
  875. newTurn();
  876. else
  877. resume = false;
  878. std::map<ui8,PlayerState>::iterator i;
  879. if(!resume)
  880. i = gs->players.begin();
  881. else
  882. i = gs->players.find(gs->currentPlayer);
  883. for(; i != gs->players.end(); i++)
  884. {
  885. if(i->second.towns.size()==0 && i->second.heroes.size()==0
  886. || i->second.color<0
  887. || i->first>=PLAYER_LIMIT
  888. || i->second.status)
  889. {
  890. continue;
  891. }
  892. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  893. gs->currentPlayer = i->first;
  894. {
  895. YourTurn yt;
  896. yt.player = i->first;
  897. boost::unique_lock<boost::mutex> lock(*connections[i->first]->wmx);
  898. *connections[i->first] << &yt;
  899. }
  900. //wait till turn is done
  901. boost::unique_lock<boost::mutex> lock(states.mx);
  902. while(states.players[i->first].makingTurn && !end2)
  903. {
  904. boost::posix_time::time_duration p;
  905. p = boost::posix_time::milliseconds(200);
  906. states.cv.timed_wait(lock,p);
  907. }
  908. }
  909. }
  910. while(conns.size() && (*conns.begin())->isOpen())
  911. boost::this_thread::sleep(boost::posix_time::milliseconds(5)); //give time client to close socket
  912. }
  913. namespace CGH
  914. {
  915. using namespace std;
  916. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  917. {
  918. for(int j=0; j<7; ++j)
  919. {
  920. std::vector<int> pom;
  921. for(int g=0; g<j+1; ++g)
  922. {
  923. int hlp; input>>hlp;
  924. pom.push_back(hlp);
  925. }
  926. dest.push_back(pom);
  927. }
  928. }
  929. }
  930. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, const CCreatureSet &army1, const CCreatureSet &army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank, const CGTownInstance *town)
  931. {
  932. battleResult.set(NULL);
  933. std::vector<CStack*> & stacks = (curB->stacks);
  934. curB->tile = tile;
  935. curB->army1=army1;
  936. curB->army2=army2;
  937. curB->heroes[0] = const_cast<CGHeroInstance*>(hero1);
  938. curB->heroes[1] = const_cast<CGHeroInstance*>(hero2);
  939. curB->round = -2;
  940. curB->activeStack = -1;
  941. if(town)
  942. {
  943. curB->tid = town->id;
  944. curB->siege = town->fortLevel();
  945. }
  946. else
  947. {
  948. curB->tid = -1;
  949. curB->siege = 0;
  950. }
  951. //reading battleStartpos
  952. std::ifstream positions;
  953. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  954. if(!positions.is_open())
  955. {
  956. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  957. }
  958. std::string dump;
  959. positions>>dump; positions>>dump;
  960. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  961. CGH::readItTo(positions, attackerLoose);
  962. positions>>dump;
  963. CGH::readItTo(positions, defenderLoose);
  964. positions>>dump;
  965. positions>>dump;
  966. CGH::readItTo(positions, attackerTight);
  967. positions>>dump;
  968. CGH::readItTo(positions, defenderTight);
  969. positions>>dump;
  970. positions>>dump;
  971. CGH::readItTo(positions, attackerCreBank);
  972. positions>>dump;
  973. CGH::readItTo(positions, defenderCreBank);
  974. positions.close();
  975. //battleStartpos read
  976. int k = 0; //stack serial
  977. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army1.slots.begin(); i!=army1.slots.end(); i++, k++)
  978. {
  979. int pos;
  980. if(creatureBank)
  981. pos = attackerCreBank[army1.slots.size()-1][k];
  982. else if(army1.formation)
  983. pos = attackerTight[army1.slots.size()-1][k];
  984. else
  985. pos = attackerLoose[army1.slots.size()-1][k];
  986. CStack * stack = curB->generateNewStack(hero1, i->second.first, i->second.second, stacks.size(), true, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  987. stacks.push_back(stack);
  988. }
  989. k = 0;
  990. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army2.slots.begin(); i!=army2.slots.end(); i++, k++)
  991. {
  992. int pos;
  993. if(creatureBank)
  994. pos = defenderCreBank[army2.slots.size()-1][k];
  995. else if(army2.formation)
  996. pos = defenderTight[army2.slots.size()-1][k];
  997. else
  998. pos = defenderLoose[army2.slots.size()-1][k];
  999. CStack * stack = curB->generateNewStack(hero2, i->second.first, i->second.second, stacks.size(), false, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  1000. stacks.push_back(stack);
  1001. }
  1002. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1003. {
  1004. if((stacks[g]->position%17)==1 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned)
  1005. {
  1006. stacks[g]->position += 1;
  1007. }
  1008. else if((stacks[g]->position%17)==15 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned)
  1009. {
  1010. stacks[g]->position -= 1;
  1011. }
  1012. }
  1013. //adding war machines
  1014. if(hero1)
  1015. {
  1016. if(hero1->getArt(13)) //ballista
  1017. {
  1018. CStack * stack = curB->generateNewStack(hero1, 146, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 52);
  1019. stacks.push_back(stack);
  1020. }
  1021. if(hero1->getArt(14)) //ammo cart
  1022. {
  1023. CStack * stack = curB->generateNewStack(hero1, 148, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 18);
  1024. stacks.push_back(stack);
  1025. }
  1026. if(hero1->getArt(15)) //first aid tent
  1027. {
  1028. CStack * stack = curB->generateNewStack(hero1, 147, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 154);
  1029. stacks.push_back(stack);
  1030. }
  1031. }
  1032. if(hero2)
  1033. {
  1034. if(hero2->getArt(13)) //ballista
  1035. {
  1036. CStack * stack = curB->generateNewStack(hero2, 146, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 66);
  1037. stacks.push_back(stack);
  1038. }
  1039. if(hero2->getArt(14)) //ammo cart
  1040. {
  1041. CStack * stack = curB->generateNewStack(hero2, 148, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 32);
  1042. stacks.push_back(stack);
  1043. }
  1044. if(hero2->getArt(15)) //first aid tent
  1045. {
  1046. CStack * stack = curB->generateNewStack(hero2, 147, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 168);
  1047. stacks.push_back(stack);
  1048. }
  1049. }
  1050. if(town && hero1 && town->hasFort()) //catapult
  1051. {
  1052. CStack * stack = curB->generateNewStack(hero1, 145, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 120);
  1053. stacks.push_back(stack);
  1054. }
  1055. //war machines added
  1056. switch(curB->siege) //adding towers
  1057. {
  1058. case 3: //castle
  1059. {//lower tower / upper tower
  1060. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -4);
  1061. stacks.push_back(stack);
  1062. stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -3);
  1063. stacks.push_back(stack);
  1064. }
  1065. case 2: //citadel
  1066. {//main tower
  1067. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -2);
  1068. stacks.push_back(stack);
  1069. }
  1070. }
  1071. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1072. //seting up siege
  1073. if(town && town->hasFort())
  1074. {
  1075. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1076. {
  1077. curB->si.wallState[b] = 1;
  1078. }
  1079. }
  1080. int terType = gs->battleGetBattlefieldType(tile);
  1081. //randomize obstacles
  1082. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1083. {
  1084. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1085. std::vector<int> possibleObstacles;
  1086. for(int i=0; i<BFIELD_SIZE; ++i)
  1087. {
  1088. if(i%17 < 4 || i%17 > 12)
  1089. {
  1090. obAv[i] = false;
  1091. }
  1092. else
  1093. {
  1094. obAv[i] = true;
  1095. }
  1096. }
  1097. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1098. {
  1099. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  1100. {
  1101. possibleObstacles.push_back(g->first);
  1102. }
  1103. }
  1104. srand(time(NULL));
  1105. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1106. {
  1107. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1108. while(toBlock>0)
  1109. {
  1110. CObstacleInstance coi;
  1111. coi.uniqueID = curB->obstacles.size();
  1112. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1113. coi.pos = rand()%BFIELD_SIZE;
  1114. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1115. bool badObstacle = false;
  1116. for(int b=0; b<block.size(); ++b)
  1117. {
  1118. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1119. {
  1120. badObstacle = true;
  1121. break;
  1122. }
  1123. }
  1124. if(badObstacle) continue;
  1125. //obstacle can be placed
  1126. curB->obstacles.push_back(coi);
  1127. for(int b=0; b<block.size(); ++b)
  1128. {
  1129. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1130. obAv[block[b]] = false;
  1131. }
  1132. toBlock -= block.size();
  1133. }
  1134. }
  1135. }
  1136. //giving building bonuses, if siege and we have harrisoned hero
  1137. if (town)
  1138. {
  1139. if (hero2)
  1140. {
  1141. for (int i=0; i<4; i++)
  1142. {
  1143. int val = town->defenceBonus(i);
  1144. if (val)
  1145. {
  1146. GiveBonus gs;
  1147. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::PRIMARY_SKILL, HeroBonus::OBJECT, val, -1, "", i);
  1148. gs.id = hero2->id;
  1149. sendAndApply(&gs);
  1150. }
  1151. }
  1152. }
  1153. else//if we don't have hero - apply separately, if hero present - will be taken from hero bonuses
  1154. {
  1155. if(town->subID == 0 && vstd::contains(town->builtBuildings,22)) //castle, brotherhood of sword built
  1156. for(int g=0; g<stacks.size(); ++g)
  1157. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 2, StackFeature::OTHER_SOURCE));
  1158. else if(vstd::contains(town->builtBuildings,5)) //tavern is built
  1159. for(int g=0; g<stacks.size(); ++g)
  1160. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1161. if(town->subID == 1 && vstd::contains(town->builtBuildings,21)) //rampart, fountain of fortune is present
  1162. for(int g=0; g<stacks.size(); ++g)
  1163. stacks[g]->features.push_back(makeFeature(StackFeature::LUCK_BONUS, StackFeature::WHOLE_BATTLE, 0, 2, StackFeature::OTHER_SOURCE));
  1164. }
  1165. }
  1166. //giving terrain premies for heroes & stacks
  1167. int bonusSubtype = -1;
  1168. switch(terType)
  1169. {
  1170. case 9: //magic plains
  1171. {
  1172. bonusSubtype = 0;
  1173. }
  1174. case 14: //fiery fields
  1175. {
  1176. if(bonusSubtype == -1) bonusSubtype = 1;
  1177. }
  1178. case 15: //rock lands
  1179. {
  1180. if(bonusSubtype == -1) bonusSubtype = 8;
  1181. }
  1182. case 16: //magic clouds
  1183. {
  1184. if(bonusSubtype == -1) bonusSubtype = 2;
  1185. }
  1186. case 17: //lucid pools
  1187. {
  1188. if(bonusSubtype == -1) bonusSubtype = 4;
  1189. }
  1190. { //common part for cases 9, 14, 15, 16, 17
  1191. const CGHeroInstance * cHero = NULL;
  1192. for(int i=0; i<2; ++i)
  1193. {
  1194. if(i == 0) cHero = hero1;
  1195. else cHero = hero2;
  1196. if(cHero == NULL) continue;
  1197. GiveBonus gs;
  1198. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::MAGIC_SCHOOL_SKILL, HeroBonus::OBJECT, 3, -1, "", bonusSubtype);
  1199. gs.id = cHero->id;
  1200. sendAndApply(&gs);
  1201. }
  1202. break;
  1203. }
  1204. case 18: //holy ground
  1205. {
  1206. for(int g=0; g<stacks.size(); ++g) //+1 morale bonus for good creatures, -1 morale bonus for evil creatures
  1207. {
  1208. if (stacks[g]->creature->isGood())
  1209. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1210. else if (stacks[g]->creature->isEvil())
  1211. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1212. }
  1213. break;
  1214. }
  1215. case 19: //clover field
  1216. {
  1217. for(int g=0; g<stacks.size(); ++g)
  1218. {
  1219. if(stacks[g]->creature->faction == -1) //+2 luck bonus for neutral creatures
  1220. {
  1221. stacks[g]->features.push_back(makeFeature(StackFeature::LUCK_BONUS, StackFeature::WHOLE_BATTLE, 0, 2, StackFeature::OTHER_SOURCE));
  1222. }
  1223. }
  1224. break;
  1225. }
  1226. case 20: //evil fog
  1227. {
  1228. for(int g=0; g<stacks.size(); ++g) //-1 morale bonus for good creatures, +1 morale bonus for evil creatures
  1229. {
  1230. if (stacks[g]->creature->isGood())
  1231. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1232. else if (stacks[g]->creature->isEvil())
  1233. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1234. }
  1235. break;
  1236. }
  1237. case 22: //cursed ground
  1238. {
  1239. for(int g=0; g<stacks.size(); ++g) //no luck nor morale
  1240. {
  1241. stacks[g]->features.push_back(makeFeature(StackFeature::NO_MORALE, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1242. stacks[g]->features.push_back(makeFeature(StackFeature::NO_LUCK, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1243. }
  1244. const CGHeroInstance * cHero = NULL;
  1245. for(int i=0; i<2; ++i) //blocking spells above level 1
  1246. {
  1247. if(i == 0) cHero = hero1;
  1248. else cHero = hero2;
  1249. if(cHero == NULL) continue;
  1250. GiveBonus gs;
  1251. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL, HeroBonus::OBJECT, 1, -1, "", bonusSubtype);
  1252. gs.id = cHero->id;
  1253. sendAndApply(&gs);
  1254. }
  1255. break;
  1256. }
  1257. }
  1258. //premies given
  1259. //send info about battles
  1260. BattleStart bs;
  1261. bs.info = curB;
  1262. sendAndApply(&bs);
  1263. }
  1264. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1265. {
  1266. //checking winning condition
  1267. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1268. hasStack[0] = hasStack[1] = false;
  1269. for(int b = 0; b<stacks.size(); ++b)
  1270. {
  1271. if(stacks[b]->alive() && !stacks[b]->hasFeatureOfType(StackFeature::SIEGE_WEAPON))
  1272. {
  1273. hasStack[1-stacks[b]->attackerOwned] = true;
  1274. }
  1275. }
  1276. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1277. {
  1278. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1279. br->result = 0;
  1280. br->winner = hasStack[1]; //fleeing side loses
  1281. gs->curB->calculateCasualties(br->casualties);
  1282. battleResult.set(br);
  1283. }
  1284. }
  1285. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1286. {
  1287. if(!vstd::contains(h->artifWorn,17))
  1288. return; //hero hasn't spellbok
  1289. ChangeSpells cs;
  1290. cs.hid = h->id;
  1291. cs.learn = true;
  1292. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  1293. {
  1294. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1295. {
  1296. if(!vstd::contains(h->spells,t->spells[i][j]))
  1297. cs.spells.insert(t->spells[i][j]);
  1298. }
  1299. }
  1300. if(cs.spells.size())
  1301. sendAndApply(&cs);
  1302. }
  1303. void CGameHandler::setBlockVis(int objid, bool bv)
  1304. {
  1305. SetObjectProperty sop(objid,2,bv);
  1306. sendAndApply(&sop);
  1307. }
  1308. bool CGameHandler::removeObject( int objid )
  1309. {
  1310. if(!getObj(objid))
  1311. {
  1312. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1313. return false;
  1314. }
  1315. RemoveObject ro;
  1316. ro.id = objid;
  1317. sendAndApply(&ro);
  1318. winLoseHandle(255); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1319. return true;
  1320. }
  1321. void CGameHandler::setAmount(int objid, ui32 val)
  1322. {
  1323. SetObjectProperty sop(objid,3,val);
  1324. sendAndApply(&sop);
  1325. }
  1326. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1327. {
  1328. bool blockvis = false;
  1329. const CGHeroInstance *h = getHero(hid);
  1330. 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)
  1331. )
  1332. {
  1333. tlog1 << "Illegal call to move hero!\n";
  1334. return false;
  1335. }
  1336. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1337. int3 hmpos = dst + int3(-1,0,0);
  1338. if(!gs->map->isInTheMap(hmpos))
  1339. {
  1340. tlog1 << "Destination tile os out of the map!\n";
  1341. return false;
  1342. }
  1343. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1344. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1345. //result structure for start - movement failed, no move points used
  1346. TryMoveHero tmh;
  1347. tmh.id = hid;
  1348. tmh.start = h->pos;
  1349. tmh.end = dst;
  1350. tmh.result = TryMoveHero::FAILED;
  1351. tmh.movePoints = h->movement;
  1352. //check if destination tile is available
  1353. //it's a rock or blocked and not visitable tile
  1354. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1355. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable))
  1356. && complain("Cannot move hero, destination tile is blocked!")
  1357. || (!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)
  1358. && complain("Cannot move hero, destination tile is on water!")
  1359. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1360. && complain("Cannot disembark hero, tile is blocked!")
  1361. || (h->movement < cost && dst != h->pos && !instant)
  1362. && complain("Hero doesn't have any movement points left!")
  1363. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1364. && complain("Cannot move hero during the battle"))
  1365. {
  1366. //send info about movement failure
  1367. sendAndApply(&tmh);
  1368. return false;
  1369. }
  1370. //hero enters the boat
  1371. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1372. {
  1373. tmh.result = TryMoveHero::EMBARK;
  1374. tmh.movePoints = 0; //embarking takes all move points
  1375. //TODO: check for bonus that removes that penalty
  1376. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1377. sendAndApply(&tmh);
  1378. return true;
  1379. }
  1380. //hero leaves the boat
  1381. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1382. {
  1383. tmh.result = TryMoveHero::DISEMBARK;
  1384. tmh.movePoints = 0; //disembarking takes all move points
  1385. //TODO: check for bonus that removes that penalty
  1386. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1387. sendAndApply(&tmh);
  1388. return true;
  1389. }
  1390. //checks for standard movement
  1391. if(!instant)
  1392. {
  1393. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighbouring!")
  1394. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1395. {
  1396. sendAndApply(&tmh);
  1397. return false;
  1398. }
  1399. //check if there is blocking visitable object
  1400. blockvis = false;
  1401. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1402. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1403. {
  1404. if(obj != h && obj->blockVisit && !(obj->getPassableness() & 1<<h->tempOwner))
  1405. {
  1406. blockvis = true;
  1407. break;
  1408. }
  1409. }
  1410. //we start moving
  1411. if(blockvis)//interaction with blocking object (like resources)
  1412. {
  1413. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1414. sendAndApply(&tmh);
  1415. //failed to move to that tile but we visit object
  1416. if(t.visitableObjects.size())
  1417. objectVisited(t.visitableObjects.back(), h);
  1418. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1419. // {
  1420. // if (obj->blockVisit)
  1421. // {
  1422. // objectVisited(obj, h);
  1423. // }
  1424. // }
  1425. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1426. return true;
  1427. }
  1428. else //normal move
  1429. {
  1430. tmh.result = TryMoveHero::SUCCESS;
  1431. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1432. {
  1433. obj->onHeroLeave(h);
  1434. }
  1435. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1436. sendAndApply(&tmh);
  1437. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1438. //call objects if they are visited
  1439. if(t.visitableObjects.size())
  1440. {
  1441. //to prevent self-visiting heroes on space press
  1442. if(t.visitableObjects.back() != h)
  1443. objectVisited(t.visitableObjects.back(), h);
  1444. else if(t.visitableObjects.size() > 1)
  1445. objectVisited(*(t.visitableObjects.end()-2),h);
  1446. }
  1447. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1448. // {
  1449. // objectVisited(obj, h);
  1450. // }
  1451. }
  1452. tlog5 << "Movement end!\n";
  1453. return true;
  1454. }
  1455. else //instant move - teleportation
  1456. {
  1457. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1458. {
  1459. if(obj->ID==HEROI_TYPE)
  1460. {
  1461. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1462. if(obj->tempOwner==h->tempOwner)
  1463. {
  1464. heroExchange(dh->id, h->id);
  1465. return true;
  1466. }
  1467. //TODO: check for ally
  1468. startBattleI(h, dh);
  1469. return true;
  1470. }
  1471. }
  1472. tmh.result = TryMoveHero::TELEPORTATION;
  1473. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1474. sendAndApply(&tmh);
  1475. return true;
  1476. }
  1477. }
  1478. void CGameHandler::setOwner(int objid, ui8 owner)
  1479. {
  1480. ui8 oldOwner = getOwner(objid);
  1481. SetObjectProperty sop(objid,1,owner);
  1482. sendAndApply(&sop);
  1483. winLoseHandle(1<<owner | 1<<oldOwner);
  1484. if(owner < PLAYER_LIMIT && getTown(objid) && !gs->getPlayer(owner)->towns.size()) //player lost last town
  1485. {
  1486. InfoWindow iw;
  1487. iw.player = oldOwner;
  1488. 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.
  1489. sendAndApply(&iw);
  1490. }
  1491. }
  1492. void CGameHandler::setHoverName(int objid, MetaString* name)
  1493. {
  1494. SetHoverName shn(objid, *name);
  1495. sendAndApply(&shn);
  1496. }
  1497. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1498. {
  1499. sendToAllClients(iw);
  1500. }
  1501. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1502. {
  1503. ask(iw,iw->player,callback);
  1504. }
  1505. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1506. {
  1507. //TODO
  1508. //gsm.lock();
  1509. //int query = QID++;
  1510. //states.addQuery(player,query);
  1511. //sendToAllClients(iw);
  1512. //gsm.unlock();
  1513. //ui32 ret = getQueryResult(iw->player, query);
  1514. //gsm.lock();
  1515. //states.removeQuery(player, query);
  1516. //gsm.unlock();
  1517. return 0;
  1518. }
  1519. int CGameHandler::getCurrentPlayer()
  1520. {
  1521. return gs->currentPlayer;
  1522. }
  1523. void CGameHandler::giveResource(int player, int which, int val)
  1524. {
  1525. if(!val) return; //don't waste time on empty call
  1526. SetResource sr;
  1527. sr.player = player;
  1528. sr.resid = which;
  1529. sr.val = gs->players.find(player)->second.resources[which]+val;
  1530. sendAndApply(&sr);
  1531. }
  1532. void CGameHandler::giveCreatures (int objid, const CGHeroInstance * h, CCreatureSet creatures)
  1533. {
  1534. if (creatures.slots.size() <= 0)
  1535. return;
  1536. CCreatureSet heroArmy = h->army;
  1537. while (creatures.slots.size() > 0)
  1538. {
  1539. int slot = heroArmy.getSlotFor (creatures.slots.begin()->second.first);
  1540. if (slot < 0)
  1541. break;
  1542. heroArmy.slots[slot].first = creatures.slots.begin()->second.first;
  1543. heroArmy.slots[slot].second += creatures.slots.begin()->second.second;
  1544. creatures.slots.erase (creatures.slots.begin());
  1545. }
  1546. if (creatures.slots.size() == 0) //all creatures can be moved to hero army - do that
  1547. {
  1548. SetGarrisons sg;
  1549. sg.garrs[h->id] = heroArmy;
  1550. sendAndApply(&sg);
  1551. }
  1552. else //show garrison window and let player pick creatures
  1553. {
  1554. SetGarrisons sg;
  1555. sg.garrs[objid] = creatures;
  1556. sendAndApply (&sg);
  1557. showGarrisonDialog (objid, h->id, true, 0);
  1558. return;
  1559. }
  1560. }
  1561. void CGameHandler::takeCreatures (int objid, TSlots creatures) //probably we could use ArmedInstance as well
  1562. {
  1563. if (creatures.size() <= 0)
  1564. return;
  1565. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  1566. CCreatureSet newArmy = obj->army;
  1567. while (creatures.size() > 0)
  1568. {
  1569. int slot = newArmy.getSlotFor (creatures.begin()->second.first);
  1570. if (slot < 0)
  1571. break;
  1572. newArmy.slots[slot].first = creatures.begin()->second.first;
  1573. newArmy.slots[slot].second -= creatures.begin()->second.second;
  1574. creatures.erase (creatures.begin());
  1575. }
  1576. SetGarrisons sg;
  1577. sg.garrs[objid] = newArmy;
  1578. sendAndApply(&sg);
  1579. }
  1580. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1581. {
  1582. sendToAllClients(comp);
  1583. }
  1584. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1585. {
  1586. HeroVisitCastle vc;
  1587. vc.hid = heroID;
  1588. vc.tid = obj;
  1589. vc.flags |= 1;
  1590. sendAndApply(&vc);
  1591. const CGHeroInstance *h = getHero(heroID);
  1592. vistiCastleObjects (getTown(obj), h);
  1593. giveSpells (getTown(obj), getHero(heroID));
  1594. if(gs->map->victoryCondition.condition == transportItem)
  1595. checkLossVictory(h->tempOwner); //transported artifact?
  1596. }
  1597. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1598. {
  1599. std::vector<CGTownBuilding*>::const_iterator i;
  1600. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1601. (*i)->onHeroVisit (h);
  1602. }
  1603. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1604. {
  1605. HeroVisitCastle vc;
  1606. vc.hid = heroID;
  1607. vc.tid = obj;
  1608. sendAndApply(&vc);
  1609. }
  1610. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1611. {
  1612. const CGHeroInstance* h = getHero(hid);
  1613. const CArtifact &art = VLC->arth->artifacts[artid];
  1614. SetHeroArtifacts sha;
  1615. sha.hid = hid;
  1616. sha.artifacts = h->artifacts;
  1617. sha.artifWorn = h->artifWorn;
  1618. if(position<0)
  1619. {
  1620. if(position == -2)
  1621. {
  1622. int i;
  1623. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1624. {
  1625. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1626. {
  1627. //we've found a free suitable slot
  1628. VLC->arth->equipArtifact(sha.artifWorn, art.possibleSlots[i], artid);
  1629. break;
  1630. }
  1631. }
  1632. if(i == art.possibleSlots.size() && !art.isBig()) //if haven't find proper slot, use backpack or discard big artifact
  1633. sha.artifacts.push_back(artid);
  1634. }
  1635. else if (!art.isBig()) //should be -1 => put artifact into backpack
  1636. {
  1637. sha.artifacts.push_back(artid);
  1638. }
  1639. }
  1640. else
  1641. {
  1642. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1643. {
  1644. VLC->arth->equipArtifact(sha.artifWorn, position, artid);
  1645. }
  1646. else if (!art.isBig())
  1647. {
  1648. sha.artifacts.push_back(artid);
  1649. }
  1650. }
  1651. sendAndApply(&sha);
  1652. }
  1653. void CGameHandler::removeArtifact(int artid, int hid)
  1654. {
  1655. const CGHeroInstance* h = getHero(hid);
  1656. SetHeroArtifacts sha;
  1657. sha.hid = hid;
  1658. sha.artifacts = h->artifacts;
  1659. sha.artifWorn = h->artifWorn;
  1660. std::vector<ui32>::iterator it;
  1661. if ((it = std::find(sha.artifacts.begin(), sha.artifacts.end(), artid)) != sha.artifacts.end()) //it is in backpack
  1662. sha.artifacts.erase(it);
  1663. else //worn
  1664. {
  1665. for (std::map<ui16,ui32>::iterator itr = sha.artifWorn.begin(); itr != sha.artifWorn.end(); ++itr)
  1666. {
  1667. if (itr->second == artid)
  1668. {
  1669. VLC->arth->unequipArtifact(sha.artifWorn, itr->first);
  1670. break;
  1671. }
  1672. }
  1673. }
  1674. sendAndApply(&sha);
  1675. }
  1676. 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
  1677. {
  1678. engageIntoBattle(army1->tempOwner);
  1679. engageIntoBattle(army2->tempOwner);
  1680. //block engaged players
  1681. if(army2->tempOwner < PLAYER_LIMIT)
  1682. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1683. boost::thread(boost::bind(&CGameHandler::startBattle, this, army1, army2, tile, hero1, hero2, creatureBank, cb, town));
  1684. }
  1685. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  1686. {
  1687. startBattleI(army1, army2, tile,
  1688. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  1689. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  1690. creatureBank, cb);
  1691. }
  1692. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  1693. {
  1694. startBattleI(army1, army2, army2->pos - army2->getVisitableOffset(), cb, creatureBank);
  1695. }
  1696. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1697. //{
  1698. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1699. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  1700. // //battle(&h->army,army,tile,h,NULL);
  1701. //}
  1702. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1703. {
  1704. ChangeSpells cs;
  1705. cs.hid = hid;
  1706. cs.spells = spells;
  1707. cs.learn = give;
  1708. sendAndApply(&cs);
  1709. }
  1710. int CGameHandler::getSelectedHero()
  1711. {
  1712. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1713. }
  1714. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  1715. {
  1716. SetObjectProperty sob;
  1717. sob.id = objid;
  1718. sob.what = prop;
  1719. sob.val = val;
  1720. sendAndApply(&sob);
  1721. }
  1722. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1723. {
  1724. SystemMessage sm;
  1725. sm.text = message;
  1726. c << &sm;
  1727. }
  1728. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1729. {
  1730. sendAndApply(bonus);
  1731. }
  1732. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1733. {
  1734. sendAndApply(smp);
  1735. }
  1736. void CGameHandler::setManaPoints( int hid, int val )
  1737. {
  1738. SetMana sm;
  1739. sm.hid = hid;
  1740. sm.val = val;
  1741. sendAndApply(&sm);
  1742. }
  1743. void CGameHandler::giveHero( int id, int player )
  1744. {
  1745. GiveHero gh;
  1746. gh.id = id;
  1747. gh.player = player;
  1748. sendAndApply(&gh);
  1749. }
  1750. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1751. {
  1752. ChangeObjPos cop;
  1753. cop.objid = objid;
  1754. cop.nPos = newPos;
  1755. cop.flags = flags;
  1756. sendAndApply(&cop);
  1757. }
  1758. void CGameHandler::useScholarSkill(si32 fromHero, si32 toHero)
  1759. {//TODO: dialog window;
  1760. const CGHeroInstance * h1 = getHero(fromHero);
  1761. const CGHeroInstance * h2 = getHero(toHero);
  1762. int ScholarLevel = std::max( h1->getSecSkillLevel(18), h2->getSecSkillLevel(18));//heroes can trade with this levels
  1763. if ( ScholarLevel == 0 )
  1764. return;
  1765. ScholarLevel++;
  1766. int h1Lvl = std::min(ScholarLevel, h1->getSecSkillLevel(7)+2),
  1767. h2Lvl = std::min(ScholarLevel, h2->getSecSkillLevel(7)+2);//heroes can receive this levels
  1768. ChangeSpells cs;
  1769. cs.learn = true;
  1770. cs.hid = toHero;//giving spells to first hero
  1771. for(std::set<ui32>::const_iterator it=h1->spells.begin(); it!=h1->spells.end();it++)
  1772. if ( h2Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h2->spells, *it))//hero can learn it and don't have it yet
  1773. cs.spells.insert(*it);//spell to learn
  1774. if (cs.spells.size())//if found new spell - apply
  1775. sendAndApply(&cs);
  1776. cs.hid = fromHero;
  1777. cs.spells.clear();
  1778. for(std::set<ui32>::const_iterator it=h2->spells.begin(); it!=h2->spells.end();it++)
  1779. if ( h1Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h1->spells, *it))
  1780. cs.spells.insert(*it);
  1781. if (cs.spells.size())
  1782. sendAndApply(&cs);
  1783. }
  1784. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  1785. {
  1786. ui8 player1 = getHero(hero1)->tempOwner;
  1787. ui8 player2 = getHero(hero2)->tempOwner;
  1788. if(player1 == player2)//TODO: allies
  1789. {
  1790. useScholarSkill(hero1,hero2);
  1791. OpenWindow hex;
  1792. hex.window = OpenWindow::EXCHANGE_WINDOW;
  1793. hex.id1 = hero1;
  1794. hex.id2 = hero2;
  1795. sendAndApply(&hex);
  1796. }
  1797. }
  1798. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1799. {
  1800. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1801. sel->id = QID;
  1802. callbacks[QID] = callback;
  1803. states.addQuery(player,QID);
  1804. QID++;
  1805. sendAndApply(sel);
  1806. }
  1807. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1808. {
  1809. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1810. sel->id = QID;
  1811. callbacks[QID] = callback;
  1812. states.addQuery(player,QID);
  1813. sendToAllClients(sel);
  1814. QID++;
  1815. }
  1816. void CGameHandler::sendToAllClients( CPackForClient * info )
  1817. {
  1818. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1819. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1820. {
  1821. (*i)->wmx->lock();
  1822. **i << info;
  1823. (*i)->wmx->unlock();
  1824. }
  1825. }
  1826. void CGameHandler::sendAndApply( CPackForClient * info )
  1827. {
  1828. gs->apply(info);
  1829. sendToAllClients(info);
  1830. }
  1831. void CGameHandler::sendAndApply( SetGarrisons * info )
  1832. {
  1833. sendAndApply((CPackForClient*)info);
  1834. if(gs->map->victoryCondition.condition == gatherTroop)
  1835. for(std::map<ui32,CCreatureSet>::const_iterator i = info->garrs.begin(); i != info->garrs.end(); i++)
  1836. checkLossVictory(getObj(i->first)->tempOwner);
  1837. }
  1838. void CGameHandler::sendAndApply( SetResource * info )
  1839. {
  1840. sendAndApply((CPackForClient*)info);
  1841. if(gs->map->victoryCondition.condition == gatherResource)
  1842. checkLossVictory(info->player);
  1843. }
  1844. void CGameHandler::sendAndApply( SetResources * info )
  1845. {
  1846. sendAndApply((CPackForClient*)info);
  1847. if(gs->map->victoryCondition.condition == gatherResource)
  1848. checkLossVictory(info->player);
  1849. }
  1850. void CGameHandler::sendAndApply( NewStructures * info )
  1851. {
  1852. sendAndApply((CPackForClient*)info);
  1853. if(gs->map->victoryCondition.condition == buildCity)
  1854. checkLossVictory(getTown(info->tid)->tempOwner);
  1855. }
  1856. void CGameHandler::save( const std::string &fname )
  1857. {
  1858. {
  1859. tlog0 << "Ordering clients to serialize...\n";
  1860. SaveGame sg(fname);
  1861. sendToAllClients(&sg);
  1862. }
  1863. {
  1864. tlog0 << "Serializing game info...\n";
  1865. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vlgm1");
  1866. char hlp[8] = "VCMISVG";
  1867. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  1868. }
  1869. {
  1870. tlog0 << "Serializing server info...\n";
  1871. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vsgm1");
  1872. save << *this;
  1873. }
  1874. tlog0 << "Game has been successfully saved!\n";
  1875. }
  1876. void CGameHandler::close()
  1877. {
  1878. tlog0 << "We have been requested to close.\n";
  1879. //BOOST_FOREACH(CConnection *cc, conns)
  1880. // if(cc && cc->socket && cc->socket->is_open())
  1881. // cc->socket->close();
  1882. //exit(0);
  1883. }
  1884. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val )
  1885. {
  1886. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  1887. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  1888. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  1889. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  1890. if(!isAllowedExchange(id1,id2))
  1891. {
  1892. complain("Cannot exchange stacks between these two objects!\n");
  1893. return false;
  1894. }
  1895. if(what==1) //swap
  1896. {
  1897. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  1898. //if one of them is empty, remove entry
  1899. if(!S1.slots[p1].second)
  1900. S1.slots.erase(p1);
  1901. if(!S2.slots[p2].second)
  1902. S2.slots.erase(p2);
  1903. }
  1904. else if(what==2)//merge
  1905. {
  1906. if(S1.slots[p1].first != S2.slots[p2].first) //not same creature
  1907. {
  1908. complain("Cannot merge different creatures stacks!");
  1909. return false;
  1910. }
  1911. S2.slots[p2].second += S1.slots[p1].second;
  1912. S1.slots.erase(p1);
  1913. }
  1914. else if(what==3) //split
  1915. {
  1916. //general conditions checking
  1917. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1918. || (val<1 && complain("no creatures to split")) )
  1919. {
  1920. return false;
  1921. }
  1922. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1923. {
  1924. int total = S1.slots[p1].second + S2.slots[p2].second;
  1925. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1926. || (S2.slots[p2].first != S1.slots[p1].first && complain("Cannot rebalance different creatures stacks!"))
  1927. )
  1928. {
  1929. return false;
  1930. }
  1931. S2.slots[p2].second = val;
  1932. S1.slots[p1].second = total - val;
  1933. }
  1934. else //split one stack to the two
  1935. {
  1936. if(S1.slots[p1].second < val)//not enough creatures
  1937. {
  1938. complain("Cannot split that stack, not enough creatures!");
  1939. return false;
  1940. }
  1941. S2.slots[p2].first = S1.slots[p1].first;
  1942. S2.slots[p2].second = val;
  1943. S1.slots[p1].second -= val;
  1944. }
  1945. if(!S1.slots[p1].second) //if we've moved all creatures
  1946. S1.slots.erase(p1);
  1947. }
  1948. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  1949. || (s2->needsLastStack() && !S2.slots.size())
  1950. )
  1951. {
  1952. complain("Cannot take the last stack!");
  1953. return false; //leave without applying changes to garrison
  1954. }
  1955. //apply changes
  1956. SetGarrisons sg;
  1957. sg.garrs[id1] = S1;
  1958. if(s1 != s2)
  1959. sg.garrs[id2] = S2;
  1960. sendAndApply(&sg);
  1961. return true;
  1962. }
  1963. int CGameHandler::getPlayerAt( CConnection *c ) const
  1964. {
  1965. std::set<int> all;
  1966. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1967. if(i->second == c)
  1968. all.insert(i->first);
  1969. switch(all.size())
  1970. {
  1971. case 0:
  1972. return 255;
  1973. case 1:
  1974. return *all.begin();
  1975. default:
  1976. {
  1977. //if we have more than one player at this connection, try to pick active one
  1978. if(vstd::contains(all,int(gs->currentPlayer)))
  1979. return gs->currentPlayer;
  1980. else
  1981. return 253; //cannot say which player is it
  1982. }
  1983. }
  1984. }
  1985. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  1986. {
  1987. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  1988. if(!vstd::contains(s1->army.slots,pos))
  1989. {
  1990. complain("Illegal call to disbandCreature - no such stack in army!");
  1991. return false;
  1992. }
  1993. s1->army.slots.erase(pos);
  1994. SetGarrisons sg;
  1995. sg.garrs[id] = s1->army;
  1996. sendAndApply(&sg);
  1997. return true;
  1998. }
  1999. bool CGameHandler::buildStructure( si32 tid, si32 bid )
  2000. {
  2001. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2002. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  2003. if(gs->canBuildStructure(t,bid) != 7)
  2004. {
  2005. complain("Cannot raze that building!");
  2006. return false;
  2007. }
  2008. NewStructures ns;
  2009. ns.tid = tid;
  2010. if ( (bid == 18) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[0]+37))) )
  2011. ns.bid.insert(19);//we have upgr. dwelling, upgr. horde will be builded as well
  2012. else if ( (bid == 24) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[1]+37))) )
  2013. ns.bid.insert(25);
  2014. else if(bid>36) //upg dwelling
  2015. {
  2016. if ( (bid-37 == t->town->hordeLvl[0]) && (vstd::contains(t->builtBuildings,18)) )
  2017. ns.bid.insert(19);//we have horde, will be upgraded as well as dwelling
  2018. if ( (bid-37 == t->town->hordeLvl[1]) && (vstd::contains(t->builtBuildings,24)) )
  2019. ns.bid.insert(25);
  2020. SetAvailableCreatures ssi;
  2021. ssi.tid = tid;
  2022. ssi.creatures = t->creatures;
  2023. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  2024. sendAndApply(&ssi);
  2025. }
  2026. else if(bid >= 30) //bas. dwelling
  2027. {
  2028. int crid = t->town->basicCreatures[bid-30];
  2029. SetAvailableCreatures ssi;
  2030. ssi.tid = tid;
  2031. ssi.creatures = t->creatures;
  2032. ssi.creatures[bid-30].first = VLC->creh->creatures[crid].growth;
  2033. ssi.creatures[bid-30].second.push_back(crid);
  2034. sendAndApply(&ssi);
  2035. }
  2036. else if(bid == 11)
  2037. ns.bid.insert(27);
  2038. else if(bid == 12)
  2039. ns.bid.insert(28);
  2040. else if(bid == 13)
  2041. ns.bid.insert(29);
  2042. ns.bid.insert(bid);
  2043. ns.builded = t->builded + 1;
  2044. sendAndApply(&ns);
  2045. //reveal ground for lookout tower
  2046. FoWChange fw;
  2047. fw.player = t->tempOwner;
  2048. fw.mode = 1;
  2049. getTilesInRange(fw.tiles,t->pos,t->getSightRadious(),t->tempOwner,1);
  2050. sendAndApply(&fw);
  2051. SetResources sr;
  2052. sr.player = t->tempOwner;
  2053. sr.res = gs->getPlayer(t->tempOwner)->resources;
  2054. for(int i=0;i<b->resources.size();i++)
  2055. sr.res[i]-=b->resources[i];
  2056. sendAndApply(&sr);
  2057. if(bid<5) //it's mage guild
  2058. {
  2059. if(t->visitingHero)
  2060. giveSpells(t,t->visitingHero);
  2061. if(t->garrisonHero)
  2062. giveSpells(t,t->garrisonHero);
  2063. }
  2064. if(t->visitingHero)
  2065. vistiCastleObjects (t, t->visitingHero);
  2066. if(t->garrisonHero)
  2067. vistiCastleObjects (t, t->garrisonHero);
  2068. return true;
  2069. }
  2070. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  2071. {
  2072. ///incomplete, simply erases target building
  2073. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2074. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  2075. return false;
  2076. RazeStructures rs;
  2077. rs.tid = tid;
  2078. rs.bid.insert(bid);
  2079. rs.destroyed = t->destroyed + 1;
  2080. sendAndApply(&rs);
  2081. return true;
  2082. }
  2083. void CGameHandler::sendMessageToAll( const std::string &message )
  2084. {
  2085. SystemMessage sm;
  2086. sm.text = message;
  2087. sendToAllClients(&sm);
  2088. }
  2089. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  2090. {
  2091. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid]);
  2092. const CArmedInstance *dst = NULL;
  2093. if(dw->ID == TOWNI_TYPE)
  2094. dst = dw;
  2095. else if(dw->ID == 17 || dw->ID == 20) //advmap dwelling
  2096. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  2097. assert(dw && dst);
  2098. //verify
  2099. bool found = false;
  2100. int level = -1;
  2101. typedef std::pair<const int,int> Parka;
  2102. for(level = 0; level < dw->creatures.size(); level++) //iterate through all levels
  2103. {
  2104. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  2105. int i = 0;
  2106. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  2107. if(cur.second[i] == crid)
  2108. break;
  2109. if(i < cur.second.size())
  2110. {
  2111. found = true;
  2112. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  2113. break;
  2114. }
  2115. }
  2116. int slot = dst->army.getSlotFor(crid);
  2117. if(!found && complain("Cannot recruit: no such creatures!")
  2118. || cram > VLC->creh->creatures[crid].maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  2119. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  2120. || slot<0 && complain("Cannot recruit: no available slot!"))
  2121. {
  2122. return false;
  2123. }
  2124. //recruit
  2125. SetResources sr;
  2126. sr.player = dst->tempOwner;
  2127. for(int i=0;i<RESOURCE_QUANTITY;i++)
  2128. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  2129. SetAvailableCreatures sac;
  2130. sac.tid = objid;
  2131. sac.creatures = dw->creatures;
  2132. sac.creatures[level].first -= cram;
  2133. SetGarrisons sg;
  2134. sg.garrs[dst->id] = dst->army;
  2135. if(sg.garrs[dst->id].slots.find(slot) == sg.garrs[dst->id].slots.end()) //take a free slot
  2136. {
  2137. sg.garrs[dst->id].slots[slot] = std::make_pair(crid,cram);
  2138. }
  2139. else //add creatures to a already existing stack
  2140. {
  2141. sg.garrs[dst->id].slots[slot].second += cram;
  2142. }
  2143. sendAndApply(&sr);
  2144. sendAndApply(&sac);
  2145. sendAndApply(&sg);
  2146. return true;
  2147. }
  2148. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  2149. {
  2150. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  2151. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  2152. int player = obj->tempOwner;
  2153. int crQuantity = obj->army.slots[pos].second;
  2154. //check if upgrade is possible
  2155. if((ui.oldID<0 || !vstd::contains(ui.newID,upgID)) && complain("That upgrade is not possible!"))
  2156. {
  2157. return false;
  2158. }
  2159. //check if player has enough resources
  2160. for(int i=0;i<ui.cost.size();i++)
  2161. {
  2162. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2163. {
  2164. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  2165. {
  2166. complain("Cannot upgrade, not enough resources!");
  2167. return false;
  2168. }
  2169. }
  2170. }
  2171. //take resources
  2172. for(int i=0;i<ui.cost.size();i++)
  2173. {
  2174. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2175. {
  2176. SetResource sr;
  2177. sr.player = player;
  2178. sr.resid = j->first;
  2179. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  2180. sendAndApply(&sr);
  2181. }
  2182. }
  2183. //upgrade creature
  2184. SetGarrisons sg;
  2185. sg.garrs[objid] = obj->army;
  2186. sg.garrs[objid].slots[pos].first = upgID;
  2187. sendAndApply(&sg);
  2188. return true;
  2189. }
  2190. bool CGameHandler::garrisonSwap( si32 tid )
  2191. {
  2192. CGTownInstance *town = gs->getTown(tid);
  2193. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2194. {
  2195. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  2196. while(!cso.slots.empty())//while there are unmoved creatures
  2197. {
  2198. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  2199. if(pos<0)
  2200. {
  2201. //try to merge two other stacks to make place
  2202. std::pair<TSlot, TSlot> toMerge;
  2203. if(csn.mergableStacks(toMerge, cso.slots.begin()->first))
  2204. {
  2205. //merge
  2206. csn.slots[toMerge.second].second += csn.slots[toMerge.first].second;
  2207. csn.slots[toMerge.first] = cso.slots.begin()->second;
  2208. }
  2209. else
  2210. {
  2211. complain("Cannot make garrison swap, not enough free slots!");
  2212. return false;
  2213. }
  2214. }
  2215. else if(csn.slots.find(pos) != csn.slots.end()) //add creatures to the existing stack
  2216. {
  2217. csn.slots[pos].second += cso.slots.begin()->second.second;
  2218. }
  2219. else //move stack on the free pos
  2220. {
  2221. csn.slots[pos].first = cso.slots.begin()->second.first;
  2222. csn.slots[pos].second = cso.slots.begin()->second.second;
  2223. }
  2224. cso.slots.erase(cso.slots.begin());
  2225. }
  2226. SetGarrisons sg;
  2227. sg.garrs[town->visitingHero->id] = csn;
  2228. sg.garrs[town->id] = csn;
  2229. sendAndApply(&sg);
  2230. SetHeroesInTown intown;
  2231. intown.tid = tid;
  2232. intown.visiting = -1;
  2233. intown.garrison = town->visitingHero->id;
  2234. sendAndApply(&intown);
  2235. return true;
  2236. }
  2237. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2238. {
  2239. //check if moving hero out of town will break 8 wandering heroes limit
  2240. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2241. {
  2242. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2243. return false;
  2244. }
  2245. SetHeroesInTown intown;
  2246. intown.tid = tid;
  2247. intown.garrison = -1;
  2248. intown.visiting = town->garrisonHero->id;
  2249. sendAndApply(&intown);
  2250. //town will be empty
  2251. SetGarrisons sg;
  2252. sg.garrs[tid] = CCreatureSet();
  2253. sendAndApply(&sg);
  2254. return true;
  2255. }
  2256. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2257. {
  2258. SetGarrisons sg;
  2259. sg.garrs[town->id] = town->visitingHero->army;
  2260. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  2261. SetHeroesInTown intown;
  2262. intown.tid = tid;
  2263. intown.garrison = town->visitingHero->id;
  2264. intown.visiting = town->garrisonHero->id;
  2265. sendAndApply(&intown);
  2266. sendAndApply(&sg);
  2267. return true;
  2268. }
  2269. else
  2270. {
  2271. complain("Cannot swap garrison hero!");
  2272. return false;
  2273. }
  2274. }
  2275. // With the amount of changes done to the function, it's more like transferArtifacts.
  2276. bool CGameHandler::swapArtifacts(si32 srcHeroID, si32 destHeroID, ui16 srcSlot, ui16 destSlot)
  2277. {
  2278. CGHeroInstance *srcHero = gs->getHero(srcHeroID);
  2279. CGHeroInstance *destHero = gs->getHero(destHeroID);
  2280. // Make sure exchange is even possible between the two heroes.
  2281. if ((distance(srcHero->pos,destHero->pos) > 1.5 )|| (srcHero->tempOwner != destHero->tempOwner))
  2282. return false;
  2283. const CArtifact *srcArtifact = srcHero->getArt(srcSlot);
  2284. const CArtifact *destArtifact = destHero->getArt(destSlot);
  2285. SetHeroArtifacts sha;
  2286. sha.hid = srcHeroID;
  2287. sha.artifacts = srcHero->artifacts;
  2288. sha.artifWorn = srcHero->artifWorn;
  2289. // Combinational artifacts needs to be removed first so they don't get denied movement because of their own locks.
  2290. if (srcHeroID == destHeroID && srcSlot < 19) {
  2291. VLC->arth->unequipArtifact(sha.artifWorn, srcSlot);
  2292. if (sha.artifWorn.find(destSlot) == sha.artifWorn.end())
  2293. destArtifact = NULL;
  2294. }
  2295. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2296. // Moving to the backpack is always allowed.
  2297. if ((!srcArtifact || destSlot < 19)
  2298. && (srcArtifact && !srcArtifact->fitsAt(srcHeroID == destHeroID ? sha.artifWorn : destHero->artifWorn, destSlot)))
  2299. {
  2300. complain("Cannot swap artifacts!");
  2301. return false;
  2302. }
  2303. if ((srcArtifact && srcArtifact->id == 145) || (destArtifact && destArtifact->id == 145)) {
  2304. complain("Cannot move artifact locks.");
  2305. return false;
  2306. }
  2307. if (destSlot >= 19 && srcArtifact->isBig()) {
  2308. complain("Cannot put big artifacts in backpack!");
  2309. return false;
  2310. }
  2311. if (srcSlot == 16 || destSlot == 16) {
  2312. complain("Cannot move catapult!");
  2313. return false;
  2314. }
  2315. // If dest does not fit in src, put it in dest's backpack instead.
  2316. bool destFits = !destArtifact || srcSlot >= 19 || destArtifact->fitsAt(sha.artifWorn, srcSlot);
  2317. sha.setArtAtPos(srcSlot, -1);
  2318. if (destSlot < 19 && (destArtifact || srcSlot < 19) && destFits)
  2319. sha.setArtAtPos(srcSlot, destHero->getArtAtPos(destSlot));
  2320. // Internal hero artifact arrangement.
  2321. if(srcHero == destHero) {
  2322. // Correction for destination from removing source artifact in backpack.
  2323. if (srcSlot >= 19 && destSlot >= 19 && srcSlot < destSlot)
  2324. destSlot--;
  2325. sha.setArtAtPos(destSlot, srcHero->getArtAtPos(srcSlot));
  2326. }
  2327. sendAndApply(&sha);
  2328. if (srcHeroID != destHeroID) {
  2329. // Exchange between two different heroes.
  2330. sha.hid = destHeroID;
  2331. sha.artifacts = destHero->artifacts;
  2332. sha.artifWorn = destHero->artifWorn;
  2333. sha.setArtAtPos(destSlot, srcArtifact ? srcArtifact->id : -1);
  2334. if (!destFits)
  2335. sha.setArtAtPos(sha.artifacts.size() + 19, destHero->getArtAtPos(destSlot));
  2336. sendAndApply(&sha);
  2337. }
  2338. return true;
  2339. }
  2340. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2341. {
  2342. CGHeroInstance *hero = gs->getHero(hid);
  2343. CGTownInstance *town = hero->visitedTown;
  2344. if(aid==0) //spellbook
  2345. {
  2346. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2347. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  2348. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  2349. )
  2350. return false;
  2351. giveResource(hero->getOwner(),6,-500);
  2352. giveHeroArtifact(0,hid,17);
  2353. giveSpells(town,hero);
  2354. return true;
  2355. }
  2356. else if(aid < 7 && aid > 3) //war machine
  2357. {
  2358. int price = VLC->arth->artifacts[aid].price;
  2359. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2360. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2361. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  2362. || (!(town->subID == 6 && vstd::contains(town->builtBuildings,si32(22) ) )
  2363. && town->town->warMachine!= aid ) && complain("This machine is unavailable here!") )
  2364. {
  2365. return false;
  2366. }
  2367. giveResource(hero->getOwner(),6,-price);
  2368. giveHeroArtifact(aid,hid,9+aid);
  2369. return true;
  2370. }
  2371. return false;
  2372. }
  2373. bool CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  2374. {
  2375. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  2376. double yield = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  2377. yield /= gs->resVals[id2];
  2378. SetResource sr;
  2379. sr.player = player;
  2380. sr.resid = id1;
  2381. sr.val = gs->getPlayer(player)->resources[id1] - val;
  2382. sendAndApply(&sr);
  2383. sr.resid = id2;
  2384. sr.val = gs->getPlayer(player)->resources[id2] + (int)yield;
  2385. sendAndApply(&sr);
  2386. return true;
  2387. }
  2388. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  2389. {
  2390. gs->getHero(hid)->army.formation = formation;
  2391. return true;
  2392. }
  2393. bool CGameHandler::hireHero( ui32 tid, ui8 hid )
  2394. {
  2395. CGTownInstance *t = gs->getTown(tid);
  2396. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  2397. || gs->getPlayer(t->tempOwner)->resources[6]<2500 && complain("Not enough gold for buying hero!")
  2398. || t->visitingHero && complain("There is visiting hero - no place!")
  2399. || getHeroCount(t->tempOwner,false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!")
  2400. )
  2401. return false;
  2402. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  2403. assert(nh);
  2404. HeroRecruited hr;
  2405. hr.tid = tid;
  2406. hr.hid = nh->subID;
  2407. hr.player = t->tempOwner;
  2408. hr.tile = t->pos - int3(1,0,0);
  2409. sendAndApply(&hr);
  2410. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  2411. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  2412. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2413. if(*j)
  2414. pool.erase((**j).subID);
  2415. SetAvailableHeroes sah;
  2416. CGHeroInstance *h1 = gs->hpool.pickHeroFor(false,t->tempOwner,t->town, pool),
  2417. *h2 = gs->getPlayer(t->tempOwner)->availableHeroes[!hid];
  2418. (hid ? sah.hid2 : sah.hid1) = h1 ? h1->subID : -1;
  2419. (hid ? sah.hid1 : sah.hid2) = h2 ? h2->subID : -1;
  2420. sah.player = t->tempOwner;
  2421. sah.flags = hid+1;
  2422. sendAndApply(&sah);
  2423. SetResource sr;
  2424. sr.player = t->tempOwner;
  2425. sr.resid = 6;
  2426. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  2427. sendAndApply(&sr);
  2428. vistiCastleObjects (t, nh);
  2429. giveSpells (t,nh);
  2430. return true;
  2431. }
  2432. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  2433. {
  2434. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2435. if(vstd::contains(callbacks,qid))
  2436. {
  2437. CFunctionList<void(ui32)> callb = callbacks[qid];
  2438. callbacks.erase(qid);
  2439. if(callb)
  2440. callb(answer);
  2441. }
  2442. else if(vstd::contains(garrisonCallbacks,qid))
  2443. {
  2444. if(garrisonCallbacks[qid])
  2445. garrisonCallbacks[qid]();
  2446. garrisonCallbacks.erase(qid);
  2447. allowedExchanges.erase(qid);
  2448. }
  2449. else
  2450. {
  2451. tlog1 << "Unknown query reply...\n";
  2452. return false;
  2453. }
  2454. return true;
  2455. }
  2456. bool CGameHandler::makeBattleAction( BattleAction &ba )
  2457. {
  2458. tlog1 << "\tMaking action of type " << ba.actionType << std::endl;
  2459. bool ok = true;
  2460. switch(ba.actionType)
  2461. {
  2462. case 2: //walk
  2463. {
  2464. sendAndApply(&StartAction(ba)); //start movement
  2465. moveStack(ba.stackNumber,ba.destinationTile); //move
  2466. sendAndApply(&EndAction());
  2467. break;
  2468. }
  2469. case 3: //defend
  2470. case 8: //wait
  2471. {
  2472. sendAndApply(&StartAction(ba));
  2473. sendAndApply(&EndAction());
  2474. break;
  2475. }
  2476. case 4: //retreat/flee
  2477. {
  2478. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  2479. break;
  2480. //TODO: remove retreating hero from map and place it in recruitment list
  2481. BattleResult *br = new BattleResult;
  2482. br->result = 1;
  2483. br->winner = !ba.side; //fleeing side loses
  2484. gs->curB->calculateCasualties(br->casualties);
  2485. giveExp(*br);
  2486. battleResult.set(br);
  2487. break;
  2488. }
  2489. case 6: //walk or attack
  2490. {
  2491. sendAndApply(&StartAction(ba)); //start movement and attack
  2492. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  2493. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  2494. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2495. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  2496. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  2497. && !(curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  2498. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  2499. ) //nor occupy specified hex
  2500. )
  2501. {
  2502. std::string problem = "We cannot move this stack to its destination " + curStack->creature->namePl;
  2503. tlog3 << problem << std::endl;
  2504. complain(problem);
  2505. ok = false;
  2506. sendAndApply(&EndAction());
  2507. break;
  2508. }
  2509. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  2510. {
  2511. stackAtEnd = NULL;
  2512. }
  2513. if(!stackAtEnd)
  2514. {
  2515. std::ostringstream problem;
  2516. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  2517. std::string probl = problem.str();
  2518. tlog3 << probl << std::endl;
  2519. complain(probl);
  2520. ok = false;
  2521. sendAndApply(&EndAction());
  2522. break;
  2523. }
  2524. ui16 curpos = curStack->position,
  2525. enemypos = stackAtEnd->position;
  2526. if( !(
  2527. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  2528. || (curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //back <=> front
  2529. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  2530. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //front <=> back
  2531. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2532. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)//back <=> back
  2533. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2534. )
  2535. )
  2536. {
  2537. tlog3 << "Attack cannot be performed!";
  2538. sendAndApply(&EndAction());
  2539. ok = false;
  2540. }
  2541. //attack
  2542. BattleAttack bat;
  2543. prepareAttack(bat, curStack, stackAtEnd, distance);
  2544. sendAndApply(&bat);
  2545. //counterattack
  2546. if(!curStack->hasFeatureOfType(StackFeature::BLOCKS_RETALIATION)
  2547. && stackAtEnd->alive()
  2548. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasFeatureOfType(StackFeature::UNLIMITED_RETALIATIONS) )
  2549. && !stackAtEnd->hasFeatureOfType(StackFeature::SIEGE_WEAPON)
  2550. && !stackAtEnd->hasFeatureOfType(StackFeature::HYPNOTIZED))
  2551. {
  2552. prepareAttack(bat, stackAtEnd, curStack, 0);
  2553. bat.flags |= 2;
  2554. sendAndApply(&bat);
  2555. }
  2556. //second attack
  2557. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0
  2558. && !curStack->hasFeatureOfType(StackFeature::SHOOTER)
  2559. && curStack->alive()
  2560. && stackAtEnd->alive() )
  2561. {
  2562. bat.flags = 0;
  2563. prepareAttack(bat, curStack, stackAtEnd, 0);
  2564. sendAndApply(&bat);
  2565. }
  2566. //return
  2567. if(curStack->hasFeatureOfType(StackFeature::RETURN_AFTER_STRIKE) && startingPos != curStack->position && curStack->alive())
  2568. {
  2569. moveStack(ba.stackNumber, startingPos);
  2570. //NOTE: curStack->ID == ba.stackNumber (rev 1431)
  2571. }
  2572. sendAndApply(&EndAction());
  2573. break;
  2574. }
  2575. case 7: //shoot
  2576. {
  2577. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2578. *destStack= gs->curB->getStackT(ba.destinationTile);
  2579. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  2580. break;
  2581. sendAndApply(&StartAction(ba)); //start shooting
  2582. BattleAttack bat;
  2583. prepareAttack(bat, curStack, destStack, 0);
  2584. bat.flags |= 1;
  2585. sendAndApply(&bat);
  2586. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  2587. && curStack->alive()
  2588. && destStack->alive()
  2589. && curStack->shots
  2590. )
  2591. {
  2592. prepareAttack(bat, curStack, destStack, 0);
  2593. sendAndApply(&bat);
  2594. }
  2595. sendAndApply(&EndAction());
  2596. break;
  2597. }
  2598. case 9: //catapult
  2599. {
  2600. sendAndApply(&StartAction(ba));
  2601. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  2602. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(20)]; //artillery
  2603. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  2604. if(attackedPart == -1)
  2605. {
  2606. complain("catapult tried to attack non-catapultable hex!");
  2607. break;
  2608. }
  2609. int wallInitHP = gs->curB->si.wallState[attackedPart];
  2610. int dmgAlreadyDealt = 0; //in successive iterations damage is dealt but not yet substracted from wall's HPs
  2611. for(int g=0; g<sbi.shots; ++g)
  2612. {
  2613. if(wallInitHP + dmgAlreadyDealt == 3) //it's not destroyed
  2614. continue;
  2615. CatapultAttack ca; //package for clients
  2616. std::pair< std::pair< ui8, si16 >, ui8> attack; //<< attackedPart , destination tile >, damageDealt >
  2617. attack.first.first = attackedPart;
  2618. attack.first.second = ba.destinationTile;
  2619. attack.second = 0;
  2620. int chanceForHit = 0;
  2621. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  2622. switch(attackedPart)
  2623. {
  2624. case 0: //keep
  2625. chanceForHit = sbi.keep;
  2626. break;
  2627. case 1: //bottom tower
  2628. case 6: //upper tower
  2629. chanceForHit = sbi.tower;
  2630. break;
  2631. case 2: //bottom wall
  2632. case 3: //below gate
  2633. case 4: //over gate
  2634. case 5: //upper wall
  2635. chanceForHit = sbi.wall;
  2636. break;
  2637. case 7: //gate
  2638. chanceForHit = sbi.gate;
  2639. break;
  2640. }
  2641. if(rand()%100 <= chanceForHit) //hit is successful
  2642. {
  2643. int dmgRand = rand()%100;
  2644. //accumulating dmgChance
  2645. dmgChance[1] += dmgChance[0];
  2646. dmgChance[2] += dmgChance[1];
  2647. //calculating dealt damage
  2648. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  2649. {
  2650. if(dmgRand <= dmgChance[v])
  2651. {
  2652. attack.second = std::min(3 - dmgAlreadyDealt - wallInitHP, v);
  2653. dmgAlreadyDealt += attack.second;
  2654. break;
  2655. }
  2656. }
  2657. //removing creatures in turrets / keep if one is destroyed
  2658. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  2659. {
  2660. int posRemove = -1;
  2661. switch(attackedPart)
  2662. {
  2663. case 0: //keep
  2664. posRemove = -2;
  2665. break;
  2666. case 1: //bottom tower
  2667. posRemove = -3;
  2668. break;
  2669. case 6: //upper tower
  2670. posRemove = -4;
  2671. break;
  2672. }
  2673. BattleStacksRemoved bsr;
  2674. for(int g=0; g<gs->curB->stacks.size(); ++g)
  2675. {
  2676. if(gs->curB->stacks[g]->position == posRemove)
  2677. {
  2678. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  2679. break;
  2680. }
  2681. }
  2682. sendAndApply(&bsr);
  2683. }
  2684. }
  2685. ca.attacker = ba.stackNumber;
  2686. ca.attackedParts.insert(attack);
  2687. sendAndApply(&ca);
  2688. }
  2689. sendAndApply(&EndAction());
  2690. break;
  2691. }
  2692. }
  2693. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  2694. battleMadeAction.setn(true);
  2695. return ok;
  2696. }
  2697. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  2698. {
  2699. bool cheated=true;
  2700. sendAndApply(&PlayerMessage(player,message));
  2701. if(message == "vcmiistari") //give all spells and 999 mana
  2702. {
  2703. SetMana sm;
  2704. ChangeSpells cs;
  2705. SetHeroArtifacts sha;
  2706. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  2707. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  2708. sm.hid = cs.hid = h->id;
  2709. //give all spells
  2710. cs.learn = 1;
  2711. for(int i=0;i<VLC->spellh->spells.size();i++)
  2712. {
  2713. if(!VLC->spellh->spells[i].creatureAbility)
  2714. cs.spells.insert(i);
  2715. }
  2716. //give mana
  2717. sm.val = 999;
  2718. if(!h->getArt(17)) //hero doesn't have spellbook
  2719. {
  2720. //give spellbook
  2721. sha.hid = h->id;
  2722. sha.artifacts = h->artifacts;
  2723. sha.artifWorn = h->artifWorn;
  2724. VLC->arth->equipArtifact(sha.artifWorn, 17, 0);
  2725. sendAndApply(&sha);
  2726. }
  2727. sendAndApply(&cs);
  2728. sendAndApply(&sm);
  2729. }
  2730. else if(message == "vcmiainur") //gives 5 archangels into each slot
  2731. {
  2732. SetGarrisons sg;
  2733. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2734. if(!hero) return;
  2735. sg.garrs[hero->id] = hero->army;
  2736. for(int i=0;i<7;i++)
  2737. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2738. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  2739. sendAndApply(&sg);
  2740. }
  2741. else if(message == "vcmiangband") //gives 10 black knight into each slot
  2742. {
  2743. SetGarrisons sg;
  2744. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2745. if(!hero) return;
  2746. sg.garrs[hero->id] = hero->army;
  2747. for(int i=0;i<7;i++)
  2748. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2749. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  2750. sendAndApply(&sg);
  2751. }
  2752. else if(message == "vcminoldor") //all war machines
  2753. {
  2754. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2755. if(!hero) return;
  2756. SetHeroArtifacts sha;
  2757. sha.hid = hero->id;
  2758. sha.artifacts = hero->artifacts;
  2759. sha.artifWorn = hero->artifWorn;
  2760. VLC->arth->equipArtifact(sha.artifWorn, 13, 4);
  2761. VLC->arth->equipArtifact(sha.artifWorn, 14, 5);
  2762. VLC->arth->equipArtifact(sha.artifWorn, 15, 6);
  2763. sendAndApply(&sha);
  2764. }
  2765. else if(message == "vcminahar") //1000000 movement points
  2766. {
  2767. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2768. if(!hero) return;
  2769. SetMovePoints smp;
  2770. smp.hid = hero->id;
  2771. smp.val = 1000000;
  2772. sendAndApply(&smp);
  2773. }
  2774. else if(message == "vcmiformenos") //give resources
  2775. {
  2776. SetResources sr;
  2777. sr.player = player;
  2778. sr.res = gs->getPlayer(player)->resources;
  2779. for(int i=0;i<7;i++)
  2780. sr.res[i] += 100;
  2781. sr.res[6] += 19900;
  2782. sendAndApply(&sr);
  2783. }
  2784. else if(message == "vcmieagles") //reveal FoW
  2785. {
  2786. FoWChange fc;
  2787. fc.mode = 1;
  2788. fc.player = player;
  2789. for(int i=0;i<gs->map->width;i++)
  2790. for(int j=0;j<gs->map->height;j++)
  2791. for(int k=0;k<gs->map->twoLevel+1;k++)
  2792. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  2793. fc.tiles.insert(int3(i,j,k));
  2794. sendAndApply(&fc);
  2795. }
  2796. else if(message == "vcmiglorfindel")
  2797. {
  2798. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2799. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  2800. }
  2801. else
  2802. cheated = false;
  2803. if(cheated)
  2804. {
  2805. sendAndApply(&SystemMessage(VLC->generaltexth->allTexts[260]));
  2806. }
  2807. }
  2808. static ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack)
  2809. {
  2810. switch(spell->id)
  2811. {
  2812. case 37: //cure
  2813. {
  2814. int healedHealth = caster->getPrimSkillLevel(2) * 5 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2815. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft);
  2816. break;
  2817. }
  2818. case 38: //resurrection
  2819. {
  2820. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2821. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2822. break;
  2823. }
  2824. case 39: //animate dead
  2825. {
  2826. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2827. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2828. break;
  2829. }
  2830. }
  2831. //we shouldn't be here
  2832. tlog1 << "calculateHealedHP called for non-healing spell: " << spell->name << std::endl;
  2833. return 0;
  2834. }
  2835. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  2836. {
  2837. std::vector<ui32> ret;
  2838. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2839. {
  2840. if ((*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2841. || ((*it)->valOfFeatures(StackFeature::LEVEL_SPELL_IMMUNITY) >= sp->level))
  2842. {
  2843. ret.push_back((*it)->ID);
  2844. continue;
  2845. }
  2846. //non-negative spells on friendly stacks should always succeed, unless immune
  2847. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  2848. continue;
  2849. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  2850. if((*it)->owner == caster->tempOwner)
  2851. bonusHero = caster;
  2852. else
  2853. bonusHero = hero2;
  2854. int prob = (*it)->valOfFeatures(StackFeature::MAGIC_RESISTANCE); //probability of resistance in %
  2855. if(bonusHero)
  2856. {
  2857. //bonusHero's resistance support (secondary skils and artifacts)
  2858. prob += bonusHero->valOfBonuses(HeroBonus::MAGIC_RESISTANCE);
  2859. switch(bonusHero->getSecSkillLevel(26)) //resistance
  2860. {
  2861. case 1: //basic
  2862. prob += 5;
  2863. break;
  2864. case 2: //advanced
  2865. prob += 10;
  2866. break;
  2867. case 3: //expert
  2868. prob += 20;
  2869. break;
  2870. }
  2871. }
  2872. if(prob > 100) prob = 100;
  2873. if(rand()%100 < prob) //immunity from resistance
  2874. ret.push_back((*it)->ID);
  2875. }
  2876. if(sp->id == 60) //hypnotize
  2877. {
  2878. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2879. {
  2880. if( (*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2881. || ( (*it)->amount - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  2882. >
  2883. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  2884. )
  2885. {
  2886. ret.push_back((*it)->ID);
  2887. }
  2888. }
  2889. }
  2890. return ret;
  2891. }
  2892. bool CGameHandler::makeCustomAction( BattleAction &ba )
  2893. {
  2894. switch(ba.actionType)
  2895. {
  2896. case 1: //hero casts spell
  2897. {
  2898. const CGHeroInstance *h = gs->curB->heroes[ba.side];
  2899. const CGHeroInstance *secondHero = gs->curB->heroes[!ba.side];
  2900. if(!h)
  2901. {
  2902. tlog2 << "Wrong caster!\n";
  2903. return false;
  2904. }
  2905. if(ba.additionalInfo >= VLC->spellh->spells.size())
  2906. {
  2907. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  2908. return false;
  2909. }
  2910. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  2911. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  2912. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  2913. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  2914. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  2915. || (gs->curB->castSpells[ba.side]) //spell has been cast
  2916. || (secondHero->hasBonusOfType(HeroBonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  2917. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  2918. )
  2919. {
  2920. tlog2 << "Spell cannot be cast!\n";
  2921. return false;
  2922. }
  2923. sendAndApply(&StartAction(ba)); //start spell casting
  2924. SpellCast sc;
  2925. sc.side = ba.side;
  2926. sc.id = ba.additionalInfo;
  2927. sc.skill = skill;
  2928. sc.tile = ba.destinationTile;
  2929. sc.dmgToDisplay = 0;
  2930. //calculating affected creatures for all spells
  2931. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(s, h, ba.destinationTile);
  2932. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2933. {
  2934. sc.affectedCres.insert((*it)->ID);
  2935. }
  2936. //checking if creatures resist
  2937. sc.resisted = calculateResistedStacks(s, h, secondHero, attackedCres);
  2938. //calculating dmg to display
  2939. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2940. {
  2941. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2942. continue;
  2943. sc.dmgToDisplay += gs->curB->calculateSpellDmg(s, h, *it);
  2944. }
  2945. sendAndApply(&sc);
  2946. //applying effects
  2947. switch(ba.additionalInfo) //spell id
  2948. {
  2949. case 15: //magic arrow
  2950. case 16: //ice bolt
  2951. case 17: //lightning bolt
  2952. case 18: //implosion
  2953. case 20: //frost ring
  2954. case 21: //fireball
  2955. case 22: //inferno
  2956. case 23: //meteor shower
  2957. case 24: //death ripple
  2958. case 25: //destroy undead
  2959. case 26: //armageddon
  2960. {
  2961. StacksInjured si;
  2962. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2963. {
  2964. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2965. continue;
  2966. BattleStackAttacked bsa;
  2967. bsa.flags |= 2;
  2968. bsa.effect = VLC->spellh->spells[ba.additionalInfo].mainEffectAnim;
  2969. bsa.damageAmount = gs->curB->calculateSpellDmg(s, h, *it);
  2970. bsa.stackAttacked = (*it)->ID;
  2971. bsa.attackerID = -1;
  2972. prepareAttacked(bsa,*it);
  2973. si.stacks.insert(bsa);
  2974. }
  2975. if(!si.stacks.empty())
  2976. sendAndApply(&si);
  2977. break;
  2978. }
  2979. case 27: //shield
  2980. case 28: //air shield
  2981. case 30: //protection from air
  2982. case 31: //protection from fire
  2983. case 32: //protection from water
  2984. case 33: //protection from earth
  2985. case 34: //anti-magic
  2986. case 41: //bless
  2987. case 42: //curse
  2988. case 43: //bloodlust
  2989. case 44: //precision
  2990. case 45: //weakness
  2991. case 46: //stone skin
  2992. case 47: //disrupting ray
  2993. case 48: //prayer
  2994. case 49: //mirth
  2995. case 50: //sorrow
  2996. case 51: //fortune
  2997. case 52: //misfortune
  2998. case 53: //haste
  2999. case 54: //slow
  3000. case 55: //slayer
  3001. case 56: //frenzy
  3002. case 58: //counterstrike
  3003. case 59: //berserk
  3004. case 60: //hypnotize
  3005. case 61: //forgetfulness
  3006. case 62: //blind
  3007. {
  3008. SetStackEffect sse;
  3009. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3010. {
  3011. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3012. continue;
  3013. sse.stacks.insert((*it)->ID);
  3014. }
  3015. sse.effect.id = ba.additionalInfo;
  3016. sse.effect.level = h->getSpellSchoolLevel(s);
  3017. sse.effect.turnsRemain = BattleInfo::calculateSpellDuration(s, h);
  3018. if(!sse.stacks.empty())
  3019. sendAndApply(&sse);
  3020. break;
  3021. }
  3022. case 37: //cure
  3023. case 38: //resurrection
  3024. case 39: //animate dead
  3025. {
  3026. StacksHealedOrResurrected shr;
  3027. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3028. {
  3029. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  3030. || (s->id == 39 && !(*it)->hasFeatureOfType(StackFeature::UNDEAD)) //we try to cast animate dead on living stack
  3031. )
  3032. continue;
  3033. StacksHealedOrResurrected::HealInfo hi;
  3034. hi.stackID = (*it)->ID;
  3035. hi.healedHP = calculateHealedHP(h, s, *it);
  3036. hi.lowLevelResurrection = h->getSpellSchoolLevel(s) <= 1;
  3037. shr.healedStacks.push_back(hi);
  3038. }
  3039. if(!shr.healedStacks.empty())
  3040. sendAndApply(&shr);
  3041. break;
  3042. }
  3043. case 64: //remove obstacle
  3044. {
  3045. ObstaclesRemoved obr;
  3046. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  3047. {
  3048. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  3049. if(vstd::contains(blockedHexes, ba.destinationTile)) //this obstacle covers given hex
  3050. {
  3051. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  3052. }
  3053. }
  3054. if(!obr.obstacles.empty())
  3055. sendAndApply(&obr);
  3056. break;
  3057. }
  3058. }
  3059. sendAndApply(&EndAction());
  3060. if( !gs->curB->getStack(gs->curB->activeStack, false)->alive() )
  3061. {
  3062. battleMadeAction.setn(true);
  3063. }
  3064. checkForBattleEnd(gs->curB->stacks);
  3065. if(battleResult.get())
  3066. {
  3067. endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  3068. }
  3069. return true;
  3070. }
  3071. }
  3072. return false;
  3073. }
  3074. void CGameHandler::handleTimeEvents()
  3075. {
  3076. gs->map->events.sort(evntCmp);
  3077. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  3078. {
  3079. CMapEvent *ev = gs->map->events.front();
  3080. for(int player = 0; player < PLAYER_LIMIT; player++)
  3081. {
  3082. PlayerState *pinfo = gs->getPlayer(player);
  3083. if( pinfo //player exists
  3084. && (ev->players & 1<<player) //event is enabled to this player
  3085. && ((ev->computerAffected && !pinfo->human)
  3086. || (ev->humanAffected && pinfo->human)
  3087. )
  3088. )
  3089. {
  3090. //give resources
  3091. SetResources sr;
  3092. sr.player = player;
  3093. sr.res = pinfo->resources;
  3094. //prepare dialog
  3095. InfoWindow iw;
  3096. iw.player = player;
  3097. iw.text << ev->message;
  3098. for (int i=0; i<ev->resources.size(); i++)
  3099. {
  3100. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  3101. {
  3102. // If removing too much resources, adjust the
  3103. // amount so the total doesn't become negative.
  3104. if (sr.res[i] + ev->resources[i] < 0)
  3105. ev->resources[i] = -sr.res[i];
  3106. if(ev->resources[i]) //if non-zero res change
  3107. {
  3108. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  3109. sr.res[i] += ev->resources[i];
  3110. }
  3111. }
  3112. }
  3113. if (iw.components.size())
  3114. {
  3115. sendAndApply(&sr); //update player resources if changed
  3116. }
  3117. sendAndApply(&iw); //show dialog
  3118. }
  3119. } //PLAYERS LOOP
  3120. if(ev->nextOccurence)
  3121. {
  3122. ev->firstOccurence += ev->nextOccurence;
  3123. gs->map->events.sort(evntCmp);
  3124. }
  3125. else
  3126. {
  3127. delete ev;
  3128. gs->map->events.pop_front();
  3129. }
  3130. }
  3131. }
  3132. bool CGameHandler::complain( const std::string &problem )
  3133. {
  3134. sendMessageToAll("Server encountered a problem: " + problem);
  3135. tlog1 << problem << std::endl;
  3136. return true;
  3137. }
  3138. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  3139. {
  3140. //TODO: write
  3141. return 0;
  3142. }
  3143. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  3144. {
  3145. ui8 player = getOwner(hid);
  3146. GarrisonDialog gd;
  3147. gd.hid = hid;
  3148. gd.objid = upobj;
  3149. {
  3150. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3151. gd.id = QID;
  3152. garrisonCallbacks[QID] = cb;
  3153. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  3154. states.addQuery(player,QID);
  3155. QID++;
  3156. gd.removableUnits = removableUnits;
  3157. sendAndApply(&gd);
  3158. }
  3159. }
  3160. void CGameHandler::showThievesGuildWindow(int requestingObjId)
  3161. {
  3162. OpenWindow ow;
  3163. ow.window = OpenWindow::THIEVES_GUILD;
  3164. ow.id1 = requestingObjId;
  3165. sendAndApply(&ow);
  3166. }
  3167. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  3168. {
  3169. if(id1 == id2)
  3170. return true;
  3171. {
  3172. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3173. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  3174. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  3175. return true;
  3176. }
  3177. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  3178. if(o1->ID == TOWNI_TYPE)
  3179. {
  3180. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  3181. if(t->visitingHero == o2 || t->garrisonHero == o2)
  3182. return true;
  3183. }
  3184. if(o2->ID == TOWNI_TYPE)
  3185. {
  3186. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  3187. if(t->visitingHero == o1 || t->garrisonHero == o1)
  3188. return true;
  3189. }
  3190. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  3191. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  3192. {
  3193. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  3194. //(to block moving stacks for free [without visiting] beteen heroes)
  3195. return true;
  3196. }
  3197. return false;
  3198. }
  3199. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  3200. {
  3201. obj->onHeroVisit(h);
  3202. }
  3203. bool CGameHandler::buildBoat( ui32 objid )
  3204. {
  3205. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  3206. int boatType = 1;
  3207. if(obj->state())
  3208. {
  3209. complain("Cannot build boat in this shipyard!");
  3210. return false;
  3211. }
  3212. else if(obj->o->ID == TOWNI_TYPE
  3213. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  3214. {
  3215. complain("Cannot build boat in the town - no shipyard!");
  3216. return false;
  3217. }
  3218. //TODO use "real" cost via obj->getBoatCost
  3219. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  3220. {
  3221. complain("Not enough resources to build a boat!");
  3222. return false;
  3223. }
  3224. int3 tile = obj->bestLocation();
  3225. if(!gs->map->isInTheMap(tile))
  3226. {
  3227. complain("Cannot find appropriate tile for a boat!");
  3228. return false;
  3229. }
  3230. //take boat cost
  3231. SetResources sr;
  3232. sr.player = obj->o->tempOwner;
  3233. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  3234. sr.res[0] -= 10;
  3235. sr.res[6] -= 1000;
  3236. sendAndApply(&sr);
  3237. //create boat
  3238. NewObject no;
  3239. no.ID = 8;
  3240. no.subID = obj->getBoatType();
  3241. no.pos = tile + int3(1,0,0);
  3242. sendAndApply(&no);
  3243. return true;
  3244. }
  3245. void CGameHandler::engageIntoBattle( ui8 player )
  3246. {
  3247. if(vstd::contains(states.players, player))
  3248. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  3249. //notify interfaces
  3250. PlayerBlocked pb;
  3251. pb.player = player;
  3252. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  3253. sendAndApply(&pb);
  3254. }
  3255. void CGameHandler::winLoseHandle(ui8 players )
  3256. {
  3257. for(size_t i = 0; i < PLAYER_LIMIT; i++)
  3258. {
  3259. if(players & 1<<i && gs->getPlayer(i))
  3260. {
  3261. checkLossVictory(i);
  3262. }
  3263. }
  3264. }
  3265. void CGameHandler::checkLossVictory( ui8 player )
  3266. {
  3267. const PlayerState *p = gs->getPlayer(player);
  3268. if(p->status) //player already won / lost
  3269. return;
  3270. int loss = gs->lossCheck(player);
  3271. int vic = gs->victoryCheck(player);
  3272. if(!loss && !vic)
  3273. return;
  3274. InfoWindow iw;
  3275. getLossVicMessage(player, vic ? vic : loss , vic, iw);
  3276. sendAndApply(&iw);
  3277. PlayerEndsGame peg;
  3278. peg.player = player;
  3279. peg.victory = vic;
  3280. sendAndApply(&peg);
  3281. if(vic > 0) //one player won -> all enemies lost //TODO: allies
  3282. {
  3283. iw.text.localStrings.front().second++; //message about losing because enemy won first is just after victory message
  3284. for (std::map<ui8,PlayerState>::const_iterator i = gs->players.begin(); i!=gs->players.end(); i++)
  3285. {
  3286. if(i->first < PLAYER_LIMIT && i->first != player)
  3287. {
  3288. iw.player = i->first;
  3289. sendAndApply(&iw);
  3290. peg.player = i->first;
  3291. peg.victory = false;
  3292. sendAndApply(&peg);
  3293. }
  3294. }
  3295. }
  3296. else //player lost -> all his objects become unflagged (neutral)
  3297. {
  3298. std::vector<CGHeroInstance*> hlp = p->heroes;
  3299. for (std::vector<CGHeroInstance*>::const_iterator i = hlp.begin(); i != hlp.end(); i++) //eliminate heroes
  3300. removeObject((*i)->id);
  3301. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  3302. {
  3303. if(*i && (*i)->tempOwner == player)
  3304. setOwner((**i).id,NEUTRAL_PLAYER);
  3305. }
  3306. //eliminating one player may cause victory of another:
  3307. winLoseHandle(ALL_PLAYERS & ~(1<<player));
  3308. }
  3309. if(vic)
  3310. end2 = true;
  3311. }
  3312. void CGameHandler::getLossVicMessage( ui8 player, ui8 standard, bool victory, InfoWindow &out ) const
  3313. {
  3314. const PlayerState *p = gs->getPlayer(player);
  3315. // if(!p->human)
  3316. // return; //AI doesn't need text info of loss
  3317. out.player = player;
  3318. if(victory)
  3319. {
  3320. if(standard < 0) //not std loss
  3321. {
  3322. switch(gs->map->victoryCondition.condition)
  3323. {
  3324. case artifact:
  3325. out.text.addTxt(MetaString::GENERAL_TXT, 280); //Congratulations! You have found the %s, and can claim victory!
  3326. out.text.addReplacement(MetaString::ART_NAMES,gs->map->victoryCondition.ID); //artifact name
  3327. break;
  3328. case gatherTroop:
  3329. 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!
  3330. out.text.addReplacement(gs->map->victoryCondition.count);
  3331. out.text.addReplacement(MetaString::CRE_PL_NAMES, gs->map->victoryCondition.ID);
  3332. break;
  3333. case gatherResource:
  3334. out.text.addTxt(MetaString::GENERAL_TXT, 278); //Congratulations! You have collected over %d %s in your treasury. Victory is yours!
  3335. out.text.addReplacement(gs->map->victoryCondition.count);
  3336. out.text.addReplacement(MetaString::RES_NAMES, gs->map->victoryCondition.ID);
  3337. break;
  3338. case buildCity:
  3339. out.text.addTxt(MetaString::GENERAL_TXT, 282); //Congratulations! You have successfully upgraded your town, and can claim victory!
  3340. break;
  3341. case buildGrail:
  3342. out.text.addTxt(MetaString::GENERAL_TXT, 284); //Congratulations! You have constructed a permanent home for the Grail, and can claim victory!
  3343. break;
  3344. case beatHero:
  3345. {
  3346. out.text.addTxt(MetaString::GENERAL_TXT, 252); //Congratulations! You have completed your quest to defeat the enemy hero %s. Victory is yours!
  3347. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->victoryCondition.obj);
  3348. assert(h);
  3349. out.text.addReplacement(h->name);
  3350. }
  3351. break;
  3352. case captureCity:
  3353. {
  3354. out.text.addTxt(MetaString::GENERAL_TXT, 249); //Congratulations! You captured %s, and are victorious!
  3355. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->victoryCondition.obj);
  3356. assert(t);
  3357. out.text.addReplacement(t->name);
  3358. }
  3359. break;
  3360. case beatMonster:
  3361. out.text.addTxt(MetaString::GENERAL_TXT, 286); //Congratulations! You have completed your quest to kill the fearsome beast, and can claim victory!
  3362. break;
  3363. case takeDwellings:
  3364. out.text.addTxt(MetaString::GENERAL_TXT, 288); //Congratulations! Your flag flies on the dwelling of every creature. Victory is yours!
  3365. break;
  3366. case takeMines:
  3367. out.text.addTxt(MetaString::GENERAL_TXT, 290); //Congratulations! Your flag flies on every mine. Victory is yours!
  3368. break;
  3369. case transportItem:
  3370. out.text.addTxt(MetaString::GENERAL_TXT, 292); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  3371. break;
  3372. }
  3373. }
  3374. else
  3375. {
  3376. out.text.addTxt(MetaString::GENERAL_TXT, 659); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  3377. }
  3378. }
  3379. else
  3380. {
  3381. if(standard < 0) //not std loss
  3382. {
  3383. switch(gs->map->lossCondition.typeOfLossCon)
  3384. {
  3385. case lossCastle:
  3386. {
  3387. out.text.addTxt(MetaString::GENERAL_TXT, 251); //The town of %s has fallen - all is lost!
  3388. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->lossCondition.obj);
  3389. assert(t);
  3390. out.text.addReplacement(t->name);
  3391. }
  3392. break;
  3393. case lossHero:
  3394. {
  3395. out.text.addTxt(MetaString::GENERAL_TXT, 253); //The hero, %s, has suffered defeat - your quest is over!
  3396. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->lossCondition.obj);
  3397. assert(h);
  3398. out.text.addReplacement(h->name);
  3399. }
  3400. break;
  3401. case timeExpires:
  3402. out.text.addTxt(MetaString::GENERAL_TXT, 254); //Alas, time has run out on your quest. All is lost.
  3403. break;
  3404. }
  3405. }
  3406. else if(standard == 2)
  3407. {
  3408. out.text.addTxt(MetaString::GENERAL_TXT, 7);//%s, your heroes abandon you, and you are banished from this land.
  3409. out.text.addReplacement(MetaString::COLOR, player);
  3410. out.components.push_back(Component(Component::FLAG,player,0,0));
  3411. }
  3412. else //lost all towns and heroes
  3413. {
  3414. out.text.addTxt(MetaString::GENERAL_TXT, 660); //All your forces have been defeated, and you are banished from this land!
  3415. }
  3416. }
  3417. }