CGameHandler.cpp 73 KB

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