CGameHandler.cpp 43 KB

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