CGameHandler.cpp 73 KB

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