CGameHandler.cpp 120 KB

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