CGameHandler.cpp 54 KB

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