CGameState.cpp 54 KB

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