CGameState.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889
  1. #define VCMI_DLL
  2. #include <algorithm>
  3. #include <queue>
  4. #include <fstream>
  5. #include "CGameState.h"
  6. #include <boost/random/linear_congruential.hpp>
  7. #include "hch/CDefObjInfoHandler.h"
  8. #include "hch/CArtHandler.h"
  9. #include "hch/CGeneralTextHandler.h"
  10. #include "hch/CTownHandler.h"
  11. #include "hch/CSpellHandler.h"
  12. #include "hch/CHeroHandler.h"
  13. #include "hch/CObjectHandler.h"
  14. #include "hch/CCreatureHandler.h"
  15. #include "lib/VCMI_Lib.h"
  16. #include "map.h"
  17. #include "StartInfo.h"
  18. #include "lib/NetPacks.h"
  19. #include <boost/foreach.hpp>
  20. #include <boost/thread.hpp>
  21. #include <boost/thread/shared_mutex.hpp>
  22. boost::rand48 ran;
  23. #ifdef min
  24. #undef min
  25. #endif
  26. #ifdef max
  27. #undef max
  28. #endif
  29. std::string DLL_EXPORT toString(MetaString &ms)
  30. {
  31. std::string ret;
  32. for(size_t i=0;i<ms.message.size();++i)
  33. {
  34. if(ms.message[i]>0)
  35. {
  36. ret += ms.strings[ms.message[i]-1];
  37. }
  38. else
  39. {
  40. std::vector<std::string> *vec;
  41. int type = ms.texts[-ms.message[i]-1].first,
  42. ser = ms.texts[-ms.message[i]-1].second;
  43. if(type == 5)
  44. {
  45. ret += VLC->arth->artifacts[ser].Name();
  46. continue;
  47. }
  48. else if(type == 7)
  49. {
  50. ret += VLC->creh->creatures[ser].namePl;
  51. continue;
  52. }
  53. else if(type == 9)
  54. {
  55. ret += VLC->generaltexth->mines[ser].first;
  56. continue;
  57. }
  58. else if(type == 10)
  59. {
  60. ret += VLC->generaltexth->mines[ser].second;
  61. continue;
  62. }
  63. else
  64. {
  65. switch(type)
  66. {
  67. case 1:
  68. vec = &VLC->generaltexth->allTexts;
  69. break;
  70. case 2:
  71. vec = &VLC->generaltexth->xtrainfo;
  72. break;
  73. case 3:
  74. vec = &VLC->generaltexth->names;
  75. break;
  76. case 4:
  77. vec = &VLC->generaltexth->restypes;
  78. break;
  79. case 6:
  80. vec = &VLC->generaltexth->arraytxt;
  81. break;
  82. case 8:
  83. vec = &VLC->generaltexth->creGens;
  84. break;
  85. case 11:
  86. vec = &VLC->generaltexth->advobtxt;
  87. break;
  88. case 12:
  89. vec = &VLC->generaltexth->artifEvents;
  90. break;
  91. }
  92. ret += (*vec)[ser];
  93. }
  94. }
  95. }
  96. for(size_t i=0; i < ms.replacements.size(); ++i)
  97. {
  98. ret.replace(ret.find("%s"),2,ms.replacements[i]);
  99. }
  100. return ret;
  101. }
  102. CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  103. {
  104. CGObjectInstance * nobj;
  105. switch(id)
  106. {
  107. case 34: //hero
  108. {
  109. CGHeroInstance * nobj = new CGHeroInstance();
  110. nobj->pos = pos;
  111. nobj->tempOwner = owner;
  112. nobj->subID = subid;
  113. //nobj->initHero(ran);
  114. return nobj;
  115. }
  116. case 98: //town
  117. nobj = new CGTownInstance;
  118. break;
  119. default: //rest of objects
  120. nobj = new CGObjectInstance;
  121. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  122. break;
  123. }
  124. nobj->ID = id;
  125. nobj->subID = subid;
  126. if(!nobj->defInfo)
  127. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  128. nobj->pos = pos;
  129. //nobj->state = NULL;//new CLuaObjectScript();
  130. nobj->tempOwner = owner;
  131. nobj->info = NULL;
  132. nobj->defInfo->id = id;
  133. nobj->defInfo->subid = subid;
  134. //assigning defhandler
  135. if(nobj->ID==34 || nobj->ID==98)
  136. return nobj;
  137. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  138. return nobj;
  139. }
  140. CStack * BattleInfo::getStack(int stackID)
  141. {
  142. for(int g=0; g<stacks.size(); ++g)
  143. {
  144. if(stacks[g]->ID == stackID)
  145. return stacks[g];
  146. }
  147. return NULL;
  148. }
  149. CStack * BattleInfo::getStackT(int tileID)
  150. {
  151. for(int g=0; g<stacks.size(); ++g)
  152. {
  153. if(stacks[g]->position == tileID
  154. || (stacks[g]->creature->isDoubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  155. || (stacks[g]->creature->isDoubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  156. {
  157. if(stacks[g]->alive())
  158. {
  159. return stacks[g];
  160. }
  161. }
  162. }
  163. return NULL;
  164. }
  165. void BattleInfo::getAccessibilityMap(bool *accessibility, int stackToOmmit)
  166. {
  167. memset(accessibility,1,BFIELD_SIZE); //initialize array with trues
  168. for(int g=0; g<stacks.size(); ++g)
  169. {
  170. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit) //we don't want to lock position of this stack
  171. continue;
  172. accessibility[stacks[g]->position] = false;
  173. if(stacks[g]->creature->isDoubleWide()) //if it's a double hex creature
  174. {
  175. if(stacks[g]->attackerOwned)
  176. accessibility[stacks[g]->position-1] = false;
  177. else
  178. accessibility[stacks[g]->position+1] = false;
  179. }
  180. }
  181. //TODO: obstacles
  182. }
  183. void BattleInfo::getAccessibilityMapForTwoHex(bool *accessibility, bool atackerSide, int stackToOmmit) //send pointer to at least 187 allocated bytes
  184. {
  185. bool mac[BFIELD_SIZE];
  186. getAccessibilityMap(mac,stackToOmmit);
  187. memcpy(accessibility,mac,BFIELD_SIZE);
  188. for(int b=0; b<BFIELD_SIZE; ++b)
  189. {
  190. if( mac[b] && !(atackerSide ? mac[b-1] : mac[b+1]))
  191. {
  192. accessibility[b] = false;
  193. }
  194. }
  195. //removing accessibility for side hexes
  196. for(int v=0; v<BFIELD_SIZE; ++v)
  197. if(atackerSide ? (v%17)==1 : (v%17)==15)
  198. accessibility[v] = false;
  199. }
  200. void BattleInfo::makeBFS(int start, bool*accessibility, int *predecessor, int *dists) //both pointers must point to the at least 187-elements int arrays
  201. {
  202. //inits
  203. for(int b=0; b<BFIELD_SIZE; ++b)
  204. predecessor[b] = -1;
  205. for(int g=0; g<BFIELD_SIZE; ++g)
  206. dists[g] = 100000000;
  207. std::queue<int> hexq; //bfs queue
  208. hexq.push(start);
  209. dists[hexq.front()] = 0;
  210. int curNext = -1; //for bfs loop only (helper var)
  211. while(!hexq.empty()) //bfs loop
  212. {
  213. int curHex = hexq.front();
  214. std::vector<int> neighbours = neighbouringTiles(curHex);
  215. hexq.pop();
  216. for(int nr=0; nr<neighbours.size(); nr++)
  217. {
  218. curNext = neighbours[nr];
  219. if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  220. continue;
  221. hexq.push(curNext);
  222. dists[curNext] = dists[curHex] + 1;
  223. predecessor[curNext] = curHex;
  224. }
  225. }
  226. };
  227. std::vector<int> BattleInfo::getAccessibility(int stackID)
  228. {
  229. std::vector<int> ret;
  230. bool ac[BFIELD_SIZE];
  231. CStack *s = getStack(stackID);
  232. if(s->creature->isDoubleWide())
  233. getAccessibilityMapForTwoHex(ac,s->attackerOwned,stackID);
  234. else
  235. getAccessibilityMap(ac,stackID);
  236. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  237. makeBFS(s->position,ac,pr,dist);
  238. for(int i=0;i<BFIELD_SIZE;i++)
  239. if(dist[i] <= s->speed())
  240. ret.push_back(i);
  241. return ret;
  242. }
  243. bool BattleInfo::isStackBlocked(int ID)
  244. {
  245. CStack *our = getStack(ID);
  246. for(int i=0; i<stacks.size();i++)
  247. {
  248. if( !stacks[i]->alive()
  249. || stacks[i]->owner==our->owner
  250. )
  251. continue; //we omit dead and allied stacks
  252. if(stacks[i]->creature->isDoubleWide())
  253. {
  254. if( mutualPosition(stacks[i]->position, our->position) >= 0
  255. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  256. return true;
  257. }
  258. else
  259. {
  260. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  261. return true;
  262. }
  263. }
  264. return false;
  265. }
  266. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  267. {
  268. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  269. return 0;
  270. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  271. return 1;
  272. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  273. return 5;
  274. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  275. return 2;
  276. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  277. return 4;
  278. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  279. return 3;
  280. return -1;
  281. }
  282. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  283. {
  284. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  285. std::vector<int> ret;
  286. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  287. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  288. CHECK_AND_PUSH(hex - 1);
  289. CHECK_AND_PUSH(hex + 1);
  290. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  291. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  292. #undef CHECK_AND_PUSH
  293. return ret;
  294. }
  295. std::vector<int> BattleInfo::getPath(int start, int dest, bool*accessibility)
  296. {
  297. int predecessor[BFIELD_SIZE]; //for getting the Path
  298. int dist[BFIELD_SIZE]; //calculated distances
  299. makeBFS(start,accessibility,predecessor,dist);
  300. //making the Path
  301. std::vector<int> path;
  302. int curElem = dest;
  303. while(curElem != start)
  304. {
  305. path.push_back(curElem);
  306. curElem = predecessor[curElem];
  307. }
  308. return path;
  309. }
  310. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  311. :creature(C),amount(A), baseAmount(A), owner(O), position(-1), ID(I), attackerOwned(AO), firstHPleft(C->hitPoints),
  312. shots(C->shots), slot(S), counterAttacks(1), effects(), state()
  313. {
  314. abilities = C->abilities;
  315. state.insert(ALIVE);
  316. }
  317. ui32 CStack::speed() const
  318. {
  319. int premy=0;
  320. const StackEffect *effect = 0;
  321. //haste effect check
  322. effect = getEffect(53);
  323. if(effect)
  324. premy += VLC->spellh->spells[effect->id].powers[effect->level];
  325. //slow effect check
  326. effect = getEffect(54);
  327. if(effect)
  328. premy -= (creature->speed * VLC->spellh->spells[effect->id].powers[effect->level])/100;
  329. //prayer effect check
  330. effect = getEffect(48);
  331. if(effect)
  332. premy += VLC->spellh->spells[effect->id].powers[effect->level];
  333. //bind effect check
  334. effect = getEffect(72);
  335. if(effect)
  336. premy = -creature->speed;
  337. return creature->speed + premy;
  338. }
  339. const CStack::StackEffect * CStack::getEffect(ui16 id) const
  340. {
  341. for (int i=0; i< effects.size(); i++)
  342. if(effects[i].id == id)
  343. return &effects[i];
  344. return NULL;
  345. }
  346. si8 CStack::Morale() const
  347. {
  348. si8 ret = morale;
  349. //premies from spells/other effects
  350. return ret;
  351. }
  352. si8 CStack::Luck() const
  353. {
  354. si8 ret = luck;
  355. //premies from spells/other effects
  356. return ret;
  357. }
  358. CGHeroInstance* CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, int notThatOne)
  359. {
  360. if(player<0 || player>=PLAYER_LIMIT)
  361. {
  362. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  363. return NULL;
  364. }
  365. std::vector<CGHeroInstance *> pool;
  366. int sum=0, r;
  367. if(native)
  368. {
  369. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  370. {
  371. if(pavailable[i->first] & 1<<player
  372. && i->second->type->heroType/2 == town->typeID
  373. && i->second->subID != notThatOne
  374. )
  375. {
  376. pool.push_back(i->second);
  377. }
  378. }
  379. if(!pool.size())
  380. return pickHeroFor(false,player,town,notThatOne);
  381. else
  382. return pool[rand()%pool.size()];
  383. }
  384. else
  385. {
  386. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  387. {
  388. if(pavailable[i->first] & 1<<player
  389. && i->second->subID != notThatOne
  390. )
  391. {
  392. pool.push_back(i->second);
  393. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  394. }
  395. }
  396. if(!pool.size())
  397. {
  398. tlog1 << "There are no heroes available for player " << player<<"!\n";
  399. return NULL;
  400. }
  401. r = rand()%sum;
  402. for(int i=0; i<pool.size(); i++)
  403. {
  404. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  405. if(r<0)
  406. return pool[i];
  407. }
  408. return pool[pool.size()-1];
  409. }
  410. }
  411. void CGameState::applyNL(IPack * pack)
  412. {
  413. switch(pack->getType())
  414. {
  415. case 101://NewTurn
  416. {
  417. NewTurn * n = static_cast<NewTurn*>(pack);
  418. day = n->day;
  419. BOOST_FOREACH(NewTurn::Hero h, n->heroes) //give mana/movement point
  420. {
  421. static_cast<CGHeroInstance*>(map->objects[h.id])->movement = h.move;
  422. static_cast<CGHeroInstance*>(map->objects[h.id])->mana = h.mana;
  423. }
  424. BOOST_FOREACH(SetResources h, n->res) //give resources
  425. applyNL(&h);
  426. BOOST_FOREACH(SetAvailableCreatures h, n->cres) //set available creatures in towns
  427. applyNL(&h);
  428. if(n->resetBuilded) //reset amount of structures set in this turn in towns
  429. BOOST_FOREACH(CGTownInstance* t, map->towns)
  430. t->builded = 0;
  431. break;
  432. }
  433. case 102: //set resource amount
  434. {
  435. SetResource *sr = static_cast<SetResource*>(pack);
  436. players[sr->player].resources[sr->resid] = sr->val;
  437. break;
  438. }
  439. case 104:
  440. {
  441. SetResources *sr = static_cast<SetResources*>(pack);
  442. for(int i=0;i<sr->res.size();i++)
  443. players[sr->player].resources[i] = sr->res[i];
  444. break;
  445. }
  446. case 105:
  447. {
  448. SetPrimSkill *sr = static_cast<SetPrimSkill*>(pack);
  449. CGHeroInstance *hero = getHero(sr->id);
  450. if(sr->which <4)
  451. {
  452. if(sr->abs)
  453. hero->primSkills[sr->which] = sr->val;
  454. else
  455. hero->primSkills[sr->which] += sr->val;
  456. }
  457. else if(sr->which == 4) //XP
  458. {
  459. if(sr->abs)
  460. hero->exp = sr->val;
  461. else
  462. hero->exp += sr->val;
  463. }
  464. break;
  465. }
  466. case 106:
  467. {
  468. SetSecSkill *sr = static_cast<SetSecSkill*>(pack);
  469. CGHeroInstance *hero = getHero(sr->id);
  470. if(hero->getSecSkillLevel(sr->which) == 0)
  471. {
  472. hero->secSkills.push_back(std::pair<int,int>(sr->which, sr->val));
  473. }
  474. else
  475. {
  476. for(unsigned i=0;i<hero->secSkills.size();i++)
  477. {
  478. if(hero->secSkills[i].first == sr->which)
  479. {
  480. if(sr->abs)
  481. hero->secSkills[i].second = sr->val;
  482. else
  483. hero->secSkills[i].second += sr->val;
  484. }
  485. }
  486. }
  487. break;
  488. }
  489. case 108:
  490. {
  491. HeroVisitCastle *vc = static_cast<HeroVisitCastle*>(pack);
  492. CGHeroInstance *h = getHero(vc->hid);
  493. CGTownInstance *t = getTown(vc->tid);
  494. if(vc->start())
  495. {
  496. if(vc->garrison())
  497. {
  498. t->garrisonHero = h;
  499. h->visitedTown = t;
  500. h->inTownGarrison = true;
  501. }
  502. else
  503. {
  504. t->visitingHero = h;
  505. h->visitedTown = t;
  506. h->inTownGarrison = false;
  507. }
  508. }
  509. else
  510. {
  511. if(vc->garrison())
  512. {
  513. t->garrisonHero = NULL;
  514. h->visitedTown = NULL;
  515. h->inTownGarrison = false;
  516. }
  517. else
  518. {
  519. t->visitingHero = NULL;
  520. h->visitedTown = NULL;
  521. h->inTownGarrison = false;
  522. }
  523. }
  524. break;
  525. }
  526. case 109:
  527. {
  528. ChangeSpells *rh = static_cast<ChangeSpells*>(pack);
  529. CGHeroInstance *hero = getHero(rh->hid);
  530. if(rh->learn)
  531. BOOST_FOREACH(ui32 sid, rh->spells)
  532. hero->spells.insert(sid);
  533. else
  534. BOOST_FOREACH(ui32 sid, rh->spells)
  535. hero->spells.erase(sid);
  536. break;
  537. }
  538. case 110:
  539. {
  540. SetMana *rh = static_cast<SetMana*>(pack);
  541. CGHeroInstance *hero = getHero(rh->hid);
  542. hero->mana = rh->val;
  543. break;
  544. }
  545. case 111:
  546. {
  547. SetMovePoints *rh = static_cast<SetMovePoints*>(pack);
  548. CGHeroInstance *hero = getHero(rh->hid);
  549. hero->movement = rh->val;
  550. break;
  551. }
  552. case 112:
  553. {
  554. FoWChange *rh = static_cast<FoWChange*>(pack);
  555. BOOST_FOREACH(int3 t, rh->tiles)
  556. players[rh->player].fogOfWarMap[t.x][t.y][t.z] = rh->mode;
  557. break;
  558. }
  559. case 113:
  560. {
  561. SetAvailableHeroes *rh = static_cast<SetAvailableHeroes*>(pack);
  562. players[rh->player].availableHeroes.clear();
  563. players[rh->player].availableHeroes.push_back(hpool.heroesPool[rh->hid1]);
  564. players[rh->player].availableHeroes.push_back(hpool.heroesPool[rh->hid2]);
  565. if(rh->flags & 1)
  566. {
  567. hpool.heroesPool[rh->hid1]->army.slots.clear();
  568. hpool.heroesPool[rh->hid1]->army.slots[0] = std::pair<ui32,si32>(VLC->creh->nameToID[hpool.heroesPool[rh->hid1]->type->refTypeStack[0]],1);
  569. }
  570. if(rh->flags & 2)
  571. {
  572. hpool.heroesPool[rh->hid2]->army.slots.clear();
  573. hpool.heroesPool[rh->hid2]->army.slots[0] = std::pair<ui32,si32>(VLC->creh->nameToID[hpool.heroesPool[rh->hid2]->type->refTypeStack[0]],1);
  574. }
  575. break;
  576. }
  577. case 115:
  578. {
  579. GiveBonus *rh = static_cast<GiveBonus*>(pack);
  580. CGHeroInstance *h = getHero(rh->hid);
  581. h->bonuses.push_back(rh->bonus);
  582. h->bonuses.back().description = toString(rh->bdescr);
  583. break;
  584. }
  585. case 500:
  586. {
  587. RemoveObject *rh = static_cast<RemoveObject*>(pack);
  588. CGObjectInstance *obj = map->objects[rh->id];
  589. if(obj->ID==34)
  590. {
  591. CGHeroInstance *h = static_cast<CGHeroInstance*>(obj);
  592. std::vector<CGHeroInstance*>::iterator nitr = std::find(map->heroes.begin(), map->heroes.end(),h);
  593. map->heroes.erase(nitr);
  594. int player = h->tempOwner;
  595. nitr = std::find(players[player].heroes.begin(), players[player].heroes.end(), h);
  596. players[player].heroes.erase(nitr);
  597. if(h->visitedTown)
  598. {
  599. if(h->inTownGarrison)
  600. h->visitedTown->garrisonHero = NULL;
  601. else
  602. h->visitedTown->visitingHero = NULL;
  603. h->visitedTown = NULL;
  604. }
  605. }
  606. map->objects[rh->id] = NULL;
  607. //unblock tiles
  608. if(obj->defInfo)
  609. {
  610. map->removeBlockVisTiles(obj);
  611. }
  612. break;
  613. }
  614. case 501://hero try-move
  615. {
  616. TryMoveHero * n = static_cast<TryMoveHero*>(pack);
  617. CGHeroInstance *h = static_cast<CGHeroInstance*>(map->objects[n->id]);
  618. h->movement = n->movePoints;
  619. if(n->start!=n->end && n->result)
  620. {
  621. map->removeBlockVisTiles(h);
  622. h->pos = n->end;
  623. map->addBlockVisTiles(h);
  624. }
  625. BOOST_FOREACH(int3 t, n->fowRevealed)
  626. players[h->getOwner()].fogOfWarMap[t.x][t.y][t.z] = 1;
  627. break;
  628. }
  629. case 502:
  630. {
  631. SetGarrisons * n = static_cast<SetGarrisons*>(pack);
  632. for(std::map<ui32,CCreatureSet>::iterator i = n->garrs.begin(); i!=n->garrs.end(); i++)
  633. {
  634. CArmedInstance *ai = static_cast<CArmedInstance*>(map->objects[i->first]);
  635. ai->army = i->second;
  636. if(ai->ID==98 && (static_cast<CGTownInstance*>(ai))->garrisonHero) //if there is a hero in garrison then we must update also his army
  637. const_cast<CGHeroInstance*>((static_cast<CGTownInstance*>(ai))->garrisonHero)->army = i->second;
  638. else if(ai->ID==34)
  639. {
  640. CGHeroInstance *h = static_cast<CGHeroInstance*>(ai);
  641. if(h->visitedTown && h->inTownGarrison)
  642. h->visitedTown->army = i->second;
  643. }
  644. }
  645. break;
  646. }
  647. case 503:
  648. {
  649. //SetStrInfo *ssi = static_cast<SetStrInfo*>(pack);
  650. //static_cast<CGTownInstance*>(map->objects[ssi->tid])->strInfo.creatures = ssi->cres;
  651. break;
  652. }
  653. case 504:
  654. {
  655. NewStructures *ns = static_cast<NewStructures*>(pack);
  656. CGTownInstance*t = static_cast<CGTownInstance*>(map->objects[ns->tid]);
  657. BOOST_FOREACH(si32 bid,ns->bid)
  658. t->builtBuildings.insert(bid);
  659. t->builded = ns->builded;
  660. break;
  661. }
  662. case 506:
  663. {
  664. SetAvailableCreatures *sac = static_cast<SetAvailableCreatures*>(pack);
  665. static_cast<CGTownInstance*>(map->objects[sac->tid])->strInfo.creatures = sac->creatures;
  666. break;
  667. }
  668. case 508:
  669. {
  670. SetHeroesInTown *sac = static_cast<SetHeroesInTown*>(pack);
  671. CGTownInstance *t = getTown(sac->tid);
  672. CGHeroInstance *v = getHero(sac->visiting), *g = getHero(sac->garrison);
  673. t->visitingHero = v;
  674. t->garrisonHero = g;
  675. if(v)
  676. {
  677. v->visitedTown = t;
  678. v->inTownGarrison = false;
  679. map->addBlockVisTiles(v);
  680. }
  681. if(g)
  682. {
  683. g->visitedTown = t;
  684. g->inTownGarrison = true;
  685. map->removeBlockVisTiles(g);
  686. }
  687. break;
  688. }
  689. case 509:
  690. {
  691. SetHeroArtifacts *sha = static_cast<SetHeroArtifacts*>(pack);
  692. CGHeroInstance *h = getHero(sha->hid);
  693. h->artifacts = sha->artifacts;
  694. h->artifWorn = sha->artifWorn;
  695. break;
  696. }
  697. case 514:
  698. {
  699. SetSelection *ss = static_cast<SetSelection*>(pack);
  700. players[ss->player].currentSelection = ss->id;
  701. break;
  702. }
  703. case 515:
  704. {
  705. HeroRecruited *sha = static_cast<HeroRecruited*>(pack);
  706. CGHeroInstance *h = hpool.heroesPool[sha->hid];
  707. CGTownInstance *t = getTown(sha->tid);
  708. h->setOwner(sha->player);
  709. h->pos = sha->tile;
  710. h->movement = h->maxMovePoints(true);
  711. hpool.heroesPool.erase(sha->hid);
  712. if(h->id < 0)
  713. {
  714. h->id = map->objects.size();
  715. map->objects.push_back(h);
  716. }
  717. else
  718. map->objects[h->id] = h;
  719. h->initHeroDefInfo();
  720. map->heroes.push_back(h);
  721. players[h->tempOwner].heroes.push_back(h);
  722. map->addBlockVisTiles(h);
  723. t->visitingHero = h;
  724. h->visitedTown = t;
  725. h->inTownGarrison = false;
  726. break;
  727. }
  728. case 1001://set object property
  729. {
  730. SetObjectProperty *p = static_cast<SetObjectProperty*>(pack);
  731. setObjProperty(p);
  732. break;
  733. }
  734. case 1002:
  735. {
  736. SetHoverName *shn = static_cast<SetHoverName*>(pack);
  737. map->objects[shn->id]->hoverName = toString(shn->name);
  738. break;
  739. }
  740. case 2000:
  741. {
  742. HeroLevelUp * bs = static_cast<HeroLevelUp*>(pack);
  743. getHero(bs->heroid)->level = bs->level;
  744. break;
  745. }
  746. case 3000:
  747. {
  748. BattleStart * bs = static_cast<BattleStart*>(pack);
  749. curB = bs->info;
  750. break;
  751. }
  752. case 3001:
  753. {
  754. BattleNextRound *ns = static_cast<BattleNextRound*>(pack);
  755. curB->round = ns->round;
  756. for(int i=0; i<curB->stacks.size();i++)
  757. {
  758. curB->stacks[i]->state -= DEFENDING;
  759. curB->stacks[i]->state -= WAITING;
  760. curB->stacks[i]->state -= MOVED;
  761. curB->stacks[i]->state -= HAD_MORALE;
  762. curB->stacks[i]->counterAttacks = 1;
  763. }
  764. break;
  765. }
  766. case 3002:
  767. {
  768. BattleSetActiveStack *ns = static_cast<BattleSetActiveStack*>(pack);
  769. curB->activeStack = ns->stack;
  770. CStack *st = curB->getStack(ns->stack);
  771. if(vstd::contains(st->state,MOVED))
  772. st->state.insert(HAD_MORALE);
  773. break;
  774. }
  775. case 3003:
  776. {
  777. BattleResult *br = static_cast<BattleResult*>(pack);
  778. for(unsigned i=0;i<curB->stacks.size();i++)
  779. delete curB->stacks[i];
  780. delete curB;
  781. curB = NULL;
  782. break;
  783. }
  784. case 3004:
  785. {
  786. BattleStackMoved *br = static_cast<BattleStackMoved*>(pack);
  787. curB->getStack(br->stack)->position = br->tile;
  788. break;
  789. }
  790. case 3005:
  791. {
  792. BattleStackAttacked *br = static_cast<BattleStackAttacked*>(pack);
  793. CStack * at = curB->getStack(br->stackAttacked);
  794. at->amount = br->newAmount;
  795. at->firstHPleft = br->newHP;
  796. if(br->killed())
  797. at->state -= ALIVE;
  798. break;
  799. }
  800. case 3006:
  801. {
  802. BattleAttack *br = static_cast<BattleAttack*>(pack);
  803. CStack *attacker = curB->getStack(br->stackAttacking);
  804. if(br->counter())
  805. attacker->counterAttacks--;
  806. if(br->shot())
  807. attacker->shots--;
  808. applyNL(&br->bsa);
  809. break;
  810. }
  811. case 3007:
  812. {
  813. StartAction *br = static_cast<StartAction*>(pack);
  814. CStack *st = curB->getStack(br->ba.stackNumber);
  815. switch(br->ba.actionType)
  816. {
  817. case 3:
  818. st->state.insert(DEFENDING);
  819. break;
  820. case 8:
  821. st->state.insert(WAITING);
  822. break;
  823. case 2: case 6: case 7: case 9: case 10: case 11:
  824. st->state.insert(MOVED);
  825. break;
  826. }
  827. break;
  828. }
  829. case 3009:
  830. {
  831. SpellCasted *sc = static_cast<SpellCasted*>(pack);
  832. CGHeroInstance *h = (sc->side) ? getHero(curB->hero2) : getHero(curB->hero1);
  833. if(h)
  834. h->mana -= VLC->spellh->spells[sc->id].costs[sc->skill];
  835. //TODO: counter
  836. break;
  837. }
  838. case 3010:
  839. {
  840. SetStackEffect *sc = static_cast<SetStackEffect*>(pack);
  841. CStack *stack = curB->getStack(sc->stack);
  842. stack->effects.push_back(sc->effect);
  843. break;
  844. }
  845. }
  846. }
  847. void CGameState::apply(IPack * pack)
  848. {
  849. while(!mx->try_lock())
  850. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  851. applyNL(pack);
  852. mx->unlock();
  853. }
  854. int CGameState::pickHero(int owner)
  855. {
  856. int h=-1;
  857. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  858. return h;
  859. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  860. int i=0;
  861. do //try to find free hero of our faction
  862. {
  863. i++;
  864. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  865. } while( map->getHero(h) && i<175);
  866. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  867. {
  868. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  869. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  870. if(!map->getHero(j))
  871. h=j;
  872. }
  873. return h;
  874. }
  875. CGHeroInstance *CGameState::getHero(int objid)
  876. {
  877. if(objid<0 || objid>=map->objects.size())
  878. return NULL;
  879. return static_cast<CGHeroInstance *>(map->objects[objid]);
  880. }
  881. CGTownInstance *CGameState::getTown(int objid)
  882. {
  883. if(objid<0 || objid>=map->objects.size())
  884. return NULL;
  885. return static_cast<CGTownInstance *>(map->objects[objid]);
  886. }
  887. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  888. {
  889. switch(obj->ID)
  890. {
  891. case 65: //random artifact
  892. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  893. case 66: //random treasure artifact
  894. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  895. case 67: //random minor artifact
  896. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  897. case 68: //random major artifact
  898. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  899. case 69: //random relic artifact
  900. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  901. case 70: //random hero
  902. {
  903. return std::pair<int,int>(34,pickHero(obj->tempOwner));
  904. }
  905. case 71: //random monster
  906. {
  907. int r;
  908. do
  909. {
  910. r = ran()%197;
  911. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  912. return std::pair<int,int>(54,r);
  913. }
  914. case 72: //random monster lvl1
  915. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  916. case 73: //random monster lvl2
  917. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  918. case 74: //random monster lvl3
  919. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  920. case 75: //random monster lvl4
  921. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  922. case 76: //random resource
  923. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  924. case 77: //random town
  925. {
  926. int align = ((CGTownInstance*)obj)->alignment,
  927. f;
  928. if(align>PLAYER_LIMIT-1)//same as owner / random
  929. {
  930. if(obj->tempOwner > PLAYER_LIMIT-1)
  931. f = -1; //random
  932. else
  933. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  934. }
  935. else
  936. {
  937. f = scenarioOps->getIthPlayersSettings(align).castle;
  938. }
  939. if(f<0) f = ran()%VLC->townh->towns.size();
  940. return std::pair<int,int>(98,f);
  941. }
  942. case 162: //random monster lvl5
  943. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  944. case 163: //random monster lvl6
  945. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  946. case 164: //random monster lvl7
  947. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  948. case 216: //random dwelling
  949. {
  950. int faction = ran()%F_NUMBER;
  951. CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info;
  952. if (info->asCastle)
  953. {
  954. for(int i=0;i<map->objects.size();i++)
  955. {
  956. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  957. {
  958. randomizeObject(map->objects[i]); //we have to randomize the castle first
  959. faction = map->objects[i]->subID;
  960. break;
  961. }
  962. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  963. {
  964. faction = map->objects[i]->subID;
  965. break;
  966. }
  967. }
  968. }
  969. else
  970. {
  971. while((!(info->castles[0]&(1<<faction))))
  972. {
  973. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  974. break;
  975. faction = ran()%F_NUMBER;
  976. }
  977. }
  978. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  979. int cid = VLC->townh->towns[faction].basicCreatures[level];
  980. for(int i=0;i<VLC->objh->cregens.size();i++)
  981. if(VLC->objh->cregens[i]==cid)
  982. return std::pair<int,int>(17,i);
  983. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  984. return std::pair<int,int>(17,0);
  985. }
  986. case 217:
  987. {
  988. int faction = ran()%F_NUMBER;
  989. CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info;
  990. if (info->asCastle)
  991. {
  992. for(int i=0;i<map->objects.size();i++)
  993. {
  994. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  995. {
  996. randomizeObject(map->objects[i]); //we have to randomize the castle first
  997. faction = map->objects[i]->subID;
  998. break;
  999. }
  1000. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  1001. {
  1002. faction = map->objects[i]->subID;
  1003. break;
  1004. }
  1005. }
  1006. }
  1007. else
  1008. {
  1009. while((!(info->castles[0]&(1<<faction))))
  1010. {
  1011. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  1012. break;
  1013. faction = ran()%F_NUMBER;
  1014. }
  1015. }
  1016. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  1017. for(int i=0;i<VLC->objh->cregens.size();i++)
  1018. if(VLC->objh->cregens[i]==cid)
  1019. return std::pair<int,int>(17,i);
  1020. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1021. return std::pair<int,int>(17,0);
  1022. }
  1023. case 218:
  1024. {
  1025. CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info;
  1026. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  1027. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  1028. for(int i=0;i<VLC->objh->cregens.size();i++)
  1029. if(VLC->objh->cregens[i]==cid)
  1030. return std::pair<int,int>(17,i);
  1031. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1032. return std::pair<int,int>(17,0);
  1033. }
  1034. }
  1035. return std::pair<int,int>(-1,-1);
  1036. }
  1037. void CGameState::randomizeObject(CGObjectInstance *cur)
  1038. {
  1039. std::pair<int,int> ran = pickObject(cur);
  1040. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  1041. {
  1042. if(cur->ID==98) //town - set def
  1043. {
  1044. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1045. if(t->hasCapitol())
  1046. t->defInfo = capitols[t->subID];
  1047. else if(t->hasFort())
  1048. t->defInfo = forts[t->subID];
  1049. else
  1050. t->defInfo = villages[t->subID];
  1051. }
  1052. return;
  1053. }
  1054. else if(ran.first==34)//special code for hero
  1055. {
  1056. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1057. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1058. cur->ID = ran.first;
  1059. h->portrait = cur->subID = ran.second;
  1060. h->type = VLC->heroh->heroes[ran.second];
  1061. map->heroes.push_back(h);
  1062. return; //TODO: maybe we should do something with definfo?
  1063. }
  1064. else if(ran.first==98)//special code for town
  1065. {
  1066. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1067. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1068. cur->ID = ran.first;
  1069. cur->subID = ran.second;
  1070. t->town = &VLC->townh->towns[ran.second];
  1071. if(t->hasCapitol())
  1072. t->defInfo = capitols[t->subID];
  1073. else if(t->hasFort())
  1074. t->defInfo = forts[t->subID];
  1075. else
  1076. t->defInfo = villages[t->subID];
  1077. map->towns.push_back(t);
  1078. return;
  1079. }
  1080. //we have to replace normal random object
  1081. cur->ID = ran.first;
  1082. cur->subID = ran.second;
  1083. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1084. if(!cur->defInfo)
  1085. {
  1086. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1087. return;
  1088. }
  1089. }
  1090. int CGameState::getDate(int mode) const
  1091. {
  1092. int temp;
  1093. switch (mode)
  1094. {
  1095. case 0:
  1096. return day;
  1097. break;
  1098. case 1:
  1099. temp = (day)%7;
  1100. if (temp)
  1101. return temp;
  1102. else return 7;
  1103. break;
  1104. case 2:
  1105. temp = ((day-1)/7)+1;
  1106. if (!(temp%4))
  1107. return 4;
  1108. else
  1109. return (temp%4);
  1110. break;
  1111. case 3:
  1112. return ((day-1)/28)+1;
  1113. break;
  1114. }
  1115. return 0;
  1116. }
  1117. CGameState::CGameState()
  1118. {
  1119. mx = new boost::shared_mutex();
  1120. map = NULL;
  1121. curB = NULL;
  1122. scenarioOps = NULL;
  1123. }
  1124. CGameState::~CGameState()
  1125. {
  1126. delete mx;
  1127. delete map;
  1128. delete curB;
  1129. delete scenarioOps;
  1130. }
  1131. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1132. {
  1133. day = 0;
  1134. seed = Seed;
  1135. ran.seed((boost::int32_t)seed);
  1136. scenarioOps = si;
  1137. this->map = map;
  1138. loadTownDInfos();
  1139. //picking random factions for players
  1140. for(int i=0;i<scenarioOps->playerInfos.size();i++)
  1141. {
  1142. if(scenarioOps->playerInfos[i].castle==-1)
  1143. {
  1144. int f;
  1145. do
  1146. {
  1147. f = ran()%F_NUMBER;
  1148. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1149. scenarioOps->playerInfos[i].castle = f;
  1150. }
  1151. }
  1152. //randomizing objects
  1153. for(int no=0; no<map->objects.size(); ++no)
  1154. {
  1155. randomizeObject(map->objects[no]);
  1156. if(map->objects[no]->ID==26)
  1157. {
  1158. map->objects[no]->defInfo->handler=NULL;
  1159. map->removeBlockVisTiles(map->objects[no]);
  1160. map->objects[no]->defInfo->blockMap[5] = 255;
  1161. map->addBlockVisTiles(map->objects[no]);
  1162. }
  1163. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1164. }
  1165. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1166. /*********give starting hero****************************************/
  1167. for(int i=0;i<PLAYER_LIMIT;i++)
  1168. {
  1169. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==RoE))
  1170. {
  1171. int3 hpos = map->players[i].posOfMainTown;
  1172. hpos.x+=1;// hpos.y+=1;
  1173. int j;
  1174. for(j=0; j<scenarioOps->playerInfos.size(); j++)
  1175. if(scenarioOps->playerInfos[j].color == i)
  1176. break;
  1177. if(j == scenarioOps->playerInfos.size())
  1178. continue;
  1179. int h=pickHero(i);
  1180. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(34,h,hpos,i));
  1181. nnn->id = map->objects.size();
  1182. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1183. for(int o=0;o<map->towns.size();o++) //find main town
  1184. {
  1185. if(map->towns[o]->pos == hpos)
  1186. {
  1187. map->towns[o]->visitingHero = nnn;
  1188. nnn->visitedTown = map->towns[o];
  1189. nnn->inTownGarrison = false;
  1190. break;
  1191. }
  1192. }
  1193. nnn->initHero();
  1194. map->heroes.push_back(nnn);
  1195. map->objects.push_back(nnn);
  1196. map->addBlockVisTiles(nnn);
  1197. }
  1198. }
  1199. /*********creating players entries in gs****************************************/
  1200. for (int i=0; i<scenarioOps->playerInfos.size();i++)
  1201. {
  1202. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1203. ins.second.color=ins.first;
  1204. ins.second.serial=i;
  1205. players.insert(ins);
  1206. }
  1207. /******************RESOURCES****************************************************/
  1208. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1209. std::vector<int> startres;
  1210. std::ifstream tis("config/startres.txt");
  1211. int k;
  1212. for (int j=0;j<scenarioOps->difficulty;j++)
  1213. {
  1214. tis >> k;
  1215. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1216. tis>>k;
  1217. }
  1218. tis >> k;
  1219. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1220. {
  1221. tis >> k;
  1222. startres.push_back(k);
  1223. }
  1224. tis.close();
  1225. tis.clear();
  1226. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1227. {
  1228. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1229. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1230. (*i).second.resources[x] = startres[x];
  1231. }
  1232. tis.open("config/resources.txt");
  1233. tis >> k;
  1234. int pom;
  1235. for(int i=0;i<k;i++)
  1236. {
  1237. tis >> pom;
  1238. resVals.push_back(pom);
  1239. }
  1240. /*************************HEROES************************************************/
  1241. std::set<int> hids;
  1242. for(int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1243. if(map->allowedHeroes[i])
  1244. hids.insert(i);
  1245. for (int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1246. {
  1247. if (map->heroes[i]->getOwner()<0)
  1248. {
  1249. tlog2 << "Warning - hero with uninitialized owner!\n";
  1250. continue;
  1251. }
  1252. CGHeroInstance * vhi = (map->heroes[i]);
  1253. vhi->initHero();
  1254. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1255. hids.erase(vhi->subID);
  1256. }
  1257. for(int i=0; i<map->predefinedHeroes.size(); i++)
  1258. {
  1259. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1260. continue;
  1261. map->predefinedHeroes[i]->initHero();
  1262. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1263. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1264. hids.erase(map->predefinedHeroes[i]->subID);
  1265. }
  1266. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1267. {
  1268. CGHeroInstance * vhi = new CGHeroInstance();
  1269. vhi->initHero(hid);
  1270. hpool.heroesPool[hid] = vhi;
  1271. hpool.pavailable[hid] = 0xff;
  1272. }
  1273. for(int i=0; i<map->disposedHeroes.size(); i++)
  1274. {
  1275. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1276. }
  1277. /*************************FOG**OF**WAR******************************************/
  1278. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1279. {
  1280. k->second.fogOfWarMap.resize(map->width);
  1281. for(int g=0; g<map->width; ++g)
  1282. k->second.fogOfWarMap[g].resize(map->height);
  1283. for(int g=-0; g<map->width; ++g)
  1284. for(int h=0; h<map->height; ++h)
  1285. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1286. for(int g=0; g<map->width; ++g)
  1287. for(int h=0; h<map->height; ++h)
  1288. for(int v=0; v<map->twoLevel+1; ++v)
  1289. k->second.fogOfWarMap[g][h][v] = 0;
  1290. for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1291. {
  1292. for(int yd=0; yd<map->height; ++yd)
  1293. {
  1294. for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1295. {
  1296. int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1297. int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1298. if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1299. k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1300. }
  1301. }
  1302. }
  1303. //starting bonus
  1304. if(si->playerInfos[k->second.serial].bonus==brandom)
  1305. si->playerInfos[k->second.serial].bonus = ran()%3;
  1306. switch(si->playerInfos[k->second.serial].bonus)
  1307. {
  1308. case bgold:
  1309. k->second.resources[6] += 500 + (ran()%6)*100;
  1310. break;
  1311. case bresource:
  1312. {
  1313. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1314. if(res == 127)
  1315. {
  1316. k->second.resources[0] += 5 + ran()%6;
  1317. k->second.resources[2] += 5 + ran()%6;
  1318. }
  1319. else
  1320. {
  1321. k->second.resources[res] += 3 + ran()%4;
  1322. }
  1323. break;
  1324. }
  1325. case bartifact:
  1326. {
  1327. if(!k->second.heroes.size())
  1328. {
  1329. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1330. break;
  1331. }
  1332. CArtifact *toGive;
  1333. do
  1334. {
  1335. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1336. } while (!map->allowedArtifact[toGive->id]);
  1337. CGHeroInstance *hero = k->second.heroes[0];
  1338. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1339. if(slot!=toGive->possibleSlots.end())
  1340. hero->artifWorn[*slot] = toGive->id;
  1341. else
  1342. hero->artifacts.push_back(toGive->id);
  1343. }
  1344. }
  1345. }
  1346. /****************************TOWNS************************************************/
  1347. for (int i=0;i<map->towns.size();i++)
  1348. {
  1349. CGTownInstance * vti =(map->towns[i]);
  1350. if(!vti->town)
  1351. vti->town = &VLC->townh->towns[vti->subID];
  1352. if (vti->name.length()==0) // if town hasn't name we draw it
  1353. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1354. //init buildings
  1355. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1356. {
  1357. vti->builtBuildings.erase(-50);
  1358. vti->builtBuildings.insert(10);
  1359. vti->builtBuildings.insert(5);
  1360. vti->builtBuildings.insert(30);
  1361. if(ran()%2)
  1362. vti->builtBuildings.insert(31);
  1363. }
  1364. //init spells
  1365. vti->spells.resize(SPELL_LEVELS);
  1366. CSpell *s;
  1367. for(int z=0; z<vti->obligatorySpells.size();z++)
  1368. {
  1369. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1370. vti->spells[s->level-1].push_back(s->id);
  1371. vti->possibleSpells -= s->id;
  1372. }
  1373. while(vti->possibleSpells.size())
  1374. {
  1375. ui32 total=0, sel=-1;
  1376. for(int ps=0;ps<vti->possibleSpells.size();ps++)
  1377. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1378. int r = (total)? ran()%total : -1;
  1379. for(int ps=0; ps<vti->possibleSpells.size();ps++)
  1380. {
  1381. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1382. if(r<0)
  1383. {
  1384. sel = ps;
  1385. break;
  1386. }
  1387. }
  1388. if(sel<0)
  1389. sel=0;
  1390. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1391. vti->spells[s->level-1].push_back(s->id);
  1392. vti->possibleSpells -= s->id;
  1393. }
  1394. //init garrisons
  1395. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1396. {
  1397. if(j->second.first > 196 && j->second.first < 211)
  1398. {
  1399. if(j->second.first%2)
  1400. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1401. else
  1402. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1403. }
  1404. }
  1405. players[vti->getOwner()].towns.push_back(vti);
  1406. }
  1407. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1408. {
  1409. if(k->first==-1 || k->first==255)
  1410. continue;
  1411. for(int xd=0; xd<map->width; ++xd) //revealing part of map around towns
  1412. {
  1413. for(int yd=0; yd<map->height; ++yd)
  1414. {
  1415. for(int ch=0; ch<k->second.towns.size(); ++ch)
  1416. {
  1417. int deltaX = (k->second.towns[ch]->pos.x-xd)*(k->second.towns[ch]->pos.x-xd);
  1418. int deltaY = (k->second.towns[ch]->pos.y-yd)*(k->second.towns[ch]->pos.y-yd);
  1419. if(deltaX+deltaY<k->second.towns[ch]->getSightDistance()*k->second.towns[ch]->getSightDistance())
  1420. k->second.fogOfWarMap[xd][yd][k->second.towns[ch]->pos.z] = 1;
  1421. }
  1422. }
  1423. }
  1424. //init visiting and garrisoned heroes
  1425. for(int l=0; l<k->second.heroes.size();l++)
  1426. {
  1427. for(int m=0; m<k->second.towns.size();m++)
  1428. {
  1429. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1430. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1431. {
  1432. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1433. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1434. k->second.heroes[l]->inTownGarrison = false;
  1435. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1436. k->second.heroes[l]->pos.x -= 1;
  1437. break;
  1438. }
  1439. }
  1440. }
  1441. }
  1442. for(int i=0; i<map->defy.size(); i++)
  1443. {
  1444. map->defy[i]->serial = i;
  1445. }
  1446. for(int i=0; i<map->objects.size(); i++)
  1447. map->objects[i]->initObj();
  1448. }
  1449. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1450. {
  1451. return true;
  1452. }
  1453. int CGameState::battleGetStack(int pos)
  1454. {
  1455. if(!curB)
  1456. return -1;
  1457. for(int g=0; g<curB->stacks.size(); ++g)
  1458. {
  1459. if((curB->stacks[g]->position == pos
  1460. || (curB->stacks[g]->creature->isDoubleWide()
  1461. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1462. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1463. ))
  1464. && curB->stacks[g]->alive()
  1465. )
  1466. return curB->stacks[g]->ID;
  1467. }
  1468. return -1;
  1469. }
  1470. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1471. {
  1472. UpgradeInfo ret;
  1473. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1474. if((obj->ID == 98) || ((obj->ID == 34) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1475. {
  1476. CGTownInstance * t;
  1477. if(obj->ID == 98)
  1478. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1479. else
  1480. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1481. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1482. {
  1483. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1484. {
  1485. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1486. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1487. {
  1488. ret.newID.push_back(nid);
  1489. ret.cost.push_back(std::set<std::pair<int,int> >());
  1490. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1491. {
  1492. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1493. if(dif)
  1494. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1495. }
  1496. }
  1497. }
  1498. }//end for
  1499. }
  1500. //TODO: check if hero ability makes some upgrades possible
  1501. if(ret.newID.size())
  1502. ret.oldID = base->idNumber;
  1503. return ret;
  1504. }
  1505. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1506. {
  1507. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1508. if(mode) return -1; //todo - support other modes
  1509. int mcount = 0;
  1510. for(int i=0;i<players[player].towns.size();i++)
  1511. if(vstd::contains(players[player].towns[i]->builtBuildings,14))
  1512. mcount++;
  1513. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1514. return ret;
  1515. }
  1516. std::set<int3> CGameState::tilesToReveal(int3 pos, int radious, int player) const
  1517. {
  1518. std::set<int3> ret;
  1519. int xbeg = pos.x - radious - 2;
  1520. if(xbeg < 0)
  1521. xbeg = 0;
  1522. int xend = pos.x + radious + 2;
  1523. if(xend >= map->width)
  1524. xend = map->width;
  1525. int ybeg = pos.y - radious - 2;
  1526. if(ybeg < 0)
  1527. ybeg = 0;
  1528. int yend = pos.y + radious + 2;
  1529. if(yend >= map->height)
  1530. yend = map->height;
  1531. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  1532. {
  1533. for(int yd=ybeg; yd<yend; ++yd)
  1534. {
  1535. int deltaX = (pos.x-xd)*(pos.x-xd);
  1536. int deltaY = (pos.y-yd)*(pos.y-yd);
  1537. if(deltaX+deltaY<radious*radious)
  1538. {
  1539. if(player<0 || players.find(player)->second.fogOfWarMap[xd][yd][pos.z]==0)
  1540. {
  1541. ret.insert(int3(xd,yd,pos.z));
  1542. }
  1543. }
  1544. }
  1545. }
  1546. return ret;
  1547. }
  1548. void CGameState::loadTownDInfos()
  1549. {
  1550. for(int i=0;i<F_NUMBER;i++)
  1551. {
  1552. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1553. forts[i] = VLC->dobjinfo->castles[i];
  1554. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1555. }
  1556. }
  1557. void CGameState::setObjProperty( SetObjectProperty * p )
  1558. {
  1559. CGObjectInstance *obj = map->objects[p->id];
  1560. switch(p->what)
  1561. {
  1562. case 1:
  1563. obj->tempOwner = p->val;
  1564. break;
  1565. case 2:
  1566. obj->blockVisit = p->val;
  1567. break;
  1568. case 3:
  1569. static_cast<CArmedInstance*>(obj)->army.slots[0].second = p->val;
  1570. break;
  1571. case 4:
  1572. static_cast<CGVisitableOPH*>(obj)->visitors.insert(p->val);
  1573. break;
  1574. case 5:
  1575. static_cast<CGVisitableOPW*>(obj)->visited = p->val;
  1576. break;
  1577. }
  1578. }
  1579. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting)
  1580. {
  1581. int attackerAttackBonus = attacker->creature->attack + (attackerHero ? attackerHero->getPrimSkillLevel(0) : 0);
  1582. if(attacker->getEffect(56)) //frenzy for attacker
  1583. {
  1584. attackerAttackBonus += (VLC->spellh->spells[attacker->getEffect(56)->id].powers[attacker->getEffect(56)->level]/100.0) *(attacker->creature->defence + (attackerHero ? attackerHero->getPrimSkillLevel(1) : 0));
  1585. }
  1586. int defenderDefenseBonus = defender->creature->defence + (defendingHero ? defendingHero->getPrimSkillLevel(1) : 0);
  1587. if(defender->getEffect(56)) //frenzy for defender
  1588. {
  1589. defenderDefenseBonus = 0;
  1590. }
  1591. int attackDefenseBonus = attackerAttackBonus - defenderDefenseBonus;
  1592. if(defender->getEffect(48)) //defender's prayer handling
  1593. {
  1594. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(48)->id].powers[defender->getEffect(48)->level];
  1595. }
  1596. if(attacker->getEffect(48)) //attacker's prayer handling
  1597. {
  1598. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(48)->id].powers[attacker->getEffect(48)->level];
  1599. }
  1600. if(defender->getEffect(46)) //stone skin handling
  1601. {
  1602. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(46)->id].powers[defender->getEffect(46)->level];
  1603. }
  1604. if(attacker->getEffect(45)) //weakness handling
  1605. {
  1606. attackDefenseBonus -= VLC->spellh->spells[attacker->getEffect(45)->id].powers[attacker->getEffect(45)->level];
  1607. }
  1608. if(!shooting && attacker->getEffect(43)) //bloodlust handling
  1609. {
  1610. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(43)->id].powers[attacker->getEffect(43)->level];
  1611. }
  1612. int damageBase = 0;
  1613. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  1614. {
  1615. damageBase = attacker->creature->damageMin;
  1616. damageBase -= VLC->spellh->spells[attacker->getEffect(42)->id].powers[attacker->getEffect(42)->level];
  1617. }
  1618. else if(attacker->getEffect(41)) //bless handling
  1619. {
  1620. damageBase = attacker->creature->damageMax;
  1621. damageBase += VLC->spellh->spells[attacker->getEffect(41)->id].powers[attacker->getEffect(41)->level];
  1622. }
  1623. else if(attacker->creature->damageMax == attacker->creature->damageMin) //constant damage
  1624. {
  1625. damageBase = attacker->creature->damageMin;
  1626. }
  1627. else
  1628. {
  1629. damageBase = rand()%(attacker->creature->damageMax - attacker->creature->damageMin) + attacker->creature->damageMin + 1;
  1630. }
  1631. float dmgBonusMultiplier = 1.0f;
  1632. if(attackDefenseBonus < 0) //decreasing dmg
  1633. {
  1634. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1635. {
  1636. dmgBonusMultiplier += -0.3f;
  1637. }
  1638. else
  1639. {
  1640. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1641. }
  1642. }
  1643. else //increasing dmg
  1644. {
  1645. if(0.05f * attackDefenseBonus > 4.0f)
  1646. {
  1647. dmgBonusMultiplier += 4.0f;
  1648. }
  1649. else
  1650. {
  1651. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1652. }
  1653. }
  1654. //handling secondary abilities
  1655. if(attackerHero)
  1656. {
  1657. if(shooting)
  1658. {
  1659. switch(attackerHero->getSecSkillLevel(1)) //archery
  1660. {
  1661. case 1: //basic
  1662. dmgBonusMultiplier *= 1.1f;
  1663. break;
  1664. case 2: //advanced
  1665. dmgBonusMultiplier *= 1.25f;
  1666. break;
  1667. case 3: //expert
  1668. dmgBonusMultiplier *= 1.5f;
  1669. break;
  1670. }
  1671. }
  1672. else
  1673. {
  1674. switch(attackerHero->getSecSkillLevel(22)) //offence
  1675. {
  1676. case 1: //basic
  1677. dmgBonusMultiplier *= 1.1f;
  1678. break;
  1679. case 2: //advanced
  1680. dmgBonusMultiplier *= 1.2f;
  1681. break;
  1682. case 3: //expert
  1683. dmgBonusMultiplier *= 1.3f;
  1684. break;
  1685. }
  1686. }
  1687. }
  1688. if(defendingHero)
  1689. {
  1690. switch(defendingHero->getSecSkillLevel(23)) //armourer
  1691. {
  1692. case 1: //basic
  1693. dmgBonusMultiplier *= 0.95f;
  1694. break;
  1695. case 2: //advanced
  1696. dmgBonusMultiplier *= 0.9f;
  1697. break;
  1698. case 3: //expert
  1699. dmgBonusMultiplier *= 0.85f;
  1700. break;
  1701. }
  1702. }
  1703. //handling spell effects
  1704. if(!shooting && defender->getEffect(27)) //shield
  1705. {
  1706. if(defender->getEffect(27)->level<=1) //none or basic
  1707. dmgBonusMultiplier *= 0.85f;
  1708. else //adv or expert
  1709. dmgBonusMultiplier *= 0.7f;
  1710. }
  1711. if(shooting && defender->getEffect(28)) //air shield
  1712. {
  1713. if(defender->getEffect(28)->level<=1) //none or basic
  1714. dmgBonusMultiplier *= 0.75f;
  1715. else //adv or expert
  1716. dmgBonusMultiplier *= 0.5f;
  1717. }
  1718. if(attacker->getEffect(42)) //curse, second part of handling
  1719. {
  1720. if(attacker->getEffect(42)->level>=2) //adv or expert
  1721. dmgBonusMultiplier *= 0.8f;
  1722. }
  1723. return (float)damageBase * (float)attacker->amount * dmgBonusMultiplier;
  1724. }
  1725. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1726. {
  1727. for(int i=0; i<stacks.size();i++)//setting casualties
  1728. {
  1729. if(!stacks[i]->alive())
  1730. {
  1731. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1732. }
  1733. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1734. {
  1735. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1736. }
  1737. }
  1738. }
  1739. CStack * BattleInfo::getNextStack()
  1740. {
  1741. CStack *current = getStack(activeStack);
  1742. for (int i = 0; i < stacks.size(); i++) //find fastest not moved/waited stack (stacks vector is sorted by speed)
  1743. {
  1744. if(vstd::contains(stacks[i]->state,DEFENDING)
  1745. ||vstd::contains(stacks[i]->state,WAITING)
  1746. ||vstd::contains(stacks[i]->state,MOVED)
  1747. ||!stacks[i]->alive()
  1748. )
  1749. continue;
  1750. return stacks[i];
  1751. }
  1752. for (int i = stacks.size() - 1; i >= 0 ; i--) //find slowest waiting stack
  1753. {
  1754. if(vstd::contains(stacks[i]->state,DEFENDING)
  1755. ||vstd::contains(stacks[i]->state,MOVED)
  1756. ||!stacks[i]->alive()
  1757. )
  1758. continue;
  1759. return stacks[i];
  1760. }
  1761. return NULL; //all stacks moved or defending!
  1762. }
  1763. std::vector<CStack> BattleInfo::getStackQueue()
  1764. {
  1765. std::vector<CStack> ret;
  1766. std::vector<int> taken; //if non-zero value, corresponding stack has been placed in ret
  1767. taken.resize(stacks.size());
  1768. for(int g=0; g<taken.size(); ++g)
  1769. {
  1770. taken[g] = 0;
  1771. }
  1772. for(int moved=0; moved<2; ++moved) //in first cycle we add stacks that can act in current turn, in second one the rest of them
  1773. {
  1774. for(int gc=0; gc<stacks.size(); ++gc)
  1775. {
  1776. int id = -1, speed = -1;
  1777. for(int i=0; i<stacks.size(); ++i) //find not waited stacks only
  1778. {
  1779. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1780. && stacks[i]->alive()
  1781. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1782. && !vstd::contains(stacks[i]->state,WAITING)
  1783. && taken[i]==0)
  1784. {
  1785. if(speed == -1 || stacks[i]->speed() > speed)
  1786. {
  1787. id = i;
  1788. speed = stacks[i]->speed();
  1789. }
  1790. }
  1791. }
  1792. if(id != -1)
  1793. {
  1794. ret.push_back(*stacks[id]);
  1795. taken[id] = 1;
  1796. }
  1797. else //choose something from not moved stacks
  1798. {
  1799. int id = -1, speed = 10000; //infinite speed
  1800. for(int i=0; i<stacks.size(); ++i) //find waited stacks only
  1801. {
  1802. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1803. && stacks[i]->alive()
  1804. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1805. && vstd::contains(stacks[i]->state,WAITING)
  1806. && taken[i]==0)
  1807. {
  1808. if(stacks[i]->speed() < speed) //slowest one
  1809. {
  1810. id = i;
  1811. speed = stacks[i]->speed();
  1812. }
  1813. }
  1814. }
  1815. if(id != -1)
  1816. {
  1817. ret.push_back(*stacks[id]);
  1818. taken[id] = 1;
  1819. }
  1820. else
  1821. {
  1822. break; //no stacks have been found, so none of them will be found in next iterations
  1823. }
  1824. }
  1825. }
  1826. }
  1827. return ret;
  1828. }