CGameHandler.cpp 42 KB

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