CGameHandler.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. #include <boost/foreach.hpp>
  2. #include <boost/thread.hpp>
  3. #include <boost/thread/shared_mutex.hpp>
  4. #include <boost/bind.hpp>
  5. #include "CGameHandler.h"
  6. #include "CScriptCallback.h"
  7. #include "../CLua.h"
  8. #include "../CGameState.h"
  9. #include "../StartInfo.h"
  10. #include "../map.h"
  11. #include "../lib/NetPacks.h"
  12. #include "../lib/Connection.h"
  13. #include "../hch/CArtHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CTownHandler.h"
  16. #include "../hch/CBuildingHandler.h"
  17. #include "../hch/CHeroHandler.h"
  18. #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types
  19. #include "../lib/VCMI_Lib.h"
  20. #include "../lib/CondSh.h"
  21. #ifndef _MSC_VER
  22. #include <boost/thread/xtime.hpp>
  23. #endif
  24. extern bool end2;
  25. #include "../lib/BattleAction.h"
  26. #ifdef min
  27. #undef min
  28. #endif
  29. #ifdef max
  30. #undef max
  31. #endif
  32. #define NEW_ROUND BattleNextRound bnr;\
  33. bnr.round = gs->curB->round + 1;\
  34. sendAndApply(&bnr);
  35. boost::mutex gsm;
  36. ui32 CGameHandler::QID = 1;
  37. CondSh<bool> battleMadeAction;
  38. CondSh<BattleResult *> battleResult(NULL);
  39. std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback function - for selection dialogs
  40. class CMP_stack
  41. {
  42. public:
  43. bool operator ()(const CStack* a, const CStack* b)
  44. {
  45. return (a->creature->speed)>(b->creature->speed);
  46. }
  47. } cmpst ;
  48. double distance(int3 a, int3 b)
  49. {
  50. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  51. }
  52. //bool CGameState::checkFunc(int obid, std::string name)
  53. //{
  54. // if (objscr.find(obid)!=objscr.end())
  55. // {
  56. // if(objscr[obid].find(name)!=objscr[obid].end())
  57. // {
  58. // return true;
  59. // }
  60. // }
  61. // return false;
  62. //}
  63. PlayerStatus PlayerStatuses::operator[](ui8 player)
  64. {
  65. boost::unique_lock<boost::mutex> l(mx);
  66. if(players.find(player) != players.end())
  67. {
  68. return players[player];
  69. }
  70. else
  71. {
  72. throw std::string("No such player!");
  73. }
  74. }
  75. void PlayerStatuses::addPlayer(ui8 player)
  76. {
  77. boost::unique_lock<boost::mutex> l(mx);
  78. players[player];
  79. }
  80. bool PlayerStatuses::hasQueries(ui8 player)
  81. {
  82. boost::unique_lock<boost::mutex> l(mx);
  83. if(players.find(player) != players.end())
  84. {
  85. return players[player].queries.size();
  86. }
  87. else
  88. {
  89. throw std::string("No such player!");
  90. }
  91. }
  92. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  93. {
  94. boost::unique_lock<boost::mutex> l(mx);
  95. if(players.find(player) != players.end())
  96. {
  97. return players[player].*flag;
  98. }
  99. else
  100. {
  101. throw std::string("No such player!");
  102. }
  103. }
  104. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  105. {
  106. boost::unique_lock<boost::mutex> l(mx);
  107. if(players.find(player) != players.end())
  108. {
  109. players[player].*flag = val;
  110. }
  111. else
  112. {
  113. throw std::string("No such player!");
  114. }
  115. cv.notify_all();
  116. }
  117. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  118. {
  119. boost::unique_lock<boost::mutex> l(mx);
  120. if(players.find(player) != players.end())
  121. {
  122. players[player].queries.insert(id);
  123. }
  124. else
  125. {
  126. throw std::string("No such player!");
  127. }
  128. cv.notify_all();
  129. }
  130. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  131. {
  132. boost::unique_lock<boost::mutex> l(mx);
  133. if(players.find(player) != players.end())
  134. {
  135. players[player].queries.erase(id);
  136. }
  137. else
  138. {
  139. throw std::string("No such player!");
  140. }
  141. cv.notify_all();
  142. }
  143. void CGameHandler::handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script)
  144. {
  145. std::vector<int> tempv = script->yourObjects();
  146. for (unsigned i=0;i<tempv.size();i++)
  147. {
  148. (*mapa)[tempv[i]]=script;
  149. }
  150. cppscripts.insert(script);
  151. }
  152. template <typename T>
  153. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  154. {
  155. fun(args[which]);
  156. }
  157. void CGameHandler::changeSecSkill(int ID, ui16 which, int val, bool abs)
  158. {
  159. SetSecSkill sps;
  160. sps.id = ID;
  161. sps.which = which;
  162. sps.abs = abs;
  163. sps.val = val;
  164. sendAndApply(&sps);
  165. }
  166. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  167. {
  168. SetPrimSkill sps;
  169. sps.id = ID;
  170. sps.which = which;
  171. sps.abs = abs;
  172. sps.val = val;
  173. sendAndApply(&sps);
  174. if(which==4) //only for exp - hero may level up
  175. {
  176. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  177. if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  178. {
  179. //give prim skill
  180. std::cout << hero->name <<" got level "<<hero->level<<std::endl;
  181. int r = rand()%100, pom=0, x=0;
  182. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  183. for(;x<PRIMARY_SKILLS;x++)
  184. {
  185. pom += hero->type->heroClass->primChance[x].*g;
  186. if(r<pom)
  187. break;
  188. }
  189. std::cout << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  190. SetPrimSkill sps;
  191. sps.id = ID;
  192. sps.which = x;
  193. sps.abs = false;
  194. sps.val = 1;
  195. sendAndApply(&sps);
  196. HeroLevelUp hlu;
  197. hlu.heroid = ID;
  198. hlu.primskill = x;
  199. hlu.level = hero->level+1;
  200. //picking sec. skills for choice
  201. std::set<int> basicAndAdv, expert, none;
  202. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  203. for(unsigned i=0;i<hero->secSkills.size();i++)
  204. {
  205. if(hero->secSkills[i].second < 2)
  206. basicAndAdv.insert(hero->secSkills[i].first);
  207. else
  208. expert.insert(hero->secSkills[i].first);
  209. none.erase(hero->secSkills[i].first);
  210. }
  211. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  212. {
  213. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  214. }
  215. else
  216. {
  217. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  218. hlu.skills.push_back(s);
  219. basicAndAdv.erase(s);
  220. }
  221. if(basicAndAdv.size())
  222. {
  223. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  224. }
  225. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  226. {
  227. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  228. }
  229. 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));
  230. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  231. }
  232. }
  233. }
  234. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb)
  235. {
  236. BattleInfo *curB = new BattleInfo;
  237. setupBattle(curB, tile, army1, army2, hero1, hero2); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  238. NEW_ROUND;
  239. //TODO: pre-tactic stuff, call scripts etc.
  240. //tactic round
  241. {
  242. NEW_ROUND;
  243. if( (hero1 && hero1->getSecSkillLevel(19)>=0) ||
  244. ( hero2 && hero2->getSecSkillLevel(19)>=0) )//someone has tactics
  245. {
  246. //TODO: tactic round (round -1)
  247. }
  248. }
  249. //main loop
  250. while(!battleResult.get()) //till the end of the battle ;]
  251. {
  252. NEW_ROUND;
  253. std::vector<CStack*> & stacks = (gs->curB->stacks);
  254. const BattleInfo & curB = *gs->curB;
  255. //stack loop
  256. for(unsigned i=0;i<stacks.size() && !battleResult.get();i++)
  257. {
  258. if(!stacks[i]->alive()) continue;//indicates imposiibility of making action for this dead unit
  259. BattleSetActiveStack sas;
  260. sas.stack = stacks[i]->ID;
  261. sendAndApply(&sas);
  262. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  263. while(!battleMadeAction.data && !battleResult.get()) //active stack hasn't made its action and battle is still going
  264. battleMadeAction.cond.wait(lock);
  265. battleMadeAction.data = false;
  266. checkForBattleEnd(stacks); //check if this action ended the battle
  267. }
  268. }
  269. //unblock engaged players
  270. if(hero1->tempOwner<PLAYER_LIMIT)
  271. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  272. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  273. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  274. //end battle, remove all info, free memory
  275. sendAndApply(battleResult.data);
  276. if(cb)
  277. cb(battleResult.data);
  278. delete battleResult.data;
  279. //for(int i=0;i<stacks.size();i++)
  280. // delete stacks[i];
  281. //delete curB;
  282. //curB = NULL;
  283. }
  284. void prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  285. {
  286. bat.stackAttacking = att->ID;
  287. bat.bsa.stackAttacked = def->ID;
  288. bat.bsa.damageAmount = BattleInfo::calculateDmg(att, def);//counting dealt damage
  289. //applying damages
  290. bat.bsa.killedAmount = bat.bsa.damageAmount / def->creature->hitPoints;
  291. unsigned damageFirst = bat.bsa.damageAmount % def->creature->hitPoints;
  292. if( def->firstHPleft <= damageFirst )
  293. {
  294. bat.bsa.killedAmount++;
  295. bat.bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  296. }
  297. else
  298. {
  299. bat.bsa.newHP = def->firstHPleft - damageFirst;
  300. }
  301. if(def->amount <= bat.bsa.killedAmount) //stack killed
  302. {
  303. bat.bsa.newAmount = 0;
  304. bat.bsa.flags |= 1;
  305. bat.bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  306. }
  307. else
  308. {
  309. bat.bsa.newAmount = def->amount - bat.bsa.killedAmount;
  310. }
  311. }
  312. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  313. {
  314. try
  315. {
  316. ui16 pom;
  317. while(!end2)
  318. {
  319. c >> pom;
  320. bool blockvis = false;
  321. switch(pom)
  322. {
  323. case 100: //my interface ended its turn
  324. {
  325. states.setFlag(gs->currentPlayer,&PlayerStatus::makingTurn,false);
  326. break;
  327. }
  328. case 500:
  329. {
  330. si32 id;
  331. c >> id;
  332. RemoveObject rh(id);
  333. sendAndApply(&rh);
  334. break;
  335. }
  336. case 501://interface wants to move hero
  337. {
  338. int3 start, end;
  339. si32 id;
  340. c >> id >> start >> end;
  341. int3 hmpos = end + int3(-1,0,0);
  342. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  343. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  344. int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end));
  345. TryMoveHero tmh;
  346. tmh.id = id;
  347. tmh.start = start;
  348. tmh.end = end;
  349. tmh.result = 0;
  350. tmh.movePoints = h->movement;
  351. if((h->getOwner() != gs->currentPlayer) || //not turn of that hero
  352. (distance(start,end)>=1.5) || //tiles are not neighouring
  353. (h->movement < cost) || //lack of movement points
  354. (t.tertype == rock) || //rock
  355. (!h->canWalkOnSea() && t.tertype == water) ||
  356. (t.blocked && !t.visitable) ) //tile is blocked andnot visitable
  357. goto fail;
  358. //check if there is blocking visitable object
  359. blockvis = false;
  360. tmh.movePoints = h->movement = (h->movement-cost); //take move points
  361. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  362. {
  363. if(obj->blockVisit)
  364. {
  365. blockvis = true;
  366. break;
  367. }
  368. }
  369. //we start moving
  370. if(blockvis)//interaction with blocking object (like resources)
  371. {
  372. sendAndApply(&tmh); //failed to move to that tile but we visit object
  373. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  374. {
  375. if (obj->blockVisit)
  376. {
  377. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  378. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  379. if(obj->state) //hard-coded function
  380. obj->state->onHeroVisit(obj->id,h->id);
  381. }
  382. }
  383. break;
  384. }
  385. else //normal move
  386. {
  387. tmh.result = 1;
  388. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x-1][start.y][start.z].visitableObjects)
  389. {
  390. //TODO: allow to handle this in script-languages
  391. if(obj->state) //hard-coded function
  392. obj->state->onHeroLeave(obj->id,h->id);
  393. }
  394. //reveal fog of war
  395. int heroSight = h->getSightDistance();
  396. int xbeg = start.x - heroSight - 2;
  397. if(xbeg < 0)
  398. xbeg = 0;
  399. int xend = start.x + heroSight + 2;
  400. if(xend >= gs->map->width)
  401. xend = gs->map->width;
  402. int ybeg = start.y - heroSight - 2;
  403. if(ybeg < 0)
  404. ybeg = 0;
  405. int yend = start.y + heroSight + 2;
  406. if(yend >= gs->map->height)
  407. yend = gs->map->height;
  408. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  409. {
  410. for(int yd=ybeg; yd<yend; ++yd)
  411. {
  412. int deltaX = (hmpos.x-xd)*(hmpos.x-xd);
  413. int deltaY = (hmpos.y-yd)*(hmpos.y-yd);
  414. if(deltaX+deltaY<h->getSightDistance()*h->getSightDistance())
  415. {
  416. if(gs->players[h->getOwner()].fogOfWarMap[xd][yd][hmpos.z] == 0)
  417. {
  418. tmh.fowRevealed.insert(int3(xd,yd,hmpos.z));
  419. }
  420. }
  421. }
  422. }
  423. sendAndApply(&tmh);
  424. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  425. {
  426. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  427. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  428. if(obj->state) //hard-coded function
  429. obj->state->onHeroVisit(obj->id,h->id);
  430. }
  431. }
  432. break;
  433. fail:
  434. sendAndApply(&tmh);
  435. break;
  436. }
  437. case 502: //swap creatures in garrison
  438. {
  439. ui8 what, p1, p2; si32 id1, id2;
  440. c >> what >> id1 >> p1 >> id2 >> p2;
  441. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  442. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  443. CCreatureSet *S1 = &s1->army, *S2 = &s2->army;
  444. if(what==1) //swap
  445. {
  446. int pom = S2->slots[p2].first;
  447. S2->slots[p2].first = S1->slots[p1].first;
  448. S1->slots[p1].first = pom;
  449. int pom2 = S2->slots[p2].second;
  450. S2->slots[p2].second = S1->slots[p1].second;
  451. S1->slots[p1].second = pom2;
  452. if(!S1->slots[p1].second)
  453. S1->slots.erase(p1);
  454. if(!S2->slots[p2].second)
  455. S2->slots.erase(p2);
  456. }
  457. else if(what==2)//merge
  458. {
  459. if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature
  460. S2->slots[p2].second += S1->slots[p1].second;
  461. S1->slots[p1].first = NULL;
  462. S1->slots[p1].second = 0;
  463. S1->slots.erase(p1);
  464. }
  465. else if(what==3) //split
  466. {
  467. si32 val;
  468. c >> val;
  469. if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free
  470. S2->slots[p2].first = S1->slots[p1].first;
  471. S2->slots[p2].second = val;
  472. S1->slots[p1].second -= val;
  473. if(!S1->slots[p1].second) //if we've moved all creatures
  474. S1->slots.erase(p1);
  475. }
  476. if((s1->ID==34 && !S1->slots.size()) //it's not allowed to take last stack from hero army!
  477. || (s2->ID==34 && !S2->slots.size()))
  478. {
  479. break;
  480. }
  481. SetGarrisons sg;
  482. sg.garrs[id1] = *S1;
  483. if(s1 != s2)
  484. sg.garrs[id2] = *S2;
  485. sendAndApply(&sg);
  486. break;
  487. }
  488. case 503:
  489. {
  490. si32 id;
  491. ui8 pos;
  492. c >> id >> pos;
  493. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  494. s1->army.slots.erase(pos);
  495. SetGarrisons sg;
  496. sg.garrs[id] = s1->army;
  497. sendAndApply(&sg);
  498. break;
  499. }
  500. case 504:
  501. {
  502. si32 tid, bid;
  503. c >> tid >> bid;
  504. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  505. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  506. for(int i=0;i<RESOURCE_QUANTITY;i++)
  507. if(b->resources[i] > gs->players[t->tempOwner].resources[i])
  508. break; //no res
  509. //TODO: check requirements
  510. //TODO: check if building isn't forbidden
  511. NewStructures ns;
  512. ns.tid = tid;
  513. if(bid>36) //upg dwelling
  514. {
  515. if(t->getHordeLevel(0) == (bid-37))
  516. ns.bid.insert(19);
  517. else if(t->getHordeLevel(1) == (bid-37))
  518. ns.bid.insert(25);
  519. }
  520. else if(bid >= 30) //bas. dwelling
  521. {
  522. SetAvailableCreatures ssi;
  523. ssi.tid = tid;
  524. ssi.creatures = t->strInfo.creatures;
  525. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  526. sendAndApply(&ssi);
  527. }
  528. ns.bid.insert(bid);
  529. ns.builded = t->builded + 1;
  530. sendAndApply(&ns);
  531. SetResources sr;
  532. sr.player = t->tempOwner;
  533. sr.res = gs->players[t->tempOwner].resources;
  534. for(int i=0;i<7;i++)
  535. sr.res[i]-=b->resources[i];
  536. sendAndApply(&sr);
  537. if(bid<5) //it's mage guild
  538. {
  539. if(t->visitingHero)
  540. giveSpells(t,t->visitingHero);
  541. if(t->garrisonHero)
  542. giveSpells(t,t->garrisonHero);
  543. }
  544. break;
  545. }
  546. case 506: //recruit creature
  547. {
  548. si32 objid, ser=-1; //ser - used dwelling level
  549. ui32 crid, cram; //recruited creature id and amount
  550. c >> objid >> crid >> cram;
  551. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  552. //verify
  553. bool found = false;
  554. typedef std::pair<const int,int> Parka;
  555. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  556. {
  557. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  558. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  559. {
  560. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  561. ser = av->first;
  562. break;
  563. }
  564. }
  565. int slot = t->army.getSlotFor(crid);
  566. if(!found || //no such creature
  567. cram > VLC->creh->creatures[crid].maxAmount(gs->players[t->tempOwner].resources) || //lack of resources
  568. cram<=0 ||
  569. slot<0 )
  570. break;
  571. //recruit
  572. SetResources sr;
  573. sr.player = t->tempOwner;
  574. for(int i=0;i<RESOURCE_QUANTITY;i++)
  575. sr.res[i] = gs->players[t->tempOwner].resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  576. SetAvailableCreatures sac;
  577. sac.tid = objid;
  578. sac.creatures = t->strInfo.creatures;
  579. sac.creatures[ser] -= cram;
  580. SetGarrisons sg;
  581. sg.garrs[objid] = t->army;
  582. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  583. {
  584. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  585. }
  586. else //add creatures to a already existing stack
  587. {
  588. sg.garrs[objid].slots[slot].second += cram;
  589. }
  590. sendAndApply(&sr);
  591. sendAndApply(&sac);
  592. sendAndApply(&sg);
  593. break;
  594. }
  595. case 507://upgrade creature
  596. {
  597. ui32 objid, upgID;
  598. ui8 pos;
  599. c >> objid >> pos >> upgID;
  600. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  601. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  602. int player = obj->tempOwner;
  603. int crQuantity = obj->army.slots[pos].second;
  604. //check if upgrade is possible
  605. if(ui.oldID<0 || !vstd::contains(ui.newID,upgID))
  606. break;
  607. //check if player has enough resources
  608. for(int i=0;i<ui.cost.size();i++)
  609. {
  610. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  611. {
  612. if(gs->players[player].resources[j->first] < j->second*crQuantity)
  613. goto upgend;
  614. }
  615. }
  616. //take resources
  617. for(int i=0;i<ui.cost.size();i++)
  618. {
  619. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  620. {
  621. SetResource sr;
  622. sr.player = player;
  623. sr.resid = j->first;
  624. sr.val = gs->players[player].resources[j->first] - j->second*crQuantity;
  625. sendAndApply(&sr);
  626. }
  627. }
  628. {
  629. //upgrade creature
  630. SetGarrisons sg;
  631. sg.garrs[objid] = obj->army;
  632. sg.garrs[objid].slots[pos].first = upgID;
  633. sendAndApply(&sg);
  634. }
  635. upgend:
  636. break;
  637. }
  638. case 508: //garrison swap
  639. {
  640. si32 tid;
  641. c >> tid;
  642. CGTownInstance *town = gs->getTown(tid);
  643. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  644. {
  645. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  646. while(!cso.slots.empty())//while there are unmoved creatures
  647. {
  648. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  649. if(pos<0)
  650. goto handleConEnd;
  651. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  652. {
  653. csn.slots[pos].second += cso.slots.begin()->second.second;
  654. }
  655. else //move stack on the free pos
  656. {
  657. csn.slots[pos].first = cso.slots.begin()->second.first;
  658. csn.slots[pos].second = cso.slots.begin()->second.second;
  659. }
  660. cso.slots.erase(cso.slots.begin());
  661. }
  662. SetGarrisons sg;
  663. sg.garrs[town->visitingHero->id] = csn;
  664. sg.garrs[town->id] = csn;
  665. sendAndApply(&sg);
  666. SetHeroesInTown intown;
  667. intown.tid = tid;
  668. intown.visiting = -1;
  669. intown.garrison = town->visitingHero->id;
  670. sendAndApply(&intown);
  671. }
  672. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  673. {
  674. SetHeroesInTown intown;
  675. intown.tid = tid;
  676. intown.garrison = -1;
  677. intown.visiting = town->garrisonHero->id;
  678. sendAndApply(&intown);
  679. //town will be empty
  680. SetGarrisons sg;
  681. sg.garrs[tid] = CCreatureSet();
  682. sendAndApply(&sg);
  683. }
  684. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  685. {
  686. SetGarrisons sg;
  687. sg.garrs[town->id] = town->visitingHero->army;
  688. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  689. //sg.garrs[town->visitingHero->id] = town->visitingHero->army;
  690. SetHeroesInTown intown;
  691. intown.tid = tid;
  692. intown.garrison = town->visitingHero->id;
  693. intown.visiting = town->garrisonHero->id;
  694. sendAndApply(&intown);
  695. sendAndApply(&sg);
  696. }
  697. else
  698. {
  699. std::cout << "Warning, wrong garrison swap command for " << tid << std::endl;
  700. }
  701. break;
  702. }
  703. case 509: //swap artifacts
  704. {
  705. si32 hid1, hid2;
  706. ui16 slot1, slot2;
  707. c >> hid1 >> slot1 >> hid2 >> slot2;
  708. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  709. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  710. break;
  711. int a1=h1->getArtAtPos(slot1), a2=h2->getArtAtPos(slot2);
  712. h2->setArtAtPos(slot2,a1);
  713. h1->setArtAtPos(slot1,a2);
  714. SetHeroArtifacts sha;
  715. sha.hid = hid1;
  716. sha.artifacts = h1->artifacts;
  717. sha.artifWorn = h1->artifWorn;
  718. sendAndApply(&sha);
  719. if(hid1 != hid2)
  720. {
  721. sha.hid = hid2;
  722. sha.artifacts = h2->artifacts;
  723. sha.artifWorn = h2->artifWorn;
  724. sendAndApply(&sha);
  725. }
  726. break;
  727. }
  728. case 510: //buy artifact
  729. {
  730. ui32 hid;
  731. si32 aid, bid;
  732. c >> hid >> aid;
  733. CGHeroInstance *hero = gs->getHero(hid);
  734. CGTownInstance *town = hero->visitedTown;
  735. if(aid==0) //spellbok
  736. {
  737. if(!vstd::contains(town->builtBuildings,si32(0)))
  738. break;
  739. SetResource sr;
  740. sr.player = hero->tempOwner;
  741. sr.resid = 6;
  742. sr.val = gs->players[hero->tempOwner].resources[6] - 500;
  743. sendAndApply(&sr);
  744. SetHeroArtifacts sha;
  745. sha.hid = hid;
  746. sha.artifacts = hero->artifacts;
  747. sha.artifWorn = hero->artifWorn;
  748. sha.artifWorn[17] = 0;
  749. sendAndApply(&sha);
  750. giveSpells(town,hero);
  751. }
  752. else if(aid < 7 && aid > 3) //war machine
  753. {
  754. int price = VLC->arth->artifacts[aid].price;
  755. if(vstd::contains(hero->artifWorn,ui16(9+aid)) //hero already has this machine
  756. || !vstd::contains(town->builtBuildings,si32(16)) //no blackismith
  757. || gs->players[hero->tempOwner].resources[6] < price //no gold
  758. || town->town->warMachine!= aid ) //this machine is not available here (//TODO: support ballista yard in stronghold)
  759. {
  760. break;
  761. }
  762. SetResource sr;
  763. sr.player = hero->tempOwner;
  764. sr.resid = 6;
  765. sr.val = gs->players[hero->tempOwner].resources[6] - price;
  766. sendAndApply(&sr);
  767. SetHeroArtifacts sha;
  768. sha.hid = hid;
  769. sha.artifacts = hero->artifacts;
  770. sha.artifWorn = hero->artifWorn;
  771. sha.artifWorn[9+aid] = aid;
  772. sendAndApply(&sha);
  773. }
  774. break;
  775. }
  776. case 511: //trade at marketplace
  777. {
  778. ui8 player;
  779. ui32 mode, id1, id2, val;
  780. c >> player >> mode >> id1 >> id2 >> val;
  781. val = std::min(si32(val),gs->players[player].resources[id1]);
  782. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  783. uzysk /= gs->resVals[id2];
  784. SetResource sr;
  785. sr.player = player;
  786. sr.resid = id1;
  787. sr.val = gs->players[player].resources[id1] - val;
  788. sendAndApply(&sr);
  789. sr.resid = id2;
  790. sr.val = gs->players[player].resources[id2] + (int)uzysk;
  791. sendAndApply(&sr);
  792. break;
  793. }
  794. case 2001:
  795. {
  796. ui32 qid, answer;
  797. c >> qid >> answer;
  798. gsm.lock();
  799. CFunctionList<void(ui32)> callb = callbacks[qid];
  800. callbacks.erase(qid);
  801. gsm.unlock();
  802. callb(answer);
  803. break;
  804. }
  805. case 3002:
  806. {
  807. BattleAction ba;
  808. c >> ba;
  809. switch(ba.actionType)
  810. {
  811. case 2: //walk
  812. {
  813. moveStack(ba.stackNumber,ba.destinationTile);
  814. break;
  815. }
  816. case 3: //defend
  817. {
  818. break;
  819. }
  820. case 4: //retreat/flee
  821. {
  822. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  823. //TODO: calculate casualties
  824. //TODO: remove retreating hero from map and place it in recrutation list
  825. BattleResult *br = new BattleResult;
  826. br->result = 1;
  827. br->winner = !ba.side; //fleeing side loses
  828. gs->curB->calculateCasualties(br->casualties);
  829. battleResult.set(br);
  830. break;
  831. }
  832. case 6: //walk or attack
  833. {
  834. moveStack(ba.stackNumber,ba.destinationTile);
  835. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  836. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  837. if((curStack->position != ba.destinationTile) || //we wasn't able to reach destination tile
  838. (BattleInfo::mutualPosition(ba.destinationTile,ba.additionalInfo)<0) ) //destination tile is not neighbouring with enemy stack
  839. return;
  840. BattleAttack bat;
  841. prepareAttack(bat,curStack,stackAtEnd);
  842. sendAndApply(&bat);
  843. //counterattack
  844. if(!vstd::contains(curStack->abilities,NO_ENEMY_RETALIATION)
  845. && stackAtEnd->alive()
  846. && !stackAtEnd->counterAttacks ) //TODO: support for multiple retaliatons per turn
  847. {
  848. prepareAttack(bat,stackAtEnd,curStack);
  849. bat.flags |= 2;
  850. sendAndApply(&bat);
  851. }
  852. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  853. && curStack->alive())
  854. {
  855. bat.flags = 0;
  856. prepareAttack(bat,curStack,stackAtEnd);
  857. sendAndApply(&bat);
  858. }
  859. break;
  860. }
  861. case 7: //shoot
  862. {
  863. //TODO: check arrows count
  864. //TODO: check if stack isn't blocked by enemy
  865. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  866. *destStack= gs->curB->getStackT(ba.destinationTile);
  867. BattleAttack bat;
  868. prepareAttack(bat,curStack,destStack);
  869. bat.flags |= 1;
  870. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  871. && curStack->alive())
  872. {
  873. prepareAttack(bat,curStack,destStack);
  874. sendAndApply(&bat);
  875. }
  876. sendAndApply(&bat);
  877. break;
  878. }
  879. }
  880. battleMadeAction.setn(true);
  881. //sprawdzic czy po tej akcji ktoras strona nie wygrala bitwy
  882. break;
  883. }
  884. default:
  885. #ifndef __GNUC__
  886. throw std::exception("Not supported client message!");
  887. #else
  888. throw std::exception();
  889. #endif
  890. break;
  891. }
  892. }
  893. }
  894. catch (const std::exception& e)
  895. {
  896. std::cerr << e.what() << std::endl;
  897. end2 = true;
  898. }
  899. catch (const std::exception * e)
  900. {
  901. std::cerr << e->what()<< std::endl;
  902. end2 = true;
  903. delete e;
  904. }
  905. catch(...)
  906. {
  907. end2 = true;
  908. }
  909. handleConEnd:
  910. ;
  911. }
  912. void CGameHandler::moveStack(int stack, int dest)
  913. {
  914. CStack *curStack = gs->curB->getStack(stack),
  915. *stackAtEnd = gs->curB->getStackT(dest);
  916. //initing necessary tables
  917. bool accessibility[187];
  918. if(curStack->creature->isDoubleWide())
  919. gs->curB->getAccessibilityMapForTwoHex(accessibility,curStack->attackerOwned,curStack->ID);
  920. else
  921. gs->curB->getAccessibilityMap(accessibility,curStack->ID);
  922. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  923. return;
  924. //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
  925. // return false;
  926. std::vector<int> path = gs->curB->getPath(curStack->position,dest,accessibility);
  927. int tilesToMove = std::max((int)path.size()-curStack->creature->speed, 0);
  928. for(int v=path.size()-1; v>=tilesToMove; --v)
  929. {
  930. //inform clients about move
  931. BattleStackMoved sm;
  932. sm.stack = curStack->ID;
  933. sm.tile = path[v];
  934. if(v==path.size()-1) //move start - set flag
  935. sm.flags |= 1;
  936. if(v==0) //move end - set flag
  937. sm.flags |= 2;
  938. sendAndApply(&sm);
  939. }
  940. }
  941. CGameHandler::CGameHandler(void)
  942. {
  943. gs = NULL;
  944. }
  945. CGameHandler::~CGameHandler(void)
  946. {
  947. delete gs;
  948. }
  949. void CGameHandler::init(StartInfo *si, int Seed)
  950. {
  951. Mapa *map = new Mapa(si->mapname);
  952. std::cout << "Map loaded!" << std::endl;
  953. gs = new CGameState();
  954. std::cout << "Gamestate created!" << std::endl;
  955. gs->init(si,map,Seed);
  956. std::cout << "Gamestate initialized!" << std::endl;
  957. /****************************LUA OBJECT SCRIPTS************************************************/
  958. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  959. //for (int i=0; i<lf->size(); i++)
  960. //{
  961. // try
  962. // {
  963. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  964. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  965. // CLuaCallback::registerFuncs(objs->is);
  966. // //objs
  967. // for (int j=0; j<temp->size(); j++)
  968. // {
  969. // int obid ; //obj ID
  970. // int dspos = (*temp)[j].find_first_of('_');
  971. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  972. // std::string fname = (*temp)[j].substr(0,dspos);
  973. // if (skrypty->find(obid)==skrypty->end())
  974. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  975. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  976. // }
  977. // delete temp;
  978. // }HANDLE_EXCEPTION
  979. //}
  980. //delete lf;
  981. }
  982. int lowestSpeed(CGHeroInstance * chi)
  983. {
  984. std::map<si32,std::pair<ui32,si32> >::iterator i = chi->army.slots.begin();
  985. int ret = VLC->creh->creatures[(*i++).second.first].speed;
  986. for (;i!=chi->army.slots.end();i++)
  987. {
  988. ret = std::min(ret,VLC->creh->creatures[(*i).second.first].speed);
  989. }
  990. return ret;
  991. }
  992. int valMovePoints(CGHeroInstance * chi)
  993. {
  994. int ret = 1270+70*lowestSpeed(chi);
  995. if (ret>2000)
  996. ret=2000;
  997. //TODO: additional bonuses (but they aren't currently stored in chi)
  998. return ret;
  999. }
  1000. void CGameHandler::newTurn()
  1001. {
  1002. NewTurn n;
  1003. n.day = gs->day + 1;
  1004. n.resetBuilded = true;
  1005. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  1006. {
  1007. if(i->first>=PLAYER_LIMIT) continue;
  1008. SetResources r;
  1009. r.player = i->first;
  1010. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1011. r.res[j] = i->second.resources[j];
  1012. for (unsigned j=0;j<(*i).second.heroes.size();j++) //handle heroes
  1013. {
  1014. NewTurn::Hero h;
  1015. h.id = (*i).second.heroes[j]->id;
  1016. h.move = valMovePoints((*i).second.heroes[j]);
  1017. h.mana = (*i).second.heroes[j]->mana;
  1018. n.heroes.insert(h);
  1019. }
  1020. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  1021. {
  1022. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  1023. {
  1024. if((**j).town->primaryRes == 127) //we'll give wood and ore
  1025. {
  1026. r.res[0] += 1;
  1027. r.res[2] += 1;
  1028. }
  1029. else
  1030. {
  1031. r.res[(**j).town->primaryRes] += 1;
  1032. }
  1033. }
  1034. if(gs->getDate(1)==7) //first day of week
  1035. {
  1036. SetAvailableCreatures sac;
  1037. sac.tid = (**j).id;
  1038. sac.creatures = (**j).strInfo.creatures;
  1039. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  1040. {
  1041. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  1042. sac.creatures[k] += (**j).creatureGrowth(k);
  1043. }
  1044. n.cres.push_back(sac);
  1045. }
  1046. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  1047. r.res[6] += (**j).dailyIncome();
  1048. }
  1049. n.res.push_back(r);
  1050. }
  1051. sendAndApply(&n);
  1052. for (std::set<CCPPObjectScript *>::iterator i=cppscripts.begin();i!=cppscripts.end();i++)
  1053. {
  1054. (*i)->newTurn();
  1055. }
  1056. }
  1057. void CGameHandler::run()
  1058. {
  1059. BOOST_FOREACH(CConnection *cc, conns)
  1060. {//init conn.
  1061. ui8 quantity, pom;
  1062. //ui32 seed;
  1063. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  1064. (*cc) >> quantity;
  1065. for(int i=0;i<quantity;i++)
  1066. {
  1067. (*cc) >> pom;
  1068. gsm.lock();
  1069. connections[pom] = cc;
  1070. gsm.unlock();
  1071. }
  1072. }
  1073. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  1074. {
  1075. std::set<int> pom;
  1076. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  1077. if(j->second == *i)
  1078. pom.insert(j->first);
  1079. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  1080. }
  1081. /****************************SCRIPTS************************************************/
  1082. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  1083. /****************************C++ OBJECT SCRIPTS************************************************/
  1084. std::map<int,CCPPObjectScript*> scripts;
  1085. CScriptCallback * csc = new CScriptCallback();
  1086. csc->gh = this;
  1087. handleCPPObjS(&scripts,new CVisitableOPH(csc));
  1088. handleCPPObjS(&scripts,new CVisitableOPW(csc));
  1089. handleCPPObjS(&scripts,new CPickable(csc));
  1090. handleCPPObjS(&scripts,new CMines(csc));
  1091. handleCPPObjS(&scripts,new CTownScript(csc));
  1092. handleCPPObjS(&scripts,new CHeroScript(csc));
  1093. handleCPPObjS(&scripts,new CMonsterS(csc));
  1094. handleCPPObjS(&scripts,new CCreatureGen(csc));
  1095. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  1096. //std::string temps("newObject");
  1097. for (unsigned i=0; i<gs->map->objects.size(); i++)
  1098. {
  1099. //c++ scripts
  1100. if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  1101. {
  1102. gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  1103. gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  1104. }
  1105. else
  1106. {
  1107. gs->map->objects[i]->state = NULL;
  1108. }
  1109. //// lua scripts
  1110. //if(checkFunc(map->objects[i]->ID,temps))
  1111. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  1112. }
  1113. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1114. states.addPlayer(i->first);
  1115. while (!end2)
  1116. {
  1117. newTurn();
  1118. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1119. {
  1120. 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
  1121. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1122. gs->currentPlayer = i->first;
  1123. *connections[i->first] << ui16(100) << i->first;
  1124. //wait till turn is done
  1125. boost::unique_lock<boost::mutex> lock(states.mx);
  1126. while(states.players[i->first].makingTurn && !end2)
  1127. {
  1128. boost::posix_time::time_duration p;
  1129. p = boost::posix_time::milliseconds(200);
  1130. #ifdef _MSC_VER
  1131. states.cv.timed_wait(lock,p);
  1132. #else
  1133. boost::xtime time={0,0};
  1134. time.nsec = static_cast<boost::xtime::xtime_nsec_t>(p.total_nanoseconds());
  1135. states.cv.timed_wait(lock,time);
  1136. #endif
  1137. }
  1138. }
  1139. }
  1140. }
  1141. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  1142. {
  1143. battleResult.set(NULL);
  1144. std::vector<CStack*> & stacks = (curB->stacks);
  1145. curB->tile = tile;
  1146. curB->siege = 0; //TODO: add sieges
  1147. curB->army1=army1;
  1148. curB->army2=army2;
  1149. curB->hero1=(hero1)?(hero1->id):(-1);
  1150. curB->hero2=(hero2)?(hero2->id):(-1);
  1151. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  1152. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  1153. curB->round = -2;
  1154. curB->activeStack = -1;
  1155. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  1156. {
  1157. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  1158. stacks[stacks.size()-1]->ID = stacks.size()-1;
  1159. }
  1160. //initialization of positions
  1161. switch(army1.slots.size()) //for attacker
  1162. {
  1163. case 0:
  1164. break;
  1165. case 1:
  1166. stacks[0]->position = 86; //6
  1167. break;
  1168. case 2:
  1169. stacks[0]->position = 35; //3
  1170. stacks[1]->position = 137; //9
  1171. break;
  1172. case 3:
  1173. stacks[0]->position = 35; //3
  1174. stacks[1]->position = 86; //6
  1175. stacks[2]->position = 137; //9
  1176. break;
  1177. case 4:
  1178. stacks[0]->position = 1; //1
  1179. stacks[1]->position = 69; //5
  1180. stacks[2]->position = 103; //7
  1181. stacks[3]->position = 171; //11
  1182. break;
  1183. case 5:
  1184. stacks[0]->position = 1; //1
  1185. stacks[1]->position = 35; //3
  1186. stacks[2]->position = 86; //6
  1187. stacks[3]->position = 137; //9
  1188. stacks[4]->position = 171; //11
  1189. break;
  1190. case 6:
  1191. stacks[0]->position = 1; //1
  1192. stacks[1]->position = 35; //3
  1193. stacks[2]->position = 69; //5
  1194. stacks[3]->position = 103; //7
  1195. stacks[4]->position = 137; //9
  1196. stacks[5]->position = 171; //11
  1197. break;
  1198. case 7:
  1199. stacks[0]->position = 1; //1
  1200. stacks[1]->position = 35; //3
  1201. stacks[2]->position = 69; //5
  1202. stacks[3]->position = 86; //6
  1203. stacks[4]->position = 103; //7
  1204. stacks[5]->position = 137; //9
  1205. stacks[6]->position = 171; //11
  1206. break;
  1207. default: //fault
  1208. break;
  1209. }
  1210. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  1211. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  1212. switch(army2.slots.size()) //for defender
  1213. {
  1214. case 0:
  1215. break;
  1216. case 1:
  1217. stacks[0+army1.slots.size()]->position = 100; //6
  1218. break;
  1219. case 2:
  1220. stacks[0+army1.slots.size()]->position = 49; //3
  1221. stacks[1+army1.slots.size()]->position = 151; //9
  1222. break;
  1223. case 3:
  1224. stacks[0+army1.slots.size()]->position = 49; //3
  1225. stacks[1+army1.slots.size()]->position = 100; //6
  1226. stacks[2+army1.slots.size()]->position = 151; //9
  1227. break;
  1228. case 4:
  1229. stacks[0+army1.slots.size()]->position = 15; //1
  1230. stacks[1+army1.slots.size()]->position = 83; //5
  1231. stacks[2+army1.slots.size()]->position = 117; //7
  1232. stacks[3+army1.slots.size()]->position = 185; //11
  1233. break;
  1234. case 5:
  1235. stacks[0+army1.slots.size()]->position = 15; //1
  1236. stacks[1+army1.slots.size()]->position = 49; //3
  1237. stacks[2+army1.slots.size()]->position = 100; //6
  1238. stacks[3+army1.slots.size()]->position = 151; //9
  1239. stacks[4+army1.slots.size()]->position = 185; //11
  1240. break;
  1241. case 6:
  1242. stacks[0+army1.slots.size()]->position = 15; //1
  1243. stacks[1+army1.slots.size()]->position = 49; //3
  1244. stacks[2+army1.slots.size()]->position = 83; //5
  1245. stacks[3+army1.slots.size()]->position = 117; //7
  1246. stacks[4+army1.slots.size()]->position = 151; //9
  1247. stacks[5+army1.slots.size()]->position = 185; //11
  1248. break;
  1249. case 7:
  1250. stacks[0+army1.slots.size()]->position = 15; //1
  1251. stacks[1+army1.slots.size()]->position = 49; //3
  1252. stacks[2+army1.slots.size()]->position = 83; //5
  1253. stacks[3+army1.slots.size()]->position = 100; //6
  1254. stacks[4+army1.slots.size()]->position = 117; //7
  1255. stacks[5+army1.slots.size()]->position = 151; //9
  1256. stacks[6+army1.slots.size()]->position = 185; //11
  1257. break;
  1258. default: //fault
  1259. break;
  1260. }
  1261. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1262. {
  1263. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  1264. {
  1265. stacks[g]->position += 1;
  1266. }
  1267. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  1268. {
  1269. stacks[g]->position -= 1;
  1270. }
  1271. }
  1272. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1273. //block engaged players
  1274. if(hero1->tempOwner<PLAYER_LIMIT)
  1275. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1276. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  1277. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1278. //send info about battles
  1279. BattleStart bs;
  1280. bs.info = curB;
  1281. sendAndApply(&bs);
  1282. }
  1283. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1284. {
  1285. //checking winning condition
  1286. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1287. hasStack[0] = hasStack[1] = false;
  1288. for(int b = 0; b<stacks.size(); ++b)
  1289. {
  1290. if(stacks[b]->alive())
  1291. {
  1292. hasStack[1-stacks[b]->attackerOwned] = true;
  1293. }
  1294. }
  1295. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1296. {
  1297. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1298. br->result = 0;
  1299. br->winner = hasStack[1]; //fleeing side loses
  1300. gs->curB->calculateCasualties(br->casualties);
  1301. battleResult.set(br);
  1302. }
  1303. }
  1304. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1305. {
  1306. if(!vstd::contains(h->artifWorn,17))
  1307. return; //hero hasn't spellbok
  1308. ChangeSpells cs;
  1309. cs.hid = h->id;
  1310. cs.learn = true;
  1311. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+4);i++)
  1312. {
  1313. for(int j=0; j<t->spellsAtLevel(i+1,true); j++)
  1314. {
  1315. if(!vstd::contains(h->spells,t->spells[i][j]))
  1316. cs.spells.insert(t->spells[i][j]);
  1317. }
  1318. }
  1319. if(cs.spells.size())
  1320. sendAndApply(&cs);
  1321. }