CGameHandler.cpp 40 KB

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