CGameHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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/CHeroHandler.h"
  17. #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types
  18. #include "../lib/VCMI_Lib.h"
  19. extern bool end;
  20. bool makingTurn;
  21. boost::condition_variable cTurn;
  22. boost::mutex mTurn;
  23. boost::shared_mutex gsm;
  24. double distance(int3 a, int3 b)
  25. {
  26. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  27. }
  28. //bool CGameState::checkFunc(int obid, std::string name)
  29. //{
  30. // if (objscr.find(obid)!=objscr.end())
  31. // {
  32. // if(objscr[obid].find(name)!=objscr[obid].end())
  33. // {
  34. // return true;
  35. // }
  36. // }
  37. // return false;
  38. //}
  39. void CGameHandler::handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script)
  40. {
  41. std::vector<int> tempv = script->yourObjects();
  42. for (unsigned i=0;i<tempv.size();i++)
  43. {
  44. (*mapa)[tempv[i]]=script;
  45. }
  46. cppscripts.insert(script);
  47. }
  48. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  49. {
  50. try
  51. {
  52. ui16 pom;
  53. while(!end)
  54. {
  55. c >> pom;
  56. switch(pom)
  57. {
  58. case 100: //my interface ended its turn
  59. {
  60. mTurn.lock();
  61. makingTurn = false;
  62. mTurn.unlock();
  63. cTurn.notify_all();
  64. break;
  65. }
  66. case 501://interface wants to move hero
  67. {
  68. int3 start, end;
  69. si32 id;
  70. c >> id >> start >> end;
  71. int3 hmpos = end + int3(-1,0,0);
  72. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  73. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  74. int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end));
  75. TryMoveHero tmh;
  76. tmh.id = id;
  77. tmh.start = start;
  78. tmh.end = end;
  79. tmh.result = 0;
  80. tmh.movePoints = h->movement;
  81. if((h->getOwner() != gs->currentPlayer) || //not turn of that hero
  82. (distance(start,end)>=1.5) || //tiles are not neighouring
  83. (h->movement < cost) || //lack of movement points
  84. (t.tertype == rock) || //rock
  85. (!h->canWalkOnSea() && t.tertype == water) ||
  86. (t.blocked && !t.visitable) ) //tile is blocked andnot visitable
  87. goto fail;
  88. //check if there is blocking visitable object
  89. bool blockvis = false;
  90. tmh.movePoints = h->movement = (h->movement-cost); //take move points
  91. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  92. {
  93. if(obj->blockVisit)
  94. {
  95. blockvis = true;
  96. break;
  97. }
  98. }
  99. //we start moving
  100. if(blockvis)//interaction with blocking object (like resources)
  101. {
  102. sendAndApply(&tmh); //failed to move to that tile but we visit object
  103. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  104. {
  105. if (obj->blockVisit)
  106. {
  107. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  108. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  109. if(obj->state) //hard-coded function
  110. obj->state->onHeroVisit(obj->id,h->subID);
  111. }
  112. }
  113. break;
  114. }
  115. else //normal move
  116. {
  117. tmh.result = 1;
  118. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x][start.y][start.z].visitableObjects)
  119. {
  120. //TODO: allow to handle this in script-languages
  121. if(obj->state) //hard-coded function
  122. obj->state->onHeroLeave(obj->id,h->subID);
  123. }
  124. //reveal fog of war
  125. int heroSight = h->getSightDistance();
  126. int xbeg = start.x - heroSight - 2;
  127. if(xbeg < 0)
  128. xbeg = 0;
  129. int xend = start.x + heroSight + 2;
  130. if(xend >= gs->map->width)
  131. xend = gs->map->width;
  132. int ybeg = start.y - heroSight - 2;
  133. if(ybeg < 0)
  134. ybeg = 0;
  135. int yend = start.y + heroSight + 2;
  136. if(yend >= gs->map->height)
  137. yend = gs->map->height;
  138. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  139. {
  140. for(int yd=ybeg; yd<yend; ++yd)
  141. {
  142. int deltaX = (hmpos.x-xd)*(hmpos.x-xd);
  143. int deltaY = (hmpos.y-yd)*(hmpos.y-yd);
  144. if(deltaX+deltaY<h->getSightDistance()*h->getSightDistance())
  145. {
  146. if(gs->players[h->getOwner()].fogOfWarMap[xd][yd][hmpos.z] == 0)
  147. {
  148. tmh.fowRevealed.insert(int3(xd,yd,hmpos.z));
  149. }
  150. }
  151. }
  152. }
  153. sendAndApply(&tmh);
  154. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  155. {
  156. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  157. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  158. if(obj->state) //hard-coded function
  159. obj->state->onHeroVisit(obj->id,h->id);
  160. }
  161. }
  162. break;
  163. fail:
  164. sendAndApply(&tmh);
  165. break;
  166. }
  167. case 502: //swap creatures in garrison
  168. {
  169. ui8 what, p1, p2; si32 id1, id2;
  170. c >> what >> id1 >> p1 >> id2 >> p2;
  171. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  172. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  173. CCreatureSet *S1 = &s1->army, *S2 = &s2->army;
  174. if(what==1) //swap
  175. {
  176. int pom = S2->slots[p2].first;
  177. S2->slots[p2].first = S1->slots[p1].first;
  178. S1->slots[p1].first = pom;
  179. int pom2 = S2->slots[p2].second;
  180. S2->slots[p2].second = S1->slots[p1].second;
  181. S1->slots[p1].second = pom2;
  182. if(!S1->slots[p1].first)
  183. S1->slots.erase(p1);
  184. if(!S2->slots[p2].first)
  185. S2->slots.erase(p2);
  186. }
  187. else if(what==2)//merge
  188. {
  189. if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature
  190. S2->slots[p2].second += S1->slots[p1].second;
  191. S1->slots[p1].first = NULL;
  192. S1->slots[p1].second = 0;
  193. S1->slots.erase(p1);
  194. }
  195. else if(what==3) //split
  196. {
  197. si32 val;
  198. c >> val;
  199. if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free
  200. S2->slots[p2].first = S1->slots[p1].first;
  201. S2->slots[p2].second = val;
  202. S1->slots[p1].second -= val;
  203. if(!S1->slots[p1].second) //if we've moved all creatures
  204. S1->slots.erase(p1);
  205. }
  206. SetGarrisons sg;
  207. sg.garrs[id1] = *S1;
  208. if(s1 != s2)
  209. sg.garrs[id2] = *S2;
  210. sendAndApply(&sg);
  211. break;
  212. }
  213. default:
  214. throw std::exception("Not supported client message!");
  215. break;
  216. }
  217. }
  218. }
  219. catch (const std::exception& e)
  220. {
  221. std::cerr << e.what() << std::endl;
  222. end = true;
  223. }
  224. catch (const std::exception * e)
  225. {
  226. std::cerr << e->what()<< std::endl;
  227. end = true;
  228. delete e;
  229. }
  230. catch(...)
  231. {
  232. end = true;
  233. }
  234. }
  235. CGameHandler::CGameHandler(void)
  236. {
  237. gs = NULL;
  238. }
  239. CGameHandler::~CGameHandler(void)
  240. {
  241. delete gs;
  242. }
  243. void CGameHandler::init(StartInfo *si, int Seed)
  244. {
  245. Mapa *map = new Mapa(si->mapname);
  246. gs = new CGameState();
  247. gs->init(si,map,Seed);
  248. /****************************LUA OBJECT SCRIPTS************************************************/
  249. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  250. //for (int i=0; i<lf->size(); i++)
  251. //{
  252. // try
  253. // {
  254. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  255. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  256. // CLuaCallback::registerFuncs(objs->is);
  257. // //objs
  258. // for (int j=0; j<temp->size(); j++)
  259. // {
  260. // int obid ; //obj ID
  261. // int dspos = (*temp)[j].find_first_of('_');
  262. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  263. // std::string fname = (*temp)[j].substr(0,dspos);
  264. // if (skrypty->find(obid)==skrypty->end())
  265. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  266. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  267. // }
  268. // delete temp;
  269. // }HANDLE_EXCEPTION
  270. //}
  271. //delete lf;
  272. }
  273. int lowestSpeed(CGHeroInstance * chi)
  274. {
  275. std::map<si32,std::pair<ui32,si32> >::iterator i = chi->army.slots.begin();
  276. int ret = VLC->creh->creatures[(*i++).second.first].speed;
  277. for (;i!=chi->army.slots.end();i++)
  278. {
  279. ret = min(ret,VLC->creh->creatures[(*i).second.first].speed);
  280. }
  281. return ret;
  282. }
  283. int valMovePoints(CGHeroInstance * chi)
  284. {
  285. int ret = 1270+70*lowestSpeed(chi);
  286. if (ret>2000)
  287. ret=2000;
  288. //TODO: additional bonuses (but they aren't currently stored in chi)
  289. return ret;
  290. }
  291. void CGameHandler::newTurn()
  292. {
  293. NewTurn n;
  294. n.day = gs->day + 1;
  295. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  296. {
  297. if(i->first>=PLAYER_LIMIT) continue;
  298. NewTurn::Resources r;
  299. r.player = i->first;
  300. for(int j=0;j<RESOURCE_QUANTITY;j++)
  301. r.resources[j] = i->second.resources[j];
  302. for (unsigned j=0;j<(*i).second.heroes.size();j++) //handle heroes
  303. {
  304. NewTurn::Hero h;
  305. h.id = (*i).second.heroes[j]->id;
  306. h.move = valMovePoints((*i).second.heroes[j]);
  307. h.mana = (*i).second.heroes[j]->mana;
  308. n.heroes.insert(h);
  309. }
  310. for(unsigned j=0;j<i->second.towns.size();j++)//handle towns
  311. {
  312. i->second.towns[j]->builded=0;
  313. //if(gs->getDate(1)==1) //first day of week
  314. //{
  315. // for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  316. // {
  317. // if(i->second.towns[j]->creatureDwelling(k))//there is dwelling (k-level)
  318. // i->second.towns[j]->strInfo.creatures[k]+=i->second.towns[j]->creatureGrowth(k);
  319. // }
  320. //}
  321. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  322. r.resources[6] += i->second.towns[j]->dailyIncome();
  323. }
  324. n.res.insert(r);
  325. }
  326. sendAndApply(&n);
  327. for (std::set<CCPPObjectScript *>::iterator i=cppscripts.begin();i!=cppscripts.end();i++)
  328. {
  329. (*i)->newTurn();
  330. }
  331. }
  332. void CGameHandler::run()
  333. {
  334. BOOST_FOREACH(CConnection *cc, conns)
  335. {//init conn.
  336. ui8 quantity, pom;
  337. //ui32 seed;
  338. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  339. (*cc) >> quantity;
  340. for(int i=0;i<quantity;i++)
  341. {
  342. (*cc) >> pom;
  343. gsm.lock();
  344. connections[pom] = cc;
  345. gsm.unlock();
  346. }
  347. }
  348. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  349. {
  350. std::set<int> pom;
  351. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  352. if(j->second == *i)
  353. pom.insert(j->first);
  354. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  355. }
  356. /****************************SCRIPTS************************************************/
  357. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  358. /****************************C++ OBJECT SCRIPTS************************************************/
  359. std::map<int,CCPPObjectScript*> scripts;
  360. CScriptCallback * csc = new CScriptCallback();
  361. csc->gh = this;
  362. handleCPPObjS(&scripts,new CVisitableOPH(csc));
  363. handleCPPObjS(&scripts,new CVisitableOPW(csc));
  364. handleCPPObjS(&scripts,new CPickable(csc));
  365. handleCPPObjS(&scripts,new CMines(csc));
  366. handleCPPObjS(&scripts,new CTownScript(csc));
  367. handleCPPObjS(&scripts,new CHeroScript(csc));
  368. handleCPPObjS(&scripts,new CMonsterS(csc));
  369. handleCPPObjS(&scripts,new CCreatureGen(csc));
  370. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  371. //std::string temps("newObject");
  372. for (unsigned i=0; i<gs->map->objects.size(); i++)
  373. {
  374. //c++ scripts
  375. if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  376. {
  377. gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  378. gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  379. }
  380. else
  381. {
  382. gs->map->objects[i]->state = NULL;
  383. }
  384. //// lua scripts
  385. //if(checkFunc(map->objects[i]->ID,temps))
  386. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  387. }
  388. while (!end)
  389. {
  390. newTurn();
  391. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  392. {
  393. if((i->second.towns.size()==0 && i->second.heroes.size()==0) || i->second.color<0) continue; //players has not towns/castle - loser
  394. makingTurn = true;
  395. gs->currentPlayer = i->first;
  396. *connections[i->first] << ui16(100) << i->first;
  397. //wait till turn is done
  398. boost::unique_lock<boost::mutex> lock(mTurn);
  399. while(makingTurn && !end)
  400. {
  401. boost::posix_time::time_duration p;
  402. p= boost::posix_time::seconds(1);
  403. cTurn.timed_wait(lock,p);
  404. }
  405. }
  406. }
  407. }