CGameHandler.cpp 63 KB

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