CGameHandler.cpp 41 KB

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