CGameHandler.cpp 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664
  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. }
  816. void CGameHandler::run(bool resume)
  817. {
  818. BOOST_FOREACH(CConnection *cc, conns)
  819. {//init conn.
  820. ui8 quantity, pom;
  821. //ui32 seed;
  822. if(!resume)
  823. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  824. (*cc) >> quantity; //how many players will be handled at that client
  825. for(int i=0;i<quantity;i++)
  826. {
  827. (*cc) >> pom; //read player color
  828. {
  829. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  830. connections[pom] = cc;
  831. }
  832. }
  833. }
  834. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  835. {
  836. std::set<int> pom;
  837. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  838. if(j->second == *i)
  839. pom.insert(j->first);
  840. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  841. }
  842. while (!end2)
  843. {
  844. if(!resume)
  845. newTurn();
  846. else
  847. resume = false;
  848. std::map<ui8,PlayerState>::iterator i;
  849. if(!resume)
  850. i = gs->players.begin();
  851. else
  852. i = gs->players.find(gs->currentPlayer);
  853. for(; i != gs->players.end(); i++)
  854. {
  855. if(i->second.towns.size()==0 && i->second.heroes.size()==0
  856. || i->second.color<0
  857. || i->first>=PLAYER_LIMIT
  858. || i->second.status)
  859. {
  860. continue;
  861. }
  862. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  863. gs->currentPlayer = i->first;
  864. {
  865. YourTurn yt;
  866. yt.player = i->first;
  867. boost::unique_lock<boost::mutex> lock(*connections[i->first]->wmx);
  868. *connections[i->first] << &yt;
  869. }
  870. //wait till turn is done
  871. boost::unique_lock<boost::mutex> lock(states.mx);
  872. while(states.players[i->first].makingTurn && !end2)
  873. {
  874. boost::posix_time::time_duration p;
  875. p = boost::posix_time::milliseconds(200);
  876. states.cv.timed_wait(lock,p);
  877. }
  878. }
  879. }
  880. while(conns.size() && (*conns.begin())->isOpen())
  881. boost::this_thread::sleep(boost::posix_time::milliseconds(5)); //give time client to close socket
  882. }
  883. namespace CGH
  884. {
  885. using namespace std;
  886. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  887. {
  888. for(int j=0; j<7; ++j)
  889. {
  890. std::vector<int> pom;
  891. for(int g=0; g<j+1; ++g)
  892. {
  893. int hlp; input>>hlp;
  894. pom.push_back(hlp);
  895. }
  896. dest.push_back(pom);
  897. }
  898. }
  899. }
  900. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, const CCreatureSet &army1, const CCreatureSet &army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank, const CGTownInstance *town)
  901. {
  902. battleResult.set(NULL);
  903. std::vector<CStack*> & stacks = (curB->stacks);
  904. curB->tile = tile;
  905. curB->army1=army1;
  906. curB->army2=army2;
  907. curB->heroes[0] = const_cast<CGHeroInstance*>(hero1);
  908. curB->heroes[1] = const_cast<CGHeroInstance*>(hero2);
  909. curB->round = -2;
  910. curB->activeStack = -1;
  911. if(town)
  912. {
  913. curB->tid = town->id;
  914. curB->siege = town->fortLevel();
  915. }
  916. else
  917. {
  918. curB->tid = -1;
  919. curB->siege = 0;
  920. }
  921. //reading battleStartpos
  922. std::ifstream positions;
  923. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  924. if(!positions.is_open())
  925. {
  926. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  927. }
  928. std::string dump;
  929. positions>>dump; positions>>dump;
  930. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  931. CGH::readItTo(positions, attackerLoose);
  932. positions>>dump;
  933. CGH::readItTo(positions, defenderLoose);
  934. positions>>dump;
  935. positions>>dump;
  936. CGH::readItTo(positions, attackerTight);
  937. positions>>dump;
  938. CGH::readItTo(positions, defenderTight);
  939. positions>>dump;
  940. positions>>dump;
  941. CGH::readItTo(positions, attackerCreBank);
  942. positions>>dump;
  943. CGH::readItTo(positions, defenderCreBank);
  944. positions.close();
  945. //battleStartpos read
  946. int k = 0; //stack serial
  947. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army1.slots.begin(); i!=army1.slots.end(); i++, k++)
  948. {
  949. int pos;
  950. if(creatureBank)
  951. pos = attackerCreBank[army1.slots.size()-1][k];
  952. else if(army1.formation)
  953. pos = attackerTight[army1.slots.size()-1][k];
  954. else
  955. pos = attackerLoose[army1.slots.size()-1][k];
  956. 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);
  957. stacks.push_back(stack);
  958. }
  959. k = 0;
  960. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army2.slots.begin(); i!=army2.slots.end(); i++, k++)
  961. {
  962. int pos;
  963. if(creatureBank)
  964. pos = defenderCreBank[army2.slots.size()-1][k];
  965. else if(army2.formation)
  966. pos = defenderTight[army2.slots.size()-1][k];
  967. else
  968. pos = defenderLoose[army2.slots.size()-1][k];
  969. 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);
  970. stacks.push_back(stack);
  971. }
  972. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  973. {
  974. if((stacks[g]->position%17)==1 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned)
  975. {
  976. stacks[g]->position += 1;
  977. }
  978. else if((stacks[g]->position%17)==15 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned)
  979. {
  980. stacks[g]->position -= 1;
  981. }
  982. }
  983. //adding war machines
  984. if(hero1)
  985. {
  986. if(hero1->getArt(13)) //ballista
  987. {
  988. CStack * stack = curB->generateNewStack(hero1, 146, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 52);
  989. stacks.push_back(stack);
  990. }
  991. if(hero1->getArt(14)) //ammo cart
  992. {
  993. CStack * stack = curB->generateNewStack(hero1, 148, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 18);
  994. stacks.push_back(stack);
  995. }
  996. if(hero1->getArt(15)) //first aid tent
  997. {
  998. CStack * stack = curB->generateNewStack(hero1, 147, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 154);
  999. stacks.push_back(stack);
  1000. }
  1001. }
  1002. if(hero2)
  1003. {
  1004. if(hero2->getArt(13)) //ballista
  1005. {
  1006. CStack * stack = curB->generateNewStack(hero2, 146, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 66);
  1007. stacks.push_back(stack);
  1008. }
  1009. if(hero2->getArt(14)) //ammo cart
  1010. {
  1011. CStack * stack = curB->generateNewStack(hero2, 148, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 32);
  1012. stacks.push_back(stack);
  1013. }
  1014. if(hero2->getArt(15)) //first aid tent
  1015. {
  1016. CStack * stack = curB->generateNewStack(hero2, 147, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 168);
  1017. stacks.push_back(stack);
  1018. }
  1019. }
  1020. if(town && hero1 && town->hasFort()) //catapult
  1021. {
  1022. CStack * stack = curB->generateNewStack(hero1, 145, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 120);
  1023. stacks.push_back(stack);
  1024. }
  1025. //war machines added
  1026. switch(curB->siege) //adding towers
  1027. {
  1028. case 3: //castle
  1029. {//lower tower / upper tower
  1030. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -4);
  1031. stacks.push_back(stack);
  1032. stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -3);
  1033. stacks.push_back(stack);
  1034. }
  1035. case 2: //citadel
  1036. {//main tower
  1037. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -2);
  1038. stacks.push_back(stack);
  1039. }
  1040. }
  1041. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1042. //seting up siege
  1043. if(town && town->hasFort())
  1044. {
  1045. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1046. {
  1047. curB->si.wallState[b] = 1;
  1048. }
  1049. }
  1050. int terType = gs->battleGetBattlefieldType(tile);
  1051. //randomize obstacles
  1052. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1053. {
  1054. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1055. std::vector<int> possibleObstacles;
  1056. for(int i=0; i<BFIELD_SIZE; ++i)
  1057. {
  1058. if(i%17 < 4 || i%17 > 12)
  1059. {
  1060. obAv[i] = false;
  1061. }
  1062. else
  1063. {
  1064. obAv[i] = true;
  1065. }
  1066. }
  1067. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1068. {
  1069. 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
  1070. {
  1071. possibleObstacles.push_back(g->first);
  1072. }
  1073. }
  1074. srand(time(NULL));
  1075. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1076. {
  1077. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1078. while(toBlock>0)
  1079. {
  1080. CObstacleInstance coi;
  1081. coi.uniqueID = curB->obstacles.size();
  1082. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1083. coi.pos = rand()%BFIELD_SIZE;
  1084. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1085. bool badObstacle = false;
  1086. for(int b=0; b<block.size(); ++b)
  1087. {
  1088. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1089. {
  1090. badObstacle = true;
  1091. break;
  1092. }
  1093. }
  1094. if(badObstacle) continue;
  1095. //obstacle can be placed
  1096. curB->obstacles.push_back(coi);
  1097. for(int b=0; b<block.size(); ++b)
  1098. {
  1099. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1100. obAv[block[b]] = false;
  1101. }
  1102. toBlock -= block.size();
  1103. }
  1104. }
  1105. }
  1106. //giving terrain premies for heroes & stacks
  1107. int bonusSubtype = -1;
  1108. switch(terType)
  1109. {
  1110. case 9: //magic plains
  1111. {
  1112. bonusSubtype = 0;
  1113. }
  1114. case 14: //fiery fields
  1115. {
  1116. if(bonusSubtype == -1) bonusSubtype = 1;
  1117. }
  1118. case 15: //rock lands
  1119. {
  1120. if(bonusSubtype == -1) bonusSubtype = 8;
  1121. }
  1122. case 16: //magic clouds
  1123. {
  1124. if(bonusSubtype == -1) bonusSubtype = 2;
  1125. }
  1126. case 17: //lucid pools
  1127. {
  1128. if(bonusSubtype == -1) bonusSubtype = 4;
  1129. }
  1130. { //common part for cases 9, 14, 15, 16, 17
  1131. const CGHeroInstance * cHero = NULL;
  1132. for(int i=0; i<2; ++i)
  1133. {
  1134. if(i == 0) cHero = hero1;
  1135. else cHero = hero2;
  1136. if(cHero == NULL) continue;
  1137. GiveBonus gs;
  1138. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::MAGIC_SCHOOL_SKILL, HeroBonus::OBJECT, 3, -1, "", bonusSubtype);
  1139. gs.hid = cHero->id;
  1140. sendAndApply(&gs);
  1141. }
  1142. break;
  1143. }
  1144. case 18: //holy ground
  1145. {
  1146. for(int g=0; g<stacks.size(); ++g) //+1 morale bonus for good creatures, -1 morale bonus for evil creatures
  1147. {
  1148. if (stacks[g]->creature->isGood())
  1149. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1150. else if (stacks[g]->creature->isEvil())
  1151. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1152. }
  1153. break;
  1154. }
  1155. case 19: //clover field
  1156. {
  1157. for(int g=0; g<stacks.size(); ++g)
  1158. {
  1159. if(stacks[g]->creature->faction == -1) //+2 luck bonus for neutral creatures
  1160. {
  1161. stacks[g]->features.push_back(makeFeature(StackFeature::LUCK_BONUS, StackFeature::WHOLE_BATTLE, 0, 2, StackFeature::OTHER_SOURCE));
  1162. }
  1163. }
  1164. break;
  1165. }
  1166. case 20: //evil fog
  1167. {
  1168. for(int g=0; g<stacks.size(); ++g) //-1 morale bonus for good creatures, +1 morale bonus for evil creatures
  1169. {
  1170. if (stacks[g]->creature->isGood())
  1171. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1172. else if (stacks[g]->creature->isEvil())
  1173. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1174. }
  1175. break;
  1176. }
  1177. case 22: //cursed ground
  1178. {
  1179. for(int g=0; g<stacks.size(); ++g) //no luck nor morale
  1180. {
  1181. stacks[g]->features.push_back(makeFeature(StackFeature::NO_MORALE, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1182. stacks[g]->features.push_back(makeFeature(StackFeature::NO_LUCK, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1183. }
  1184. const CGHeroInstance * cHero = NULL;
  1185. for(int i=0; i<2; ++i) //blocking spells above level 1
  1186. {
  1187. if(i == 0) cHero = hero1;
  1188. else cHero = hero2;
  1189. if(cHero == NULL) continue;
  1190. GiveBonus gs;
  1191. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL, HeroBonus::OBJECT, 1, -1, "", bonusSubtype);
  1192. gs.hid = cHero->id;
  1193. sendAndApply(&gs);
  1194. }
  1195. break;
  1196. }
  1197. }
  1198. //premies given
  1199. //send info about battles
  1200. BattleStart bs;
  1201. bs.info = curB;
  1202. sendAndApply(&bs);
  1203. }
  1204. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1205. {
  1206. //checking winning condition
  1207. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1208. hasStack[0] = hasStack[1] = false;
  1209. for(int b = 0; b<stacks.size(); ++b)
  1210. {
  1211. if(stacks[b]->alive() && !stacks[b]->hasFeatureOfType(StackFeature::SIEGE_WEAPON))
  1212. {
  1213. hasStack[1-stacks[b]->attackerOwned] = true;
  1214. }
  1215. }
  1216. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1217. {
  1218. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1219. br->result = 0;
  1220. br->winner = hasStack[1]; //fleeing side loses
  1221. gs->curB->calculateCasualties(br->casualties);
  1222. battleResult.set(br);
  1223. }
  1224. }
  1225. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1226. {
  1227. if(!vstd::contains(h->artifWorn,17))
  1228. return; //hero hasn't spellbok
  1229. ChangeSpells cs;
  1230. cs.hid = h->id;
  1231. cs.learn = true;
  1232. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  1233. {
  1234. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1235. {
  1236. if(!vstd::contains(h->spells,t->spells[i][j]))
  1237. cs.spells.insert(t->spells[i][j]);
  1238. }
  1239. }
  1240. if(cs.spells.size())
  1241. sendAndApply(&cs);
  1242. }
  1243. void CGameHandler::setBlockVis(int objid, bool bv)
  1244. {
  1245. SetObjectProperty sop(objid,2,bv);
  1246. sendAndApply(&sop);
  1247. }
  1248. bool CGameHandler::removeObject( int objid )
  1249. {
  1250. if(!getObj(objid))
  1251. {
  1252. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1253. return false;
  1254. }
  1255. RemoveObject ro;
  1256. ro.id = objid;
  1257. sendAndApply(&ro);
  1258. winLoseHandle(255); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1259. return true;
  1260. }
  1261. void CGameHandler::setAmount(int objid, ui32 val)
  1262. {
  1263. SetObjectProperty sop(objid,3,val);
  1264. sendAndApply(&sop);
  1265. }
  1266. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1267. {
  1268. bool blockvis = false;
  1269. const CGHeroInstance *h = getHero(hid);
  1270. 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)
  1271. )
  1272. {
  1273. tlog1 << "Illegal call to move hero!\n";
  1274. return false;
  1275. }
  1276. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1277. int3 hmpos = dst + int3(-1,0,0);
  1278. if(!gs->map->isInTheMap(hmpos))
  1279. {
  1280. tlog1 << "Destination tile os out of the map!\n";
  1281. return false;
  1282. }
  1283. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1284. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1285. //result structure for start - movement failed, no move points used
  1286. TryMoveHero tmh;
  1287. tmh.id = hid;
  1288. tmh.start = h->pos;
  1289. tmh.end = dst;
  1290. tmh.result = TryMoveHero::FAILED;
  1291. tmh.movePoints = h->movement;
  1292. //check if destination tile is available
  1293. //it's a rock or blocked and not visitable tile
  1294. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1295. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable))
  1296. && complain("Cannot move hero, destination tile is blocked!")
  1297. || (!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)
  1298. && complain("Cannot move hero, destination tile is on water!")
  1299. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1300. && complain("Cannot disembark hero, tile is blocked!")
  1301. || (h->movement < cost && dst != h->pos)
  1302. && complain("Hero don't have any movement points left!")
  1303. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1304. && complain("Cannot move hero during the battle"))
  1305. {
  1306. //send info about movement failure
  1307. sendAndApply(&tmh);
  1308. return false;
  1309. }
  1310. //hero enters the boat
  1311. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1312. {
  1313. tmh.result = TryMoveHero::EMBARK;
  1314. tmh.movePoints = 0; //embarking takes all move points
  1315. //TODO: check for bonus that removes that penalty
  1316. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1317. sendAndApply(&tmh);
  1318. return true;
  1319. }
  1320. //hero leaves the boat
  1321. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1322. {
  1323. tmh.result = TryMoveHero::DISEMBARK;
  1324. tmh.movePoints = 0; //disembarking takes all move points
  1325. //TODO: check for bonus that removes that penalty
  1326. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1327. sendAndApply(&tmh);
  1328. return true;
  1329. }
  1330. //checks for standard movement
  1331. if(!instant)
  1332. {
  1333. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighbouring!")
  1334. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1335. {
  1336. sendAndApply(&tmh);
  1337. return false;
  1338. }
  1339. //check if there is blocking visitable object
  1340. blockvis = false;
  1341. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1342. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1343. {
  1344. if(obj != h && obj->blockVisit && !(obj->getPassableness() & 1<<h->tempOwner))
  1345. {
  1346. blockvis = true;
  1347. break;
  1348. }
  1349. }
  1350. //we start moving
  1351. if(blockvis)//interaction with blocking object (like resources)
  1352. {
  1353. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1354. sendAndApply(&tmh);
  1355. //failed to move to that tile but we visit object
  1356. if(t.visitableObjects.size())
  1357. objectVisited(t.visitableObjects.back(), h);
  1358. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1359. // {
  1360. // if (obj->blockVisit)
  1361. // {
  1362. // objectVisited(obj, h);
  1363. // }
  1364. // }
  1365. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1366. return true;
  1367. }
  1368. else //normal move
  1369. {
  1370. tmh.result = TryMoveHero::SUCCESS;
  1371. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1372. {
  1373. obj->onHeroLeave(h);
  1374. }
  1375. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1376. sendAndApply(&tmh);
  1377. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1378. //call objects if they are visited
  1379. if(t.visitableObjects.size())
  1380. objectVisited(t.visitableObjects.back(), h);
  1381. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1382. // {
  1383. // objectVisited(obj, h);
  1384. // }
  1385. }
  1386. tlog5 << "Movement end!\n";
  1387. return true;
  1388. }
  1389. else //instant move - teleportation
  1390. {
  1391. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1392. {
  1393. if(obj->ID==HEROI_TYPE)
  1394. {
  1395. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1396. if(obj->tempOwner==h->tempOwner)
  1397. {
  1398. heroExchange(dh->id, h->id);
  1399. return true;
  1400. }
  1401. //TODO: check for ally
  1402. startBattleI(h, dh);
  1403. return true;
  1404. }
  1405. }
  1406. tmh.result = TryMoveHero::TELEPORTATION;
  1407. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1408. sendAndApply(&tmh);
  1409. return true;
  1410. }
  1411. }
  1412. void CGameHandler::setOwner(int objid, ui8 owner)
  1413. {
  1414. SetObjectProperty sop(objid,1,owner);
  1415. sendAndApply(&sop);
  1416. winLoseHandle(1<<owner);
  1417. }
  1418. void CGameHandler::setHoverName(int objid, MetaString* name)
  1419. {
  1420. SetHoverName shn(objid, *name);
  1421. sendAndApply(&shn);
  1422. }
  1423. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1424. {
  1425. sendToAllClients(iw);
  1426. }
  1427. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1428. {
  1429. ask(iw,iw->player,callback);
  1430. }
  1431. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1432. {
  1433. //TODO
  1434. //gsm.lock();
  1435. //int query = QID++;
  1436. //states.addQuery(player,query);
  1437. //sendToAllClients(iw);
  1438. //gsm.unlock();
  1439. //ui32 ret = getQueryResult(iw->player, query);
  1440. //gsm.lock();
  1441. //states.removeQuery(player, query);
  1442. //gsm.unlock();
  1443. return 0;
  1444. }
  1445. int CGameHandler::getCurrentPlayer()
  1446. {
  1447. return gs->currentPlayer;
  1448. }
  1449. void CGameHandler::giveResource(int player, int which, int val)
  1450. {
  1451. if(!val) return; //don't waste time on empty call
  1452. SetResource sr;
  1453. sr.player = player;
  1454. sr.resid = which;
  1455. sr.val = gs->players.find(player)->second.resources[which]+val;
  1456. sendAndApply(&sr);
  1457. }
  1458. void CGameHandler::giveCreatures (int objid, const CGHeroInstance * h, CCreatureSet creatures)
  1459. {
  1460. if (creatures.slots.size() <= 0)
  1461. return;
  1462. CCreatureSet heroArmy = h->army;
  1463. while (creatures.slots.size() > 0)
  1464. {
  1465. int slot = heroArmy.getSlotFor (creatures.slots.begin()->second.first);
  1466. if (slot < 0)
  1467. break;
  1468. heroArmy.slots[slot].first = creatures.slots.begin()->second.first;
  1469. heroArmy.slots[slot].second += creatures.slots.begin()->second.second;
  1470. creatures.slots.erase (creatures.slots.begin());
  1471. }
  1472. if (creatures.slots.size() == 0) //all creatures can be moved to hero army - do that
  1473. {
  1474. SetGarrisons sg;
  1475. sg.garrs[h->id] = heroArmy;
  1476. sendAndApply(&sg);
  1477. }
  1478. else //show garrison window and let player pick creatures
  1479. {
  1480. SetGarrisons sg;
  1481. sg.garrs[objid] = creatures;
  1482. sendAndApply (&sg);
  1483. showGarrisonDialog (objid, h->id, true, 0);
  1484. return;
  1485. }
  1486. }
  1487. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1488. {
  1489. sendToAllClients(comp);
  1490. }
  1491. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1492. {
  1493. HeroVisitCastle vc;
  1494. vc.hid = heroID;
  1495. vc.tid = obj;
  1496. vc.flags |= 1;
  1497. sendAndApply(&vc);
  1498. const CGHeroInstance *h = getHero(heroID);
  1499. vistiCastleObjects (getTown(obj), h);
  1500. giveSpells (getTown(obj), getHero(heroID));
  1501. if(gs->map->victoryCondition.condition == transportItem)
  1502. checkLossVictory(h->tempOwner); //transported artifact?
  1503. }
  1504. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1505. {
  1506. std::vector<CGTownBuilding*>::const_iterator i;
  1507. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1508. (*i)->onHeroVisit (h);
  1509. }
  1510. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1511. {
  1512. HeroVisitCastle vc;
  1513. vc.hid = heroID;
  1514. vc.tid = obj;
  1515. sendAndApply(&vc);
  1516. }
  1517. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1518. {
  1519. const CGHeroInstance* h = getHero(hid);
  1520. const CArtifact &art = VLC->arth->artifacts[artid];
  1521. SetHeroArtifacts sha;
  1522. sha.hid = hid;
  1523. sha.artifacts = h->artifacts;
  1524. sha.artifWorn = h->artifWorn;
  1525. if(position<0)
  1526. {
  1527. if(position == -2)
  1528. {
  1529. int i;
  1530. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1531. {
  1532. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1533. {
  1534. //we've found a free suitable slot
  1535. sha.artifWorn[art.possibleSlots[i]] = artid;
  1536. break;
  1537. }
  1538. }
  1539. if(i == art.possibleSlots.size() && !art.isBig()) //if haven't find proper slot, use backpack or discard big artifact
  1540. sha.artifacts.push_back(artid);
  1541. }
  1542. else if (!art.isBig()) //should be -1 => put artifact into backpack
  1543. {
  1544. sha.artifacts.push_back(artid);
  1545. }
  1546. }
  1547. else
  1548. {
  1549. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1550. {
  1551. sha.artifWorn[position] = artid;
  1552. }
  1553. else if (!art.isBig())
  1554. {
  1555. sha.artifacts.push_back(artid);
  1556. }
  1557. }
  1558. sendAndApply(&sha);
  1559. }
  1560. 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
  1561. {
  1562. engageIntoBattle(army1->tempOwner);
  1563. engageIntoBattle(army2->tempOwner);
  1564. //block engaged players
  1565. if(army2->tempOwner < PLAYER_LIMIT)
  1566. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1567. boost::thread(boost::bind(&CGameHandler::startBattle, this, army1, army2, tile, hero1, hero2, creatureBank, cb, town));
  1568. }
  1569. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  1570. {
  1571. startBattleI(army1, army2, tile,
  1572. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  1573. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  1574. creatureBank, cb);
  1575. }
  1576. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  1577. {
  1578. startBattleI(army1, army2, army2->pos - army2->getVisitableOffset(), cb, creatureBank);
  1579. }
  1580. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1581. //{
  1582. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1583. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  1584. // //battle(&h->army,army,tile,h,NULL);
  1585. //}
  1586. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1587. {
  1588. ChangeSpells cs;
  1589. cs.hid = hid;
  1590. cs.spells = spells;
  1591. cs.learn = give;
  1592. sendAndApply(&cs);
  1593. }
  1594. int CGameHandler::getSelectedHero()
  1595. {
  1596. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1597. }
  1598. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  1599. {
  1600. SetObjectProperty sob;
  1601. sob.id = objid;
  1602. sob.what = prop;
  1603. sob.val = val;
  1604. sendAndApply(&sob);
  1605. }
  1606. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1607. {
  1608. SystemMessage sm;
  1609. sm.text = message;
  1610. c << &sm;
  1611. }
  1612. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1613. {
  1614. sendAndApply(bonus);
  1615. }
  1616. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1617. {
  1618. sendAndApply(smp);
  1619. }
  1620. void CGameHandler::setManaPoints( int hid, int val )
  1621. {
  1622. SetMana sm;
  1623. sm.hid = hid;
  1624. sm.val = val;
  1625. sendAndApply(&sm);
  1626. }
  1627. void CGameHandler::giveHero( int id, int player )
  1628. {
  1629. GiveHero gh;
  1630. gh.id = id;
  1631. gh.player = player;
  1632. sendAndApply(&gh);
  1633. }
  1634. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1635. {
  1636. ChangeObjPos cop;
  1637. cop.objid = objid;
  1638. cop.nPos = newPos;
  1639. cop.flags = flags;
  1640. sendAndApply(&cop);
  1641. }
  1642. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  1643. {
  1644. ui8 player1 = getHero(hero1)->tempOwner;
  1645. ui8 player2 = getHero(hero2)->tempOwner;
  1646. if(player1 == player2)
  1647. {
  1648. OpenWindow hex;
  1649. hex.window = OpenWindow::EXCHANGE_WINDOW;
  1650. hex.id1 = hero1;
  1651. hex.id2 = hero2;
  1652. sendAndApply(&hex);
  1653. }
  1654. }
  1655. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1656. {
  1657. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1658. sel->id = QID;
  1659. callbacks[QID] = callback;
  1660. states.addQuery(player,QID);
  1661. QID++;
  1662. sendAndApply(sel);
  1663. }
  1664. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1665. {
  1666. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1667. sel->id = QID;
  1668. callbacks[QID] = callback;
  1669. states.addQuery(player,QID);
  1670. sendToAllClients(sel);
  1671. QID++;
  1672. }
  1673. void CGameHandler::sendToAllClients( CPackForClient * info )
  1674. {
  1675. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1676. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1677. {
  1678. (*i)->wmx->lock();
  1679. **i << info;
  1680. (*i)->wmx->unlock();
  1681. }
  1682. }
  1683. void CGameHandler::sendAndApply( CPackForClient * info )
  1684. {
  1685. gs->apply(info);
  1686. sendToAllClients(info);
  1687. }
  1688. void CGameHandler::sendAndApply( SetGarrisons * info )
  1689. {
  1690. sendAndApply((CPackForClient*)info);
  1691. if(gs->map->victoryCondition.condition == gatherTroop)
  1692. for(std::map<ui32,CCreatureSet>::const_iterator i = info->garrs.begin(); i != info->garrs.end(); i++)
  1693. checkLossVictory(getObj(i->first)->tempOwner);
  1694. }
  1695. void CGameHandler::sendAndApply( SetResource * info )
  1696. {
  1697. sendAndApply((CPackForClient*)info);
  1698. if(gs->map->victoryCondition.condition == gatherResource)
  1699. checkLossVictory(info->player);
  1700. }
  1701. void CGameHandler::sendAndApply( SetResources * info )
  1702. {
  1703. sendAndApply((CPackForClient*)info);
  1704. if(gs->map->victoryCondition.condition == gatherResource)
  1705. checkLossVictory(info->player);
  1706. }
  1707. void CGameHandler::sendAndApply( NewStructures * info )
  1708. {
  1709. sendAndApply((CPackForClient*)info);
  1710. if(gs->map->victoryCondition.condition == buildCity)
  1711. checkLossVictory(getTown(info->tid)->tempOwner);
  1712. }
  1713. void CGameHandler::save( const std::string &fname )
  1714. {
  1715. {
  1716. tlog0 << "Ordering clients to serialize...\n";
  1717. SaveGame sg(fname);
  1718. sendToAllClients(&sg);
  1719. }
  1720. {
  1721. tlog0 << "Serializing game info...\n";
  1722. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vlgm1");
  1723. char hlp[8] = "VCMISVG";
  1724. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  1725. }
  1726. {
  1727. tlog0 << "Serializing server info...\n";
  1728. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vsgm1");
  1729. save << *this;
  1730. }
  1731. tlog0 << "Game has been successfully saved!\n";
  1732. }
  1733. void CGameHandler::close()
  1734. {
  1735. tlog0 << "We have been requested to close.\n";
  1736. //BOOST_FOREACH(CConnection *cc, conns)
  1737. // if(cc && cc->socket && cc->socket->is_open())
  1738. // cc->socket->close();
  1739. //exit(0);
  1740. }
  1741. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val )
  1742. {
  1743. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  1744. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  1745. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  1746. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  1747. if(!isAllowedExchange(id1,id2))
  1748. {
  1749. complain("Cannot exchange stacks between these two objects!\n");
  1750. return false;
  1751. }
  1752. if(what==1) //swap
  1753. {
  1754. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  1755. //if one of them is empty, remove entry
  1756. if(!S1.slots[p1].second)
  1757. S1.slots.erase(p1);
  1758. if(!S2.slots[p2].second)
  1759. S2.slots.erase(p2);
  1760. }
  1761. else if(what==2)//merge
  1762. {
  1763. if(S1.slots[p1].first != S2.slots[p2].first) //not same creature
  1764. {
  1765. complain("Cannot merge different creatures stacks!");
  1766. return false;
  1767. }
  1768. S2.slots[p2].second += S1.slots[p1].second;
  1769. S1.slots.erase(p1);
  1770. }
  1771. else if(what==3) //split
  1772. {
  1773. //general conditions checking
  1774. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1775. || (val<1 && complain("no creatures to split")) )
  1776. {
  1777. return false;
  1778. }
  1779. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1780. {
  1781. int total = S1.slots[p1].second + S2.slots[p2].second;
  1782. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1783. || (S2.slots[p2].first != S1.slots[p1].first && complain("Cannot rebalance different creatures stacks!"))
  1784. )
  1785. {
  1786. return false;
  1787. }
  1788. S2.slots[p2].second = val;
  1789. S1.slots[p1].second = total - val;
  1790. }
  1791. else //split one stack to the two
  1792. {
  1793. if(S1.slots[p1].second < val)//not enough creatures
  1794. {
  1795. complain("Cannot split that stack, not enough creatures!");
  1796. return false;
  1797. }
  1798. S2.slots[p2].first = S1.slots[p1].first;
  1799. S2.slots[p2].second = val;
  1800. S1.slots[p1].second -= val;
  1801. }
  1802. if(!S1.slots[p1].second) //if we've moved all creatures
  1803. S1.slots.erase(p1);
  1804. }
  1805. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  1806. || (s2->needsLastStack() && !S2.slots.size())
  1807. )
  1808. {
  1809. complain("Cannot take the last stack!");
  1810. return false; //leave without applying changes to garrison
  1811. }
  1812. //apply changes
  1813. SetGarrisons sg;
  1814. sg.garrs[id1] = S1;
  1815. if(s1 != s2)
  1816. sg.garrs[id2] = S2;
  1817. sendAndApply(&sg);
  1818. return true;
  1819. }
  1820. int CGameHandler::getPlayerAt( CConnection *c ) const
  1821. {
  1822. std::set<int> all;
  1823. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1824. if(i->second == c)
  1825. all.insert(i->first);
  1826. switch(all.size())
  1827. {
  1828. case 0:
  1829. return 255;
  1830. case 1:
  1831. return *all.begin();
  1832. default:
  1833. {
  1834. //if we have more than one player at this connection, try to pick active one
  1835. if(vstd::contains(all,int(gs->currentPlayer)))
  1836. return gs->currentPlayer;
  1837. else
  1838. return 253; //cannot say which player is it
  1839. }
  1840. }
  1841. }
  1842. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  1843. {
  1844. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  1845. if(!vstd::contains(s1->army.slots,pos))
  1846. {
  1847. complain("Illegal call to disbandCreature - no such stack in army!");
  1848. return false;
  1849. }
  1850. s1->army.slots.erase(pos);
  1851. SetGarrisons sg;
  1852. sg.garrs[id] = s1->army;
  1853. sendAndApply(&sg);
  1854. return true;
  1855. }
  1856. bool CGameHandler::buildStructure( si32 tid, si32 bid )
  1857. {
  1858. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1859. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  1860. if(gs->canBuildStructure(t,bid) != 7)
  1861. {
  1862. complain("Cannot raze that building!");
  1863. return false;
  1864. }
  1865. NewStructures ns;
  1866. ns.tid = tid;
  1867. if ( (bid == 18) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[0]+37))) )
  1868. ns.bid.insert(19);//we have upgr. dwelling, upgr. horde will be builded as well
  1869. else if ( (bid == 24) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[1]+37))) )
  1870. ns.bid.insert(25);
  1871. else if(bid>36) //upg dwelling
  1872. {
  1873. if ( (bid-37 == t->town->hordeLvl[0]) && (vstd::contains(t->builtBuildings,18)) )
  1874. ns.bid.insert(19);//we have horde, will be upgraded as well as dwelling
  1875. if ( (bid-37 == t->town->hordeLvl[1]) && (vstd::contains(t->builtBuildings,24)) )
  1876. ns.bid.insert(25);
  1877. SetAvailableCreatures ssi;
  1878. ssi.tid = tid;
  1879. ssi.creatures = t->creatures;
  1880. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  1881. sendAndApply(&ssi);
  1882. }
  1883. else if(bid >= 30) //bas. dwelling
  1884. {
  1885. int crid = t->town->basicCreatures[bid-30];
  1886. SetAvailableCreatures ssi;
  1887. ssi.tid = tid;
  1888. ssi.creatures = t->creatures;
  1889. ssi.creatures[bid-30].first = VLC->creh->creatures[crid].growth;
  1890. ssi.creatures[bid-30].second.push_back(crid);
  1891. sendAndApply(&ssi);
  1892. }
  1893. else if(bid == 11)
  1894. ns.bid.insert(27);
  1895. else if(bid == 12)
  1896. ns.bid.insert(28);
  1897. else if(bid == 13)
  1898. ns.bid.insert(29);
  1899. ns.bid.insert(bid);
  1900. ns.builded = t->builded + 1;
  1901. sendAndApply(&ns);
  1902. //reveal ground for lookout tower
  1903. FoWChange fw;
  1904. fw.player = t->tempOwner;
  1905. fw.mode = 1;
  1906. getTilesInRange(fw.tiles,t->pos,t->getSightRadious(),t->tempOwner,1);
  1907. sendAndApply(&fw);
  1908. SetResources sr;
  1909. sr.player = t->tempOwner;
  1910. sr.res = gs->getPlayer(t->tempOwner)->resources;
  1911. for(int i=0;i<b->resources.size();i++)
  1912. sr.res[i]-=b->resources[i];
  1913. sendAndApply(&sr);
  1914. if(bid<5) //it's mage guild
  1915. {
  1916. if(t->visitingHero)
  1917. giveSpells(t,t->visitingHero);
  1918. if(t->garrisonHero)
  1919. giveSpells(t,t->garrisonHero);
  1920. }
  1921. if(t->visitingHero)
  1922. vistiCastleObjects (t, t->visitingHero);
  1923. if(t->garrisonHero)
  1924. vistiCastleObjects (t, t->garrisonHero);
  1925. return true;
  1926. }
  1927. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  1928. {
  1929. ///incomplete, simply erases target building
  1930. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1931. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  1932. return false;
  1933. RazeStructures rs;
  1934. rs.tid = tid;
  1935. rs.bid.insert(bid);
  1936. rs.destroyed = t->destroyed + 1;
  1937. sendAndApply(&rs);
  1938. return true;
  1939. }
  1940. void CGameHandler::sendMessageToAll( const std::string &message )
  1941. {
  1942. SystemMessage sm;
  1943. sm.text = message;
  1944. sendToAllClients(&sm);
  1945. }
  1946. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  1947. {
  1948. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid]);
  1949. const CArmedInstance *dst = NULL;
  1950. if(dw->ID == TOWNI_TYPE)
  1951. dst = dw;
  1952. else if(dw->ID == 17 || dw->ID == 20) //advmap dwelling
  1953. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  1954. assert(dw && dst);
  1955. //verify
  1956. bool found = false;
  1957. int level = -1;
  1958. typedef std::pair<const int,int> Parka;
  1959. for(level = 0; level < dw->creatures.size(); level++) //iterate through all levels
  1960. {
  1961. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  1962. int i = 0;
  1963. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  1964. if(cur.second[i] == crid)
  1965. break;
  1966. if(i < cur.second.size())
  1967. {
  1968. found = true;
  1969. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  1970. break;
  1971. }
  1972. }
  1973. int slot = dst->army.getSlotFor(crid);
  1974. if(!found && complain("Cannot recruit: no such creatures!")
  1975. || cram > VLC->creh->creatures[crid].maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  1976. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  1977. || slot<0 && complain("Cannot recruit: no available slot!"))
  1978. {
  1979. return false;
  1980. }
  1981. //recruit
  1982. SetResources sr;
  1983. sr.player = dst->tempOwner;
  1984. for(int i=0;i<RESOURCE_QUANTITY;i++)
  1985. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  1986. SetAvailableCreatures sac;
  1987. sac.tid = objid;
  1988. sac.creatures = dw->creatures;
  1989. sac.creatures[level].first -= cram;
  1990. SetGarrisons sg;
  1991. sg.garrs[dst->id] = dst->army;
  1992. if(sg.garrs[dst->id].slots.find(slot) == sg.garrs[dst->id].slots.end()) //take a free slot
  1993. {
  1994. sg.garrs[dst->id].slots[slot] = std::make_pair(crid,cram);
  1995. }
  1996. else //add creatures to a already existing stack
  1997. {
  1998. sg.garrs[dst->id].slots[slot].second += cram;
  1999. }
  2000. sendAndApply(&sr);
  2001. sendAndApply(&sac);
  2002. sendAndApply(&sg);
  2003. return true;
  2004. }
  2005. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  2006. {
  2007. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  2008. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  2009. int player = obj->tempOwner;
  2010. int crQuantity = obj->army.slots[pos].second;
  2011. //check if upgrade is possible
  2012. if((ui.oldID<0 || !vstd::contains(ui.newID,upgID)) && complain("That upgrade is not possible!"))
  2013. {
  2014. return false;
  2015. }
  2016. //check if player has enough resources
  2017. for(int i=0;i<ui.cost.size();i++)
  2018. {
  2019. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2020. {
  2021. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  2022. {
  2023. complain("Cannot upgrade, not enough resources!");
  2024. return false;
  2025. }
  2026. }
  2027. }
  2028. //take resources
  2029. for(int i=0;i<ui.cost.size();i++)
  2030. {
  2031. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2032. {
  2033. SetResource sr;
  2034. sr.player = player;
  2035. sr.resid = j->first;
  2036. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  2037. sendAndApply(&sr);
  2038. }
  2039. }
  2040. //upgrade creature
  2041. SetGarrisons sg;
  2042. sg.garrs[objid] = obj->army;
  2043. sg.garrs[objid].slots[pos].first = upgID;
  2044. sendAndApply(&sg);
  2045. return true;
  2046. }
  2047. bool CGameHandler::garrisonSwap( si32 tid )
  2048. {
  2049. CGTownInstance *town = gs->getTown(tid);
  2050. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2051. {
  2052. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  2053. while(!cso.slots.empty())//while there are unmoved creatures
  2054. {
  2055. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  2056. if(pos<0)
  2057. {
  2058. //try to merge two other stacks to make place
  2059. std::pair<TSlot, TSlot> toMerge;
  2060. if(csn.mergableStacks(toMerge, cso.slots.begin()->first))
  2061. {
  2062. //merge
  2063. csn.slots[toMerge.second].second += csn.slots[toMerge.first].second;
  2064. csn.slots[toMerge.first] = cso.slots.begin()->second;
  2065. }
  2066. else
  2067. {
  2068. complain("Cannot make garrison swap, not enough free slots!");
  2069. return false;
  2070. }
  2071. }
  2072. else if(csn.slots.find(pos) != csn.slots.end()) //add creatures to the existing stack
  2073. {
  2074. csn.slots[pos].second += cso.slots.begin()->second.second;
  2075. }
  2076. else //move stack on the free pos
  2077. {
  2078. csn.slots[pos].first = cso.slots.begin()->second.first;
  2079. csn.slots[pos].second = cso.slots.begin()->second.second;
  2080. }
  2081. cso.slots.erase(cso.slots.begin());
  2082. }
  2083. SetGarrisons sg;
  2084. sg.garrs[town->visitingHero->id] = csn;
  2085. sg.garrs[town->id] = csn;
  2086. sendAndApply(&sg);
  2087. SetHeroesInTown intown;
  2088. intown.tid = tid;
  2089. intown.visiting = -1;
  2090. intown.garrison = town->visitingHero->id;
  2091. sendAndApply(&intown);
  2092. return true;
  2093. }
  2094. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2095. {
  2096. //check if moving hero out of town will break 8 wandering heroes limit
  2097. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2098. {
  2099. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2100. return false;
  2101. }
  2102. SetHeroesInTown intown;
  2103. intown.tid = tid;
  2104. intown.garrison = -1;
  2105. intown.visiting = town->garrisonHero->id;
  2106. sendAndApply(&intown);
  2107. //town will be empty
  2108. SetGarrisons sg;
  2109. sg.garrs[tid] = CCreatureSet();
  2110. sendAndApply(&sg);
  2111. return true;
  2112. }
  2113. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2114. {
  2115. SetGarrisons sg;
  2116. sg.garrs[town->id] = town->visitingHero->army;
  2117. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  2118. SetHeroesInTown intown;
  2119. intown.tid = tid;
  2120. intown.garrison = town->visitingHero->id;
  2121. intown.visiting = town->garrisonHero->id;
  2122. sendAndApply(&intown);
  2123. sendAndApply(&sg);
  2124. return true;
  2125. }
  2126. else
  2127. {
  2128. complain("Cannot swap garrison hero!");
  2129. return false;
  2130. }
  2131. }
  2132. bool CGameHandler::swapArtifacts(si32 srcHeroID, si32 destHeroID, ui16 srcSlot, ui16 destSlot)
  2133. {
  2134. CGHeroInstance *srcHero = gs->getHero(srcHeroID);
  2135. CGHeroInstance *destHero = gs->getHero(destHeroID);
  2136. // Make sure exchange is even possible between the two heroes.
  2137. if ((distance(srcHero->pos,destHero->pos) > 1.5 )|| (srcHero->tempOwner != destHero->tempOwner))
  2138. return false;
  2139. const CArtifact *srcArtifact = srcHero->getArt(srcSlot);
  2140. const CArtifact *destArtifact = destHero->getArt(destSlot);
  2141. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2142. // Moving to the backpack is always allowed.
  2143. if ((!srcArtifact || destSlot < 19)
  2144. && (((srcArtifact && !vstd::contains(srcArtifact->possibleSlots, destSlot))
  2145. || (destArtifact && srcSlot < 19 && !vstd::contains(destArtifact->possibleSlots, srcSlot)))))
  2146. {
  2147. complain("Cannot swap artifacts!");
  2148. return false;
  2149. }
  2150. if (destSlot >= 19 && srcArtifact->isBig()) {
  2151. complain("Cannot put big artifacts in backpack!");
  2152. return false;
  2153. }
  2154. if (srcSlot == 16 || destSlot == 16) {
  2155. complain("Cannot move catapult!");
  2156. return false;
  2157. }
  2158. // Perform the exchange.
  2159. SetHeroArtifacts sha;
  2160. sha.hid = srcHeroID;
  2161. sha.artifacts = srcHero->artifacts;
  2162. sha.artifWorn = srcHero->artifWorn;
  2163. sha.setArtAtPos(srcSlot, -1);
  2164. if (destSlot < 19 && (destArtifact || srcSlot < 19))
  2165. sha.setArtAtPos(srcSlot, destHero->getArtAtPos(destSlot));
  2166. // Internal hero artifact arrangement.
  2167. if(srcHero == destHero) {
  2168. // Correction for destination from removing source artifact in backpack.
  2169. if (srcSlot >= 19 && destSlot >= 19 && srcSlot < destSlot)
  2170. destSlot--;
  2171. sha.setArtAtPos(destSlot, srcHero->getArtAtPos(srcSlot));
  2172. }
  2173. sendAndApply(&sha);
  2174. if (srcHeroID != destHeroID) {
  2175. // Exchange between two different heroes.
  2176. sha.hid = destHeroID;
  2177. sha.artifacts = destHero->artifacts;
  2178. sha.artifWorn = destHero->artifWorn;
  2179. sha.setArtAtPos(destSlot, srcArtifact ? srcArtifact->id : -1);
  2180. sendAndApply(&sha);
  2181. }
  2182. return true;
  2183. }
  2184. /**
  2185. * Sets a hero artifact slot to contain a specific artifact.
  2186. *
  2187. * @param artID ID of an artifact or -1 for no artifact.
  2188. */
  2189. bool CGameHandler::setArtifact(si32 heroID, ui16 slot, int artID)
  2190. {
  2191. const CGHeroInstance *hero = gs->getHero(heroID);
  2192. if (artID != -1) {
  2193. const CArtifact &artifact = VLC->arth->artifacts[artID];
  2194. if (slot < 19 && !vstd::contains(artifact.possibleSlots, slot)) {
  2195. complain("Artifact does not fit!");
  2196. return false;
  2197. }
  2198. if (slot >= 19 && artifact.isBig()) {
  2199. complain("Cannot put big artifacts in backpack!");
  2200. return false;
  2201. }
  2202. }
  2203. if (slot == 16) {
  2204. complain("Cannot alter catapult slot!");
  2205. return false;
  2206. }
  2207. // Perform the exchange.
  2208. SetHeroArtifacts sha;
  2209. sha.hid = heroID;
  2210. sha.artifacts = hero->artifacts;
  2211. sha.artifWorn = hero->artifWorn;
  2212. sha.setArtAtPos(slot, artID);
  2213. sendAndApply(&sha);
  2214. return true;
  2215. }
  2216. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2217. {
  2218. CGHeroInstance *hero = gs->getHero(hid);
  2219. CGTownInstance *town = hero->visitedTown;
  2220. if(aid==0) //spellbook
  2221. {
  2222. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2223. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  2224. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  2225. )
  2226. return false;
  2227. giveResource(hero->getOwner(),6,-500);
  2228. giveHeroArtifact(0,hid,17);
  2229. giveSpells(town,hero);
  2230. return true;
  2231. }
  2232. else if(aid < 7 && aid > 3) //war machine
  2233. {
  2234. int price = VLC->arth->artifacts[aid].price;
  2235. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2236. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2237. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  2238. || town->town->warMachine!= aid && complain("This machine is unavailable here!") ) //TODO: ballista yard in Stronghold
  2239. {
  2240. return false;
  2241. }
  2242. giveResource(hero->getOwner(),6,-price);
  2243. giveHeroArtifact(aid,hid,9+aid);
  2244. return true;
  2245. }
  2246. return false;
  2247. }
  2248. bool CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  2249. {
  2250. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  2251. double yield = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  2252. yield /= gs->resVals[id2];
  2253. SetResource sr;
  2254. sr.player = player;
  2255. sr.resid = id1;
  2256. sr.val = gs->getPlayer(player)->resources[id1] - val;
  2257. sendAndApply(&sr);
  2258. sr.resid = id2;
  2259. sr.val = gs->getPlayer(player)->resources[id2] + (int)yield;
  2260. sendAndApply(&sr);
  2261. return true;
  2262. }
  2263. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  2264. {
  2265. gs->getHero(hid)->army.formation = formation;
  2266. return true;
  2267. }
  2268. bool CGameHandler::hireHero( ui32 tid, ui8 hid )
  2269. {
  2270. CGTownInstance *t = gs->getTown(tid);
  2271. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  2272. || gs->getPlayer(t->tempOwner)->resources[6]<2500 && complain("Not enough gold for buying hero!")
  2273. || t->visitingHero && complain("There is visiting hero - no place!")
  2274. || getHeroCount(t->tempOwner,false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!")
  2275. )
  2276. return false;
  2277. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  2278. assert(nh);
  2279. HeroRecruited hr;
  2280. hr.tid = tid;
  2281. hr.hid = nh->subID;
  2282. hr.player = t->tempOwner;
  2283. hr.tile = t->pos - int3(1,0,0);
  2284. sendAndApply(&hr);
  2285. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  2286. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  2287. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2288. if(*j)
  2289. pool.erase((**j).subID);
  2290. SetAvailableHeroes sah;
  2291. CGHeroInstance *h1 = gs->hpool.pickHeroFor(false,t->tempOwner,t->town, pool),
  2292. *h2 = gs->getPlayer(t->tempOwner)->availableHeroes[!hid];
  2293. (hid ? sah.hid2 : sah.hid1) = h1 ? h1->subID : -1;
  2294. (hid ? sah.hid1 : sah.hid2) = h2 ? h2->subID : -1;
  2295. sah.player = t->tempOwner;
  2296. sah.flags = hid+1;
  2297. sendAndApply(&sah);
  2298. SetResource sr;
  2299. sr.player = t->tempOwner;
  2300. sr.resid = 6;
  2301. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  2302. sendAndApply(&sr);
  2303. vistiCastleObjects (t, nh);
  2304. giveSpells (t,nh);
  2305. return true;
  2306. }
  2307. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  2308. {
  2309. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2310. if(vstd::contains(callbacks,qid))
  2311. {
  2312. CFunctionList<void(ui32)> callb = callbacks[qid];
  2313. callbacks.erase(qid);
  2314. if(callb)
  2315. callb(answer);
  2316. }
  2317. else if(vstd::contains(garrisonCallbacks,qid))
  2318. {
  2319. if(garrisonCallbacks[qid])
  2320. garrisonCallbacks[qid]();
  2321. garrisonCallbacks.erase(qid);
  2322. allowedExchanges.erase(qid);
  2323. }
  2324. else
  2325. {
  2326. tlog1 << "Unknown query reply...\n";
  2327. return false;
  2328. }
  2329. return true;
  2330. }
  2331. bool CGameHandler::makeBattleAction( BattleAction &ba )
  2332. {
  2333. tlog1 << "\tMaking action of type " << ba.actionType << std::endl;
  2334. bool ok = true;
  2335. switch(ba.actionType)
  2336. {
  2337. case 2: //walk
  2338. {
  2339. sendAndApply(&StartAction(ba)); //start movement
  2340. moveStack(ba.stackNumber,ba.destinationTile); //move
  2341. sendAndApply(&EndAction());
  2342. break;
  2343. }
  2344. case 3: //defend
  2345. case 8: //wait
  2346. {
  2347. sendAndApply(&StartAction(ba));
  2348. sendAndApply(&EndAction());
  2349. break;
  2350. }
  2351. case 4: //retreat/flee
  2352. {
  2353. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  2354. break;
  2355. //TODO: remove retreating hero from map and place it in recruitment list
  2356. BattleResult *br = new BattleResult;
  2357. br->result = 1;
  2358. br->winner = !ba.side; //fleeing side loses
  2359. gs->curB->calculateCasualties(br->casualties);
  2360. giveExp(*br);
  2361. battleResult.set(br);
  2362. break;
  2363. }
  2364. case 6: //walk or attack
  2365. {
  2366. sendAndApply(&StartAction(ba)); //start movement and attack
  2367. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  2368. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  2369. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2370. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  2371. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  2372. && !(curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  2373. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  2374. ) //nor occupy specified hex
  2375. )
  2376. {
  2377. std::string problem = "We cannot move this stack to its destination " + curStack->creature->namePl;
  2378. tlog3 << problem << std::endl;
  2379. complain(problem);
  2380. ok = false;
  2381. sendAndApply(&EndAction());
  2382. break;
  2383. }
  2384. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  2385. {
  2386. stackAtEnd = NULL;
  2387. }
  2388. if(!stackAtEnd)
  2389. {
  2390. std::ostringstream problem;
  2391. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  2392. std::string probl = problem.str();
  2393. tlog3 << probl << std::endl;
  2394. complain(probl);
  2395. ok = false;
  2396. sendAndApply(&EndAction());
  2397. break;
  2398. }
  2399. ui16 curpos = curStack->position,
  2400. enemypos = stackAtEnd->position;
  2401. if( !(
  2402. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  2403. || (curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //back <=> front
  2404. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  2405. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //front <=> back
  2406. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2407. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)//back <=> back
  2408. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2409. )
  2410. )
  2411. {
  2412. tlog3 << "Attack cannot be performed!";
  2413. sendAndApply(&EndAction());
  2414. ok = false;
  2415. }
  2416. //attack
  2417. BattleAttack bat;
  2418. prepareAttack(bat, curStack, stackAtEnd, distance);
  2419. sendAndApply(&bat);
  2420. //counterattack
  2421. if(!curStack->hasFeatureOfType(StackFeature::BLOCKS_RETALIATION)
  2422. && stackAtEnd->alive()
  2423. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasFeatureOfType(StackFeature::UNLIMITED_RETALIATIONS) )
  2424. && !stackAtEnd->hasFeatureOfType(StackFeature::SIEGE_WEAPON)
  2425. && !stackAtEnd->hasFeatureOfType(StackFeature::HYPNOTIZED))
  2426. {
  2427. prepareAttack(bat, stackAtEnd, curStack, 0);
  2428. bat.flags |= 2;
  2429. sendAndApply(&bat);
  2430. }
  2431. //second attack
  2432. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0
  2433. && !curStack->hasFeatureOfType(StackFeature::SHOOTER)
  2434. && curStack->alive()
  2435. && stackAtEnd->alive() )
  2436. {
  2437. bat.flags = 0;
  2438. prepareAttack(bat, curStack, stackAtEnd, 0);
  2439. sendAndApply(&bat);
  2440. }
  2441. //return
  2442. if(curStack->hasFeatureOfType(StackFeature::RETURN_AFTER_STRIKE) && startingPos != curStack->position && curStack->alive())
  2443. {
  2444. moveStack(ba.stackNumber, startingPos);
  2445. //NOTE: curStack->ID == ba.stackNumber (rev 1431)
  2446. }
  2447. sendAndApply(&EndAction());
  2448. break;
  2449. }
  2450. case 7: //shoot
  2451. {
  2452. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2453. *destStack= gs->curB->getStackT(ba.destinationTile);
  2454. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  2455. break;
  2456. sendAndApply(&StartAction(ba)); //start shooting
  2457. BattleAttack bat;
  2458. prepareAttack(bat, curStack, destStack, 0);
  2459. bat.flags |= 1;
  2460. sendAndApply(&bat);
  2461. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  2462. && curStack->alive()
  2463. && destStack->alive()
  2464. && curStack->shots
  2465. )
  2466. {
  2467. prepareAttack(bat, curStack, destStack, 0);
  2468. sendAndApply(&bat);
  2469. }
  2470. sendAndApply(&EndAction());
  2471. break;
  2472. }
  2473. case 9: //catapult
  2474. {
  2475. sendAndApply(&StartAction(ba));
  2476. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  2477. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(20)]; //artillery
  2478. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  2479. if(attackedPart == -1)
  2480. {
  2481. complain("catapult tried to attack non-catapultable hex!");
  2482. break;
  2483. }
  2484. int wallInitHP = gs->curB->si.wallState[attackedPart];
  2485. int dmgAlreadyDealt = 0; //in successive iterations damage is dealt but not yet substracted from wall's HPs
  2486. for(int g=0; g<sbi.shots; ++g)
  2487. {
  2488. if(wallInitHP + dmgAlreadyDealt == 3) //it's not destroyed
  2489. continue;
  2490. CatapultAttack ca; //package for clients
  2491. std::pair< std::pair< ui8, si16 >, ui8> attack; //<< attackedPart , destination tile >, damageDealt >
  2492. attack.first.first = attackedPart;
  2493. attack.first.second = ba.destinationTile;
  2494. attack.second = 0;
  2495. int chanceForHit = 0;
  2496. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  2497. switch(attackedPart)
  2498. {
  2499. case 0: //keep
  2500. chanceForHit = sbi.keep;
  2501. break;
  2502. case 1: //bottom tower
  2503. case 6: //upper tower
  2504. chanceForHit = sbi.tower;
  2505. break;
  2506. case 2: //bottom wall
  2507. case 3: //below gate
  2508. case 4: //over gate
  2509. case 5: //upper wall
  2510. chanceForHit = sbi.wall;
  2511. break;
  2512. case 7: //gate
  2513. chanceForHit = sbi.gate;
  2514. break;
  2515. }
  2516. if(rand()%100 <= chanceForHit) //hit is successful
  2517. {
  2518. int dmgRand = rand()%100;
  2519. //accumulating dmgChance
  2520. dmgChance[1] += dmgChance[0];
  2521. dmgChance[2] += dmgChance[1];
  2522. //calculating dealt damage
  2523. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  2524. {
  2525. if(dmgRand <= dmgChance[v])
  2526. {
  2527. attack.second = std::min(3 - dmgAlreadyDealt - wallInitHP, v);
  2528. dmgAlreadyDealt += attack.second;
  2529. break;
  2530. }
  2531. }
  2532. //removing creatures in turrets / keep if one is destroyed
  2533. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  2534. {
  2535. int posRemove = -1;
  2536. switch(attackedPart)
  2537. {
  2538. case 0: //keep
  2539. posRemove = -2;
  2540. break;
  2541. case 1: //bottom tower
  2542. posRemove = -3;
  2543. break;
  2544. case 6: //upper tower
  2545. posRemove = -4;
  2546. break;
  2547. }
  2548. BattleStacksRemoved bsr;
  2549. for(int g=0; g<gs->curB->stacks.size(); ++g)
  2550. {
  2551. if(gs->curB->stacks[g]->position == posRemove)
  2552. {
  2553. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  2554. break;
  2555. }
  2556. }
  2557. sendAndApply(&bsr);
  2558. }
  2559. }
  2560. ca.attacker = ba.stackNumber;
  2561. ca.attackedParts.insert(attack);
  2562. sendAndApply(&ca);
  2563. }
  2564. sendAndApply(&EndAction());
  2565. break;
  2566. }
  2567. }
  2568. if(ba.stackNumber == gs->curB->activeStack)
  2569. battleMadeAction.setn(true);
  2570. return ok;
  2571. }
  2572. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  2573. {
  2574. bool cheated=true;
  2575. sendAndApply(&PlayerMessage(player,message));
  2576. if(message == "vcmiistari") //give all spells and 999 mana
  2577. {
  2578. SetMana sm;
  2579. ChangeSpells cs;
  2580. SetHeroArtifacts sha;
  2581. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  2582. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  2583. sm.hid = cs.hid = h->id;
  2584. //give all spells
  2585. cs.learn = 1;
  2586. for(int i=0;i<VLC->spellh->spells.size();i++)
  2587. {
  2588. if(!VLC->spellh->spells[i].creatureAbility)
  2589. cs.spells.insert(i);
  2590. }
  2591. //give mana
  2592. sm.val = 999;
  2593. if(!h->getArt(17)) //hero doesn't have spellbook
  2594. {
  2595. //give spellbook
  2596. sha.hid = h->id;
  2597. sha.artifacts = h->artifacts;
  2598. sha.artifWorn = h->artifWorn;
  2599. sha.artifWorn[17] = 0;
  2600. sendAndApply(&sha);
  2601. }
  2602. sendAndApply(&cs);
  2603. sendAndApply(&sm);
  2604. }
  2605. else if(message == "vcmiainur") //gives 5 archangels into each slot
  2606. {
  2607. SetGarrisons sg;
  2608. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2609. if(!hero) return;
  2610. sg.garrs[hero->id] = hero->army;
  2611. for(int i=0;i<7;i++)
  2612. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2613. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  2614. sendAndApply(&sg);
  2615. }
  2616. else if(message == "vcmiangband") //gives 10 black knight into each slot
  2617. {
  2618. SetGarrisons sg;
  2619. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2620. if(!hero) return;
  2621. sg.garrs[hero->id] = hero->army;
  2622. for(int i=0;i<7;i++)
  2623. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2624. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  2625. sendAndApply(&sg);
  2626. }
  2627. else if(message == "vcminoldor") //all war machines
  2628. {
  2629. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2630. if(!hero) return;
  2631. SetHeroArtifacts sha;
  2632. sha.hid = hero->id;
  2633. sha.artifacts = hero->artifacts;
  2634. sha.artifWorn = hero->artifWorn;
  2635. sha.artifWorn[13] = 4;
  2636. sha.artifWorn[14] = 5;
  2637. sha.artifWorn[15] = 6;
  2638. sendAndApply(&sha);
  2639. }
  2640. else if(message == "vcminahar") //1000000 movement points
  2641. {
  2642. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2643. if(!hero) return;
  2644. SetMovePoints smp;
  2645. smp.hid = hero->id;
  2646. smp.val = 1000000;
  2647. sendAndApply(&smp);
  2648. }
  2649. else if(message == "vcmiformenos") //give resources
  2650. {
  2651. SetResources sr;
  2652. sr.player = player;
  2653. sr.res = gs->getPlayer(player)->resources;
  2654. for(int i=0;i<7;i++)
  2655. sr.res[i] += 100;
  2656. sr.res[6] += 19900;
  2657. sendAndApply(&sr);
  2658. }
  2659. else if(message == "vcmieagles") //reveal FoW
  2660. {
  2661. FoWChange fc;
  2662. fc.mode = 1;
  2663. fc.player = player;
  2664. for(int i=0;i<gs->map->width;i++)
  2665. for(int j=0;j<gs->map->height;j++)
  2666. for(int k=0;k<gs->map->twoLevel+1;k++)
  2667. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  2668. fc.tiles.insert(int3(i,j,k));
  2669. sendAndApply(&fc);
  2670. }
  2671. else if(message == "vcmiglorfindel")
  2672. {
  2673. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2674. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  2675. }
  2676. else
  2677. cheated = false;
  2678. if(cheated)
  2679. {
  2680. sendAndApply(&SystemMessage(VLC->generaltexth->allTexts[260]));
  2681. }
  2682. }
  2683. static ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack)
  2684. {
  2685. switch(spell->id)
  2686. {
  2687. case 37: //cure
  2688. {
  2689. int healedHealth = caster->getPrimSkillLevel(2) * 5 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2690. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft);
  2691. break;
  2692. }
  2693. case 38: //resurrection
  2694. {
  2695. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2696. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2697. break;
  2698. }
  2699. case 39: //animate dead
  2700. {
  2701. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2702. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2703. break;
  2704. }
  2705. }
  2706. //we shouldn't be here
  2707. tlog1 << "calculateHealedHP called for non-healing spell: " << spell->name << std::endl;
  2708. return 0;
  2709. }
  2710. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  2711. {
  2712. std::vector<ui32> ret;
  2713. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2714. {
  2715. if ((*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2716. || ((*it)->valOfFeatures(StackFeature::LEVEL_SPELL_IMMUNITY) >= sp->level))
  2717. {
  2718. ret.push_back((*it)->ID);
  2719. continue;
  2720. }
  2721. //non-negative spells on friendly stacks should always succeed, unless immune
  2722. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  2723. continue;
  2724. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  2725. if((*it)->owner == caster->tempOwner)
  2726. bonusHero = caster;
  2727. else
  2728. bonusHero = hero2;
  2729. int prob = (*it)->valOfFeatures(StackFeature::MAGIC_RESISTANCE); //probability of resistance in %
  2730. if(bonusHero)
  2731. {
  2732. //bonusHero's resistance support (secondary skils and artifacts)
  2733. prob += bonusHero->valOfBonuses(HeroBonus::MAGIC_RESISTANCE);
  2734. switch(bonusHero->getSecSkillLevel(26)) //resistance
  2735. {
  2736. case 1: //basic
  2737. prob += 5;
  2738. break;
  2739. case 2: //advanced
  2740. prob += 10;
  2741. break;
  2742. case 3: //expert
  2743. prob += 20;
  2744. break;
  2745. }
  2746. }
  2747. if(prob > 100) prob = 100;
  2748. if(rand()%100 < prob) //immunity from resistance
  2749. ret.push_back((*it)->ID);
  2750. }
  2751. if(sp->id == 60) //hypnotize
  2752. {
  2753. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2754. {
  2755. if( (*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2756. || ( (*it)->amount - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  2757. >
  2758. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  2759. )
  2760. {
  2761. ret.push_back((*it)->ID);
  2762. }
  2763. }
  2764. }
  2765. return ret;
  2766. }
  2767. bool CGameHandler::makeCustomAction( BattleAction &ba )
  2768. {
  2769. switch(ba.actionType)
  2770. {
  2771. case 1: //hero casts spell
  2772. {
  2773. const CGHeroInstance *h = gs->curB->heroes[ba.side];
  2774. const CGHeroInstance *secondHero = gs->curB->heroes[!ba.side];
  2775. if(!h)
  2776. {
  2777. tlog2 << "Wrong caster!\n";
  2778. return false;
  2779. }
  2780. if(ba.additionalInfo >= VLC->spellh->spells.size())
  2781. {
  2782. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  2783. return false;
  2784. }
  2785. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  2786. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  2787. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  2788. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  2789. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  2790. || (gs->curB->castSpells[ba.side]) //spell has been cast
  2791. || (secondHero->hasBonusOfType(HeroBonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  2792. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  2793. )
  2794. {
  2795. tlog2 << "Spell cannot be cast!\n";
  2796. return false;
  2797. }
  2798. sendAndApply(&StartAction(ba)); //start spell casting
  2799. SpellCast sc;
  2800. sc.side = ba.side;
  2801. sc.id = ba.additionalInfo;
  2802. sc.skill = skill;
  2803. sc.tile = ba.destinationTile;
  2804. sc.dmgToDisplay = 0;
  2805. //calculating affected creatures for all spells
  2806. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(s, h, ba.destinationTile);
  2807. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2808. {
  2809. sc.affectedCres.insert((*it)->ID);
  2810. }
  2811. //checking if creatures resist
  2812. sc.resisted = calculateResistedStacks(s, h, secondHero, attackedCres);
  2813. //calculating dmg to display
  2814. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2815. {
  2816. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2817. continue;
  2818. sc.dmgToDisplay += gs->curB->calculateSpellDmg(s, h, *it);
  2819. }
  2820. sendAndApply(&sc);
  2821. //applying effects
  2822. switch(ba.additionalInfo) //spell id
  2823. {
  2824. case 15: //magic arrow
  2825. case 16: //ice bolt
  2826. case 17: //lightning bolt
  2827. case 18: //implosion
  2828. case 20: //frost ring
  2829. case 21: //fireball
  2830. case 22: //inferno
  2831. case 23: //meteor shower
  2832. case 24: //death ripple
  2833. case 25: //destroy undead
  2834. case 26: //armageddon
  2835. {
  2836. StacksInjured si;
  2837. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2838. {
  2839. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2840. continue;
  2841. BattleStackAttacked bsa;
  2842. bsa.flags |= 2;
  2843. bsa.effect = VLC->spellh->spells[ba.additionalInfo].mainEffectAnim;
  2844. bsa.damageAmount = gs->curB->calculateSpellDmg(s, h, *it);
  2845. bsa.stackAttacked = (*it)->ID;
  2846. bsa.attackerID = -1;
  2847. prepareAttacked(bsa,*it);
  2848. si.stacks.insert(bsa);
  2849. }
  2850. if(!si.stacks.empty())
  2851. sendAndApply(&si);
  2852. break;
  2853. }
  2854. case 27: //shield
  2855. case 28: //air shield
  2856. case 30: //protection from air
  2857. case 31: //protection from fire
  2858. case 32: //protection from water
  2859. case 33: //protection from earth
  2860. case 34: //anti-magic
  2861. case 41: //bless
  2862. case 42: //curse
  2863. case 43: //bloodlust
  2864. case 44: //precision
  2865. case 45: //weakness
  2866. case 46: //stone skin
  2867. case 47: //disrupting ray
  2868. case 48: //prayer
  2869. case 49: //mirth
  2870. case 50: //sorrow
  2871. case 51: //fortune
  2872. case 52: //misfortune
  2873. case 53: //haste
  2874. case 54: //slow
  2875. case 55: //slayer
  2876. case 56: //frenzy
  2877. case 58: //counterstrike
  2878. case 59: //berserk
  2879. case 60: //hypnotize
  2880. case 61: //forgetfulness
  2881. case 62: //blind
  2882. {
  2883. SetStackEffect sse;
  2884. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2885. {
  2886. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2887. continue;
  2888. sse.stacks.insert((*it)->ID);
  2889. }
  2890. sse.effect.id = ba.additionalInfo;
  2891. sse.effect.level = h->getSpellSchoolLevel(s);
  2892. sse.effect.turnsRemain = BattleInfo::calculateSpellDuration(s, h);
  2893. if(!sse.stacks.empty())
  2894. sendAndApply(&sse);
  2895. break;
  2896. }
  2897. case 37: //cure
  2898. case 38: //resurrection
  2899. case 39: //animate dead
  2900. {
  2901. StacksHealedOrResurrected shr;
  2902. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2903. {
  2904. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  2905. || (s->id == 39 && !(*it)->hasFeatureOfType(StackFeature::UNDEAD)) //we try to cast animate dead on living stack
  2906. )
  2907. continue;
  2908. StacksHealedOrResurrected::HealInfo hi;
  2909. hi.stackID = (*it)->ID;
  2910. hi.healedHP = calculateHealedHP(h, s, *it);
  2911. hi.lowLevelResurrection = h->getSpellSchoolLevel(s) <= 1;
  2912. shr.healedStacks.push_back(hi);
  2913. }
  2914. if(!shr.healedStacks.empty())
  2915. sendAndApply(&shr);
  2916. break;
  2917. }
  2918. case 64: //remove obstacle
  2919. {
  2920. ObstaclesRemoved obr;
  2921. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  2922. {
  2923. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  2924. if(vstd::contains(blockedHexes, ba.destinationTile)) //this obstacle covers given hex
  2925. {
  2926. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  2927. }
  2928. }
  2929. if(!obr.obstacles.empty())
  2930. sendAndApply(&obr);
  2931. break;
  2932. }
  2933. }
  2934. sendAndApply(&EndAction());
  2935. if( !gs->curB->getStack(gs->curB->activeStack, false)->alive() )
  2936. {
  2937. battleMadeAction.setn(true);
  2938. }
  2939. checkForBattleEnd(gs->curB->stacks);
  2940. if(battleResult.get())
  2941. {
  2942. endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  2943. }
  2944. return true;
  2945. }
  2946. }
  2947. return false;
  2948. }
  2949. void CGameHandler::handleTimeEvents()
  2950. {
  2951. gs->map->events.sort(evntCmp);
  2952. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  2953. {
  2954. CMapEvent *ev = gs->map->events.front();
  2955. for(int player = 0; player < PLAYER_LIMIT; player++)
  2956. {
  2957. PlayerState *pinfo = gs->getPlayer(player);
  2958. if( pinfo //player exists
  2959. && (ev->players & 1<<player) //event is enabled to this player
  2960. && ((ev->computerAffected && !pinfo->human)
  2961. || (ev->humanAffected && pinfo->human)
  2962. )
  2963. )
  2964. {
  2965. //give resources
  2966. SetResources sr;
  2967. sr.player = player;
  2968. sr.res = pinfo->resources;
  2969. //prepare dialog
  2970. InfoWindow iw;
  2971. iw.player = player;
  2972. iw.text << ev->message;
  2973. for (int i=0; i<ev->resources.size(); i++)
  2974. {
  2975. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  2976. {
  2977. // If removing too much resources, adjust the
  2978. // amount so the total doesn't become negative.
  2979. if (sr.res[i] + ev->resources[i] < 0)
  2980. ev->resources[i] = -sr.res[i];
  2981. if(ev->resources[i]) //if non-zero res change
  2982. {
  2983. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  2984. sr.res[i] += ev->resources[i];
  2985. }
  2986. }
  2987. }
  2988. if (iw.components.size())
  2989. {
  2990. sendAndApply(&sr); //update player resources if changed
  2991. }
  2992. sendAndApply(&iw); //show dialog
  2993. }
  2994. } //PLAYERS LOOP
  2995. if(ev->nextOccurence)
  2996. {
  2997. ev->firstOccurence += ev->nextOccurence;
  2998. gs->map->events.sort(evntCmp);
  2999. }
  3000. else
  3001. {
  3002. delete ev;
  3003. gs->map->events.pop_front();
  3004. }
  3005. }
  3006. }
  3007. bool CGameHandler::complain( const std::string &problem )
  3008. {
  3009. sendMessageToAll("Server encountered a problem: " + problem);
  3010. tlog1 << problem << std::endl;
  3011. return true;
  3012. }
  3013. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  3014. {
  3015. //TODO: write
  3016. return 0;
  3017. }
  3018. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  3019. {
  3020. ui8 player = getOwner(hid);
  3021. GarrisonDialog gd;
  3022. gd.hid = hid;
  3023. gd.objid = upobj;
  3024. {
  3025. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3026. gd.id = QID;
  3027. garrisonCallbacks[QID] = cb;
  3028. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  3029. states.addQuery(player,QID);
  3030. QID++;
  3031. gd.removableUnits = removableUnits;
  3032. sendAndApply(&gd);
  3033. }
  3034. }
  3035. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  3036. {
  3037. if(id1 == id2)
  3038. return true;
  3039. {
  3040. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3041. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  3042. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  3043. return true;
  3044. }
  3045. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  3046. if(o1->ID == TOWNI_TYPE)
  3047. {
  3048. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  3049. if(t->visitingHero == o2 || t->garrisonHero == o2)
  3050. return true;
  3051. }
  3052. if(o2->ID == TOWNI_TYPE)
  3053. {
  3054. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  3055. if(t->visitingHero == o1 || t->garrisonHero == o1)
  3056. return true;
  3057. }
  3058. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  3059. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  3060. {
  3061. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  3062. //(to block moving stacks for free [without visiting] beteen heroes)
  3063. return true;
  3064. }
  3065. return false;
  3066. }
  3067. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  3068. {
  3069. obj->onHeroVisit(h);
  3070. }
  3071. bool CGameHandler::buildBoat( ui32 objid )
  3072. {
  3073. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  3074. int boatType = 1;
  3075. if(obj->state())
  3076. {
  3077. complain("Cannot build boat in this shipyard!");
  3078. return false;
  3079. }
  3080. else if(obj->o->ID == TOWNI_TYPE
  3081. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  3082. {
  3083. complain("Cannot build boat in the town - no shipyard!");
  3084. return false;
  3085. }
  3086. //TODO use "real" cost via obj->getBoatCost
  3087. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  3088. {
  3089. complain("Not enough resources to build a boat!");
  3090. return false;
  3091. }
  3092. int3 tile = obj->bestLocation();
  3093. if(!gs->map->isInTheMap(tile))
  3094. {
  3095. complain("Cannot find appropriate tile for a boat!");
  3096. return false;
  3097. }
  3098. //take boat cost
  3099. SetResources sr;
  3100. sr.player = obj->o->tempOwner;
  3101. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  3102. sr.res[0] -= 10;
  3103. sr.res[6] -= 1000;
  3104. sendAndApply(&sr);
  3105. //create boat
  3106. NewObject no;
  3107. no.ID = 8;
  3108. if (obj->o->ID == TOWNI_TYPE)
  3109. { //check what kind of creatures are avaliable in town
  3110. if (VLC->creh->creatures[(static_cast<const CGTownInstance*>(obj))->creatures[0].second[0]].isGood())
  3111. boatType = 1;
  3112. else if (VLC->creh->creatures[(static_cast<const CGTownInstance*>(obj))->creatures[0].second[0]].isEvil())
  3113. boatType = 0;
  3114. else //neutral
  3115. boatType = 2;
  3116. }
  3117. no.subID = boatType;
  3118. no.pos = tile + int3(1,0,0);
  3119. sendAndApply(&no);
  3120. return true;
  3121. }
  3122. void CGameHandler::engageIntoBattle( ui8 player )
  3123. {
  3124. if(vstd::contains(states.players, player))
  3125. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  3126. //notify interfaces
  3127. PlayerBlocked pb;
  3128. pb.player = player;
  3129. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  3130. sendAndApply(&pb);
  3131. }
  3132. void CGameHandler::winLoseHandle(ui8 players )
  3133. {
  3134. for(size_t i = 0; i < PLAYER_LIMIT; i++)
  3135. {
  3136. if(players & 1<<i && gs->getPlayer(i))
  3137. {
  3138. checkLossVictory(i);
  3139. }
  3140. }
  3141. }
  3142. void CGameHandler::checkLossVictory( ui8 player )
  3143. {
  3144. const PlayerState *p = gs->getPlayer(player);
  3145. if(p->status) //player already won / lost
  3146. return;
  3147. int loss = gs->lossCheck(player);
  3148. int vic = gs->victoryCheck(player);
  3149. if(!loss && !vic)
  3150. return;
  3151. InfoWindow iw;
  3152. getLossVicMessage(player, vic ? vic < 0 : loss < 0, vic, iw);
  3153. sendAndApply(&iw);
  3154. PlayerEndsGame peg;
  3155. peg.player = player;
  3156. peg.victory = vic;
  3157. sendAndApply(&peg);
  3158. if(vic) //one player won -> all enemies lost //TODO: allies
  3159. {
  3160. iw.text.localStrings.front().second++; //message about losing because enemy won first is just after victory message
  3161. for (std::map<ui8,PlayerState>::const_iterator i = gs->players.begin(); i!=gs->players.end(); i++)
  3162. {
  3163. if(i->first < PLAYER_LIMIT && i->first != player)
  3164. {
  3165. iw.player = i->first;
  3166. sendAndApply(&iw);
  3167. peg.player = i->first;
  3168. peg.victory = false;
  3169. sendAndApply(&peg);
  3170. }
  3171. }
  3172. }
  3173. else //player lost -> all his objects become unflagged (neutral)
  3174. {
  3175. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++)
  3176. {
  3177. if(*i && (*i)->tempOwner == player)
  3178. setOwner((**i).id,NEUTRAL_PLAYER);
  3179. }
  3180. }
  3181. if(vic)
  3182. end2 = true;
  3183. }
  3184. void CGameHandler::getLossVicMessage( ui8 player, bool standard, bool victory, InfoWindow &out ) const
  3185. {
  3186. const PlayerState *p = gs->getPlayer(player);
  3187. // if(!p->human)
  3188. // return; //AI doesn't need text info of loss
  3189. out.player = player;
  3190. if(victory)
  3191. {
  3192. if(!standard) //not std loss
  3193. {
  3194. switch(gs->map->victoryCondition.condition)
  3195. {
  3196. case artifact:
  3197. out.text.addTxt(MetaString::GENERAL_TXT, 280); //Congratulations! You have found the %s, and can claim victory!
  3198. out.text.addReplacement(MetaString::ART_NAMES,gs->map->victoryCondition.ID); //artifact name
  3199. break;
  3200. case gatherTroop:
  3201. 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!
  3202. out.text.addReplacement(gs->map->victoryCondition.count);
  3203. out.text.addReplacement(MetaString::CRE_PL_NAMES, gs->map->victoryCondition.ID);
  3204. break;
  3205. case gatherResource:
  3206. out.text.addTxt(MetaString::GENERAL_TXT, 278); //Congratulations! You have collected over %d %s in your treasury. Victory is yours!
  3207. out.text.addReplacement(gs->map->victoryCondition.count);
  3208. out.text.addReplacement(MetaString::RES_NAMES, gs->map->victoryCondition.ID);
  3209. break;
  3210. case buildCity:
  3211. out.text.addTxt(MetaString::GENERAL_TXT, 282); //Congratulations! You have successfully upgraded your town, and can claim victory!
  3212. break;
  3213. case buildGrail:
  3214. out.text.addTxt(MetaString::GENERAL_TXT, 284); //Congratulations! You have constructed a permanent home for the Grail, and can claim victory!
  3215. break;
  3216. case beatHero:
  3217. {
  3218. out.text.addTxt(MetaString::GENERAL_TXT, 252); //Congratulations! You have completed your quest to defeat the enemy hero %s. Victory is yours!
  3219. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->victoryCondition.obj);
  3220. assert(h);
  3221. out.text.addReplacement(h->name);
  3222. }
  3223. break;
  3224. case captureCity:
  3225. {
  3226. out.text.addTxt(MetaString::GENERAL_TXT, 249); //Congratulations! You captured %s, and are victorious!
  3227. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->victoryCondition.obj);
  3228. assert(t);
  3229. out.text.addReplacement(t->name);
  3230. }
  3231. break;
  3232. case beatMonster:
  3233. out.text.addTxt(MetaString::GENERAL_TXT, 286); //Congratulations! You have completed your quest to kill the fearsome beast, and can claim victory!
  3234. break;
  3235. case takeDwellings:
  3236. out.text.addTxt(MetaString::GENERAL_TXT, 288); //Congratulations! Your flag flies on the dwelling of every creature. Victory is yours!
  3237. break;
  3238. case takeMines:
  3239. out.text.addTxt(MetaString::GENERAL_TXT, 290); //Congratulations! Your flag flies on every mine. Victory is yours!
  3240. break;
  3241. case transportItem:
  3242. out.text.addTxt(MetaString::GENERAL_TXT, 292); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  3243. break;
  3244. }
  3245. }
  3246. else
  3247. {
  3248. }
  3249. }
  3250. else
  3251. {
  3252. if(!standard) //not std loss
  3253. {
  3254. switch(gs->map->lossCondition.typeOfLossCon)
  3255. {
  3256. case lossCastle:
  3257. {
  3258. out.text.addTxt(MetaString::GENERAL_TXT, 251); //The town of %s has fallen - all is lost!
  3259. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->lossCondition.obj);
  3260. assert(t);
  3261. out.text.addReplacement(t->name);
  3262. }
  3263. break;
  3264. case lossHero:
  3265. {
  3266. out.text.addTxt(MetaString::GENERAL_TXT, 253); //The hero, %s, has suffered defeat - your quest is over!
  3267. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->lossCondition.obj);
  3268. assert(h);
  3269. out.text.addReplacement(h->name);
  3270. }
  3271. break;
  3272. case timeExpires:
  3273. out.text.addTxt(MetaString::GENERAL_TXT, 254); //Alas, time has run out on your quest. All is lost.
  3274. break;
  3275. }
  3276. }
  3277. else //lost all towns and heroes
  3278. {
  3279. out.text.addTxt(MetaString::GENERAL_TXT, 660); //All your forces have been defeated, and you are banished from this land!
  3280. }
  3281. }
  3282. }