CGameHandler.cpp 55 KB

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