CGameHandler.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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 "../CLua.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, boost::function<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. applyAndAsk(&hlu,hero->tempOwner,boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::changeSecSkill,this,ID,_1,1,0)),_1))); //call changeSecSkill with appropriate args when client responds
  230. }
  231. }
  232. }
  233. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2)
  234. {
  235. BattleInfo *curB = new BattleInfo;
  236. //battle start
  237. {
  238. battleResult.set(NULL);
  239. std::vector<CStack*> & stacks = (curB->stacks);
  240. curB->tile = tile;
  241. curB->siege = 0; //TODO: add sieges
  242. curB->army1=army1;
  243. curB->army2=army2;
  244. curB->hero1=(hero1)?(hero1->id):(-1);
  245. curB->hero2=(hero2)?(hero2->id):(-1);
  246. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  247. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  248. curB->round = -2;
  249. curB->activeStack = -1;
  250. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  251. {
  252. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true));
  253. stacks[stacks.size()-1]->ID = stacks.size()-1;
  254. }
  255. //initialization of positions
  256. switch(army1.slots.size()) //for attacker
  257. {
  258. case 0:
  259. break;
  260. case 1:
  261. stacks[0]->position = 86; //6
  262. break;
  263. case 2:
  264. stacks[0]->position = 35; //3
  265. stacks[1]->position = 137; //9
  266. break;
  267. case 3:
  268. stacks[0]->position = 35; //3
  269. stacks[1]->position = 86; //6
  270. stacks[2]->position = 137; //9
  271. break;
  272. case 4:
  273. stacks[0]->position = 1; //1
  274. stacks[1]->position = 69; //5
  275. stacks[2]->position = 103; //7
  276. stacks[3]->position = 171; //11
  277. break;
  278. case 5:
  279. stacks[0]->position = 1; //1
  280. stacks[1]->position = 35; //3
  281. stacks[2]->position = 86; //6
  282. stacks[3]->position = 137; //9
  283. stacks[4]->position = 171; //11
  284. break;
  285. case 6:
  286. stacks[0]->position = 1; //1
  287. stacks[1]->position = 35; //3
  288. stacks[2]->position = 69; //5
  289. stacks[3]->position = 103; //7
  290. stacks[4]->position = 137; //9
  291. stacks[5]->position = 171; //11
  292. break;
  293. case 7:
  294. stacks[0]->position = 1; //1
  295. stacks[1]->position = 35; //3
  296. stacks[2]->position = 69; //5
  297. stacks[3]->position = 86; //6
  298. stacks[4]->position = 103; //7
  299. stacks[5]->position = 137; //9
  300. stacks[6]->position = 171; //11
  301. break;
  302. default: //fault
  303. break;
  304. }
  305. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  306. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false));
  307. switch(army2.slots.size()) //for defender
  308. {
  309. case 0:
  310. break;
  311. case 1:
  312. stacks[0+army1.slots.size()]->position = 100; //6
  313. break;
  314. case 2:
  315. stacks[0+army1.slots.size()]->position = 49; //3
  316. stacks[1+army1.slots.size()]->position = 151; //9
  317. break;
  318. case 3:
  319. stacks[0+army1.slots.size()]->position = 49; //3
  320. stacks[1+army1.slots.size()]->position = 100; //6
  321. stacks[2+army1.slots.size()]->position = 151; //9
  322. break;
  323. case 4:
  324. stacks[0+army1.slots.size()]->position = 15; //1
  325. stacks[1+army1.slots.size()]->position = 83; //5
  326. stacks[2+army1.slots.size()]->position = 117; //7
  327. stacks[3+army1.slots.size()]->position = 185; //11
  328. break;
  329. case 5:
  330. stacks[0+army1.slots.size()]->position = 15; //1
  331. stacks[1+army1.slots.size()]->position = 49; //3
  332. stacks[2+army1.slots.size()]->position = 100; //6
  333. stacks[3+army1.slots.size()]->position = 151; //9
  334. stacks[4+army1.slots.size()]->position = 185; //11
  335. break;
  336. case 6:
  337. stacks[0+army1.slots.size()]->position = 15; //1
  338. stacks[1+army1.slots.size()]->position = 49; //3
  339. stacks[2+army1.slots.size()]->position = 83; //5
  340. stacks[3+army1.slots.size()]->position = 117; //7
  341. stacks[4+army1.slots.size()]->position = 151; //9
  342. stacks[5+army1.slots.size()]->position = 185; //11
  343. break;
  344. case 7:
  345. stacks[0+army1.slots.size()]->position = 15; //1
  346. stacks[1+army1.slots.size()]->position = 49; //3
  347. stacks[2+army1.slots.size()]->position = 83; //5
  348. stacks[3+army1.slots.size()]->position = 100; //6
  349. stacks[4+army1.slots.size()]->position = 117; //7
  350. stacks[5+army1.slots.size()]->position = 151; //9
  351. stacks[6+army1.slots.size()]->position = 185; //11
  352. break;
  353. default: //fault
  354. break;
  355. }
  356. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  357. {
  358. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  359. {
  360. stacks[g]->position += 1;
  361. }
  362. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  363. {
  364. stacks[g]->position -= 1;
  365. }
  366. }
  367. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  368. //block engaged players
  369. if(hero1->tempOwner<PLAYER_LIMIT)
  370. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  371. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  372. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  373. //send info about battles
  374. BattleStart bs;
  375. bs.info = curB;
  376. sendAndApply(&bs);
  377. NEW_ROUND;
  378. }
  379. //tactic round
  380. {
  381. NEW_ROUND;
  382. if( (hero1 && hero1->getSecSkillLevel(19)>=0) ||
  383. ( hero2 && hero2->getSecSkillLevel(19)>=0) )//someone has tactics
  384. {
  385. //TODO: tactic round (round -1)
  386. }
  387. }
  388. //main loop
  389. while(!battleResult.get()) //till the end of the battle ;]
  390. {
  391. NEW_ROUND;
  392. std::vector<CStack*> & stacks = (gs->curB->stacks);
  393. const BattleInfo & curB = *gs->curB;
  394. //stack loop
  395. for(unsigned i=0;i<stacks.size() && !battleResult.get();i++)
  396. {
  397. if(!stacks[i]->alive) continue;//indicates imposiibility of making action for this dead unit
  398. BattleSetActiveStack sas;
  399. sas.stack = stacks[i]->ID;
  400. sendAndApply(&sas);
  401. //wait for response about battle action
  402. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  403. while(!battleMadeAction.data)
  404. battleMadeAction.cond.wait(lock);
  405. battleMadeAction.data = false;
  406. }
  407. }
  408. //unblock engaged players
  409. if(hero1->tempOwner<PLAYER_LIMIT)
  410. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  411. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  412. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  413. //end battle, remove all info, free memory
  414. sendAndApply(battleResult.data);
  415. delete battleResult.data;
  416. //for(int i=0;i<stacks.size();i++)
  417. // delete stacks[i];
  418. //delete curB;
  419. //curB = NULL;
  420. }
  421. void prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  422. {
  423. bat.stackAttacking = att->ID;
  424. bat.bsa.stackAttacked = def->ID;
  425. bat.bsa.damageAmount = BattleInfo::calculateDmg(att, def);//counting dealt damage
  426. //applying damages
  427. bat.bsa.killedAmount = bat.bsa.damageAmount / def->creature->hitPoints;
  428. unsigned damageFirst = bat.bsa.damageAmount % def->creature->hitPoints;
  429. if( def->firstHPleft <= damageFirst )
  430. {
  431. bat.bsa.killedAmount++;
  432. bat.bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  433. }
  434. else
  435. {
  436. bat.bsa.newHP = def->firstHPleft - damageFirst;
  437. }
  438. if(def->amount <= bat.bsa.killedAmount) //stack killed
  439. {
  440. bat.bsa.newAmount = 0;
  441. bat.bsa.flags |= 1;
  442. }
  443. else
  444. {
  445. bat.bsa.newAmount = def->amount - bat.bsa.killedAmount;
  446. }
  447. }
  448. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  449. {
  450. try
  451. {
  452. ui16 pom;
  453. while(!end2)
  454. {
  455. c >> pom;
  456. bool blockvis = false;
  457. switch(pom)
  458. {
  459. case 100: //my interface ended its turn
  460. {
  461. states.setFlag(gs->currentPlayer,&PlayerStatus::makingTurn,false);
  462. break;
  463. }
  464. case 500:
  465. {
  466. si32 id;
  467. c >> id;
  468. RemoveHero rh(id);
  469. sendAndApply(&rh);
  470. break;
  471. }
  472. case 501://interface wants to move hero
  473. {
  474. int3 start, end;
  475. si32 id;
  476. c >> id >> start >> end;
  477. int3 hmpos = end + int3(-1,0,0);
  478. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  479. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  480. int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end));
  481. TryMoveHero tmh;
  482. tmh.id = id;
  483. tmh.start = start;
  484. tmh.end = end;
  485. tmh.result = 0;
  486. tmh.movePoints = h->movement;
  487. if((h->getOwner() != gs->currentPlayer) || //not turn of that hero
  488. (distance(start,end)>=1.5) || //tiles are not neighouring
  489. (h->movement < cost) || //lack of movement points
  490. (t.tertype == rock) || //rock
  491. (!h->canWalkOnSea() && t.tertype == water) ||
  492. (t.blocked && !t.visitable) ) //tile is blocked andnot visitable
  493. goto fail;
  494. //check if there is blocking visitable object
  495. blockvis = false;
  496. tmh.movePoints = h->movement = (h->movement-cost); //take move points
  497. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  498. {
  499. if(obj->blockVisit)
  500. {
  501. blockvis = true;
  502. break;
  503. }
  504. }
  505. //we start moving
  506. if(blockvis)//interaction with blocking object (like resources)
  507. {
  508. sendAndApply(&tmh); //failed to move to that tile but we visit object
  509. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  510. {
  511. if (obj->blockVisit)
  512. {
  513. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  514. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  515. if(obj->state) //hard-coded function
  516. obj->state->onHeroVisit(obj->id,h->id);
  517. }
  518. }
  519. break;
  520. }
  521. else //normal move
  522. {
  523. tmh.result = 1;
  524. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x][start.y][start.z].visitableObjects)
  525. {
  526. //TODO: allow to handle this in script-languages
  527. if(obj->state) //hard-coded function
  528. obj->state->onHeroLeave(obj->id,h->id);
  529. }
  530. //reveal fog of war
  531. int heroSight = h->getSightDistance();
  532. int xbeg = start.x - heroSight - 2;
  533. if(xbeg < 0)
  534. xbeg = 0;
  535. int xend = start.x + heroSight + 2;
  536. if(xend >= gs->map->width)
  537. xend = gs->map->width;
  538. int ybeg = start.y - heroSight - 2;
  539. if(ybeg < 0)
  540. ybeg = 0;
  541. int yend = start.y + heroSight + 2;
  542. if(yend >= gs->map->height)
  543. yend = gs->map->height;
  544. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  545. {
  546. for(int yd=ybeg; yd<yend; ++yd)
  547. {
  548. int deltaX = (hmpos.x-xd)*(hmpos.x-xd);
  549. int deltaY = (hmpos.y-yd)*(hmpos.y-yd);
  550. if(deltaX+deltaY<h->getSightDistance()*h->getSightDistance())
  551. {
  552. if(gs->players[h->getOwner()].fogOfWarMap[xd][yd][hmpos.z] == 0)
  553. {
  554. tmh.fowRevealed.insert(int3(xd,yd,hmpos.z));
  555. }
  556. }
  557. }
  558. }
  559. sendAndApply(&tmh);
  560. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  561. {
  562. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  563. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  564. if(obj->state) //hard-coded function
  565. obj->state->onHeroVisit(obj->id,h->id);
  566. }
  567. }
  568. break;
  569. fail:
  570. sendAndApply(&tmh);
  571. break;
  572. }
  573. case 502: //swap creatures in garrison
  574. {
  575. ui8 what, p1, p2; si32 id1, id2;
  576. c >> what >> id1 >> p1 >> id2 >> p2;
  577. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  578. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  579. CCreatureSet *S1 = &s1->army, *S2 = &s2->army;
  580. if(what==1) //swap
  581. {
  582. int pom = S2->slots[p2].first;
  583. S2->slots[p2].first = S1->slots[p1].first;
  584. S1->slots[p1].first = pom;
  585. int pom2 = S2->slots[p2].second;
  586. S2->slots[p2].second = S1->slots[p1].second;
  587. S1->slots[p1].second = pom2;
  588. if(!S1->slots[p1].first)
  589. S1->slots.erase(p1);
  590. if(!S2->slots[p2].first)
  591. S2->slots.erase(p2);
  592. }
  593. else if(what==2)//merge
  594. {
  595. if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature
  596. S2->slots[p2].second += S1->slots[p1].second;
  597. S1->slots[p1].first = NULL;
  598. S1->slots[p1].second = 0;
  599. S1->slots.erase(p1);
  600. }
  601. else if(what==3) //split
  602. {
  603. si32 val;
  604. c >> val;
  605. if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free
  606. S2->slots[p2].first = S1->slots[p1].first;
  607. S2->slots[p2].second = val;
  608. S1->slots[p1].second -= val;
  609. if(!S1->slots[p1].second) //if we've moved all creatures
  610. S1->slots.erase(p1);
  611. }
  612. SetGarrisons sg;
  613. sg.garrs[id1] = *S1;
  614. if(s1 != s2)
  615. sg.garrs[id2] = *S2;
  616. sendAndApply(&sg);
  617. break;
  618. }
  619. case 503:
  620. {
  621. si32 id;
  622. ui8 pos;
  623. c >> id >> pos;
  624. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  625. s1->army.slots.erase(pos);
  626. SetGarrisons sg;
  627. sg.garrs[id] = s1->army;
  628. sendAndApply(&sg);
  629. break;
  630. }
  631. case 504:
  632. {
  633. si32 tid, bid;
  634. c >> tid >> bid;
  635. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  636. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  637. for(int i=0;i<RESOURCE_QUANTITY;i++)
  638. if(b->resources[i] > gs->players[t->tempOwner].resources[i])
  639. break; //no res
  640. //TODO: check requirements
  641. //TODO: check if building isn't forbidden
  642. NewStructures ns;
  643. ns.tid = tid;
  644. if(bid>36) //upg dwelling
  645. {
  646. if(t->getHordeLevel(0) == (bid-37))
  647. ns.bid.insert(19);
  648. else if(t->getHordeLevel(1) == (bid-37))
  649. ns.bid.insert(25);
  650. }
  651. else if(bid >= 30) //bas. dwelling
  652. {
  653. SetAvailableCreatures ssi;
  654. ssi.tid = tid;
  655. ssi.creatures = t->strInfo.creatures;
  656. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  657. sendAndApply(&ssi);
  658. }
  659. ns.bid.insert(bid);
  660. ns.builded = t->builded + 1;
  661. sendAndApply(&ns);
  662. SetResources sr;
  663. sr.player = t->tempOwner;
  664. sr.res = gs->players[t->tempOwner].resources;
  665. for(int i=0;i<7;i++)
  666. sr.res[i]-=b->resources[i];
  667. sendAndApply(&sr);
  668. break;
  669. }
  670. case 506: //recruit creature
  671. {
  672. si32 objid, ser=-1; //ser - used dwelling level
  673. ui32 crid, cram; //recruited creature id and amount
  674. c >> objid >> crid >> cram;
  675. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  676. //verify
  677. bool found = false;
  678. typedef std::pair<const int,int> Parka;
  679. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  680. {
  681. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  682. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  683. {
  684. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  685. ser = av->first;
  686. break;
  687. }
  688. }
  689. int slot = t->army.getSlotFor(crid);
  690. if(!found || //no such creature
  691. cram > VLC->creh->creatures[crid].maxAmount(gs->players[t->tempOwner].resources) || //lack of resources
  692. cram<=0 ||
  693. slot<0 )
  694. break;
  695. //recruit
  696. SetResources sr;
  697. sr.player = t->tempOwner;
  698. for(int i=0;i<RESOURCE_QUANTITY;i++)
  699. sr.res[i] = gs->players[t->tempOwner].resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  700. SetAvailableCreatures sac;
  701. sac.tid = objid;
  702. sac.creatures = t->strInfo.creatures;
  703. sac.creatures[ser] -= cram;
  704. SetGarrisons sg;
  705. sg.garrs[objid] = t->army;
  706. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  707. {
  708. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  709. }
  710. else //add creatures to a already existing stack
  711. {
  712. sg.garrs[objid].slots[slot].second += cram;
  713. }
  714. sendAndApply(&sr);
  715. sendAndApply(&sac);
  716. sendAndApply(&sg);
  717. break;
  718. }
  719. case 2001:
  720. {
  721. ui32 qid, answer;
  722. c >> qid >> answer;
  723. gsm.lock();
  724. boost::function<void(ui32)> callb = callbacks[qid];
  725. callbacks.erase(qid);
  726. gsm.unlock();
  727. callb(answer);
  728. break;
  729. }
  730. case 3002:
  731. {
  732. BattleAction ba;
  733. c >> ba;
  734. switch(ba.actionType)
  735. {
  736. case 2: //walk
  737. {
  738. moveStack(ba.stackNumber,ba.destinationTile);
  739. break;
  740. }
  741. case 3: //defend
  742. {
  743. break;
  744. }
  745. case 4: //retreat/flee
  746. {
  747. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  748. //TODO: calculate casualties
  749. //TODO: remove retreating hero from map and place it in recrutation list
  750. BattleResult *br = new BattleResult;
  751. br->result = 1;
  752. battleResult.set(br);
  753. break;
  754. }
  755. case 6: //walk or attack
  756. {
  757. moveStack(ba.stackNumber,ba.destinationTile);
  758. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  759. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  760. if((curStack->position != ba.destinationTile) || //we wasn't able to reach destination tile
  761. (BattleInfo::mutualPosition(ba.destinationTile,ba.additionalInfo)<0) ) //destination tile is not neighbouring with enemy stack
  762. return;
  763. BattleAttack bat;
  764. prepareAttack(bat,curStack,stackAtEnd);
  765. sendAndApply(&bat);
  766. break;
  767. }
  768. case 7: //shoot
  769. {
  770. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  771. *destStack= gs->curB->getStackT(ba.destinationTile);
  772. BattleAttack bat;
  773. prepareAttack(bat,curStack,destStack);
  774. bat.flags |= 1;
  775. sendAndApply(&bat);
  776. break;
  777. }
  778. }
  779. battleMadeAction.setn(true);
  780. //sprawdzic czy po tej akcji ktoras strona nie wygrala bitwy
  781. break;
  782. }
  783. default:
  784. #ifndef __GNUC__
  785. throw std::exception("Not supported client message!");
  786. #else
  787. throw std::exception();
  788. #endif
  789. break;
  790. }
  791. }
  792. }
  793. catch (const std::exception& e)
  794. {
  795. std::cerr << e.what() << std::endl;
  796. end2 = true;
  797. }
  798. catch (const std::exception * e)
  799. {
  800. std::cerr << e->what()<< std::endl;
  801. end2 = true;
  802. delete e;
  803. }
  804. catch(...)
  805. {
  806. end2 = true;
  807. }
  808. }
  809. void CGameHandler::moveStack(int stack, int dest)
  810. {
  811. CStack *curStack = gs->curB->getStack(stack),
  812. *stackAtEnd = gs->curB->getStackT(dest);
  813. //initing necessary tables
  814. bool accessibility[187];
  815. if(curStack->creature->isDoubleWide())
  816. gs->curB->getAccessibilityMapForTwoHex(accessibility,curStack->attackerOwned,curStack->ID);
  817. else
  818. gs->curB->getAccessibilityMap(accessibility,curStack->ID);
  819. if((stackAtEnd && stackAtEnd->alive) || !accessibility[dest])
  820. return;
  821. //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
  822. // return false;
  823. std::vector<int> path = gs->curB->getPath(curStack->position,dest,accessibility);
  824. int tilesToMove = std::max((int)path.size()-curStack->creature->speed, 0);
  825. for(int v=path.size()-1; v>=tilesToMove; --v)
  826. {
  827. //inform clients about move
  828. BattleStackMoved sm;
  829. sm.stack = curStack->ID;
  830. sm.tile = path[v];
  831. if(v==path.size()-1) //move start - set flag
  832. sm.flags |= 1;
  833. if(v==0) //move end - set flag
  834. sm.flags |= 2;
  835. sendAndApply(&sm);
  836. }
  837. }
  838. CGameHandler::CGameHandler(void)
  839. {
  840. gs = NULL;
  841. }
  842. CGameHandler::~CGameHandler(void)
  843. {
  844. delete gs;
  845. }
  846. void CGameHandler::init(StartInfo *si, int Seed)
  847. {
  848. Mapa *map = new Mapa(si->mapname);
  849. gs = new CGameState();
  850. gs->init(si,map,Seed);
  851. /****************************LUA OBJECT SCRIPTS************************************************/
  852. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  853. //for (int i=0; i<lf->size(); i++)
  854. //{
  855. // try
  856. // {
  857. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  858. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  859. // CLuaCallback::registerFuncs(objs->is);
  860. // //objs
  861. // for (int j=0; j<temp->size(); j++)
  862. // {
  863. // int obid ; //obj ID
  864. // int dspos = (*temp)[j].find_first_of('_');
  865. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  866. // std::string fname = (*temp)[j].substr(0,dspos);
  867. // if (skrypty->find(obid)==skrypty->end())
  868. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  869. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  870. // }
  871. // delete temp;
  872. // }HANDLE_EXCEPTION
  873. //}
  874. //delete lf;
  875. }
  876. int lowestSpeed(CGHeroInstance * chi)
  877. {
  878. std::map<si32,std::pair<ui32,si32> >::iterator i = chi->army.slots.begin();
  879. int ret = VLC->creh->creatures[(*i++).second.first].speed;
  880. for (;i!=chi->army.slots.end();i++)
  881. {
  882. ret = std::min(ret,VLC->creh->creatures[(*i).second.first].speed);
  883. }
  884. return ret;
  885. }
  886. int valMovePoints(CGHeroInstance * chi)
  887. {
  888. int ret = 1270+70*lowestSpeed(chi);
  889. if (ret>2000)
  890. ret=2000;
  891. //TODO: additional bonuses (but they aren't currently stored in chi)
  892. return ret;
  893. }
  894. void CGameHandler::newTurn()
  895. {
  896. NewTurn n;
  897. n.day = gs->day + 1;
  898. n.resetBuilded = true;
  899. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  900. {
  901. if(i->first>=PLAYER_LIMIT) continue;
  902. SetResources r;
  903. r.player = i->first;
  904. for(int j=0;j<RESOURCE_QUANTITY;j++)
  905. r.res[j] = i->second.resources[j];
  906. for (unsigned j=0;j<(*i).second.heroes.size();j++) //handle heroes
  907. {
  908. NewTurn::Hero h;
  909. h.id = (*i).second.heroes[j]->id;
  910. h.move = valMovePoints((*i).second.heroes[j]);
  911. h.mana = (*i).second.heroes[j]->mana;
  912. n.heroes.insert(h);
  913. }
  914. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  915. {
  916. if(gs->getDate(1)==7) //first day of week
  917. {
  918. SetAvailableCreatures sac;
  919. sac.tid = (**j).id;
  920. sac.creatures = (**j).strInfo.creatures;
  921. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  922. {
  923. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  924. sac.creatures[k] += (**j).creatureGrowth(k);
  925. }
  926. n.cres.push_back(sac);
  927. }
  928. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  929. r.res[6] += (**j).dailyIncome();
  930. }
  931. n.res.push_back(r);
  932. }
  933. sendAndApply(&n);
  934. for (std::set<CCPPObjectScript *>::iterator i=cppscripts.begin();i!=cppscripts.end();i++)
  935. {
  936. (*i)->newTurn();
  937. }
  938. }
  939. void CGameHandler::run()
  940. {
  941. BOOST_FOREACH(CConnection *cc, conns)
  942. {//init conn.
  943. ui8 quantity, pom;
  944. //ui32 seed;
  945. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  946. (*cc) >> quantity;
  947. for(int i=0;i<quantity;i++)
  948. {
  949. (*cc) >> pom;
  950. gsm.lock();
  951. connections[pom] = cc;
  952. gsm.unlock();
  953. }
  954. }
  955. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  956. {
  957. std::set<int> pom;
  958. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  959. if(j->second == *i)
  960. pom.insert(j->first);
  961. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  962. }
  963. /****************************SCRIPTS************************************************/
  964. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  965. /****************************C++ OBJECT SCRIPTS************************************************/
  966. std::map<int,CCPPObjectScript*> scripts;
  967. CScriptCallback * csc = new CScriptCallback();
  968. csc->gh = this;
  969. handleCPPObjS(&scripts,new CVisitableOPH(csc));
  970. handleCPPObjS(&scripts,new CVisitableOPW(csc));
  971. handleCPPObjS(&scripts,new CPickable(csc));
  972. handleCPPObjS(&scripts,new CMines(csc));
  973. handleCPPObjS(&scripts,new CTownScript(csc));
  974. handleCPPObjS(&scripts,new CHeroScript(csc));
  975. handleCPPObjS(&scripts,new CMonsterS(csc));
  976. handleCPPObjS(&scripts,new CCreatureGen(csc));
  977. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  978. //std::string temps("newObject");
  979. for (unsigned i=0; i<gs->map->objects.size(); i++)
  980. {
  981. //c++ scripts
  982. if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  983. {
  984. gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  985. gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  986. }
  987. else
  988. {
  989. gs->map->objects[i]->state = NULL;
  990. }
  991. //// lua scripts
  992. //if(checkFunc(map->objects[i]->ID,temps))
  993. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  994. }
  995. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  996. states.addPlayer(i->first);
  997. while (!end2)
  998. {
  999. newTurn();
  1000. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1001. {
  1002. 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
  1003. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1004. gs->currentPlayer = i->first;
  1005. *connections[i->first] << ui16(100) << i->first;
  1006. //wait till turn is done
  1007. boost::unique_lock<boost::mutex> lock(states.mx);
  1008. while(states.players[i->first].makingTurn && !end2)
  1009. {
  1010. boost::posix_time::time_duration p;
  1011. p= boost::posix_time::seconds(1);
  1012. #ifdef _MSC_VER
  1013. states.cv.timed_wait(lock,p);
  1014. #else
  1015. boost::xtime time={0,0};
  1016. time.sec = static_cast<boost::xtime::xtime_sec_t>(p.total_seconds());
  1017. cTurn.timed_wait(lock,time);
  1018. #endif
  1019. }
  1020. }
  1021. }
  1022. }