CGameHandler.cpp 109 KB

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