CGameHandler.cpp 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641
  1. #include "../StartInfo.h"
  2. #include "../hch/CArtHandler.h"
  3. #include "../hch/CBuildingHandler.h"
  4. #include "../hch/CDefObjInfoHandler.h"
  5. #include "../hch/CGeneralTextHandler.h"
  6. #include "../hch/CHeroHandler.h"
  7. #include "../hch/CObjectHandler.h"
  8. #include "../hch/CSpellHandler.h"
  9. #include "../hch/CTownHandler.h"
  10. #include "../CGameState.h"
  11. #include "../lib/CondSh.h"
  12. #include "../lib/NetPacks.h"
  13. #include "../lib/Connection.h"
  14. #include "../lib/VCMI_Lib.h"
  15. #include "../map.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 <fstream>
  23. /*
  24. * CGameHandler.cpp, part of VCMI engine
  25. *
  26. * Authors: listed in file AUTHORS in main folder
  27. *
  28. * License: GNU General Public License v2.0 or later
  29. * Full text of license available in license.txt file, in main folder
  30. *
  31. */
  32. #undef DLL_EXPORT
  33. #define DLL_EXPORT
  34. #include "../lib/RegisterTypes.cpp"
  35. #ifndef _MSC_VER
  36. #include <boost/thread/xtime.hpp>
  37. #endif
  38. extern bool end2;
  39. #ifdef min
  40. #undef min
  41. #endif
  42. #ifdef max
  43. #undef max
  44. #endif
  45. #define NEW_ROUND BattleNextRound bnr;\
  46. bnr.round = gs->curB->round + 1;\
  47. sendAndApply(&bnr);
  48. CondSh<bool> battleMadeAction;
  49. CondSh<BattleResult *> battleResult(NULL);
  50. class CBaseForGHApply
  51. {
  52. public:
  53. virtual bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  54. };
  55. template <typename T> class CApplyOnGH : public CBaseForGHApply
  56. {
  57. public:
  58. bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  59. {
  60. T *ptr = static_cast<T*>(pack);
  61. ptr->c = c;
  62. return ptr->applyGh(gh);
  63. }
  64. };
  65. class CGHApplier
  66. {
  67. public:
  68. std::map<ui16,CBaseForGHApply*> apps;
  69. CGHApplier()
  70. {
  71. registerTypes3(*this);
  72. }
  73. template<typename T> void registerType(const T * t=NULL)
  74. {
  75. ui16 ID = typeList.registerType(t);
  76. apps[ID] = new CApplyOnGH<T>;
  77. }
  78. } *applier = NULL;
  79. class CMP_stack
  80. {
  81. public:
  82. inline bool operator ()(const CStack* a, const CStack* b)
  83. {
  84. return (a->Speed())>(b->Speed());
  85. }
  86. } cmpst ;
  87. double distance(int3 a, int3 b)
  88. {
  89. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  90. }
  91. void giveExp(BattleResult &r)
  92. {
  93. r.exp[0] = 0;
  94. r.exp[1] = 0;
  95. for(std::set<std::pair<ui32,si32> >::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  96. {
  97. r.exp[r.winner] += VLC->creh->creatures[i->first].hitPoints * i->second;
  98. }
  99. }
  100. PlayerStatus PlayerStatuses::operator[](ui8 player)
  101. {
  102. boost::unique_lock<boost::mutex> l(mx);
  103. if(players.find(player) != players.end())
  104. {
  105. return players[player];
  106. }
  107. else
  108. {
  109. throw std::string("No such player!");
  110. }
  111. }
  112. void PlayerStatuses::addPlayer(ui8 player)
  113. {
  114. boost::unique_lock<boost::mutex> l(mx);
  115. players[player];
  116. }
  117. bool PlayerStatuses::hasQueries(ui8 player)
  118. {
  119. boost::unique_lock<boost::mutex> l(mx);
  120. if(players.find(player) != players.end())
  121. {
  122. return players[player].queries.size();
  123. }
  124. else
  125. {
  126. throw std::string("No such player!");
  127. }
  128. }
  129. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  130. {
  131. boost::unique_lock<boost::mutex> l(mx);
  132. if(players.find(player) != players.end())
  133. {
  134. return players[player].*flag;
  135. }
  136. else
  137. {
  138. throw std::string("No such player!");
  139. }
  140. }
  141. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  142. {
  143. boost::unique_lock<boost::mutex> l(mx);
  144. if(players.find(player) != players.end())
  145. {
  146. players[player].*flag = val;
  147. }
  148. else
  149. {
  150. throw std::string("No such player!");
  151. }
  152. cv.notify_all();
  153. }
  154. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  155. {
  156. boost::unique_lock<boost::mutex> l(mx);
  157. if(players.find(player) != players.end())
  158. {
  159. players[player].queries.insert(id);
  160. }
  161. else
  162. {
  163. throw std::string("No such player!");
  164. }
  165. cv.notify_all();
  166. }
  167. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  168. {
  169. boost::unique_lock<boost::mutex> l(mx);
  170. if(players.find(player) != players.end())
  171. {
  172. players[player].queries.erase(id);
  173. }
  174. else
  175. {
  176. throw std::string("No such player!");
  177. }
  178. cv.notify_all();
  179. }
  180. template <typename T>
  181. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  182. {
  183. fun(args[which]);
  184. }
  185. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  186. {
  187. SetSecSkill sss;
  188. sss.id = ID;
  189. sss.which = which;
  190. sss.val = val;
  191. sss.abs = abs;
  192. sendAndApply(&sss);
  193. }
  194. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  195. {
  196. SetPrimSkill sps;
  197. sps.id = ID;
  198. sps.which = which;
  199. sps.abs = abs;
  200. sps.val = val;
  201. sendAndApply(&sps);
  202. if(which==4) //only for exp - hero may level up
  203. {
  204. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  205. while (hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  206. {
  207. //give prim skill
  208. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  209. int r = rand()%100, pom=0, x=0;
  210. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  211. for(;x<PRIMARY_SKILLS;x++)
  212. {
  213. pom += hero->type->heroClass->primChance[x].*g;
  214. if(r<pom)
  215. break;
  216. }
  217. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  218. SetPrimSkill sps;
  219. sps.id = ID;
  220. sps.which = x;
  221. sps.abs = false;
  222. sps.val = 1;
  223. sendAndApply(&sps);
  224. HeroLevelUp hlu;
  225. hlu.heroid = ID;
  226. hlu.primskill = x;
  227. hlu.level = hero->level+1;
  228. //picking sec. skills for choice
  229. std::set<int> basicAndAdv, expert, none;
  230. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  231. for(unsigned i=0;i<hero->secSkills.size();i++)
  232. {
  233. if(hero->secSkills[i].second < 3)
  234. basicAndAdv.insert(hero->secSkills[i].first);
  235. else
  236. expert.insert(hero->secSkills[i].first);
  237. none.erase(hero->secSkills[i].first);
  238. }
  239. //first offered skill
  240. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  241. {
  242. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  243. none.erase(hlu.skills.back());
  244. }
  245. else if(basicAndAdv.size())
  246. {
  247. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  248. hlu.skills.push_back(s);
  249. basicAndAdv.erase(s);
  250. }
  251. //second offered skill
  252. if(basicAndAdv.size())
  253. {
  254. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  255. }
  256. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  257. {
  258. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  259. }
  260. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  261. {
  262. boost::function<void(ui32)> callback = boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::changeSecSkill,this,ID,_1,1,0)),_1));
  263. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  264. }
  265. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  266. {
  267. sendAndApply(&hlu);
  268. changeSecSkill(ID,hlu.skills.back(),1,false);
  269. }
  270. else //apply and send info
  271. {
  272. sendAndApply(&hlu);
  273. }
  274. }
  275. }
  276. }
  277. CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  278. {
  279. CCreatureSet ret(set);
  280. for(int i=0; i<bat->stacks.size();i++)
  281. {
  282. CStack *st = bat->stacks[i];
  283. if(st->owner==color && vstd::contains(set.slots,st->slot) && st->amount < set.slots.find(st->slot)->second.second)
  284. {
  285. if(st->alive())
  286. ret.slots[st->slot].second = st->amount;
  287. else
  288. ret.slots.erase(st->slot);
  289. }
  290. }
  291. return ret;
  292. }
  293. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb)
  294. {
  295. BattleInfo *curB = new BattleInfo;
  296. setupBattle(curB, tile, army1, army2, hero1, hero2); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  297. NEW_ROUND;
  298. //TODO: pre-tactic stuff, call scripts etc.
  299. //tactic round
  300. {
  301. NEW_ROUND;
  302. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  303. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  304. {
  305. //TODO: tactic round (round -1)
  306. }
  307. }
  308. //main loop
  309. while(!battleResult.get()) //till the end of the battle ;]
  310. {
  311. NEW_ROUND;
  312. std::vector<CStack*> & stacks = (gs->curB->stacks);
  313. const BattleInfo & curB = *gs->curB;
  314. //stack loop
  315. CStack *next;
  316. while(!battleResult.get() && (next=gs->curB->getNextStack()))
  317. {
  318. next->state -= WAITING; //if stack was waiting it'll now make move, so it won't be "waiting" anymore
  319. //check for bad morale => freeze
  320. if(next->Morale() < 0)
  321. {
  322. if( rand()%24 < (-next->Morale())*2 )
  323. {
  324. //unit loses its turn - empty freeze action
  325. BattleAction ba;
  326. ba.actionType = 11;
  327. ba.additionalInfo = 1;
  328. ba.side = !next->attackerOwned;
  329. ba.stackNumber = next->ID;
  330. sendAndApply(&StartAction(ba));
  331. sendAndApply(&EndAction());
  332. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  333. continue;
  334. }
  335. }
  336. askInterfaceForMove:
  337. //ask interface and wait for answer
  338. if(!battleResult.get())
  339. {
  340. BattleSetActiveStack sas;
  341. sas.stack = next->ID;
  342. sendAndApply(&sas);
  343. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  344. while(!battleMadeAction.data && !battleResult.get()) //active stack hasn't made its action and battle is still going
  345. battleMadeAction.cond.wait(lock);
  346. battleMadeAction.data = false;
  347. }
  348. else
  349. {
  350. break;
  351. }
  352. //we're after action, all results applied
  353. checkForBattleEnd(stacks); //check if this action ended the battle
  354. //check for good morale
  355. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  356. && !vstd::contains(next->state,DEFENDING)
  357. && !vstd::contains(next->state,WAITING)
  358. && next->alive()
  359. && next->Morale() > 0
  360. )
  361. if(rand()%24 < next->Morale()) //this stack hasn't got morale this turn
  362. goto askInterfaceForMove; //move this stack once more
  363. }
  364. }
  365. //unblock engaged players
  366. if(hero1->tempOwner<PLAYER_LIMIT)
  367. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  368. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  369. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  370. //casualties among heroes armies
  371. SetGarrisons sg;
  372. if(hero1)
  373. sg.garrs[hero1->id] = takeCasualties(hero1->tempOwner,hero1->army,gs->curB);
  374. if(hero2)
  375. sg.garrs[hero2->id] = takeCasualties(hero2->tempOwner,hero2->army,gs->curB);
  376. sendAndApply(&sg);
  377. //end battle, remove all info, free memory
  378. giveExp(*battleResult.data);
  379. sendAndApply(battleResult.data);
  380. //if one hero has lost we will erase him
  381. if(battleResult.data->winner!=0 && hero1)
  382. {
  383. RemoveObject ro(hero1->id);
  384. sendAndApply(&ro);
  385. }
  386. if(battleResult.data->winner!=1 && hero2)
  387. {
  388. RemoveObject ro(hero2->id);
  389. sendAndApply(&ro);
  390. }
  391. //give exp
  392. if(battleResult.data->exp[0] && hero1)
  393. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  394. if(battleResult.data->exp[1] && hero2)
  395. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  396. if(cb)
  397. cb(battleResult.data);
  398. delete battleResult.data;
  399. }
  400. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, CStack *def)
  401. {
  402. bsa.killedAmount = bsa.damageAmount / def->creature->hitPoints;
  403. unsigned damageFirst = bsa.damageAmount % def->creature->hitPoints;
  404. if( def->firstHPleft <= damageFirst )
  405. {
  406. bsa.killedAmount++;
  407. bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  408. }
  409. else
  410. {
  411. bsa.newHP = def->firstHPleft - damageFirst;
  412. }
  413. if(def->amount <= bsa.killedAmount) //stack killed
  414. {
  415. bsa.newAmount = 0;
  416. bsa.flags |= 1;
  417. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  418. }
  419. else
  420. {
  421. bsa.newAmount = def->amount - bsa.killedAmount;
  422. }
  423. }
  424. void CGameHandler::prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  425. {
  426. bat.bsa.clear();
  427. bat.stackAttacking = att->ID;
  428. std::set<BattleStackAttacked>::iterator i = bat.bsa.insert(BattleStackAttacked()).first;
  429. BattleStackAttacked *bsa = &*i;
  430. bsa->stackAttacked = def->ID;
  431. bsa->damageAmount = BattleInfo::calculateDmg(att, def, gs->getHero(att->attackerOwned ? gs->curB->hero1 : gs->curB->hero2), gs->getHero(def->attackerOwned ? gs->curB->hero1 : gs->curB->hero2), bat.shot());//counting dealt damage
  432. if(att->Luck() > 0 && rand()%24 < att->Luck())
  433. {
  434. bsa->damageAmount *= 2;
  435. bsa->flags |= 4;
  436. }
  437. prepareAttacked(*bsa,def);
  438. }
  439. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  440. {
  441. srand(time(NULL));
  442. CPack *pack = NULL;
  443. try
  444. {
  445. while(!end2)
  446. {
  447. {
  448. boost::unique_lock<boost::mutex> lock(*c.rmx);
  449. c >> pack; //get the package
  450. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  451. }
  452. int packType = typeList.getTypeID(pack); //get the id of type
  453. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  454. if(apply)
  455. {
  456. bool result = apply->applyOnGH(this,&c,pack);
  457. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  458. //send confirmation that we've applied the package
  459. PackageApplied applied;
  460. applied.result = result;
  461. applied.packType = packType;
  462. {
  463. boost::unique_lock<boost::mutex> lock(*c.wmx);
  464. c << &applied;
  465. }
  466. }
  467. else
  468. {
  469. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  470. }
  471. delete pack;
  472. pack = NULL;
  473. }
  474. }
  475. HANDLE_EXCEPTION(end2 = true);
  476. handleConEnd:
  477. tlog1 << "Ended handling connection\n";
  478. #undef SPELL_CAST_TEMPLATE_1
  479. #undef SPELL_CAST_TEMPLATE_2
  480. }
  481. void CGameHandler::moveStack(int stack, int dest)
  482. {
  483. CStack *curStack = gs->curB->getStack(stack),
  484. *stackAtEnd = gs->curB->getStackT(dest);
  485. //initing necessary tables
  486. bool accessibility[BFIELD_SIZE];
  487. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  488. for(int b=0; b<BFIELD_SIZE; ++b)
  489. {
  490. accessibility[b] = false;
  491. }
  492. for(int g=0; g<accessible.size(); ++g)
  493. {
  494. accessibility[accessible[g]] = true;
  495. }
  496. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  497. if(!stackAtEnd && curStack->creature->isDoubleWide() && !accessibility[dest])
  498. {
  499. if(curStack->attackerOwned)
  500. {
  501. if(accessibility[dest+1])
  502. dest+=1;
  503. }
  504. else
  505. {
  506. if(accessibility[dest-1])
  507. dest-=1;
  508. }
  509. }
  510. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  511. return;
  512. //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
  513. // return false;
  514. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibility, curStack->creature->isFlying());
  515. if(curStack->creature->isFlying())
  516. {
  517. if(path.second <= curStack->Speed() && path.first.size() > 0)
  518. {
  519. //inform clients about move
  520. BattleStackMoved sm;
  521. sm.stack = curStack->ID;
  522. sm.tile = path.first[0];
  523. sm.distance = path.second;
  524. sm.ending = true;
  525. sendAndApply(&sm);
  526. }
  527. }
  528. else //for non-flying creatures
  529. {
  530. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  531. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  532. {
  533. //inform clients about move
  534. BattleStackMoved sm;
  535. sm.stack = curStack->ID;
  536. sm.tile = path.first[v];
  537. sm.distance = path.second;
  538. sm.ending = v==tilesToMove;
  539. sendAndApply(&sm);
  540. }
  541. }
  542. }
  543. CGameHandler::CGameHandler(void)
  544. {
  545. QID = 1;
  546. gs = NULL;
  547. IObjectInterface::cb = this;
  548. applier = new CGHApplier;
  549. }
  550. CGameHandler::~CGameHandler(void)
  551. {
  552. delete applier;
  553. applier = NULL;
  554. delete gs;
  555. }
  556. void CGameHandler::init(StartInfo *si, int Seed)
  557. {
  558. Mapa *map = new Mapa(si->mapname);
  559. tlog0 << "Map loaded!" << std::endl;
  560. gs = new CGameState();
  561. tlog0 << "Gamestate created!" << std::endl;
  562. gs->init(si,map,Seed);
  563. tlog0 << "Gamestate initialized!" << std::endl;
  564. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  565. states.addPlayer(i->first);
  566. }
  567. bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  568. {
  569. return *a < *b;
  570. }
  571. void CGameHandler::newTurn()
  572. {
  573. tlog5 << "Turn " << gs->day+1 << std::endl;
  574. NewTurn n;
  575. n.day = gs->day + 1;
  576. n.resetBuilded = true;
  577. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  578. {
  579. if(i->first == 255) continue;
  580. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  581. {
  582. SetAvailableHeroes sah;
  583. sah.player = i->first;
  584. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle]);
  585. if(h)
  586. sah.hid1 = h->subID;
  587. else
  588. sah.hid1 = -1;
  589. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle],sah.hid1);
  590. if(h)
  591. sah.hid2 = h->subID;
  592. else
  593. sah.hid2 = -1;
  594. sendAndApply(&sah);
  595. }
  596. if(i->first>=PLAYER_LIMIT) continue;
  597. SetResources r;
  598. r.player = i->first;
  599. for(int j=0;j<RESOURCE_QUANTITY;j++)
  600. r.res[j] = i->second.resources[j];
  601. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  602. {
  603. NewTurn::Hero hth;
  604. hth.id = h->id;
  605. hth.move = h->maxMovePoints(true); //TODO: check if hero is really on the land
  606. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  607. hth.mana = h->manaLimit(); //restore all mana
  608. else
  609. hth.mana = std::max(si32(0), std::min(h->mana + h->manaRegain(), h->manaLimit()) );
  610. n.heroes.insert(hth);
  611. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  612. {
  613. case 1: //basic
  614. r.res[6] += 125;
  615. break;
  616. case 2: //advanced
  617. r.res[6] += 250;
  618. break;
  619. case 3: //expert
  620. r.res[6] += 500;
  621. break;
  622. }
  623. for(std::list<HeroBonus>::iterator i = h->bonuses.begin(); i != h->bonuses.end(); i++)
  624. if(i->type == HeroBonus::GENERATE_RESOURCE)
  625. r.res[i->subtype] += i->val;
  626. }
  627. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  628. {
  629. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  630. {
  631. if((**j).town->primaryRes == 127) //we'll give wood and ore
  632. {
  633. r.res[0] += 1;
  634. r.res[2] += 1;
  635. }
  636. else
  637. {
  638. r.res[(**j).town->primaryRes] += 1;
  639. }
  640. }
  641. if(gs->getDate(1)==7) //first day of week
  642. {
  643. SetAvailableCreatures sac;
  644. sac.tid = (**j).id;
  645. sac.creatures = (**j).strInfo.creatures;
  646. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  647. {
  648. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  649. sac.creatures[k] += (**j).creatureGrowth(k);
  650. }
  651. n.cres.push_back(sac);
  652. }
  653. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  654. r.res[6] += (**j).dailyIncome();
  655. }
  656. n.res.push_back(r);
  657. }
  658. sendAndApply(&n);
  659. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  660. handleTimeEvents();
  661. //call objects
  662. for(size_t i = 0; i<gs->map->objects.size(); i++)
  663. if(gs->map->objects[i])
  664. gs->map->objects[i]->newTurn();
  665. }
  666. void CGameHandler::run(bool resume)
  667. {
  668. BOOST_FOREACH(CConnection *cc, conns)
  669. {//init conn.
  670. ui8 quantity, pom;
  671. //ui32 seed;
  672. if(!resume)
  673. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  674. (*cc) >> quantity; //how many players will be handled at that client
  675. for(int i=0;i<quantity;i++)
  676. {
  677. (*cc) >> pom; //read player color
  678. {
  679. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  680. connections[pom] = cc;
  681. }
  682. }
  683. }
  684. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  685. {
  686. std::set<int> pom;
  687. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  688. if(j->second == *i)
  689. pom.insert(j->first);
  690. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  691. }
  692. while (!end2)
  693. {
  694. if(!resume)
  695. newTurn();
  696. else
  697. resume = false;
  698. std::map<ui8,PlayerState>::iterator i;
  699. if(!resume)
  700. i = gs->players.begin();
  701. else
  702. i = gs->players.find(gs->currentPlayer);
  703. for(; i != gs->players.end(); i++)
  704. {
  705. if((i->second.towns.size()==0 && i->second.heroes.size()==0) || i->second.color<0 || i->first>=PLAYER_LIMIT ) continue; //players has not towns/castle - loser
  706. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  707. gs->currentPlayer = i->first;
  708. {
  709. YourTurn yt;
  710. yt.player = i->first;
  711. boost::unique_lock<boost::mutex> lock(*connections[i->first]->wmx);
  712. *connections[i->first] << &yt;
  713. }
  714. //wait till turn is done
  715. boost::unique_lock<boost::mutex> lock(states.mx);
  716. while(states.players[i->first].makingTurn && !end2)
  717. {
  718. boost::posix_time::time_duration p;
  719. p = boost::posix_time::milliseconds(200);
  720. states.cv.timed_wait(lock,p);
  721. }
  722. }
  723. }
  724. }
  725. namespace CGH
  726. {
  727. using namespace std;
  728. void readItTo(ifstream & input, vector< vector<int> > & dest)
  729. {
  730. for(int j=0; j<7; ++j)
  731. {
  732. std::vector<int> pom;
  733. for(int g=0; g<j+1; ++g)
  734. {
  735. int hlp; input>>hlp;
  736. pom.push_back(hlp);
  737. }
  738. dest.push_back(pom);
  739. }
  740. }
  741. }
  742. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  743. {
  744. battleResult.set(NULL);
  745. std::vector<CStack*> & stacks = (curB->stacks);
  746. curB->tile = tile;
  747. curB->siege = 0; //TODO: add sieges
  748. curB->army1=army1;
  749. curB->army2=army2;
  750. curB->hero1=(hero1)?(hero1->id):(-1);
  751. curB->hero2=(hero2)?(hero2->id):(-1);
  752. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  753. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  754. curB->round = -2;
  755. curB->activeStack = -1;
  756. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  757. {
  758. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  759. if(hero1)
  760. {
  761. stacks.back()->speed += hero1->valOfBonuses(HeroBonus::STACKS_SPEED);
  762. //base luck/morale calculations
  763. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  764. stacks.back()->morale = hero1->getCurrentMorale(i->first,false);
  765. stacks.back()->luck = hero1->getCurrentLuck(i->first,false);
  766. stacks.back()->attack += hero1->getPrimSkillLevel(0);
  767. stacks.back()->defense += hero1->getPrimSkillLevel(1);
  768. }
  769. else
  770. {
  771. stacks.back()->morale = 0;
  772. stacks.back()->luck = 0;
  773. }
  774. stacks[stacks.size()-1]->ID = stacks.size()-1;
  775. }
  776. //initialization of positions
  777. std::ifstream positions;
  778. positions.open("config" PATHSEPARATOR "battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  779. if(!positions.is_open())
  780. {
  781. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  782. }
  783. std::string dump;
  784. positions>>dump; positions>>dump;
  785. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight;
  786. CGH::readItTo(positions, attackerLoose);
  787. positions>>dump;
  788. CGH::readItTo(positions, defenderLoose);
  789. positions>>dump;
  790. positions>>dump;
  791. CGH::readItTo(positions, attackerTight);
  792. positions>>dump;
  793. CGH::readItTo(positions, defenderTight);
  794. positions.close();
  795. if(army1.formation)
  796. for(int b=0; b<army1.slots.size(); ++b) //tight
  797. {
  798. stacks[b]->position = attackerTight[army1.slots.size()-1][b];
  799. }
  800. else
  801. for(int b=0; b<army1.slots.size(); ++b) //loose
  802. {
  803. stacks[b]->position = attackerLoose[army1.slots.size()-1][b];
  804. }
  805. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  806. {
  807. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  808. //base luck/morale calculations
  809. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  810. if(hero2)
  811. {
  812. stacks.back()->speed += hero2->valOfBonuses(HeroBonus::STACKS_SPEED);
  813. stacks.back()->morale = hero2->getCurrentMorale(i->first,false);
  814. stacks.back()->luck = hero2->getCurrentLuck(i->first,false);
  815. stacks.back()->attack += hero2->getPrimSkillLevel(0);
  816. stacks.back()->defense += hero2->getPrimSkillLevel(1);
  817. }
  818. else
  819. {
  820. stacks.back()->morale = 0;
  821. stacks.back()->luck = 0;
  822. }
  823. }
  824. if(army2.formation)
  825. for(int b=0; b<army2.slots.size(); ++b) //tight
  826. {
  827. stacks[b+army1.slots.size()]->position = defenderTight[army2.slots.size()-1][b];
  828. }
  829. else
  830. for(int b=0; b<army2.slots.size(); ++b) //loose
  831. {
  832. stacks[b+army1.slots.size()]->position = defenderLoose[army2.slots.size()-1][b];
  833. }
  834. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  835. {
  836. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  837. {
  838. stacks[g]->position += 1;
  839. }
  840. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  841. {
  842. stacks[g]->position -= 1;
  843. }
  844. }
  845. //adding war machines
  846. if(hero1)
  847. {
  848. if(hero1->getArt(13)) //ballista
  849. {
  850. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero1->tempOwner, stacks.size(), true, 255));
  851. stacks[stacks.size()-1]->position = 52;
  852. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  853. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  854. }
  855. if(hero1->getArt(14)) //ammo cart
  856. {
  857. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero1->tempOwner, stacks.size(), true, 255));
  858. stacks[stacks.size()-1]->position = 18;
  859. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  860. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  861. }
  862. if(hero1->getArt(15)) //first aid tent
  863. {
  864. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero1->tempOwner, stacks.size(), true, 255));
  865. stacks[stacks.size()-1]->position = 154;
  866. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  867. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  868. }
  869. }
  870. if(hero2)
  871. {
  872. if(hero2->getArt(13)) //ballista
  873. {
  874. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero2->tempOwner, stacks.size(), false, 255));
  875. stacks[stacks.size()-1]->position = 66;
  876. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  877. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  878. }
  879. if(hero2->getArt(14)) //ammo cart
  880. {
  881. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero2->tempOwner, stacks.size(), false, 255));
  882. stacks[stacks.size()-1]->position = 32;
  883. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  884. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  885. }
  886. if(hero2->getArt(15)) //first aid tent
  887. {
  888. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero2->tempOwner, stacks.size(), false, 255));
  889. stacks[stacks.size()-1]->position = 168;
  890. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  891. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  892. }
  893. }
  894. //war machiens added
  895. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  896. //randomize obstacles
  897. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  898. std::vector<int> possibleObstacles;
  899. for(int i=0; i<BFIELD_SIZE; ++i)
  900. {
  901. if(i%17 < 4 || i%17 > 12)
  902. {
  903. obAv[i] = false;
  904. }
  905. else
  906. {
  907. obAv[i] = true;
  908. }
  909. }
  910. int terType = gs->battleGetBattlefieldType(tile);
  911. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  912. {
  913. 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
  914. {
  915. possibleObstacles.push_back(g->first);
  916. }
  917. }
  918. srand(time(NULL));
  919. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  920. {
  921. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  922. while(toBlock>0)
  923. {
  924. CObstacleInstance coi;
  925. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  926. coi.pos = rand()%BFIELD_SIZE;
  927. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  928. bool badObstacle = false;
  929. for(int b=0; b<block.size(); ++b)
  930. {
  931. if(!obAv[block[b]])
  932. {
  933. badObstacle = true;
  934. break;
  935. }
  936. }
  937. if(badObstacle) continue;
  938. //obstacle can be placed
  939. curB->obstacles.push_back(coi);
  940. for(int b=0; b<block.size(); ++b)
  941. {
  942. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  943. obAv[block[b]] = false;
  944. }
  945. toBlock -= block.size();
  946. }
  947. }
  948. //block engaged players
  949. if(hero1->tempOwner<PLAYER_LIMIT)
  950. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  951. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  952. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  953. //send info about battles
  954. BattleStart bs;
  955. bs.info = curB;
  956. sendAndApply(&bs);
  957. }
  958. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  959. {
  960. //checking winning condition
  961. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  962. hasStack[0] = hasStack[1] = false;
  963. for(int b = 0; b<stacks.size(); ++b)
  964. {
  965. if(stacks[b]->alive() && !vstd::contains(stacks[b]->abilities,SIEGE_WEAPON))
  966. {
  967. hasStack[1-stacks[b]->attackerOwned] = true;
  968. }
  969. }
  970. if(!hasStack[0] || !hasStack[1]) //somebody has won
  971. {
  972. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  973. br->result = 0;
  974. br->winner = hasStack[1]; //fleeing side loses
  975. gs->curB->calculateCasualties(br->casualties);
  976. battleResult.set(br);
  977. }
  978. }
  979. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  980. {
  981. if(!vstd::contains(h->artifWorn,17))
  982. return; //hero hasn't spellbok
  983. ChangeSpells cs;
  984. cs.hid = h->id;
  985. cs.learn = true;
  986. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  987. {
  988. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  989. {
  990. if(!vstd::contains(h->spells,t->spells[i][j]))
  991. cs.spells.insert(t->spells[i][j]);
  992. }
  993. }
  994. if(cs.spells.size())
  995. sendAndApply(&cs);
  996. }
  997. void CGameHandler::setBlockVis(int objid, bool bv)
  998. {
  999. SetObjectProperty sop(objid,2,bv);
  1000. sendAndApply(&sop);
  1001. }
  1002. bool CGameHandler::removeObject( int objid )
  1003. {
  1004. if(!getObj(objid))
  1005. {
  1006. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1007. return false;
  1008. }
  1009. RemoveObject ro;
  1010. ro.id = objid;
  1011. sendAndApply(&ro);
  1012. return true;
  1013. }
  1014. void CGameHandler::setAmount(int objid, ui32 val)
  1015. {
  1016. SetObjectProperty sop(objid,3,val);
  1017. sendAndApply(&sop);
  1018. }
  1019. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1020. {
  1021. bool blockvis = false;
  1022. const CGHeroInstance *h = getHero(hid);
  1023. 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)
  1024. )
  1025. {
  1026. tlog1 << "Illegal call to move hero!\n";
  1027. return false;
  1028. }
  1029. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1030. int3 hmpos = dst + int3(-1,0,0);
  1031. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1032. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1033. //result structure for start - movement failed, no move points used
  1034. TryMoveHero tmh;
  1035. tmh.id = hid;
  1036. tmh.start = h->pos;
  1037. tmh.end = dst;
  1038. tmh.result = 0;
  1039. tmh.movePoints = h->movement;
  1040. //check if destination tile is available
  1041. if( t.tertype == rock
  1042. || (!h->canWalkOnSea() && t.tertype == water)
  1043. || (t.blocked && !t.visitable) //tile is blocked andnot visitable
  1044. )
  1045. {
  1046. tlog2 << "Cannot move hero, destination tile is blocked!\n";
  1047. sendAndApply(&tmh);
  1048. return false;
  1049. }
  1050. //checks for standard movement
  1051. if(!instant)
  1052. {
  1053. if( (distance(h->pos,dst)>=1.5) //tiles are not neighouring
  1054. || (h->movement < cost && h->movement < 100) //lack of movement points
  1055. )
  1056. {
  1057. tlog2 << "Cannot move hero, not enough move points or tiles are not neighbouring!\n";
  1058. sendAndApply(&tmh);
  1059. return false;
  1060. }
  1061. //check if there is blocking visitable object
  1062. blockvis = false;
  1063. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1064. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1065. {
  1066. if(obj != h && obj->blockVisit)
  1067. {
  1068. blockvis = true;
  1069. break;
  1070. }
  1071. }
  1072. //we start moving
  1073. if(blockvis)//interaction with blocking object (like resources)
  1074. {
  1075. sendAndApply(&tmh);
  1076. //failed to move to that tile but we visit object
  1077. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1078. {
  1079. if (obj->blockVisit)
  1080. {
  1081. obj->onHeroVisit(h);
  1082. }
  1083. }
  1084. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1085. return true;
  1086. }
  1087. else //normal move
  1088. {
  1089. tmh.result = 1;
  1090. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1091. {
  1092. obj->onHeroLeave(h);
  1093. }
  1094. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1095. sendAndApply(&tmh);
  1096. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1097. //call objects if they are visited
  1098. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1099. {
  1100. obj->onHeroVisit(h);
  1101. }
  1102. }
  1103. tlog5 << "Movement end!\n";
  1104. return true;
  1105. }
  1106. else //instant move - teleportation
  1107. {
  1108. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1109. {
  1110. if(obj->ID==HEROI_TYPE)
  1111. {
  1112. if(obj->tempOwner==h->tempOwner)
  1113. return true;//TODO: exchange
  1114. //TODO: check for ally
  1115. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1116. startBattleI(&h->army,&dh->army,dst,h,dh,0);
  1117. return true;
  1118. }
  1119. }
  1120. tmh.result = instant+1;
  1121. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1122. sendAndApply(&tmh);
  1123. return true;
  1124. }
  1125. }
  1126. void CGameHandler::setOwner(int objid, ui8 owner)
  1127. {
  1128. SetObjectProperty sop(objid,1,owner);
  1129. sendAndApply(&sop);
  1130. }
  1131. void CGameHandler::setHoverName(int objid, MetaString* name)
  1132. {
  1133. SetHoverName shn(objid, *name);
  1134. sendAndApply(&shn);
  1135. }
  1136. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1137. {
  1138. sendToAllClients(iw);
  1139. }
  1140. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1141. {
  1142. ask(iw,iw->player,callback);
  1143. }
  1144. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1145. {
  1146. //TODO
  1147. //gsm.lock();
  1148. //int query = QID++;
  1149. //states.addQuery(player,query);
  1150. //sendToAllClients(iw);
  1151. //gsm.unlock();
  1152. //ui32 ret = getQueryResult(iw->player, query);
  1153. //gsm.lock();
  1154. //states.removeQuery(player, query);
  1155. //gsm.unlock();
  1156. return 0;
  1157. }
  1158. int CGameHandler::getCurrentPlayer()
  1159. {
  1160. return gs->currentPlayer;
  1161. }
  1162. void CGameHandler::giveResource(int player, int which, int val)
  1163. {
  1164. SetResource sr;
  1165. sr.player = player;
  1166. sr.resid = which;
  1167. sr.val = (gs->players.find(player)->second.resources[which]+val);
  1168. sendAndApply(&sr);
  1169. }
  1170. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1171. {
  1172. sendToAllClients(comp);
  1173. }
  1174. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1175. {
  1176. HeroVisitCastle vc;
  1177. vc.hid = heroID;
  1178. vc.tid = obj;
  1179. vc.flags |= 1;
  1180. sendAndApply(&vc);
  1181. giveSpells(getTown(obj),getHero(heroID));
  1182. }
  1183. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1184. {
  1185. HeroVisitCastle vc;
  1186. vc.hid = heroID;
  1187. vc.tid = obj;
  1188. sendAndApply(&vc);
  1189. }
  1190. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1191. {
  1192. const CGHeroInstance* h = getHero(hid);
  1193. const CArtifact &art = VLC->arth->artifacts[artid];
  1194. SetHeroArtifacts sha;
  1195. sha.hid = hid;
  1196. sha.artifacts = h->artifacts;
  1197. sha.artifWorn = h->artifWorn;
  1198. if(position<0)
  1199. {
  1200. if(position == -2)
  1201. {
  1202. int i;
  1203. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1204. {
  1205. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1206. {
  1207. //we've found a free suitable slot
  1208. sha.artifWorn[art.possibleSlots[i]] = artid;
  1209. break;
  1210. }
  1211. }
  1212. if(i == art.possibleSlots.size()) //if haven't find proper slot, use backpack
  1213. sha.artifacts.push_back(artid);
  1214. }
  1215. else //should be -1 => put artifact into backpack
  1216. {
  1217. sha.artifacts.push_back(artid);
  1218. }
  1219. }
  1220. else
  1221. {
  1222. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1223. {
  1224. sha.artifWorn[position] = artid;
  1225. }
  1226. else
  1227. {
  1228. sha.artifacts.push_back(artid);
  1229. }
  1230. }
  1231. sendAndApply(&sha);
  1232. }
  1233. void CGameHandler::startBattleI(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb) //use hero=NULL for no hero
  1234. {
  1235. boost::thread(boost::bind(&CGameHandler::startBattle,this,*const_cast<CCreatureSet *>(army1),*const_cast<CCreatureSet *>(army2),tile,const_cast<CGHeroInstance *>(hero1), const_cast<CGHeroInstance *>(hero2),cb));
  1236. }
  1237. void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1238. {
  1239. CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1240. startBattleI(&h->army,&army,tile,h,NULL,cb);
  1241. //battle(&h->army,army,tile,h,NULL);
  1242. }
  1243. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1244. {
  1245. ChangeSpells cs;
  1246. cs.hid = hid;
  1247. cs.spells = spells;
  1248. cs.learn = give;
  1249. sendAndApply(&cs);
  1250. }
  1251. int CGameHandler::getSelectedHero()
  1252. {
  1253. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1254. }
  1255. void CGameHandler::setObjProperty( int objid, int prop, int val )
  1256. {
  1257. SetObjectProperty sob;
  1258. sob.id = objid;
  1259. sob.what = prop;
  1260. sob.val = val;
  1261. sendAndApply(&sob);
  1262. }
  1263. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1264. {
  1265. SystemMessage sm;
  1266. sm.text = message;
  1267. c << &sm;
  1268. }
  1269. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1270. {
  1271. sendAndApply(bonus);
  1272. }
  1273. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1274. {
  1275. sendAndApply(smp);
  1276. }
  1277. void CGameHandler::setManaPoints( int hid, int val )
  1278. {
  1279. SetMana sm;
  1280. sm.hid = hid;
  1281. sm.val = val;
  1282. sendAndApply(&sm);
  1283. }
  1284. void CGameHandler::giveHero( int id, int player )
  1285. {
  1286. GiveHero gh;
  1287. gh.id = id;
  1288. gh.player = player;
  1289. sendAndApply(&gh);
  1290. }
  1291. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1292. {
  1293. ChangeObjPos cop;
  1294. cop.objid = objid;
  1295. cop.nPos = newPos;
  1296. cop.flags = flags;
  1297. sendAndApply(&cop);
  1298. }
  1299. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1300. {
  1301. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1302. sel->id = QID;
  1303. callbacks[QID] = callback;
  1304. states.addQuery(player,QID);
  1305. QID++;
  1306. sendAndApply(sel);
  1307. }
  1308. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1309. {
  1310. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1311. sel->id = QID;
  1312. callbacks[QID] = callback;
  1313. states.addQuery(player,QID);
  1314. sendToAllClients(sel);
  1315. QID++;
  1316. }
  1317. void CGameHandler::sendToAllClients( CPackForClient * info )
  1318. {
  1319. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1320. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1321. {
  1322. (*i)->wmx->lock();
  1323. **i << info;
  1324. (*i)->wmx->unlock();
  1325. }
  1326. }
  1327. void CGameHandler::sendAndApply( CPackForClient * info )
  1328. {
  1329. gs->apply(info);
  1330. sendToAllClients(info);
  1331. }
  1332. void CGameHandler::save( const std::string &fname )
  1333. {
  1334. {
  1335. tlog0 << "Ordering clients to serialize...\n";
  1336. SaveGame sg(fname);
  1337. //TODO: uncomment when client saving is ready
  1338. //sendToAllClients(&sg);
  1339. }
  1340. {
  1341. tlog0 << "Serializing game info...\n";
  1342. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vlgm1");
  1343. char hlp[8] = "VCMISVG";
  1344. save << hlp << version << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  1345. }
  1346. {
  1347. tlog0 << "Serializing server info...\n";
  1348. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vsgm1");
  1349. save << *this;
  1350. }
  1351. tlog0 << "Game has been succesfully saved!\n";
  1352. }
  1353. void CGameHandler::close()
  1354. {
  1355. tlog0 << "We have been requested to close.\n";
  1356. //BOOST_FOREACH(CConnection *cc, conns)
  1357. // if(cc && cc->socket && cc->socket->is_open())
  1358. // cc->socket->close();
  1359. //exit(0);
  1360. }
  1361. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val )
  1362. {
  1363. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  1364. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  1365. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  1366. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  1367. if(!isAllowedExchange(id1,id2))
  1368. {
  1369. complain("Cannot exchange stacks between these two objects!\n");
  1370. return false;
  1371. }
  1372. if(what==1) //swap
  1373. {
  1374. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  1375. //if one of them is empty, remove entry
  1376. if(!S1.slots[p1].second)
  1377. S1.slots.erase(p1);
  1378. if(!S2.slots[p2].second)
  1379. S2.slots.erase(p2);
  1380. }
  1381. else if(what==2)//merge
  1382. {
  1383. if(S1.slots[p1].first != S2.slots[p2].first) //not same creature
  1384. {
  1385. complain("Cannot merge different creatures stacks!");
  1386. return false;
  1387. }
  1388. S2.slots[p2].second += S1.slots[p1].second;
  1389. S1.slots.erase(p1);
  1390. }
  1391. else if(what==3) //split
  1392. {
  1393. //general conditions checking
  1394. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1395. || (val<1 && complain("no creatures to split")) )
  1396. {
  1397. return false;
  1398. }
  1399. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1400. {
  1401. int total = S1.slots[p1].second + S2.slots[p2].second;
  1402. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1403. || (S2.slots[p2].first != S1.slots[p1].first && complain("Cannot rebalance different creatures stacks!"))
  1404. )
  1405. {
  1406. return false;
  1407. }
  1408. S2.slots[p2].second = val;
  1409. S1.slots[p1].second = total - val;
  1410. }
  1411. else //split one stack to the two
  1412. {
  1413. if(S1.slots[p1].second < val)//not enough creatures
  1414. {
  1415. complain("Cannot split that stack, not enough creatures!");
  1416. return false;
  1417. }
  1418. S2.slots[p2].first = S1.slots[p1].first;
  1419. S2.slots[p2].second = val;
  1420. S1.slots[p1].second -= val;
  1421. }
  1422. if(!S1.slots[p1].second) //if we've moved all creatures
  1423. S1.slots.erase(p1);
  1424. }
  1425. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  1426. || (s2->needsLastStack() && !S2.slots.size())
  1427. )
  1428. {
  1429. complain("Cannot take the last stack!");
  1430. return false; //leave without applying changes to garrison
  1431. }
  1432. //apply changes
  1433. SetGarrisons sg;
  1434. sg.garrs[id1] = S1;
  1435. if(s1 != s2)
  1436. sg.garrs[id2] = S2;
  1437. sendAndApply(&sg);
  1438. return true;
  1439. }
  1440. int CGameHandler::getPlayerAt( CConnection *c ) const
  1441. {
  1442. std::set<int> all;
  1443. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1444. if(i->second == c)
  1445. all.insert(i->first);
  1446. switch(all.size())
  1447. {
  1448. case 0:
  1449. return 255;
  1450. case 1:
  1451. return *all.begin();
  1452. default:
  1453. {
  1454. //if we have more than one player at this connection, try to pick active one
  1455. if(vstd::contains(all,int(gs->currentPlayer)))
  1456. return gs->currentPlayer;
  1457. else
  1458. return 253; //cannot say which player is it
  1459. }
  1460. }
  1461. }
  1462. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  1463. {
  1464. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  1465. if(!vstd::contains(s1->army.slots,pos))
  1466. {
  1467. complain("Illegal call to disbandCreature - no such stack in army!");
  1468. return false;
  1469. }
  1470. s1->army.slots.erase(pos);
  1471. SetGarrisons sg;
  1472. sg.garrs[id] = s1->army;
  1473. sendAndApply(&sg);
  1474. return true;
  1475. }
  1476. bool CGameHandler::buildStructure( si32 tid, si32 bid )
  1477. {
  1478. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1479. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  1480. if(gs->canBuildStructure(t,bid) != 7)
  1481. {
  1482. complain("Cannot build that building!");
  1483. return false;
  1484. }
  1485. NewStructures ns;
  1486. ns.tid = tid;
  1487. if(bid>36) //upg dwelling
  1488. {
  1489. if(t->getHordeLevel(0) == (bid-37))
  1490. ns.bid.insert(19);
  1491. else if(t->getHordeLevel(1) == (bid-37))
  1492. ns.bid.insert(25);
  1493. }
  1494. else if(bid >= 30) //bas. dwelling
  1495. {
  1496. SetAvailableCreatures ssi;
  1497. ssi.tid = tid;
  1498. ssi.creatures = t->strInfo.creatures;
  1499. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  1500. sendAndApply(&ssi);
  1501. }
  1502. ns.bid.insert(bid);
  1503. ns.builded = t->builded + 1;
  1504. sendAndApply(&ns);
  1505. SetResources sr;
  1506. sr.player = t->tempOwner;
  1507. sr.res = gs->getPlayer(t->tempOwner)->resources;
  1508. for(int i=0;i<7;i++)
  1509. sr.res[i]-=b->resources[i];
  1510. sendAndApply(&sr);
  1511. if(bid<5) //it's mage guild
  1512. {
  1513. if(t->visitingHero)
  1514. giveSpells(t,t->visitingHero);
  1515. if(t->garrisonHero)
  1516. giveSpells(t,t->garrisonHero);
  1517. }
  1518. return true;
  1519. }
  1520. void CGameHandler::sendMessageToAll( const std::string &message )
  1521. {
  1522. SystemMessage sm;
  1523. sm.text = message;
  1524. sendToAllClients(&sm);
  1525. }
  1526. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  1527. {
  1528. si32 ser = -1;
  1529. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  1530. //verify
  1531. bool found = false;
  1532. typedef std::pair<const int,int> Parka;
  1533. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  1534. {
  1535. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  1536. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  1537. {
  1538. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  1539. ser = av->first;
  1540. break;
  1541. }
  1542. }
  1543. int slot = t->army.getSlotFor(crid);
  1544. if(!found && complain("Cannot recruit: no such creatures!")
  1545. || cram > VLC->creh->creatures[crid].maxAmount(gs->getPlayer(t->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  1546. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  1547. || slot<0 && complain("Cannot recruit: no available slot!"))
  1548. {
  1549. return false;
  1550. }
  1551. //recruit
  1552. SetResources sr;
  1553. sr.player = t->tempOwner;
  1554. for(int i=0;i<RESOURCE_QUANTITY;i++)
  1555. sr.res[i] = gs->getPlayer(t->tempOwner)->resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  1556. SetAvailableCreatures sac;
  1557. sac.tid = objid;
  1558. sac.creatures = t->strInfo.creatures;
  1559. sac.creatures[ser] -= cram;
  1560. SetGarrisons sg;
  1561. sg.garrs[objid] = t->army;
  1562. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  1563. {
  1564. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  1565. }
  1566. else //add creatures to a already existing stack
  1567. {
  1568. sg.garrs[objid].slots[slot].second += cram;
  1569. }
  1570. sendAndApply(&sr);
  1571. sendAndApply(&sac);
  1572. sendAndApply(&sg);
  1573. return true;
  1574. }
  1575. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  1576. {
  1577. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  1578. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  1579. int player = obj->tempOwner;
  1580. int crQuantity = obj->army.slots[pos].second;
  1581. //check if upgrade is possible
  1582. if((ui.oldID<0 || !vstd::contains(ui.newID,upgID)) && complain("That upgrade is not possible!"))
  1583. {
  1584. return false;
  1585. }
  1586. //check if player has enough resources
  1587. for(int i=0;i<ui.cost.size();i++)
  1588. {
  1589. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1590. {
  1591. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  1592. {
  1593. complain("Cannot upgrade, not enough resources!");
  1594. return false;
  1595. }
  1596. }
  1597. }
  1598. //take resources
  1599. for(int i=0;i<ui.cost.size();i++)
  1600. {
  1601. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1602. {
  1603. SetResource sr;
  1604. sr.player = player;
  1605. sr.resid = j->first;
  1606. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  1607. sendAndApply(&sr);
  1608. }
  1609. }
  1610. //upgrade creature
  1611. SetGarrisons sg;
  1612. sg.garrs[objid] = obj->army;
  1613. sg.garrs[objid].slots[pos].first = upgID;
  1614. sendAndApply(&sg);
  1615. return true;
  1616. }
  1617. bool CGameHandler::garrisonSwap( si32 tid )
  1618. {
  1619. CGTownInstance *town = gs->getTown(tid);
  1620. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  1621. {
  1622. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  1623. while(!cso.slots.empty())//while there are unmoved creatures
  1624. {
  1625. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  1626. if(pos<0)
  1627. {
  1628. complain("Cannot make garrison swap, not enough free slots!");
  1629. return false;
  1630. }
  1631. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  1632. {
  1633. csn.slots[pos].second += cso.slots.begin()->second.second;
  1634. }
  1635. else //move stack on the free pos
  1636. {
  1637. csn.slots[pos].first = cso.slots.begin()->second.first;
  1638. csn.slots[pos].second = cso.slots.begin()->second.second;
  1639. }
  1640. cso.slots.erase(cso.slots.begin());
  1641. }
  1642. SetGarrisons sg;
  1643. sg.garrs[town->visitingHero->id] = csn;
  1644. sg.garrs[town->id] = csn;
  1645. sendAndApply(&sg);
  1646. SetHeroesInTown intown;
  1647. intown.tid = tid;
  1648. intown.visiting = -1;
  1649. intown.garrison = town->visitingHero->id;
  1650. sendAndApply(&intown);
  1651. return true;
  1652. }
  1653. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  1654. {
  1655. //check if moving hero out of town will break 8 wandering heroes limit
  1656. if(getHeroCount(town->garrisonHero->tempOwner,true) >= 8)
  1657. {
  1658. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  1659. return false;
  1660. }
  1661. SetHeroesInTown intown;
  1662. intown.tid = tid;
  1663. intown.garrison = -1;
  1664. intown.visiting = town->garrisonHero->id;
  1665. sendAndApply(&intown);
  1666. //town will be empty
  1667. SetGarrisons sg;
  1668. sg.garrs[tid] = CCreatureSet();
  1669. sendAndApply(&sg);
  1670. return true;
  1671. }
  1672. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  1673. {
  1674. SetGarrisons sg;
  1675. sg.garrs[town->id] = town->visitingHero->army;
  1676. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  1677. SetHeroesInTown intown;
  1678. intown.tid = tid;
  1679. intown.garrison = town->visitingHero->id;
  1680. intown.visiting = town->garrisonHero->id;
  1681. sendAndApply(&intown);
  1682. sendAndApply(&sg);
  1683. return true;
  1684. }
  1685. else
  1686. {
  1687. complain("Cannot swap garrison hero!");
  1688. return false;
  1689. }
  1690. }
  1691. bool CGameHandler::swapArtifacts( si32 hid1, si32 hid2, ui16 slot1, ui16 slot2 )
  1692. {
  1693. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  1694. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  1695. return false;
  1696. const CArtifact *a1 = h1->getArt(slot1),
  1697. *a2=h2->getArt(slot2);
  1698. if(a1 && slot2<19 && !vstd::contains(a1->possibleSlots,slot2)
  1699. || a2 && slot1<19 && !vstd::contains(a2->possibleSlots,slot1)
  1700. )
  1701. {
  1702. //artifact doesn't fit dst slot
  1703. complain("Cannot swap artifacts!");
  1704. return false;
  1705. }
  1706. SetHeroArtifacts sha;
  1707. sha.hid = hid1;
  1708. sha.artifacts = h1->artifacts;
  1709. sha.artifWorn = h1->artifWorn;
  1710. sha.setArtAtPos(slot1,h2->getArtAtPos(slot2));
  1711. if(h1 == h2) sha.setArtAtPos(slot2,h1->getArtAtPos(slot1));
  1712. sendAndApply(&sha);
  1713. if(hid1 != hid2)
  1714. {
  1715. sha.hid = hid2;
  1716. sha.artifacts = h2->artifacts;
  1717. sha.artifWorn = h2->artifWorn;
  1718. sha.setArtAtPos(slot2,h1->getArtAtPos(slot1));
  1719. sendAndApply(&sha);
  1720. }
  1721. return true;
  1722. }
  1723. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  1724. {
  1725. CGHeroInstance *hero = gs->getHero(hid);
  1726. CGTownInstance *town = hero->visitedTown;
  1727. if(aid==0) //spellbook
  1728. {
  1729. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  1730. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  1731. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  1732. )
  1733. return false;
  1734. giveResource(hero->getOwner(),6,-500);
  1735. giveHeroArtifact(0,hid,17);
  1736. giveSpells(town,hero);
  1737. return true;
  1738. }
  1739. else if(aid < 7 && aid > 3) //war machine
  1740. {
  1741. int price = VLC->arth->artifacts[aid].price;
  1742. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  1743. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  1744. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  1745. || town->town->warMachine!= aid && complain("This machine is unavailale here!") ) //TODO: ballista yard in Stronghold
  1746. {
  1747. return false;
  1748. }
  1749. giveResource(hero->getOwner(),6,-price);
  1750. giveHeroArtifact(aid,hid,9+aid);
  1751. return true;
  1752. }
  1753. return false;
  1754. }
  1755. bool CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  1756. {
  1757. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  1758. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  1759. uzysk /= gs->resVals[id2];
  1760. SetResource sr;
  1761. sr.player = player;
  1762. sr.resid = id1;
  1763. sr.val = gs->getPlayer(player)->resources[id1] - val;
  1764. sendAndApply(&sr);
  1765. sr.resid = id2;
  1766. sr.val = gs->getPlayer(player)->resources[id2] + (int)uzysk;
  1767. sendAndApply(&sr);
  1768. return true;
  1769. }
  1770. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  1771. {
  1772. gs->getHero(hid)->army.formation = formation;
  1773. return true;
  1774. }
  1775. bool CGameHandler::hireHero( ui32 tid, ui8 hid )
  1776. {
  1777. CGTownInstance *t = gs->getTown(tid);
  1778. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  1779. || gs->getPlayer(t->tempOwner)->resources[6]<2500 && complain("Not enough gold for buying hero!")
  1780. || t->visitingHero && complain("There is visiting hero - no place!")
  1781. || getHeroCount(t->tempOwner,false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!")
  1782. )
  1783. return false;
  1784. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  1785. HeroRecruited hr;
  1786. hr.tid = tid;
  1787. hr.hid = nh->subID;
  1788. hr.player = t->tempOwner;
  1789. hr.tile = t->pos - int3(1,0,0);
  1790. sendAndApply(&hr);
  1791. SetAvailableHeroes sah;
  1792. (hid ? sah.hid2 : sah.hid1) = gs->hpool.pickHeroFor(false,t->tempOwner,t->town)->subID;
  1793. (hid ? sah.hid1 : sah.hid2) = gs->getPlayer(t->tempOwner)->availableHeroes[!hid]->subID;
  1794. sah.player = t->tempOwner;
  1795. sah.flags = hid+1;
  1796. sendAndApply(&sah);
  1797. SetResource sr;
  1798. sr.player = t->tempOwner;
  1799. sr.resid = 6;
  1800. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  1801. sendAndApply(&sr);
  1802. giveSpells(t,nh);
  1803. return true;
  1804. }
  1805. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  1806. {
  1807. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1808. if(vstd::contains(callbacks,qid))
  1809. {
  1810. CFunctionList<void(ui32)> callb = callbacks[qid];
  1811. callbacks.erase(qid);
  1812. if(callb)
  1813. callb(answer);
  1814. }
  1815. else if(vstd::contains(garrisonCallbacks,qid))
  1816. {
  1817. if(garrisonCallbacks[qid])
  1818. garrisonCallbacks[qid]();
  1819. garrisonCallbacks.erase(qid);
  1820. allowedExchanges.erase(qid);
  1821. }
  1822. else
  1823. {
  1824. tlog1 << "Unknown query reply...\n";
  1825. return false;
  1826. }
  1827. return true;
  1828. }
  1829. bool CGameHandler::makeBattleAction( BattleAction &ba )
  1830. {
  1831. bool ok = true;
  1832. switch(ba.actionType)
  1833. {
  1834. case 2: //walk
  1835. {
  1836. sendAndApply(&StartAction(ba)); //start movement
  1837. moveStack(ba.stackNumber,ba.destinationTile); //move
  1838. sendAndApply(&EndAction());
  1839. break;
  1840. }
  1841. case 3: //defend
  1842. case 8: //wait
  1843. {
  1844. sendAndApply(&StartAction(ba));
  1845. sendAndApply(&EndAction());
  1846. break;
  1847. }
  1848. case 4: //retreat/flee
  1849. {
  1850. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  1851. //TODO: calculate casualties
  1852. //TODO: remove retreating hero from map and place it in recruitment list
  1853. BattleResult *br = new BattleResult;
  1854. br->result = 1;
  1855. br->winner = !ba.side; //fleeing side loses
  1856. gs->curB->calculateCasualties(br->casualties);
  1857. giveExp(*br);
  1858. battleResult.set(br);
  1859. break;
  1860. }
  1861. case 6: //walk or attack
  1862. {
  1863. sendAndApply(&StartAction(ba)); //start movement and attack
  1864. moveStack(ba.stackNumber,ba.destinationTile);
  1865. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1866. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  1867. if(curStack->position != ba.destinationTile) //we wasn't able to reach destination tile
  1868. {
  1869. tlog3<<"We cannot move this stack to its destination "<<curStack->creature->namePl<<std::endl;
  1870. ok = false;
  1871. }
  1872. if(!stackAtEnd)
  1873. {
  1874. tlog3 << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  1875. ok = false;
  1876. break;
  1877. }
  1878. ui16 curpos = curStack->position,
  1879. enemypos = stackAtEnd->position;
  1880. if( !(
  1881. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  1882. || (curStack->creature->isDoubleWide() //back <=> front
  1883. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  1884. || (stackAtEnd->creature->isDoubleWide() //front <=> back
  1885. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1886. || (stackAtEnd->creature->isDoubleWide() && curStack->creature->isDoubleWide()//back <=> back
  1887. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1888. )
  1889. )
  1890. {
  1891. tlog3 << "Attack cannot be performed!";
  1892. sendAndApply(&EndAction());
  1893. ok = false;
  1894. }
  1895. //attack
  1896. BattleAttack bat;
  1897. prepareAttack(bat,curStack,stackAtEnd);
  1898. sendAndApply(&bat);
  1899. //counterattack
  1900. if(!vstd::contains(curStack->abilities,NO_ENEMY_RETALIATION)
  1901. && stackAtEnd->alive()
  1902. && stackAtEnd->counterAttacks
  1903. && !vstd::contains(stackAtEnd->abilities, SIEGE_WEAPON)) //TODO: support for multiple retaliatons per turn
  1904. {
  1905. prepareAttack(bat,stackAtEnd,curStack);
  1906. bat.flags |= 2;
  1907. sendAndApply(&bat);
  1908. }
  1909. //second attack
  1910. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  1911. && curStack->alive()
  1912. && stackAtEnd->alive() )
  1913. {
  1914. bat.flags = 0;
  1915. prepareAttack(bat,curStack,stackAtEnd);
  1916. sendAndApply(&bat);
  1917. }
  1918. sendAndApply(&EndAction());
  1919. break;
  1920. }
  1921. case 7: //shoot
  1922. {
  1923. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1924. *destStack= gs->curB->getStackT(ba.destinationTile);
  1925. if(!curStack //our stack exists
  1926. || !destStack //there is a stack at destination tile
  1927. || !curStack->shots //stack has shots
  1928. || gs->curB->isStackBlocked(curStack->ID) //we are not blocked
  1929. || !vstd::contains(curStack->abilities,SHOOTER) //our stack is shooting unit
  1930. )
  1931. break;
  1932. for(int g=0; g<curStack->effects.size(); ++g)
  1933. {
  1934. if(61 == curStack->effects[g].id) //forgetfulness
  1935. break;
  1936. }
  1937. sendAndApply(&StartAction(ba)); //start shooting
  1938. BattleAttack bat;
  1939. prepareAttack(bat,curStack,destStack);
  1940. bat.flags |= 1;
  1941. sendAndApply(&bat);
  1942. if(vstd::contains(curStack->abilities,TWICE_ATTACK) //if unit shots twice let's make another shot
  1943. && curStack->alive()
  1944. && destStack->alive()
  1945. && curStack->shots
  1946. )
  1947. {
  1948. prepareAttack(bat,curStack,destStack);
  1949. sendAndApply(&bat);
  1950. }
  1951. sendAndApply(&EndAction());
  1952. break;
  1953. }
  1954. }
  1955. battleMadeAction.setn(true);
  1956. return ok;
  1957. }
  1958. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  1959. {
  1960. bool cheated=true;
  1961. sendAndApply(&PlayerMessage(player,message));
  1962. if(message == "vcmiistari") //give all spells and 999 mana
  1963. {
  1964. SetMana sm;
  1965. ChangeSpells cs;
  1966. cs.learn = 1;
  1967. for(int i=0;i<VLC->spellh->spells.size();i++)
  1968. {
  1969. if(!VLC->spellh->spells[i].creatureAbility)
  1970. cs.spells.insert(i);
  1971. }
  1972. sm.hid = cs.hid = gs->players[player].currentSelection;
  1973. sm.val = 999;
  1974. if(gs->getHero(cs.hid))
  1975. {
  1976. sendAndApply(&cs);
  1977. sendAndApply(&sm);
  1978. }
  1979. }
  1980. else if(message == "vcmiainur") //gives 5 archangels into each slot
  1981. {
  1982. SetGarrisons sg;
  1983. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1984. if(!hero) return;
  1985. sg.garrs[hero->id] = hero->army;
  1986. for(int i=0;i<7;i++)
  1987. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  1988. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  1989. sendAndApply(&sg);
  1990. }
  1991. else if(message == "vcmiangband") //gives 10 black knightinto each slot
  1992. {
  1993. SetGarrisons sg;
  1994. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1995. if(!hero) return;
  1996. sg.garrs[hero->id] = hero->army;
  1997. for(int i=0;i<7;i++)
  1998. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  1999. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  2000. sendAndApply(&sg);
  2001. }
  2002. else if(message == "vcminoldor") //all war machines
  2003. {
  2004. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2005. if(!hero) return;
  2006. SetHeroArtifacts sha;
  2007. sha.hid = hero->id;
  2008. sha.artifacts = hero->artifacts;
  2009. sha.artifWorn = hero->artifWorn;
  2010. sha.artifWorn[13] = 4;
  2011. sha.artifWorn[14] = 5;
  2012. sha.artifWorn[15] = 6;
  2013. sendAndApply(&sha);
  2014. }
  2015. else if(message == "vcminahar") //1000000 movement points
  2016. {
  2017. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2018. if(!hero) return;
  2019. SetMovePoints smp;
  2020. smp.hid = hero->id;
  2021. smp.val = 1000000;
  2022. sendAndApply(&smp);
  2023. }
  2024. else if(message == "vcmiformenos") //give resources
  2025. {
  2026. SetResources sr;
  2027. sr.player = player;
  2028. sr.res = gs->getPlayer(player)->resources;
  2029. for(int i=0;i<7;i++)
  2030. sr.res[i] += 100;
  2031. sr.res[6] += 19900;
  2032. sendAndApply(&sr);
  2033. }
  2034. else if(message == "vcmieagles") //reveal FoW
  2035. {
  2036. FoWChange fc;
  2037. fc.player = player;
  2038. for(int i=0;i<gs->map->width;i++)
  2039. for(int j=0;j<gs->map->height;j++)
  2040. for(int k=0;k<gs->map->twoLevel+1;k++)
  2041. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  2042. fc.tiles.insert(int3(i,j,k));
  2043. sendAndApply(&fc);
  2044. }
  2045. else if(message == "vcmiglorfindel")
  2046. {
  2047. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2048. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  2049. }
  2050. else
  2051. cheated = false;
  2052. if(cheated)
  2053. {
  2054. sendAndApply(&SystemMessage("CHEATER!!!"));
  2055. }
  2056. }
  2057. ui32 calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature)
  2058. {
  2059. ui32 ret = 0; //value to return
  2060. switch(sp->id)
  2061. {
  2062. case 15: //magic arrow
  2063. {
  2064. ret = caster->getPrimSkillLevel(2) * 10 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2065. }
  2066. case 16: //ice bolt
  2067. {
  2068. ret = caster->getPrimSkillLevel(2) * 20 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2069. }
  2070. case 17: //lightning bolt
  2071. {
  2072. ret = caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2073. }
  2074. case 18: //implosion
  2075. {
  2076. ret = caster->getPrimSkillLevel(2) * 75 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2077. }
  2078. case 20: //frost ring
  2079. {
  2080. ret = caster->getPrimSkillLevel(2) * 10 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2081. }
  2082. case 21: //fireball
  2083. {
  2084. ret = caster->getPrimSkillLevel(2) * 10 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2085. }
  2086. case 22: //inferno
  2087. {
  2088. ret = caster->getPrimSkillLevel(2) * 10 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2089. }
  2090. case 23: //meteor shower
  2091. {
  2092. ret = caster->getPrimSkillLevel(2) * 10 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2093. }
  2094. case 24: //death ripple
  2095. {
  2096. ret = caster->getPrimSkillLevel(2) * 5 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2097. }
  2098. case 25: //destroy undead
  2099. {
  2100. ret = caster->getPrimSkillLevel(2) * 10 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2101. }
  2102. case 26: //armageddon
  2103. {
  2104. ret = caster->getPrimSkillLevel(2) * 50 + sp->powers[caster->getSpellSchoolLevel(sp)];
  2105. }
  2106. }
  2107. //applying sorcerery secondary skill
  2108. switch(caster->getSecSkillLevel(25))
  2109. {
  2110. case 1: //basic
  2111. ret *= 1.05f;
  2112. break;
  2113. case 2: //advanced
  2114. ret *= 1.1f;
  2115. break;
  2116. case 3: //expert
  2117. ret *= 1.15f;
  2118. break;
  2119. }
  2120. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2121. if(sp->air && affectedCreature->getEffect(30)) //air spell & protection from air
  2122. {
  2123. ret *= VLC->spellh->spells[30].powers[affectedCreature->getEffect(30)->level];
  2124. ret /= 100;
  2125. }
  2126. else if(sp->fire && affectedCreature->getEffect(31)) //fire spell & protection from fire
  2127. {
  2128. ret *= VLC->spellh->spells[31].powers[affectedCreature->getEffect(31)->level];
  2129. ret /= 100;
  2130. }
  2131. else if(sp->water && affectedCreature->getEffect(32)) //water spell & protection from water
  2132. {
  2133. ret *= VLC->spellh->spells[32].powers[affectedCreature->getEffect(32)->level];
  2134. ret /= 100;
  2135. }
  2136. else if (sp->earth && affectedCreature->getEffect(33)) //earth spell & protection from earth
  2137. {
  2138. ret *= VLC->spellh->spells[33].powers[affectedCreature->getEffect(33)->level];
  2139. ret /= 100;
  2140. }
  2141. return ret;
  2142. }
  2143. bool CGameHandler::makeCustomAction( BattleAction &ba )
  2144. {
  2145. switch(ba.actionType)
  2146. {
  2147. case 1: //hero casts spell
  2148. {
  2149. CGHeroInstance *h = (ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  2150. if(!h)
  2151. {
  2152. tlog2 << "Wrong caster!\n";
  2153. return false;
  2154. }
  2155. if(ba.additionalInfo >= VLC->spellh->spells.size())
  2156. {
  2157. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  2158. return false;
  2159. }
  2160. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  2161. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  2162. if( !(vstd::contains(h->spells,ba.additionalInfo)) //hero doesn't know this spell
  2163. || (h->mana < s->costs[skill]) //not enough mana
  2164. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  2165. || (gs->curB->castedSpells[ba.side])
  2166. )
  2167. {
  2168. tlog2 << "Spell cannot be casted!\n";
  2169. return false;
  2170. }
  2171. sendAndApply(&StartAction(ba)); //start spell casting
  2172. //TODO: check resistances
  2173. SpellCasted sc;
  2174. sc.side = ba.side;
  2175. sc.id = ba.additionalInfo;
  2176. sc.skill = skill;
  2177. sc.tile = ba.destinationTile;
  2178. sendAndApply(&sc);
  2179. //calculating affected creatures for all spells ///////////////////
  2180. std::set<ui16> attackedHexes = s->rangeInHexes(ba.destinationTile, h->getSpellSchoolLevel(s));
  2181. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurences of two hex creatures*/
  2182. if(ba.additionalInfo == 24 || ba.additionalInfo == 25 || ba.additionalInfo == 26) //death ripple, destroy undead and armageddon
  2183. {
  2184. for(int it=0; it<gs->curB->stacks.size(); ++it)
  2185. {
  2186. if((ba.additionalInfo == 24 && !gs->curB->stacks[it]->creature->isUndead()) //death ripple
  2187. || (ba.additionalInfo == 25 && gs->curB->stacks[it]->creature->isUndead()) //destroy undead
  2188. || (ba.additionalInfo == 26) //armageddon
  2189. )
  2190. {
  2191. attackedCres.insert(gs->curB->stacks[it]);
  2192. }
  2193. }
  2194. }
  2195. else if(VLC->spellh->spells[ba.additionalInfo].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  2196. {
  2197. if(h->getSpellSchoolLevel(s) < 3) /*not expert */
  2198. {
  2199. CStack * st = gs->curB->getStackT(ba.destinationTile);
  2200. if(st)
  2201. attackedCres.insert(st);
  2202. }
  2203. else
  2204. {
  2205. for(int it=0; it<gs->curB->stacks.size(); ++it)
  2206. {
  2207. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2208. if((VLC->spellh->spells[ba.additionalInfo].positiveness >= 0 && gs->curB->stacks[it]->owner == h->tempOwner)
  2209. ||(VLC->spellh->spells[ba.additionalInfo].positiveness <= 0 && gs->curB->stacks[it]->owner != h->tempOwner )
  2210. )
  2211. {
  2212. attackedCres.insert(gs->curB->stacks[it]);
  2213. }
  2214. }
  2215. } //if(h->getSpellSchoolLevel(s) < 3)
  2216. }
  2217. else if(VLC->spellh->spells[ba.additionalInfo].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2218. {
  2219. CStack * st = gs->curB->getStackT(ba.destinationTile);
  2220. if(st)
  2221. attackedCres.insert(st);
  2222. }
  2223. else //custom range from attackedHexes
  2224. {
  2225. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2226. {
  2227. CStack * st = gs->curB->getStackT(*it);
  2228. if(st)
  2229. attackedCres.insert(st);
  2230. }
  2231. }
  2232. //affected creatures calculated
  2233. //applying effects
  2234. switch(ba.additionalInfo) //spell id
  2235. {
  2236. case 15: //magic arrow
  2237. case 16: //ice bolt
  2238. case 17: //lightning bolt
  2239. case 18: //implosion
  2240. case 20: //frost ring
  2241. case 21: //fireball
  2242. case 22: //inferno
  2243. case 23: //meteor shower
  2244. case 24: //death ripple
  2245. case 25: //destroy undead
  2246. case 26: //armageddon
  2247. {
  2248. StacksInjured si;
  2249. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2250. {
  2251. BattleStackAttacked bsa;
  2252. bsa.flags |= 2;
  2253. bsa.effect = VLC->spellh->spells[ba.additionalInfo].mainEffectAnim;
  2254. bsa.damageAmount = calculateSpellDmg(&VLC->spellh->spells[ba.additionalInfo], h, *it);
  2255. bsa.stackAttacked = (*it)->ID;
  2256. prepareAttacked(bsa,*it);
  2257. si.stacks.insert(bsa);
  2258. }
  2259. sendAndApply(&si);
  2260. break;
  2261. }
  2262. case 27: //shield
  2263. case 28: //air shield
  2264. case 30: //protection from air
  2265. case 31: //protection from fire
  2266. case 32: //protection from water
  2267. case 33: //protection from earth
  2268. case 41: //bless
  2269. case 42: //curse
  2270. case 43: //bloodlust
  2271. case 44: //precision
  2272. case 45: //weakness
  2273. case 46: //stone skin
  2274. case 47: //disrupting ray
  2275. case 48: //prayer
  2276. case 49: //mirth
  2277. case 50: //sorrow
  2278. case 51: //fortune
  2279. case 52: //misfortune
  2280. case 53: //haste
  2281. case 54: //slow
  2282. case 55: //slayer
  2283. case 61: //forgetfulness
  2284. {
  2285. SetStackEffect sse;
  2286. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2287. {
  2288. sse.stacks.insert((*it)->ID);
  2289. }
  2290. sse.effect.id = ba.additionalInfo;
  2291. sse.effect.level = h->getSpellSchoolLevel(s);
  2292. sse.effect.turnsRemain = h->getPrimSkillLevel(2) + h->valOfBonuses(HeroBonus::SPELL_DURATION);
  2293. sendAndApply(&sse);
  2294. break;
  2295. }
  2296. case 56: //frenzy
  2297. {
  2298. SetStackEffect sse;
  2299. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2300. {
  2301. sse.stacks.insert((*it)->ID);
  2302. }
  2303. sse.effect.id = ba.additionalInfo;
  2304. sse.effect.level = h->getSpellSchoolLevel(s);
  2305. sse.effect.turnsRemain = 1;
  2306. sendAndApply(&sse);
  2307. break;
  2308. }
  2309. }
  2310. sendAndApply(&EndAction());
  2311. return true;
  2312. }
  2313. }
  2314. return false;
  2315. }
  2316. void CGameHandler::handleTimeEvents()
  2317. {
  2318. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  2319. {
  2320. CMapEvent *ev = gs->map->events.front();
  2321. for(int player = 0; player < PLAYER_LIMIT; player++)
  2322. {
  2323. PlayerState *pinfo = gs->getPlayer(player);
  2324. if( pinfo //player exists
  2325. && (ev->players & 1<<player) //event is enabled to this player
  2326. && ((ev->computerAffected && !pinfo->human)
  2327. || (ev->humanAffected && pinfo->human)
  2328. )
  2329. )
  2330. {
  2331. //give resources
  2332. SetResources sr;
  2333. sr.player = player;
  2334. sr.res = pinfo->resources;
  2335. //prepare dialog
  2336. InfoWindow iw;
  2337. iw.player = player;
  2338. iw.text << ev->message;
  2339. for (int i=0; i<ev->resources.size(); i++)
  2340. {
  2341. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  2342. {
  2343. // If removing too much ressources, adjust the
  2344. // amount so the total doesn't become negative.
  2345. if (sr.res[i] + ev->resources[i] < 0)
  2346. ev->resources[i] = -sr.res[i];
  2347. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  2348. sr.res[i] += ev->resources[i];
  2349. }
  2350. }
  2351. if (iw.components.size())
  2352. {
  2353. sendAndApply(&sr); //update player resources if changed
  2354. }
  2355. sendAndApply(&iw); //show dialog
  2356. }
  2357. } //PLAYERS LOOP
  2358. if(ev->nextOccurence)
  2359. {
  2360. ev->firstOccurence += ev->nextOccurence;
  2361. gs->map->events.sort(evntCmp);
  2362. }
  2363. else
  2364. {
  2365. delete ev;
  2366. gs->map->events.pop_front();
  2367. }
  2368. }
  2369. }
  2370. bool CGameHandler::complain( const std::string &problem )
  2371. {
  2372. sendMessageToAll("Server encountered a problem: " + problem);
  2373. tlog1 << problem << std::endl;
  2374. return true;
  2375. }
  2376. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  2377. {
  2378. //TODO: write
  2379. return 0;
  2380. }
  2381. void CGameHandler::showGarrisonDialog( int upobj, int hid, const boost::function<void()> &cb )
  2382. {
  2383. ui8 player = getOwner(hid);
  2384. GarrisonDialog gd;
  2385. gd.hid = hid;
  2386. gd.objid = upobj;
  2387. {
  2388. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2389. gd.id = QID;
  2390. garrisonCallbacks[QID] = cb;
  2391. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  2392. states.addQuery(player,QID);
  2393. QID++;
  2394. sendAndApply(&gd);
  2395. }
  2396. }
  2397. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  2398. {
  2399. if(id1 == id2)
  2400. return true;
  2401. {
  2402. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2403. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  2404. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  2405. return true;
  2406. }
  2407. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  2408. if(o1->ID == TOWNI_TYPE)
  2409. {
  2410. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  2411. if(t->visitingHero == o2 || t->garrisonHero == o2)
  2412. return true;
  2413. }
  2414. if(o2->ID == TOWNI_TYPE)
  2415. {
  2416. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  2417. if(t->visitingHero == o1 || t->garrisonHero == o1)
  2418. return true;
  2419. }
  2420. return false;
  2421. }