CGameHandler.cpp 49 KB

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